label
int64
0
1
text
stringlengths
0
2.8M
0
// Copyright (c) RxSwiftCommunity // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if canImport(UIKit) import UIKit import RxSwift import RxCocoa public typealias TapConfiguration = Configuration<UITapGestureRecognizer> public typealias TapControlEvent = ControlEvent<UITapGestureRecognizer> public typealias TapObservable = Observable<UITapGestureRecognizer> extension Factory where Gesture == RxGestureRecognizer { /** Returns an `AnyFactory` for `UITapGestureRecognizer` - parameter configuration: A closure that allows to fully configure the gesture recognizer */ public static func tap(configuration: TapConfiguration? = nil) -> AnyFactory { make(configuration: configuration).abstracted() } } extension Reactive where Base: RxGestureView { /** Returns an observable `UITapGestureRecognizer` events sequence - parameter configuration: A closure that allows to fully configure the gesture recognizer */ public func tapGesture(configuration: TapConfiguration? = nil) -> TapControlEvent { gesture(make(configuration: configuration)) } } #endif
0
// // first.swift // KeyPathKit // // Created by Vincent on 24/03/2018. // Copyright © 2018 Vincent. All rights reserved. // import Foundation extension Sequence { public func first(where attribute: KeyPath<Element, Bool>) -> Element? { return first(where: { $0[keyPath: attribute] }) } }
0
// // TileLayoutManager.swift // ManagerSpecial // // Created by Ye Ma on 7/17/20. // Copyright © 2020 Ye Ma. All rights reserved. // import Foundation import UIKit protocol FlexibleSize { var widthInUnit: Int { get } var heightInUnit: Int { get } } typealias WeightAndTotal = (weight: Int, total: Int) extension ManagerSpecial: FlexibleSize {} protocol TileLayoutManager: ManagerSpecialViewControllerViewModel { var canvasUnit: Int { get } func update(_ list: [FlexibleSize], canvasUnit: Int) func sizeForIndex(_ index: Int, screenWidth: Int, padding: Int, spacing: Int) -> CGSize } final class TileLayoutManagerImpl: TileLayoutManager { private var list: [FlexibleSize] = [] private var rowByIndex: [Int] = [] private func recalcuate() -> [Int] { var leftInCurrentRow = canvasUnit var row = 0 var index = 0 var result = [Int]() while index < list.count { leftInCurrentRow -= list[index].widthInUnit if leftInCurrentRow >= 0 { result.append(row) index += 1 } else { row += 1 leftInCurrentRow = canvasUnit } } return result } private func countForIndex(_ index: Int) -> Int { guard index < rowByIndex.count else { return 0 } let row = rowByIndex[index] return rowByIndex.filter{ $0 == row }.count } private func weightForIndex(_ index: Int) -> WeightAndTotal { let weight = list[index].widthInUnit let row = rowByIndex[index] var total = 0 for i in 0..<rowByIndex.count { if rowByIndex[i] == row { total += list[i].widthInUnit } } return (weight: weight, total: total) } //MARK: - TitleLayoutComputer var canvasUnit: Int = 0 func update(_ list: [FlexibleSize], canvasUnit: Int) { self.canvasUnit = canvasUnit self.list = list rowByIndex = recalcuate() } func sizeForIndex(_ index: Int, screenWidth: Int, padding: Int, spacing: Int) -> CGSize { let pixelPerUnit = screenWidth / canvasUnit let itemCount = countForIndex(index) let weightAndTotal = weightForIndex(index) let width = (screenWidth - (padding * 2 + (itemCount - 1) * spacing)) * weightAndTotal.weight / weightAndTotal.total let height = pixelPerUnit * list[index].heightInUnit return CGSize(width: CGFloat(width), height: CGFloat(height)) } }
0
// Generated from ./grammars-v4/asn/ASN.g4 by ANTLR 4.5.1 import Antlr4 /** * This interface defines a complete generic visitor for a parse tree produced * by {@link ASNParser}. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */ open class ASNVisitor<T>: ParseTreeVisitor<T> { /** * Visit a parse tree produced by {@link ASNParser#moduleDefinition}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitModuleDefinition(_ ctx: ASNParser.ModuleDefinitionContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#tagDefault}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitTagDefault(_ ctx: ASNParser.TagDefaultContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#extensionDefault}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExtensionDefault(_ ctx: ASNParser.ExtensionDefaultContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#moduleBody}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitModuleBody(_ ctx: ASNParser.ModuleBodyContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#exports}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExports(_ ctx: ASNParser.ExportsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#symbolsExported}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSymbolsExported(_ ctx: ASNParser.SymbolsExportedContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#imports}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitImports(_ ctx: ASNParser.ImportsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#symbolsImported}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSymbolsImported(_ ctx: ASNParser.SymbolsImportedContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#symbolsFromModuleList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSymbolsFromModuleList(_ ctx: ASNParser.SymbolsFromModuleListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#symbolsFromModule}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSymbolsFromModule(_ ctx: ASNParser.SymbolsFromModuleContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#globalModuleReference}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitGlobalModuleReference(_ ctx: ASNParser.GlobalModuleReferenceContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#assignedIdentifier}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitAssignedIdentifier(_ ctx: ASNParser.AssignedIdentifierContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#symbolList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSymbolList(_ ctx: ASNParser.SymbolListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#symbol}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSymbol(_ ctx: ASNParser.SymbolContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#assignmentList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitAssignmentList(_ ctx: ASNParser.AssignmentListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#assignment}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitAssignment(_ ctx: ASNParser.AssignmentContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#sequenceType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSequenceType(_ ctx: ASNParser.SequenceTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#extensionAndException}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExtensionAndException(_ ctx: ASNParser.ExtensionAndExceptionContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#optionalExtensionMarker}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitOptionalExtensionMarker(_ ctx: ASNParser.OptionalExtensionMarkerContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#componentTypeLists}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitComponentTypeLists(_ ctx: ASNParser.ComponentTypeListsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#rootComponentTypeList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitRootComponentTypeList(_ ctx: ASNParser.RootComponentTypeListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#componentTypeList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitComponentTypeList(_ ctx: ASNParser.ComponentTypeListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#componentType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitComponentType(_ ctx: ASNParser.ComponentTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#extensionAdditions}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExtensionAdditions(_ ctx: ASNParser.ExtensionAdditionsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#extensionAdditionList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExtensionAdditionList(_ ctx: ASNParser.ExtensionAdditionListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#extensionAddition}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExtensionAddition(_ ctx: ASNParser.ExtensionAdditionContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#extensionAdditionGroup}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExtensionAdditionGroup(_ ctx: ASNParser.ExtensionAdditionGroupContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#versionNumber}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitVersionNumber(_ ctx: ASNParser.VersionNumberContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#sequenceOfType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSequenceOfType(_ ctx: ASNParser.SequenceOfTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#sizeConstraint}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSizeConstraint(_ ctx: ASNParser.SizeConstraintContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#parameterizedAssignment}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitParameterizedAssignment(_ ctx: ASNParser.ParameterizedAssignmentContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#parameterList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitParameterList(_ ctx: ASNParser.ParameterListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#parameter}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitParameter(_ ctx: ASNParser.ParameterContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#paramGovernor}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitParamGovernor(_ ctx: ASNParser.ParamGovernorContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#governor}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitGovernor(_ ctx: ASNParser.GovernorContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectClassAssignment}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectClassAssignment(_ ctx: ASNParser.ObjectClassAssignmentContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectClass}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectClass(_ ctx: ASNParser.ObjectClassContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#definedObjectClass}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitDefinedObjectClass(_ ctx: ASNParser.DefinedObjectClassContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#usefulObjectClassReference}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitUsefulObjectClassReference(_ ctx: ASNParser.UsefulObjectClassReferenceContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#externalObjectClassReference}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExternalObjectClassReference(_ ctx: ASNParser.ExternalObjectClassReferenceContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectClassDefn}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectClassDefn(_ ctx: ASNParser.ObjectClassDefnContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#withSyntaxSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitWithSyntaxSpec(_ ctx: ASNParser.WithSyntaxSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#syntaxList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSyntaxList(_ ctx: ASNParser.SyntaxListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#tokenOrGroupSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitTokenOrGroupSpec(_ ctx: ASNParser.TokenOrGroupSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#optionalGroup}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitOptionalGroup(_ ctx: ASNParser.OptionalGroupContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#requiredToken}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitRequiredToken(_ ctx: ASNParser.RequiredTokenContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#literal}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitLiteral(_ ctx: ASNParser.LiteralContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#primitiveFieldName}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitPrimitiveFieldName(_ ctx: ASNParser.PrimitiveFieldNameContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#fieldSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitFieldSpec(_ ctx: ASNParser.FieldSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#typeFieldSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitTypeFieldSpec(_ ctx: ASNParser.TypeFieldSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#typeOptionalitySpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitTypeOptionalitySpec(_ ctx: ASNParser.TypeOptionalitySpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#fixedTypeValueFieldSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitFixedTypeValueFieldSpec(_ ctx: ASNParser.FixedTypeValueFieldSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#valueOptionalitySpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitValueOptionalitySpec(_ ctx: ASNParser.ValueOptionalitySpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#variableTypeValueFieldSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitVariableTypeValueFieldSpec(_ ctx: ASNParser.VariableTypeValueFieldSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#fixedTypeValueSetFieldSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitFixedTypeValueSetFieldSpec(_ ctx: ASNParser.FixedTypeValueSetFieldSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#valueSetOptionalitySpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitValueSetOptionalitySpec(_ ctx: ASNParser.ValueSetOptionalitySpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#object}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObject(_ ctx: ASNParser.ObjectContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#parameterizedObject}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitParameterizedObject(_ ctx: ASNParser.ParameterizedObjectContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#definedObject}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitDefinedObject(_ ctx: ASNParser.DefinedObjectContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectSet}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectSet(_ ctx: ASNParser.ObjectSetContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectSetSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectSetSpec(_ ctx: ASNParser.ObjectSetSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#fieldName}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitFieldName(_ ctx: ASNParser.FieldNameContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#valueSet}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitValueSet(_ ctx: ASNParser.ValueSetContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#elementSetSpecs}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitElementSetSpecs(_ ctx: ASNParser.ElementSetSpecsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#rootElementSetSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitRootElementSetSpec(_ ctx: ASNParser.RootElementSetSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#additionalElementSetSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitAdditionalElementSetSpec(_ ctx: ASNParser.AdditionalElementSetSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#elementSetSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitElementSetSpec(_ ctx: ASNParser.ElementSetSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#unions}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitUnions(_ ctx: ASNParser.UnionsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#exclusions}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExclusions(_ ctx: ASNParser.ExclusionsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#intersections}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitIntersections(_ ctx: ASNParser.IntersectionsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#unionMark}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitUnionMark(_ ctx: ASNParser.UnionMarkContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#intersectionMark}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitIntersectionMark(_ ctx: ASNParser.IntersectionMarkContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#elements}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitElements(_ ctx: ASNParser.ElementsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectSetElements}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectSetElements(_ ctx: ASNParser.ObjectSetElementsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#intersectionElements}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitIntersectionElements(_ ctx: ASNParser.IntersectionElementsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#subtypeElements}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSubtypeElements(_ ctx: ASNParser.SubtypeElementsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#variableTypeValueSetFieldSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitVariableTypeValueSetFieldSpec(_ ctx: ASNParser.VariableTypeValueSetFieldSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectFieldSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectFieldSpec(_ ctx: ASNParser.ObjectFieldSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectOptionalitySpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectOptionalitySpec(_ ctx: ASNParser.ObjectOptionalitySpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectSetFieldSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectSetFieldSpec(_ ctx: ASNParser.ObjectSetFieldSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectSetOptionalitySpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectSetOptionalitySpec(_ ctx: ASNParser.ObjectSetOptionalitySpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#typeAssignment}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitTypeAssignment(_ ctx: ASNParser.TypeAssignmentContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#valueAssignment}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitValueAssignment(_ ctx: ASNParser.ValueAssignmentContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#type}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitType(_ ctx: ASNParser.TypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#builtinType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitBuiltinType(_ ctx: ASNParser.BuiltinTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectClassFieldType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectClassFieldType(_ ctx: ASNParser.ObjectClassFieldTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#setType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSetType(_ ctx: ASNParser.SetTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#setOfType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSetOfType(_ ctx: ASNParser.SetOfTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#referencedType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitReferencedType(_ ctx: ASNParser.ReferencedTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#definedType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitDefinedType(_ ctx: ASNParser.DefinedTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#constraint}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitConstraint(_ ctx: ASNParser.ConstraintContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#constraintSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitConstraintSpec(_ ctx: ASNParser.ConstraintSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#userDefinedConstraint}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitUserDefinedConstraint(_ ctx: ASNParser.UserDefinedConstraintContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#generalConstraint}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitGeneralConstraint(_ ctx: ASNParser.GeneralConstraintContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#userDefinedConstraintParameter}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitUserDefinedConstraintParameter(_ ctx: ASNParser.UserDefinedConstraintParameterContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#tableConstraint}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitTableConstraint(_ ctx: ASNParser.TableConstraintContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#simpleTableConstraint}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSimpleTableConstraint(_ ctx: ASNParser.SimpleTableConstraintContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#contentsConstraint}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitContentsConstraint(_ ctx: ASNParser.ContentsConstraintContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#subtypeConstraint}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSubtypeConstraint(_ ctx: ASNParser.SubtypeConstraintContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#value}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitValue(_ ctx: ASNParser.ValueContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#builtinValue}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitBuiltinValue(_ ctx: ASNParser.BuiltinValueContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectIdentifierValue}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectIdentifierValue(_ ctx: ASNParser.ObjectIdentifierValueContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objIdComponentsList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjIdComponentsList(_ ctx: ASNParser.ObjIdComponentsListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objIdComponents}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjIdComponents(_ ctx: ASNParser.ObjIdComponentsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#integerValue}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitIntegerValue(_ ctx: ASNParser.IntegerValueContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#choiceValue}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitChoiceValue(_ ctx: ASNParser.ChoiceValueContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#enumeratedValue}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitEnumeratedValue(_ ctx: ASNParser.EnumeratedValueContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#signedNumber}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSignedNumber(_ ctx: ASNParser.SignedNumberContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#choiceType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitChoiceType(_ ctx: ASNParser.ChoiceTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#alternativeTypeLists}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitAlternativeTypeLists(_ ctx: ASNParser.AlternativeTypeListsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#extensionAdditionAlternatives}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExtensionAdditionAlternatives(_ ctx: ASNParser.ExtensionAdditionAlternativesContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#extensionAdditionAlternativesList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExtensionAdditionAlternativesList(_ ctx: ASNParser.ExtensionAdditionAlternativesListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#extensionAdditionAlternative}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExtensionAdditionAlternative(_ ctx: ASNParser.ExtensionAdditionAlternativeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#extensionAdditionAlternativesGroup}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExtensionAdditionAlternativesGroup(_ ctx: ASNParser.ExtensionAdditionAlternativesGroupContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#rootAlternativeTypeList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitRootAlternativeTypeList(_ ctx: ASNParser.RootAlternativeTypeListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#alternativeTypeList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitAlternativeTypeList(_ ctx: ASNParser.AlternativeTypeListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#namedType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitNamedType(_ ctx: ASNParser.NamedTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#enumeratedType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitEnumeratedType(_ ctx: ASNParser.EnumeratedTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#enumerations}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitEnumerations(_ ctx: ASNParser.EnumerationsContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#rootEnumeration}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitRootEnumeration(_ ctx: ASNParser.RootEnumerationContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#enumeration}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitEnumeration(_ ctx: ASNParser.EnumerationContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#enumerationItem}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitEnumerationItem(_ ctx: ASNParser.EnumerationItemContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#namedNumber}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitNamedNumber(_ ctx: ASNParser.NamedNumberContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#definedValue}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitDefinedValue(_ ctx: ASNParser.DefinedValueContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#parameterizedValue}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitParameterizedValue(_ ctx: ASNParser.ParameterizedValueContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#simpleDefinedValue}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitSimpleDefinedValue(_ ctx: ASNParser.SimpleDefinedValueContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#actualParameterList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitActualParameterList(_ ctx: ASNParser.ActualParameterListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#actualParameter}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitActualParameter(_ ctx: ASNParser.ActualParameterContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#exceptionSpec}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExceptionSpec(_ ctx: ASNParser.ExceptionSpecContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#exceptionIdentification}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitExceptionIdentification(_ ctx: ASNParser.ExceptionIdentificationContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#additionalEnumeration}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitAdditionalEnumeration(_ ctx: ASNParser.AdditionalEnumerationContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#integerType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitIntegerType(_ ctx: ASNParser.IntegerTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#namedNumberList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitNamedNumberList(_ ctx: ASNParser.NamedNumberListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#objectidentifiertype}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitObjectidentifiertype(_ ctx: ASNParser.ObjectidentifiertypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#componentRelationConstraint}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitComponentRelationConstraint(_ ctx: ASNParser.ComponentRelationConstraintContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#atNotation}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitAtNotation(_ ctx: ASNParser.AtNotationContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#level}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitLevel(_ ctx: ASNParser.LevelContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#componentIdList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitComponentIdList(_ ctx: ASNParser.ComponentIdListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#octetStringType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitOctetStringType(_ ctx: ASNParser.OctetStringTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#bitStringType}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitBitStringType(_ ctx: ASNParser.BitStringTypeContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#namedBitList}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitNamedBitList(_ ctx: ASNParser.NamedBitListContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#namedBit}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitNamedBit(_ ctx: ASNParser.NamedBitContext) -> T{ fatalError(#function + " must be overridden") } /** * Visit a parse tree produced by {@link ASNParser#booleanValue}. - Parameters: - ctx: the parse tree - returns: the visitor result */ open func visitBooleanValue(_ ctx: ASNParser.BooleanValueContext) -> T{ fatalError(#function + " must be overridden") } }
0
// // ModuleBuilder.swift // StorytelLite // // Created by Alex Kravchenko on 12.12.2020. // import UIKit protocol ModuleBuilder { associatedtype Controller: UIViewController associatedtype Interactor: Any func build() -> Controller }
0
import UIKit class WebViewCell: UITableViewCell { /* WebView */ @IBOutlet weak var viewWeb: UIWebView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
0
import UIKit class WeatherScreenTableView: UITableView { convenience init(_ frame: CGRect, _ style: UITableView.Style) { self.init(frame: frame, style: style) } override init(frame: CGRect, style: UITableView.Style) { super.init(frame: frame, style: style) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
0
// // OP_EQUAL.swift // // Copyright © 2018 BitcoinCashKit developers // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation // Returns 1 if the inputs are exactly equal, 0 otherwise. public struct OpEqual: OpCodeProtocol { public var value: UInt8 { return 0x87 } public var name: String { return "OP_EQUAL" } // input : x1 x2 // output : true / false public func execute(_ context: ScriptExecutionContext) throws { try prepareExecute(context) try context.assertStackHeightGreaterThan(2) let x1 = context.stack.popLast()! let x2 = context.stack.popLast()! let equal: Bool = x1 == x2 context.pushToStack(equal) } }
0
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "redis", platforms: [ .macOS(.v10_14) ], products: [ .library(name: "Redis", targets: ["Redis"]) ], dependencies: [ .package(url: "https://github.com/vapor/redis-kit.git", from: "1.0.0-beta.2"), .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0-beta.2.1"), ], targets: [ .target(name: "Redis", dependencies: ["RedisKit", "Vapor"]), .testTarget(name: "RedisTests", dependencies: ["Redis"]) ] )
0
// // RatingPriceViewController.swift // Eat // // Created by Milton Leung on 2018-03-17. // Copyright © 2018 launchpad. All rights reserved. // import UIKit class RatingPriceViewController: UIViewController { private struct Constants { static let sliderInterval: Double = 0.5 } @IBOutlet weak var ratingQuestionLabel: UILabel! @IBOutlet weak var minimumRatingLabel: UILabel! @IBOutlet weak var ratingSlider: UISlider! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var onePriceButton: UIButton! @IBOutlet weak var twoPriceButton: UIButton! @IBOutlet weak var threePriceButton: UIButton! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var backButton: UIButton! @IBOutlet weak var nextButton: UIButton! static func viewController(searchQuery: SearchQuery) -> RatingPriceViewController { let storyboard = UIStoryboard(name: "RatingPrice", bundle: nil) guard let vc = storyboard.instantiateViewController(withIdentifier: "RatingPriceViewController") as? RatingPriceViewController else { fatalError() } vc.searchQuery = searchQuery return vc } var searchQuery: SearchQuery! var isOneSelected = false var isTwoSelected = false var isThreeSelected = false override func viewDidLoad() { super.viewDidLoad() applyStyling() setNavigation() setSlider() setDefaults() } private func setDefaults() { ratingSlider.value = Float(searchQuery.minimumRating) ratingSliderChanged() searchQuery.price.forEach { switch $0 { case 1: isOneSelected = true selectButton(button: onePriceButton) case 2: isTwoSelected = true selectButton(button: twoPriceButton) case 3: isThreeSelected = true selectButton(button: threePriceButton) default: break } } } private func applyStyling() { ratingQuestionLabel.font = Font.header(size: 13) ratingQuestionLabel.textColor = #colorLiteral(red: 0.4196078431, green: 0.4352941176, blue: 0.6, alpha: 1) minimumRatingLabel.font = Font.header(size: 24) minimumRatingLabel.textColor = #colorLiteral(red: 0.2235294118, green: 0, blue: 0.8196078431, alpha: 1) priceLabel.font = Font.header(size: 13) priceLabel.textColor = #colorLiteral(red: 0.4196078431, green: 0.4352941176, blue: 0.6, alpha: 1) self.view.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1) onePriceButton.layer.cornerRadius = 8 onePriceButton.layer.borderColor = #colorLiteral(red: 0.968627451, green: 0.6117647059, blue: 0.5333333333, alpha: 1) onePriceButton.titleLabel?.font = Font.boldButton(size: 18) unselectButton(button: onePriceButton) twoPriceButton.layer.cornerRadius = 8 twoPriceButton.layer.borderColor = #colorLiteral(red: 0.968627451, green: 0.6117647059, blue: 0.5333333333, alpha: 1) twoPriceButton.titleLabel?.font = Font.boldButton(size: 18) unselectButton(button: twoPriceButton) threePriceButton.layer.cornerRadius = 8 threePriceButton.layer.borderColor = #colorLiteral(red: 0.968627451, green: 0.6117647059, blue: 0.5333333333, alpha: 1) threePriceButton.titleLabel?.font = Font.boldButton(size: 18) unselectButton(button: threePriceButton) ratingQuestionLabel.text = "How picky are you with Yelp ratings?" priceLabel.text = "Choose your price range:" } private func unselectButton(button: UIButton) { button.setTitleColor(#colorLiteral(red: 0.968627451, green: 0.6117647059, blue: 0.5333333333, alpha: 1), for: .normal) button.layer.borderWidth = 2 button.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1) } private func selectButton(button: UIButton) { button.backgroundColor = UIColor(gradientStyle: .topToBottom, withFrame: button.frame, andColors: [#colorLiteral(red: 1, green: 0.7647058824, blue: 0.4901960784, alpha: 1), #colorLiteral(red: 0.968627451, green: 0.6117647059, blue: 0.5333333333, alpha: 1)]) button.setTitleColor(UIColor.white, for: .normal) button.layer.borderWidth = 0 } private func setSlider() { ratingSlider.setThumbImage(#imageLiteral(resourceName: "Slider"), for: .normal) ratingSlider.minimumTrackTintColor = #colorLiteral(red: 0.968627451, green: 0.6117647059, blue: 0.5333333333, alpha: 1) ratingSlider.maximumTrackTintColor = #colorLiteral(red: 1, green: 0.8784313725, blue: 0.8, alpha: 1) ratingSlider.maximumValue = 5 ratingSlider.minimumValue = 0 } @IBAction func ratingSliderChanged() { let roundedValue = Double(ratingSlider.value).round(nearest: Constants.sliderInterval) ratingSlider.value = Float(roundedValue) if roundedValue < 5 { minimumRatingLabel.text = "Minimum \(ratingSlider.value)+" } else { minimumRatingLabel.text = "Minimum \(ratingSlider.value)" } } @IBAction private func onePriceTapped() { if isOneSelected { unselectButton(button: onePriceButton) isOneSelected = false } else { selectButton(button: onePriceButton) isOneSelected = true } } @IBAction private func twoPriceTapped() { if isTwoSelected { unselectButton(button: twoPriceButton) isTwoSelected = false } else { selectButton(button: twoPriceButton) isTwoSelected = true } } @IBAction private func threePriceTapped() { if isThreeSelected { unselectButton(button: threePriceButton) isThreeSelected = false } else { selectButton(button: threePriceButton) isThreeSelected = true } } private func transformPriceInput() -> [Int] { var prices: [Int] = [] if isOneSelected { prices.append(1) } if isTwoSelected { prices.append(2) } if isThreeSelected { prices.append(3) } return prices } } // MARK: Navigation extension RatingPriceViewController { func setNavigation() { backButton.titleLabel?.font = Font.formNavigation(size: 18) backButton.setTitleColor(#colorLiteral(red: 0.4196078431, green: 0.4352941176, blue: 0.6, alpha: 1), for: .normal) nextButton.titleLabel?.font = Font.formNavigation(size: 18) nextButton.setTitleColor(#colorLiteral(red: 0.4196078431, green: 0.4352941176, blue: 0.6, alpha: 1), for: .normal) } @IBAction private func closeTapped() { navigationController?.popToRootViewController(animated: true) } @IBAction private func backTapped() { navigationController?.popViewController(animated: true) } @IBAction private func nextTapped() { searchQuery.minimumRating = Double(ratingSlider.value) searchQuery.price = transformPriceInput() let dietaryVC = DietaryRestrictionsViewController.viewController(searchQuery: searchQuery) navigationController?.pushViewController(dietaryVC, animated: true) } }
0
/* * Created by Ubique Innovation AG * https://www.ubique.ch * Copyright (c) 2020. All rights reserved. */ /// This is used to differentiate between production and calibration mode public enum DP3TMode: Equatable { case production case calibration(identifierPrefix: String, appVersion: String) static var current: DP3TMode = .production }
0
// Linear search. Time: O(n^2). TLE for big input class Solution { func getFolderNames(_ names: [String]) -> [String] { var counter = [String:Int]() var result = [String]() for name in names { if counter[name] == nil { counter[name, default: 0] += 1 result.append(name) continue } var k = counter[name]!, newName = "\(name)(\(k))" while counter[newName] != nil { k += 1 newName = "\(name)(\(k))" } counter[newName, default: 0] += 1 result.append(newName) } return result } } // Linear search. Time: O(n^2). Similar to mi above one but it's accepted. No idea why? https://tinyurl.com/yy9kwrbm class Solution { func getFolderNames(_ names: [String]) -> [String] { var dict : [String:Int] = [:] var res : [String] = [] for n in names{ if dict[n] == nil{ dict[n] = 0 res.append(n) } else{ if dict[n] != nil{ var i = dict[n]! + 1 var val = n + String("(\(i))") while(dict[val] != nil) { i += 1 val = n + String("(\(i))") } dict[n] = i dict[val] = 0 res.append(val) } } } return res } } // Binary search. Time: O(n). Wrong answer for some cases class Solution { func getFolderNames(_ names: [String]) -> [String] { var counter = [String:Int]() var result = [String]() for name in names { if counter[name] == nil { counter[name, default: 0] += 1 result.append(name) continue } var startK = counter[name]!, endK = names.count while startK < endK { let midK = startK + ((endK - startK) / 2) let newName = "\(name)(\(midK))" if counter[newName] == nil { endK = midK } else { startK = midK + 1 } } let newName = "\(name)(\(startK))" counter[newName, default: 0] += 1 result.append(newName) } return result } }
0
/** * Copyright © 2019 Aga Khan Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. 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. * * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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 import SnapKit protocol EmptyActivityCellDelegate: AnyObject { func emptyActivityCellConnectTapped() } struct EmptyActivityCellContext: CellContext { let identifier: String = EmptyActivityCell.identifier let title: String let body: String let ctaTitle: String } class EmptyActivityCell: ConfigurableTableViewCell { static let identifier = "EmptyActivityCell" private let cardView = CardViewV2() private let titleLabel = UILabel(typography: .title) private let emptyActivityImageView = UIImageView(image: Assets.onboardingDashboard.image) private let bodyLabel = UILabel(typography: .bodyRegular) private let button = Button() weak var delegate: EmptyActivityCellDelegate? override func commonInit() { super.commonInit() emptyActivityImageView.contentMode = .scaleAspectFit button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) contentView.addSubview(cardView) { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p24) $0.top.bottom.equalToSuperview().inset(Style.Padding.p12) } cardView.addSubview(titleLabel) { $0.top.equalToSuperview().inset(Style.Padding.p32) $0.leading.trailing.equalToSuperview().inset(Style.Padding.p16) } cardView.addSubview(emptyActivityImageView) { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p64) $0.top.equalTo(titleLabel.snp.bottom).offset(Style.Padding.p8) } cardView.addSubview(bodyLabel) { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p16) $0.top.equalTo(emptyActivityImageView.snp.bottom).offset(Style.Padding.p16) } cardView.addSubview(button) { $0.leading.trailing.equalToSuperview().inset(Style.Padding.p16) $0.top.equalTo(bodyLabel.snp.bottom).offset(Style.Padding.p16) $0.bottom.equalToSuperview().inset(Style.Padding.p32) } } func configure(context: CellContext) { guard let context = context as? EmptyActivityCellContext else { return } titleLabel.text = context.title bodyLabel.text = context.body button.title = context.ctaTitle } @objc func buttonTapped() { delegate?.emptyActivityCellConnectTapped() } }
0
// // FloatingSlider.swift // FloatingSlider // // Created by Renaud Cousin on 4/30/21. // import Foundation import UIKit final class FloatingSlider: UISlider { private(set) var isDragging: Bool = false private lazy var currentTimeLabel: UILabel = { let label = UILabel() label.backgroundColor = self.tintColor label.textColor = .white label.textAlignment = .center label.font = .boldSystemFont(ofSize: 12) label.layer.cornerRadius = 6 label.alpha = 0 label.layer.masksToBounds = true label.transform = hiddenTransform return label }() private let hiddenTransform = CGAffineTransform(translationX: 0, y: 20) override func layoutSubviews() { super.layoutSubviews() if currentTimeLabel.superview == nil { setupLabel() } updateValueLabel() } private func updateValueLabel() { currentTimeLabel.text = "\(self.value.rounded(.toNearestOrEven))" let thumbFrame = thumbRect(forBounds: bounds, trackRect: trackRect(forBounds: bounds), value: self.value) let labelCenter = CGPoint(x: thumbFrame.midX, y: thumbFrame.minY).applying(CGAffineTransform(translationX: 0, y: -20)) currentTimeLabel.frame = CGRect(origin: .zero, size: CGSize(width: 36, height: 22)) currentTimeLabel.center = labelCenter } private func setupLabel() { addSubview(currentTimeLabel) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) isDragging = true displayLabel() } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) isDragging = false hideLabel() } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) isDragging = false hideLabel() } private func displayLabel() { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .curveEaseInOut) { self.currentTimeLabel.transform = .identity self.currentTimeLabel.alpha = 1 } completion: { (_) in } } private func hideLabel() { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseInOut) { self.currentTimeLabel.transform = self.hiddenTransform self.currentTimeLabel.alpha = 0 } completion: { (_) in } } }
0
// // CharacterViewModel.swift // MarvelApp // // Created by Rafael Lucena on 11/24/19. // Copyright © 2019 RLMG. All rights reserved. // import Foundation import Realm import RealmSwift import RxSwift enum CharacterViewModelViewerMode { case description, comics, series } struct CharacterViewModelViewer { var indexes: [IndexPath] var mode: CharacterViewModelViewerMode } class CharacterViewModel: BaseViewModel { // Observable variables private var models = BehaviorSubject(value: CharacterViewModelViewer(indexes: [], mode: .description)) var modelsObservable: Observable<CharacterViewModelViewer> { return models.asObserver() } // Model variables var model: Character? init(withPresenter presenter: UIViewController, model: Character?) { super.init(withPresenter: presenter) self.model = model } } extension CharacterViewModel { func fetchThumbnail(character: Character) { guard let thumbnail = character.thumbnail else { return } ImageDownloaderService.shared.requestImage(withURL: thumbnail) { [weak self] (error) in guard error == nil else { return } self?.models.onNext(CharacterViewModelViewer(indexes: [IndexPath(row: 0, section: 0)], mode: .description)) } } func fetch(forModel model: HorizontalCollectionTableViewCellModel) { if let indexPath = model.indexPath { ImageDownloaderService.shared.requestImage(withURL: model.imageURL) { [weak self] (error) in guard error == nil else { return } self?.models.onNext(CharacterViewModelViewer(indexes: [indexPath], mode: .description)) } } } func fetchComics(forCharacter character: Character) { let group = DispatchGroup() for index in 0..<character.comicIds.count { let object = character.comicIds.object(at: index) group.enter() CharactersService.fetchComic(withID: "\(object.id.intValue)") { (response, error) in if let caughtError = error { self.defaultErrorHandler(withError: caughtError) return } if let result = response?.results.first { let comic = ResourceList() comic.id = NSNumber(integerLiteral: result.id) comic.name = result.title comic.image = "\(result.thumbnail.path).\(result.thumbnail.extensionString)" self.model?.comics.add(comic) } group.leave() } } group.notify(queue: DispatchQueue.main) { [weak self] in self?.models.onNext(CharacterViewModelViewer(indexes: [IndexPath(row: 0, section: 1)], mode: .comics)) } } func fetchSeries(forCharacter character: Character) { let group = DispatchGroup() for index in 0..<character.serieIds.count { let object = character.serieIds.object(at: index) group.enter() CharactersService.fetchComic(withID: "\(object.id.intValue)") { (response, error) in if let caughtError = error { self.defaultErrorHandler(withError: caughtError) return } if let result = response?.results.first { let series = ResourceList() series.id = NSNumber(integerLiteral: result.id) series.name = result.title series.image = "\(result.thumbnail.path).\(result.thumbnail.extensionString)" self.model?.serie.add(series) } group.leave() } } group.notify(queue: DispatchQueue.main) { [weak self] in if let count = self?.model?.comics.count { self?.models.onNext(CharacterViewModelViewer(indexes: [IndexPath(row: 0, section: count > 0 ? 2 : 1)], mode: .series)) } } } func favorite(character: Character) { CharactersDatabaseService.shared.addFavorite(character: character, callback: { error in guard error == nil else { return } }) } }
0
// // Fetch.swift // Carthage // // Created by Justin Spahr-Summers on 2014-12-24. // Copyright (c) 2014 Carthage. All rights reserved. // import CarthageKit import Commandant import LlamaKit import Foundation import ReactiveCocoa public struct FetchCommand: CommandType { public let verb = "fetch" public let function = "Clones or fetches a Git repository ahead of time" public func run(mode: CommandMode) -> Result<()> { return ColdSignal.fromResult(FetchOptions.evaluate(mode)) .mergeMap { options -> ColdSignal<()> in let project = ProjectIdentifier.Git(options.repositoryURL) var eventSink = ProjectEventSink() return cloneOrFetchProject(project, preferHTTPS: true) .on(next: { event, _ in eventSink.put(event) }) .then(.empty()) } .wait() } } private struct FetchOptions: OptionsType { let repositoryURL: GitURL static func create(repositoryURL: GitURL) -> FetchOptions { return self(repositoryURL: repositoryURL) } static func evaluate(m: CommandMode) -> Result<FetchOptions> { return create <*> m <| Option(usage: "the Git repository that should be cloned or fetched") } }
0
import GroupActivities import Combine enum SharePlayEvent: String, CaseIterable { case available case newSession case newActivity case receivedMessage case sessionInvalidated } public struct GenericGroupActivity: GroupActivity { let title: String let extraInfo: String? let fallbackURL: String? let supportsContinuationOnTV: Bool? public static var activityIdentifier: String = "generic-group-activity" @available(iOS 15, *) public var metadata: GroupActivityMetadata { var metadata = GroupActivityMetadata() metadata.title = self.title metadata.type = .generic metadata.fallbackURL = self.fallbackURL.flatMap({URL(string: $0)}) metadata.supportsContinuationOnTV = self.supportsContinuationOnTV ?? false return metadata } var eventPayload: [String: Any?] { return [ "title": self.title, "extraInfo": self.extraInfo ] } } struct GenericActivityMessage: Codable { let info: String } class Weak<T: AnyObject> { weak var value : T? init (value: T) { self.value = value } } @available(iOS 15, *) public class ActualSharePlay { public static let shared = ActualSharePlay() let groupStateObserver = GroupStateObserver() var emitters: [Weak<RCTEventEmitter>] = [] init() { self.groupStateObserver.$isEligibleForGroupSession.sink(receiveValue: {[weak self] available in self?.send(event: .available, body: available) }).store(in: &cancelable) Task {[weak self] in for await session in GenericGroupActivity.sessions() { self?.received(newSession: session) } } } func send(event: SharePlayEvent, body: Any!) { self.emitters.forEach({ $0.value?.sendEvent(withName: event.rawValue, body: body) }) } var cancelable = Set<AnyCancellable>() var tasks = Set<Task<Void, Error>>() public var groupSession: GroupSession<GenericGroupActivity>? var messenger: GroupSessionMessenger? func reset() { self.groupSession?.leave() self.groupSession = nil self.messenger = nil self.tasks.forEach { $0.cancel() } self.cancelable = Set() } func getInitialSession() -> NSDictionary? { if let groupSession = groupSession { return [ "title": groupSession.activity.title, "extraInfo": groupSession.activity.extraInfo ?? "" ] } return nil } func received(newSession: GroupSession<GenericGroupActivity>) { self.groupSession = newSession let messenger = GroupSessionMessenger(session: newSession) newSession.$state.sink {[weak self] state in if case .invalidated(let reason) = state { self?.send(event: .sessionInvalidated, body: "\(reason)") self?.reset() } }.store(in: &cancelable) newSession.$activity.sink { [weak self] activity in self?.send(event: .newActivity, body: activity.eventPayload) }.store(in: &cancelable) self.tasks.insert(Task {[weak self] in for await (message, _) in messenger.messages(of: GenericActivityMessage.self) { self?.send(event: .receivedMessage, body: message.info) } }) self.send(event: .newSession, body: newSession.activity.eventPayload) self.messenger = messenger } func start( title: String, extraInfo: String?, fallbackURL: String?, supportsContinuationOnTV: Bool?, prepareFirst: Bool ) async throws { let activity = GenericGroupActivity( title: title, extraInfo: extraInfo, fallbackURL: fallbackURL, supportsContinuationOnTV: supportsContinuationOnTV ) if let groupSession = groupSession { groupSession.activity = activity return } if prepareFirst { if case .activationPreferred = await activity.prepareForActivation() { _ = try await activity.activate() } return } _ = try await activity.activate() } func join() { if let groupSession = groupSession { groupSession.join() } } func sendMessage(info: String) async throws { if let messenger = messenger { try await messenger.send(GenericActivityMessage(info: info)) } } func leave() { if let groupSession = groupSession { groupSession.leave() } } func end() { if let groupSession = groupSession { groupSession.end() } } } @objc(SharePlay) class SharePlay: RCTEventEmitter { override class func requiresMainQueueSetup() -> Bool { return true } override func supportedEvents() -> [String]! { return SharePlayEvent.allCases.map({ $0.rawValue }) } @available(iOS 15, *) var sharePlay: ActualSharePlay { return ActualSharePlay.shared } override init() { super.init() if #available(iOS 15, *) { ActualSharePlay.shared.emitters.append(Weak(value: self)) } } var hasObserver = false override func startObserving() { self.hasObserver = true } override func stopObserving() { self.hasObserver = false } override func sendEvent(withName name: String!, body: Any!) { if hasObserver { super.sendEvent(withName: name, body: body) } } @objc(isSharePlayAvailable:withRejecter:) func isSharePlayAvailable(resolve: @escaping RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void { if #available(iOS 15, *) { resolve(self.sharePlay.groupStateObserver.isEligibleForGroupSession) } else { resolve(false) } } @objc(startActivity:withOptions:withResolver:withRejecter:) func startActivity(title: String, options: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void { if #available(iOS 15, *) { Task { do { try await self.sharePlay.start( title: title, extraInfo: options["extraInfo"] as? String, fallbackURL: options["fallbackURL"] as? String, supportsContinuationOnTV: options["supportsContinuationOnTV"] as? Bool, prepareFirst: options["prepareFirst"] as? Bool ?? false ) resolve(nil) } catch { reject("failed", "Failed to start group activity", error) } } } else { reject("not_available", "Share Play is not available on this iOS version", nil) } } @objc(getInitialSession:withRejecter:) func getInitialSession(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void { if #available(iOS 15, *) { resolve(self.sharePlay.getInitialSession()) } else { resolve(nil) } } @objc(joinSession) func joinSession() { if #available(iOS 15, *) { self.sharePlay.join() } } @objc(leaveSession) func leaveSession() { if #available(iOS 15, *) { self.sharePlay.leave() } } @objc(endSession) func endSession() { if #available(iOS 15, *) { self.sharePlay.end() } } @objc(sendMessage:withResolver:withRejecter:) func sendMessage(info: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { if #available(iOS 15, *) { Task { do { try await self.sharePlay.sendMessage(info: info) resolve(nil) } catch { reject("failed", "Failed to start group activity", error) } } } else { reject("not_available", "Share Play is not available on this iOS version", nil) } } }
0
// // CollectionConfigurable.swift // // Copyright (c) 2020 Dmytro Mishchenko (https://github.com/DimaMishchenko) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit public protocol CollectionConfigurable: Configurable { static var size: CGSize? { get } } public extension CollectionConfigurable { static var size: CGSize? { nil } }
0
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(HeaderStickyTabViewControllerTests.allTests), ] } #endif
0
// // Stevia+GetConstraint.swift // Stevia // // Created by Sacha Durand Saint Omer on 12/03/16. // Copyright © 2016 Sacha Durand Saint Omer. All rights reserved. // import Foundation public extension UIView { /** Gets the left constraint if found. Example Usage for changing left margin of a label : ``` label.leftConstraint?.constant = 10 // Animate if needed UIView.animateWithDuration(0.3, animations:layoutIfNeeded) ``` - Returns: The left NSLayoutConstraint if found. */ public var leftConstraint: NSLayoutConstraint? { return constraintForView(self, attribute: .Left) } /** Gets the right constraint if found. Example Usage for changing right margin of a label : ``` label.rightConstraint?.constant = 10 // Animate if needed UIView.animateWithDuration(0.3, animations:layoutIfNeeded) ``` - Returns: The right NSLayoutConstraint if found. */ public var rightConstraint: NSLayoutConstraint? { return constraintForView(self, attribute: .Right) } /** Gets the top constraint if found. Example Usage for changing top margin of a label : ``` label.topConstraint?.constant = 10 // Animate if needed UIView.animateWithDuration(0.3, animations:layoutIfNeeded) ``` - Returns: The top NSLayoutConstraint if found. */ public var topConstraint: NSLayoutConstraint? { return constraintForView(self, attribute: .Top) } /** Gets the bottom constraint if found. Example Usage for changing bottom margin of a label : ``` label.bottomConstraint?.constant = 10 // Animate if needed UIView.animateWithDuration(0.3, animations:layoutIfNeeded) ``` - Returns: The bottom NSLayoutConstraint if found. */ public var bottomConstraint: NSLayoutConstraint? { return constraintForView(self, attribute: .Bottom) } /** Gets the height constraint if found. Example Usage for changing height property of a label : ``` label.heightConstraint?.constant = 10 // Animate if needed UIView.animateWithDuration(0.3, animations:layoutIfNeeded) ``` - Returns: The height NSLayoutConstraint if found. */ public var heightConstraint: NSLayoutConstraint? { return constraintForView(self, attribute: .Height) } /** Gets the width constraint if found. Example Usage for changing width property of a label : ``` label.widthConstraint?.constant = 10 // Animate if needed UIView.animateWithDuration(0.3, animations:layoutIfNeeded) ``` - Returns: The width NSLayoutConstraint if found. */ public var widthConstraint: NSLayoutConstraint? { return constraintForView(self, attribute: .Width) } } func constraintForView(v: UIView, attribute: NSLayoutAttribute) -> NSLayoutConstraint? { if let spv = v.superview { for c in spv.constraints { if let fi = c.firstItem as? NSObject where fi == v && c.firstAttribute == attribute { return c } if let si = c.secondItem as? NSObject where si == v && c.secondAttribute == attribute { return c } } } return nil }
0
import CloudKit import XCTest @testable import CKRecordCoder class CKRecordEncoderTests: XCTestCase { func testEncodingWithSystemFields() throws { let encoder = CKRecordEncoder( zoneID: CKRecordZone.ID( zoneName: String(describing: Person.self), ownerName: CKCurrentUserDefaultName ) ) let record = try encoder.encode(Person.personWithSystemFields) XCTAssertEqual(record.recordID, Person.testRecordID) XCTAssertEqual(record.recordType, "Person") XCTAssertEqual(record["cloudKitIdentifier"], Person.testIdentifier) XCTAssertNil( record[_CloudKitSystemFieldsKeyName], "\(_CloudKitSystemFieldsKeyName) should NOT be encoded to the record directly" ) } func testEncodingPrimitives() throws { let encoder = CKRecordEncoder( zoneID: CKRecordZone.ID( zoneName: String(describing: Person.self), ownerName: CKCurrentUserDefaultName ) ) let record = try encoder.encode(Person.personWithSystemFields) XCTAssertEqual(record["name"] as? String, "Tobias Funke") XCTAssertEqual(record["age"] as? Int, 50) XCTAssertEqual(record["website"] as? String, "https://blueman.com") XCTAssertEqual(record["isDeveloper"] as? Bool, true) XCTAssertEqual(record["access"] as? String, "admin") XCTAssertNil(record["twitter"]) } func testEncodingFileURL() throws { let encoder = CKRecordEncoder( zoneID: CKRecordZone.ID( zoneName: String(describing: Person.self), ownerName: CKCurrentUserDefaultName ) ) let record = try encoder.encode(Person.personWithSystemFields) guard let asset = record["avatar"] as? CKAsset else { XCTFail("URL property with file url should encode to CKAsset.") return } XCTAssertEqual(asset.fileURL?.path, "/path/to/file") } func testEncodingWithoutSystemFields() throws { let encoder = CKRecordEncoder( zoneID: CKRecordZone.ID( zoneName: String(describing: Bookmark.self), ownerName: CKCurrentUserDefaultName ) ) let record = try encoder.encode(Bookmark.bookmarkWithoutSystemFields) XCTAssertEqual( record.recordID, CKRecord.ID( recordName: Bookmark.testIdentifier, zoneID: CKRecordZone.ID( zoneName: String(describing: Bookmark.self), ownerName: CKCurrentUserDefaultName ) ) ) XCTAssertEqual(record["title"], "Apple") } func testEncodingNestedValues() throws { let pet = Pet(name: "Buster") let child = Child(age: 22, name: "George Michael Bluth", gender: .male, pet: pet) let parent = Parent( cloudKitSystemFields: nil, cloudKitIdentifier: UUID().uuidString, name: "Michael Bluth", child: child ) let encoder = CKRecordEncoder( zoneID: CKRecordZone.ID( zoneName: String(describing: Person.self), ownerName: CKCurrentUserDefaultName ) ) let record = try encoder.encode(parent) XCTAssertEqual(record["name"], "Michael Bluth") XCTAssertEqual(record["child"], try JSONEncoder().encode(child)) } func testEncodingLists() throws { let encoder = CKRecordEncoder( zoneID: CKRecordZone.ID( zoneName: String(describing: Person.self), ownerName: CKCurrentUserDefaultName ) ) let record = try encoder.encode(Numbers.numbersMock) XCTAssertEqual(record["favorites"], [1, 2, 3, 4]) } func testEncodingUUID() throws { let model = UUIDModel.uuidModelMock let encoder = CKRecordEncoder( zoneID: CKRecordZone.ID( zoneName: String(describing: Person.self), ownerName: CKCurrentUserDefaultName ) ) let record = try encoder.encode(model) XCTAssertEqual(record["uuid"], model.uuid.uuidString) } func testEncodingURLArray() throws { let model = URLModel( cloudKitIdentifier: UUID().uuidString, urls: [ "http://tkdfeddizkj.pafpapsnrnn.net", "http://dcacju.uyczcghcqruf.bg", "http://utonggatwhxz.aicwdazc.info", "http://kfvbza.zvmoitujnrq.fr", ].compactMap(URL.init(string:)) ) let encoder = CKRecordEncoder( zoneID: CKRecordZone.ID( zoneName: String(describing: Person.self), ownerName: CKCurrentUserDefaultName ) ) let record = try encoder.encode(model) let urls = (record["urls"] as! [CKRecordValue]) .compactMap { $0 as? String } .compactMap({ URL(string: $0) }) XCTAssertEqual(urls.count, model.urls.count) } }
0
// // ViewController.swift // PROJECT // // Created by PROJECT_OWNER on TODAYS_DATE. // Copyright (c) TODAYS_YEAR PROJECT_OWNER. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
0
// RUN: %target-typecheck-verify-swift @_functionBuilder // expected-error {{'@_functionBuilder' attribute cannot be applied to this declaration}} var globalBuilder: Int @_functionBuilder // expected-error {{'@_functionBuilder' attribute cannot be applied to this declaration}} func globalBuilderFunction() -> Int { return 0 } @_functionBuilder struct Maker {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} @_functionBuilder class Inventor {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} @Maker // expected-error {{function builder attribute 'Maker' can only be applied to a parameter, function, or computed property}} typealias typename = Inventor @Maker // expected-error {{function builder attribute 'Maker' can only be applied to a variable if it defines a getter}} var global: Int // FIXME: should this be allowed? @Maker var globalWithEmptyImplicitGetter: Int {} // expected-error@-1 {{computed property must have accessors specified}} // expected-error@-3 {{function builder attribute 'Maker' can only be applied to a variable if it defines a getter}} @Maker var globalWithEmptyExplicitGetter: Int { get {} } // expected-error{{type 'Maker' has no member 'buildBlock'}} @Maker var globalWithSingleGetter: Int { 0 } // expected-error {{ype 'Maker' has no member 'buildBlock'}} @Maker var globalWithMultiGetter: Int { 0; 0 } // expected-error {{ype 'Maker' has no member 'buildBlock'}} @Maker func globalFunction() {} // expected-error {{ype 'Maker' has no member 'buildBlock'}} @Maker func globalFunctionWithFunctionParam(fn: () -> ()) {} // expected-error {{ype 'Maker' has no member 'buildBlock'}} func makerParam(@Maker fn: () -> ()) {} // FIXME: these diagnostics are reversed? func makerParamRedundant(@Maker // expected-error {{only one function builder attribute can be attached to a parameter}} @Maker // expected-note {{previous function builder specified here}} fn: () -> ()) {} func makerParamConflict(@Maker // expected-error {{only one function builder attribute can be attached to a parameter}} @Inventor // expected-note {{previous function builder specified here}} fn: () -> ()) {} func makerParamMissing1(@Missing // expected-error {{unknown attribute 'Missing'}} @Maker fn: () -> ()) {} func makerParamMissing2(@Maker @Missing // expected-error {{unknown attribute 'Missing'}} fn: () -> ()) {} func makerParamExtra(@Maker(5) // expected-error {{function builder attributes cannot have arguments}} fn: () -> ()) {} func makerParamAutoclosure(@Maker // expected-error {{function builder attribute 'Maker' cannot be applied to an autoclosure parameter}} fn: @autoclosure () -> ()) {} @_functionBuilder struct GenericMaker<T> {} // expected-note {{generic type 'GenericMaker' declared here}} expected-error {{function builder must provide at least one static 'buildBlock' method}} struct GenericContainer<T> { // expected-note {{generic type 'GenericContainer' declared here}} @_functionBuilder struct Maker {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} } func makeParamUnbound(@GenericMaker // expected-error {{reference to generic type 'GenericMaker' requires arguments}} fn: () -> ()) {} func makeParamBound(@GenericMaker<Int> fn: () -> ()) {} func makeParamNestedUnbound(@GenericContainer.Maker // expected-error {{reference to generic type 'GenericContainer' requires arguments}} fn: () -> ()) {} func makeParamNestedBound(@GenericContainer<Int>.Maker fn: () -> ()) {} protocol P { } @_functionBuilder struct ConstrainedGenericMaker<T: P> {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} struct WithinGeneric<U> { func makeParamBoundInContext(@GenericMaker<U> fn: () -> ()) {} // expected-error@+1{{type 'U' does not conform to protocol 'P'}} func makeParamBoundInContextBad(@ConstrainedGenericMaker<U> fn: () -> ()) {} } @_functionBuilder struct ValidBuilder1 { static func buildBlock(_ exprs: Any...) -> Int { return exprs.count } } protocol BuilderFuncHelper {} extension BuilderFuncHelper { static func buildBlock(_ exprs: Any...) -> Int { return exprs.count } } @_functionBuilder struct ValidBuilder2: BuilderFuncHelper {} class BuilderFuncBase { static func buildBlock(_ exprs: Any...) -> Int { return exprs.count } } @_functionBuilder class ValidBuilder3: BuilderFuncBase {} @_functionBuilder struct ValidBuilder4 {} extension ValidBuilder4 { static func buildBlock(_ exprs: Any...) -> Int { return exprs.count } } @_functionBuilder struct ValidBuilder5 { static func buildBlock() -> Int { 0 } } @_functionBuilder struct InvalidBuilder1 {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} @_functionBuilder struct InvalidBuilder2 { // expected-error {{function builder must provide at least one static 'buildBlock' method}} func buildBlock(_ exprs: Any...) -> Int { return exprs.count } // expected-note {{did you mean to make instance method 'buildBlock' static?}} {{3-3=static }} } @_functionBuilder struct InvalidBuilder3 { // expected-error {{function builder must provide at least one static 'buildBlock' method}} var buildBlock: (Any...) -> Int = { return $0.count } // expected-note {{potential match 'buildBlock' is not a static method}} } @_functionBuilder struct InvalidBuilder4 {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} extension InvalidBuilder4 { func buildBlock(_ exprs: Any...) -> Int { return exprs.count } // expected-note {{did you mean to make instance method 'buildBlock' static?}} {{3-3=static }} } protocol InvalidBuilderHelper {} extension InvalidBuilderHelper { func buildBlock(_ exprs: Any...) -> Int { return exprs.count } // expected-note {{potential match 'buildBlock' is not a static method}} } @_functionBuilder struct InvalidBuilder5: InvalidBuilderHelper {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} @_functionBuilder struct InvalidBuilder6 { // expected-error {{function builder must provide at least one static 'buildBlock' method}} static var buildBlock: Int = 0 // expected-note {{potential match 'buildBlock' is not a static method}} } struct Callable { func callAsFunction(_ exprs: Any...) -> Int { return exprs.count } } @_functionBuilder struct InvalidBuilder7 { // expected-error {{function builder must provide at least one static 'buildBlock' method}} static var buildBlock = Callable() // expected-note {{potential match 'buildBlock' is not a static method}} } class BuilderVarBase { static var buildBlock: (Any...) -> Int = { return $0.count } // expected-note {{potential match 'buildBlock' is not a static method}} } @_functionBuilder class InvalidBuilder8: BuilderVarBase {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} protocol BuilderVarHelper {} extension BuilderVarHelper { static var buildBlock: (Any...) -> Int { { return $0.count } } // expected-note {{potential match 'buildBlock' is not a static method}} } @_functionBuilder struct InvalidBuilder9: BuilderVarHelper {} // expected-error {{function builder must provide at least one static 'buildBlock' method}} @_functionBuilder struct InvalidBuilder10 { // expected-error {{function builder must provide at least one static 'buildBlock' method}} static var buildBlock: (Any...) -> Int = { return $0.count } // expected-note {{potential match 'buildBlock' is not a static method}} } @_functionBuilder enum InvalidBuilder11 { // expected-error {{function builder must provide at least one static 'buildBlock' method}} case buildBlock(Any) // expected-note {{enum case 'buildBlock' cannot be used to satisfy the function builder requirement}} } struct S { @ValidBuilder1 var v1: Int { 1 } @ValidBuilder2 var v2: Int { 1 } @ValidBuilder3 var v3: Int { 1 } @ValidBuilder4 var v4: Int { 1 } @ValidBuilder5 func v5() -> Int {} @InvalidBuilder1 var i1: Int { 1 } // expected-error {{type 'InvalidBuilder1' has no member 'buildBlock'}} @InvalidBuilder2 var i2: Int { 1 } // expected-error {{instance member 'buildBlock' cannot be used on type 'InvalidBuilder2'; did you mean to use a value of this type instead?}} @InvalidBuilder3 var i3: Int { 1 } // expected-error {{instance member 'buildBlock' cannot be used on type 'InvalidBuilder3'; did you mean to use a value of this type instead?}} @InvalidBuilder4 var i4: Int { 1 } // expected-error {{instance member 'buildBlock' cannot be used on type 'InvalidBuilder4'; did you mean to use a value of this type instead?}} @InvalidBuilder5 var i5: Int { 1 } // expected-error {{instance member 'buildBlock' cannot be used on type 'InvalidBuilder5'; did you mean to use a value of this type instead?}} @InvalidBuilder6 var i6: Int { 1 } // expected-error {{cannot call value of non-function type 'Int'}} @InvalidBuilder7 var i7: Int { 1 } @InvalidBuilder8 var i8: Int { 1 } @InvalidBuilder9 var i9: Int { 1 } @InvalidBuilder10 var i10: Int { 1 } @InvalidBuilder11 var i11: InvalidBuilder11 { 1 } }
0
// // PhotosDataSource.swift // Yep // // Created by NIX on 16/6/17. // Copyright © 2016年 Catch Inc. All rights reserved. // import Foundation class PhotosDataSource: NSObject { let photos: [Photo] fileprivate let _photos: NSArray! init(photos: [Photo]) { self.photos = photos let _photos = NSMutableArray() for photo in photos { _photos.add(photo) } self._photos = _photos } } extension PhotosDataSource: PhotosViewControllerDataSource { var numberOfPhotos: Int { return photos.count } func photoAtIndex(_ index: Int) -> Photo? { if (index >= 0) && (index < numberOfPhotos) { return photos[index] } return nil } func indexOfPhoto(_ photo: Photo) -> Int { return _photos.index(of: photo) } func containsPhoto(_ photo: Photo) -> Bool { return _photos.contains(photo) } }
0
// main.swift // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- class POClass { var ivar = "Hello World" } func main() { var object: POClass object = POClass() //% self.assertTrue(self.frame().FindVariable('object').GetObjectDescription() == '<uninitialized>', 'po correctly detects uninitialized instances') print("yay I am done") //% self.assertFalse(self.frame().FindVariable('object').GetObjectDescription() == '<uninitialized>', 'po incorrectly detects uninitialized instances') } print("Some code here") main() print("Some code there")
0
// // DimmedView.swift // PanModal // // Copyright © 2017 Tiny Speck, Inc. All rights reserved. // #if os(iOS) import UIKit /** A dim view for use as an overlay over content you want dimmed. */ public class DimmedView: UIView { /** Represents the possible states of the dimmed view. max, off or a percentage of dimAlpha. */ enum DimState { case max case off case percent(CGFloat) } // MARK: - Properties /** The state of the dimmed view */ var dimState: DimState = .off { didSet { switch dimState { case .max: alpha = 1.0 case .off: alpha = 0.0 case .percent(let percentage): alpha = max(0.0, min(1.0, percentage)) } } } /** The closure to be executed on hitTest */ var hitTestHandler: ((_ point: CGPoint, _ event: UIEvent?) -> UIView?)? /** The closure to be executed when a tap occurs */ var didTap: ((_ recognizer: UIGestureRecognizer) -> Void)? { didSet { if self.didTap != nil { addGestureRecognizer(tapGesture) } else { removeGestureRecognizer(tapGesture) } } } /** The closure to be executed when a drop session enter occurs */ var dropSessionDidEnter: (() -> Void)? { didSet { guard #available(iOS 11.0, *) else { return } if self.dropSessionDidEnter != nil { addInteraction(dropInteraction) } else { removeInteraction(dropInteraction) } } } /** Tap gesture recognizer */ private lazy var tapGesture: UIGestureRecognizer = { return UITapGestureRecognizer(target: self, action: #selector(didTapView)) }() /** Drop interaction */ @available(iOS 11.0, *) private lazy var dropInteraction = UIDropInteraction(delegate: self) // MARK: - Initializers init(dimColor: UIColor = UIColor.black.withAlphaComponent(0.7)) { super.init(frame: .zero) alpha = 0.0 backgroundColor = dimColor addGestureRecognizer(tapGesture) } required public init?(coder aDecoder: NSCoder) { fatalError() } // MARK: - Event Handlers public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { return self.hitTestHandler?(point, event) ?? super.hitTest(point, with: event) } @objc private func didTapView() { didTap?(tapGesture) } } @available(iOS 11.0, *) extension DimmedView: UIDropInteractionDelegate { public func dropInteraction( _ interaction: UIDropInteraction, sessionDidEnter session: UIDropSession ) { dropSessionDidEnter?() } } #endif
0
// // MathTableViewCell.swift // CustomCellMath // // Created by James Campagno on 6/17/16. // Copyright © 2016 Flatiron School. All rights reserved. // import UIKit class MathTableViewCell: UITableViewCell { @IBOutlet weak var firstNumberLabel: UILabel! @IBOutlet weak var secondNumberLabel: UILabel! @IBOutlet weak var thirdNumberLabel: UILabel! @IBOutlet weak var fourthNumberLabel: UILabel! }
0
// // CustomSegueTests.swift // CustomSegueTests // // Created by Martinho on 16/04/15. // Copyright (c) 2015 Martinho. All rights reserved. // import UIKit import XCTest class CustomSegueTests: 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() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
1
import XCTest #if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API // Skip tests that require @testable imports of CryptoKit. #else #if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API @testable import CryptoKit #else @testable import Crypto #endif // Test Vectors are coming from https://tools.ietf.org/html/rfc4231 class HMACTests: XCTestCase { func testUsage() { let key = SymmetricKey(size: .bits256) let someData = "SomeData".data(using: .utf8)! let mac = HMAC<SHA256>.authenticationCode(for: someData, using: key) XCTAssert(HMAC.isValidAuthenticationCode(mac, authenticating: someData, using: key)) } // Test Case 1 func testCase1VectorForAlgorithm<H: HashFunction>(hashFunction: H.Type) throws -> String { switch H.self { case is SHA256.Type: return "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" case is SHA384.Type: return "afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6" case is SHA512.Type: return "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854" default: XCTFail("Unhandled type: \(H.self)") throw TestError.unhandled } } // Test Case 2 func testCase2VectorForAlgorithm<H: HashFunction>(hashFunction: H.Type) throws -> String { switch H.self { case is SHA256.Type: return "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" case is SHA384.Type: return "af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e8e2240ca5e69e2c78b3239ecfab21649" case is SHA512.Type: return "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737" default: XCTFail("Unhandled type: \(H.self)") throw TestError.unhandled } } // Test Case 3 func testCase3VectorForAlgorithm<H: HashFunction>(hashFunction: H.Type) throws -> String { switch H.self { case is SHA256.Type: return "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe" case is SHA384.Type: return "88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e55966144b2a5ab39dc13814b94e3ab6e101a34f27" case is SHA512.Type: return "fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb" default: XCTFail("Unhandled type: \(H.self)") throw TestError.unhandled } } // Test Case 4 func testCase4VectorForAlgorithm<H: HashFunction>(hashFunction: H.Type) throws -> String { switch H.self { case is SHA256.Type: return "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b" case is SHA384.Type: return "3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e1f573b4e6801dd23c4a7d679ccf8a386c674cffb" case is SHA512.Type: return "b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd" default: XCTFail("Unhandled type: \(H.self)") throw TestError.unhandled } } // Test Case 6 func testCase6VectorForAlgorithm<H: HashFunction>(hashFunction: H.Type) throws -> String { switch H.self { case is SHA256.Type: return "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54" case is SHA384.Type: return "4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05033ac4c60c2ef6ab4030fe8296248df163f44952" case is SHA512.Type: return "80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598" default: XCTFail("Unhandled type: \(H.self)") throw TestError.unhandled } } // Test Case 7 func testCase7VectorForAlgorithm<H: HashFunction>(hashFunction: H.Type) throws -> String { switch H.self { case is SHA256.Type: return "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2" case is SHA384.Type: return "6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82461e99c5a678cc31e799176d3860e6110c46523e" case is SHA512.Type: return "e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58" default: XCTFail("Unhandled type: \(H.self)") throw TestError.unhandled } } func testHMAC<H: HashFunction>(key: SymmetricKey, data: Data, vectors: (H.Type) throws -> String, for: H.Type, file: StaticString = #file, line: UInt = #line) throws -> Bool { let code = try orFail(file: file, line: line) { try Data(hexString: vectors(H.self)) } return HMAC<H>.isValidAuthenticationCode(code, authenticating: data, using: key) } func testCase1() throws { let keyBytes = try orFail { try Array(hexString: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b") } let key = SymmetricKey(data: keyBytes) let data = "Hi There".data(using: .ascii)! XCTAssert(try testHMAC(key: key, data: data, vectors: testCase1VectorForAlgorithm, for: SHA256.self)) XCTAssert(try testHMAC(key: key, data: data, vectors: testCase1VectorForAlgorithm, for: SHA384.self)) XCTAssert(try testHMAC(key: key, data: data, vectors: testCase1VectorForAlgorithm, for: SHA512.self)) } func testCase2() throws { let keyBytes = try orFail { try Array(hexString: "4a656665") } let key = SymmetricKey(data: keyBytes) let data = try orFail { try Data(hexString: "7768617420646f2079612077616e7420666f72206e6f7468696e673f") } XCTAssert(try testHMAC(key: key, data: data, vectors: testCase2VectorForAlgorithm, for: SHA256.self)) XCTAssert(try testHMAC(key: key, data: data, vectors: testCase2VectorForAlgorithm, for: SHA384.self)) XCTAssert(try testHMAC(key: key, data: data, vectors: testCase2VectorForAlgorithm, for: SHA512.self)) } func testCase3() throws { let keyBytes = try orFail { try Array(hexString: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") } let key = SymmetricKey(data: keyBytes) let data = try orFail { try Data(hexString: "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd") } XCTAssert(try testHMAC(key: key, data: data, vectors: testCase3VectorForAlgorithm, for: SHA256.self)) XCTAssert(try testHMAC(key: key, data: data, vectors: testCase3VectorForAlgorithm, for: SHA384.self)) XCTAssert(try testHMAC(key: key, data: data, vectors: testCase3VectorForAlgorithm, for: SHA512.self)) } func testCase4() throws { let keyBytes = try orFail { try Array(hexString: "0102030405060708090a0b0c0d0e0f10111213141516171819") } let key = SymmetricKey(data: keyBytes) let data = try orFail { try Data(hexString: "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd") } XCTAssert(try testHMAC(key: key, data: data, vectors: testCase4VectorForAlgorithm, for: SHA256.self)) XCTAssert(try testHMAC(key: key, data: data, vectors: testCase4VectorForAlgorithm, for: SHA384.self)) XCTAssert(try testHMAC(key: key, data: data, vectors: testCase4VectorForAlgorithm, for: SHA512.self)) } func testCase6() throws { let keyBytes = try orFail { try Array(hexString: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") } let key = SymmetricKey(data: keyBytes) let data = try orFail { try Data(hexString: "54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a65204b6579202d2048617368204b6579204669727374") } XCTAssert(try testHMAC(key: key, data: data, vectors: testCase6VectorForAlgorithm, for: SHA256.self)) XCTAssert(try testHMAC(key: key, data: data, vectors: testCase6VectorForAlgorithm, for: SHA384.self)) XCTAssert(try testHMAC(key: key, data: data, vectors: testCase6VectorForAlgorithm, for: SHA512.self)) } func testCase7() throws { let keyBytes = try orFail { try Array(hexString: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") } let key = SymmetricKey(data: keyBytes) let data = try orFail { try Data(hexString: "5468697320697320612074657374207573696e672061206c6172676572207468616e20626c6f636b2d73697a65206b657920616e642061206c6172676572207468616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565647320746f20626520686173686564206265666f7265206265696e6720757365642062792074686520484d414320616c676f726974686d2e") } XCTAssert(try testHMAC(key: key, data: data, vectors: testCase7VectorForAlgorithm, for: SHA256.self)) XCTAssert(try testHMAC(key: key, data: data, vectors: testCase7VectorForAlgorithm, for: SHA384.self)) XCTAssert(try testHMAC(key: key, data: data, vectors: testCase7VectorForAlgorithm, for: SHA512.self)) } func testDiscontiguousHMAC<H: HashFunction>(key: SymmetricKey, data: [UInt8], for: H.Type) { let (contiguousData, discontiguousData) = data.asDataProtocols() let authContiguous = HMAC<H>.authenticationCode(for: contiguousData, using: key) let authDiscontiguous = HMAC<H>.authenticationCode(for: discontiguousData, using: key) XCTAssertEqual(authContiguous, authDiscontiguous) XCTAssertEqual(authContiguous.byteCount, H.Digest.byteCount) XCTAssertEqual(authDiscontiguous.byteCount, H.Digest.byteCount) XCTAssertTrue(HMAC<H>.isValidAuthenticationCode(authContiguous, authenticating: contiguousData, using: key)) XCTAssertTrue(HMAC<H>.isValidAuthenticationCode(authContiguous, authenticating: discontiguousData, using: key)) XCTAssertTrue(HMAC<H>.isValidAuthenticationCode(authDiscontiguous, authenticating: contiguousData, using: key)) XCTAssertTrue(HMAC<H>.isValidAuthenticationCode(authDiscontiguous, authenticating: discontiguousData, using: key)) let unrelatedAuthenticationCode = HMAC<H>.authenticationCode(for: Array("hello, world!".utf8), using: key) XCTAssertFalse(HMAC<H>.isValidAuthenticationCode(unrelatedAuthenticationCode, authenticating: contiguousData, using: key)) XCTAssertFalse(HMAC<H>.isValidAuthenticationCode(unrelatedAuthenticationCode, authenticating: discontiguousData, using: key)) // The HashedAuthenticationCode itself also has a == implementation against DataProtocols, so we want to test that. let (contiguousGoodCode, discontiguousGoodCode) = Array(authContiguous).asDataProtocols() XCTAssertTrue(authContiguous == contiguousGoodCode) XCTAssertTrue(authContiguous == discontiguousGoodCode) XCTAssertFalse(unrelatedAuthenticationCode == contiguousGoodCode) XCTAssertFalse(unrelatedAuthenticationCode == discontiguousGoodCode) } func testDiscontiguousSHA256() { testDiscontiguousHMAC(key: SymmetricKey(size: .bits256), data: Array("some data".utf8), for: SHA256.self) } func testDiscontiguousSHA384() { testDiscontiguousHMAC(key: SymmetricKey(size: .bits256), data: Array("some data".utf8), for: SHA384.self) } func testDiscontiguousSHA512() { testDiscontiguousHMAC(key: SymmetricKey(size: .bits256), data: Array("some data".utf8), for: SHA512.self) } func testHMACViaPointer() throws { let key = SymmetricKey(size: .bits256) let someData = "SomeData".data(using: .utf8)! let mac = HMAC<SHA256>.authenticationCode(for: someData, using: key) someData.withUnsafeBytes { bytesPointer in XCTAssert(HMAC.isValidAuthenticationCode(mac, authenticating: bytesPointer, using: key)) } } func testMACEqualityAgainstEmptyDispatchData() throws { let key = SymmetricKey(size: .bits256) let someData = "SomeData".data(using: .utf8)! let mac = HMAC<SHA256>.authenticationCode(for: someData, using: key) XCTAssertFalse(mac == DispatchData.empty) } } #endif // (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM
0
// // Extension+Array+IndexRange.swift // RandomHuman // // Created by Guerson Perez on 31/03/21. // import Foundation extension Array { func indexRange(_ index: Int?) -> Bool { guard let index = index, index >= 0 && index < self.count else { return false } return true } }
0
// // CoverBuilder.swift // TryTVOS // // Created by Ben on 09/04/2016. // Copyright © 2016 bcylin. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class CoverBuilder { static let DidCreateCoverNotification = "CoverBuilderDidCreateCoverNotification" static let NotificationUserInfoCoverKey = "CoverBuilderNotificationUserInfoCoverKey" private lazy var operationQueue: OperationQueue = { let _queue = OperationQueue() _queue.maxConcurrentOperationCount = 1 return _queue }() private(set) var cover: UIImage? private static let imageCache = NSCache<NSString, UIImage>() private var filledGrids = Set<Grid>() // MARK: - Private Methods private func cacheImage(_ image: UIImage, forKey key: String) { type(of: self).imageCache.setObject(image, forKey: key as NSString) NotificationCenter.default.post( name: Notification.Name(rawValue: type(of: self).DidCreateCoverNotification), object: self, userInfo: [type(of: self).NotificationUserInfoCoverKey: image] ) } // MARK: - Public Methods func add(image: UIImage, to grid: Grid, categoryID id: String? = nil, completion: @escaping (_ newCover: UIImage?) -> Void) { operationQueue.addOperation(BlockOperation { [weak self] in let imageSize = CGSize(width: image.size.width * 2, height: image.size.height * 2) var canvas: UIImage? if let currentImage = self?.cover, currentImage.size == imageSize { canvas = currentImage } else { canvas = UIImage.placeholderImage(with: imageSize) } let cover = canvas?.image(byReplacingImage: image, in: grid) self?.cover = cover self?.filledGrids.insert(grid) if let key = id, let image = cover, self?.filledGrids.count == Grid.numberOfGrids { self?.cacheImage(image, forKey: key) } DispatchQueue.main.sync { completion(cover) } }) } func coverForCategory(withID id: String) -> UIImage? { return type(of: self).imageCache.object(forKey: id as NSString) } func resetCover() { cover = nil filledGrids.removeAll() } }
0
// // File.swift // // // Created by Данил Войдилов on 28.07.2021. // import Foundation public protocol StateWithSubstate { associatedtype Substate var substate: Substate { get set } } public protocol PareGestureType: GestureType { override associatedtype State: StateWithSubstate } public protocol PareGestureBuildable: GestureType { associatedtype Substate static var initialSubstate: Substate { get } static func recognize<First: GestureType, Second: GestureType>(_ first: First, _ second: Second, context: GestureContext, state: inout Gestures.Pare<First, Second, Substate>.State) -> GestureState } extension Gestures { public struct Pare<First: GestureType, Second: GestureType, Substate>: PareGestureType { public var first: First public var second: Second private var _recognize: (First, Second, GestureContext, inout State) -> GestureState public var config: GestureConfig { first.config } public var initialState: State { State(first: first.initialState, second: second.initialState, substate: initialSubstate) } public var initialSubstate: Substate public init(_ first: First, _ second: Second, initialState: Substate, recognize: @escaping (First, Second, GestureContext, inout State) -> GestureState) { self.first = first self.second = second self.initialSubstate = initialState _recognize = recognize } public init<P: PareGestureBuildable>(_ first: First, _ second: Second, pareGesture: P.Type) where P.Substate == Substate { self = .init(first, second, initialState: P.initialSubstate) { P.recognize($0, $1, context: $2, state: &$3) } } public func recognize(context: GestureContext, state: inout State) -> GestureState { _recognize(first, second, context, &state) } public func property(context: GestureContext, state: State) -> (First.Property, Second.Property) { (first.property(context: context, state: state.first), second.property(context: context, state: state.second)) } public struct State: StateWithSubstate { public var first: First.State public var second: Second.State public var substate: Substate } } }
0
// // PostInfoViewController.swift // Ghost // // Created by Ray Bradley on 5/3/18. // Copyright © 2018 Analemma Heavy Industries. All rights reserved. // import Foundation import UIKit class PostInfoViewController: GhostBaseDetailViewController, UITableViewDataSource, UITableViewDelegate { private var _tags: [Tag] = [] var post: Post = Post() { didSet { tableView.reloadData() } } @IBOutlet weak var tableView: UITableView! @IBAction func save() { containerViewController?.editPostViewController?.save() } @IBAction func delete() { containerViewController?.editPostViewController?.delete() } override func viewDidLoad() { super.viewDidLoad() view.layer.shadowColor = UIColor.black.cgColor Tag.all { tags in self._tags = tags } } @IBAction func hide() { containerViewController?.toggleInfo() } // MARK: delegates func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch(section) { case 0: return 3 case 1: return _tags.count default: return 0 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // if it was a tag if indexPath.section == 1 { let cell = tableView.cellForRow(at: indexPath)! let tagName = cell.textLabel!.text! let isChecked = cell.accessoryType == UITableViewCellAccessoryType.checkmark if isChecked { cell.accessoryType = .none post.tags = post.tags.filter() { $0.name != tagName } // remove the tapped tagName } else { cell.accessoryType = .checkmark let selectedTag = _tags[indexPath.row] if !post.tags.contains(where: { (tag: Tag) -> Bool in tag.name == selectedTag.name }) { post.tags.append(selectedTag) } } } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = UITableViewCell() switch(indexPath.section) { case 0: switch(indexPath.row) { case 0: cell = tableView.dequeueReusableCell(withIdentifier: "postEditCellSingleLine")! (cell as! PostInfoEditCell).valueTextField.text = post.title case 1: cell = tableView.dequeueReusableCell(withIdentifier: "postEditCellMultiLine")! (cell as! PostInfoEditCellMultiLine).valueTextView.text = post.excerpt case 2: cell = tableView.dequeueReusableCell(withIdentifier: "postInfoStatus")! (cell as! PostInfoStatusCell).datePicker.date = Date() var segmentIndex = 0 if post.isDraft { segmentIndex = 2 } (cell as! PostInfoStatusCell).statusSegmentView.selectedSegmentIndex = segmentIndex default: break } // tags section case 1: // this should prolly test for Tag.id instead of Tag.name, but I'm feeling a little lazy right now cell = tableView.dequeueReusableCell(withIdentifier: "postInfoTag")! let tagName = self._tags[indexPath.row].name cell.textLabel?.text = tagName if post.tags.contains(where: { (tag: Tag) -> Bool in tag.name == tagName }) { cell.accessoryType = .checkmark } default: break; } (cell as! PostInfoBaseCell).post = self.post (cell as! PostInfoBaseCell).postInfoViewController = self return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch(section) { case 0: return "Settings" case 1: return "Tags" default: return "" } } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch(indexPath.section) { case 0: switch(indexPath.row) { case 0: return 72 // title case 1: return 80 // excerpt case 2: return 50 // status default: return 44 } case 1: return 44 default: return 44 } } }
0
// // Data // // Copyright © 2018 mkerekes. All rights reserved. // import Foundation import Domain public class MockKeychainWrapper: KeychainLoading, SessionCleaning { public init() {} public var id: String? = "28" public var token: String? { if let value = ProcessInfo().environment["userLoggedIn"], value == "false" { return nil } return "token" } public func saveToken(_ value: String) { } public var hasSession: Bool { if let value = ProcessInfo().environment["userLoggedIn"], value == "false" { return false } return true } public func deleteSession() { } public func deleteUserId() { } }
0
import Foundation import CCommonCrypto public extension String { public var md5: String { let length = Int(CC_MD5_DIGEST_LENGTH) guard let data = data(using: .utf8) else { return self } let hash = data.withUnsafeBytes { (bytes: UnsafePointer<Data>) -> [UInt8] in var hash = [UInt8](repeating: 0, count: length) CC_MD5(bytes, CC_LONG(data.count), &hash) return hash } return (0..<length) .map { String(format: hashFormat, hash[$0]) } .joined() } /// hashFormat - %02x private var hashFormat: String { return "%02x" } }
0
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "WDImagePicker", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "WDImagePicker", targets: ["WDImagePicker"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "WDImagePicker", dependencies: []), .testTarget( name: "WDImagePickerTests", dependencies: ["WDImagePicker"]), ] )
0
// // FileThumbnail.swift // Files // // Created by 翟泉 on 2019/3/20. // Copyright © 2019 cezres. All rights reserved. // import UIKit import FastImageCache class FileThumbnailCache: NSObject { typealias CompletionBlock = (String, UIImage?) -> Void static let shared = FileThumbnailCache() private let imageCache: FICImageCache = FICImageCache.shared() private let formatFamily = "ImageFormatFamily" private let formatName = "FileIconCacheFormatName" private let queue = OperationQueue() private override init() { super.init() let format = FICImageFormat(name: formatName, family: formatFamily, imageSize: CGSize(width: 160, height: 160), style: .style32BitBGR, maximumCount: 200, devices: .phone, protectionMode: .none)! imageCache.setFormats([format]) imageCache.delegate = self // imageCache.reset() queue.maxConcurrentOperationCount = 1 } func retrieveImage(identifier: String, sourceImage: @escaping () -> UIImage?, completion: @escaping CompletionBlock) { let entity = FileThumbnail(identifier: identifier, sourceImage: sourceImage) let completionBlock: FICImageCacheCompletionBlock = { (entity, _, image) in guard let entity = entity as? FileThumbnail else { return } if Thread.isMainThread { completion(entity.identifier, image) } else { DispatchQueue.main.async { completion(entity.identifier, image) } } } queue.addOperation { if self.imageCache.imageExists(for: entity, withFormatName: self.formatName) { self.imageCache.retrieveImage(for: entity, withFormatName: self.formatName, completionBlock: completionBlock) } else { self.imageCache.retrieveImage(for: entity, withFormatName: self.formatName, completionBlock: completionBlock) } } } } extension FileThumbnailCache: FICImageCacheDelegate { } private class FileThumbnail: NSObject, FICEntity { var identifier: String var sourceImage: () -> UIImage? init(identifier: String, sourceImage: @escaping () -> UIImage?) { self.identifier = identifier self.sourceImage = sourceImage } // MARK: - FICEntity @objc(UUID) var uuid: String! { return self.identifier } var sourceImageUUID: String! { return self.identifier } func sourceImageURL(withFormatName formatName: String!) -> URL! { return URL(fileURLWithPath: "/") } func image(for format: FICImageFormat!) -> UIImage! { return sourceImage() } func drawingBlock(for image: UIImage!, withFormatName formatName: String!) -> FICEntityImageDrawingBlock! { return { (context: CGContext?, contextSize: CGSize) -> Void in guard let context = context else { return } let contextBounds = CGRect(origin: .zero, size: contextSize) // context.clear(contextBounds) context.setFillColor(UIColor.white.cgColor) context.fill(contextBounds) var drawRect = CGRect.zero let imageSize = image.size let contextAspectRatio = contextSize.width / contextSize.height let imageAspectRatio = imageSize.width / imageSize.height if contextAspectRatio == imageAspectRatio { drawRect = contextBounds } else if contextAspectRatio > imageAspectRatio { let drawWidth = contextSize.height * imageAspectRatio drawRect = CGRect(x: (contextSize.width - drawWidth) / 2, y: 0, width: drawWidth, height: contextSize.height) } else { let drawHeight = contextSize.width * imageSize.height / imageSize.width drawRect = CGRect(x: 0, y: (contextSize.height - drawHeight) / 2, width: contextSize.width, height: drawHeight) } UIGraphicsPushContext(context) image.draw(in: drawRect) UIGraphicsPopContext() } } }
0
// // EventLoop.swift // Embassy // // Created by Fang-Pen Lin on 5/23/16. // Copyright © 2016 Fang-Pen Lin. All rights reserved. // import Foundation /// EventLoop uses given selector to monitor IO events, trigger callbacks when needed to /// Follow Python EventLoop design https://docs.python.org/3/library/asyncio-eventloop.html public protocol EventLoop { /// Indicate whether is this event loop running var running: Bool { get } /// Set a read-ready callback for given fileDescriptor /// - Parameter fileDescriptor: target file descriptor /// - Parameter callback: callback function to be triggered when file is ready to be read func setReader(_ fileDescriptor: Int32, callback: @escaping () -> Void) /// Remove reader callback for given fileDescriptor /// - Parameter fileDescriptor: target file descriptor func removeReader(_ fileDescriptor: Int32) /// Set a write-ready callback for given fileDescriptor /// - Parameter fileDescriptor: target file descriptor /// - Parameter callback: callback function to be triggered when file is ready to be written func setWriter(_ fileDescriptor: Int32, callback: @escaping () -> Void) /// Remove writer callback for given fileDescriptor /// - Parameter fileDescriptor: target file descriptor func removeWriter(_ fileDescriptor: Int32) /// Call given callback as soon as possible (the next event loop iteration) /// - Parameter callback: the callback function to be called func call(callback: @escaping () -> Void) /// Call given callback `withDelay` seconds later /// - Parameter withDelay: delaying in seconds /// - Parameter callback: the callback function to be called func call(withDelay: TimeInterval, callback: @escaping () -> Void) /// Call given callback at specific time /// - Parameter atTime: time the callback to be called /// - Parameter callback: the callback function to be called func call(atTime: Date, callback: @escaping () -> Void) /// Stop the event loop func stop() /// Run the event loop forever func runForever() }
0
import XCTest import TensorFlow @testable import KrakenKit final class KrakenKitTests: XCTestCase { func testUpperBound() { // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 let a: [Float] = [-1, -0.5, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let b: [Float] = [-1, -0.5, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] let c: [Float] = [-1, -0.5, 0.9, 1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10, 11] let d: [Float] = [-1, -0.5, 0.9, 1, 2, 3.3, 4, 5, 6, 7, 8, 9, 10] XCTAssertEqual(a.upperBound(value: 1.0), 4) XCTAssertEqual(a.upperBound(value: 0.99), 3) XCTAssertEqual(b.upperBound(value: 1.0), 4) XCTAssertEqual(b.upperBound(value: 0.99), 3) XCTAssertEqual(a.upperBound(value: -10), 0) XCTAssertEqual(a.upperBound(value: 100), 12) XCTAssertEqual(b.upperBound(value: 100), 13) XCTAssertEqual(b.upperBound(value: -10), 0) XCTAssertEqual(c.upperBound(value: 3.3), 6) XCTAssertEqual(c.upperBound(value: 3.4), 6) XCTAssertEqual(d.upperBound(value: 3.3), 6) XCTAssertEqual(d.upperBound(value: 3.4), 6) } func checkFileWriterStatus(fileWriter: FileWriter) { guard let fileURL = fileWriter.fileURL else { XCTAssert(false) return } if !FileManager.default.fileExists(atPath: fileURL.path) { XCTAssert(false) return } } func testHistogramSummary() { let summary = Summary() guard let fileWriterURL = URL(string: "/tmp/KrakenKit/tests/") else { XCTAssert(false) return } let fileWriter = try! FileWriter(folder: fileWriterURL, identifier: "summary-histogram") for step in 0..<100 { let floatTensor = Tensor<Float>(randomNormal: TensorShape([1000])) let doubleTensor = Tensor<Double>(randomNormal: TensorShape([1000])) let integerTensor = Tensor<Double>(randomNormal: TensorShape([1000])) summary.histogram(tensor: floatTensor, tag: "tests/Float/Tensor") summary.histogram(tensor: doubleTensor, tag: "tests/Double/Tensor") summary.histogram(tensor: integerTensor, tag: "tests/Integer/Tensor") // After that operation summary is clear if step % 2 == 0 { XCTAssertEqual(summary.proto.value.count, 3) } else { try! fileWriter.add(summary: summary, step: step) } } checkFileWriterStatus(fileWriter:fileWriter) } func testScalarSummary() { let summary = Summary() guard let fileWriterURL = URL(string: "/tmp/KrakenKit/tests/") else { XCTAssert(false) return } let fileWriter = try! FileWriter(folder: fileWriterURL, identifier: "summary-scalar") for step in 1..<100 { summary.add(scalar: Int(step) + Int(drand48() * 10), tag: "tests/Scalar/Int") summary.add(scalar: (Float(step) / 50.0) + Float(drand48()), tag: "tests/Scalar/Float") summary.add(scalar: Double(step) / 50.0 + drand48(), tag: "tests/Scalar/Double") // After that operation summary is clear if step % 2 == 0 { XCTAssertEqual(summary.proto.value.count, 3) } try! fileWriter.add(summary: summary, step: step) } checkFileWriterStatus(fileWriter:fileWriter) } func testTensorSummary() { let summary = Summary() guard let fileWriterURL = URL(string: "/tmp/KrakenKit/tests/") else { XCTAssert(false) return } let fileWriter = try! FileWriter(folder: fileWriterURL, identifier: "summary-tensor") for step in 1..<3 { let floatTensor = Tensor<Float>(randomNormal: TensorShape([1000])) let doubleTensor = Tensor<Double>(randomNormal: TensorShape([1000])) let integerTensor = Tensor<Double>(randomNormal: TensorShape([1000])) summary.add(tensor: floatTensor, tag: "Tensor/Float") summary.add(tensor: doubleTensor, tag: "Tensor/Double") summary.add(tensor :integerTensor, tag: "Tensor/Integer") // After that operation summary is clear if step % 2 == 0 { XCTAssertEqual(summary.proto.value.count, 3) } try! fileWriter.add(summary: summary, step: step) } checkFileWriterStatus(fileWriter:fileWriter) } func testImageSummary() { let summary = Summary() guard let fileWriterURL = URL(string: "/tmp/KrakenKit/tests/") else { XCTAssert(false) return } let fileWriter = try! FileWriter(folder: fileWriterURL, identifier: "summary-image") let size = Summary.ImageSize(width: 250, height: 250) for step in 0..<25 { var array = [Float]() for row in 0..<size.width { for column in 0..<size.width { var value: Float = 0/0 // NuN value, test if step % 2 == 0 { value = (0.5 - Float(row + column)) / Float(100.0) array.append(value) } else { if column == row { // leave NuN value }else { value = (Float(row + column)) / Float(100.0) } array.append(value) } } } try! summary.image(array: array, colorspace: .grayscale, size: size, tag: "/image/0") try! fileWriter.add(summary: summary, step: step) } checkFileWriterStatus(fileWriter:fileWriter) } static var allTests = [ ("testScalarSummary", testScalarSummary), ("testScalarSummary", testScalarSummary), ("testUpperBound", testUpperBound), ] }
0
// // SlashCommandKey.swift // App // // Created by Steven Vlaminck on 10/26/17. // import Foundation enum SlashCommandKey: String { case text case token case command case responseUrl = "response_url" case userName = "user_name" case userId = "user_id" case triggerId = "trigger_id" case teamId = "team_id" case channelId = "channel_id" case channelName = "channel_name" case teamDomain = "team_domain" }
0
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2019-2020 Datadog, Inc. */ import XCTest @testable import Datadog @testable import DatadogObjc /// This tests verify that objc-compatible `DatadogObjc` wrapper properly interacts with`Datadog` public API (swift). class DDDatadogTests: XCTestCase { override func setUp() { super.setUp() XCTAssertNil(Datadog.instance) XCTAssertNil(LoggingFeature.instance) XCTAssertNil(URLSessionAutoInstrumentation.instance) } override func tearDown() { XCTAssertNil(Datadog.instance) XCTAssertNil(LoggingFeature.instance) XCTAssertNil(URLSessionAutoInstrumentation.instance) super.tearDown() } // MARK: - Initializing with configuration func testItFowardsInitializationToSwift() { let configBuilder = DDConfiguration.builder(clientToken: "abcefghi", environment: "tests") configBuilder.trackURLSession(firstPartyHosts: ["example.com"]) DDDatadog.initialize( appContext: DDAppContext(mainBundle: BundleMock.mockWith(CFBundleExecutable: "app-name")), trackingConsent: randomConsent().objc, configuration: configBuilder.build() ) XCTAssertNotNil(Datadog.instance) XCTAssertEqual(LoggingFeature.instance?.configuration.common.applicationName, "app-name") XCTAssertEqual(LoggingFeature.instance?.configuration.common.environment, "tests") XCTAssertNotNil(URLSessionAutoInstrumentation.instance) URLSessionAutoInstrumentation.instance?.swizzler.unswizzle() Datadog.flushAndDeinitialize() } // MARK: - Changing Tracking Consent func testItForwardsTrackingConsentToSwift() { let initialConsent = randomConsent() let nextConsent = randomConsent() DDDatadog.initialize( appContext: .init(), trackingConsent: initialConsent.objc, configuration: DDConfiguration.builder(clientToken: "abcefghi", environment: "tests").build() ) XCTAssertEqual(Datadog.instance?.consentProvider.currentValue, initialConsent.swift) DDDatadog.setTrackingConsent(consent: nextConsent.objc) XCTAssertEqual(Datadog.instance?.consentProvider.currentValue, nextConsent.swift) Datadog.flushAndDeinitialize() } // MARK: - Setting user info func testItForwardsUserInfoToSwift() throws { DDDatadog.initialize( appContext: .init(), trackingConsent: randomConsent().objc, configuration: DDConfiguration.builder(clientToken: "abcefghi", environment: "tests").build() ) let userInfo = try XCTUnwrap(Datadog.instance?.userInfoProvider) DDDatadog.setUserInfo( id: "id", name: "name", email: "email", extraInfo: [ "attribute-int": 42, "attribute-double": 42.5, "attribute-string": "string value" ] ) XCTAssertEqual(userInfo.value.id, "id") XCTAssertEqual(userInfo.value.name, "name") XCTAssertEqual(userInfo.value.email, "email") let extraInfo = try XCTUnwrap(userInfo.value.extraInfo as? [String: AnyEncodable]) XCTAssertEqual(extraInfo["attribute-int"]?.value as? Int, 42) XCTAssertEqual(extraInfo["attribute-double"]?.value as? Double, 42.5) XCTAssertEqual(extraInfo["attribute-string"]?.value as? String, "string value") DDDatadog.setUserInfo(id: nil, name: nil, email: nil, extraInfo: [:]) XCTAssertNil(userInfo.value.id) XCTAssertNil(userInfo.value.name) XCTAssertNil(userInfo.value.email) XCTAssertTrue(userInfo.value.extraInfo.isEmpty) Datadog.flushAndDeinitialize() } // MARK: - Changing SDK verbosity level private let swiftVerbosityLevels: [LogLevel?] = [ .debug, .info, .notice, .warn, .error, .critical, nil ] private let objcVerbosityLevels: [DDSDKVerbosityLevel] = [ .debug, .info, .notice, .warn, .error, .critical, .none ] func testItForwardsSettingVerbosityLevelToSwift() { defer { Datadog.verbosityLevel = nil } zip(swiftVerbosityLevels, objcVerbosityLevels).forEach { swiftLevel, objcLevel in DDDatadog.setVerbosityLevel(objcLevel) XCTAssertEqual(Datadog.verbosityLevel, swiftLevel) } } func testItGetsVerbosityLevelFromSwift() { defer { Datadog.verbosityLevel = nil } zip(swiftVerbosityLevels, objcVerbosityLevels).forEach { swiftLevel, objcLevel in Datadog.verbosityLevel = swiftLevel XCTAssertEqual(DDDatadog.verbosityLevel(), objcLevel) } } // MARK: - Helpers private func randomConsent() -> (objc: DDTrackingConsent, swift: TrackingConsent) { let objcConsents: [DDTrackingConsent] = [.granted(), .notGranted(), .pending()] let swiftConsents: [TrackingConsent] = [.granted, .notGranted, .pending] let index: Int = .random(in: 0..<3) return (objc: objcConsents[index], swift: swiftConsents[index]) } }
0
// // FinishBlockObserver.swift // Overdrive // // Created by Said Sikira on 6/21/16. // Copyright © 2016 Said Sikira. All rights reserved. // /** Task observer that is used to notify `TaskQueue` that the task finished execution. */ class FinishBlockObserver: TaskObserver { /** Completion block that will be executed when task finished execution. Called regardless of the task result. */ var finishExecutionBlock: ((Void) -> ()) var observerName: String = "FinishBlockObserver" /// Create new `FinishBlockObserver` with completion block init(finishExecutionBlock: @escaping ((Void) -> ())) { self.finishExecutionBlock = finishExecutionBlock } func taskDidFinishExecution<T>(_ task: Task<T>) { finishExecutionBlock() } }
0
//: Playground - noun: a place where people can play import UIKit import Foundation import DTFont // use UIFontTextStyle _ = DTFont.make(with: "Avenir-Book", textStyle: .body) // use DTSize (DTSize is a enum wrapped UIContentSizeCategory _ = DTFont.make(with: "Avenir-Book") { size -> CGFloat in switch size { case .xs ... .l: return 18.0 case .xl ... .xxxl: return 22.0 default: return 24.0 } } // use DTSize and comparision operator _ = DTFont.make(with: "Avenir-Book") { size in size < .xl ? 18.0 : 22.0 } _ = DTFont.make(with: "Avenir-Book") { $0 < .xl ? 18.0 : 22.0 } class ViewControlelr: UIViewController { @IBOutlet private weak var label: UILabel! { didSet { label.enableAutomaticFontUpdate(with: DTFont.make(with: "Avenir-Book") { $0 < .l ? 18.0 : 22.0 }) } } }
0
// // AMColorPickerSlider.swift // AMColorPicker, https://github.com/adventam10/AMColorPicker // // Created by am10 on 2018/01/03. // Copyright © 2018年 am10. All rights reserved. // import UIKit class AMColorPickerSlider: UISlider { @IBInspectable var sliderTopSpace:CGFloat = 0 @IBInspectable var sliderSideSpace:CGFloat = 0 @IBInspectable var sliderColor:UIColor = UIColor.clear override var bounds: CGRect { didSet { drawSlider() } } private let sliderLayer = CAGradientLayer() required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) initView() } private func initView() { self.maximumTrackTintColor = UIColor.clear self.minimumTrackTintColor = UIColor.clear let bundle = Bundle(for: AMColorPickerSlider.self) if let imagePath = bundle.path(forResource: "AMCP_slider_thumb@2x", ofType: "png") { setThumbImage(UIImage(contentsOfFile: imagePath), for: .normal) } } override func draw(_ rect: CGRect) { drawSlider() } private func drawSlider() { sliderLayer.removeFromSuperlayer() let height = frame.height - sliderTopSpace*2 let width = frame.width - sliderSideSpace*2 sliderLayer.frame = CGRect(x: sliderSideSpace, y: sliderTopSpace, width: width, height: height) sliderLayer.startPoint = CGPoint(x: 0.0, y: 0.5) sliderLayer.endPoint = CGPoint(x: 1.0, y: 0.5) sliderLayer.cornerRadius = 5.0 sliderLayer.borderWidth = 2.0 sliderLayer.borderColor = UIColor.gray.cgColor sliderLayer.backgroundColor = sliderColor.cgColor layer.insertSublayer(sliderLayer, at: 0) } func setGradient(startColor: UIColor, endColor: UIColor) { CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) sliderLayer.colors = [startColor.cgColor, endColor.cgColor] CATransaction.commit() } }
0
// // GiftDetailModal.swift // nth Rewards // // Created by Deepak Tomar on 03/09/19. // Copyright © 2019 Deepak Tomar. All rights reserved. // import Foundation import UIKit struct GiftDetailModal : Codable { var data : GiftCard? var message : String? var success : Bool? }
0
// // dragFrame.swift // frame // // Created by Igor Grishchenko on 2018-05-14. // Copyright © 2018 Igor Grishchenko. All rights reserved. // import UIKit @IBDesignable public class UICropFrameView: UIView { // MARK: - Properties @IBInspectable var edges: Bool = true @IBInspectable var sides: Bool = true @IBInspectable var points: Bool = true @IBInspectable var lines: Bool = true @IBInspectable var border: Bool = false @IBInspectable var shadow: Bool = true @IBInspectable var resizeByCorner: Bool = true @IBInspectable var resizeByPinch: Bool = true @IBInspectable var borderColor: UIColor = .gray @IBInspectable var edgesColor: UIColor = .gray @IBInspectable var sidesColor: UIColor = .gray @IBInspectable var pointsColor: UIColor = .gray @IBInspectable var linesColor: UIColor = .gray @IBInspectable var borderWidth: CGFloat = 5 { didSet { if self.borderWidth > 10 { self.borderWidth = 10 } else if self.borderWidth < 0 { self.borderWidth = 0 } } } @IBInspectable var linesWidth: CGFloat = 0.5 { didSet { if self.linesWidth > 5 { self.linesWidth = 5 } else if self.linesWidth < 0 { self.linesWidth = 0 } } } @IBInspectable var shadowAlpha: CGFloat = 0.5 { didSet { if self.shadowAlpha > 1 { self.shadowAlpha = 1 } else if self.shadowAlpha < 0 { self.shadowAlpha = 0 } } } private var initialTouchPosition: CGPoint? private var resizing: Bool! private var frameShadow: UICropFrameShadow? override public init(frame: CGRect) { super.init(frame: frame) self.config() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.config() } override public func draw(_ rect: CGRect) { if self.edges {self.drawEdges(in: rect)} if self.points {self.drawPoints(in: rect)} if self.lines {self.drawLines(in: rect)} if self.sides {self.drawSides(in: rect)} if self.border {self.drawBorder(in: rect)} } override public func layoutSubviews() { self.backgroundColor = .clear if self.shadow { //: Init and add only one instance of the shadow if let _ = self.frameShadow {return} self.frameShadow = UICropFrameShadow(self.shadowAlpha) self.addSubview(frameShadow!) } } private func config() { self.resizing = false self.backgroundColor = .clear if self.resizeByPinch { self.addGestureRecognizer(UIPinchGestureRecognizer(target: self, action: #selector(self.resizeByPinch(_:)))) } NotificationCenter.default.addObserver(self, selector: #selector(self.didChangedOrientation(_:)), name: .UIDeviceOrientationDidChange, object: nil) } @objc private func didChangedOrientation(_ sender: AnyObject) { //: Swipes x & y and width & height to adjust frame for the orientation if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) { self.frame = CGRect(x: self.frame.minY, y: self.frame.minX, width: self.frame.height, height: self.frame.width) } if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) { self.frame = CGRect(x: self.frame.minY, y: self.frame.minX, width: self.frame.height, height: self.frame.width) } //: Redraw self.setNeedsDisplay() self.frameShadow?.frame = CGRect(x: 0 - self.frame.minX, y: 0 - self.frame.minY, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) self.frameShadow?.setNeedsDisplay() } } // MARK: - Drag & Resize extension UICropFrameView { override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) //: Init initial touch location if #available(iOS 9.1, *) { self.initialTouchPosition = touches.first?.preciseLocation(in: self) } else { self.initialTouchPosition = touches.first?.location(in: self) } } override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) if let touch = touches.first { if self.resizeByCorner { //: User finger's current point let currentPoint = touch.location(in: self) //: User is able to resize frame if he drags the corner if currentPoint.x > self.frame.width - 20 && currentPoint.y > self.frame.height - 20 { //: Resizing the frame self.resizing = true UIView.animate(withDuration: 0.01) { //: Sets the minimum possible width and height let width = max(currentPoint.x, 100) let height = max(currentPoint.y, 100) self.frame = CGRect(x: self.frame.minX, y: self.frame.minY, width: width, height: height) } } else { //: Should check if the frame is not resizing, otherwise, it will interrupt the resizing method if !self.resizing { self.modifyBased(on: touch.location(in: self.superview)) } } } else { self.modifyBased(on: touch.location(in: self.superview)) } } self.setNeedsDisplay() self.frameShadow?.setNeedsDisplay() } override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) //: Deinit initial touch location self.initialTouchPosition = nil self.resizing = false } override public func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) self.resizing = false } @objc private func resizeByPinch(_ sender: UIPinchGestureRecognizer) { if let view = sender.view { //: Scales the frame self.bounds = self.bounds.applying(view.transform.scaledBy(x: sender.scale, y: sender.scale)) sender.scale = 1 //: Sets the min size the user is able to scale to let width = min(max(view.frame.width, 100), (self.superview?.frame.width)!) let height = min(max(view.frame.height, 100), (self.superview?.frame.height)!) self.frame = CGRect(x: self.frame.minX, y: self.frame.minY, width: width, height: height) self.modifyBased(on: sender.location(in: self.superview)) } self.setNeedsDisplay() self.frameShadow?.setNeedsDisplay() } private func modifyBased(on location: CGPoint) { guard let localTouchPosition = self.initialTouchPosition else {return} var x: CGFloat = location.x - localTouchPosition.x var y: CGFloat = location.y - localTouchPosition.y //: Sets the min x & y in order not to go off the screen x = min(max(0, x), (self.superview?.frame.size.width)! - self.frame.width) y = min(max(0, y), (self.superview?.frame.size.height)! - self.frame.height) self.frame.origin = CGPoint(x: x, y: y) } } // MARK: - Drawing elements extension UICropFrameView { private func drawSides(in rect: CGRect) { var direction = (x: CGFloat(0.0), y: CGFloat(0.0)) let sides = [CGPoint(x: rect.minX, y: rect.midY), CGPoint(x: rect.maxX, y: rect.midY), CGPoint(x: rect.midX, y: rect.minY), CGPoint(x: rect.midX, y: rect.maxY)] for i in 0 ..< sides.count { switch i { case 0...1: direction.x = 0 direction.y = 5 case 2...3: direction.x = 5 direction.y = 0 default: break } let path = UIBezierPath() path.move(to: CGPoint(x: sides[i].x - direction.x, y: sides[i].y - direction.y)) path.addLine(to: CGPoint(x: sides[i].x + direction.x * 2, y: sides[i].y + direction.y * 2)) path.close() path.lineWidth = 5 self.sidesColor.set() path.stroke() } } private func drawEdges(in rect: CGRect) { var sides = (x: CGFloat(0.0), y: CGFloat(0.0)) var edges = [CGPoint(x: rect.minX, y: rect.minY), CGPoint(x: rect.minX, y: rect.maxY), CGPoint(x: rect.maxX, y: rect.minY)] //: Adds the last edge if the user removes the handle if !self.points { edges.append(CGPoint(x: rect.maxX, y: rect.maxY)) } for i in 0 ..< edges.count { switch i { case 0: sides.x = 15 sides.y = 15 case 1: sides.x = 15 sides.y = -15 case 2: sides.x = -15 sides.y = 15 case 3: sides.x = -15 sides.y = -15 default: break } let path = UIBezierPath() path.move(to: CGPoint(x: edges[i].x + sides.x, y: edges[i].y)) path.addLine(to: CGPoint(x: edges[i].x, y: edges[i].y)) path.addLine(to: CGPoint(x: edges[i].x, y: edges[i].y + sides.y)) path.addLine(to: CGPoint(x: edges[i].x, y: edges[i].y)) path.close() path.lineWidth = 5 self.edgesColor.set() path.stroke() } } private func drawPoints(in rect: CGRect) { //: Draws points for the handle var points = (x: CGFloat(0.0), y: CGFloat(0.0)) for i in 0 ..< 7 { switch i { case 0: points.x = -2 points.y = -2 case 1: points.x = -8 points.y = -2 case 2: points.x = -14 points.y = -2 case 3: points.x = -2 points.y = -8 case 4: points.x = -2 points.y = -14 case 5: points.x = -14 points.y = -2 case 6: points.x = -8 points.y = -8 default: break } let circlePath = UIBezierPath(arcCenter: CGPoint(x: rect.maxX + points.x, y: rect.maxY + points.y), radius: 2, startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true) circlePath.close() self.pointsColor.set() circlePath.fill() } } private func drawBorder(in rect: CGRect) { //: Draws frame's border let border = UIBezierPath() border.move(to: CGPoint(x: rect.minX, y: rect.minY)) border.addLine(to: CGPoint(x: rect.minX, y: rect.maxY)) border.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) border.addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) border.close() border.lineWidth = self.borderWidth self.borderColor.set() border.stroke() } private func drawLines(in rect: CGRect) { var xCoord = self.frame.width / 6 var yCoord = self.frame.height / 6 //: Lines from top to bottom for _ in 0 ..< 5 { let line = UIBezierPath() line.move(to: CGPoint(x: xCoord - 0.05, y: rect.minY)) line.addLine(to: CGPoint(x: xCoord - 0.05, y: rect.maxY)) line.close() line.lineWidth = self.linesWidth self.linesColor.set() line.stroke() xCoord += self.frame.width / 6 } //: Lines from left to right for _ in 0 ..< 5 { let line = UIBezierPath() line.move(to: CGPoint(x: rect.minX, y: yCoord - 0.05)) line.addLine(to: CGPoint(x: rect.maxX, y: yCoord - 0.05)) line.close() line.lineWidth = self.linesWidth self.linesColor.set() line.stroke() yCoord += self.frame.height / 6 } } } extension UICropFrameView { private func switchDrawings(_ initials: [Bool]? = nil) -> [Bool]? { //: Returns initial state of the drawings if let initials = initials { self.edges = initials[0] self.sides = initials[1] self.points = initials[2] self.lines = initials[3] self.border = initials[4] self.setNeedsDisplay() return nil } else { //: Hides all the drawings let initialStates = [self.edges, self.sides, self.points, self.lines, self.border] self.edges = false self.sides = false self.points = false self.lines = false self.border = false self.setNeedsDisplay() return initialStates } } public var crop: UIImage { get { let initials = self.switchDrawings() self.setNeedsDisplay() let image: UIImage = { if #available(iOS 10.0, *) { //: >= iOS 10 return UIGraphicsImageRenderer(size: (self.superview?.frame.size)!).image { _ in self.superview?.drawHierarchy(in: (self.superview?.frame)!, afterScreenUpdates: true) } } else { //: < iOS 10 UIGraphicsBeginImageContextWithOptions((self.superview?.bounds.size)!, false, 0.0) self.superview?.drawHierarchy(in: (self.superview?.bounds)!, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }() //: Scales frame bounds by 2 and crops it from the image let imageRef = image.cgImage?.cropping(to: CGRect(x: self.frame.minX * 2, y: self.frame.minY * 2, width: self.frame.width * 2, height: self.frame.height * 2)) _ = self.switchDrawings(initials!) self.setNeedsDisplay() return UIImage(cgImage: imageRef!) } } }
0
// // RequestError.swift // MastodonKit // // Created by Ornithologist Coder on 4/15/17. // Copyright © 2017 MastodonKit. All rights reserved. // import Foundation class MastodonError: Codable { /// Reason why Mastodon returned an error. let description: String private enum CodingKeys: String, CodingKey { case description = "error" } @available(*, deprecated, message: "Do not use.") init() { fatalError("Swift 4.1") } }
0
// // Traversal.swift // SwiftGraphTerminal // // Created by James Miller on 12/3/17. // Copyright © 2017 jamesmiller.io. All rights reserved. // import Foundation public enum Traversal { case BFS case DFS_Preorder case DFS_Inorder case DFS_Postorder }
0
// // QuoteImage.swift // FolioReaderKit // // Created by Heberti Almeida on 8/31/16. // Copyright (c) 2016 Folio Reader. All rights reserved. // import UIKit /** * Defines a custom Quote image, can be a square `UIImage`, solid `UIColor` or `CAGradientLayer`. */ public struct QuoteImage { public var image: UIImage! public var alpha: CGFloat! public var textColor: UIColor! public var backgroundColor: UIColor! /** Quote image from `UIImage` - parameter image: An `UIImage` to be used as background. - parameter alpha: The image opacity. Defaults to 1. - parameter textColor: The color of quote text and custom logo. Defaults to white. - parameter backgroundColor: The filter background color, if the image has a opacity this will appear. Defaults to white. - returns: A newly initialized `QuoteImage` object. */ public init(withImage image: UIImage, alpha: CGFloat = 1, textColor: UIColor = UIColor.whiteColor(), backgroundColor: UIColor = UIColor.whiteColor()) { self.image = image self.alpha = alpha self.textColor = textColor self.backgroundColor = backgroundColor } /** Quote image from `CAGradientLayer` - parameter gradient: A custom `CAGradientLayer` to make a gradient background. - parameter alpha: The image opacity. Defaults to 1. - parameter textColor: The color of quote text and custom logo. Defaults to white. - parameter backgroundColor: The filter background color, if the image has a opacity this will appear. Defaults to white. - returns: A newly initialized `QuoteImage` object. */ public init(withGradient gradient: CAGradientLayer, alpha: CGFloat = 1, textColor: UIColor = UIColor.whiteColor(), backgroundColor: UIColor = UIColor.whiteColor()) { let screenBounds = UIScreen.mainScreen().bounds gradient.frame = CGRect(x: 0, y: 0, width: screenBounds.width, height: screenBounds.width) self.image = UIImage.imageWithLayer(gradient) self.alpha = alpha self.textColor = textColor self.backgroundColor = backgroundColor } /** Quote image from `UIColor` - parameter color: A custom `UIColor` - parameter alpha: The image opacity. Defaults to 1. - parameter textColor: The color of quote text and custom logo. Defaults to white. - parameter backgroundColor: The filter background color, if the image has a opacity this will appear. Defaults to white. - returns: A newly initialized `QuoteImage` object. */ public init(withColor color: UIColor, alpha: CGFloat = 1, textColor: UIColor = UIColor.whiteColor(), backgroundColor: UIColor = UIColor.whiteColor()) { self.image = UIImage.imageWithColor(color) self.alpha = alpha self.textColor = textColor self.backgroundColor = backgroundColor } }
0
// // VerticalScrollView.swift // SwiftUIInfinityScrollExample // // Created by 松本和也 on 2020/04/15. // Copyright © 2020 松本和也. All rights reserved. // import SwiftUI struct VerticalScrollView: View { @ObservedObject var scrollState = InfinityScrollState( pageSize: CGSize(width: 200, height: 200), verticalScroll: InfinityScroll( scrollSetting: ScrollSetting( pageCount: 5, // -2〜2の0ページ目 initialPage: 2, pageSize: 200, afterMoveType: .unit ) ) ) var body: some View { let scroll = scrollState.infinityVerticalScroll return VStack { VerticalInfinityScrollView( generator: RectGenerator() ).environmentObject(scrollState) VStack { Text("page: \(scroll.pageInInfinity)") }.padding(.top, 20) } } } struct VerticalScrollView_Previews: PreviewProvider { static var previews: some View { return VerticalScrollView() } }
0
// // TagItem.swift // TagView // // Created by galaxy on 2021/5/28. // import Foundation import UIKit public final class TagItem { /// 自定义`View` public var customView: UIView? /// 宽度。如果是`auto`,需要实现`customView`的`intrinsicContentSize`方法 public var width: TagSize = .auto /// 宽度。如果是`auto`,需要实现`customView`的`intrinsicContentSize`方法,且是垂直居中显示 public var height: TagSize = .auto /// 初始化方法 public init(customView: UIView?, width: TagSize, height: TagSize) { self.customView = customView self.width = width self.height = height } public init() { } } extension TagItem { /// `item`的唯一标识符,用于两个`item`之间的比较 internal var identifier: String { return UUID().uuidString } }
0
// // KeyboardViewController.swift // SmartSyncExplorerKeyboard // // Created by Joe Andolina on 1/17/17. // Copyright © 2017 salesforce.com. All rights reserved. // import UIKit class KeyboardViewController: UIInputViewController { @IBOutlet var nextKeyboardButton: UIButton! override func updateViewConstraints() { super.updateViewConstraints() // Add custom view sizing constraints here } override func viewDidLoad() { super.viewDidLoad() // Initialize the sdk let _ = KeyboardModel.sharedInstance // Perform custom UI setup here self.nextKeyboardButton = UIButton(type: .system) self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), for: []) self.nextKeyboardButton.sizeToFit() self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false self.nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents) self.view.addSubview(self.nextKeyboardButton) self.nextKeyboardButton.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.nextKeyboardButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated } override func textWillChange(_ textInput: UITextInput?) { // The app is about to change the document's contents. Perform any preparation here. } override func textDidChange(_ textInput: UITextInput?) { // The app has just changed the document's contents, the document context has been updated. var textColor: UIColor let proxy = self.textDocumentProxy if proxy.keyboardAppearance == UIKeyboardAppearance.dark { textColor = UIColor.white } else { textColor = UIColor.black } self.nextKeyboardButton.setTitleColor(textColor, for: []) } // func initSDK(_ completionBlock: ((Void) -> Void)? = nil ) { // // let cfg = SmartSyncExplorerConfig.sharedInstance() // SFSDKDatasharingHelper.sharedInstance().appGroupName = cfg?.appGroupName // SFSDKDatasharingHelper.sharedInstance().appGroupEnabled = true // // guard // let config = SmartSyncExplorerConfig.sharedInstance() else { // return // } // // if( self.validUser ) { // print("----------> User has logged in") // SalesforceSDKManager.setInstanceClass(SalesforceSDKManagerWithSmartStore.self) // // SalesforceSDKManager.shared().connectedAppId = config.remoteAccessConsumerKey // SalesforceSDKManager.shared().connectedAppCallbackUri = config.oauthRedirectURI // SalesforceSDKManager.shared().authScopes = config.oauthScopes as! [String]? // SalesforceSDKManager.shared().authenticateAtLaunch = config.appGroupsEnabled // // let currentUser = SFUserAccountManager.sharedInstance().userAccount(forUserIdentity:SFUserAccountManager.sharedInstance().activeUserIdentity!) // SFUserAccountManager.sharedInstance().currentUser = currentUser; // // if( currentUser != nil) { // if ( self.dataMgr == nil ) { // self.dataMgr = SObjectDataManager.init(dataSpec:ContactSObjectData.dataSpec()) // } // ///self.dataMgr?.lastModifiedRecords(3, completion: completionBlock) // } // } // else { // print("----------> User not logged in") // } // } }
0
#if os(Linux) import Glibc private let system_accept = Glibc.accept private let system_listen = Glibc.listen private let sock_stream = Int32(SOCK_STREAM.rawValue) private let system_bind = Glibc.bind #else import Darwin private let system_accept = Darwin.accept private let system_listen = Darwin.listen private let sock_stream = SOCK_STREAM private let system_bind = Darwin.bind #endif public class UNIXListener : FileDescriptor { public let fileNumber: FileNumber public init(path: String) throws { fileNumber = socket(AF_UNIX, sock_stream, 0) if fileNumber == -1 { throw FileDescriptorError() } do { try bind(path) } catch { try close() throw error } } deinit { let _ = try? close() } fileprivate func bind(_ path: String) throws { var addr = sockaddr_un() addr.sun_family = sa_family_t(AF_UNIX) let lengthOfPath = path.withCString { Int(strlen($0)) } guard lengthOfPath < MemoryLayout.size(ofValue: addr.sun_path) else { throw FileDescriptorError() } _ = withUnsafeMutablePointer(to: &addr.sun_path.0) { ptr in path.withCString { strncpy(ptr, $0, lengthOfPath) } } try withUnsafePointer(to: &addr) { try $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { guard system_bind(fileNumber, $0, UInt32(MemoryLayout<sockaddr_un>.stride)) != -1 else { throw FileDescriptorError() } } } } fileprivate func listen(backlog: Int32) throws { if system_listen(fileNumber, backlog) == -1 { throw FileDescriptorError() } } /// Accepts a connection socket public func accept() throws -> UNIXConnection { let fileNumber = system_accept(self.fileNumber, nil, nil) if fileNumber == -1 { throw FileDescriptorError() } return UNIXConnection(fileNumber: fileNumber) } }
0
// // ScatterChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics.CGBase import UIKit.UIFont @objc public protocol ScatterChartRendererDelegate { func scatterChartRendererData(renderer: ScatterChartRenderer) -> ScatterChartData!; func scatterChartRenderer(renderer: ScatterChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!; func scatterChartDefaultRendererValueFormatter(renderer: ScatterChartRenderer) -> NSNumberFormatter!; func scatterChartRendererChartYMax(renderer: ScatterChartRenderer) -> Float; func scatterChartRendererChartYMin(renderer: ScatterChartRenderer) -> Float; func scatterChartRendererChartXMax(renderer: ScatterChartRenderer) -> Float; func scatterChartRendererChartXMin(renderer: ScatterChartRenderer) -> Float; func scatterChartRendererMaxVisibleValueCount(renderer: ScatterChartRenderer) -> Int; } public class ScatterChartRenderer: ChartDataRendererBase { public weak var delegate: ScatterChartRendererDelegate?; public init(delegate: ScatterChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler); self.delegate = delegate; } public override func drawData(context context: CGContext) { let scatterData = delegate!.scatterChartRendererData(self); if (scatterData === nil) { return; } for (var i = 0; i < scatterData.dataSetCount; i++) { let set = scatterData.getDataSetByIndex(i); if (set !== nil && set!.isVisible) { drawDataSet(context: context, dataSet: set as! ScatterChartDataSet); } } } private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()); internal func drawDataSet(context context: CGContext, dataSet: ScatterChartDataSet) { let trans = delegate!.scatterChartRenderer(self, transformerForAxis: dataSet.axisDependency); var phaseX = _animator.phaseX; let phaseY = _animator.phaseY; var entries = dataSet.yVals; let shapeSize = dataSet.scatterShapeSize; let shapeHalf = shapeSize / 2.0; var point = CGPoint(); let valueToPixelMatrix = trans.valueToPixelMatrix; let shape = dataSet.scatterShape; CGContextSaveGState(context); for (var j = 0, count = Int(min(ceil(CGFloat(entries.count) * _animator.phaseX), CGFloat(entries.count))); j < count; j++) { let e = entries[j]; point.x = CGFloat(e.xIndex); point.y = CGFloat(e.value) * phaseY; point = CGPointApplyAffineTransform(point, valueToPixelMatrix); if (!viewPortHandler.isInBoundsRight(point.x)) { break; } if (!viewPortHandler.isInBoundsLeft(point.x) || !viewPortHandler.isInBoundsY(point.y)) { continue; } if (shape == .Square) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor); var rect = CGRect(); rect.origin.x = point.x - shapeHalf; rect.origin.y = point.y - shapeHalf; rect.size.width = shapeSize; rect.size.height = shapeSize; CGContextFillRect(context, rect); } else if (shape == .Circle) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor); var rect = CGRect(); rect.origin.x = point.x - shapeHalf; rect.origin.y = point.y - shapeHalf; rect.size.width = shapeSize; rect.size.height = shapeSize; CGContextFillEllipseInRect(context, rect); } else if (shape == .Cross) { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor); _lineSegments[0].x = point.x - shapeHalf; _lineSegments[0].y = point.y; _lineSegments[1].x = point.x + shapeHalf; _lineSegments[1].y = point.y; CGContextStrokeLineSegments(context, _lineSegments, 2); _lineSegments[0].x = point.x; _lineSegments[0].y = point.y - shapeHalf; _lineSegments[1].x = point.x; _lineSegments[1].y = point.y + shapeHalf; CGContextStrokeLineSegments(context, _lineSegments, 2); } else if (shape == .Triangle) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor); // create a triangle path CGContextBeginPath(context); CGContextMoveToPoint(context, point.x, point.y - shapeHalf); CGContextAddLineToPoint(context, point.x + shapeHalf, point.y + shapeHalf); CGContextAddLineToPoint(context, point.x - shapeHalf, point.y + shapeHalf); CGContextClosePath(context); CGContextFillPath(context); } else if (shape == .Custom) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor); let customShape = dataSet.customScatterShape if (customShape === nil) { return; } // transform the provided custom path CGContextSaveGState(context); CGContextTranslateCTM(context, -point.x, -point.y); CGContextBeginPath(context); CGContextAddPath(context, customShape); CGContextFillPath(context); CGContextRestoreGState(context); } } CGContextRestoreGState(context); } public override func drawValues(context context: CGContext) { let scatterData = delegate!.scatterChartRendererData(self); if (scatterData === nil) { return; } let defaultValueFormatter = delegate!.scatterChartDefaultRendererValueFormatter(self); // if values are drawn if (scatterData.yValCount < Int(ceil(CGFloat(delegate!.scatterChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX))) { var dataSets = scatterData.dataSets as! [ScatterChartDataSet]; for (var i = 0; i < scatterData.dataSetCount; i++) { let dataSet = dataSets[i]; if (!dataSet.isDrawValuesEnabled) { continue; } let valueFont = dataSet.valueFont; let valueTextColor = dataSet.valueTextColor; var formatter = dataSet.valueFormatter; if (formatter === nil) { formatter = defaultValueFormatter; } var entries = dataSet.yVals; var positions = delegate!.scatterChartRenderer(self, transformerForAxis: dataSet.axisDependency).generateTransformedValuesScatter(entries, phaseY: _animator.phaseY); let shapeSize = dataSet.scatterShapeSize; let lineHeight = valueFont.lineHeight; for (var j = 0, count = Int(ceil(CGFloat(positions.count) * _animator.phaseX)); j < count; j++) { if (!viewPortHandler.isInBoundsRight(positions[j].x)) { break; } // make sure the lines don't do shitty things outside bounds if ((!viewPortHandler.isInBoundsLeft(positions[j].x) || !viewPortHandler.isInBoundsY(positions[j].y))) { continue; } let val = entries[j].value; let text = formatter!.stringFromNumber(val); ChartUtils.drawText(context: context, text: text!, point: CGPoint(x: positions[j].x, y: positions[j].y - shapeSize - lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]); } } } } public override func drawExtras(context context: CGContext) { } public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { let scatterData = delegate!.scatterChartRendererData(self); let chartXMax = delegate!.scatterChartRendererChartXMax(self); let chartYMax = delegate!.scatterChartRendererChartYMax(self); let chartYMin = delegate!.scatterChartRendererChartYMin(self); CGContextSaveGState(context); var pts = [CGPoint](count: 4, repeatedValue: CGPoint()); for (var i = 0; i < indices.count; i++) { let set = scatterData.getDataSetByIndex(indices[i].dataSetIndex) as! ScatterChartDataSet!; if (set === nil) { continue; } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor); CGContextSetLineWidth(context, set.highlightLineWidth); if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } let xIndex = indices[i].xIndex; // get the x-position if (CGFloat(xIndex) > CGFloat(chartXMax) * _animator.phaseX) { continue; } let y = CGFloat(set.yValForXIndex(xIndex)) * _animator.phaseY; // get the y-position pts[0] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMax)); pts[1] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMin)); pts[2] = CGPoint(x: 0.0, y: y); pts[3] = CGPoint(x: CGFloat(chartXMax), y: y); let trans = delegate!.scatterChartRenderer(self, transformerForAxis: set.axisDependency); trans.pointValuesToPixel(&pts); // draw the highlight lines CGContextStrokeLineSegments(context, pts, pts.count); } CGContextRestoreGState(context); } }
0
// // BluetoothTestProtocol.swift // reiner_ccid_via_dk_sample // // Created by Prakti_E on 02.06.15. // Copyright (c) 2015 Reiner SCT. All rights reserved. // import Foundation import UIKit @objc protocol BluetoothTestProtocol { /** * Open device selection. */ func openDeviceSelection() /** * Start with selected reader. */ func startWithSelectedReader() /** * Start with closest reader. */ func startWithClosestReader() }
0
// // BufferManager.swift // AudioHelpers-CoreML // // Created by Rakeeb Hossain on 2019-08-02. // Copyright © 2019 Rakeeb Hossain. All rights reserved. // import UIKit class BufferManager: NSObject { var mFFTInputBuffer: UnsafeMutablePointer<Float32>? private var mFFTInputBufferFrameIndex: Int private var mFFTInputBufferLoopingFrameIndex: Int private var mFFTInputBufferLen: Int let bufferSize = 4160 var hasNewFFTData: Int32 = 0 // volatile var needsNewFFTData: Int32 = 1 // volatile var semaphore = DispatchSemaphore(value: 2) var semaphoreCounter: Int32 = 1 init(maxFramesPerSlice: Int) { mFFTInputBufferLen = maxFramesPerSlice mFFTInputBufferFrameIndex = 0 mFFTInputBufferLoopingFrameIndex = 0 mFFTInputBuffer = UnsafeMutablePointer.allocate(capacity: maxFramesPerSlice) } deinit { mFFTInputBuffer?.deallocate() } func memcpyAudioToFFTBuffer(_ inData: UnsafeMutablePointer<Float32>, _ nFrames: UInt32, completion: @escaping (Bool, UnsafeMutablePointer<Float32>) -> Void) { let framesToCopy = Int(nFrames) memcpy(mFFTInputBuffer?.advanced(by: mFFTInputBufferFrameIndex*MemoryLayout<Float32>.size), inData, size_t(framesToCopy * MemoryLayout<Float32>.size)) mFFTInputBufferFrameIndex += framesToCopy if mFFTInputBufferFrameIndex >= mFFTInputBufferLen { let bufptr: UnsafeMutablePointer<Float32> = UnsafeMutablePointer.allocate(capacity: mFFTInputBufferLen) memcpy(bufptr, mFFTInputBuffer, size_t(mFFTInputBufferLen * MemoryLayout<Float32>.size)) mFFTInputBufferFrameIndex -= mFFTInputBufferLen completion(true, bufptr) } else { var arr: [Float32] = [] completion(false, &arr) } } }
0
// // TouchHandler.swift // SwiftResponsiveLabel // // Created by Susmita Horrow on 01/03/16. // Copyright © 2016 hsusmita.com. All rights reserved. // import Foundation import UIKit.UIGestureRecognizerSubclass class TouchGestureRecognizer: UIGestureRecognizer { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesBegan(touches, with: event) self.state = .began } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesCancelled(touches, with: event) self.state = .cancelled } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesEnded(touches, with: event) self.state = .ended } } class TouchHandler: NSObject { fileprivate var responsiveLabel: SwiftResponsiveLabel? var touchIndex: Int? var selectedRange: NSRange? fileprivate var defaultAttributes: [String: AnyObject]? fileprivate var highlightAttributes: [String: AnyObject]? init(responsiveLabel: SwiftResponsiveLabel) { super.init() self.responsiveLabel = responsiveLabel let gestureRecognizer = TouchGestureRecognizer(target: self, action: #selector(TouchHandler.handleTouch(_:))) self.responsiveLabel?.addGestureRecognizer(gestureRecognizer) gestureRecognizer.delegate = self } @objc fileprivate func handleTouch(_ gesture: UIGestureRecognizer) { let touchLocation = gesture.location(in: self.responsiveLabel) let index = self.responsiveLabel?.textKitStack.touchedCharacterIndexAtLocation(touchLocation) self.touchIndex = index switch gesture.state { case .began: self.beginSession() case .cancelled: self.cancelSession() case .ended: self.endSession() default: return } } fileprivate func beginSession() { guard let textkitStack = self.responsiveLabel?.textKitStack, let touchIndex = self.touchIndex, self.touchIndex! < textkitStack.textStorageLength else { return } var rangeOfTappedText = NSRange() let highlightAttributeInfo = textkitStack.rangeAttributeForKey(RLHighlightedAttributesDictionary, atIndex: touchIndex) rangeOfTappedText = highlightAttributeInfo.range self.highlightAttributes = highlightAttributeInfo.attribute as? [String : AnyObject] if let attributes = self.highlightAttributes { self.selectedRange = rangeOfTappedText self.defaultAttributes = [String : AnyObject]() for (key, value) in attributes { self.defaultAttributes![key] = textkitStack.rangeAttributeForKey(key, atIndex: touchIndex).attribute textkitStack.addAttribute(value, forkey: key, atRange: rangeOfTappedText) } self.responsiveLabel?.setNeedsDisplay() } if self.selectedRange == nil { if let _ = textkitStack.rangeAttributeForKey(RLTapResponderAttributeName, atIndex: touchIndex).attribute as? PatternTapResponder { self.selectedRange = rangeOfTappedText } } } fileprivate func cancelSession() { self.removeHighlight() } fileprivate func endSession() { self.performActionOnSelection() self.removeHighlight() } fileprivate func removeHighlight() { guard let textkitStack = self.responsiveLabel?.textKitStack, let selectedRange = self.selectedRange, let highlightAttributes = self.highlightAttributes, let defaultAttributes = self.defaultAttributes else { self.resetGlobalVariables() return } for (key, _) in highlightAttributes { textkitStack.removeAttribute(forkey: key, atRange: selectedRange) if let defaultValue = defaultAttributes[key] { textkitStack.addAttribute(defaultValue, forkey: key, atRange: selectedRange) } } self.responsiveLabel?.setNeedsDisplay() self.resetGlobalVariables() } private func resetGlobalVariables() { self.selectedRange = nil self.defaultAttributes = nil self.highlightAttributes = nil } fileprivate func performActionOnSelection() { guard let textkitStack = self.responsiveLabel?.textKitStack, let selectedRange = self.selectedRange else { return } if let tapResponder = textkitStack.rangeAttributeForKey(RLTapResponderAttributeName, atIndex: selectedRange.location).attribute as? PatternTapResponder { let tappedString = textkitStack.substringForRange(selectedRange) tapResponder.perform(tappedString) } } } extension TouchHandler : UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { let touchLocation = touch.location(in: self.responsiveLabel) guard let textkitStack = self.responsiveLabel?.textKitStack, let index = self.responsiveLabel?.textKitStack.touchedCharacterIndexAtLocation(touchLocation), index < textkitStack.textStorageLength else { return false } let keys = textkitStack.rangeAttributesAtIndex(index).map { $0.key } return keys.contains(RLHighlightedAttributesDictionary) || keys.contains(RLTapResponderAttributeName) } }
0
// // FactoryChanTests.swift // FactoryChanTests // // Created by Bubblegum on 14/11/18. // Copyright © 2018 Pleni. All rights reserved. // import XCTest @testable import FactoryChan class FactoryChanTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
0
// // UIView+Constraint.swift // TodayNews // // Created by ZXL on 2017/2/14. // Copyright © 2017年 zxl. All rights reserved. // import UIKit extension UIView { private func disableTranslatesAutoresizingMaskIntoConstraints() { // 系统默认会给autoresizing 约束 关闭autoresizing 不关闭否则程序崩溃 self.translatesAutoresizingMaskIntoConstraints = false } // 下 右 上 左 (子视图和父视图) func addBottomConstraintToSuperView(constraint:CGFloat) { self.addBottomConstraintToView(toView: superview!, constraint: constraint) } func addRightConstraintToSuperView(constraint:CGFloat) { self.addRightConstraintToView(toView: superview!, constraint: constraint) } func addTopConstraintToSuperView(constraint:CGFloat) { self.addTopConstraintToView(toView: superview!, constraint: constraint) } func addLeftConstraintToSuperView(constraint:CGFloat) { self.addLeftConstraintToView(toView: superview!, constraint: constraint) } // 宽 高 func addWidthConstraint(constraint:CGFloat) { self.disableTranslatesAutoresizingMaskIntoConstraints() let width:NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 0.0, constant: constraint) self.addConstraint(width) } func addHeightConstraint(constraint:CGFloat) { self.disableTranslatesAutoresizingMaskIntoConstraints() let height:NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 0.0, constant: constraint) self.addConstraint(height) } func addSizeConstraint(width:CGFloat ,height:CGFloat) { self.addWidthConstraint(constraint: width) self.addHeightConstraint(constraint: height) } // 下 右 上 左(约束和其他视图的关系) func addBottomConstraintToView(toView:UIView ,constraint:CGFloat) { self.disableTranslatesAutoresizingMaskIntoConstraints() let bottom:NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: toView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -constraint) toView.addConstraint(bottom) } func addRightConstraintToView(toView:UIView ,constraint:CGFloat) { self.disableTranslatesAutoresizingMaskIntoConstraints() let right:NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: toView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -constraint) toView.addConstraint(right) } func addTopConstraintToView(toView:UIView ,constraint:CGFloat) { self.disableTranslatesAutoresizingMaskIntoConstraints() let top:NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: toView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: constraint) toView.addConstraint(top) } func addLeftConstraintToView(toView:UIView ,constraint:CGFloat) { self.disableTranslatesAutoresizingMaskIntoConstraints() let left:NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: toView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: constraint) toView.addConstraint(left) } func addCenterXConstraintToView(toView:UIView ,offset:CGFloat) { self.disableTranslatesAutoresizingMaskIntoConstraints() let centerX:NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: toView, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: offset) toView.addConstraint(centerX) } }
0
// // PodComms.swift // OmniKit // // Created by Pete Schwamb on 10/7/17. // Copyright © 2017 Pete Schwamb. All rights reserved. // import Foundation import RileyLinkBLEKit import LoopKit import os.log public protocol PodCommsDelegate: class { func podComms(_ podComms: PodComms, didChange state: PodState) } public class PodComms { private var configuredDevices: Set<RileyLinkDevice> = Set() private weak var delegate: PodCommsDelegate? private let sessionQueue = DispatchQueue(label: "com.rileylink.OmniKit.PodComms", qos: .utility) public let log = OSLog(category: "PodComms") private var podState: PodState { didSet { self.delegate?.podComms(self, didChange: podState) } } public init(podState: PodState, delegate: PodCommsDelegate?) { self.podState = podState self.delegate = delegate } public enum PairResults { case success(podState: PodState) case failure(Error) } public class func pair(using deviceSelector: @escaping (_ completion: @escaping (_ device: RileyLinkDevice?) -> Void) -> Void, timeZone: TimeZone, completion: @escaping (PairResults) -> Void) { deviceSelector { (device) in guard let device = device else { completion(.failure(PodCommsError.noRileyLinkAvailable)) return } device.runSession(withName: "Pair Pod") { (commandSession) in do { try commandSession.configureRadio() // Create random address with 20 bits. Can we use all 24 bits? let newAddress = 0x1f000000 | (arc4random() & 0x000fffff) let transport = MessageTransport(session: commandSession, address: 0xffffffff, ackAddress: newAddress) // Assign Address let assignAddress = AssignAddressCommand(address: newAddress) let response = try transport.send([assignAddress]) guard let config1 = response.messageBlocks[0] as? ConfigResponse else { let responseType = response.messageBlocks[0].blockType throw PodCommsError.unexpectedResponse(response: responseType) } // Verify address is set let activationDate = Date() let dateComponents = ConfirmPairingCommand.dateComponents(date: activationDate, timeZone: timeZone) let confirmPairing = ConfirmPairingCommand(address: newAddress, dateComponents: dateComponents, lot: config1.lot, tid: config1.tid) let response2 = try transport.send([confirmPairing]) guard let config2 = response2.messageBlocks[0] as? ConfigResponse else { let responseType = response.messageBlocks[0].blockType throw PodCommsError.unexpectedResponse(response: responseType) } guard config2.pairingState == .paired else { throw PodCommsError.invalidData } let newPodState = PodState( address: newAddress, activatedAt: activationDate, timeZone: timeZone, piVersion: String(describing: config2.piVersion), pmVersion: String(describing: config2.pmVersion), lot: config2.lot, tid: config2.tid ) completion(.success(podState: newPodState)) } catch let error { completion(.failure(error)) } } } } public enum SessionRunResult { case success(session: PodCommsSession) case failure(PodCommsError) } public func runSession(withName name: String, using deviceSelector: @escaping (_ completion: @escaping (_ device: RileyLinkDevice?) -> Void) -> Void, _ block: @escaping (_ result: SessionRunResult) -> Void) { sessionQueue.async { let semaphore = DispatchSemaphore(value: 0) deviceSelector { (device) in guard let device = device else { block(.failure(PodCommsError.noRileyLinkAvailable)) semaphore.signal() return } device.runSession(withName: name) { (commandSession) in self.configureDevice(device, with: commandSession) let transport = MessageTransport(session: commandSession, address: self.podState.address) let podSession = PodCommsSession(podState: self.podState, transport: transport, delegate: self) block(.success(session: podSession)) semaphore.signal() } } semaphore.wait() } } // Must be called from within the RileyLinkDevice sessionQueue private func configureDevice(_ device: RileyLinkDevice, with session: CommandSession) { guard !self.configuredDevices.contains(device) else { return } do { log.debug("configureRadio (omnipod)") _ = try session.configureRadio() } catch let error { log.error("configure Radio failed with error: %{public}@", String(describing: error)) // Ignore the error and let the block run anyway return } NotificationCenter.default.post(name: .DeviceRadioConfigDidChange, object: device) NotificationCenter.default.addObserver(self, selector: #selector(deviceRadioConfigDidChange(_:)), name: .DeviceRadioConfigDidChange, object: device) NotificationCenter.default.addObserver(self, selector: #selector(deviceRadioConfigDidChange(_:)), name: .DeviceConnectionStateDidChange, object: device) log.debug("added device %{public}@ to configuredDevices", device.name ?? "unknown") configuredDevices.insert(device) } @objc private func deviceRadioConfigDidChange(_ note: Notification) { guard let device = note.object as? RileyLinkDevice else { return } log.debug("removing device %{public}@ from configuredDevices", device.name ?? "unknown") NotificationCenter.default.removeObserver(self, name: .DeviceRadioConfigDidChange, object: device) NotificationCenter.default.removeObserver(self, name: .DeviceConnectionStateDidChange, object: device) configuredDevices.remove(device) } } private extension CommandSession { func configureRadio() throws { // SYNC1 |0xDF00|0x54|Sync Word, High Byte // SYNC0 |0xDF01|0xC3|Sync Word, Low Byte // PKTLEN |0xDF02|0x32|Packet Length // PKTCTRL1 |0xDF03|0x24|Packet Automation Control // PKTCTRL0 |0xDF04|0x00|Packet Automation Control // FSCTRL1 |0xDF07|0x06|Frequency Synthesizer Control // FREQ2 |0xDF09|0x12|Frequency Control Word, High Byte // FREQ1 |0xDF0A|0x14|Frequency Control Word, Middle Byte // FREQ0 |0xDF0B|0x5F|Frequency Control Word, Low Byte // MDMCFG4 |0xDF0C|0xCA|Modem configuration // MDMCFG3 |0xDF0D|0xBC|Modem Configuration // MDMCFG2 |0xDF0E|0x0A|Modem Configuration // MDMCFG1 |0xDF0F|0x13|Modem Configuration // MDMCFG0 |0xDF10|0x11|Modem Configuration // MCSM0 |0xDF14|0x18|Main Radio Control State Machine Configuration // FOCCFG |0xDF15|0x17|Frequency Offset Compensation Configuration // AGCCTRL1 |0xDF18|0x70|AGC Control // FSCAL3 |0xDF1C|0xE9|Frequency Synthesizer Calibration // FSCAL2 |0xDF1D|0x2A|Frequency Synthesizer Calibration // FSCAL1 |0xDF1E|0x00|Frequency Synthesizer Calibration // FSCAL0 |0xDF1F|0x1F|Frequency Synthesizer Calibration // TEST1 |0xDF24|0x31|Various Test Settings // TEST0 |0xDF25|0x09|Various Test Settings // PA_TABLE0 |0xDF2E|0x60|PA Power Setting 0 // VERSION |0xDF37|0x04|Chip ID[7:0] try setSoftwareEncoding(.manchester) try setPreamble(0x6665) try setBaseFrequency(Measurement(value: 433.91, unit: .megahertz)) try updateRegister(.pktctrl1, value: 0x20) try updateRegister(.pktctrl0, value: 0x00) try updateRegister(.fsctrl1, value: 0x06) try updateRegister(.mdmcfg4, value: 0xCA) try updateRegister(.mdmcfg3, value: 0xBC) // 0xBB for next lower bitrate try updateRegister(.mdmcfg2, value: 0x06) try updateRegister(.mdmcfg1, value: 0x70) try updateRegister(.mdmcfg0, value: 0x11) try updateRegister(.deviatn, value: 0x44) try updateRegister(.mcsm0, value: 0x18) try updateRegister(.foccfg, value: 0x17) try updateRegister(.fscal3, value: 0xE9) try updateRegister(.fscal2, value: 0x2A) try updateRegister(.fscal1, value: 0x00) try updateRegister(.fscal0, value: 0x1F) try updateRegister(.test1, value: 0x31) try updateRegister(.test0, value: 0x09) try updateRegister(.paTable0, value: 0x84) try updateRegister(.sync1, value: 0xA5) try updateRegister(.sync0, value: 0x5A) } } extension PodComms: PodCommsSessionDelegate { public func podCommsSession(_ podCommsSession: PodCommsSession, didChange state: PodState) { self.podState = state } }
0
/* This source file is part of the Swift.org open source project Copyright (c) 2021 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basics import PackageGraph import PackageLoading import PackageModel @testable import SPMBuildCore import SPMTestSupport import TSCBasic import TSCUtility import Workspace import XCTest class PluginInvocationTests: XCTestCase { func testBasics() throws { // Construct a canned file system and package graph with a single package and a library that uses a plugin that uses a tool. let fileSystem = InMemoryFileSystem(emptyFiles: "/Foo/Plugins/FooPlugin/source.swift", "/Foo/Sources/FooTool/source.swift", "/Foo/Sources/Foo/source.swift", "/Foo/Sources/Foo/SomeFile.abc" ) let observability = ObservabilitySystem.makeForTesting() let graph = try loadPackageGraph( fs: fileSystem, manifests: [ Manifest.createRootManifest( name: "Foo", path: .init("/Foo"), products: [ ProductDescription( name: "Foo", type: .library(.dynamic), targets: ["Foo"] ) ], targets: [ TargetDescription( name: "Foo", type: .regular, pluginUsages: [.plugin(name: "FooPlugin", package: nil)] ), TargetDescription( name: "FooPlugin", dependencies: ["FooTool"], type: .plugin, pluginCapability: .buildTool ), TargetDescription( name: "FooTool", dependencies: [], type: .executable ), ] ) ], observabilityScope: observability.topScope ) // Check the basic integrity before running plugins. XCTAssertNoDiagnostics(observability.diagnostics) PackageGraphTester(graph) { graph in graph.check(packages: "Foo") graph.check(targets: "Foo", "FooPlugin", "FooTool") graph.checkTarget("Foo") { target in target.check(dependencies: "FooPlugin") } graph.checkTarget("FooPlugin") { target in target.check(type: .plugin) target.check(dependencies: "FooTool") } graph.checkTarget("FooTool") { target in target.check(type: .executable) } } // A fake PluginScriptRunner that just checks the input conditions and returns canned output. struct MockPluginScriptRunner: PluginScriptRunner { var hostTriple: Triple { return UserToolchain.default.triple } func runPluginScript( sources: Sources, inputJSON: Data, toolsVersion: ToolsVersion, writableDirectories: [AbsolutePath], observabilityScope: ObservabilityScope, fileSystem: FileSystem ) throws -> (outputJSON: Data, stdoutText: Data) { // Check that we were given the right sources. XCTAssertEqual(sources.root, AbsolutePath("/Foo/Plugins/FooPlugin")) XCTAssertEqual(sources.relativePaths, [RelativePath("source.swift")]) // Deserialize and check the input. let decoder = JSONDecoder() let context = try decoder.decode(PluginScriptRunnerInput.self, from: inputJSON) XCTAssertEqual(context.products.count, 2, "unexpected products: \(dump(context.products))") XCTAssertEqual(context.products[0].name, "Foo", "unexpected products: \(dump(context.products))") XCTAssertEqual(context.products[0].targetIds.count, 1, "unexpected product targets: \(dump(context.products[0].targetIds))") XCTAssertEqual(context.products[1].name, "FooTool", "unexpected products: \(dump(context.products))") XCTAssertEqual(context.products[1].targetIds.count, 1, "unexpected product targets: \(dump(context.products[1].targetIds))") XCTAssertEqual(context.targets.count, 2, "unexpected targets: \(dump(context.targets))") XCTAssertEqual(context.targets[0].name, "Foo", "unexpected targets: \(dump(context.targets))") XCTAssertEqual(context.targets[0].dependencies.count, 0, "unexpected target dependencies: \(dump(context.targets[0].dependencies))") XCTAssertEqual(context.targets[1].name, "FooTool", "unexpected targets: \(dump(context.targets))") XCTAssertEqual(context.targets[1].dependencies.count, 0, "unexpected target dependencies: \(dump(context.targets[1].dependencies))") // Emit and return a serialized output PluginInvocationResult JSON. let encoder = JSONEncoder() let result = PluginScriptRunnerOutput( diagnostics: [ .init( severity: .warning, message: "A warning", file: "/Foo/Sources/Foo/SomeFile.abc", line: 42 ) ], buildCommands: [ .init( displayName: "Do something", executable: "/bin/FooTool", arguments: ["-c", "/Foo/Sources/Foo/SomeFile.abc"], environment: [ "X": "Y" ], workingDirectory: "/Foo/Sources/Foo", inputFiles: [], outputFiles: [] ) ], prebuildCommands: [ ] ) let outputJSON = try encoder.encode(result) return (outputJSON: outputJSON, stdoutText: "Hello Plugin!".data(using: .utf8)!) } } // Construct a canned input and run plugins using our MockPluginScriptRunner(). let outputDir = AbsolutePath("/Foo/.build") let builtToolsDir = AbsolutePath("/Foo/.build/debug") let pluginRunner = MockPluginScriptRunner() let results = try graph.invokePlugins( outputDir: outputDir, builtToolsDir: builtToolsDir, buildEnvironment: BuildEnvironment(platform: .macOS, configuration: .debug), pluginScriptRunner: pluginRunner, observabilityScope: observability.topScope, fileSystem: fileSystem ) // Check the canned output to make sure nothing was lost in transport. XCTAssertNoDiagnostics(observability.diagnostics) XCTAssertEqual(results.count, 1) let (evalTarget, evalResults) = try XCTUnwrap(results.first) XCTAssertEqual(evalTarget.name, "Foo") XCTAssertEqual(evalResults.count, 1) let evalFirstResult = try XCTUnwrap(evalResults.first) XCTAssertEqual(evalFirstResult.prebuildCommands.count, 0) XCTAssertEqual(evalFirstResult.buildCommands.count, 1) let evalFirstCommand = try XCTUnwrap(evalFirstResult.buildCommands.first) XCTAssertEqual(evalFirstCommand.configuration.displayName, "Do something") XCTAssertEqual(evalFirstCommand.configuration.executable, "/bin/FooTool") XCTAssertEqual(evalFirstCommand.configuration.arguments, ["-c", "/Foo/Sources/Foo/SomeFile.abc"]) XCTAssertEqual(evalFirstCommand.configuration.environment, ["X": "Y"]) XCTAssertEqual(evalFirstCommand.configuration.workingDirectory, AbsolutePath("/Foo/Sources/Foo")) XCTAssertEqual(evalFirstCommand.inputFiles, []) XCTAssertEqual(evalFirstCommand.outputFiles, []) XCTAssertEqual(evalFirstResult.diagnostics.count, 1) let evalFirstDiagnostic = try XCTUnwrap(evalFirstResult.diagnostics.first) XCTAssertEqual(evalFirstDiagnostic.severity, .warning) XCTAssertEqual(evalFirstDiagnostic.message, "A warning") XCTAssertEqual(evalFirstDiagnostic.metadata?.fileLocation, FileLocation(.init("/Foo/Sources/Foo/SomeFile.abc"), line: 42)) XCTAssertEqual(evalFirstResult.textOutput, "Hello Plugin!") } func testCompilationDiagnostics() throws { try testWithTemporaryDirectory { tmpPath in // Create a sample package with a library target and a plugin. let packageDir = tmpPath.appending(components: "MyPackage") try localFileSystem.writeFileContents(packageDir.appending(component: "Package.swift")) { $0 <<< """ // swift-tools-version: 5.6 import PackageDescription let package = Package( name: "MyPackage", targets: [ .target( name: "MyLibrary", plugins: [ "MyPlugin", ] ), .plugin( name: "MyPlugin", capability: .buildTool() ), ] ) """ } try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "library.swift")) { $0 <<< "public func Foo() { }\n" } try localFileSystem.writeFileContents(packageDir.appending(components: "Plugins", "MyPlugin", "plugin.swift")) { $0 <<< "syntax error\n" } // Load a workspace from the package. let observability = ObservabilitySystem.makeForTesting() let workspace = try Workspace( fileSystem: localFileSystem, location: .init(forRootPackage: packageDir, fileSystem: localFileSystem), customManifestLoader: ManifestLoader(toolchain: ToolchainConfiguration.default), delegate: MockWorkspaceDelegate() ) // Load the root manifest. let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: []) let rootManifests = try tsc_await { workspace.loadRootManifests( packages: rootInput.packages, observabilityScope: observability.topScope, completion: $0 ) } XCTAssert(rootManifests.count == 1, "\(rootManifests)") // Load the package graph. let packageGraph = try workspace.loadPackageGraph(rootInput: rootInput, observabilityScope: observability.topScope) XCTAssert(observability.diagnostics.isEmpty, "\(observability.diagnostics)") XCTAssert(packageGraph.packages.count == 1, "\(packageGraph.packages)") // Find the build tool plugin. let buildToolPlugin = try XCTUnwrap(packageGraph.packages[0].targets.first{ $0.type == .plugin }) XCTAssertEqual(buildToolPlugin.name, "MyPlugin") let pluginCacheDir = tmpPath.appending(component: "plugin-cache") let pluginScriptRunner = DefaultPluginScriptRunner(cacheDir: pluginCacheDir, toolchain: ToolchainConfiguration.default) let result = try pluginScriptRunner.compilePluginScript(sources: buildToolPlugin.sources, toolsVersion: .currentToolsVersion) // Expect a failure since our input code is intentionally broken. XCTAssert(result.compilerResult.exitStatus == .terminated(code: 1), "\(result.compilerResult.exitStatus)") XCTAssert(result.compiledExecutable == .none, "\(result.compiledExecutable?.pathString ?? "-")") XCTAssert(result.diagnosticsFile.suffix == ".dia", "\(result.diagnosticsFile.pathString)") } } }
0
// // CircularCarouselDatasource.swift // CircularCarousel Demo // // Created by Piotr Suwara on 24/12/18. // Copyright © 2018 Piotr Suwara. All rights reserved. // import Foundation import UIKit public protocol CircularCarouselDataSource { func numberOfItems(inCarousel carousel: CircularCarousel) -> Int func carousel(_: CircularCarousel, viewForItemAt: IndexPath, reuseView: UIView?) -> UIView func startingItemIndex(inCarousel carousel: CircularCarousel) -> Int } public extension CircularCarouselDataSource { func startingItemIndex(inCarousel carousel: CircularCarousel) -> Int { return 0 } }
0
// // PhotoModel.swift // Accented // // Photo view model // // Created by You, Tiangong on 4/22/16. // Copyright © 2016 Tiangong You. All rights reserved. // import UIKit import SwiftyJSON class PhotoModel: ModelBase { private var dateFormatter = DateFormatter() var photoId : String! var imageUrls = [ImageSize : String!]() var width : CGFloat! var height: CGFloat! var title : String! var desc : String? var creationDate : Date? var lens : String? var camera : String? var aperture : String? var longitude : Double? var latitude : Double? var tags = [String]() var user : UserModel! var commentsCount : Int? var voted : Bool! var voteCount : Int? var rating : Float? var viewCount : Int? override init() { super.init() } init(json:JSON) { super.init() photoId = String(json["id"].int!) modelId = photoId // Image urls for (_, imageJson):(String, JSON) in json["images"] { guard imageJson["https_url"].string != nil else { continue } // Parse size metadta let imageSizeString = String(imageJson["size"].intValue) if let size = ImageSize(rawValue: imageSizeString) { imageUrls[size] = imageJson["https_url"].stringValue } } // Original width and height width = CGFloat(json["width"].intValue) height = CGFloat(json["height"].intValue) // Title title = json["name"].stringValue // Description desc = json["description"].string // Dates dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZZ" let createdAt = json["created_at"].string! creationDate = dateFormatter.date(from: createdAt) // EXIF camera = json["camera"].string lens = json["lens"].string aperture = json["aperture"].string // Geolocation longitude = json["longitude"].double latitude = json["latitude"].double // User user = UserModel(json: json["user"]) StorageService.sharedInstance.putUserToCache(user) // Tags for (_, tagJSON):(String, JSON) in json["tags"] { tags.append(tagJSON.string!) } // Like status voted = json["voted"].boolValue voteCount = json["votes_count"].int rating = json["rating"].float viewCount = json["times_viewed"].int } override func copy(with zone: NSZone? = nil) -> Any { let clone = PhotoModel() clone.modelId = self.modelId clone.photoId = self.photoId clone.imageUrls = self.imageUrls clone.width = self.width clone.height = self.height clone.title = self.title clone.desc = self.desc clone.creationDate = self.creationDate clone.camera = self.camera clone.lens = self.lens clone.aperture = self.aperture clone.longitude = self.longitude clone.latitude = self.latitude clone.user = self.user.copy() as! UserModel clone.tags = self.tags clone.voted = self.voted clone.voteCount = self.voteCount clone.rating = self.rating clone.viewCount = self.viewCount return clone } }
0
// // CMUiSettings.swift // CercaliaSDK // // Created by David Comas on 30/5/17. // // import Foundation import UIKit /** Map UISettings. ### Usage example: ### ```` // zoom controls enable let mapController: CMMapController = ... mapController.settings.zoomControls = true ```` */ public class CMUISettings : NSObject { private static let MARGIN: CGFloat = 16 private static let MARGIN_ZOOM_COMPONENTS: CGFloat = 5 private static let BUTTON_SIZE : CGFloat = 48 //Icons private let ICON_LOCATION : String = "gps" private let ICON_ZOOM_IN : String = "plus" private let ICON_ZOOM_OUT : String = "less" private let ICON_COMPASS : String = "north" // private private var map_: CMMapController? // map controller internal var map: CMMapController? { get { return map_ } set(value) { map_ = value self.updateUI() } } /// MyLocation Button private var myLocationUIButton: UIButton? /// zoomControlZoomIn Button private var zoomControlZoomInUIButton: UIButton? /// zoomControlZoomOut Button private var zoomControlZoomOutUIButton: UIButton? /// Compass Button private var compassUIButton: UIButton? // attr public private var compassButton_: Bool = false /// Enable compass Button public var compassButton: Bool { get { return compassButton_ } set(value) { compassButton_ = value self.updateUI() } } private var myLocationButton_: Bool = false /// Enable MyLocation Button public var myLocationButton: Bool { get { return myLocationButton_ } set(value) { myLocationButton_ = value self.updateUI() } } private var zoomControls_: Bool = false /// Enable ZoomControls public var zoomControls: Bool { get { return zoomControls_ } set(value) { zoomControls_ = value self.updateUI() } } internal override init(){ super.init() } internal init(map: CMMapController, myLocationUIButton: UIButton, zoomControlZoomInUIButton: UIButton, zoomControlZoomOutUIButton: UIButton, compassUIButton: UIButton) { super.init() self.map = map self.myLocationUIButton = myLocationUIButton self.zoomControlZoomInUIButton = zoomControlZoomInUIButton self.zoomControlZoomOutUIButton = zoomControlZoomOutUIButton self.compassUIButton = compassUIButton self.updateUI() } internal init(map: CMMapController) { super.init() self.map = map self.updateUI() } //MARK: UI Fires methods @objc func myLocationUIButtonClick() { if let location = self.map?.myLocation { _ = self.map?.animateCamera(cameraUpdate: CMCameraUpdateFactory.new(latLng: location)) } } @objc func zoomControlZoomInUIButtonClick() { _ = self.map?.animateCamera(cameraUpdate: CMCameraUpdateFactory.zoomIn()) } @objc func zoomControlZoomOutUIButtonClick() { _ = self.map?.animateCamera(cameraUpdate: CMCameraUpdateFactory.zoomOut()) } @objc func compassUIButtonClick() { self.rotate(radians: 0) _ = self.map?.animateCamera(cameraUpdate: CMCameraUpdateFactory.rotation(0)) } //MARK: private methods /// Update/Create buttons private func updateUI(){ // Actualitzem els controls del mapa if self.map != nil && self.map!.mapView.isCreated && self.map?.mapView.map?.view.frame.width != nil { let originX: CGFloat = self.map!.mapView.map!.view.frame.width - CMUISettings.MARGIN - CMUISettings.BUTTON_SIZE var originY = CMUISettings.MARGIN //Actualitzem el Botó self.myLocationUIButton = self.updateUIButton(self.myLocationUIButton, image: CMUtils.image(CMMarker.self, resource: ICON_LOCATION)!, enable: self.myLocationButton, action: #selector(CMUISettings.myLocationUIButtonClick), originX: originX, originY: originY) //Incrementem el origenY originY += self.myLocationButton && self.myLocationUIButton != nil ? self.myLocationUIButton!.frame.height + CMUISettings.MARGIN : 0 //Actualitzem el Botó self.zoomControlZoomInUIButton = self.updateUIButton(self.zoomControlZoomInUIButton, image: CMUtils.image(CMMarker.self, resource: ICON_ZOOM_IN)!, enable: self.zoomControls, action: #selector(CMUISettings.zoomControlZoomInUIButtonClick), originX: originX, originY: originY) //Incrementem el origenY originY += self.zoomControls && self.zoomControlZoomInUIButton != nil ? self.zoomControlZoomInUIButton!.frame.height + CMUISettings.MARGIN_ZOOM_COMPONENTS : 0 //Actualitzem el Botó self.zoomControlZoomOutUIButton = self.updateUIButton(self.zoomControlZoomOutUIButton, image: CMUtils.image(CMMarker.self, resource: ICON_ZOOM_OUT)!, enable: self.zoomControls, action: #selector(CMUISettings.zoomControlZoomOutUIButtonClick), originX: originX, originY: originY) //Incrementem el origenY originY += self.zoomControls && self.zoomControlZoomOutUIButton != nil ? self.zoomControlZoomOutUIButton!.frame.height + CMUISettings.MARGIN : 0 //Actualitzem el Botó self.compassUIButton = self.updateUIButton(self.compassUIButton, image: CMUtils.image(CMMarker.self, resource: ICON_COMPASS)!, enable: self.compassButton, action: #selector(CMUISettings.compassUIButtonClick), originX: originX, originY: originY) if let rounderedButton = self.compassUIButton as? CMUISettingsButton { rounderedButton.rounded = true } } } /// Create/Update Button private func updateUIButton(_ button: UIButton?, image: UIImage, enable: Bool, action: Selector, originX: CGFloat, originY: CGFloat ) -> UIButton? { var button: UIButton? = button //Actualitzem l'estat de UIBUtton if enable && button == nil { button = CMUISettingsButton(frame: CGRect(x: originX, y: originY, width: CMUISettings.BUTTON_SIZE, height: CMUISettings.BUTTON_SIZE), image: image) button?.addTarget(self, action: action, for: .touchUpInside) self.map?.mapView.addSubview(button!) }else if enable { button?.frame = CGRect(x: originX, y: originY, width: CMUISettings.BUTTON_SIZE, height: CMUISettings.BUTTON_SIZE) button?.isHidden = false }else { button?.isHidden = true } return button } /** * called when map rotated. */ internal func onRotated(){ let radiantsRotationMap = self.map!.getCameraPosition().rotation animateRotate(radians: CGFloat(radiantsRotationMap)); } /** * Rotate animated compass-image. * * @param degrees map rotation in degrees */ private func animateRotate(radians: CGFloat){ self.compassUIButton?.transform = CGAffineTransform(rotationAngle: radians) } /** * Rotate compass-image. * * @param degrees map rotation in degrees */ private func rotate(radians: CGFloat){ self.compassUIButton?.transform = CGAffineTransform(rotationAngle: radians) } }
0
// // ReviewOrderHostingController.swift // Project03 // // Created by Lam Nguyen on 5/29/21. // import UIKit import SwiftUI class ReviewOrderHostingController: UIHostingController<ReviewOrderScrollView> { required init?(coder aDecoder: NSCoder){ super.init(coder: aDecoder, rootView: ReviewOrderScrollView()) NotificationCenter.default.addObserver(self, selector: #selector(reviewOrderDidUpdate), name: .shoppingCartDidUpdate, object: nil) } override func viewDidLoad() { super.viewDidLoad() } @objc func reviewOrderDidUpdate(){ rootView = ReviewOrderScrollView() } }
0
import Foundation import Vapor import FluentMySQL import Authentication final class Token: Codable { var id: UUID? var token: String var userID: User.ID init(token: String, userID: User.ID) { self.token = token self.userID = userID } } extension Token: MySQLUUIDModel {} extension Token: Migration { static func prepare(on connection: MySQLConnection) -> Future<Void> { return Database.create(self, on: connection) { builder in try addProperties(to: builder) builder.reference(from: \.userID, to: \User.id) } } } extension Token: Content {} extension Token { static func generate(for user: User) throws -> Token { // TODO: invalidate or delete prior tokens for user let random = try CryptoRandom().generateData(count: 16) return try Token( token: random.base64EncodedString(), userID: user.requireID()) } } extension Token: Authentication.Token { typealias UserType = User static let userIDKey: UserIDKey = \Token.userID } extension Token: BearerAuthenticatable { static let tokenKey: TokenKey = \Token.token }
0
// // JuiceUITests.swift // JuiceUI // // Created by Matthew Wyskiel on 10/2/19. import XCTest @testable import JuiceUI final class JuiceUITests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. XCTAssertEqual(true, true) } static var allTests = [ ("testExample", testExample), ] }
0
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse protocol A struct S<h:String var e{ struct S<T where A:A{protocol a
0
// // WheelyTests.swift // WheelyTests // // Created by Andrey Filonov on 19/03/2019. // Copyright © 2019 Andrey Filonov. All rights reserved. // import XCTest class WheelyTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
0
import Foundation import XCTest @testable import GRDB class FetchableRecordDecodableTests: GRDBTestCase { } // MARK: - FetchableRecord conformance derived from Decodable extension FetchableRecordDecodableTests { func testTrivialDecodable() { struct Struct : FetchableRecord, Decodable { let value: String } do { let s = Struct(row: ["value": "foo"]) XCTAssertEqual(s.value, "foo") } } func testCustomDecodable() { struct Struct : FetchableRecord, Decodable { let value: String private enum CodingKeys : String, CodingKey { case value = "someColumn" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) value = try container.decode(String.self, forKey: .value) } } do { let s = Struct(row: ["someColumn": "foo"]) XCTAssertEqual(s.value, "foo") } } func testCustomFetchableRecord() { struct Struct : FetchableRecord, Decodable { let value: String init(row: Row) { value = (row["value"] as String) + " (FetchableRecord)" } } do { let s = Struct(row: ["value": "foo"]) XCTAssertEqual(s.value, "foo (FetchableRecord)") } } } // MARK: - Different kinds of single-value properties extension FetchableRecordDecodableTests { func testTrivialProperty() { struct Struct : FetchableRecord, Decodable { let int64: Int64 let optionalInt64: Int64? } do { // No null values let s = Struct(row: ["int64": 1, "optionalInt64": 2]) XCTAssertEqual(s.int64, 1) XCTAssertEqual(s.optionalInt64, 2) } do { // Null values let s = Struct(row: ["int64": 2, "optionalInt64": nil]) XCTAssertEqual(s.int64, 2) XCTAssertNil(s.optionalInt64) } do { // Missing and extra values let s = Struct(row: ["int64": 3, "ignored": "?"]) XCTAssertEqual(s.int64, 3) XCTAssertNil(s.optionalInt64) } } func testTrivialSingleValueDecodableProperty() { struct Value : Decodable { let string: String init(from decoder: Decoder) throws { string = try decoder.singleValueContainer().decode(String.self) } } struct Struct : FetchableRecord, Decodable { let value: Value let optionalValue: Value? } do { // No null values let s = Struct(row: ["value": "foo", "optionalValue": "bar"]) XCTAssertEqual(s.value.string, "foo") XCTAssertEqual(s.optionalValue!.string, "bar") } do { // Null values let s = Struct(row: ["value": "foo", "optionalValue": nil]) XCTAssertEqual(s.value.string, "foo") XCTAssertNil(s.optionalValue) } do { // Missing and extra values let s = Struct(row: ["value": "foo", "ignored": "?"]) XCTAssertEqual(s.value.string, "foo") XCTAssertNil(s.optionalValue) } } func testNonTrivialSingleValueDecodableProperty() { struct NestedValue : Decodable { let string: String init(from decoder: Decoder) throws { string = try decoder.singleValueContainer().decode(String.self) } } struct Value : Decodable { let nestedValue: NestedValue init(from decoder: Decoder) throws { nestedValue = try decoder.singleValueContainer().decode(NestedValue.self) } } struct Struct : FetchableRecord, Decodable { let value: Value let optionalValue: Value? } do { // No null values let s = Struct(row: ["value": "foo", "optionalValue": "bar"]) XCTAssertEqual(s.value.nestedValue.string, "foo") XCTAssertEqual(s.optionalValue!.nestedValue.string, "bar") } do { // Null values let s = Struct(row: ["value": "foo", "optionalValue": nil]) XCTAssertEqual(s.value.nestedValue.string, "foo") XCTAssertNil(s.optionalValue) } do { // Missing and extra values let s = Struct(row: ["value": "foo", "ignored": "?"]) XCTAssertEqual(s.value.nestedValue.string, "foo") XCTAssertNil(s.optionalValue) } } func testDecodableRawRepresentableProperty() { // This test is somewhat redundant with testSingleValueDecodableProperty, // since a RawRepresentable enum is a "single-value" Decodable. // // But with an explicit test for enums, we are sure that enums, widely // used, are supported. enum Value : String, Decodable { case foo, bar } struct Struct : FetchableRecord, Decodable { let value: Value let optionalValue: Value? } do { // No null values let s = Struct(row: ["value": "foo", "optionalValue": "bar"]) XCTAssertEqual(s.value, .foo) XCTAssertEqual(s.optionalValue!, .bar) } do { // Null values let s = Struct(row: ["value": "foo", "optionalValue": nil]) XCTAssertEqual(s.value, .foo) XCTAssertNil(s.optionalValue) } do { // Missing and extra values let s = Struct(row: ["value": "foo", "ignored": "?"]) XCTAssertEqual(s.value, .foo) XCTAssertNil(s.optionalValue) } } func testDatabaseValueConvertibleProperty() { // This test makes sure that Date, for example, can be read from a String. // // Without this preference for fromDatabaseValue(_:) over init(from:Decoder), // Date would only decode from doubles. struct Value : Decodable, DatabaseValueConvertible { let string: String init(string: String) { self.string = string } init(from decoder: Decoder) throws { string = try decoder.singleValueContainer().decode(String.self) + " (Decodable)" } // DatabaseValueConvertible adoption var databaseValue: DatabaseValue { fatalError("irrelevant") } static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? { if let string = String.fromDatabaseValue(databaseValue) { return Value(string: string + " (DatabaseValueConvertible)") } else { return nil } } } struct Struct : FetchableRecord, Decodable { let value: Value let optionalValue: Value? } do { // No null values let s = Struct(row: ["value": "foo", "optionalValue": "bar"]) XCTAssertEqual(s.value.string, "foo (DatabaseValueConvertible)") XCTAssertEqual(s.optionalValue!.string, "bar (DatabaseValueConvertible)") } do { // Null values let s = Struct(row: ["value": "foo", "optionalValue": nil]) XCTAssertEqual(s.value.string, "foo (DatabaseValueConvertible)") XCTAssertNil(s.optionalValue) } do { // Missing and extra values let s = Struct(row: ["value": "foo", "ignored": "?"]) XCTAssertEqual(s.value.string, "foo (DatabaseValueConvertible)") XCTAssertNil(s.optionalValue) } } } // MARK: - Foundation Codable Types extension FetchableRecordDecodableTests { func testStructWithDate() { struct StructWithDate : FetchableRecord, Decodable { let date: Date } let date = Date() let value = StructWithDate(row: ["date": date]) XCTAssert(abs(value.date.timeIntervalSince(date)) < 0.001) } func testStructWithURL() { struct StructWithURL : FetchableRecord, Decodable { let url: URL } let url = URL(string: "https://github.com") let value = StructWithURL(row: ["url": url]) XCTAssertEqual(value.url, url) } func testStructWithUUID() { struct StructWithUUID : FetchableRecord, Decodable { let uuid: UUID } let uuid = UUID() let value = StructWithUUID(row: ["uuid": uuid]) XCTAssertEqual(value.uuid, uuid) } } // MARK: - Custom nested Decodable types - nested saved as JSON extension FetchableRecordDecodableTests { func testOptionalNestedStruct() throws { struct NestedStruct : Codable { let firstName: String? let lastName: String? } struct StructWithNestedType : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let nested: NestedStruct? } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("nested", .text) } let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: nested) try value.insert(db) let parentModel = try StructWithNestedType.fetchAll(db) guard let nestedModel = parentModel.first?.nested else { XCTFail() return } // Check the nested model contains the expected values of first and last name XCTAssertEqual(nestedModel.firstName, "Bob") XCTAssertEqual(nestedModel.lastName, "Dylan") } } func testOptionalNestedStructNil() throws { struct NestedStruct : Codable { let firstName: String? let lastName: String? } struct StructWithNestedType : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let nested: NestedStruct? } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("nested", .text) } let value = StructWithNestedType(nested: nil) try value.insert(db) let parentModel = try StructWithNestedType.fetchAll(db) XCTAssertNil(parentModel.first?.nested) } } func testOptionalNestedArrayStruct() throws { struct NestedStruct : Codable { let firstName: String? let lastName: String? } struct StructWithNestedType : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let nested: [NestedStruct]? } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("nested", .text) } let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: [nested, nested]) try value.insert(db) let parentModel = try StructWithNestedType.fetchAll(db) guard let arrayOfNestedModel = parentModel.first?.nested, let firstNestedModelInArray = arrayOfNestedModel.first else { XCTFail() return } // Check there are two models in array XCTAssertTrue(arrayOfNestedModel.count == 2) // Check the nested model contains the expected values of first and last name XCTAssertEqual(firstNestedModelInArray.firstName, "Bob") XCTAssertEqual(firstNestedModelInArray.lastName, "Dylan") } } func testOptionalNestedArrayStructNil() throws { struct NestedStruct: Codable { let firstName: String? let lastName: String? } struct StructWithNestedType : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let nested: [NestedStruct]? } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("nested", .text) } let value = StructWithNestedType(nested: nil) try value.insert(db) let parentModel = try StructWithNestedType.fetchAll(db) XCTAssertNil(parentModel.first?.nested) } } func testNonOptionalNestedStruct() throws { struct NestedStruct: Codable { let firstName: String? let lastName: String? } struct StructWithNestedType : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let nested: NestedStruct } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("nested", .text) } let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") let value = StructWithNestedType(nested: nested) try value.insert(db) let parentModel = try StructWithNestedType.fetchAll(db) guard let nestedModel = parentModel.first?.nested else { XCTFail() return } // Check the nested model contains the expected values of first and last name XCTAssertEqual(nestedModel.firstName, "Bob") XCTAssertEqual(nestedModel.lastName, "Dylan") } } func testNonOptionalNestedArrayStruct() throws { struct NestedStruct : Codable { let firstName: String? let lastName: String? } struct StructWithNestedType : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let nested: [NestedStruct] } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("nested", .text) } } try dbQueue.inTransaction { db in let value = StructWithNestedType(nested: [ NestedStruct(firstName: "Bob", lastName: "Dylan"), NestedStruct(firstName: "Bob", lastName: "Dylan")]) try value.insert(db) let parentModel = try StructWithNestedType.fetchOne(db) guard let nested = parentModel?.nested else { XCTFail() return .rollback } // Check there are two models in array XCTAssertEqual(nested.count, 2) // Check the nested model contains the expected values of first and last name XCTAssertEqual(nested[0].firstName, "Bob") XCTAssertEqual(nested[0].lastName, "Dylan") return .rollback } try dbQueue.inTransaction { db in let value = StructWithNestedType(nested: []) try value.insert(db) let parentModel = try StructWithNestedType.fetchOne(db) guard let nested = parentModel?.nested else { XCTFail() return .rollback } XCTAssertTrue(nested.isEmpty) return .rollback } } func testCodableExampleCode() throws { struct Player: PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let name: String let score: Int let scores: [Int] let lastMedal: PlayerMedal let medals: [PlayerMedal] let timeline: [String: PlayerMedal] } // A simple Codable that will be nested in a parent Codable struct PlayerMedal : Codable { let name: String? let type: String? } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("name", .text) t.column("score", .integer) t.column("scores", .integer) t.column("lastMedal", .text) t.column("medals", .text) t.column("timeline", .text) } let medal1 = PlayerMedal(name: "First", type: "Gold") let medal2 = PlayerMedal(name: "Second", type: "Silver") let timeline = ["Local Contest": medal1, "National Contest": medal2] let value = Player(name: "PlayerName", score: 10, scores: [1,2,3,4,5], lastMedal: medal1, medals: [medal1, medal2], timeline: timeline) try value.insert(db) let parentModel = try Player.fetchAll(db) guard let first = parentModel.first, let firstNestedModelInArray = first.medals.first, let secondNestedModelInArray = first.medals.last else { XCTFail() return } // Check there are two models in array XCTAssertTrue(first.medals.count == 2) // Check the nested model contains the expected values of first and last name XCTAssertEqual(firstNestedModelInArray.name, "First") XCTAssertEqual(secondNestedModelInArray.name, "Second") XCTAssertEqual(first.name, "PlayerName") XCTAssertEqual(first.score, 10) XCTAssertEqual(first.scores, [1,2,3,4,5]) XCTAssertEqual(first.lastMedal.name, medal1.name) XCTAssertEqual(first.timeline["Local Contest"]?.name, medal1.name) XCTAssertEqual(first.timeline["National Contest"]?.name, medal2.name) } } // MARK: - JSON data in Detached Rows func testDetachedRows() throws { struct NestedStruct : PersistableRecord, FetchableRecord, Codable { let firstName: String? let lastName: String? } struct StructWithNestedType : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let nested: NestedStruct } let row: Row = ["nested": """ {"firstName":"Bob","lastName":"Dylan"} """] let model = StructWithNestedType(row: row) XCTAssertEqual(model.nested.firstName, "Bob") XCTAssertEqual(model.nested.lastName, "Dylan") } func testArrayOfDetachedRowsAsData() throws { struct TestStruct : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let name: String } let jsonAsString = "{\"firstName\":\"Bob\",\"lastName\":\"Marley\"}" let jsonAsData = jsonAsString.data(using: .utf8) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("name", .text) } let model = TestStruct(name: jsonAsString) try model.insert(db) } try dbQueue.read { db in // ... with an array of detached rows: let array = try Row.fetchAll(db, sql: "SELECT * FROM t1") for row in array { let data1: Data? = row["name"] XCTAssertEqual(jsonAsData, data1) let data = row.dataNoCopy(named: "name") XCTAssertEqual(jsonAsData, data) } } } func testArrayOfDetachedRowsAsString() throws { struct TestStruct : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let name: String } let jsonAsString = "{\"firstName\":\"Bob\",\"lastName\":\"Marley\"}" let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("name", .text) } let model = TestStruct(name: jsonAsString) try model.insert(db) } try dbQueue.read { db in // ... with an array of detached rows: let array = try Row.fetchAll(db, sql: "SELECT * FROM t1") for row in array { let string: String? = row["name"] XCTAssertEqual(jsonAsString, string) } } } func testCursorRowsAsData() throws { struct TestStruct : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let name: String } let jsonAsString = "{\"firstName\":\"Bob\",\"lastName\":\"Marley\"}" let jsonAsData = jsonAsString.data(using: .utf8) let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("name", .text) } let model = TestStruct(name: jsonAsString) try model.insert(db) } try dbQueue.read { db in // Compare cursor of low-level rows: let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM t1") while let row = try cursor.next() { let data1: Data? = row["name"] XCTAssertEqual(jsonAsData, data1) let data = row.dataNoCopy(named: "name") XCTAssertEqual(jsonAsData, data) } } } func testCursorRowsAsString() throws { struct TestStruct : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" let name: String } let jsonAsString = "{\"firstName\":\"Bob\",\"lastName\":\"Marley\"}" let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "t1") { t in t.column("name", .text) } let model = TestStruct(name: jsonAsString) try model.insert(db) } try dbQueue.read { db in // Compare cursor of low-level rows: let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM t1") while let row = try cursor.next() { let string: String? = row["name"] XCTAssertEqual(jsonAsString, string) } } } func testJSONDataEncodingStrategy() throws { struct Record: FetchableRecord, Decodable { let data: Data let optionalData: Data? let datas: [Data] let optionalDatas: [Data?] } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let data = "foo".data(using: .utf8)! let record = try Record.fetchOne(db, sql: "SELECT ? AS data, ? AS optionalData, ? AS datas, ? AS optionalDatas", arguments: [ data, data, "[\"Zm9v\"]", "[null, \"Zm9v\"]" ])! XCTAssertEqual(record.data, data) XCTAssertEqual(record.optionalData!, data) XCTAssertEqual(record.datas.count, 1) XCTAssertEqual(record.datas[0], data) XCTAssertEqual(record.optionalDatas.count, 2) XCTAssertNil(record.optionalDatas[0]) XCTAssertEqual(record.optionalDatas[1]!, data) } } func testJSONDateEncodingStrategy() throws { struct Record: FetchableRecord, Decodable { let date: Date let optionalDate: Date? let dates: [Date] let optionalDates: [Date?] } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let record = try Record.fetchOne(db, sql: "SELECT ? AS date, ? AS optionalDate, ? AS dates, ? AS optionalDates", arguments: [ "1970-01-01 00:02:08.000", "1970-01-01 00:02:08.000", "[128000]", "[null,128000]" ])! XCTAssertEqual(record.date.timeIntervalSince1970, 128) XCTAssertEqual(record.optionalDate!.timeIntervalSince1970, 128) XCTAssertEqual(record.dates.count, 1) XCTAssertEqual(record.dates[0].timeIntervalSince1970, 128) XCTAssertEqual(record.optionalDates.count, 2) XCTAssertNil(record.optionalDates[0]) XCTAssertEqual(record.optionalDates[1]!.timeIntervalSince1970, 128) } } } // MARK: - User Infos & Coding Keys private let testKeyRoot = CodingUserInfoKey(rawValue: "test1")! private let testKeyNested = CodingUserInfoKey(rawValue: "test2")! extension FetchableRecordDecodableTests { struct NestedKeyed: Decodable { var name: String var key: String? var context: String? enum CodingKeys: String, CodingKey { case name } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decode(String.self, forKey: .name) key = decoder.codingPath.last?.stringValue context = decoder.userInfo[testKeyNested] as? String } } struct NestedSingle: Decodable { var name: String var key: String? var context: String? init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() name = try container.decode(String.self) key = decoder.codingPath.last?.stringValue context = decoder.userInfo[testKeyNested] as? String } } struct NestedUnkeyed: Decodable { var name: String var key: String? var context: String? init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() name = try container.decode(String.self) key = decoder.codingPath.last?.stringValue context = decoder.userInfo[testKeyNested] as? String } } struct Record: Decodable, FetchableRecord { var nestedKeyed: NestedKeyed var nestedSingle: NestedSingle var nestedUnkeyed: NestedUnkeyed var key: String? var context: String? enum CodingKeys: String, CodingKey { case nestedKeyed, nestedSingle, nestedUnkeyed } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) nestedKeyed = try container.decode(NestedKeyed.self, forKey: .nestedKeyed) nestedSingle = try container.decode(NestedSingle.self, forKey: .nestedSingle) nestedUnkeyed = try container.decode(NestedUnkeyed.self, forKey: .nestedUnkeyed) key = decoder.codingPath.last?.stringValue context = decoder.userInfo[testKeyRoot] as? String } } class CustomizedRecord: Decodable, FetchableRecord { var nestedKeyed: NestedKeyed var nestedSingle: NestedSingle var nestedUnkeyed: NestedUnkeyed var key: String? var context: String? enum CodingKeys: String, CodingKey { case nestedKeyed, nestedSingle, nestedUnkeyed } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) nestedKeyed = try container.decode(NestedKeyed.self, forKey: .nestedKeyed) nestedSingle = try container.decode(NestedSingle.self, forKey: .nestedSingle) nestedUnkeyed = try container.decode(NestedUnkeyed.self, forKey: .nestedUnkeyed) key = decoder.codingPath.last?.stringValue context = decoder.userInfo[testKeyRoot] as? String } static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [ testKeyRoot: "GRDB root", testKeyNested: "GRDB column or scope"] static func databaseJSONDecoder(for column: String) -> JSONDecoder { let decoder = JSONDecoder() decoder.userInfo = [ testKeyRoot: "JSON root", testKeyNested: "JSON column: \(column)"] return decoder } } // Used as a reference func testFoundationBehavior() throws { let json = """ { "nestedKeyed": { "name": "foo" }, "nestedSingle": "bar", "nestedUnkeyed": ["baz"] } """.data(using: .utf8)! do { let decoder = JSONDecoder() let record = try decoder.decode(Record.self, from: json) XCTAssertNil(record.key) XCTAssertNil(record.context) XCTAssertEqual(record.nestedKeyed.name, "foo") XCTAssertEqual(record.nestedKeyed.key, "nestedKeyed") XCTAssertNil(record.nestedKeyed.context) XCTAssertEqual(record.nestedSingle.name, "bar") XCTAssertEqual(record.nestedSingle.key, "nestedSingle") XCTAssertNil(record.nestedSingle.context) XCTAssertEqual(record.nestedUnkeyed.name, "baz") XCTAssertEqual(record.nestedUnkeyed.key, "nestedUnkeyed") XCTAssertNil(record.nestedUnkeyed.context) } do { let decoder = JSONDecoder() decoder.userInfo = [testKeyRoot: "root", testKeyNested: "nested"] let record = try decoder.decode(Record.self, from: json) XCTAssertNil(record.key) XCTAssertEqual(record.context, "root") XCTAssertEqual(record.nestedKeyed.name, "foo") XCTAssertEqual(record.nestedKeyed.key, "nestedKeyed") XCTAssertEqual(record.nestedKeyed.context, "nested") XCTAssertEqual(record.nestedSingle.name, "bar") XCTAssertEqual(record.nestedSingle.key, "nestedSingle") XCTAssertEqual(record.nestedSingle.context, "nested") XCTAssertEqual(record.nestedUnkeyed.name, "baz") XCTAssertEqual(record.nestedUnkeyed.key, "nestedUnkeyed") XCTAssertEqual(record.nestedUnkeyed.context, "nested") } } func testRecord1() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in func test(_ record: Record) { XCTAssertNil(record.key) XCTAssertNil(record.context) // scope XCTAssertEqual(record.nestedKeyed.name, "foo") XCTAssertEqual(record.nestedKeyed.key, "nestedKeyed") XCTAssertNil(record.nestedKeyed.context) // column XCTAssertEqual(record.nestedSingle.name, "bar") XCTAssertEqual(record.nestedSingle.key, "nestedSingle") XCTAssertNil(record.nestedSingle.context) // JSON column XCTAssertEqual(record.nestedUnkeyed.name, "baz") XCTAssertNil(record.nestedUnkeyed.key) XCTAssertNil(record.nestedUnkeyed.context) } let adapter = SuffixRowAdapter(fromIndex: 1).addingScopes(["nestedKeyed": RangeRowAdapter(0..<1)]) let request = SQLRequest<Void>( sql: "SELECT ? AS name, ? AS nestedSingle, ? AS nestedUnkeyed", arguments: ["foo", "bar", "[\"baz\"]"], adapter: adapter) let record = try Record.fetchOne(db, request)! test(record) let row = try Row.fetchOne(db, request)! test(Record(row: row)) } } func testRecord2() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in func test(_ record: Record) { XCTAssertNil(record.key) XCTAssertNil(record.context) // JSON column XCTAssertEqual(record.nestedKeyed.name, "foo") XCTAssertNil(record.nestedKeyed.key) XCTAssertNil(record.nestedKeyed.context) // column XCTAssertEqual(record.nestedSingle.name, "bar") XCTAssertEqual(record.nestedSingle.key, "nestedSingle") XCTAssertNil(record.nestedSingle.context) // JSON column XCTAssertEqual(record.nestedUnkeyed.name, "baz") XCTAssertNil(record.nestedUnkeyed.key) XCTAssertNil(record.nestedUnkeyed.context) } let request = SQLRequest<Void>( sql: "SELECT ? AS nestedKeyed, ? AS nestedSingle, ? AS nestedUnkeyed", arguments: ["{\"name\":\"foo\"}", "bar", "[\"baz\"]"]) let record = try Record.fetchOne(db, request)! test(record) let row = try Row.fetchOne(db, request)! test(Record(row: row)) } } func testCustomizedRecord1() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in func test(_ record: CustomizedRecord) { XCTAssertNil(record.key) XCTAssertEqual(record.context, "GRDB root") // scope XCTAssertEqual(record.nestedKeyed.name, "foo") XCTAssertEqual(record.nestedKeyed.key, "nestedKeyed") XCTAssertEqual(record.nestedKeyed.context, "GRDB column or scope") // column XCTAssertEqual(record.nestedSingle.name, "bar") XCTAssertEqual(record.nestedSingle.key, "nestedSingle") XCTAssertEqual(record.nestedSingle.context, "GRDB column or scope") // JSON column XCTAssertEqual(record.nestedUnkeyed.name, "baz") XCTAssertNil(record.nestedUnkeyed.key) XCTAssertEqual(record.nestedUnkeyed.context, "JSON column: nestedUnkeyed") } let adapter = SuffixRowAdapter(fromIndex: 1).addingScopes(["nestedKeyed": RangeRowAdapter(0..<1)]) let request = SQLRequest<Void>( sql: "SELECT ? AS name, ? AS nestedSingle, ? AS nestedUnkeyed", arguments: ["foo", "bar", "[\"baz\"]"], adapter: adapter) let record = try CustomizedRecord.fetchOne(db, request)! test(record) let row = try Row.fetchOne(db, request)! test(CustomizedRecord(row: row)) } } func testCustomizedRecord2() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in func test(_ record: CustomizedRecord) { XCTAssertNil(record.key) XCTAssertEqual(record.context, "GRDB root") // JSON column XCTAssertEqual(record.nestedKeyed.name, "foo") XCTAssertNil(record.nestedKeyed.key) XCTAssertEqual(record.nestedKeyed.context, "JSON column: nestedKeyed") // column XCTAssertEqual(record.nestedSingle.name, "bar") XCTAssertEqual(record.nestedSingle.key, "nestedSingle") XCTAssertEqual(record.nestedSingle.context, "GRDB column or scope") // JSON column XCTAssertEqual(record.nestedUnkeyed.name, "baz") XCTAssertNil(record.nestedUnkeyed.key) XCTAssertEqual(record.nestedUnkeyed.context, "JSON column: nestedUnkeyed") } let request = SQLRequest<Void>( sql: "SELECT ? AS nestedKeyed, ? AS nestedSingle, ? AS nestedUnkeyed", arguments: ["{\"name\":\"foo\"}", "bar", "[\"baz\"]"]) let record = try CustomizedRecord.fetchOne(db, request)! test(record) let row = try Row.fetchOne(db, request)! test(CustomizedRecord(row: row)) } } func testMissingKeys1() throws { struct A: Decodable { } struct B: Decodable { } struct C: Decodable { } struct Composed: Decodable, FetchableRecord { var a: A var b: B? var c: C? } // No error expected: // - a is succesfully decoded because it consumes the one and unique // allowed missing key // - b and c are succesfully decoded, because they are optionals, and // all optionals decode missing keys are nil. This is because GRDB // records accept rows with missing columns, and b and c may want to // decode columns. _ = try RowDecoder().decode(Composed.self, from: [:]) } // This is a regression test for https://github.com/groue/GRDB.swift/issues/664 func testMissingKeys2() throws { struct A: Decodable { } struct B: Decodable { } struct Composed: Decodable, FetchableRecord { var a: A var b: B } do { _ = try RowDecoder().decode(Composed.self, from: [:]) XCTFail("Expected error") } catch DecodingError.keyNotFound { // a or b can not be decoded because only one key is allowed to be missing } } // Regression test for https://github.com/groue/GRDB.swift/issues/836 func testRootKeyDecodingError() throws { struct Record: Decodable { } struct Composed: Decodable, FetchableRecord { var a: Record var b: Record var c: Record } try makeDatabaseQueue().read { db in do { // - a is present // - root is b and c is missing, or the opposite (two possible user intents) let row = try Row.fetchOne(db, sql: "SELECT NULL", adapter: ScopeAdapter(["a": EmptyRowAdapter()]))! _ = try RowDecoder().decode(Composed.self, from: row) XCTFail("Expected error") } catch let DecodingError.keyNotFound(key, context) { XCTAssert(["b", "c"].contains(key.stringValue)) XCTAssertEqual(context.debugDescription, "No such key: b or c") } do { // - b is present // - root is a and c is missing, or the opposite (two possible user intents) let row = try Row.fetchOne(db, sql: "SELECT NULL", adapter: ScopeAdapter(["b": EmptyRowAdapter()]))! _ = try RowDecoder().decode(Composed.self, from: row) XCTFail("Expected error") } catch let DecodingError.keyNotFound(key, context) { XCTAssert(["a", "c"].contains(key.stringValue)) XCTAssertEqual(context.debugDescription, "No such key: a or c") } do { // - c is present // - root is a and b is missing, or the opposite (two possible user intents) let row = try Row.fetchOne(db, sql: "SELECT NULL", adapter: ScopeAdapter(["c": EmptyRowAdapter()]))! _ = try RowDecoder().decode(Composed.self, from: row) XCTFail("Expected error") } catch let DecodingError.keyNotFound(key, context) { XCTAssert(["a", "b"].contains(key.stringValue)) XCTAssertEqual(context.debugDescription, "No such key: a or b") } } } }
0
// // Globals.swift // pass // // Created by Mingshen Sun on 21/1/2017. // Copyright © 2017 Bob Sun. All rights reserved. // import Foundation import UIKit public final class Globals { public static let bundleIdentifier = "me.mssun.passforios" public static let groupIdentifier = "group." + bundleIdentifier public static let passKitBundleIdentifier = bundleIdentifier + ".passKit" public static let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier)! public static let documentPath = sharedContainerURL.appendingPathComponent("Documents").path public static let libraryPath = sharedContainerURL.appendingPathComponent("Library").path public static let pgpPublicKeyPath = documentPath + "/gpg_key.pub" public static let pgpPrivateKeyPath = documentPath + "/gpg_key" public static let gitSSHPrivateKeyPath = documentPath + "/ssh_key" public static let gitSSHPrivateKeyURL = URL(fileURLWithPath: gitSSHPrivateKeyPath) public static let repositoryPath = libraryPath + "/password-store" public static let dbPath = documentPath + "/pass.sqlite" public static let iTunesFileSharingPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] public static let iTunesFileSharingPGPPublic = iTunesFileSharingPath + "/gpg_key.pub" public static let iTunesFileSharingPGPPrivate = iTunesFileSharingPath + "/gpg_key" public static let iTunesFileSharingSSHPrivate = iTunesFileSharingPath + "/ssh_key" public static let gitPassword = "gitPassword" public static let gitSSHPrivateKeyPassphrase = "gitSSHPrivateKeyPassphrase" public static let pgpKeyPassphrase = "pgpKeyPassphrase" public static let gitSignatureDefaultName = "Pass for iOS" public static let gitSignatureDefaultEmail = "user@passforios" public static let passwordDots = "••••••••••••" public static let oneTimePasswordDots = "••••••" public static let passwordFont = UIFont(name: "Courier-Bold", size: UIFont.labelFontSize - 1) // UI related public static let tableCellButtonSize = CGFloat(20.0) private init() { } } public extension Bundle { var releaseVersionNumber: String? { return infoDictionary?["CFBundleShortVersionString"] as? String } var buildVersionNumber: String? { return infoDictionary?["CFBundleVersion"] as? String } }
0
// // UIResponder+Extension.swift // Deluge // // Created by Yotam Ohayon on 02/12/2017. // Copyright © 2017 Yotam Ohayon. All rights reserved. // import Foundation import RxSwift import RxCocoa extension Reactive where Base: UIResponder { var becomeFirstResponder: Binder<Void> { return Binder(self.base) { textfield, _ in textfield.becomeFirstResponder() } } var resignFirstResponder: Binder<Void> { return Binder(self.base) { textfield, _ in textfield.resignFirstResponder() } } }
0
import SKCollectionViewDataSource import UIKit class SupplementaryViewsViewController: UIViewController { var dataSource: CollectionViewDataSource<String>? @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() let array = [["Alaska", "Alabama", "Arkansas", "American Samoa", "Arizona"], ["California", "Colorado", "Connecticut"], ["District of Columbia", "Delaware"], ["Florida"], ["Georgia", "Guam"], ["Hawaii"], ["Iowa", "Idaho", "Illinois", "Indiana"], ["Kansas", "Kentucky"], ["Louisiana"], ["Massachusetts", "Maryland", "Maine", "Michigan", "Minnesota", "Missouri", "Mississippi", "Montana"], ["North Carolina", "North Dakota", "Nebraska", "New Hampshire", "New Jersey", "New Mexico", "Nevada", "New York"], ["Ohio", "Oklahoma", "Oregon"], ["Pennsylvania", "Puerto Rico"], ["Rhode Island"], ["South Carolina", "South Dakota"], ["Tennessee", "Texas"], ["Utah"], ["Virginia", "Virgin Islands", "Vermont"], ["Washington", "Wisconsin", "West Virginia", "Wyoming"]] let textCellNib = UINib(nibName: "TextCell", bundle: Bundle.main) let cellConfiguration = CellConfiguration<String>(cell: textCellNib) { (cell, object) in guard let cell = cell as? TextCell else { return } cell.label.text = object } let headerNib = UINib(nibName: "HeaderCell", bundle: Bundle.main) let headerConfiguration = SupplementaryViewConfiguration<String>(view: headerNib, viewKind: UICollectionElementKindSectionHeader) { (view, section) in guard let view = view as? HeaderCell else { return } var firstLetter: String? = nil if let firstWord = self.dataSource?.object(IndexPath(item: 0, section: section)) { let index = firstWord.index(firstWord.startIndex, offsetBy: 1) let firstLetterSubstring = firstWord[..<index] firstLetter = String(firstLetterSubstring) } view.label.text = firstLetter } let footerNib = UINib(nibName: "FooterCell", bundle: Bundle.main) let footerConfiguration = SupplementaryViewConfiguration<String>(view: footerNib, viewKind: UICollectionElementKindSectionFooter) { (view, section) in guard let view = view as? FooterCell else { return } view.backgroundColor = .red } dataSource = CollectionViewDataSource(objects: array, cellConfiguration: cellConfiguration, supplementaryViewConfigurations: [headerConfiguration, footerConfiguration]) collectionView.dataSource = dataSource if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { layout.headerReferenceSize = CGSize(width: 100, height: 50) layout.footerReferenceSize = CGSize(width: 100, height: 4) layout.sectionHeadersPinToVisibleBounds = true } } }
0
// // ConfirmableAlert.swift // ErrorHandler // // Created by Stefan Renne on 19/07/2019. // Copyright © 2019 stefanrenne. All rights reserved. // import Foundation public struct ConfirmableAlert: ErrorAlert { let title: String let message: String? let confirmTitle: String let confirmAction: ((Error) -> Void)? public init(title: String, message: String? = nil, confirmTitle: String, confirmAction: ((Error) -> Void)? = nil) { self.title = title self.message = message self.confirmTitle = confirmTitle self.confirmAction = confirmAction } public func build(for error: Error, onCompleted: OnErrorHandled) -> AlertController { let controller = AlertController(title: title, message: message, preferredStyle: .alert) let confirmButton = AlertAction(title: confirmTitle, style: .default) { _ in self.confirmAction?(error) onCompleted?() } controller.addAction(confirmButton) return controller } }
0
// // PredictionResult.swift // predictivevision // // Created by René Winkelmeyer on 02/28/2017. // Copyright © 2016 René Winkelmeyer. All rights reserved. // import Foundation import SwiftyJSON public struct PredictionResult { public var object: String? public var probabilities: [Probability]? init?() { } init?(jsonObject: SwiftyJSON.JSON) { probabilities = [Probability]() let jsonProbabilities = jsonObject["probabilities"].array for object in jsonProbabilities! { let probability = Probability(jsonObject: object) probabilities?.append(probability!) } object = jsonObject["object"].string } }
0
// // ActiveCrittersViewModel.swift // ACHNBrowserUI // // Created by Thomas Ricouard on 01/06/2020. // Copyright © 2020 Thomas Ricouard. All rights reserved. // import Foundation import Combine import SwiftUI import Backend class ActiveCrittersViewModel: ObservableObject { enum CritterType: String, CaseIterable { case fish = "Fishes" case bugs = "Bugs" case seaCreatures = "Sea Creatures" func category() -> Backend.Category { switch self { case .fish: return .fish case .bugs: return .bugs case .seaCreatures: return .seaCreatures } } func imagePrefix() -> String { switch self { case .fish: return "Fish" case .bugs: return "Ins" case .seaCreatures: return "div" } } } struct CritterInfo { let active: [Item] let new: [Item] let leaving: [Item] let caught: [Item] let toCatchNow: [Item] let toCatchLater: [Item] } @Published var crittersInfo: [CritterType: CritterInfo] = [:] @Published var isLoading: Bool private let items: Items private let collection: UserCollection private var cancellable: AnyCancellable? init(filterOutInCollection: Bool = false, items: Items = .shared, collection: UserCollection = .shared) { self.items = items self.collection = collection self.isLoading = true cancellable = Publishers.CombineLatest(items.$categories, collection.$critters) .receive(on: DispatchQueue.main) .sink { [weak self] (items, critters) in guard let self = self else { return } for type in CritterType.allCases { var active = items[type.category()]?.filterActiveThisMonth() ?? [] var new = active.filter{ $0.isNewThisMonth() } var leaving = active.filter{ $0.leavingThisMonth() } let caught = active.filter{ critters.contains($0) } let toCatchNow = active.filter{ !caught.contains($0) && $0.isActiveAtThisHour() } let toCatchLater = active.filter{ !caught.contains($0) && !toCatchNow.contains($0) } if filterOutInCollection { new = new.filter{ !critters.contains($0) } leaving = leaving.filter{ !critters.contains($0) } active = active.filter{ !critters.contains($0) } } self.crittersInfo[type] = CritterInfo(active: active, new: new, leaving: leaving, caught: caught, toCatchNow: toCatchNow, toCatchLater: toCatchLater) self.isLoading = false } } } }
0
/** https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/ 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。   示例 1: 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5] 示例 2: 输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 输出:[1,2,3,4,8,12,11,10,9,5,6,7]   限制: 0 <= matrix.length <= 100 0 <= matrix[i].length <= 100 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class _剑指Offer29_顺时针打印矩阵 { //class Solution { public init() {} public func spiralOrder(_ matrix: [[Int]]) -> [Int] { if matrix.isEmpty { return [] } var result = [Int]() var top = 0 var bottom = matrix.count - 1 var left = 0 var right = matrix[0].count - 1 var direction = 0 while left <= right && top <= bottom { if direction == 0 { // go RIGHT for i in left...right { result.append(matrix[top][i]) } top += 1 } else if direction == 1 { // go DOWN for i in top...bottom { result.append(matrix[i][right]) } right -= 1 } else if direction == 2 { // go LEFT for i in stride(from: right, through: left, by: -1) { result.append(matrix[bottom][i]) } bottom -= 1 } else { // go UP for i in stride(from: bottom, through: top, by: -1) { result.append(matrix[i][left]) } left += 1 } direction = (direction + 1) % 4 } return result } } //let s = _剑指Offer29_顺时针打印矩阵() //let input1 = [[1,2,3],[4,5,6],[7,8,9]] //let input2 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] //let result = s.spiralOrder(input1) //print(result) // //assert(s.spiralOrder(input1) == [1,2,3,6,9,8,7,4,5]) //assert(s.spiralOrder(input2) == [1,2,3,4,8,12,11,10,9,5,6,7]) // ///// 全局打印,发布时不触发, isDebug == false时不打印 //public func print<T>(_ msg: T, // line: Int = #line) { // let prefix = "🏷_\(line)" // print(prefix, msg) //}
0
import Foundation import XCTest public protocol Disposable { func dispose() } protocol Invocable : class { func invoke(_ data: Any) } public class Event<T> { public typealias EventHandler = (T) -> () var eventHandlers = [Invocable]() public func raise(_ data: T) { for handler in self.eventHandlers { handler.invoke(data) } } public func addHandler<U: AnyObject> (target: U, handler: @escaping (U) -> EventHandler) -> Disposable { let subscription = Subscription(target: target, handler: handler, event: self) eventHandlers.append(subscription) return subscription } } class Subscription<T: AnyObject, U> : Invocable, Disposable { weak var target: T? let handler: (T) -> (U) -> () let event: Event<U> init(target: T?, handler: @escaping (T) -> (U) -> (), event: Event<U>) { self.target = target self.handler = handler self.event = event } func invoke(_ data: Any) { if let t = target { handler(t)(data as! U) } } func dispose() { event.eventHandlers = event.eventHandlers.filter { $0 as AnyObject? !== self } } } class Participant { private let mediator: Mediator var value = 0 init(_ mediator: Mediator) { self.mediator = mediator mediator.alert.addHandler( target: self, handler: { (_) -> ((AnyObject, Int)) -> () in return self.alert } ) } func alert(_ data: (AnyObject, Int)) { if (data.0 !== self) { value += data.1 } } func say(_ n: Int) { mediator.broadcast(self, n) } } class Mediator { let alert = Event<(AnyObject, Int)>() func broadcast(_ sender: AnyObject, _ n: Int) { alert.raise(sender, n) } } class UMBaseTestCase : XCTestCase {} class Evaluate: UMBaseTestCase { func simpleTest() { let mediator = Mediator() let p1 = Participant(mediator) let p2 = Participant(mediator) XCTAssertEqual(0, p1.value) XCTAssertEqual(0, p2.value) p1.say(2) XCTAssertEqual(0, p1.value) XCTAssertEqual(2, p2.value) p2.say(4) XCTAssertEqual(4, p1.value) XCTAssertEqual(2, p2.value) } } extension Evaluate { static var allTests : [(String, (Evaluate) -> () throws -> Void)] { return [ ("simpleTest", simpleTest) ] } } func main() { XCTMain([testCase(Evaluate.allTests)]) } main()
0
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck rn b(g> String enum b { func b.A? = j> (Any) { _, (2, d.c(t: [B<T>) return ") class func b<l : b(A, obj
0
// // requestParser.swift // Ribbit // // Created by Ahsan Ali on 31/03/2021. // let serverError = "Server not responding" import Foundation class RequestParser: NSObject { // MARK: - Varibales private let newJSONDecoder = JSONDecoder() // MARK: - Helpers func parseResponse(response: Any, reqType: RequestType) -> Any? { var items: Any? switch reqType { case .signUp, .login, .magic: items = parseSignup(response: response) case .countryList, .stateList, .cityList: items = parseCountries(response: response) case .updateProfile, .sign: items = parseUpdate(response: response) case .createLinkToken: items = parseLinkToken(response: response) case .setAccessToken: items = parseSetAccessToken(response: response) case .transfer: items = parseTransactions(response: response) case .deposit: items = parseDeposit(response: response) case .recipientBanks: items = parseReceipientBank(response: response) case .detachBank: items = response case .stats: items = parseStats(response: response) case .shareableLink: items = parseShareableLink(response: response) case .assets: items = response case .referelCode: items = (response as? NSDictionary)?["referral_code"] as? String ?? "" case .bars: items = parseShares(response: response) case .tradingView: items = parseTotalBalance(response: response) case .order: items = parseStringError(response: response) case .markfav, .deleteFav: items = parseFav(response: response) case .watchList, .positions: items = parseStocks(response: response) } return items } // MARK: - Rest Api's // parsng of sign up api private func parseUpdate(response: Any) -> Any? { do { let jsonData = try JSONSerialization.data(withJSONObject: response, options: JSONSerialization.WritingOptions.prettyPrinted) let model = try newJSONDecoder.decode(UpdatedUser.self, from: jsonData) USER.shared.merge(updated: model) USER.shared.updateUser() return model } catch { consoleLog("Model Not Mapped on Json Signup", error.localizedDescription) return parseResponse(response: response) } } private func parseSignup(response: Any) -> Signup? { do { let jsonData = try JSONSerialization.data(withJSONObject: response, options: JSONSerialization.WritingOptions.prettyPrinted) let model = try newJSONDecoder.decode(Signup.self, from: jsonData) return model } catch { consoleLog("Model Not Mapped on Json Signup", error.localizedDescription) return nil } } private func parseCountries(response: Any) -> CountryModel? { do { let jsonData = try JSONSerialization.data(withJSONObject: response, options: JSONSerialization.WritingOptions.prettyPrinted) let model = try newJSONDecoder.decode(CountryModel.self, from: jsonData) return model } catch { consoleLog("Model Not Mapped on Json CountryModel", error.localizedDescription) return nil } } private func parseSetAccessToken(response: Any) -> Any? { do { let jsonData = try JSONSerialization.data(withJSONObject: response, options: JSONSerialization.WritingOptions.prettyPrinted) let model = try newJSONDecoder.decode(PlaidAccount.self, from: jsonData) USER.shared.saveAccount(detail: model) return model } catch { consoleLog("Model Not Mapped on Json PlaidAccount", error.localizedDescription) return parseStringError(response: response) } } private func parseLinkToken(response: Any) -> String { if let res = response as? NSDictionary { return res["link_token"] as? String ?? serverError } return serverError } private func parseStringError(response: Any) -> String { if let res = response as? NSDictionary { return res["status"] as? String ?? res["message"] as? String ?? serverError } return serverError } private func parseReceipientBank(response: Any) -> [PlaidAccount]? { do { let jsonData = try JSONSerialization.data(withJSONObject: response, options: JSONSerialization.WritingOptions.prettyPrinted) let model = try newJSONDecoder.decode([PlaidAccount].self, from: jsonData) return model } catch { consoleLog("Model Not Mapped on Json PlaidAccount", error.localizedDescription) return nil } } private func parseDeposit(response: Any) -> DepositDetail? { do { let jsonData = try JSONSerialization.data(withJSONObject: response, options: JSONSerialization.WritingOptions.prettyPrinted) let model = try newJSONDecoder.decode(DepositDetail.self, from: jsonData) return model } catch { consoleLog("Model Not Mapped on Json DepositDetail", error.localizedDescription) return nil } } private func parseTransactions(response: Any) -> Transactions? { do { let jsonData = try JSONSerialization.data(withJSONObject: response, options: JSONSerialization.WritingOptions.prettyPrinted) let model = try newJSONDecoder.decode(Transactions.self, from: jsonData) return model } catch { consoleLog("Model Not Mapped on Json Transactions", error.localizedDescription) return nil } } private func parseStats(response: Any) -> (Int, Int) { if let res = response as? NSDictionary { let rewards = (res["reward_earned"] as? Int ?? 0) let invite = (res["people_invited"] as? Int ?? 0) return(rewards, invite) } return(0, 0) } private func parseShareableLink(response: Any) -> (String?, String?) { if let res = response as? NSDictionary { let link = (res["url"] as? String ?? "") let code = (res["code"] as? String ?? "") return (link, code) } return (nil, nil) } private func parseTotalBalance(response: Any) -> String { if let res = response as? NSDictionary { let amount = (res["buying_power"] as? String ?? "") return amount } return "0" } private func parseFav(response: Any) -> (String?, String?) { if let res = response as? NSDictionary { let aid = (res["account_id"] as? String ?? "") let msg = (res["message"] as? String ?? "") return (aid, msg) } return (nil, nil) } private func parseShares(response: Any) -> Any? { do { let jsonData = try JSONSerialization.data(withJSONObject: response, options: JSONSerialization.WritingOptions.prettyPrinted) let model = try newJSONDecoder.decode(Bar.self, from: jsonData) return model } catch { consoleLog("Model Not Mapped on Json Shares Bar Graph Data", error.localizedDescription) return parseStringError(response: response) } } private func parseStocks(response: Any) -> Any? { do { let jsonData = try JSONSerialization.data(withJSONObject: response, options: JSONSerialization.WritingOptions.prettyPrinted) let model = try newJSONDecoder.decode(Stocks.self, from: jsonData) return model } catch { consoleLog("Model Not Mapped on Json Stocks", error.localizedDescription) return parseStringError(response: response) } } // MARK: - parse Error CASE // parse errors from api func parseResponse(response: Any) -> ErrorModel? { do { let jsonData = try JSONSerialization.data(withJSONObject: response, options: JSONSerialization.WritingOptions.prettyPrinted) let error = try newJSONDecoder.decode(ErrorModel.self, from: jsonData) return error } catch { consoleLog("Model Not Mapped on Json ErrorModel", error.localizedDescription) return nil } } }
0
// Copyright 2019 Algorand, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // LedgerAccountVerificationStatusView.swift import UIKit class LedgerAccountVerificationStatusView: BaseView { private let layout = Layout<LayoutConstants>() private lazy var backgroundView = UIView() private lazy var verificationStatusView = VerificationStatusView() private lazy var addressLabel: UILabel = { UILabel() .withFont(UIFont.font(withWeight: .regular(size: 12.0))) .withTextColor(Colors.Text.primary) .withLine(.contained) .withAlignment(.left) }() override func configureAppearance() { backgroundView.layer.cornerRadius = 12.0 backgroundColor = .clear } override func prepareLayout() { setupBackgroundViewLayout() setupVerificationStatusViewLayout() setupAddressLabelLayout() } } extension LedgerAccountVerificationStatusView { private func setupBackgroundViewLayout() { addSubview(backgroundView) backgroundView.snp.makeConstraints { make in make.leading.trailing.top.bottom.equalToSuperview() } } private func setupVerificationStatusViewLayout() { backgroundView.addSubview(verificationStatusView) verificationStatusView.snp.makeConstraints { make in make.leading.equalToSuperview().inset(layout.current.horizontalInset) make.trailing.lessThanOrEqualToSuperview().inset(layout.current.horizontalInset) make.top.equalToSuperview().inset(layout.current.topInset) } } private func setupAddressLabelLayout() { backgroundView.addSubview(addressLabel) addressLabel.snp.makeConstraints { make in make.top.equalTo(verificationStatusView.snp.bottom).offset(layout.current.addressLabelTopInset) make.leading.equalToSuperview().inset(layout.current.addressLabelLeadingInset) make.trailing.equalToSuperview().inset(layout.current.horizontalInset) make.bottom.equalToSuperview().inset(layout.current.bottomInset) } } } extension LedgerAccountVerificationStatusView { func showLoading() { verificationStatusView.showLoading() } func stopLoading() { verificationStatusView.stopLoading() } } extension LedgerAccountVerificationStatusView { func bind(_ viewModel: LedgerAccountVerificationStatusViewModel) { addressLabel.text = viewModel.address backgroundView.backgroundColor = viewModel.backgroundColor backgroundView.layer.borderColor = viewModel.borderColor?.cgColor if let verificationStatusViewModel = viewModel.verificationStatusViewModel { verificationStatusView.bind(verificationStatusViewModel) } } } extension LedgerAccountVerificationStatusView { private struct LayoutConstants: AdaptiveLayoutConstants { let horizontalInset: CGFloat = 20.0 let addressLabelLeadingInset: CGFloat = 60.0 let addressLabelTopInset: CGFloat = 4.0 let topInset: CGFloat = 16.0 let bottomInset: CGFloat = 20.0 } }
0
// // ConfigMetrica.swift // yandex-metrica-swift // // Created by Aleksey Pleshkov on 05.01.17. // Copyright © 2017 Aleksey Pleshkov. All rights reserved. // import Foundation // // Конфигурационный файл метрики // final class ConfigMetrica { private let token: String private let dateStart: String private let dateEnd: String // Ссылки для получения данных в формате JSON public let linkGetCounters: String public let linkGetSingleCounter: String public let linkGetStandartStats: String public let linkGetGoals: String public let linkGetGoalStats: String // // Стандартный конструктор // init(token: String, dateStart: String, dateEnd: String) { self.token = token self.dateStart = dateStart self.dateEnd = dateEnd // Ссылки для получения данных в формате JSON self.linkGetCounters = "https://api-metrika.yandex.ru/management/v1/counters?oauth_token=\(token)"; self.linkGetSingleCounter = "https://api-metrika.yandex.ru/management/v1/counter/REPLACE_ID?oauth_token=\(token)"; self.linkGetStandartStats = "https://api-metrika.yandex.ru/stat/v1/data?preset=sources_summary&metrics=ym:s:visits,ym:s:pageviews,ym:s:users,ym:s:bounceRate,ym:s:pageDepth,ym:s:avgVisitDurationSeconds,ym:s:percentNewVisitors,ym:s:newUsers,ym:s:newUserVisitsPercentage&id=REPLACE_ID&date1=\(dateStart)&date2=\(dateEnd)&oauth_token=\(token)"; self.linkGetGoals = "https://api-metrika.yandex.ru/management/v1/counter/REPLACE_ID/goals?oauth_token=\(token)"; self.linkGetGoalStats = "https://api-metrika.yandex.ru/stat/v1/data?metrics=ym:s:goalREPLACE_GOAL_IDreaches,ym:s:goalREPLACE_GOAL_IDconversionRate&id=REPLACE_ID&date1=\(dateStart)&date2=\(dateEnd)&oauth_token=\(token)"; } }
0
// // DetailViewController.swift // Watchlist // // Created by Kim Toy (Personal) on 3/31/17. // Copyright © 2017 Codepath. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var posterImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var overviewLabel: UILabel! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var movieInfoView: UIView! var movie: NSDictionary! override func viewDidLoad() { super.viewDidLoad() titleLabel.text = movie["title"] as? String overviewLabel.text = movie["overview"] as? String print(self.movieInfoView.frame.origin.y) UIView.animate(withDuration: 0.3, animations: { () -> Void in self.movieInfoView.frame.origin.y = 350 }) print(self.movieInfoView.frame.origin.y) print(self.movieInfoView.frame.size.height) scrollView.contentSize = CGSize(width: scrollView.frame.size.width, height: self.movieInfoView.frame.origin.y + self.movieInfoView.frame.size.height) overviewLabel.sizeToFit() let baseUrl = "https://image.tmdb.org/t/p/w500" if let posterPath = movie["poster_path"] as? String { let imageUrl = URL(string: baseUrl + posterPath) posterImageView.setImageWith(imageUrl!) } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
0
// // HomeTableViewController.swift // weibo // // Created by mada on 15/9/27. // Copyright © 2015年 MD. All rights reserved. // import UIKit import SDWebImage private let JSJHomeTableViewCellIdentify = "JSJHomeTableViewCellIdentify" class HomeTableViewController: BaseTableViewController { // 标记是下拉还是上拉 private var isPullUp: Bool = false deinit { // 移除通知 NSNotificationCenter.defaultCenter().removeObserver(self) } // 存储所有微博数据 private var statues: [Status]? { didSet { // 刷新微博列表 tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() if !isLogin { visitorView?.setupVisitorInfo(true, centerIconImage: "visitordiscover_feed_image_house", noteText: "关注一些人,回这里看看有什么惊喜") return } // 注册cell tableView.registerClass(HomeNormalCell.self, forCellReuseIdentifier: JSJCellReusableIdentifier.normalCell.rawValue) tableView.registerClass(HomeForwardCell.self, forCellReuseIdentifier: JSJCellReusableIdentifier.forwardCell.rawValue) // 初始化导航条 setupNav() // 添加下拉刷新控件 tableView.addSubview(refreshTipView) // refreshControl = HomeRefreshController() // 加载微博数据 loadData() tableView.separatorStyle = UITableViewCellSeparatorStyle.None } private func loadData() { var since_id = 0 var max_id = 0 // 判断是上拉刷新还是下拉刷新 if isPullUp { // 上拉 max_id = statues!.last!.id - 1 ?? 0 } else { since_id = statues?.first?.id ?? 0 } // 配置请求参数 let parameter = ["access_token": UserAccount.loadAccount()!.access_token!, "max_id": max_id, "since_id": since_id]; NetworkingTools.shareNetworkTools().GET("2/statuses/home_timeline.json", parameters: parameter, success: { (_, JSON) -> Void in // 关闭下拉控件 self.refreshTipView.removeRefresh() if let dictArray = JSON["statuses"] { // 有值 var models = [Status]() for dict in dictArray as! [[String: AnyObject]] { models.append(Status(dict: dict)) } // 判断是否是下拉刷新 if since_id > 0 { JSJLog("下拉") // 拼接在前面 models = models + self.statues! } // 判断是不是上拉 if max_id > 0 { JSJLog("上拉") // 拼接在后面 self.isPullUp = false models = self.statues! + models } // 缓存所有微博配图(优化) self.cacheImage(models) } }) { (_, error) -> Void in JSJLog(error) } } // MARK: - 缓存所有配图 private func cacheImage(models: [Status]) { // 判断模型数组是否为空 // 如果count是nil则等于0 let count = models.count ?? 0 guard count != 0 else { // 确保不为0 return } // 创建一个组(用来确保所有图片的缓存完成,再进行其他操作) let group = dispatch_group_create() // 遍历模型数组 for status in models { // 判断是否有配图 if status.pictureURLs == nil || status.pictureURLs?.count == 0 { continue } for url in status.pictureURLs! { // 将当前下载图片的操作添加到组 dispatch_group_enter(group) // 下载图片 SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil) { (_, _, _, _, _) -> Void in JSJLog("图片已下载") // 离开组 dispatch_group_leave(group) } } } // 监听到所有图片都下载完成(所有元素都退出了组) dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in JSJLog("***所有图片下载完成***") self.statues = models }) } // MARK: - 设置导航栏 private func setupNav() { // 初始化标题按钮 titleButton.setTitle("啦啦啦啦 ", forState: UIControlState.Normal) titleButton.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal) titleButton.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Selected) titleButton.addTarget(self, action: Selector("titleButtonClick"), forControlEvents: UIControlEvents.TouchUpInside) navigationItem.titleView = titleButton // 初始化两边的按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, actionName: "leftButtonClick") navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, actionName: "rightButtonClick") } func titleButtonClick() { JSJLog(__FUNCTION__) let storyboard = UIStoryboard(name: "PopoverViewController", bundle: nil) let vc = storyboard.instantiateInitialViewController()! /* 设置这两个属性之后,modal出控制器后,原控制器的view不会被移除*/ // 告诉系统谁负责转场 vc.transitioningDelegate = popoverAnimator // 转场样式 vc.modalPresentationStyle = UIModalPresentationStyle.Custom presentViewController(vc, animated: true, completion: nil) } func changeTitleButton() { titleButton.selected = !titleButton.selected } func leftButtonClick() { JSJLog(__FUNCTION__) } func rightButtonClick() { JSJLog(__FUNCTION__) let storyboard = UIStoryboard.init(name: "QRCodeViewController", bundle: nil) let vc = storyboard.instantiateInitialViewController()! presentViewController(vc, animated: true, completion: nil) } // MARK: - 数据源方法 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return statues?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let status = statues![indexPath.row] let identity = JSJCellReusableIdentifier.reusableIdentifier(status) let cell = tableView.dequeueReusableCellWithIdentifier(identity) as! HomeTableViewCell cell.status = status // 判断是不是最后一条微博 if indexPath.item == (statues?.count)! - 1 && !isPullUp { JSJLog("最后一条微博") isPullUp = true loadData() } return cell } // MARK: - 代理方法 // 缓存cell高的字典 private var rowHeightCache = [Int: CGFloat]() override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let status = statues![indexPath.row] let identity = JSJCellReusableIdentifier.reusableIdentifier(status) // 取出cell // let cell = tableView.cellForRowAtIndexPath(indexPath) as! HomeTableViewCell // 从缓存池中取 let cell = tableView.dequeueReusableCellWithIdentifier(identity) as! HomeTableViewCell // 判断缓存中是否有高度 if let height = rowHeightCache[status.id] { return height } let height = cell.rowHeight(status) // 缓存高度 rowHeightCache[status.id] = height return height } // 收到内存警告,手动释放 override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() rowHeightCache.removeAll() } // // override func scrollViewDidScroll(scrollView: UIScrollView) { // JSJLog(scrollView.contentOffset) // // } // MARK: - 懒加载 private lazy var popoverAnimator: PopoverAnimationController = { let animator = PopoverAnimationController() // 设置popoverview的大小和位置 animator.presentFrame = CGRect(x: 85, y: 56, width: 200, height: 300) // 注册监听通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("changeTitleButton"), name: JSJPopoverViewDidPrentedNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("changeTitleButton"), name: JSJPopoverViewDidDismissedNotification, object: nil) return animator }() private lazy var titleButton: TitleButton = TitleButton() // 刷新控件 private lazy var refreshTipView: RefreshControllerTipView = RefreshControllerTipView.refreshTipView { () -> Void in self.loadData() } }
0
// // Functions.swift // PasscodeLock // // Created by Yanko Dimitrov on 8/28/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import Foundation func localizedStringFor(key: String, comment: String) -> String { let name = "PasscodeLock" let bundle = bundleForResource(name: name, ofType: "strings") return NSLocalizedString(key, tableName: name, bundle: bundle, comment: comment) } func bundleForResource(name: String, ofType type: String) -> Bundle { if(Bundle.main.path(forResource: name, ofType: type) != nil) { return Bundle.main } return Bundle(for: PasscodeLock.self) }
0
// // TimetableAPI.swift // MyNSB // // Created by Hanyuan Li on 31/12/18. // Copyright © 2018 Qwerp-Derp. All rights reserved. // import Foundation import Alamofire import AwaitKit import PromiseKit import SwiftyJSON class TimetableAPI { static func week() -> Promise<String> { return async { let week = try await(MyNSBRequest.get(path: "/week/get")) return week.stringValue } } /// Fetches bell times from the API and converts it to a list of lists. There /// are 10 `[Timespan]`s in `bellTimes`, each one representing a day in the /// 10-day school fortnight. Each `[Timespan]` contains all the timespans /// for each period. /// /// - Returns: Bell times for the fortnight, marking the beginning and end /// of each period static func bellTimes() -> Promise<BellTimes> { return async { let body = try await(MyNSBRequest.get(path: "/belltimes/get"))[0] return BellTimes(json: body) } } static func timetable(bellTimes: BellTimes) -> Promise<Timetable> { return async { let body = try await(MyNSBRequest.get(path: "/timetable/get"))[0] return Timetable(json: body, bellTimes: bellTimes) } } }
0
// // File.swift // // // Created by Noah Kamara on 10.03.20. // import Foundation import Logging /// Legacy Logging Class public class LoggingLegacy: LogHelper { let logLevel: LoggingLevel let logger: Logger public func debug(_ message: String) { if self.logLevel.rawValue <= LoggingLevel.debug.rawValue { logger.debug("\(message)") } } public func info(_ message: String) { if self.logLevel.rawValue <= LoggingLevel.info.rawValue { logger.info("\(message)") } } public func error(_ message: String) { if self.logLevel.rawValue <= LoggingLevel.error.rawValue { logger.error("\(message)") } } public func warning(_ message: String) { if self.logLevel.rawValue <= LoggingLevel.warning.rawValue { logger.warning("\(message)") } } required init(_ logLevel: LoggingLevel = .debug) { self.logger = Logger(label: "com.noahkamara.TelemachusKit") self.logLevel = logLevel } }
0
import Foundation import CoreData extension InviteLinks { @nonobjc public class func fetchRequest() -> NSFetchRequest<InviteLinks> { return NSFetchRequest<InviteLinks>(entityName: "InviteLinks") } @NSManaged public var inviteKey: String! @NSManaged public var role: String! @NSManaged public var isPending: Bool @NSManaged public var inviteDate: Date! @NSManaged public var groupInvite: Bool @NSManaged public var expiry: Int64 @NSManaged public var link: String! @NSManaged public var blog: Blog! }
0
// // ProfileViewController.swift // twitter_alamofire_demo // // Created by Harjas Monga on 2/19/18. // Copyright © 2018 Charles Hieger. All rights reserved. // import UIKit class ProfileViewController: UIViewController { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var screenNameLabel: UILabel! @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var taglineLabel: UILabel! @IBOutlet weak var numOfTweetsLabel: UILabel! @IBOutlet weak var numOfFollowingLabel: UILabel! @IBOutlet weak var numOfFollowersLabel: UILabel! @IBOutlet weak var profileBackgroundImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() if let user = User.current { profileImageView.af_setImage(withURL: user.profileImageUrl) taglineLabel.text = user.tagline numOfTweetsLabel.text = "\(String(user.tweetCount)) tweets" numOfFollowersLabel.text = "\(String(user.followers)) followers" numOfFollowingLabel.text = "\(String(user.following)) following" if let url = user.profileBackgroundUrl { profileBackgroundImageView.af_setImage(withURL: url) } nameLabel.text = user.name screenNameLabel.text = "@\(user.screenName)" profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2 profileImageView.clipsToBounds = true } } }
0
// // APIActionDispatcher.swift // List // // Created by Luciano Polit on 8/16/20. // Copyright © 2020 LucianoPolit. All rights reserved. // import Foundation import Caesura import API class APIActionDispatcher: Caesura.APIActionDispatcher<Action> { let exampleClient: ExampleClient init( exampleClient: ExampleClient ) { self.exampleClient = exampleClient } override func dispatch( _ action: ActionType, to destination: @escaping Destination ) -> Bool { switch action { case .fetch: handleFetch(with: destination) default: return super.dispatch(action, to: destination) } return true } } extension APIActionDispatcher { func handleFetch( with destination: @escaping Destination ) { destination(.loading) DispatchQueue.main.asyncAfter( deadline: .now() + 1 ) { destination(.set(["First", "Second", "Third"])) } } // func handleFetch( // with destination: @escaping Destination // ) { // handle( // request: exampleClient.readAll, // loading: ActionType.loading, // success: ActionType.set, // failure: ActionType.error, // destination: destination // ) // } }
0
import Foundation import Security public struct Keychain { /// This is used to identifier your service public static let bundleIdentifier: String = { return Bundle.main.bundleIdentifier ?? "" }() /// Actions that can be performed with Keychain, mostly for handling password enum Action { /// Insert an item into keychain case insert /// Fetch an item from keychain case fetch /// Delete an item from keychain case delete } // MARK: - Public methods /// Query password using account in a Keychain service /// /// - Parameters: /// - account: The account, this is for kSecAttrAccount /// - service: The service, this is for kSecAttrService /// - accessGroup: The access group, this is for kSecAttrAccessGroup /// - Returns: The password public static func password(forAccount account: String, service: String = bundleIdentifier, accessGroup: String = "") -> String? { guard !service.isEmpty && !account.isEmpty else { return nil } var query = [ kSecAttrAccount as String : account, kSecAttrService as String : service, kSecClass as String : kSecClassGenericPassword] as [String : Any] if !accessGroup.isEmpty { query[kSecAttrAccessGroup as String] = accessGroup } return Keychain.query(.fetch, query as [String : AnyObject]).1 } /// Set the password for the account in a Keychain service /// /// - Parameters: /// - password: The password string you want to set /// - account: The account, this is for kSecAttrAccount /// - service: The service, this is for kSecAttrService /// - accessGroup: The access group, this is for kSecAttrAccessGroup /// - Returns: True if the password can be set successfully @discardableResult public static func setPassword(_ password: String, forAccount account: String, service: String = bundleIdentifier, accessGroup: String = "") -> Bool { guard !service.isEmpty && !account.isEmpty else { return false } var query = [ kSecAttrAccount as String : account, kSecAttrService as String : service, kSecClass as String : kSecClassGenericPassword, kSecAttrAccessible as String : kSecAttrAccessibleAfterFirstUnlock] as [String : Any] if !accessGroup.isEmpty { query[kSecAttrAccessGroup as String] = accessGroup } return Keychain.query(.insert, query as [String : AnyObject], password).0 == errSecSuccess } /// Delete password for the account in a Keychain service /// /// - Parameters: /// - account: The account, this is for kSecAttrAccount /// - service: The service, this is for kSecAttrService /// - Returns: True if the password can be safely deleted @discardableResult public static func deletePassword(forAccount account: String, service: String = bundleIdentifier, accessGroup: String = "") -> Bool { guard !service.isEmpty && !account.isEmpty else { return false } var query = [ kSecAttrAccount as String: account, kSecAttrService as String : service, kSecClass as String : kSecClassGenericPassword ] as [String : Any] if !accessGroup.isEmpty { query[kSecAttrAccessGroup as String] = accessGroup } return Keychain.query(.delete, query as [String : AnyObject]).0 == errSecSuccess } // MARK: - Private methods /// A helper method to query Keychain based on some actions /// /// - Parameters: /// - action: The action /// - query: A dictionary containing keychain parameters /// - password: The password /// - Returns: A tuple with status and returned password fileprivate static func query(_ action: Action, _ query: [String : AnyObject], _ password: String = "") -> (OSStatus, String) { let passwordData = password.data(using: String.Encoding.utf8) var returnPassword = "" var status = SecItemCopyMatching(query as CFDictionary, nil) var attributes = [String : AnyObject]() switch action { case .insert: switch status { case errSecSuccess: attributes[kSecValueData as String] = passwordData as AnyObject? status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) case errSecItemNotFound: var query = query query[kSecValueData as String] = passwordData as AnyObject? status = SecItemAdd(query as CFDictionary, nil) default: break } case .fetch: var query = query query[kSecReturnData as String] = true as AnyObject? query[kSecMatchLimit as String] = kSecMatchLimitOne var result: CFTypeRef? status = SecItemCopyMatching(query as CFDictionary, &result) if let result = result as? Data, let password = String(data: result, encoding: String.Encoding.utf8) { returnPassword = password } case .delete: status = SecItemDelete(query as CFDictionary) } return (status, returnPassword) } }
0
import Foundation import TSCBasic import TuistCache import TuistCacheTesting import TuistCore import TuistCoreTesting import TuistGraph import TuistGraphTesting import TuistLoader import TuistLoaderTesting import TuistSupport import XCTest @testable import TuistCore @testable import TuistKit @testable import TuistSupportTesting final class CacheControllerTests: TuistUnitTestCase { var generator: MockGenerator! var graphContentHasher: MockGraphContentHasher! var artifactBuilder: MockCacheArtifactBuilder! var manifestLoader: MockManifestLoader! var cache: MockCacheStorage! var subject: CacheController! var projectGeneratorProvider: MockCacheControllerProjectGeneratorProvider! var config: Config! var cacheGraphLinter: MockCacheGraphLinter! var focusServiceProjectGeneratorFactory: MockFocusServiceProjectGeneratorFactory! override func setUp() { generator = MockGenerator() artifactBuilder = MockCacheArtifactBuilder() cache = MockCacheStorage() manifestLoader = MockManifestLoader() graphContentHasher = MockGraphContentHasher() config = .test() projectGeneratorProvider = MockCacheControllerProjectGeneratorProvider() projectGeneratorProvider.stubbedGeneratorResult = generator cacheGraphLinter = MockCacheGraphLinter() focusServiceProjectGeneratorFactory = MockFocusServiceProjectGeneratorFactory() focusServiceProjectGeneratorFactory.stubbedGeneratorResult = generator subject = CacheController(cache: cache, artifactBuilder: artifactBuilder, projectGeneratorProvider: projectGeneratorProvider, graphContentHasher: graphContentHasher, cacheGraphLinter: cacheGraphLinter, focusServiceProjectGeneratorFactory: focusServiceProjectGeneratorFactory) super.setUp() } override func tearDown() { super.tearDown() generator = nil artifactBuilder = nil graphContentHasher = nil manifestLoader = nil cache = nil subject = nil config = nil focusServiceProjectGeneratorFactory = nil } func test_cache_builds_and_caches_the_frameworks() throws { // Given let path = try temporaryPath() let xcworkspacePath = path.appending(component: "Project.xcworkspace") let project = Project.test(path: path, name: "Cache") let targetNames = ["foo", "bar", "baz"].shuffled() let aTarget = Target.test(name: targetNames[0]) let bTarget = Target.test(name: targetNames[1]) let cTarget = Target.test(name: targetNames[2]) let aFrameworkPath = path.appending(component: "\(aTarget.name).framework") let bFrameworkPath = path.appending(component: "\(bTarget.name).framework") let cFrameworkPath = path.appending(component: "\(cTarget.name).framework") try FileHandler.shared.createFolder(aFrameworkPath) try FileHandler.shared.createFolder(bFrameworkPath) try FileHandler.shared.createFolder(cFrameworkPath) let aTargetNode = TargetNode.test(project: project, target: aTarget) let bTargetNode = TargetNode.test(project: project, target: bTarget, dependencies: [aTargetNode]) let cTargetNode = TargetNode.test(project: project, target: cTarget, dependencies: [bTargetNode]) let nodeWithHashes = [ aTargetNode: "\(aTarget.name)_HASH", bTargetNode: "\(bTarget.name)_HASH", cTargetNode: "\(cTarget.name)_HASH", ] let graph = Graph.test(projects: [project], targets: nodeWithHashes.keys.reduce(into: [project.path: [TargetNode]()]) { $0[project.path]?.append($1) }) manifestLoader.manifestsAtStub = { (loadPath: AbsolutePath) -> Set<Manifest> in XCTAssertEqual(loadPath, path) return Set(arrayLiteral: .project) } generator.generateWithGraphStub = { (loadPath, _) -> (AbsolutePath, Graph) in XCTAssertEqual(loadPath, path) return (xcworkspacePath, graph) } generator.generateStub = { (loadPath, _) -> AbsolutePath in XCTAssertEqual(loadPath, path) return xcworkspacePath } graphContentHasher.stubbedContentHashesResult = nodeWithHashes artifactBuilder.stubbedCacheOutputType = .xcframework try subject.cache(path: path) // Then XCTAssertPrinterOutputContains(""" Hashing cacheable targets Building cacheable targets Building cacheable targets: \(aTarget.name), 1 out of 3 Focusing cacheable targets: \(aTarget.name) Building cacheable targets: \(bTarget.name), 2 out of 3 Focusing cacheable targets: \(bTarget.name) Building cacheable targets: \(cTarget.name), 3 out of 3 Focusing cacheable targets: \(cTarget.name) All cacheable targets have been cached successfully as xcframeworks """) XCTAssertEqual(cacheGraphLinter.invokedLintCount, 1) XCTAssertEqual(artifactBuilder.invokedBuildWorkspacePathParametersList[0].target, aTarget) XCTAssertEqual(artifactBuilder.invokedBuildWorkspacePathParametersList[1].target, bTarget) XCTAssertEqual(artifactBuilder.invokedBuildWorkspacePathParametersList[2].target, cTarget) } }
0
// // UILabel+Additions.swift // TapAdditionsKit // // Copyright © 2019 Tap Payments. All rights reserved. // import struct Foundation.NSDate.TimeInterval import class UIKit.UIColor.UIColor import class UIKit.UILabel.UILabel import class UIKit.UIView.UIView /// Useful extensions to UILabel class. public extension UILabel { // MARK: - Public - // MARK: Methods /// Sets text color with animation. /// /// - Parameters: /// - textColor: Text color. /// - animationDuration: Animation duration. func tap_setTextColor(_ textColor: UIColor, animationDuration: TimeInterval) { let animations: TypeAlias.ArgumentlessClosure = { [weak self] in self?.textColor = textColor } UIView.transition(with: self, duration: max(animationDuration, 0.0), options: .transitionCrossDissolve, animations: animations, completion: nil) } /// Sets text with animation. /// /// - Parameters: /// - text: string for text /// - animationDuration: Animation duration func tap_setText(_ text: String, animationDuration: TimeInterval) { let animations: TypeAlias.ArgumentlessClosure = { [weak self] in self?.text = text } UIView.transition(with: self, duration: max(animationDuration, 0.0), options: [.transitionCrossDissolve, .layoutSubviews], animations: animations, completion: nil) } }
0
// Copyright (C) 2019 Parrot Drones SAS // // 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 the Parrot Company 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 // PARROT COMPANY 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 XCTest @testable import GroundSdk /// Test Alarms instrument class AlarmsTests: XCTestCase { private var store: ComponentStoreCore! override func setUp() { super.setUp() store = ComponentStoreCore() } func testPublishUnpublish() { let impl = AlarmsCore(store: store, supportedAlarms: Set()) impl.publish() assertThat(store.get(Instruments.alarms), present()) impl.unpublish() assertThat(store.get(Instruments.alarms), nilValue()) } func testAlarmKindAllValues() { var allKind: Set<Alarm.Kind> = Set() for i in 0 ... Int.max - 1 { let kind = Alarm.Kind(rawValue: i) if let kind = kind { allKind.insert(kind) } else { break } } assertThat(Alarm.Kind.allCases, `is`(allKind)) } func testAlarmsKind() { let impl = AlarmsCore(store: store, supportedAlarms: [.power]) // check that all alarms are the same kind with the one they are stored in for kind in Alarm.Kind.allCases { assertThat(impl.getAlarm(kind: kind).kind, `is`(kind)) } } func testLevelChanges() { let impl = AlarmsCore(store: store, supportedAlarms: [.power]) impl.publish() var cnt = 0 let alarms = store.get(Instruments.alarms)! _ = store.register(desc: Instruments.alarms) { cnt += 1 } // check availability set at construction assertThat(alarms.getAlarm(kind: .power).level, `is`(.off)) assertThat(alarms.getAlarm(kind: .userEmergency).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .motorCutOut).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .motorError).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .batteryTooCold).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .batteryTooHot).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .hoveringDifficultiesNoGpsTooHigh).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .hoveringDifficultiesNoGpsTooDark).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .automaticLandingBatteryIssue).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .wind).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .verticalCamera).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .strongVibrations).level, `is`(.notAvailable)) // check changing a single level impl.update(level: .critical, forAlarm: .power).notifyUpdated() assertThat(cnt, `is`(1)) assertThat(alarms.getAlarm(kind: .power).level, `is`(.critical)) assertThat(alarms.getAlarm(kind: .userEmergency).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .motorCutOut).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .motorError).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .batteryTooCold).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .batteryTooHot).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .hoveringDifficultiesNoGpsTooHigh).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .hoveringDifficultiesNoGpsTooDark).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .automaticLandingBatteryIssue).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .wind).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .verticalCamera).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .strongVibrations).level, `is`(.notAvailable)) // check changing multiple levels impl.update(level: .warning, forAlarm: .power).update(level: .critical, forAlarm: .userEmergency) .update(level: .critical, forAlarm: .batteryTooHot) .update(level: .critical, forAlarm: .hoveringDifficultiesNoGpsTooDark) .update(level: .warning, forAlarm: .strongVibrations) .notifyUpdated() assertThat(cnt, `is`(2)) assertThat(alarms.getAlarm(kind: .power).level, `is`(.warning)) assertThat(alarms.getAlarm(kind: .userEmergency).level, `is`(.critical)) assertThat(alarms.getAlarm(kind: .motorCutOut).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .motorError).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .batteryTooCold).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .batteryTooHot).level, `is`(.critical)) assertThat(alarms.getAlarm(kind: .hoveringDifficultiesNoGpsTooHigh).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .hoveringDifficultiesNoGpsTooDark).level, `is`(.critical)) assertThat(alarms.getAlarm(kind: .automaticLandingBatteryIssue).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .wind).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .verticalCamera).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .strongVibrations).level, `is`(.warning)) // check setting again the same level does nothing impl.update(level: .warning, forAlarm: .power).notifyUpdated() assertThat(cnt, `is`(2)) assertThat(alarms.getAlarm(kind: .power).level, `is`(.warning)) assertThat(alarms.getAlarm(kind: .userEmergency).level, `is`(.critical)) assertThat(alarms.getAlarm(kind: .motorCutOut).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .motorError).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .batteryTooCold).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .batteryTooHot).level, `is`(.critical)) assertThat(alarms.getAlarm(kind: .hoveringDifficultiesNoGpsTooHigh).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .hoveringDifficultiesNoGpsTooDark).level, `is`(.critical)) assertThat(alarms.getAlarm(kind: .automaticLandingBatteryIssue).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .wind).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .verticalCamera).level, `is`(.notAvailable)) assertThat(alarms.getAlarm(kind: .strongVibrations).level, `is`(.warning)) // test notify without changes impl.notifyUpdated() assertThat(cnt, `is`(2)) } func testAutoLandingDelay() { let impl = AlarmsCore(store: store, supportedAlarms: []) impl.publish() var cnt = 0 let alarms = store.get(Instruments.alarms)! _ = store.register(desc: Instruments.alarms) { cnt += 1 } // check initial state assertThat(alarms.automaticLandingDelay, `is`(0)) assertThat(cnt, `is`(0)) // mock delay changed impl.update(automaticLandingDelay: 25).notifyUpdated() assertThat(alarms.automaticLandingDelay, `is`(25)) assertThat(cnt, `is`(1)) // mock delay update with same value impl.update(automaticLandingDelay: 25).notifyUpdated() assertThat(alarms.automaticLandingDelay, `is`(25)) assertThat(cnt, `is`(1)) } }
0
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import DummyModule } var d { protocol A { typealias e: e { { } } } case .d { init { { enum ( ( { { { [ [ { { { { ( ( ( a" }
0
// // CompetitionViewController.swift // WESST // // Created by Tannar, Nathan on 2016-09-13. // Copyright © 2016 NathanTannar. All rights reserved. // import UIKit import Parse import Former import Agrume import SVProgressHUD import JSQWebViewController import MessageUI import BRYXBanner import Material class ConferenceViewController: FormViewController { var firstLoad = true var positionIDs = [String]() var conference: String? override func viewDidLoad() { super.viewDidLoad() // Setup UI and Table Properties tableView.contentInset.top = 0 tableView.contentInset.bottom = 60 tableView.separatorStyle = UITableViewCellSeparatorStyle.none self.navigationItem.titleView = Utilities.setTitle(title: conference!, subtitle: "Conference") self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: Icon.cm.menu, style: .plain, target: self, action: #selector(leftDrawerButtonPressed)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: Icon.cm.moreVertical, style: .plain, target: self, action: #selector(settingsButtonPressed)) Conference.sharedInstance.clear() SVProgressHUD.show(withStatus: "Loading") let query = PFQuery(className: "WESST_Conferences") query.whereKey(PF_CONFERENCE_NAME, equalTo: self.conference!) query.findObjectsInBackground { (conferences: [PFObject]?, error: Error?) in SVProgressHUD.dismiss() if error == nil { Conference.sharedInstance.conference = conferences?.first if Conference.sharedInstance.conference == nil { print("Creating Conference") Conference.sharedInstance.name = self.conference! Conference.sharedInstance.create() } Conference.sharedInstance.unpack() self.getPositions() self.configure() } else { let banner = Banner(title: "An Error Occurred", subtitle: error.debugDescription, image: nil, backgroundColor: MAIN_COLOR!) banner.dismissesOnTap = true banner.show(duration: 2.0) } } } override func viewDidAppear(_ animated: Bool) { if !firstLoad { updateRows() getPositions() self.former.remove(section: 1) self.former.reload() self.loadOC() } else { firstLoad = false } } private func getPositions() { positionIDs.removeAll() for position in Conference.sharedInstance.positions { if Conference.sharedInstance.conference![position.lowercased().replacingOccurrences(of: " ", with: "")] != nil { positionIDs.append(Conference.sharedInstance.conference![position.lowercased().replacingOccurrences(of: " ", with: "")] as! String) } else { positionIDs.append("") } } print(positionIDs) } let createMenu: ((String, (() -> Void)?) -> RowFormer) = { text, onSelected in return LabelRowFormer<FormLabelCell>() { $0.titleLabel.textColor = MAIN_COLOR $0.titleLabel.font = .boldSystemFont(ofSize: 16) $0.accessoryType = .disclosureIndicator }.configure { $0.text = text }.onSelected { _ in onSelected?() } } private lazy var onlyImageRow: LabelRowFormer<ImageCell> = { LabelRowFormer<ImageCell>(instantiateType: .Nib(nibName: "ImageCell")) { $0.displayImage.file = Conference.sharedInstance.conference![PF_CONFERENCE_COVER_PHOTO] as? PFFile $0.displayImage.loadInBackground() }.configure { $0.rowHeight = 200 }.onSelected({ _ in if Conference.sharedInstance.coverPhoto != nil { let agrume = Agrume(image: Conference.sharedInstance.coverPhoto!) agrume.showFrom(self) } }) }() private lazy var infoRow: CustomRowFormer<DynamicHeightCell> = { CustomRowFormer<DynamicHeightCell>(instantiateType: .Nib(nibName: "DynamicHeightCell")) { $0.selectionStyle = .none $0.title = "Info" $0.body = Conference.sharedInstance.info! $0.titleLabel.font = RobotoFont.medium(with: 15) $0.titleLabel.textColor = MAIN_COLOR $0.bodyLabel.font = RobotoFont.regular(with: 15) $0.date = "" }.configure { $0.rowHeight = UITableViewAutomaticDimension }.onSelected { [weak self] _ in self?.former.deselect(animated: true) } }() private lazy var hostSchoolRow: CustomRowFormer<DynamicHeightCell> = { CustomRowFormer<DynamicHeightCell>(instantiateType: .Nib(nibName: "DynamicHeightCell")) { $0.selectionStyle = .none $0.title = "Host" $0.body = Conference.sharedInstance.hostSchool $0.date = "" $0.bodyColor = UIColor.black $0.titleLabel.font = RobotoFont.medium(with: 15) $0.titleLabel.textColor = MAIN_COLOR $0.bodyLabel.font = RobotoFont.regular(with: 15) }.configure { $0.rowHeight = UITableViewAutomaticDimension }.onSelected { [weak self] _ in self?.former.deselect(animated: true) } }() private lazy var locationRow: CustomRowFormer<DynamicHeightCell> = { CustomRowFormer<DynamicHeightCell>(instantiateType: .Nib(nibName: "DynamicHeightCell")) { $0.selectionStyle = .none $0.title = "Location" $0.body = Conference.sharedInstance.location $0.date = "" $0.bodyColor = UIColor.black $0.titleLabel.font = RobotoFont.medium(with: 15) $0.titleLabel.textColor = MAIN_COLOR $0.bodyLabel.font = RobotoFont.regular(with: 15) }.configure { $0.rowHeight = UITableViewAutomaticDimension }.onSelected { [weak self] _ in self?.former.deselect(animated: true) } }() private lazy var timeRow: CustomRowFormer<DynamicHeightCell> = { CustomRowFormer<DynamicHeightCell>(instantiateType: .Nib(nibName: "DynamicHeightCell")) { $0.selectionStyle = .none $0.title = "Dates" $0.body = "\(Conference.sharedInstance.start!.mediumDateString!) to \(Conference.sharedInstance.end!.mediumDateString!)" $0.date = "" $0.bodyColor = UIColor.black $0.titleLabel.font = RobotoFont.medium(with: 15) $0.titleLabel.textColor = MAIN_COLOR $0.bodyLabel.font = RobotoFont.regular(with: 15) }.configure { $0.rowHeight = UITableViewAutomaticDimension }.onSelected { [weak self] _ in self?.former.deselect(animated: true) } }() private lazy var urlRow: CustomRowFormer<DynamicHeightCell> = { CustomRowFormer<DynamicHeightCell>(instantiateType: .Nib(nibName: "DynamicHeightCell")) { $0.selectionStyle = .none $0.title = "Website" $0.body = Conference.sharedInstance.url $0.date = "" $0.bodyColor = UIColor.black $0.titleLabel.font = RobotoFont.medium(with: 15) $0.titleLabel.textColor = MAIN_COLOR $0.bodyLabel.font = RobotoFont.regular(with: 15) }.configure { $0.rowHeight = UITableViewAutomaticDimension }.onSelected { [weak self] _ in self?.former.deselect(animated: true) if Conference.sharedInstance.url != "" { let controller = WebViewController(url: NSURL(string: "http://\(Conference.sharedInstance.url!)")! as URL) let nav = UINavigationController(rootViewController: controller) nav.navigationBar.barTintColor = MAIN_COLOR self!.present(nav, animated: true, completion: nil) } } }() private func configure() { let delegatePackageRow = createMenu("Delegate Portal") { [weak self] in self?.former.deselect(animated: true) self?.navigationController?.pushViewController(DelegatePackageViewController(), animated: true) } self.former.append(sectionFormer: SectionFormer(rowFormer: onlyImageRow, infoRow, hostSchoolRow, locationRow, timeRow, urlRow)) if conference == "WEC" { self.former.insert(rowFormer: delegatePackageRow, below: urlRow) } loadOC() } private func loadOC() { var members = [RowFormer]() let memberQuery = PFUser.query() memberQuery!.whereKey(PF_USER_OBJECTID, containedIn: self.positionIDs) memberQuery!.addAscendingOrder(PF_USER_FULLNAME) memberQuery!.findObjectsInBackground(block: { (users: [PFObject]?, error: Error?) in if error == nil { if users != nil { for user in users! { if self.positionIDs.contains(user.objectId!) { members.append(LabelRowFormer<ProfileImageDetailCell>(instantiateType: .Nib(nibName: "ProfileImageDetailCell")) { $0.accessoryType = .detailButton $0.tintColor = MAIN_COLOR $0.iconView.backgroundColor = MAIN_COLOR $0.iconView.layer.borderWidth = 1 $0.iconView.layer.borderColor = MAIN_COLOR?.cgColor $0.iconView.image = UIImage(named: "profile_blank") $0.iconView.file = user[PF_USER_PICTURE] as? PFFile $0.iconView.loadInBackground() $0.titleLabel.textColor = UIColor.black $0.detailLabel.textColor = UIColor.gray let index = self.positionIDs.index(of: user.objectId!) $0.detailLabel.text = Conference.sharedInstance.positions[index!] }.configure { $0.text = user[PF_USER_FULLNAME] as? String $0.rowHeight = 60 }.onSelected { [weak self] _ in self?.former.deselect(animated: true) let profileVC = PublicProfileViewController() profileVC.user = user let navVC = UINavigationController(rootViewController: profileVC) navVC.navigationBar.barTintColor = MAIN_COLOR! self?.present(navVC, animated: true, completion: nil) }) } } self.former.insertUpdate(sectionFormer: SectionFormer(rowFormers: members).set(headerViewFormer: TableFunctions.createHeader(text: "Organizing Committee")), toSection: 1, rowAnimation: .fade) } } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - User actions func settingsButtonPressed() { let actionSheetController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) actionSheetController.view.tintColor = MAIN_COLOR let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in //Just dismiss the action sheet } actionSheetController.addAction(cancelAction) if Engagement.sharedInstance.admins.contains(PFUser.current()!.objectId!) { let editAction: UIAlertAction = UIAlertAction(title: "Edit", style: .default) { action -> Void in self.navigationController?.pushViewController(EditConferenceViewController(), animated: true) } actionSheetController.addAction(editAction) let adminFunctionsAction: UIAlertAction = UIAlertAction(title: "Admin Function", style: .default) { action -> Void in let delegateQuery = PFQuery(className: "WESST_WEC_Delegates") delegateQuery.limit = 300 delegateQuery.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in if error == nil { var userIds = [String]() if let objects = objects { for object in objects { let user = object.value(forKey: "user") as! PFUser userIds.append(user.objectId!) } let vc = AdminFunctionsViewController() vc.userIds = userIds self.navigationController?.pushViewController(vc, animated: true) } } else { SVProgressHUD.showError(withStatus: "Network Error") } }) } actionSheetController.addAction(adminFunctionsAction) } actionSheetController.popoverPresentationController?.sourceView = self.view //Present the AlertController self.present(actionSheetController, animated: true, completion: nil) } func updateRows() { infoRow.cellUpdate { $0.bodyLabel.text = Conference.sharedInstance.info } hostSchoolRow.cellUpdate { $0.bodyLabel.text = Conference.sharedInstance.hostSchool } locationRow.cellUpdate { $0.bodyLabel.text = Conference.sharedInstance.location } timeRow.cellUpdate { $0.body = "\(Conference.sharedInstance.start!.mediumDateString!) to \(Conference.sharedInstance.end!.mediumDateString!)" } urlRow.cellUpdate { $0.bodyLabel.text = Conference.sharedInstance.url } onlyImageRow.cellUpdate { $0.displayImage.file = Conference.sharedInstance.conference![PF_CONFERENCE_COVER_PHOTO] as? PFFile $0.displayImage.loadInBackground() } self.former.reload() } func leftDrawerButtonPressed() { self.evo_drawerController?.toggleDrawerSide(.left, animated: true, completion: nil) } }
0
// // Created by Maxim Pervushin on 10/03/16. // Copyright (c) 2016 Maxim Pervushin. All rights reserved. // import UIKit class SignUpViewController: UIViewController { // MARK: SignUpViewController @IB @IBOutlet weak var usernameTextField: UITextField? @IBOutlet weak var passwordTextField: UITextField? @IBOutlet weak var containerView: UIView? @IBOutlet weak var containerToBottomLayoutConstraint: NSLayoutConstraint? @IBAction func closeButtonAction(sender: AnyObject) { onClose?() } @IBAction func signUpButtonAction(sender: AnyObject) { didSignUp?(username: usernameTextField?.text, password: passwordTextField?.text) } @IBAction func tapGestureRecognizerAction(sender: AnyObject) { if usernameTextField?.isFirstResponder() == true { usernameTextField?.resignFirstResponder() } else if passwordTextField?.isFirstResponder() == true { passwordTextField?.resignFirstResponder() } } // MARK: SignUpViewController var onClose: (Void -> Void)? var didSignUp: ((username: String?, password: String?) -> Void)? private func keyboardWillChangeFrameNotification(notification: NSNotification) { guard let viewHeight = view?.bounds.size.height, frameEnd = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue(), animationDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval else { return } view.layoutIfNeeded() UIView.animateWithDuration(animationDuration) { () -> Void in self.containerToBottomLayoutConstraint?.constant = viewHeight - frameEnd.origin.y self.view.layoutIfNeeded() } } private func subscribe() { NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillChangeFrameNotification, object: nil, queue: nil, usingBlock: keyboardWillChangeFrameNotification) } private func unsubscribe() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) subscribe() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) unsubscribe() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if traitCollection.horizontalSizeClass == .Compact { return [.Portrait] } return [.All] } }
0
// // DaxDialogsSettings.swift // DuckDuckGo // // Copyright © 2020 DuckDuckGo. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Core protocol DaxDialogsSettings { var isDismissed: Bool { get set } var homeScreenMessagesSeen: Int { get set } var browsingAfterSearchShown: Bool { get set } var browsingWithTrackersShown: Bool { get set } var browsingWithoutTrackersShown: Bool { get set } var browsingMajorTrackingSiteShown: Bool { get set } var fireButtonEducationShownOrExpired: Bool { get set } var fireButtonPulseDateShown: Date? { get set } } class DefaultDaxDialogsSettings: DaxDialogsSettings { @UserDefaultsWrapper(key: .daxIsDismissed, defaultValue: true) var isDismissed: Bool @UserDefaultsWrapper(key: .daxHomeScreenMessagesSeen, defaultValue: 0) var homeScreenMessagesSeen: Int @UserDefaultsWrapper(key: .daxBrowsingAfterSearchShown, defaultValue: false) var browsingAfterSearchShown: Bool @UserDefaultsWrapper(key: .daxBrowsingWithTrackersShown, defaultValue: false) var browsingWithTrackersShown: Bool @UserDefaultsWrapper(key: .daxBrowsingWithoutTrackersShown, defaultValue: false) var browsingWithoutTrackersShown: Bool @UserDefaultsWrapper(key: .daxBrowsingMajorTrackingSiteShown, defaultValue: false) var browsingMajorTrackingSiteShown: Bool @UserDefaultsWrapper(key: .daxFireButtonEducationShownOrExpired, defaultValue: false) var fireButtonEducationShownOrExpired: Bool @UserDefaultsWrapper(key: .fireButtonPulseDateShown, defaultValue: nil) var fireButtonPulseDateShown: Date? } class InMemoryDaxDialogsSettings: DaxDialogsSettings { var isDismissed: Bool = false var homeScreenMessagesSeen: Int = 0 var browsingAfterSearchShown: Bool = false var browsingWithTrackersShown: Bool = false var browsingWithoutTrackersShown: Bool = false var browsingMajorTrackingSiteShown: Bool = false var fireButtonEducationShownOrExpired: Bool = false var fireButtonPulseDateShown: Date? }
0
// // Created by Marko Justinek on 1/4/20. // Copyright © 2020 Marko Justinek. All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // import Foundation extension Bundle { static var pact: Bundle? { #if os(iOS) return Bundle(identifier: "au.com.pact-foundation.iOS.PactSwift") #elseif os(macOS) return Bundle(identifier: "au.com.pact-foundation.macOS.PactSwift") #else return nil #endif } var shortVersion: String? { object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String } }
0
// // Zalgo.swift // Red Zebra // // Created by Jan Kříž on 02/07/2019. // Copyright © 2019 Jan Kříž. All rights reserved. // public struct Zalgo { public func transform(_ text: String) -> String { // space before & after text for better looking result var input = " \(text) " var output = "" for _ in input { output.append(input.removeFirst()) output.append(self.above.randomElement()!) output.append(self.above.randomElement()!) output.append(self.inline.randomElement()!) output.append(self.inline.randomElement()!) output.append(self.below.randomElement()!) output.append(self.below.randomElement()!) } return output } private let above: [Character] private let inline: [Character] private let below: [Character] public init() { self.above = [ "\u{030d}", "\u{030e}", "\u{0304}", "\u{0305}", "\u{033f}", "\u{0311}", "\u{0306}", "\u{0310}", "\u{0352}", "\u{0357}", "\u{0351}", "\u{0307}", "\u{0308}", "\u{030a}", "\u{0342}", "\u{0343}", "\u{0344}", "\u{034b}", "\u{034c}", "\u{0303}", "\u{0302}", "\u{030c}", "\u{0350}", "\u{0300}", "\u{0301}", "\u{030b}", "\u{030f}", "\u{0312}", "\u{0313}", "\u{0314}", "\u{033d}", "\u{0309}", "\u{0363}", "\u{0364}", "\u{0365}", "\u{0366}", "\u{0367}", "\u{0368}", "\u{0369}", "\u{036a}", "\u{036b}", "\u{036c}", "\u{036d}", "\u{036e}", "\u{036f}", "\u{033e}", "\u{035b}", "\u{0346}", "\u{031a}" ] self.inline = [ "\u{0315}", "\u{031b}", "\u{0340}", "\u{0341}", "\u{0358}", "\u{0321}", "\u{0322}", "\u{0327}", "\u{0328}", "\u{0334}", "\u{0335}", "\u{0336}", "\u{034f}", "\u{035c}", "\u{035d}", "\u{035e}", "\u{035f}", "\u{0360}", "\u{0362}", "\u{0338}", "\u{0337}", "\u{0361}", "\u{0489}" ] self.below = [ "\u{0316}", "\u{0317}", "\u{0318}", "\u{0319}", "\u{031c}", "\u{031d}", "\u{031e}", "\u{031f}", "\u{0320}", "\u{0324}", "\u{0325}", "\u{0326}", "\u{0329}", "\u{032a}", "\u{032b}", "\u{032c}", "\u{032d}", "\u{032e}", "\u{032f}", "\u{0330}", "\u{0331}", "\u{0332}", "\u{0333}", "\u{0339}", "\u{033a}", "\u{033b}", "\u{033c}", "\u{0345}", "\u{0347}", "\u{0348}", "\u{0349}", "\u{034d}", "\u{034e}", "\u{0353}", "\u{0354}", "\u{0355}", "\u{0356}", "\u{0359}", "\u{035a}", "\u{0323}" ] } }