hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
e07effa177420ee1ae9050b25dc6a3b194499828
54,230
public enum CGVisualBasicCodeGeneratorDialect { case Standard case Mercury } public class CGVisualBasicNetCodeGenerator : CGCodeGenerator { public init() { super.init() useTabs = false tabSize = 2 keywordsAreCaseSensitive = false keywords = ["addhandler", "addressof", "alias", "and", "andalso", "as", "ascending", "assembly", "async", "await", "boolean", "by", "byref", "byte", "byval", "call", "case", "catch", "cbool", "cbyte", "cchar", "cdate", "cdec", "cdbl", "char", "cint", "class", "clng", "cobj", "const", "continue", "csbyte", "cshort", "csng", "cstr", "ctype", "cuint", "culng", "cushort", "custom", "date", "decimal", "declare", "default", "delegate", "descending", "dim", "directcast", "distinct", "do", "double", "dynamic", "each", "else", "elseif", "end", "endif", "enum", "equals", "erase", "error", "event", "exit", "extends", "false", "finally", "for", "friend", "from", "function", "get", "gettype", "getxmlnamespace", "global", "gosub", "goto", "group", "handles", "if", "implements", "imports", "in", "inherits", "integer", "interface", "into", "iterator", "is", "isnot", "join", "key", "lazy", "let", "lib", "like", "long", "loop", "me", "mod", "module", "mustinherit", "mustoverride", "mybase", "myclass", "namespace", "narrowing", "new", "next", "not", "nothing", "notinheritable", "notoverridable", "null", "object", "of", "on", "operator", "option", "optional", "or", "order", "orelse", "out", "overloads", "overridable", "overrides", "paramarray", "partial", "preserve", "private", "property", "protected", "ptr", "public", "raiseevent", "readonly", "redim", "rem", "removehandler", "resume", "return", "sbyte", "select", "set", "shadows", "shared", "short", "single", "skip", "static", "step", "stop", "string", "structure", "sub", "synclock", "take", "then", "throw", "to", "true", "try", "trycast", "typeof", "uinteger", "ulong", "ushort", "unmanaged", "until", "using", "variant", "wend", "when", "where", "while", "widening", "with", "withevents", "writeonly", "xor", "yield"].ToList() as! List<String> } public var Dialect: CGVisualBasicCodeGeneratorDialect = .Standard public convenience init(dialect: CGVisualBasicCodeGeneratorDialect) { init() Dialect = dialect } public override var defaultFileExtension: String { return "vb" } override func escapeIdentifier(_ name: String) -> String { if (!positionedAfterPeriod) { return "[\(name)]" } return name } var Methods: Stack<String> = Stack<String>() var Loops: Stack<String> = Stack<String>() var InLoop: Integer = 0 //done override func generateDirectives() { super.generateDirectives() if currentUnit.Imports.Count > 0 { AppendLine() } // VB.NET-specific if Dialect == .Standard { AppendLine("Option Explicit On") AppendLine("Option Infer On") AppendLine("Option Strict Off") AppendLine() } } override func generateHeader() { if let namespace = currentUnit.Namespace { Append("Namespace") Append(" ") generateIdentifier(namespace.Name, alwaysEmitNamespace: true) AppendLine() AppendLine() } } //done override func generateFooter() { if let namespace = currentUnit.Namespace { AppendLine() Append("End Namespace") AppendLine() } } //done override func generateImports() { super.generateImports() if currentUnit.Imports.Count > 0 { AppendLine() } } //done 21-5-2020 override func generateImport(_ imp: CGImport) { if imp.StaticClass != nil { Append("Imports ") generateIdentifier(imp.Namespace!.Name, alwaysEmitNamespace: true) AppendLine() } else { Append("Imports ") generateIdentifier(imp.Namespace!.Name, alwaysEmitNamespace: true) AppendLine() } } //done override func generateSingleLineCommentPrefix() { Append("' ") } //done 21-5-2020 override func generateInlineComment(_ comment: String) { if Dialect == .Mercury { Append("/* \(comment) */") } else { assert(false, "Inline comments are not supported on Visual Basic") } } // // Statements // //done override func generateBeginEndStatement(_ statement: CGBeginEndBlockStatement) { generateStatementsSkippingOuterBeginEndBlock(statement.Statements) AppendLine("") } //done 21-5-2020 override func generateIfElseStatement(_ statement: CGIfThenElseStatement) { Append("If ") generateExpression(statement.Condition) AppendLine(" Then") incIndent() generateStatementSkippingOuterBeginEndBlock(statement.IfStatement) decIndent() if let elseStatement = statement.ElseStatement { AppendLine("Else") incIndent() generateStatementSkippingOuterBeginEndBlock(elseStatement) decIndent() //Append("end")//done 21-5-2020 } AppendLine("End If") } override func generateStatementIndentedOrTrailingIfItsABeginEndBlock(_ statement: CGStatement) { AppendLine() incIndent() if let block = statement as? CGBeginEndBlockStatement { generateStatements(block.Statements) } else { generateStatement(statement) } decIndent() } //21-5-2020 //todo: support for other step than 1? (not supported by CGForToLoopStatement) override func generateForToLoopStatement(_ statement: CGForToLoopStatement) { InLoop = InLoop + 1 Loops.Push("For") Append("For ") generateIdentifier(statement.LoopVariableName) if let type = statement.LoopVariableType { Append(" As ") generateTypeReference(type) } Append(" = ") generateExpression(statement.StartValue) Append(" To ") generateExpression(statement.EndValue) if let step = statement.Step { Append(" Step ") if statement.Direction == CGLoopDirectionKind.Backward { if let step = step as? CGUnaryOperatorExpression, step.Operator == CGUnaryOperatorKind.Minus { generateExpression(step.Value) } else { generateExpression(CGUnaryOperatorExpression(step, CGUnaryOperatorKind.Minus)) } } else { generateExpression(step) } } else if statement.Direction == CGLoopDirectionKind.Backward { Append(" Step -1") } generateStatementIndentedOrTrailingIfItsABeginEndBlock(statement.NestedStatement) AppendLine("Next") Loops.Pop() InLoop = InLoop - 1 } //done 21-5-2020 override func generateForEachLoopStatement(_ statement: CGForEachLoopStatement) { InLoop = InLoop + 1 Loops.Push("For") Append("For Each ") generateSingleNameOrTupleWithNames(statement.LoopVariableNames) if let type = statement.LoopVariableType { Append(" As ") generateTypeReference(type) } Append(" In ") generateExpression(statement.Collection) generateStatementIndentedOrTrailingIfItsABeginEndBlock(statement.NestedStatement) AppendLine("Next") Loops.Pop() InLoop = InLoop - 1 } //done override func generateWhileDoLoopStatement(_ statement: CGWhileDoLoopStatement) { InLoop = InLoop + 1 Loops.Push("For") Append("Do While ") generateExpression(statement.Condition) generateStatementIndentedOrTrailingIfItsABeginEndBlock(statement.NestedStatement) AppendLine("Loop") Loops.Pop() InLoop = InLoop - 1 } //done 22-5-2020 override func generateDoWhileLoopStatement(_ statement: CGDoWhileLoopStatement) { InLoop = InLoop + 1 Loops.Push("For") Append("Do ") AppendLine() incIndent() generateStatementsSkippingOuterBeginEndBlock(statement.Statements) decIndent() Append("Loop While") if let notCondition = statement.Condition as? CGUnaryOperatorExpression, notCondition.Operator == CGUnaryOperatorKind.Not { generateExpression(notCondition.Value) } else { generateExpression(CGUnaryOperatorExpression.NotExpression(statement.Condition)) } AppendLine() Loops.Pop() InLoop = InLoop - 1 } //done 21-5-2020 (was marked out) override func generateInfiniteLoopStatement(_ statement: CGInfiniteLoopStatement) { InLoop = InLoop + 1 Loops.Push("For") Append("Do ") generateStatementIndentedOrTrailingIfItsABeginEndBlock(statement.NestedStatement) AppendLine("Loop") Loops.Pop() InLoop = InLoop - 1 } //done override func generateSwitchStatement(_ statement: CGSwitchStatement) { InLoop = InLoop + 1 //misuse because you can break here in a lot of languages Loops.Push("") Append("Select Case ") generateExpression(statement.Expression) AppendLine() incIndent() for c in statement.Cases { //Range would use "Case 1 To 5" Append("Case ") helpGenerateCommaSeparatedList(c.CaseExpressions) { self.generateExpression($0) } AppendLine(":") incIndent() generateStatementsSkippingOuterBeginEndBlock(c.Statements) decIndent() } if let defaultStatements = statement.DefaultCase, defaultStatements.Count > 0 { AppendLine("Case Else") incIndent() generateStatementsSkippingOuterBeginEndBlock(defaultStatements) decIndent() } decIndent() AppendLine("End Select") Loops.Pop() InLoop = InLoop - 1 } //done 21-5-2020 override func generateLockingStatement(_ statement: CGLockingStatement) { Append("SyncLock ") generateExpression(statement.Expression) generateStatementIndentedOrTrailingIfItsABeginEndBlock(statement.NestedStatement) AppendLine("End SyncLock") } //done 21-5-2020 override func generateUsingStatement(_ statement: CGUsingStatement) { Append("Using ") if let name = statement.Name { generateIdentifier(name) if let type = statement.`Type` { Append(" As ") generateTypeReference(type) } Append(" = ") } generateExpression(statement.Value) generateStatementIndentedOrTrailingIfItsABeginEndBlock(statement.NestedStatement) AppendLine("End Using") } //done 21-5-2020 override func generateAutoReleasePoolStatement(_ statement: CGAutoReleasePoolStatement) { Append("Using AutoReleasePool ") generateStatementIndentedOrTrailingIfItsABeginEndBlock(statement.NestedStatement) AppendLine("End Using ") } //done 22-5-2020 override func generateTryFinallyCatchStatement(_ statement: CGTryFinallyCatchStatement) { let finallyStatements = statement.FinallyStatements let catchBlocks = statement.CatchBlocks if (finallyStatements.Count + catchBlocks.Count) > 0 { AppendLine("Try") incIndent() } generateStatements(statement.Statements) if let catchBlocks = statement.CatchBlocks, catchBlocks.Count > 0 { AppendLine("Catch ") for b in catchBlocks { if let name = b.Name, let type = b.`Type` { generateIdentifier(name) Append(" As ") generateTypeReference(type) if let wn = b.Filter { Append(" When ") generateExpression(wn) } AppendLine("") incIndent() generateStatements(b.Statements) decIndent() } else { assert(catchBlocks.Count == 1, "Can only have a single Catch block, if there is no type filter") generateStatements(b.Statements) } } decIndent() } if let finallyStatements = statement.FinallyStatements, finallyStatements.Count > 0 { AppendLine("Finally") incIndent() generateStatements(finallyStatements) decIndent() } AppendLine("End Try") } //done override func generateReturnStatement(_ statement: CGReturnStatement) { if let value = statement.Value { Append("Return ") generateExpression(value) AppendLine() } else { AppendLine("Return") } } //done 21-5-2020 override func generateThrowExpression(_ statement: CGThrowExpression) { Append("Throw ") if let value = statement.Exception { generateExpression(value) } } //21-5-2020 //todo: everywhere you can break out need to be pushed and popped to create the correct statement override func generateBreakStatement(_ statement: CGBreakStatement) { if InLoop > 0{ let f = Loops.Pop() Loops.Push(f) if f != "" { Append("Exit ") AppendLine(f) } } else { let f = Methods.Pop() Methods.Push(f) if f != "" { Append("Exit ") AppendLine(f) } } } //21-5-2020 //todo: everywhere you can continue need to be pushed and popped to create the correct statement override func generateContinueStatement(_ statement: CGContinueStatement) { let f = Loops.Pop() Loops.Push(f) if (f != "") { Append("Continue ") AppendLine(f) } } //added and done, 21-5-2020 override func generateYieldExpression(_ statement: CGYieldExpression) { Append("Yield ") generateExpression(statement.Value) } //done override func generateVariableDeclarationStatement(_ statement: CGVariableDeclarationStatement) { Append("Dim ") generateIdentifier(statement.Name) if let type = statement.`Type` { Append(" As ") generateTypeReference(type) } if let value = statement.Value { Append(" = ") generateExpression(value) } AppendLine() } //done override func generateAssignmentStatement(_ statement: CGAssignmentStatement) { generateExpression(statement.Target) Append(" = ") generateExpression(statement.Value) AppendLine() } //done 21-5-2020 override func generateConstructorCallStatement(_ statement: CGConstructorCallStatement) { if let callSite = statement.CallSite { if callSite is CGInheritedExpression { generateExpression(callSite) Append(" ") } else if callSite is CGSelfExpression { // no-op } else { assert(false, "Unsupported call site for constructor call.") } } Append("New") if let name = statement.ConstructorName { Append(" ") Append(name) } Append("(") vbGenerateCallParameters(statement.Parameters) AppendLine(")") } //done override func generateStatementTerminator() { AppendLine() } // // Expressions // //done internal func vbGenerateCallSiteForExpression(_ expression: CGMemberAccessExpression) { if let callSite = expression.CallSite { generateExpression(callSite) Append(".") } } //done 21-5-2020 func vbGenerateCallParameters(_ parameters: List<CGCallParameter>) { for p in 0 ..< parameters.Count { let param = parameters[p] if p > 0 { Append(", ") } if let name = param.Name { //block named parameters added 21-5-2020 generateIdentifier(name) Append(": ") } generateExpression(param.Value) } } //done 21-5-2020 func vbGenerateAttributeParameters(_ parameters: List<CGCallParameter>) { for p in 0 ..< parameters.Count { let param = parameters[p] if p > 0 { Append(", ") } if let name = param.Name { generateIdentifier(name) Append(": ") } generateExpression(param.Value) } } /* override func generateNamedIdentifierExpression(_ expression: CGNamedIdentifierExpression) { // handled in base } */ //done 21-5-2020 override func generateAssignedExpression(_ expression: CGAssignedExpression) { generateExpression(expression.Value) if expression.Inverted { Append(" Is Nothing") } else { Append(" IsNot Nothing") } } //done 21-5-2020 override func generateSizeOfExpression(_ expression: CGSizeOfExpression) { Append("Len(") generateExpression(expression.Expression) Append(")") } //done 21-5-2020 override func generateTypeOfExpression(_ expression: CGTypeOfExpression) { Append("GetType(") //from RTL generateExpression(expression.Expression) Append(")") } //done override func generateDefaultExpression(_ expression: CGDefaultExpression) { Append("Nothing") } //done override func generateSelectorExpression(_ expression: CGSelectorExpression) { assert(false, "Not implemented yet") } //done override func generateTypeCastExpression(_ expression: CGTypeCastExpression) { if expression.ThrowsException { Append("CType(") generateExpression(expression.Expression) Append(", ") generateTypeReference(expression.TargetType) Append(")") } else { Append("TryCast(") generateExpression(expression.Expression) Append(", ") generateTypeReference(expression.TargetType) Append(")") } } //done override func generateInheritedExpression(_ expression: CGInheritedExpression) { Append("MyBase") } //done override func generateSelfExpression(_ expression: CGSelfExpression) { Append("Me") } //done override func generateNilExpression(_ expression: CGNilExpression) { if Dialect == .Mercury { Append("Null") } else { Append("Nothing") } } //done override func generatePropertyValueExpression(_ expression: CGPropertyValueExpression) { Append("value") } //done 21-5-2020 override func generateAwaitExpression(_ expression: CGAwaitExpression) { Append("Await ") generateExpression(expression.Expression) } //done 21-5-2020 override func generateAnonymousMethodExpression(_ method: CGAnonymousMethodExpression) { if method.Lambda { Append(vbKeywordForMethod(method, close: false)) Append("(") helpGenerateCommaSeparatedList(method.Parameters) { param in self.generateAttributes(param.Attributes, inline: true) self.generateParameterDefinition(param) } Append(") ") if method.Statements.Count == 1, let expression = method.Statements[0] as? CGExpression { generateExpression(expression) Methods.Pop() //single line has no End } else { AppendLine() incIndent() generateStatements(variables: method.LocalVariables) generateStatementsSkippingOuterBeginEndBlock(method.Statements) decIndent() AppendLine(vbKeywordForMethod(method, close: true)) } } else { Append(vbKeywordForMethod(method, close: false)) Append("(") if method.Parameters.Count > 0 { helpGenerateCommaSeparatedList(method.Parameters) { param in self.generateIdentifier(param.Name) if let type = param.`Type` { self.Append(" As ") self.generateTypeReference(type) } } } AppendLine(")") if let returnType = method.ReturnType, !returnType.IsVoid { Append(" As ") generateTypeReference(returnType) } incIndent() generateStatements(variables: method.LocalVariables) generateStatementsSkippingOuterBeginEndBlock(method.Statements) decIndent() AppendLine(vbKeywordForMethod(method, close: true)) } } //done 21-5-2020 override func generateAnonymousTypeExpression(_ type: CGAnonymousTypeExpression) { Append("New With {") helpGenerateCommaSeparatedList(type.Members) { m in self.generateIdentifier(m.Name) self.Append(" = ") if let member = m as? CGAnonymousPropertyMemberDefinition { self.generateExpression(member.Value) } } AppendLine("}") } //done 21-5-2020 override func generatePointerDereferenceExpression(_ expression: CGPointerDereferenceExpression) { if Dialect == .Mercury { generateExpression(expression.PointerExpression) Append(".Dereference^") } else { assert(false, "Visual Basic does not support pointers") } } /* override func generateUnaryOperatorExpression(_ expression: CGUnaryOperatorExpression) { // handled in base } */ override func generateBinaryOperatorExpression(_ expression: CGBinaryOperatorExpression) { switch (expression.Operator) { case .AddEvent: Append("AddHandler ") generateExpression(expression.LefthandValue) Append(", ") generateExpression(expression.RighthandValue) case .RemoveEvent: Append("RemoveHandler ") generateExpression(expression.LefthandValue) Append(", ") generateExpression(expression.RighthandValue) case .Equals: fallthrough case .NotEquals: if let nilExpression = (expression.RighthandValue as? CGNilExpression) { if expression.Operator == CGBinaryOperatorKind.NotEquals { Append("Not ") } Append("(") generateExpression(expression.LefthandValue) Append(")") Append(" Is ") generateNilExpression(nilExpression); } else { fallthrough } default: super.generateBinaryOperatorExpression(expression) } } //done 21-5-2020 override func generateUnaryOperator(_ `operator`: CGUnaryOperatorKind) { switch (`operator`) { case .Plus: Append("+") case .Minus: Append("-") case .BitwiseNot: Append("Not ") case .Not: Append("Not ") case .AddressOf: Append("AddressOf ") case .ForceUnwrapNullable: if Dialect == .Standard { // Do nothing for Standard VB.NET dialect } else { Append("{ NOT SUPPORTED }") } } } //done //todo: add and remove event works completely different in VB override func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) { switch (`operator`) { case .Concat: Append("&") case .Addition: Append("+") case .Subtraction: Append("-") case .Multiplication: Append("*") case .Division: Append("/") case .LegacyPascalDivision: Append("/") case .Modulus: Append("Mod") case .Equals: Append("=") case .NotEquals: Append("<>") case .LessThan: Append("<") case .LessThanOrEquals: Append("<=") case .GreaterThan: Append(">") case .GreatThanOrEqual: Append(">=") case .LogicalAnd: Append("AndAlso") case .LogicalOr: Append("OrElse") case .LogicalXor: Append("Xor") case .Shl: Append("<<") case .Shr: Append(">>") case .BitwiseAnd: Append("And") case .BitwiseOr: Append("Or") case .BitwiseXor: Append("Xor") //case .Implies: //case .Is: Append("Is") //case .IsNot: Append("IsNot") //case .In: Append("in") //case .NotIn: case .Assign: Append("=") case .AssignAddition: Append("+=") case .AssignSubtraction: Append("-=") case .AssignMultiplication: Append("*=") case .AssignDivision: Append("/=") case .AddEvent: break // handled separately case .RemoveEvent: break // handled separately default: Append("/* NOT SUPPORTED */") } } //done 21-5-2020 override func generateIfThenElseExpression(_ expression: CGIfThenElseExpression) { Append("(if(") generateExpression(expression.Condition) Append(", ") generateExpression(expression.IfExpression) if let elseExpression = expression.ElseExpression { Append(", ") generateExpression(elseExpression) } Append(")") } //done override func generateFieldAccessExpression(_ expression: CGFieldAccessExpression) { vbGenerateCallSiteForExpression(expression) generateIdentifier(expression.Name) } //done override func generateEventAccessExpression(_ expression: CGEventAccessExpression) { generateFieldAccessExpression(expression) Append("Event") } override func generateArrayElementAccessExpression(_ expression: CGArrayElementAccessExpression) { generateExpression(expression.Array) Append("(") for p in 0 ..< expression.Parameters.Count { let param = expression.Parameters[p] if p > 0 { Append(", ") } generateExpression(param) } Append(")") } //done override func generateMethodCallExpression(_ method: CGMethodCallExpression) { //Append("Call ") vbGenerateCallSiteForExpression(method) generateIdentifier(method.Name) generateGenericArguments(method.GenericArguments) Append("(") vbGenerateCallParameters(method.Parameters) Append(")") } //done override func generateNewInstanceExpression(_ expression: CGNewInstanceExpression) { Append("New ") generateExpression(expression.`Type`) /*if let bounds = expression.ArrayBounds, bounds.Count > 0 { Append("[") helpGenerateCommaSeparatedList(bounds) { boundExpression in self.generateExpression(boundExpression) } Append("]") } else {*/ Append("(") vbGenerateCallParameters(expression.Parameters) Append(")") //} } //done 21-5-2020 override func generatePropertyAccessExpression(_ property: CGPropertyAccessExpression) { vbGenerateCallSiteForExpression(property) generateIdentifier(property.Name) if let params = property.Parameters, params.Count > 0 { Append("(") vbGenerateCallParameters(property.Parameters) Append(")") } } /* override func generateEnumValueAccessExpression(_ expression: CGEnumValueAccessExpression) { // handled in base } */ //done internal func vbEscapeCharactersInStringLiteral(_ string: String) -> String { let result = StringBuilder() let len = string.Length for i in 0 ..< len { let ch = string[i] switch ch { case "\"": result.Append("\"\"") default: result.Append(ch) } } return result.ToString() } //done override func generateStringLiteralExpression(_ expression: CGStringLiteralExpression) { Append("\"\(vbEscapeCharactersInStringLiteral(expression.Value))\"") } //done 22-5-2020 override func generateCharacterLiteralExpression(_ expression: CGCharacterLiteralExpression) { Append("ChrW(\(expression.Value))") } //done 21-5-2020 override func generateIntegerLiteralExpression(_ literalExpression: CGIntegerLiteralExpression) { switch literalExpression.Base { case 16: Append("&H"+literalExpression.StringRepresentation(base:16)) case 10: Append(literalExpression.StringRepresentation(base:10)) case 8: Append("&O"+literalExpression.StringRepresentation(base:8)) case 2: Append("&B"+literalExpression.StringRepresentation(base:2)) default: throw Exception("Base \(literalExpression.Base) integer literals are not currently supported for Visual Basic.") } } /* override func generateFloatLiteralExpression(_ literalExpression: CGFloatLiteralExpression) { // handled in base } */ //done 21-5-2020 override func generateArrayLiteralExpression(_ array: CGArrayLiteralExpression) { Append("{") helpGenerateCommaSeparatedList(array.Elements) { e in self.generateExpression(e) } Append("}") } //done 21-5-2020 override func generateSetLiteralExpression(_ expression: CGSetLiteralExpression) { assert(false, "Sets are not supported") } //done 21-5-2020 override func generateDictionaryExpression(_ expression: CGDictionaryLiteralExpression) { assert(false, "generateDictionaryExpression is not supported in Visual Basic") } //done 21-5-2020 override func generateTupleExpression(_ tuple: CGTupleLiteralExpression) { Append("(") helpGenerateCommaSeparatedList(tuple.Members) { e in self.generateExpression(e) } Append(")") } //done 21-5-2020 override func generateSetTypeReference(_ type: CGSetTypeReference, ignoreNullability: Boolean = false) { assert(false, "Sets are not supported") } override func generateSequenceTypeReference(_ sequence: CGSequenceTypeReference, ignoreNullability: Boolean = false) { Append("ISequence(Of ") generateTypeReference(sequence.`Type`) Append(")") if !ignoreNullability { vbGenerateSuffixForNullability(sequence) } } // // Type Definitions // //done override func generateAttribute(_ attribute: CGAttribute, inline: Boolean) { Append("<") generateAttributeScope(attribute) generateTypeReference(attribute.`Type`) if let parameters = attribute.Parameters, parameters.Count > 0 { Append("(") vbGenerateAttributeParameters(parameters) Append(")") } Append(">") if let comment = attribute.Comment { Append(" ") generateSingleLineCommentStatement(comment) } else { if inline { Append(" ") } else { AppendLine() } } } //done func vbGenerateTypeVisibilityPrefix(_ visibility: CGTypeVisibilityKind) { switch visibility { case .Unspecified: break /* no-op */ case .Unit: Append("Private ") case .Assembly: Append("Friend ") case .Public: Append("Public ") } } //done func vbGenerateMemberTypeVisibilityPrefix(_ visibility: CGMemberVisibilityKind) { switch visibility { case .Unspecified: break /* no-op */ case .Private: Append("Private ") case .Unit: fallthrough case .UnitOrProtected: fallthrough case .UnitAndProtected: fallthrough case .Assembly: fallthrough case .AssemblyAndProtected: Append("Friend ") case .AssemblyOrProtected: Append("Protected Friend") case .Protected: Append("Protected ") case .Published: fallthrough case .Public: Append("Public ") } } //done func vbGenerateStaticPrefix(_ isStatic: Boolean) { if isStatic { Append("Shared ") } } func vbGeneratePartialPrefix(_ isStatic: Boolean) { if isStatic { Append("Partial ") } } func vbGenerateAbstractPrefix(_ isAbstract: Boolean) { if isAbstract { Append("MustInherit ") } } //done 21-5-2020 func vbGenerateSealedPrefix(_ isSealed: Boolean) { if isSealed { Append("NotInherirable ") } } //done 21-5-2020 func vbGenerateVirtualityPrefix(_ member: CGMemberDefinition) { switch member.Virtuality { //case .None case .Virtual: Append("MustOverride ") case .Abstract: Append("MustOverride ") case .Override: Append("Overrides ") case .Final: Append("NotOverridable ") default: } if member.Reintroduced { Append("Shadows ") } } //done 21-5-2020 override func generateParameterDefinition(_ param: CGParameterDefinition) { generateParameterDefinition(param, emitExternal: false) } func generateParameterDefinition(_ param: CGParameterDefinition, emitExternal: Boolean, externalName: String? = nil) { if Dialect == .Mercury { switch param.Modifier { case .Var: Append("ByRef ") case .Const: Append("In ") case .Out: Append("Out ") case .Params: Append("ParamArray ") case .In: } } else { switch param.Modifier { case .Var: Append("ByRef ") case .Const: Append("<In> ByRef ") case .Out: Append("<Out> ByRef ") case .Params: Append("ParamArray ") case .In: } } if emitExternal, let externalName = externalName ?? param.ExternalName { if externalName != param.Name { generateIdentifier(externalName) Append(" ") } }/* else if emitExternal { Append("_ ") }*/ generateIdentifier(param.Name) if let type = param.Type { Append(" As ") generateTypeReference(type) } if let defaultValue = param.DefaultValue { Append(" = ") generateExpression(defaultValue) } } //done 21-5-2020 func vbGenerateDefinitionParameters(_ parameters: List<CGParameterDefinition>, firstExternalName: String? = nil) { for p in 0 ..< parameters.Count { let param = parameters[p] if p > 0 { Append(", ") param.startLocation = currentLocation } else { param.startLocation = currentLocation } generateParameterDefinition(param, emitExternal: true, externalName: p == 0 ? firstExternalName : nil) param.endLocation = currentLocation } } //Done 21-5-2020 func vbGenerateGenericParameters(_ parameters: List<CGGenericParameterDefinition>?) { if let parameters = parameters, parameters.Count > 0 { Append("(Of ") helpGenerateCommaSeparatedList(parameters) { param in self.generateIdentifier(param.Name) //todo: constraints } Append(")") } } //Done 21-5-2020 func vbGenerateGenericConstraints(_ parameters: List<CGGenericParameterDefinition>?) { if let parameters = parameters, parameters.Count > 0 { var needsWhere = true for param in parameters { if let constraints = param.Constraints, constraints.Count > 0 { if needsWhere { self.Append(", ") needsWhere = false } else { self.Append(", ") } self.generateIdentifier(param.Name) self.Append(": ") self.helpGenerateCommaSeparatedList(constraints) { constraint in if let constraint = constraint as? CGGenericHasConstructorConstraint { self.Append("new") } else if let constraint2 = constraint as? CGGenericIsSpecificTypeConstraint { self.generateTypeReference(constraint2.`Type`) } else if let constraint2 = constraint as? CGGenericIsSpecificTypeKindConstraint { switch constraint2.Kind { case .Class: self.Append("Class") case .Struct: self.Append("Structure") case .Interface: self.Append("Interface") } } } } } } } //Done func vbGenerateAncestorList(_ type: CGClassOrStructTypeDefinition, keyword: String = "Inherits") { if type.Ancestors.Count > 0 { Append(keyword) Append(" ") for a in 0 ..< type.Ancestors.Count { if let ancestor = type.Ancestors[a] { if a > 0 { Append(", ") } generateTypeReference(ancestor) } } AppendLine() } if type.ImplementedInterfaces.Count > 0 { Append("Implements ") for a in 0 ..< type.ImplementedInterfaces.Count { if let interface = type.ImplementedInterfaces[a] { if a > 0 { Append(", ") } generateTypeReference(interface) } } AppendLine() } } //Done 21-5-2020 //Todo: aliases must be on top of files -> after imports, before the rest of the code override func generateAliasType(_ type: CGTypeAliasDefinition) { Append("Imports ") generateIdentifier(type.Name) Append(" = ") generateTypeReference(type.ActualType) generateStatementTerminator() } override func generateBlockType(_ block: CGBlockTypeDefinition) { if block.IsPlainFunctionPointer { AppendLine("<FunctionPointer> _") } vbGenerateTypeVisibilityPrefix(block.Visibility) Append("Delegate ") if let returnType = block.ReturnType, !returnType.IsVoid { Append("Function ") } else { Append("Sub ") } generateIdentifier(block.Name) Append("(") if let parameters = block.Parameters, parameters.Count > 0 { vbGenerateDefinitionParameters(parameters) } Append(")") if let returnType = block.ReturnType, !returnType.IsVoid { Append(" As ") generateTypeReference(returnType) } AppendLine() } //Done 21-5-2020 override func generateEnumType(_ type: CGEnumTypeDefinition) { vbGenerateTypeVisibilityPrefix(type.Visibility) Append("Enum ") generateIdentifier(type.Name) if let baseType = type.BaseType { Append(" As ") generateTypeReference(baseType) } AppendLine() incIndent() for m in type.Members { if let member = m as? CGEnumValueDefinition { self.generateAttributes(member.Attributes, inline: true) self.generateIdentifier(member.Name) if let value = member.Value { self.Append(" = ") self.generateExpression(value) } AppendLine() } } decIndent() AppendLine("End Enum ") } //done 22-5-2020 override func generateClassTypeStart(_ type: CGClassTypeDefinition) { vbGenerateTypeVisibilityPrefix(type.Visibility) vbGenerateStaticPrefix(type.Static) vbGeneratePartialPrefix(type.Partial) vbGenerateAbstractPrefix(type.Abstract) vbGenerateSealedPrefix(type.Sealed) Append("Class ") generateIdentifier(type.Name) vbGenerateGenericParameters(type.GenericParameters) vbGenerateGenericConstraints(type.GenericParameters) AppendLine() incIndent() vbGenerateAncestorList(type) AppendLine() } //done 22-5-2020 override func generateClassTypeEnd(_ type: CGClassTypeDefinition) { vbGenerateNestedTypes(type) decIndent() AppendLine() AppendLine("End Class") } //done 22-5-2020 override func generateStructTypeStart(_ type: CGStructTypeDefinition) { vbGenerateTypeVisibilityPrefix(type.Visibility) vbGenerateStaticPrefix(type.Static) vbGenerateAbstractPrefix(type.Abstract) vbGenerateSealedPrefix(type.Sealed) Append("Structure ") generateIdentifier(type.Name) vbGenerateGenericParameters(type.GenericParameters) vbGenerateGenericConstraints(type.GenericParameters) AppendLine() incIndent() vbGenerateAncestorList(type) AppendLine() } //done 22-5-2020 override func generateStructTypeEnd(_ type: CGStructTypeDefinition) { vbGenerateNestedTypes(type) decIndent() AppendLine() AppendLine("End Structure") } internal func vbGenerateNestedTypes(_ type: CGTypeDefinition) { for m in type.Members { if let nestedType = m as? CGNestedTypeDefinition { AppendLine() nestedType.`Type`.Name = nestedType.Name // Todo: nasty hack. generateTypeDefinition(nestedType.`Type`) } } } //done 22-5-2020 override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) { vbGenerateTypeVisibilityPrefix(type.Visibility) vbGenerateSealedPrefix(type.Sealed) Append("Interface ") generateIdentifier(type.Name) vbGenerateGenericParameters(type.GenericParameters) vbGenerateGenericConstraints(type.GenericParameters) AppendLine() incIndent() vbGenerateAncestorList(type) AppendLine() } //done 22-5-2020 override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) { vbGenerateNestedTypes(type) decIndent() AppendLine("End Interface") } override func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) { vbGenerateTypeVisibilityPrefix(type.Visibility) Append(" Class ") generateIdentifier(type.Name) AppendLine() incIndent() vbGenerateAncestorList(type, keyword: "Extends") AppendLine() } override func generateExtensionTypeEnd(_ type: CGExtensionTypeDefinition) { Append("End Class ") } // // Type Members // //done 22-5-2020 internal func vbKeywordForMethod(_ method: CGMethodDefinition, close: Boolean) -> String { if close { Methods.Pop() if let returnType = method.ReturnType, !returnType.IsVoid { return "End Function" } else { return "End Sub" } } else { if let returnType = method.ReturnType, !returnType.IsVoid { Methods.Push("Function") return "Function" } else { Methods.Push("Sub") return "Sub" } } } //done 22-5-2020 internal func vbKeywordForMethod(_ method: CGMethodLikeMemberDefinition, close: Boolean) -> String { if close { Methods.Pop() if let returnType = method.ReturnType, !returnType.IsVoid { return "End Function" } else { return "End Sub" } } else { if let returnType = method.ReturnType, !returnType.IsVoid { Methods.Push("Function") return "Function" } else { Methods.Push("Sub") return "Sub" } } } //done 22-5-2020 internal func vbKeywordForMethod(_ method: CGAnonymousMethodExpression, close: Boolean) -> String { if close { Methods.Pop() if let returnType = method.ReturnType, !returnType.IsVoid { return "End Function" } else { return "End Sub" } } else { if let returnType = method.ReturnType, !returnType.IsVoid { Methods.Push("Function") return "Function" } else { Methods.Push("Sub") return "Sub" } } } //done 22-5-2020 func vbGenerateImplementedInterface(_ member: CGMemberDefinition) { if let implementsInterface = member.ImplementsInterface { Append(" Implements ") generateTypeReference(implementsInterface) Append(".") if let implementsMember = member.ImplementsInterfaceMember { generateIdentifier(implementsMember) } else { generateIdentifier(member.Name) } } } //done 22-5-2020 //todo: P/Invoke declare override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) { if type is CGInterfaceTypeDefinition { vbGenerateStaticPrefix(method.Static && !type.Static) } else { vbGenerateMemberTypeVisibilityPrefix(method.Visibility) vbGenerateStaticPrefix(method.Static && !type.Static) if method.Awaitable { Append("Async ") } /*if method.External { Append("extern ") }*/ vbGenerateVirtualityPrefix(method) } Append(vbKeywordForMethod(method, close: false)) Append(" ") generateIdentifier(method.Name) vbGenerateGenericParameters(method.GenericParameters) Append("(") vbGenerateDefinitionParameters(method.Parameters) Append(")") if let returnType = method.ReturnType, !returnType.IsVoid { Append(" As ") returnType.startLocation = currentLocation generateTypeReference(returnType) returnType.endLocation = currentLocation } if let handlesExpression = method.Handles { Append(" Handles ") generateExpression(handlesExpression) } vbGenerateImplementedInterface(method) AppendLine() //vbGenerateGenericConstraints(method.GenericParameters) if type is CGInterfaceTypeDefinition || method.Virtuality == CGMemberVirtualityKind.Abstract || method.External || definitionOnly { return } incIndent() generateStatements(variables: method.LocalVariables) generateStatements(method.Statements) decIndent() AppendLine(vbKeywordForMethod(method, close: true)) } //done 22-5-2020 override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) { vbGenerateConstructorHeader(ctor, type: type, methodKeyword: "constructor") if type is CGInterfaceTypeDefinition || ctor.Virtuality == CGMemberVirtualityKind.Abstract || ctor.External || definitionOnly { return } vbGenerateMethodBody(ctor, type: type) vbGenerateMethodFooter(ctor) } //done 22-5-2020 internal func vbGenerateConstructorHeader(_ method: CGMethodLikeMemberDefinition, type: CGTypeDefinition, methodKeyword: String) { vbGenerateMethodHeader("New", method: method) } //done 22-5-2020 internal func vbGenerateMethodHeader(_ methodName: String, method: CGMethodLikeMemberDefinition) { vbGenerateMemberTypeVisibilityPrefix(method.Visibility) vbGenerateVirtualityModifiders(method) if method.Partial { assert(false, "Visual Basic does not support Partial Methods") Append("Partial ") } if method.Async { Append("Async ") } if method.Static { Append("Shared ") } if method.Overloaded { Append(" Overrides ") } Append(vbKeywordForMethod(method, close: false)) Append(" ") Append(methodName) if let ctor = method as? CGConstructorDefinition, length(ctor.Name) > 0 { Append(" ") Append(ctor.Name) } Append("(") if let parameters = method.Parameters, parameters.Count > 0 { vbGenerateDefinitionParameters(parameters) } Append(")") if let returnType = method.ReturnType, !returnType.IsVoid { Append(" As ") returnType.startLocation = currentLocation generateTypeReference(returnType) returnType.endLocation = currentLocation } vbGenerateImplementedInterface(method) if method.Locked { AppendLine() Append("SyncLock ") if let lockedOn = method.LockedOn { generateExpression(lockedOn) } else { Append("Me") } } AppendLine() } //done 22-5-2020 func vbGenerateVirtualityModifiders(_ member: CGMemberDefinition) { switch member.Virtuality { //case .None case .Virtual: Append("Overridable ") case .Abstract: Append("Abstract ") case .Override: Append("Overrides ") case .Final: Append("NotOverridable ") default: } if member.Reintroduced { Append("Reintroduce ") } } //done 22-5-2020 internal func vbGenerateMethodFooter(_ method: CGMethodLikeMemberDefinition) { AppendLine() if method.Locked { AppendLine("End SyncLock ") } AppendLine(vbKeywordForMethod(method, close: true)) } //done 22-5-2020 internal func vbGenerateMethodBody(_ method: CGMethodLikeMemberDefinition, type: CGTypeDefinition?) { if let localVariables = method.LocalVariables, localVariables.Count > 0 { for v in localVariables { if let type = v.`Type` { Append("Dim ") generateIdentifier(v.Name) Append(" As ") generateTypeReference(type) if let val = v.Value { generateIdentifier(v.Name) Append(" := ") generateExpressionStatement(val) } AppendLine() } } } if let localTypes = method.LocalTypes, localTypes.Count > 0 { assert("Local type definitions are not supported in Visual Basic") } if let localMethods = method.LocalMethods, localMethods.Count > 0 { for m in localMethods { //local methods as anonymous method variables Append("Dim ") Append(method.Name) Append(" = ") vbGenerateMethodHeader("", method: m) incIndent() vbGenerateMethodBody(m, type: nil) decIndent() vbGenerateMethodFooter(m) AppendLine("") } } AppendLine("") generateStatementsSkippingOuterBeginEndBlock(method.Statements) AppendLine() } //done 22-5-2020 override func generateDestructorDefinition(_ dtor: CGDestructorDefinition, type: CGTypeDefinition) { assert(false, "Destructor is not supported in Visual Basic") } //done 22-5-2020 override func generateFinalizerDefinition(_ finalizer: CGFinalizerDefinition, type: CGTypeDefinition) { AppendLine("Protected Overrides Sub Finalize()") vbGenerateMethodBody(finalizer, type: type) AppendLine("End Sub") } //done override func generateFieldDefinition(_ field: CGFieldDefinition, type: CGTypeDefinition) { vbGenerateMemberTypeVisibilityPrefix(field.Visibility) vbGenerateStaticPrefix(field.Static && !type.Static) if field.Constant { Append("Const ") } else { if field.Visibility == .Unspecified { Append("Dim ") } } if field.WithEvents { Append("WithEvents ") } generateIdentifier(field.Name) if let type = field.`Type` { Append(" As ") //vbGenerateStorageModifierPrefix(type) generateTypeReference(type) } else { } if let value = field.Initializer { Append(" = ") generateExpression(value) } AppendLine() } //done 22-5-2020 override func generatePropertyDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) { if !(type is CGInterfaceTypeDefinition) { vbGenerateMemberTypeVisibilityPrefix(property.Visibility) vbGenerateStaticPrefix(property.Static) } if property.ReadOnly || (property.SetStatements == nil && property.SetExpression == nil && (property.GetStatements != nil || property.GetExpression != nil)) { Append("ReadOnly ") } else { if property.WriteOnly || (property.GetStatements == nil && property.GetExpression == nil && (property.SetStatements != nil || property.SetExpression != nil)) { Append("WriteOnly ") } } if property.Default { Append("Default ") } Append("Property ") generateIdentifier(property.Name) if let params = property.Parameters, params.Count > 0 { Append("(") vbGenerateDefinitionParameters(params) Append(")") } if let type = property.`Type` { Append(" As ") generateTypeReference(type) } vbGenerateImplementedInterface(property) if property.GetStatements == nil && property.SetStatements == nil && property.GetExpression == nil && property.SetExpression == nil { if let value = property.Initializer { Append(" = ") generateExpression(value) } AppendLine() } else { if definitionOnly { return } AppendLine() incIndent() if let getStatements = property.GetStatements { AppendLine("Get") incIndent() generateStatementsSkippingOuterBeginEndBlock(getStatements) decIndent() AppendLine("End Get") } else if let getExpresssion = property.GetExpression { AppendLine("Get") incIndent() generateStatement(CGReturnStatement(getExpresssion)) decIndent() AppendLine("End Get") } else { AppendLine("WriteOnly") } if let setStatements = property.SetStatements { AppendLine("Set") incIndent() generateStatementsSkippingOuterBeginEndBlock(setStatements) decIndent() AppendLine("End Set") } else if let setExpression = property.SetExpression { AppendLine("Set") incIndent() generateStatement(CGAssignmentStatement(setExpression, CGPropertyValueExpression.PropertyValue)) decIndent() AppendLine("End Set") } decIndent() Append("End Property") AppendLine() } } //done override func generateEventDefinition(_ event: CGEventDefinition, type: CGTypeDefinition) { vbGenerateMemberTypeVisibilityPrefix(event.Visibility) vbGenerateStaticPrefix(event.Static && !type.Static) vbGenerateVirtualityPrefix(event) Append("Event ") generateIdentifier(event.Name) if let type = event.`Type` { Append(" As ") generateTypeReference(type) } vbGenerateImplementedInterface(event) AppendLine() } //todo: implement override func generateCustomOperatorDefinition(_ customOperator: CGCustomOperatorDefinition, type: CGTypeDefinition) { } //todo: implement override func generateNestedTypeDefinition(_ member: CGNestedTypeDefinition, type: CGTypeDefinition) { } // // Type References // func vbGenerateSuffixForNullability(_ type: CGTypeReference) { // same as C#! if type.DefaultNullability == CGTypeNullabilityKind.NotNullable || (type.Nullability == CGTypeNullabilityKind.NullableNotUnwrapped && Dialect == .Mercury) { //Append("/*default not null*/") if type.Nullability == CGTypeNullabilityKind.NullableUnwrapped || type.Nullability == CGTypeNullabilityKind.NullableNotUnwrapped { Append("?") } } else { //Append("/*default nullable*/") if type.Nullability == CGTypeNullabilityKind.NotNullable { //Append("/*not null*/") if Dialect == .Mercury { Append("!") } } } } /* override func generateNamedTypeReference(_ type: CGNamedTypeReference) { // handled in base } */ //done 21-5-2020 override func generateGenericArguments(_ genericArguments: List<CGTypeReference>?) { if let genericArguments = genericArguments, genericArguments.Count > 0 { Append("(") Append("Of ") for p in 0 ..< genericArguments.Count { let param = genericArguments[p] if p > 0 { Append(",") } generateTypeReference(param, ignoreNullability: false) } Append(")") } } //done 22-5-2020 override func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) { switch (type.Kind) { case .Int: Append("Integer") case .UInt: Append("UInteger") case .Int8: Append("SByte") case .UInt8: Append("Byte") case .Int16: Append("Short") case .UInt16: Append("UShort") case .Int32: Append("Integer") case .UInt32: Append("UInteger") case .Int64: Append("Long") case .UInt64: Append("ULong") case .IntPtr: Append("IntPtr") case .UIntPtr: Append("UIntPtr") case .Single: Append("Single") case .Double: Append("Double") case .Boolean: Append("Boolean") case .String: Append("String") case .AnsiChar: Append("AnsiChar") case .UTF16Char: Append("Char") case .UTF32Char: Append("UInt32") case .Dynamic: Append("Dynamic") case .InstanceType: Append("") case .Void: Append("") case .Object: Append("Object") case .Class: Append("") } } override func generateIntegerRangeTypeReference(_ type: CGIntegerRangeTypeReference, ignoreNullability: Boolean = false) { assert(false, "Integer ranges are not supported by Visual Basic") } override func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) { if Dialect == .Mercury { let block = type.Block if block.IsPlainFunctionPointer { Append("<FunctionPointer> ") } if let returnType = block.ReturnType, !returnType.IsVoid { Append("Function ") } else { Append("Sub ") } Append("(") if let parameters = block.Parameters, parameters.Count > 0 { vbGenerateDefinitionParameters(parameters) } Append(")") if let returnType = block.ReturnType, !returnType.IsVoid { Append(" As ") generateTypeReference(returnType) } } else { assert(false, "Inline Block Type References are not supported by Visual Basic") } } //done 22-5-2020 override func generatePointerTypeReference(_ type: CGPointerTypeReference) { if Dialect == .Mercury { if (type.`Type` as? CGPredefinedTypeReference)?.Kind == CGPredefinedTypeKind.Void { Append("Ptr") } else { Append("Ptr(Of ") generateTypeReference(type.`Type`) Append(")") } } else { assert(false, "Pointers are not supported by Visual Basic") } } //done 22-5-2020 override func generateKindOfTypeReference(_ type: CGKindOfTypeReference, ignoreNullability: Boolean = false) { if Dialect == .Mercury { Append("Dynamic(Of ") generateTypeReference(type.`Type`) Append(")") if !ignoreNullability { vbGenerateSuffixForNullability(type) } } else { assert(false, "Kind Of Type References are not supported by Visual Basic") } } //done 22-5-2020 override func generateTupleTypeReference(_ type: CGTupleTypeReference, ignoreNullability: Boolean = false) { Append("Tuple (Of ") for m in 0 ..< type.Members.Count { if m > 0 { Append(", ") } generateTypeReference(type.Members[m]) } Append(")") } //done 22-5-2020 override func generateArrayTypeReference(_ array: CGArrayTypeReference, ignoreNullability: Boolean = false) { generateTypeReference(array.`Type`) Append("()") if let bounds = array.Bounds, bounds.Count > 0 { for b in 1 ..< bounds.Count { Append("()") } } } //done 22-5-2020 override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) { Append("Dictionary(Of ") generateTypeReference(type.KeyType) Append(", ") generateTypeReference(type.ValueType) Append(")") } }
28.572181
228
0.681523
fe109f36b598c8b90161ad6b78304c0ec1cdf614
2,483
// // NormalCell.swift // LiveBroadcast // // Created by 许鹏程 on 2019/5/23. // Copyright © 2019 许鹏程. All rights reserved. // import UIKit import Kingfisher class NormalCell: BaseCell { //房间名 @objc let leftLabel : UILabel = UILabel() @objc override var model : AnchorModel?{ didSet{ super.model = model //房间名 leftLabel.text = model?.room_name } } override init(frame: CGRect) { super.init(frame: frame) setUp() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension NormalCell{ func setUp(){ let bottomImg = UIImageView() self.addSubview(bottomImg) bottomImg.image = UIImage(named: "home_live_cate_normal") bottomImg.snp.makeConstraints { (make) in make.bottom.equalTo(-5) make.left.equalTo(0) } bottomImg.sizeToFit() self.addSubview(leftLabel) leftLabel.font = UIFont.systemFont(ofSize: 11) leftLabel.text = "iOS开发大牛许鹏程" leftLabel.snp.makeConstraints { (make) in make.top.equalTo(bottomImg.snp.top) make.left.equalTo(bottomImg.snp.right).offset(2) make.right.equalTo(-1) } // leftLabel.backgroundColor = .red leftLabel.numberOfLines = 0 leftLabel.textColor = UIColor.gray self.addSubview(imageView) imageView.image = UIImage(named: "Img_default") imageView.snp.makeConstraints { (make) in make.top.left.right.equalTo(0) make.bottom.equalTo(-22) } imageView.layer.cornerRadius = 5 imageView.layer.masksToBounds = true self.addSubview(anchorLabel) anchorLabel.text = "iOS大牛许鹏程" anchorLabel.textColor = UIColor.white anchorLabel.font = UIFont.systemFont(ofSize: 11) anchorLabel.snp.makeConstraints { (make) in make.bottom.equalTo(leftLabel.snp.top).offset(-5) make.left.equalTo(2) } self.addSubview(onlineBtn) onlineBtn.setImage(UIImage(named: "Image_online"), for: .normal) onlineBtn.setTitle("666", for: .normal) onlineBtn.titleLabel?.font = UIFont.systemFont(ofSize: 11) onlineBtn.snp.makeConstraints { (make) in make.right.equalTo(-2) make.centerY.equalTo(anchorLabel) } } }
29.211765
72
0.597261
f579e3402e7d54a3e5efca6de67be615ddb5d30d
634
// // UserCollectionViewCell.swift // TableViewCompatible // // Created by Fredrik Nannestad on 31/01/2017. // Copyright © 2017 Fredrik Nannestad. All rights reserved. // import UIKit import CollectionAndTableViewCompatible class UserCollectionViewCell: UICollectionViewCell, Configurable { @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var userNameLabel: UILabel! var model: UserCellModel? func configure(withModel model: UserCellModel) { self.model = model userImageView.image = UIImage(named: model.imageName) userNameLabel.text = model.userName } }
25.36
66
0.722397
0a564f8eb09cd66662832f4868b6e850a99c08fd
233
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for in a { { } func g< { extension NSData { class case c, let f
17.923077
87
0.733906
ff25990fec18873e0c11d7626162f27e41d61957
1,058
// // Copyright (C) 2005-2020 Alfresco Software Limited. // // This file is part of the Alfresco Content Mobile iOS App. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit class BrowseSectionCollectionReusableView: UICollectionReusableView { @IBOutlet weak var separator: UIView! func applyTheme(_ currentTheme: PresentationTheme?) { guard let currentTheme = currentTheme else { return } backgroundColor = currentTheme.surfaceColor separator.backgroundColor = currentTheme.onSurface15Color } }
35.266667
76
0.741966
6769d55a0b6a008d6b79c6068ecfbe49d3289802
3,842
// // ViewPlaceholder.swift // ZeroMessger // // Created by Sandeep Mukherjee on 5/22/20. // Copyright © 2020 Sandeep Mukherjee. All rights reserved. // import UIKit enum ViewPlaceholderPriority: CGFloat { case low = 0.1 case medium = 0.5 case high = 1.0 } enum ViewPlaceholderPosition { case top case center } enum ViewPlaceholderTitle: String { case denied = "Zero doesn't have access to your contacts" case empty = "You don't have any Zero Users yet." case emptyChat = "You don't have any active conversations yet." } enum ViewPlaceholderSubtitle: String { case denied = "Please go to your iPhone Settings –– Privacy –– Contacts. Then select ON for Zero." case empty = "You can invite your friends to Flacon Messenger at the Contacts tab " case emptyChat = "You can select somebody in Contacts, and send your first message." } class ViewPlaceholder: UIView { var title = UILabel() var subtitle = UILabel() var placeholderPriority: ViewPlaceholderPriority = .low override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear translatesAutoresizingMaskIntoConstraints = false title.font = .systemFont(ofSize: 18) title.textColor = ThemeManager.currentTheme().generalSubtitleColor title.textAlignment = .center title.numberOfLines = 0 title.translatesAutoresizingMaskIntoConstraints = false subtitle.font = .systemFont(ofSize: 13) subtitle.textColor = ThemeManager.currentTheme().generalSubtitleColor subtitle.textAlignment = .center subtitle.numberOfLines = 0 subtitle.translatesAutoresizingMaskIntoConstraints = false addSubview(title) title.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true title.rightAnchor.constraint(equalTo: rightAnchor, constant: -15).isActive = true title.heightAnchor.constraint(equalToConstant: 45).isActive = true addSubview(subtitle) subtitle.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 5).isActive = true subtitle.leftAnchor.constraint(equalTo: leftAnchor, constant: 35).isActive = true subtitle.rightAnchor.constraint(equalTo: rightAnchor, constant: -35).isActive = true subtitle.heightAnchor.constraint(equalToConstant: 50).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func add(for view: UIView, title: ViewPlaceholderTitle, subtitle: ViewPlaceholderSubtitle, priority: ViewPlaceholderPriority, position: ViewPlaceholderPosition) { guard priority.rawValue >= placeholderPriority.rawValue else { return } placeholderPriority = priority self.title.text = title.rawValue self.subtitle.text = subtitle.rawValue if position == .center { self.title.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0).isActive = true } if position == .top { self.title.topAnchor.constraint(equalTo: topAnchor, constant: 0).isActive = true } DispatchQueue.main.async { view.addSubview(self) if #available(iOS 11.0, *) { self.topAnchor.constraint(equalTo: view.topAnchor, constant: 175).isActive = true } else { self.topAnchor.constraint(equalTo: view.topAnchor, constant: 135).isActive = true } self.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true self.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width - 20).isActive = true } } func remove(from view: UIView, priority: ViewPlaceholderPriority) { guard priority.rawValue >= placeholderPriority.rawValue else { return } for subview in view.subviews where subview is ViewPlaceholder { DispatchQueue.main.async { subview.removeFromSuperview() } } } }
34.612613
164
0.72176
8789eb2cd8d42c60bb7b6c89e3116fb11245a8ab
1,656
// // This is free and unencumbered software released into the public domain. // // Anyone is free to copy, modify, publish, use, compile, sell, or // distribute this software, either in source code form or as a compiled // binary, for any purpose, commercial or non-commercial, and by any // means. // // In jurisdictions that recognize copyright laws, the author or authors // of this software dedicate any and all copyright interest in the // software to the public domain. We make this dedication for the benefit // of the public at large and to the detriment of our heirs and // successors. We intend this dedication to be an overt act of // relinquishment in perpetuity of all present and future rights to this // software under copyright law. // // 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 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. // // For more information, please refer to <http://unlicense.org/> // // MARK: - DynamicType (Name) public extension DynamicType { /// The string describing this type from local context. var shortName: String { @inlinable get { return .init(describing: self.native) } } /// The string describing this type from global context. var longName: String { @inlinable get { return .init(reflecting: self.native) } } }
34.5
74
0.738527
09996a733320fc80f02eeec9fad1304d687cc8fa
15,509
/* file: row_variable.swift generated: Mon Jan 3 16:32:52 2022 */ /* This file was generated by the EXPRESS to Swift translator "exp2swift", derived from STEPcode (formerly NIST's SCL). exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23 WARNING: You probably don't want to edit it since your modifications will be lost if exp2swift is used to regenerate it. */ import SwiftSDAIcore extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { //MARK: -ENTITY DEFINITION in EXPRESS /* ENTITY row_variable SUBTYPE OF ( abstract_variable ); END_ENTITY; -- row_variable (line:28354 file:ap242ed2_mim_lf_v1.101.TY.exp) */ //MARK: - ALL DEFINED ATTRIBUTES /* SUPER- ENTITY(1) property_definition ATTR: name, TYPE: label -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: description, TYPE: OPTIONAL text -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: definition, TYPE: characterized_definition -- EXPLICIT (DYNAMIC) (AMBIGUOUS/MASKED) -- possibly overriden by ENTITY: mating_material, TYPE: product_definition_usage_relationship ENTITY: product_definition_kinematics, TYPE: product_definition ENTITY: product_definition_relationship_kinematics, TYPE: product_definition_relationship ENTITY: mated_part_relationship, TYPE: mated_part_relationship (as DERIVED) ENTITY: single_property_is_definition, TYPE: product_definition ENTITY: assembly_component, TYPE: assembly_component (as DERIVED) ATTR: id, TYPE: identifier -- DERIVED (AMBIGUOUS/MASKED) := get_id_value( SELF ) SUPER- ENTITY(2) property_definition_representation ATTR: definition, TYPE: represented_definition -- EXPLICIT (AMBIGUOUS/MASKED) -- possibly overriden by ENTITY: shape_definition_representation, TYPE: property_definition ENTITY: kinematic_property_definition_representation, TYPE: product_definition_kinematics (OBSERVED) ATTR: used_representation, TYPE: representation -- EXPLICIT -- possibly overriden by ENTITY: shape_definition_representation, TYPE: shape_representation ENTITY: kinematic_property_topology_representation, TYPE: kinematic_topology_representation_select ENTITY: kinematic_property_mechanism_representation, TYPE: mechanism_representation ATTR: description, TYPE: text -- DERIVED (AMBIGUOUS/MASKED) := get_description_value( SELF ) ATTR: name, TYPE: label -- DERIVED (AMBIGUOUS/MASKED) := get_name_value( SELF ) SUPER- ENTITY(3) representation ATTR: name, TYPE: label -- EXPLICIT (AMBIGUOUS/MASKED) ATTR: items, TYPE: SET [1 : ?] OF representation_item -- EXPLICIT -- observed by ENTITY(1): hidden_element_over_riding_styled_item, ATTR: container, TYPE: SET [1 : ?] OF presentation_view -- possibly overriden by ENTITY: shape_representation_with_parameters, TYPE: SET [1 : ?] OF shape_representation_with_parameters_items ENTITY: mechanical_design_shaded_presentation_area, TYPE: SET [1 : ?] OF mechanical_design_shaded_presentation_area_items ENTITY: mechanical_design_shaded_presentation_representation, TYPE: SET [1 : ?] OF mechanical_design_shaded_presentation_representation_items ENTITY: connected_edge_with_length_set_representation, TYPE: SET [1 : ?] OF connected_edge_with_length_set_items ENTITY: mechanism_state_representation, TYPE: SET [1 : ?] OF pair_value ENTITY: reinforcement_orientation_basis, TYPE: SET [1 : 1] OF basis_11_direction_member ENTITY: externally_defined_representation, TYPE: SET [1 : ?] OF externally_defined_representation_item ENTITY: kinematic_topology_network_structure, TYPE: SET [1 : ?] OF kinematic_loop ENTITY: kinematic_topology_structure, TYPE: SET [1 : ?] OF kinematic_joint ENTITY: single_area_csg_2d_shape_representation, TYPE: SET [1 : ?] OF csg_2d_area_select ENTITY: draughting_model, TYPE: SET [1 : ?] OF draughting_model_item_select ENTITY: shape_dimension_representation, TYPE: SET [1 : ?] OF shape_dimension_representation_item ENTITY: point_placement_shape_representation, TYPE: SET [1 : ?] OF point_placement_shape_representation_item ENTITY: link_motion_representation_along_path, TYPE: SET [1 : ?] OF kinematic_path ENTITY: kinematic_topology_directed_structure, TYPE: SET [1 : ?] OF oriented_joint ENTITY: scan_data_shape_representation, TYPE: SET [1 : ?] OF scanned_data_item ENTITY: mechanical_design_geometric_presentation_area, TYPE: SET [1 : ?] OF mechanical_design_geometric_presentation_area_items ENTITY: procedural_shape_representation, TYPE: SET [1 : ?] OF procedural_shape_representation_sequence ENTITY: path_parameter_representation, TYPE: SET [1 : ?] OF bounded_curve ENTITY: csg_2d_shape_representation, TYPE: SET [1 : ?] OF csg_2d_shape_select ENTITY: ply_angle_representation, TYPE: SET [1 : 1] OF measure_representation_item ENTITY: text_string_representation, TYPE: SET [1 : ?] OF text_string_representation_item ENTITY: procedural_representation, TYPE: SET [1 : ?] OF procedural_representation_sequence ENTITY: draughting_subfigure_representation, TYPE: SET [1 : ?] OF draughting_subfigure_representation_item ENTITY: picture_representation, TYPE: SET [2 : ?] OF picture_representation_item_select ENTITY: structured_text_representation, TYPE: SET [1 : ?] OF string_representation_item_select ENTITY: interpolated_configuration_representation, TYPE: SET [1 : ?] OF interpolated_configuration_sequence ENTITY: mechanical_design_presentation_representation_with_draughting, TYPE: SET [1 : ?] OF camera_model_d3 ENTITY: mechanism_representation, TYPE: SET [1 : ?] OF pair_representation_relationship ENTITY: mechanical_design_geometric_presentation_representation, TYPE: SET [1 : ?] OF mechanical_design_geometric_presentation_representation_items ENTITY: kinematic_link_representation, TYPE: SET [1 : ?] OF kinematic_link_representation_items ENTITY: neutral_sketch_representation, TYPE: SET [1 : ?] OF sketch_element_select ENTITY: draughting_symbol_representation, TYPE: SET [1 : ?] OF draughting_symbol_representation_item ATTR: context_of_items, TYPE: representation_context -- EXPLICIT (DYNAMIC) -- observed by ENTITY(1): representation_context, ATTR: representations_in_context, TYPE: SET [1 : ?] OF representation -- possibly overriden by ENTITY: mechanism_state_representation, TYPE: geometric_representation_context (as DERIVED) ENTITY: presentation_representation, TYPE: geometric_representation_context ENTITY: link_motion_representation_along_path, TYPE: geometric_representation_context_with_parameter ENTITY: path_parameter_representation, TYPE: path_parameter_representation_context ENTITY: analysis_model, TYPE: analysis_representation_context ENTITY: interpolated_configuration_representation, TYPE: geometric_representation_context_with_parameter ENTITY: mechanism_representation, TYPE: geometric_representation_context ENTITY: kinematic_link_representation, TYPE: geometric_representation_context ATTR: id, TYPE: identifier -- DERIVED (AMBIGUOUS/MASKED) := get_id_value( SELF ) ATTR: description, TYPE: text -- DERIVED (AMBIGUOUS/MASKED) := get_description_value( SELF ) SUPER- ENTITY(4) representation_item ATTR: name, TYPE: label -- EXPLICIT (AMBIGUOUS/MASKED) SUPER- ENTITY(5) abstract_variable (no local attributes) ENTITY(SELF) row_variable (no local attributes) */ //MARK: - Partial Entity public final class _row_variable : SDAI.PartialEntity { public override class var entityReferenceType: SDAI.EntityReference.Type { eROW_VARIABLE.self } //ATTRIBUTES // (no local attributes) public override var typeMembers: Set<SDAI.STRING> { var members = Set<SDAI.STRING>() members.insert(SDAI.STRING(Self.typeName)) return members } //VALUE COMPARISON SUPPORT public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) { super.hashAsValue(into: &hasher, visited: &complexEntities) } public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool { guard let rhs = rhs as? Self else { return false } if !super.isValueEqual(to: rhs, visited: &comppairs) { return false } return true } public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? { guard let rhs = rhs as? Self else { return false } var result: Bool? = true if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) { if !comp { return false } } else { result = nil } return result } //EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR public init() { super.init(asAbstructSuperclass:()) } //p21 PARTIAL ENTITY CONSTRUCTOR public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) { let numParams = 0 guard parameters.count == numParams else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil } self.init( ) } } //MARK: - Entity Reference /** ENTITY reference - EXPRESS: ```express ENTITY row_variable SUBTYPE OF ( abstract_variable ); END_ENTITY; -- row_variable (line:28354 file:ap242ed2_mim_lf_v1.101.TY.exp) ``` */ public final class eROW_VARIABLE : SDAI.EntityReference { //MARK: PARTIAL ENTITY public override class var partialEntityType: SDAI.PartialEntity.Type { _row_variable.self } public let partialEntity: _row_variable //MARK: SUPERTYPES public let super_ePROPERTY_DEFINITION: ePROPERTY_DEFINITION // [1] public let super_ePROPERTY_DEFINITION_REPRESENTATION: ePROPERTY_DEFINITION_REPRESENTATION // [2] public let super_eREPRESENTATION: eREPRESENTATION // [3] public let super_eREPRESENTATION_ITEM: eREPRESENTATION_ITEM // [4] public let super_eABSTRACT_VARIABLE: eABSTRACT_VARIABLE // [5] public var super_eROW_VARIABLE: eROW_VARIABLE { return self } // [6] //MARK: SUBTYPES //MARK: ATTRIBUTES // DESCRIPTION: (3 AMBIGUOUS REFs) // ID: (2 AMBIGUOUS REFs) // DEFINITION: (2 AMBIGUOUS REFs) // NAME: (4 AMBIGUOUS REFs) /// __EXPLICIT(OBSERVED)__ attribute /// - origin: SUPER( ``eREPRESENTATION`` ) public var ITEMS: SDAI.SET<eREPRESENTATION_ITEM>/*[1:nil]*/ { get { return SDAI.UNWRAP( super_eREPRESENTATION.partialEntity._items ) } set(newValue) { let partial = super_eREPRESENTATION.partialEntity partial._items = SDAI.UNWRAP(newValue) } } /// __EXPLICIT__ attribute /// - origin: SUPER( ``ePROPERTY_DEFINITION_REPRESENTATION`` ) public var USED_REPRESENTATION: eREPRESENTATION { get { return SDAI.UNWRAP( super_ePROPERTY_DEFINITION_REPRESENTATION.partialEntity._used_representation ) } set(newValue) { let partial = super_ePROPERTY_DEFINITION_REPRESENTATION.partialEntity partial._used_representation = SDAI.UNWRAP(newValue) } } /// __EXPLICIT(DYNAMIC)(OBSERVED)__ attribute /// - origin: SUPER( ``eREPRESENTATION`` ) public var CONTEXT_OF_ITEMS: eREPRESENTATION_CONTEXT { get { if let resolved = _representation._context_of_items__provider(complex: self.complexEntity) { let value = resolved._context_of_items__getter(complex: self.complexEntity) return value } else { return SDAI.UNWRAP( super_eREPRESENTATION.partialEntity._context_of_items ) } } set(newValue) { if let _ = _representation._context_of_items__provider(complex: self.complexEntity) { return } let partial = super_eREPRESENTATION.partialEntity partial._context_of_items = SDAI.UNWRAP(newValue) } } //MARK: INITIALIZERS public convenience init?(_ entityRef: SDAI.EntityReference?) { let complex = entityRef?.complexEntity self.init(complex: complex) } public required init?(complex complexEntity: SDAI.ComplexEntity?) { guard let partial = complexEntity?.partialEntityInstance(_row_variable.self) else { return nil } self.partialEntity = partial guard let super1 = complexEntity?.entityReference(ePROPERTY_DEFINITION.self) else { return nil } self.super_ePROPERTY_DEFINITION = super1 guard let super2 = complexEntity?.entityReference(ePROPERTY_DEFINITION_REPRESENTATION.self) else { return nil } self.super_ePROPERTY_DEFINITION_REPRESENTATION = super2 guard let super3 = complexEntity?.entityReference(eREPRESENTATION.self) else { return nil } self.super_eREPRESENTATION = super3 guard let super4 = complexEntity?.entityReference(eREPRESENTATION_ITEM.self) else { return nil } self.super_eREPRESENTATION_ITEM = super4 guard let super5 = complexEntity?.entityReference(eABSTRACT_VARIABLE.self) else { return nil } self.super_eABSTRACT_VARIABLE = super5 super.init(complex: complexEntity) } public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) { guard let entityRef = generic?.entityReference else { return nil } self.init(complex: entityRef.complexEntity) } public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) } public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) } //MARK: DICTIONARY DEFINITION public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition } private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition() private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition { let entityDef = SDAIDictionarySchema.EntityDefinition(name: "ROW_VARIABLE", type: self, explicitAttributeCount: 0) //MARK: SUPERTYPE REGISTRATIONS entityDef.add(supertype: ePROPERTY_DEFINITION.self) entityDef.add(supertype: ePROPERTY_DEFINITION_REPRESENTATION.self) entityDef.add(supertype: eREPRESENTATION.self) entityDef.add(supertype: eREPRESENTATION_ITEM.self) entityDef.add(supertype: eABSTRACT_VARIABLE.self) entityDef.add(supertype: eROW_VARIABLE.self) //MARK: ATTRIBUTE REGISTRATIONS entityDef.addAttribute(name: "ITEMS", keyPath: \eROW_VARIABLE.ITEMS, kind: .explicit, source: .superEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "USED_REPRESENTATION", keyPath: \eROW_VARIABLE.USED_REPRESENTATION, kind: .explicit, source: .superEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "CONTEXT_OF_ITEMS", keyPath: \eROW_VARIABLE.CONTEXT_OF_ITEMS, kind: .explicit, source: .superEntity, mayYieldEntityReference: true) return entityDef } } }
45.347953
185
0.729512
8978dd0afb0318ca74592ebe6cb9c9dfa4b940c0
9,424
import MixboxUiTestsFoundation import MixboxTestsFoundation import MixboxFoundation public final class XcuiElementInteractionDependenciesFactory: ElementInteractionDependenciesFactory { private let elementSettings: ElementSettings private let xcuiBasedTestsDependenciesFactory: XcuiBasedTestsDependenciesFactory init( elementSettings: ElementSettings, xcuiBasedTestsDependenciesFactory: XcuiBasedTestsDependenciesFactory) { self.elementSettings = elementSettings self.xcuiBasedTestsDependenciesFactory = xcuiBasedTestsDependenciesFactory } // swiftlint:disable function_body_length public func elementInteractionDependencies( interaction: ElementInteraction, fileLine: FileLine, elementInteractionWithDependenciesPerformer: ElementInteractionWithDependenciesPerformer, retriableTimedInteractionState: RetriableTimedInteractionState, elementSettings: ElementSettings) -> ElementInteractionDependencies { let elementInfo = HumanReadableInteractionDescriptionBuilderSource( elementName: elementSettings.name ) let interactionFailureResultFactory = actionInteractionFailureResultFactory( fileLine: fileLine ) let interactionRetrier = self.interactionRetrier( elementSettings: elementSettings, retriableTimedInteractionState: retriableTimedInteractionState ) return ElementInteractionDependenciesImpl( snapshotResolver: SnapshotForInteractionResolverImpl( retriableTimedInteractionState: retriableTimedInteractionState, interactionRetrier: interactionRetrier, performerOfSpecificImplementationOfInteractionForVisibleElement: performerOfSpecificImplementationOfInteractionForVisibleElement( elementSettings: elementSettings, interactionFailureResultFactory: interactionFailureResultFactory ), interactionFailureResultFactory: interactionFailureResultFactory, elementResolverWithScrollingAndRetries: elementResolverWithScrollingAndRetries( elementSettings: elementSettings ) ), textTyper: XcuiTextTyper( applicationProvider: xcuiBasedTestsDependenciesFactory.applicationProvider ), menuItemProvider: XcuiMenuItemProvider( applicationProvider: xcuiBasedTestsDependenciesFactory.applicationProvider ), keyboardEventInjector: xcuiBasedTestsDependenciesFactory.keyboardEventInjector, pasteboard: xcuiBasedTestsDependenciesFactory.pasteboard, interactionPerformer: NestedInteractionPerformerImpl( elementInteractionDependenciesFactory: self, elementInteractionWithDependenciesPerformer: elementInteractionWithDependenciesPerformer, retriableTimedInteractionState: retriableTimedInteractionState, elementSettings: elementSettings, fileLine: fileLine, signpostActivityLogger: xcuiBasedTestsDependenciesFactory.signpostActivityLogger ), elementSimpleGesturesProvider: XcuiElementSimpleGesturesProvider( applicationProvider: xcuiBasedTestsDependenciesFactory.applicationProvider, applicationFrameProvider: xcuiBasedTestsDependenciesFactory.applicationFrameProvider, applicationCoordinatesProvider: xcuiBasedTestsDependenciesFactory.applicationCoordinatesProvider ), eventGenerator: XcuiEventGenerator( applicationProvider: xcuiBasedTestsDependenciesFactory.applicationProvider ), interactionRetrier: interactionRetrier, interactionResultMaker: InteractionResultMakerImpl( elementHierarchyDescriptionProvider: XcuiElementHierarchyDescriptionProvider( applicationProvider: xcuiBasedTestsDependenciesFactory.applicationProvider ), screenshotTaker: xcuiBasedTestsDependenciesFactory.screenshotTaker, extendedStackTraceProvider: extendedStackTraceProvider(), fileLine: fileLine ), elementMatcherBuilder: xcuiBasedTestsDependenciesFactory.elementMatcherBuilder, elementInfo: elementInfo, retriableTimedInteractionState: retriableTimedInteractionState, signpostActivityLogger: xcuiBasedTestsDependenciesFactory.signpostActivityLogger, applicationQuiescenceWaiter: xcuiBasedTestsDependenciesFactory.applicationQuiescenceWaiter ) } // MARK: - Private private func performerOfSpecificImplementationOfInteractionForVisibleElement( elementSettings: ElementSettings, interactionFailureResultFactory: InteractionFailureResultFactory) -> PerformerOfSpecificImplementationOfInteractionForVisibleElement { return PerformerOfSpecificImplementationOfInteractionForVisibleElementImpl( elementVisibilityChecker: xcuiBasedTestsDependenciesFactory.elementVisibilityChecker, elementSettings: elementSettings, interactionFailureResultFactory: interactionFailureResultFactory, scroller: scroller( elementSettings: elementSettings ) ) } private func elementResolverWithScrollingAndRetries( elementSettings: ElementSettings) -> ElementResolverWithScrollingAndRetries { return ElementResolverWithScrollingAndRetriesImpl( elementResolver: elementResolver( elementSettings: elementSettings ), elementSettings: elementSettings, applicationFrameProvider: xcuiBasedTestsDependenciesFactory.applicationFrameProvider, eventGenerator: xcuiBasedTestsDependenciesFactory.eventGenerator, retrier: xcuiBasedTestsDependenciesFactory.retrier ) } private func interactionRetrier( elementSettings: ElementSettings, retriableTimedInteractionState: RetriableTimedInteractionState) -> InteractionRetrier { return InteractionRetrierImpl( dateProvider: dateProvider(), timeout: elementSettings.interactionTimeout, retrier: xcuiBasedTestsDependenciesFactory.retrier, retriableTimedInteractionState: retriableTimedInteractionState ) } private func actionInteractionFailureResultFactory( fileLine: FileLine) -> InteractionFailureResultFactory { return interactionFailureResultFactory( messagePrefix: "Действие неуспешно", fileLine: fileLine ) } private func interactionFailureResultFactory( messagePrefix: String, fileLine: FileLine) -> InteractionFailureResultFactory { return InteractionFailureResultFactoryImpl( applicationStateProvider: XcuiApplicationStateProvider( applicationProvider: xcuiBasedTestsDependenciesFactory.applicationProvider ), messagePrefix: messagePrefix, interactionResultMaker: InteractionResultMakerImpl( elementHierarchyDescriptionProvider: XcuiElementHierarchyDescriptionProvider( applicationProvider: xcuiBasedTestsDependenciesFactory.applicationProvider ), screenshotTaker: xcuiBasedTestsDependenciesFactory.screenshotTaker, extendedStackTraceProvider: extendedStackTraceProvider(), fileLine: fileLine ) ) } private func elementResolver( elementSettings: ElementSettings) -> ElementResolver { return ElementResolverImpl( elementFinder: xcuiBasedTestsDependenciesFactory.elementFinder, elementSettings: elementSettings ) } private func scroller( elementSettings: ElementSettings) -> Scroller { return ScrollerImpl( scrollingHintsProvider: xcuiBasedTestsDependenciesFactory.scrollingHintsProvider, elementVisibilityChecker: xcuiBasedTestsDependenciesFactory.elementVisibilityChecker, elementResolver: WaitingForQuiescenceElementResolver( elementResolver: elementResolver( elementSettings: elementSettings ), applicationProvider: xcuiBasedTestsDependenciesFactory.applicationProvider ), applicationFrameProvider: xcuiBasedTestsDependenciesFactory.applicationFrameProvider, eventGenerator: xcuiBasedTestsDependenciesFactory.eventGenerator, elementSettings: elementSettings ) } private func dateProvider() -> DateProvider { return SystemClockDateProvider() } private func extendedStackTraceProvider() -> ExtendedStackTraceProvider { return ExtendedStackTraceProviderImpl( stackTraceProvider: StackTraceProviderImpl(), extendedStackTraceEntryFromCallStackSymbolsConverter: ExtendedStackTraceEntryFromStackTraceEntryConverterImpl() ) } }
45.090909
145
0.708298
20b9e9362a2524119ecd6e98981a12969b6e4205
7,180
// // ContactCardViewController.swift // BillionWallet // // Created by Evolution Group Ltd on 30.08.17. // Copyright © 2017 Evolution Group Ltd. All rights reserved. // import Foundation class ContactCardViewController: BaseViewController<ContactCardVM>, UIImagePickerControllerDelegate, UITextFieldDelegate { typealias LocalizedStrings = Strings.ContactCard private let picker = UIImagePickerController() private var textfieldBottomConstraintDefault: CGFloat = 0 @IBOutlet private weak var boarderView: UIView! @IBOutlet private weak var backgroundImageView: UIImageView! @IBOutlet private weak var nameLabel: UILabel! @IBOutlet private weak var subtitleLabel: UILabel! @IBOutlet private weak var closeButton: UIButton! @IBOutlet private weak var avatarImageView: UIImageView! @IBOutlet private weak var qrImageView: UIImageView! @IBOutlet private weak var contactTypeLabel: UILabel! @IBOutlet private weak var addressLabel: UILabel! @IBOutlet private weak var nameTextField: UITextField! @IBOutlet private weak var shareContactButton: UIButton! @IBOutlet private weak var sharingBackView: UIView! @IBOutlet private weak var blackGradientView: UIView! @IBOutlet private var loader: UIActivityIndicatorView! weak var router: MainRouter? override func configure(viewModel: ContactCardVM) { viewModel.delegate = self } override func viewDidLoad() { super.viewDidLoad() let attributes = [NSAttributedStringKey.foregroundColor: UIColor.white] nameTextField.attributedPlaceholder = NSAttributedString(string: LocalizedStrings.namePlaceholder, attributes: attributes) picker.delegate = self nameTextField.enablesReturnKeyAutomatically = true viewModel.getContact() nameTextField.autocapitalizationType = .words configureBorders() configureGradient() testnetLabel() setupLoader() } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Private methods private func configureBorders() { boarderView.layer.borderWidth = 6 boarderView.layer.borderColor = UIColor.white.cgColor } private func configureGradient() { let startColor = Color.ProfileCardGradient.startColor let endColor: UIColor = Color.ProfileCardGradient.endColor let gradient: CAGradientLayer = CAGradientLayer() gradient.frame = blackGradientView.bounds gradient.colors = [startColor.cgColor, endColor.cgColor] gradient.startPoint = CGPoint(x: 0.5, y: 0.0) gradient.endPoint = CGPoint(x: 0.5, y: 1.0) gradient.zPosition = -1 blackGradientView.layer.addSublayer(gradient) } private func testnetLabel() { #if BITCOIN_TESTNET let labelFrame = CGRect(x: 20, y: nameTextField.frame.origin.y + 30, width: UIScreen.main.bounds.width - 40, height: 130) let label = UILabel.init(frame: labelFrame) label.numberOfLines = 0 label.textAlignment = .center label.adjustsFontSizeToFitWidth = true label.text = Strings.OtherErrors.testnetWarning label.font = UIFont.systemFont(ofSize: 80, weight: .bold) label.textColor = UIColor.red view.addSubview(label) #endif } private func setupLoader() { self.loader = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) self.loader.translatesAutoresizingMaskIntoConstraints = false self.avatarImageView.addSubview(self.loader) self.loader.hidesWhenStopped = true NSLayoutConstraint.activate([ self.loader.centerXAnchor.constraint(equalTo: avatarImageView.centerXAnchor), self.loader.centerYAnchor.constraint(equalTo: avatarImageView.centerYAnchor) ]) } // MARK: - Actions @IBAction func deleteAction(_ sender: UIButton) { let back = captureScreen(view: view) let confirmView = ConfirmDeletingView(backView: back) confirmView.delegate = self UIApplication.shared.keyWindow?.addSubview(confirmView) } @IBAction func addContactPhoto(_ sender: UIButton) { picker.allowsEditing = true present(picker, animated: true, completion: nil) } @IBAction func shareContactPressed(_ sender: UIButton) { sharingBackView.isHidden = false if let cardImage = self.view.makeSnapshot(immediately: false) { sharingBackView.isHidden = true viewModel.shareContact(card: cardImage) } } @IBAction func closeButtonPressed(_ sender: UIButton) { navigationController?.pop() } @IBAction func didChangeName(_ sender: UITextField) { guard let text = sender.text else { return } viewModel.didChangeName(name: text) } @IBAction func refreshContactCard(_ sender: Any) { viewModel.refreshContact() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { view.endEditing(true) viewModel.save() return true } //MARK: - UIImagePickerControllerDelegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { guard let cropImage = info[UIImagePickerControllerEditedImage] as? UIImage else { dismiss(animated:true, completion: nil) return } viewModel.didChangePhoto(photo: cropImage) avatarImageView.image = cropImage backgroundImageView.image = cropImage dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } } //MARK: - ConfirmViewDelegate extension ContactCardViewController: ConfirmDeletingViewDelegate { func contactDeleted() { viewModel.archiveContact() } } // MARK: - ContactCardVMDelegate extension ContactCardViewController: ContactCardVMDelegate { func startLoader() { DispatchQueue.main.async { self.loader.startAnimating() } } func stopLoader() { DispatchQueue.main.async { self.loader.stopAnimating() } } func didReceiveSharePicture(_ sharePic: UIImage) { let controller = UIActivityViewController(activityItems: [sharePic as Any, viewModel.urlToShare], applicationActivities: nil) present(controller, animated: true, completion: nil) } func didReceiveContact(_ contact: ContactProtocol) { let avatarImage = contact.avatarImage self.avatarImageView.image = avatarImage self.backgroundImageView.image = avatarImage self.nameLabel.text = contact.displayName self.nameTextField.text = contact.givenName self.qrImageView.image = contact.qrImage self.addressLabel.text = contact.uniqueValue self.contactTypeLabel.text = contact.description.value } func didDelete() { navigationController?.pop() } }
35.9
133
0.685933
f8915f68e473982c120051b71e8a255e3b024caf
3,882
// // RSSItem.swift // SwiftRSS_Example // // Created by Thibaut LE LEVIER on 28/09/2014. // Copyright (c) 2014 Thibaut LE LEVIER. All rights reserved. // import UIKit class RSSItem: NSObject, NSCoding { var title: String? var link: NSURL? func setLink(let linkString: String!) { link = NSURL(string: linkString) } var guid: String? var pubDate: NSDate? func setPubDate(let dateString: String!) { pubDate = NSDate.dateFromInternetDateTimeString(dateString) } var itemDescription: String? var content: String? // Wordpress specifics var commentsLink: NSURL? func setCommentsLink(let linkString: String!) { commentsLink = NSURL(string: linkString) } var commentsCount: Int? var commentRSSLink: NSURL? func setCommentRSSLink(let linkString: String!) { commentRSSLink = NSURL(string: linkString) } var author: String? var categories: [String]! = [String]() var imagesFromItemDescription: [NSURL]! { if let itemDescription = self.itemDescription? { return itemDescription.imageLinksFromHTMLString } return [NSURL]() } var imagesFromContent: [NSURL]! { if let content = self.content? { return content.imageLinksFromHTMLString } return [NSURL]() } override init() { super.init() } // MARK: NSCoding required init(coder aDecoder: NSCoder) { super.init() title = aDecoder.decodeObjectForKey("title") as? String link = aDecoder.decodeObjectForKey("link") as? NSURL guid = aDecoder.decodeObjectForKey("guid") as? String pubDate = aDecoder.decodeObjectForKey("pubDate") as? NSDate itemDescription = aDecoder.decodeObjectForKey("description") as? NSString content = aDecoder.decodeObjectForKey("content") as? NSString commentsLink = aDecoder.decodeObjectForKey("commentsLink") as? NSURL commentsCount = aDecoder.decodeObjectForKey("commentsCount") as? Int commentRSSLink = aDecoder.decodeObjectForKey("commentRSSLink") as? NSURL author = aDecoder.decodeObjectForKey("author") as? String categories = aDecoder.decodeObjectForKey("categories") as? [String] } func encodeWithCoder(aCoder: NSCoder) { if let title = self.title? { aCoder.encodeObject(title, forKey: "title") } if let link = self.link? { aCoder.encodeObject(link, forKey: "link") } if let guid = self.guid? { aCoder.encodeObject(guid, forKey: "guid") } if let pubDate = self.pubDate? { aCoder.encodeObject(pubDate, forKey: "pubDate") } if let itemDescription = self.itemDescription? { aCoder.encodeObject(itemDescription, forKey: "description") } if let content = self.content? { aCoder.encodeObject(content, forKey: "content") } if let commentsLink = self.commentsLink? { aCoder.encodeObject(commentsLink, forKey: "commentsLink") } if let commentsCount = self.commentsCount? { aCoder.encodeObject(commentsCount, forKey: "commentsCount") } if let commentRSSLink = self.commentRSSLink? { aCoder.encodeObject(commentRSSLink, forKey: "commentRSSLink") } if let author = self.author? { aCoder.encodeObject(author, forKey: "author") } aCoder.encodeObject(categories, forKey: "categories") } }
26.408163
81
0.581659
16c2e6bce762107553c420557bc6ae291b9058b3
3,095
// // SceneDelegate.swift // PhotoPostingApp // // Created by Lauren Banawa on 5/3/20. // Copyright © 2020 Lauren Banawa. All rights reserved. // import UIKit import Firebase class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). let currentUser = Auth.auth().currentUser // allow user to stay signed in even if they close and reopen the app if currentUser != nil { let board = UIStoryboard(name: "Main", bundle: nil) // create specified view controller from storyboard and initialize using custom initialization code let tabBar = board.instantiateViewController(identifier: "tabBar") as! UITabBarController // takes the start arrow from View Controller and moves it to point to the Tab Bar Controller if a user has signed in before // takes previously signed in user directly to Feed window?.rootViewController = tabBar } guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
45.514706
147
0.699192
4ac17d2edd927455e8149b717a3809a3f447fb5b
4,536
// // DBService.swift // Stylist // // Created by Ashli Rankin on 4/5/19. // Copyright © 2019 Ashli Rankin. All rights reserved. // import Foundation import FirebaseFirestore import Firebase final class DBService { private init() {} public static var firestoreDB: Firestore = { let db = Firestore.firestore() let settings = db.settings settings.areTimestampsInSnapshotsEnabled = true db.settings = settings return db }() static func CreateServiceProvider(serviceProvider:ServiceSideUser,completionHandler: @escaping (Error?) -> Void){ firestoreDB.collection(ServiceSideUserCollectionKeys.serviceProvider).document(serviceProvider.userId).setData([ServiceSideUserCollectionKeys.firstName: serviceProvider.firstName ?? "" , ServiceSideUserCollectionKeys.lastName:serviceProvider.lastName ?? "" , ServiceSideUserCollectionKeys.bio: serviceProvider.bio ?? "" , ServiceSideUserCollectionKeys.email:serviceProvider.email, ServiceSideUserCollectionKeys.gender: serviceProvider.gender ?? "" ,ServiceSideUserCollectionKeys.imageURL:serviceProvider.imageURL ?? "" , ServiceSideUserCollectionKeys.joinedDate:serviceProvider.joinedDate, ServiceSideUserCollectionKeys.licenseExpiryDate:serviceProvider.licenseExpiryDate ?? "" , ServiceSideUserCollectionKeys.licenseNumber:serviceProvider.licenseNumber ?? "" , ServiceSideUserCollectionKeys.isCertified : serviceProvider.isCertified, ServiceSideUserCollectionKeys.userId: serviceProvider.userId ]) { (error) in if let error = error { print("there was an error:\(error.localizedDescription)") } print("database user sucessfully created") } } static func createConsumerDatabaseAccount(consumer:StylistsUser,completionHandle: @escaping (Error?) -> Void ){ firestoreDB.collection(StylistsUserCollectionKeys.stylistUser).document(consumer.userId).setData([StylistsUserCollectionKeys.userId : consumer.userId, StylistsUserCollectionKeys.firstName: consumer.firstName ?? "" ,StylistsUserCollectionKeys.lastName:consumer.lastName ?? "", StylistsUserCollectionKeys.email : consumer.email,StylistsUserCollectionKeys.gender: consumer.gender ?? "", StylistsUserCollectionKeys.imageURL: consumer.imageURL ?? "", StylistsUserCollectionKeys.joinedDate: Date.getISOTimestamp()]) { (error) in if let error = error { print(" there was an error: \(error.localizedDescription)") } } } static func getDatabaseUser(userID: String, completionHandler: @escaping (Error?,StylistsUser?)-> Void){ firestoreDB.collection(StylistsUserCollectionKeys.stylistUser) .whereField(StylistsUserCollectionKeys.userId, isEqualTo: userID) .getDocuments(completion: { (snapshot, error) in if let error = error { completionHandler(error, nil) } else if let snapshot = snapshot?.documents.first { let stylistUser = StylistsUser(dict: snapshot.data()) completionHandler(nil, stylistUser) } }) } static func rateUser(collectionName:String,userId:String,rating:Ratings){ let id = firestoreDB.collection(collectionName).document().documentID DBService.firestoreDB.collection(collectionName).document(userId).collection(RatingsCollectionKeys.ratings).addDocument(data: [RatingsCollectionKeys.ratingId:id, RatingsCollectionKeys.value:rating.value,RatingsCollectionKeys.userId:rating.userId,RatingsCollectionKeys.ratingId:userId]) { (error) in if let error = error { print("there was an error: uploading your rating:\(error.localizedDescription)") } } } func retrieveStockServices(qurey:String,collectionName:String,field:String,completion: @escaping(Service?,Error?) -> Void){ DBService.firestoreDB.collection(collectionName).whereField(field, isEqualTo: qurey).getDocuments { (snapshot, error) in if let error = error { completion(nil,error) }else if let snapshot = snapshot { guard let serviceData = snapshot.documents.first else {return} let services = Service(dict: serviceData.data()) completion(services,nil) } } } }
52.137931
768
0.68276
bf24b15a846b33f4926287b263b29a0089df587d
673
// // UIViewController+SafeAreaInsets.swift // SafeAreaExample // // Created by Evgeny Mikhaylov on 10/10/2017. // Copyright © 2017 Rosberry. All rights reserved. // import UIKit extension UIViewController { var sa_safeAreaInsets: UIEdgeInsets { if #available(iOS 11, *) { return view.safeAreaInsets } return UIEdgeInsets(top: topLayoutGuide.length, left: 0.0, bottom: bottomLayoutGuide.length, right: 0.0) } var sa_safeAreaFrame: CGRect { if #available(iOS 11, *) { return view.safeAreaLayoutGuide.layoutFrame } return UIEdgeInsetsInsetRect(view.bounds, sa_safeAreaInsets) } }
25.884615
112
0.665676
f83d1513ca5ec6151969e626051b0cf3c165a456
451
// // Copyright © 2019 MBition GmbH. All rights reserved. // import RealmSwift /// Database class of vehicle supportable data object @objcMembers public class DBVehicleSupportableModel: Object { // MARK: Properties dynamic var canReceiveVACs: Bool = false dynamic var finOrVin: String = "" dynamic var vehicleConnectivity: String = "" // MARK: - Realm override public static func primaryKey() -> String? { return "finOrVin" } }
20.5
61
0.713969
db9f651bc595c57ff154259795a34e3f4830baa9
2,200
//: play ground import Foundation public struct HashTable<Key:Hashable, Value> { private typealias Element = (key: Key, value: Value) private typealias Bucket = [Element] private var buckets: [Bucket] private(set) public var count = 0 public var isEmpty: Bool { return count == 0 } public init(capacity: Int) { assert(capacity > 0) buckets = Array<Bucket>(repeatElement([], count: capacity)) } private func index(forkey key: Key) -> Int { return abs(key.hashValue) % buckets.count } public subscript(key: Key) -> Value? { get { return value(forKey: key) } set { if let value = newValue { updateValue(value, forKey: key) } else { removeValue(forKey: key) } } } public func value(forKey key: Key) -> Value? { let index = self.index(forkey: key) for element in buckets[index] { if element.key == key { return element.value } } return nil } public mutating func updateValue(_ value: Value, forKey key: Key) -> Value? { let index = self.index(forkey: key) for (i,element) in buckets[index].enumerated() { if element.key == key { let oldValue = element.value buckets[index][i].value = value return oldValue } } buckets[index].append((key: key, value: value)) count += 1 return nil } public mutating func removeValue(forKey key: Key) -> Value? { let index = self.index(forkey: key) for (i, element) in buckets[index].enumerated() { if element.key == key { buckets[index].remove(at: i) count -= 1 return element.value } } return nil } } var hashTable = HashTable<String,String>(capacity: 5) hashTable["firstName"] = "Steve" let x = hashTable["fristName"] hashTable["firstName"] = "Tim" hashTable["firstName"] = nil print(hashTable)
26.190476
81
0.526818
f861c2cd8ef52d70d2413e3117cc2a686b7512d8
518
// // ViewController.swift // DDXMPP-SimpleChat // // Created by Dennin Dalke on 06/02/15. // Copyright (c) 2015 Dennin Dalke. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.923077
80
0.671815
89c48874615d5cd18a54dcf5dac7e0e6625302ec
1,083
// // WeatherLoader.swift // WeathIt // // Created by Niklas Korz on 27/10/17. // Copyright © 2017 Niklas Korz. All rights reserved. // import Foundation import Alamofire class WeatherLoader { static let shared = WeatherLoader(apiKey: API_KEY) static let baseUrl = "https://api.openweathermap.org/data/2.5" static let weatherUrl = baseUrl + "/weather" static let forecastUrl = baseUrl + "/forecast" let baseParams: [String: String] init(apiKey: String, lang: String = "de", units: String = "metric") { baseParams = [ "APPID": apiKey, "lang": lang, "units": units ] } func load(location: String) -> DataRequest { var params = baseParams params["q"] = location return Alamofire.request(WeatherLoader.weatherUrl, parameters: params) } func loadForecast(location: String) -> DataRequest { var params = baseParams params["q"] = location return Alamofire.request(WeatherLoader.forecastUrl, parameters: params) } }
26.414634
79
0.619575
64dd987c7a4df2837168f8e36c120a6c3eade7fb
719
// // SecondViewController.swift // BogusAlertController // // Created by Daisy on 09/04/2019. // Copyright © 2019 고정아. All rights reserved. // protocol SecondVCDelegate: class { func sendColor(_ color:UIColor) } import UIKit class SecondViewController: UIViewController { weak var delegate: SecondVCDelegate? @IBOutlet weak var yellowButton: UIButton! @IBOutlet weak var whiteButton: UIButton! override func viewDidLoad() { super.viewDidLoad() } @IBAction func yelloeButtonAction(_ sender: UIButton) { delegate?.sendColor(.yellow) } @IBAction func whiteButton(_ sender: UIButton) { delegate?.sendColor(.white) } }
18.921053
59
0.662031
e42f8b067af1ad2bd5c91f0317960f389f3f30d6
1,174
/// A parser that can parse output from two types of parsers. /// /// This parser is useful for situations where you want to run one of two different parsers based on /// a condition, which typically would force you to perform ``Parser/eraseToAnyParser()`` and incur /// a performance penalty. /// /// For example, you can use this parser in a ``Parser/flatMap(_:)`` operation to use the parsed /// output to determine what parser to run next: /// /// ```swift /// versionParser.flatMap { version in /// version == "2.0" /// ? Conditional.first(V2Parser()) /// : Conditional.second(LegacyParser()) /// } /// ``` public enum Conditional<First, Second>: Parser where First: Parser, Second: Parser, First.Input == Second.Input, First.Output == Second.Output { case first(First) case second(Second) @inlinable public func parse(_ input: inout First.Input) -> First.Output? { switch self { case let .first(first): return first.parse(&input) case let .second(second): return second.parse(&input) } } } extension Parsers { public typealias Conditional = Parsing.Conditional // NB: Convenience type alias for discovery }
28.634146
100
0.681431
e20ae85d8eae2063c4fe3c0b5bb989bf26e844b3
279
// // ViewController.swift // EmailApp // // Created by Emilia Nedyalkova on 15.04.21. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } }
16.411765
58
0.659498
fc6d824e5e1eb00fe740046404697ef9d12d35d0
4,752
// // Zip+Collection.swift // RxSwift // // Created by Krunoslav Zaher on 8/30/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // final class ZipCollectionTypeSink<C: Collection, O: ObserverType> : Sink<O> where C.Iterator.Element : ObservableConvertibleType { typealias R = O.E typealias Parent = ZipCollectionType<C, R> typealias SourceElement = C.Iterator.Element.E private let _parent: Parent private let _lock = RecursiveLock() // state private var _numberOfValues = 0 private var _values: [Queue<SourceElement>] private var _isDone: [Bool] private var _numberOfDone = 0 private var _subscriptions: [SingleAssignmentDisposable] init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent _values = [Queue<SourceElement>](repeating: Queue(capacity: 4), count: parent.count) _isDone = [Bool](repeating: false, count: parent.count) _subscriptions = Array<SingleAssignmentDisposable>() _subscriptions.reserveCapacity(parent.count) for _ in 0 ..< parent.count { _subscriptions.append(SingleAssignmentDisposable()) } super.init(observer: observer, cancel: cancel) } func on(_ event: Event<SourceElement>, atIndex: Int) { _lock.lock(); defer { _lock.unlock() } // { switch event { case .next(let element): _values[atIndex].enqueue(element) if _values[atIndex].count == 1 { _numberOfValues += 1 } if _numberOfValues < _parent.count { let numberOfOthersThatAreDone = _numberOfDone - (_isDone[atIndex] ? 1 : 0) if numberOfOthersThatAreDone == _parent.count - 1 { self.forwardOn(.completed) self.dispose() } return } do { var arguments = [SourceElement]() arguments.reserveCapacity(_parent.count) // recalculate number of values _numberOfValues = 0 for i in 0 ..< _values.count { arguments.append(_values[i].dequeue()!) if _values[i].count > 0 { _numberOfValues += 1 } } let result = try _parent.resultSelector(arguments) self.forwardOn(.next(result)) } catch let error { self.forwardOn(.error(error)) self.dispose() } case .error(let error): self.forwardOn(.error(error)) self.dispose() case .completed: if _isDone[atIndex] { return } _isDone[atIndex] = true _numberOfDone += 1 if _numberOfDone == _parent.count { self.forwardOn(.completed) self.dispose() } else { _subscriptions[atIndex].dispose() } } // } } func run() -> Disposable { var j = 0 for i in _parent.sources { let index = j let source = i.asObservable() let disposable = source.subscribe(AnyObserver { event in self.on(event, atIndex: index) }) _subscriptions[j].setDisposable(disposable) j += 1 } return Disposables.create(_subscriptions) } } final class ZipCollectionType<C: Collection, R> : Producer<R> where C.Iterator.Element : ObservableConvertibleType { typealias ResultSelector = ([C.Iterator.Element.E]) throws -> R let sources: C let resultSelector: ResultSelector let count: Int init(sources: C, resultSelector: @escaping ResultSelector) { self.sources = sources self.resultSelector = resultSelector self.count = Int(self.sources.count.toIntMax()) } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R { let sink = ZipCollectionTypeSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
34.18705
139
0.515572
f99af1d84cd01edfd6786295eeef6d8cc2b3ca1d
1,090
// // GattRequest.swift // Gormsson // // Created by Damien Noël Dubuisson on 09/04/2019. // Copyright © 2019 Damien Noël Dubuisson. All rights reserved. // import CoreBluetooth import Nevanlinna /// A class that represent a request on a characteristic. internal final class GattRequest { /// The peripheral to request internal var peripheral: CBPeripheral /// The property of the characteristic. internal var property: CBCharacteristicProperties /// The Gormsson's characteristic. internal var characteristic: CharacteristicProtocol /// The result internal var result: ((Result<DataInitializable, Error>) -> Void)? /// Init with some default values. internal init(_ property: CBCharacteristicProperties, on peripheral: CBPeripheral, characteristic: CharacteristicProtocol, result: ((Result<DataInitializable, Error>) -> Void)? = nil) { self.peripheral = peripheral self.property = property self.characteristic = characteristic self.result = result } }
32.058824
80
0.683486
bbaa7b41e49487ef71610283c68d249dd6ddf752
2,226
// // UIImageView+URLImage.swift // Marvel // // Created by Diego Rogel on 22/1/22. // import Foundation import UIKit enum URLImageError: Error { case loadingFailed } protocol URLImage { func loadImage(from url: URL?) func clear() } class FetchImageView: UIImageView, URLImage { private var imageTask: Task<Void, Never>? func loadImage(from url: URL?) { imageTask = Task { await loadImage(from: url) } } func clear() { image = nil imageTask?.cancel() } } private extension UIImageView { func loadImage(from url: URL?) async { guard let urlRequest = buildURLRequest(from: url) else { return } if let image = retrieveCachedImageIfAny(for: urlRequest) { setImage(image) } else { await requestNetworkImage(urlRequest) } } func buildURLRequest(from url: URL?) -> URLRequest? { guard let url = url else { return nil } return URLRequest(url: url, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 20) } func retrieveCachedImageIfAny(for urlRequest: URLRequest) -> UIImage? { guard let cachedData = URLCache.shared.cachedResponse(for: urlRequest)?.data else { return nil } return UIImage(data: cachedData) } func requestNetworkImage(_ urlRequest: URLRequest) async { guard let requestResult = try? await URLSession.shared.data(for: urlRequest, delegate: nil) else { return } let data = requestResult.0 let response = requestResult.1 cacheResponse(from: urlRequest, data: data, response: response) handleRequestResult(data: data) } func handleRequestResult(data: Data) { guard let image = UIImage(data: data) else { return } setImage(image) } func setImage(_ image: UIImage) { DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.image = image } } func cacheResponse(from urlRequest: URLRequest, data: Data, response: URLResponse) { let cachedData = CachedURLResponse(response: response, data: data) URLCache.shared.storeCachedResponse(cachedData, for: urlRequest) } }
28.538462
115
0.649146
56ef3dd6825b85bca661a1f60d2e2a592b6607d5
6,454
// // LGRecordView.swift // record // // Created by jamy on 11/6/15. // Copyright © 2015 jamy. All rights reserved. // 该模块未使用autolayout import UIKit import AVFoundation private let buttonW: CGFloat = 60 class LGRecordVideoView: UIView { var videoView: UIView! var indicatorView: UILabel! var recordButton: UIButton! var progressView: UIProgressView! var progressView2: UIProgressView! var recordVideoModel: LGRecordVideoModel! var preViewLayer: AVCaptureVideoPreviewLayer! var recordTimer: NSTimer! override init(frame: CGRect) { super.init(frame: frame) customInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) customInit() } func customInit() { backgroundColor = UIColor.blackColor() if TARGET_IPHONE_SIMULATOR == 1 { NSLog("simulator can't do this!!!") } else { recordVideoModel = LGRecordVideoModel() videoView = UIView(frame: CGRectMake(0, 0, bounds.width, bounds.height * 0.7)) videoView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] addSubview(videoView) preViewLayer = AVCaptureVideoPreviewLayer(session: recordVideoModel.captureSession) preViewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill preViewLayer.frame = videoView.bounds videoView.layer.insertSublayer(preViewLayer, atIndex: 0) recordButton = UIButton(type: .Custom) recordButton.setTitleColor(UIColor.orangeColor(), forState: .Normal) recordButton.layer.cornerRadius = buttonW / 2 recordButton.layer.borderWidth = 1.5 recordButton.layer.borderColor = UIColor.orangeColor().CGColor recordButton.setTitle("按住拍", forState: .Normal) recordButton.addTarget(self, action: "buttonTouchDown", forControlEvents: .TouchDown) recordButton.addTarget(self, action: "buttonDragOutside", forControlEvents: .TouchDragOutside) recordButton.addTarget(self, action: "buttonCancel", forControlEvents: .TouchUpOutside) recordButton.addTarget(self, action: "buttonTouchUp", forControlEvents: .TouchUpInside) addSubview(recordButton) progressView = UIProgressView(frame: CGRectZero) progressView.progressTintColor = UIColor.blackColor() progressView.trackTintColor = UIColor.orangeColor() progressView.hidden = true addSubview(progressView) progressView2 = UIProgressView(frame: CGRectZero) progressView2.progressTintColor = UIColor.blackColor() progressView2.trackTintColor = UIColor.orangeColor() progressView2.hidden = true addSubview(progressView2) progressView2.transform = CGAffineTransformMakeRotation(CGFloat(M_PI)) indicatorView = UILabel() indicatorView.textColor = UIColor.whiteColor() indicatorView.font = UIFont.systemFontOfSize(12.0) indicatorView.backgroundColor = UIColor.redColor() indicatorView.hidden = true addSubview(indicatorView) recordButton.bounds = CGRectMake(0, 0, buttonW, buttonW) recordButton.center = CGPointMake(center.x, videoView.frame.height + buttonW) progressView.frame = CGRectMake(0, videoView.frame.height, bounds.width / 2, 2) progressView2.frame = CGRectMake(bounds.width / 2 - 1, videoView.frame.height, bounds.width / 2 + 1, 2) indicatorView.center = CGPointMake(center.x, videoView.frame.height - 20) indicatorView.bounds = CGRectMake(0, 0, 50, 20) } } override func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) if TARGET_IPHONE_SIMULATOR == 0 { recordVideoModel.start() } } func buttonTouchDown() { UIView.animateWithDuration(0.2, animations: { () -> Void in self.recordButton.transform = CGAffineTransformMakeScale(1.5, 1.5) }) { (finish) -> Void in self.recordButton.hidden = true } recordVideoModel.beginRecord() stopTimer() self.progressView.hidden = false self.progressView2.hidden = false indicatorView.hidden = false indicatorView.text = "上移取消" recordTimer = NSTimer(timeInterval: 1.0, target: self, selector: "recordTimerUpdate", userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(recordTimer, forMode: NSRunLoopCommonModes) } func buttonDragOutside() { indicatorView.hidden = false indicatorView.text = "松手取消" } func buttonCancel() { UIView.animateWithDuration(0.2, animations: { () -> Void in self.recordButton.hidden = false self.recordButton.transform = CGAffineTransformIdentity }) { (finish) -> Void in self.indicatorView.hidden = true self.progressView.hidden = true self.progressView.progress = 0 self.progressView2.hidden = true self.progressView2.progress = 0 self.stopTimer() } recordVideoModel.cancelRecord() } func buttonTouchUp() { UIView.animateWithDuration(0.2, animations: { () -> Void in self.recordButton.hidden = false self.recordButton.transform = CGAffineTransformIdentity }) { (finish) -> Void in self.indicatorView.hidden = true self.progressView.hidden = true self.progressView.progress = 0 self.progressView2.hidden = true self.progressView2.progress = 0 self.stopTimer() } recordVideoModel.complectionRecord() } func stopTimer() { if recordTimer != nil { recordTimer.invalidate() recordTimer = nil } } func recordTimerUpdate() { if progressView.progress == 1 { buttonTouchUp() } else { progressView.progress += 0.1 progressView2.progress += 0.1 } } }
37.523256
123
0.613108
29f8dde625518db0f7b6cc5008126c8fbf39263f
5,484
// // GymViewController.swift // Project01-ResortSurvey // // Created by Lam Nguyen on 4/28/21. // import UIKit // Fetch all the questions from peristent storage and add it to an object. // I want to loop through each of the questions and add a label and use the cosmos thing to make the stars for each of the questions using code and not the storyboard. class GymViewController: UIViewController { @IBOutlet weak var progressLabel: UILabel! @IBOutlet weak var q1: UILabel! @IBOutlet weak var q2: UILabel! @IBOutlet weak var q3: UILabel! @IBOutlet weak var q4: UILabel! @IBOutlet weak var q5: UILabel! @IBOutlet weak var q1Rating: CosmosView! @IBOutlet weak var q2Rating: CosmosView! @IBOutlet weak var q3Rating: CosmosView! @IBOutlet weak var q4Rating: CosmosView! @IBOutlet weak var q5Rating: CosmosView! @IBOutlet weak var q1Img: UIImageView! @IBOutlet weak var q2Img: UIImageView! @IBOutlet weak var q3Img: UIImageView! @IBOutlet weak var q4Img: UIImageView! @IBOutlet weak var q5Img: UIImageView! @IBOutlet weak var headingImg: UIImageView! var questionTracker = 0 override func viewDidLoad() { super.viewDidLoad() surveyProgress() loadQuestions() saveRatings() print("Number of Gym Questions",QuestionsHelper.inst.getCategory(category: "Gym" ).count) } // Set Autorotation to false override open var shouldAutorotate: Bool { return false } // Specify the supported Orientation override open var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } @IBAction func submitFeedback(_ sender: Any) { // Make sure that questions aren't tracked multiple times let questionsPerCategory = QuestionsHelper.inst.getCategory(category: "Gym" ).count if self.questionTracker > questionsPerCategory { self.questionTracker = questionsPerCategory } let ud = UserDefaults.standard ud.set(ud.integer(forKey: "questionTracker") + self.questionTracker, forKey: "questionTracker") let sb : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let wel = sb.instantiateViewController(withIdentifier: "Spa") as! SpaViewController self.present(wel, animated: true, completion: nil) } func surveyProgress() { // Get number of questions answered so far: let questionsAnswered = UserDefaults.standard.integer(forKey: "questionTracker") // Get total number of questions in database: let totalQuestions = QuestionsHelper.inst.getData().count progressLabel.text = "Questions Answered: \(questionsAnswered) of \(totalQuestions)" } func loadQuestions() { let data = QuestionsHelper.inst.getCategory(category: "Gym" ) // Load Questions q1.text = data[0].question q2.text = data[1].question q3.text = data[2].question q4.text = data[3].question q5.text = data[4].question // Load default ratings q1Rating.rating = Double(data[0].rating!) ?? 1 q2Rating.rating = Double(data[1].rating!) ?? 1 q3Rating.rating = Double(data[2].rating!) ?? 1 q4Rating.rating = Double(data[3].rating!) ?? 1 q5Rating.rating = Double(data[4].rating!) ?? 1 } func saveRatings() { let data = QuestionsHelper.inst.getCategory(category: "Gym" ) let question1Id = data[0].idCategory! let question2Id = data[1].idCategory! let question3Id = data[2].idCategory! let question4Id = data[3].idCategory! let question5Id = data[4].idCategory! q1Rating.didFinishTouchingCosmos = { rate in print(rate) self.q1Img.image = UIImage(named: "Checkmark")! let dic = ["idCategory": question1Id, "rating": String(rate)] QuestionsHelper.inst.updateData(object: dic ) self.questionTracker += 1 } q2Rating.didFinishTouchingCosmos = { rate in print(rate) self.q2Img.image = UIImage(named: "Checkmark")! let dic = ["idCategory": question2Id, "rating": String(rate)] QuestionsHelper.inst.updateData(object: dic ) self.questionTracker += 1 } q3Rating.didFinishTouchingCosmos = { rate in print(rate) self.q3Img.image = UIImage(named: "Checkmark")! let dic = ["idCategory": question3Id, "rating": String(rate)] QuestionsHelper.inst.updateData(object: dic ) self.questionTracker += 1 } q4Rating.didFinishTouchingCosmos = { rate in print(rate) self.q4Img.image = UIImage(named: "Checkmark")! let dic = ["idCategory": question4Id, "rating": String(rate)] QuestionsHelper.inst.updateData(object: dic ) self.questionTracker += 1 } q5Rating.didFinishTouchingCosmos = { rate in print(rate) self.q5Img.image = UIImage(named: "Checkmark")! let dic = ["idCategory": question5Id, "rating": String(rate)] QuestionsHelper.inst.updateData(object: dic ) self.questionTracker += 1 }} }
34.708861
167
0.618162
e6962aa7fbcf273d0ea11e2f0936056257f830f4
2,727
// // AppDelegate.swift // HealthKitHelper // // Created by Finn Gaida on 23.09.16. // Copyright © 2016 Finn Gaida. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { guard let vc = self.window?.rootViewController as? ViewController else { print("couldn't find view controller"); return false } do { let data = try Data(contentsOf: url) print("got data") vc.importData(data) return true } catch { print("an error occured: \(error)") return false } } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
43.285714
285
0.710304
e0abc95535f837a43a6c8680c90207cea42a0212
332
// // UIColor-Extenstion.swift // DYZB // // Created by Macbook on 2017/11/23. // Copyright © 2017年 何洪涛. All rights reserved. // import UIKit extension UIColor { convenience init(r : CGFloat, g : CGFloat , b : CGFloat) { self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0) } }
11.857143
80
0.584337
0847eec4f42e505f54127baf129aeb3375a8b8d9
217
// // MainView.swift // To-Do-List // // Created by Arjun Bhalodia on 8/10/21. // import SwiftUI struct MainView: View { var body: some View{ ToDoListPage(items: ["One", "Two", "Three"]) } }
13.5625
52
0.571429
29c859abd1b2e8814aa6b1e9579f9d8c12ad93b4
1,294
// // ViewController.swift // TippyV2 // // Created by Yaniv Bronshtein on 12/6/18. // Copyright © 2018 Yaniv Bronshtein. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var tipControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() // 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. } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } @IBAction func calculateTip(_ sender: Any) { let tipPercentages = [0.18, 0.2, 0.25] //If the field is nil then set default to 0 let bill = Double(billField.text!) ?? 0 let tip = bill * tipPercentages[tipControl.selectedSegmentIndex] //Use array to choice tip percentage let total = bill + tip tipLabel.text = String(format: "$%0.2f", tip) //Format to 2 decimal places using 0.2f totalLabel.text = String(format: "$%0.2f", total) } }
28.755556
109
0.64915
9cb5cc21ac991697186ab9e781cc8c0853916132
830
// // ContactRealmLiveUITestsLaunchTests.swift // ContactRealmLiveUITests // // Created by Suppasit beer on 28/12/2564 BE. // import XCTest class ContactRealmLiveUITestsLaunchTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } override func setUpWithError() throws { continueAfterFailure = false } func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } }
25.151515
88
0.684337
0ed7e4eb9ca705d67b51e29ab8b21c4bd543e4f0
4,784
import UIKit import Swinject import TethysKit import Result import CoreSpotlight @UIApplicationMain public final class AppDelegate: UIResponder, UIApplicationDelegate { public var window: UIWindow? public lazy var container: Container = { let container = Container() TethysKit.configure(container: container) Tethys.configure(container: container) return container }() private lazy var analytics: Analytics = { self.container.resolve(Analytics.self)! }() private lazy var importUseCase: ImportUseCase = { self.container.resolve(ImportUseCase.self)! }() private func splitView() -> SplitViewController { self.container.resolve(SplitViewController.self)! } private func feedListController() -> FeedListController { return self.container.resolve(FeedListController.self)! } private func getWindow() -> UIWindow { if let window = self.window { return window } let window = UIWindow(frame: UIScreen.main.bounds) window.makeKeyAndVisible() self.window = window return window } public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { UINavigationBar.appearance().tintColor = UIColor(named: "highlight") UIBarButtonItem.appearance().tintColor = UIColor(named: "highlight") UITabBar.appearance().tintColor = UIColor(named: "highlight") if NSClassFromString("XCTestCase") != nil && launchOptions?[UIApplication.LaunchOptionsKey(rawValue: "test")] as? Bool != true { self.getWindow().rootViewController = UIViewController() return true } self.createControllerHierarchy() if launchOptions == nil || launchOptions?.isEmpty == true || (launchOptions?.count == 1 && launchOptions?[UIApplication.LaunchOptionsKey(rawValue: "test")] as? Bool == true) { self.analytics.logEvent("SessionBegan", data: nil) } return true } public func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { _ = self.importUseCase.scanForImportable(url).then { item in if case let .opml(url, _) = item { _ = self.importUseCase.importItem(url) } } return true } // MARK: Quick Actions public func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { let splitView = self.getWindow().rootViewController as? UISplitViewController guard let navigationController = splitView?.viewControllers.first as? UINavigationController else { completionHandler(false) return } navigationController.popToRootViewController(animated: false) guard let feedsViewController = navigationController.topViewController as? FeedListController else { completionHandler(false) return } if shortcutItem.type == "com.rachelbrindle.rssclient.newfeed" { feedsViewController.importFromWeb() self.analytics.logEvent("QuickActionUsed", data: ["kind": "Add New Feed"]) completionHandler(true) } else { completionHandler(false) } } public func applicationWillEnterForeground(_ application: UIApplication) { application.applicationIconBadgeNumber = 0 } // MARK: - Private private func createControllerHierarchy(_ feed: Feed? = nil, article: Article? = nil) { let feedListController = self.feedListController() let splitView = self.splitView() let detailVC = UIViewController() detailVC.view.backgroundColor = Theme.backgroundColor splitView.masterNavigationController.viewControllers = [ feedListController ] splitView.detailNavigationController.viewControllers = [ detailVC ] splitView.viewControllers = [ splitView.masterNavigationController, splitView.detailNavigationController ] if let feed = feed { let articleListController = feedListController.showFeed(feed, animated: false) if let article = article { _ = articleListController.showArticle(article, animated: false) } } self.getWindow().rootViewController = splitView } }
34.919708
111
0.633988
6a321570a2a5f7b96df18ecbfeb2cff5a0fae3a8
909
// // TischSearchTests.swift // TischSearchTests // // Created by Mike Yeung on 4/8/15. // Copyright (c) 2015 Mike Yeung. All rights reserved. // import UIKit import XCTest class TischSearchTests: 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. } } }
24.567568
111
0.617162
1860c858a7b62b416f810bce394b0aaac023a1b2
1,317
// // DoubleExtension.swift // HackerNews // // Created by Shanshan Wang on 11/25/19. // Copyright © 2019 Amit Burstein. All rights reserved. // import Foundation extension Double { func timeIntervalAgo() -> String { let _ts = self //let date = NSDate(timeIntervalSince1970: _ts) as Date // let dayTimePeriodFormatter = DateFormatter() //dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a" //let dateString = dayTimePeriodFormatter.string(from: date) let now = NSDate() as Date let timeInterval = now.timeIntervalSince1970 //let dateNowString = dayTimePeriodFormatter.string(from: now) let days = Int((timeInterval - (_ts))/86400.0) if days >= 1 { if days == 1 { return "\(days) day ago" } else{ return "\(days) days ago" } } let hours = Int((timeInterval - (_ts))/3600.0) if hours >= 1 { if hours == 1 { return "\(hours) hour ago" } else{ return "\(hours) hours ago" } } let minutes = Int((timeInterval - (_ts))/60.0) if minutes >= 1 { if minutes == 1 { return "\(minutes) minute ago" } else{ return "\(minutes) minutes ago" } } return "" // print( " _ts value is \(_ts)") } }
22.706897
62
0.56568
20d2e9c14ff48c1769d24fa8f4aa8f82929c82ac
2,017
/* * Resistance * Copyright (c) Matt Malenko 2021 * MIT license, see LICENSE file for details */ import Foundation // MARK:- Properties public struct FourBandResistor: BandedResistor { let digit1: Digit let digit2: Digit public let multiplier: Multiplier public let tolerance: Tolerance public var digits: [Digit] { [digit1, digit2] } public init(digit1: Digit, digit2: Digit, multiplier: Multiplier, tolerance: Tolerance) { self.digit1 = digit1 self.digit2 = digit2 self.multiplier = multiplier self.tolerance = tolerance } } // MARK:- Convenience Inits extension FourBandResistor { public init(value: Double, tolerance: Tolerance = .gold) { let colors = BandsCalculator.fourBandColors(value: value) self.init(digit1: colors.digit1, digit2: colors.digit2, multiplier: colors.multiplier, tolerance: tolerance) } public init<T: BandedResistor>(resistor: T, tolerance: Tolerance = .gold) { self.init(value: resistor.value, tolerance: tolerance) } } // MARK:- Failable Inits extension FourBandResistor { public init(exactValue: Double, tolerance: Tolerance = .gold) throws { let colors = try BandsCalculator.fourBandColorsOrFail(value: exactValue) self.init(digit1: colors.digit1, digit2: colors.digit2, multiplier: colors.multiplier, tolerance: tolerance) } public init<T: BandedResistor>(exactResistor: T, tolerance: Tolerance = .gold) throws { try self.init(exactValue: exactResistor.value, tolerance: tolerance) } } // MARK:- Multiplier Functions extension FourBandResistor { public func decadeUp() -> FourBandResistor { guard multiplier != .white else { return self } return .init(value: value * 10, tolerance: tolerance) } public func decadeDown() -> FourBandResistor { guard multiplier != .silver else { return self } return .init(value: value / 10, tolerance: tolerance) } }
31.515625
116
0.677243
33245854f5dc61f62e11c720b35783f4d7ac394e
208
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum S { { } var b = " \(array: Any) "
23.111111
87
0.711538
e21c32498124a911e0a13d08336ba5f94ee8c9de
860
// // SettingsViewController.swift // TipCalculator // // Created by Ali Mehrpour on 9/15/16. // Copyright © 2016 Ali Mehrpour. All rights reserved. // import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var tipControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() let defaults = NSUserDefaults.standardUserDefaults() let defaultTipPercent = defaults.integerForKey(defaultTipPercentIndex) tipControl.selectedSegmentIndex = defaultTipPercent } @IBAction func changeTipPercent(sender: AnyObject) { let selectedIndex = tipControl.selectedSegmentIndex let defaults = NSUserDefaults.standardUserDefaults() defaults.setInteger(selectedIndex, forKey: defaultTipPercentIndex) defaults.synchronize() } }
27.741935
78
0.710465
8f300a22889a697f1fb3cdf0e749ed047d2fdd0d
1,536
// // UIScrollView+Addtion.swift // CollectionView // // Created by Luke on 4/16/17. // Copyright © 2017 lkzhao. All rights reserved. // import UIKit extension UIScrollView { public var visibleFrame: CGRect { return bounds } public var visibleFrameLessInset: CGRect { return UIEdgeInsetsInsetRect(visibleFrame, contentInset) } public var absoluteFrameLessInset: CGRect { return UIEdgeInsetsInsetRect(CGRect(origin: .zero, size: bounds.size), contentInset) } public var innerSize: CGSize { return absoluteFrameLessInset.size } public var offsetFrame: CGRect { return CGRect(x: -contentInset.left, y: -contentInset.top, width: max(0, contentSize.width - bounds.width + contentInset.right + contentInset.left), height: max(0, contentSize.height - bounds.height + contentInset.bottom + contentInset.top)) } public func absoluteLocation(for point: CGPoint) -> CGPoint { return point - contentOffset } public func scrollTo(edge: UIRectEdge, animated: Bool) { let target: CGPoint switch edge { case UIRectEdge.top: target = CGPoint(x: contentOffset.x, y: offsetFrame.minY) case UIRectEdge.bottom: target = CGPoint(x: contentOffset.x, y: offsetFrame.maxY) case UIRectEdge.left: target = CGPoint(x: offsetFrame.minX, y: contentOffset.y) case UIRectEdge.right: target = CGPoint(x: offsetFrame.maxX, y: contentOffset.y) default: return } setContentOffset(target, animated: animated) } }
31.346939
110
0.695964
91014e047ffe5462cee55af6c654fe0591ad3184
4,521
import UIKit extension SideMenu { class HeaderView: UIView { // MARK: - Private properties private let iconImageView: UIImageView = UIImageView() private let titleLabel: UILabel = UILabel() private let subTitleLabel: UILabel = UILabel() private let appNameLoginSeparator: UIView = UIView() // MARK: - Public properties let horizontalOffset: CGFloat = 15.0 let verticalOffset: CGFloat = 6.0 var iconImage: UIImage? { get { return self.iconImageView.image } set { self.iconImageView.image = newValue self.updateLayout() } } var title: String? { get { return self.titleLabel.text } set { self.titleLabel.text = newValue } } var subTitle: String? { get { return self.subTitleLabel.text } set { self.subTitleLabel.text = newValue } } // MARK: - override init(frame: CGRect) { super.init(frame: frame) self.customInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.customInit() } private func customInit() { self.backgroundColor = UIColor.clear self.setupIconImageView() self.setupTitleLabel() self.setupSubTitleLabel() self.setupAppNameLoginSeparator() self.setupLayout() } // MARK: - Private private func setupIconImageView() { self.iconImageView.contentMode = .scaleAspectFit self.iconImageView.tintColor = Theme.Colors.darkAccentColor } private func setupTitleLabel() { self.titleLabel.backgroundColor = UIColor.clear self.titleLabel.textColor = Theme.Colors.textOnMainColor self.titleLabel.font = Theme.Fonts.largeTitleFont } private func setupSubTitleLabel() { self.subTitleLabel.backgroundColor = UIColor.clear self.subTitleLabel.textColor = Theme.Colors.textOnMainColor self.subTitleLabel.font = Theme.Fonts.plainTextFont } private func setupAppNameLoginSeparator() { self.appNameLoginSeparator.backgroundColor = UIColor.clear self.appNameLoginSeparator.isUserInteractionEnabled = false } private func setupLayout() { self.addSubview(self.iconImageView) self.addSubview(self.appNameLoginSeparator) self.addSubview(self.titleLabel) self.addSubview(self.subTitleLabel) self.updateLayout() self.titleLabel.snp.makeConstraints { (make) in make.leading.trailing.equalTo(self.appNameLoginSeparator) make.bottom.equalTo(self.appNameLoginSeparator.snp.top) } self.subTitleLabel.snp.makeConstraints { (make) in make.leading.trailing.equalTo(self.titleLabel) make.top.equalTo(self.appNameLoginSeparator.snp.bottom) } } private func updateLayout() { if self.iconImage == nil { self.iconImageView.snp.remakeConstraints { (make) in make.leading.top.equalToSuperview() make.size.equalTo(0.0) } } else { self.iconImageView.snp.remakeConstraints { (make) in make.leading.top.bottom.equalToSuperview().inset(self.horizontalOffset) make.width.equalTo(self.iconImageView.snp.height) } } self.appNameLoginSeparator.snp.remakeConstraints { (make) in if self.iconImage == nil { make.leading.equalToSuperview().inset(self.horizontalOffset) } else { make.leading.equalTo(self.iconImageView.snp.trailing).offset(self.horizontalOffset) } make.trailing.equalToSuperview().inset(self.horizontalOffset) make.centerY.equalToSuperview() make.height.equalTo(self.verticalOffset) } } } }
34.51145
103
0.546339
184bb217203628de1d022b0b2b1e4c56bb2900c6
1,718
// // CustomTextField.swift // SO-34985404 // // Copyright © 2017, 2018 Xavier Schott // 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 CustomTextField: UITextField { override func becomeFirstResponder() -> Bool { let becomeFirstResponder = super.becomeFirstResponder() if becomeFirstResponder { self.borderStyle = .line } return becomeFirstResponder } override func resignFirstResponder() -> Bool { let resignFirstResponder = super.resignFirstResponder() if resignFirstResponder { self.borderStyle = .roundedRect } return resignFirstResponder } }
38.177778
81
0.719441
bb670cceeccf765b553c8ed92b75b16411d76b3e
1,338
// // OrderedDictionary.swift // WeaverCodeGen // // Created by Théophane Rupin on 6/15/18. // import Foundation // MARK: - Dictionary final class OrderedDictionary<Key: Hashable, Value> { private(set) var dictionary = [Key: Value]() private(set) var orderedKeys = [Key]() struct KeyValue { let key: Key let value: Value } init(_ keyValues: [(Key, Value)] = []) { dictionary = keyValues.reduce(into: [:]) { $0[$1.0] = $1.1 } orderedKeys = keyValues.map { $0.0 } } var orderedKeyValues: [KeyValue] { var result = [KeyValue]() for key in orderedKeys { dictionary[key].flatMap { result.append(KeyValue(key: key, value: $0)) } } return result } var orderedValues: [Value] { return orderedKeyValues.map { $0.value } } subscript(key: Key) -> Value? { get { return dictionary[key] } set { if dictionary[key] == nil { orderedKeys.append(key) } else { orderedKeys.firstIndex(of: key).flatMap { index -> Void in orderedKeys.remove(at: index) } orderedKeys.append(key) } dictionary[key] = newValue } } }
23.473684
84
0.5142
5dd7142b2285ad4accd8b18c84b4cade78517240
3,841
// // main.swift // Observer // // Created by 韩陈昊 on 2018/5/11. // Copyright © 2018年 韩陈昊. All rights reserved. // import Foundation // 通知 class Notification: NSObject { let name: String let object: AnyObject? let info: [AnyHashable: Any]? var count = 0 init(name: String , object: AnyObject? , info: [AnyHashable: Any]?) { self.name = name self.object = object self.info = info } } // 观察者 class Observer: NSObject { let observer: AnyObject let selector: Selector init(observer: AnyObject, selector: Selector) { self.observer = observer self.selector = selector } } // 操作 class Subject: NSObject { var notification: Notification? var observers: [Observer] init(notification: Notification? , observers: [Observer] ) { self.notification = notification self.observers = observers } // 添加观察者 func add(observer: Observer) -> Void { if observers.contains(observer) { return } observers.append(observer) } // 移除观察者 func remove(observer: Observer) -> Void { for i in 0..<observers.count { if observers[i] == observer { observers.remove(at: i) break } } } func post() -> Void { observers.forEach { (obs) in let _ = obs.observer.perform(obs.selector, with: notification) } } } class PostCenter: NSObject { private static let singleton = PostCenter() static func defaultCenter() -> PostCenter { return singleton } private var center = [String: Subject]() func post(_ notification: Notification) -> Void { getSubject(notification).post() } func getSubject(_ notification: Notification) -> Subject { guard let subject = center[notification.name] else { center[notification.name] = Subject(notification: notification, observers: [Observer]()) return self.getSubject(notification) } subject.notification = notification return subject } func add(observer: AnyObject , aSelector: Selector , aName: String) -> Void { var sub = center[aName] if sub == nil { sub = Subject(notification: nil, observers: [Observer]()) center[aName] = sub } sub?.add(observer: Observer(observer: observer, selector: aSelector)) } func remove(observer: AnyObject , name: String) -> Void { guard let subject = center[name] else { return } subject.remove(observer: observer as! Observer) } override private init() { super.init() } } class PostOffice: NSObject { func send(message: AnyObject) -> Void { PostCenter.defaultCenter().post(Notification(name: "PostMessage", object: self, info: ["info": message] )) } } class User: NSObject { func subscription() -> Void { PostCenter.defaultCenter().add(observer: self, aSelector: #selector(User.incept(_:)), aName: "PostMessage") } @objc func incept(_ message: Notification) -> Void { guard let msg = message.info else { print("no message") return } print(msg) } deinit { PostCenter.defaultCenter().remove(observer: self, name: "PostMessage") } } let postman = PostOffice() let user1 = User() let user2 = User() let user3 = User() user1.subscription() user2.subscription() postman.send(message: "post 1" as AnyObject) postman.send(message: "post 2" as AnyObject) postman.send(message: "post 3" as AnyObject)
22.074713
115
0.571986
224b87ba5fa0d2bff1e63a8665ae804e10601449
950
// // Implement strStr().swift // LeetCode // // Created by Kagen Zhao on 2017/6/13. // Copyright © 2017年 kagenZhao. All rights reserved. // import Foundation /* Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. */ class ImplementStrStr { func strStr(_ haystack: String, _ needle: String) -> Int { let hayChars = [Character](haystack) let needleChars = [Character](needle) guard hayChars.count >= needleChars.count else { return -1 } guard needleChars.count > 0 else { return 0 } var i = 0 var j = 0 while i < hayChars.count, j < needleChars.count { if hayChars[i] == needleChars[j] { i += 1 j += 1 } else { i = i - j + 1 j = 0 } } return j == needleChars.count ? i - j : -1 } }
24.358974
106
0.541053
e90c5ced088ffd45ca217198f7db2af33d18db5a
7,425
// // CoreDataManagerExtension.swift // Time Tracking Widget // // Created by Jonathan Kummerfeld on 20/9/20. // Copyright © 2020 Jonathan Kummerfeld. All rights reserved. // import Foundation import CoreData // From https://www.avanderlee.com/swift/persistent-history-tracking-core-data/ public enum AppTarget: String, CaseIterable { case app case todayExtension } public final class PersistentHistoryObserverExtension { private let target: AppTarget private let userDefaults: UserDefaults private let persistentContainer: NSPersistentContainer /// An operation queue for processing history transactions. private lazy var historyQueue: OperationQueue = { let queue = OperationQueue() queue.maxConcurrentOperationCount = 1 return queue }() public init(target: AppTarget, persistentContainer: NSPersistentContainer, userDefaults: UserDefaults) { self.target = target self.userDefaults = userDefaults self.persistentContainer = persistentContainer print("Created observer") } public func startObserving() { NotificationCenter.default.addObserver( self, selector: #selector(processStoreRemoteChanges), name: .NSPersistentStoreRemoteChange, object: persistentContainer.persistentStoreCoordinator ) print("Observing") } /// Process persistent history to merge changes from other coordinators. @objc private func processStoreRemoteChanges(_ notification: Notification) { print("Notified of change") historyQueue.addOperation { [weak self] in self?.processPersistentHistory() } } @objc private func processPersistentHistory() { let context = persistentContainer.newBackgroundContext() context.performAndWait { do { let merger = PersistentHistoryMerger(backgroundContext: context, viewContext: persistentContainer.viewContext, currentTarget: target, userDefaults: userDefaults) try merger.merge() let cleaner = PersistentHistoryCleaner(context: context, targets: AppTarget.allCases, userDefaults: userDefaults) try cleaner.clean() } catch { print("Persistent History Tracking failed with error \(error)") } } } } extension UserDefaults { func lastHistoryTransactionTimestamp(for target: AppTarget) -> Date? { let key = "lastHistoryTransactionTimeStamp-\(target.rawValue)" return object(forKey: key) as? Date } func updateLastHistoryTransactionTimestamp(for target: AppTarget, to newValue: Date?) { let key = "lastHistoryTransactionTimeStamp-\(target.rawValue)" set(newValue, forKey: key) } func lastCommonTransactionTimestamp(in targets: [AppTarget]) -> Date? { let timestamp = targets .map { lastHistoryTransactionTimestamp(for: $0) ?? .distantPast } .min() ?? .distantPast return timestamp > .distantPast ? timestamp : nil } } extension Collection where Element == NSPersistentHistoryTransaction { /// Merges the current collection of history transactions into the given managed object context. /// - Parameter context: The managed object context in which the history transactions should be merged. func merge(into context: NSManagedObjectContext) { forEach { transaction in guard let userInfo = transaction.objectIDNotification().userInfo else { return } NSManagedObjectContext.mergeChanges(fromRemoteContextSave: userInfo, into: [context]) } } } struct PersistentHistoryFetcher { enum Error: Swift.Error { /// In case that the fetched history transactions couldn't be converted into the expected type. case historyTransactionConvertionFailed } let context: NSManagedObjectContext let fromDate: Date func fetch() throws -> [NSPersistentHistoryTransaction] { let fetchRequest = createFetchRequest() guard let historyResult = try context.execute(fetchRequest) as? NSPersistentHistoryResult, let history = historyResult.result as? [NSPersistentHistoryTransaction] else { throw Error.historyTransactionConvertionFailed } return history } func createFetchRequest() -> NSPersistentHistoryChangeRequest { let historyFetchRequest = NSPersistentHistoryChangeRequest .fetchHistory(after: fromDate) if let fetchRequest = NSPersistentHistoryTransaction.fetchRequest { var predicates: [NSPredicate] = [] if let transactionAuthor = context.transactionAuthor { /// Only look at transactions created by other targets. predicates.append(NSPredicate(format: "%K != %@", #keyPath(NSPersistentHistoryTransaction.author), transactionAuthor)) } //if let contextName = context.name { // /// Only look at transactions not from our current context. // predicates.append(NSPredicate(format: "%K != %@", #keyPath(NSPersistentHistoryTransaction.contextName), contextName)) //} fetchRequest.predicate = NSCompoundPredicate(type: .and, subpredicates: predicates) historyFetchRequest.fetchRequest = fetchRequest } return historyFetchRequest } } struct PersistentHistoryMerger { let backgroundContext: NSManagedObjectContext let viewContext: NSManagedObjectContext let currentTarget: AppTarget let userDefaults: UserDefaults func merge() throws { let fromDate = userDefaults.lastHistoryTransactionTimestamp(for: currentTarget) ?? .distantPast let fetcher = PersistentHistoryFetcher(context: backgroundContext, fromDate: fromDate) let history = try fetcher.fetch() guard !history.isEmpty else { print("No history transactions found to merge for target \(currentTarget)") return } print("Merging \(history.count) persistent history transactions for target \(currentTarget)") history.merge(into: backgroundContext) viewContext.perform { history.merge(into: self.viewContext) } guard let lastTimestamp = history.last?.timestamp else { return } userDefaults.updateLastHistoryTransactionTimestamp(for: currentTarget, to: lastTimestamp) } } struct PersistentHistoryCleaner { let context: NSManagedObjectContext let targets: [AppTarget] let userDefaults: UserDefaults /// Cleans up the persistent history by deleting the transactions that have been merged into each target. func clean() throws { guard let timestamp = userDefaults.lastCommonTransactionTimestamp(in: targets) else { print("Cancelling deletions as there is no common transaction timestamp") return } let deleteHistoryRequest = NSPersistentHistoryChangeRequest.deleteHistory(before: timestamp) print("Deleting persistent history using common timestamp \(timestamp)") try context.execute(deleteHistoryRequest) targets.forEach { target in /// Reset the dates as we would otherwise end up in an infinite loop. userDefaults.updateLastHistoryTransactionTimestamp(for: target, to: nil) } } }
38.076923
177
0.689024
56293e69fd0967dc0bd0c58f4d52f15510340a0e
195
// // PickerViewCell.swift // FlightController // // Created by Matthew Territo on 9/14/18. // Copyright © 2018 OpenSpace. All rights reserved. // class PickerViewCell: SettingsViewCell { }
17.727273
52
0.712821
0a661432a7ec1ff80091aa542be231ff6915fa63
491
// 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 func compose<T : d = T) -> { func e> { } struct c : b: Boolean>: Array<U, a<3) public var b = [c()
35.071429
78
0.708758
eb89a950a591901035f399d7f19a938d62ab0448
472
// // AppDelegate.swift // PicSplash // // Created by Marcus on 2/6/21. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let homeVC: HomeViewController = HomeViewController() window?.rootViewController = homeVC window?.makeKeyAndVisible() return true } }
19.666667
142
0.745763
50d69caaafd71cd5a43a12b183598fc224fa8b12
511
// // ViewController.swift // iOSSaurabhK // // Created by iOSlenskart on 12/26/2019. // Copyright (c) 2019 iOSlenskart. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.44
80
0.675147
5d272859f246549f0fd3b05916231587ada0d686
7,220
// // RealmObjectTests.swift // SugarRecord // // Created by Pedro Piñera Buendia on 20/09/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import XCTest import CoreData import Realm class RealmObjectTests: XCTestCase { override func setUp() { SugarRecord.addStack(DefaultREALMStack(stackName: "RealmTest", stackDescription: "Realm stack for tests")) } override func tearDown() { SugarRecord.cleanup() SugarRecord.removeDatabase() } func testObjectCreation() { var realmObject: RealmObject = RealmObject.create() as! RealmObject realmObject.name = "Realmy" realmObject.age = 22 realmObject.email = "[email protected]" realmObject.city = "TestCity" realmObject.birthday = NSDate() let saved: Bool = realmObject.save() var realmObject2: RealmObject = RealmObject.create() as! RealmObject realmObject2.name = "Realmy" realmObject2.age = 22 realmObject2.email = "[email protected]" realmObject2.city = "TestCity" realmObject2.birthday = NSDate() let saved2: Bool = realmObject2.save() XCTAssertEqual(RealmObject.all().find().count, 2, "The number of objects fetched should be equal to 2") realmObject.beginWriting().delete().endWriting() realmObject2.beginWriting().delete().endWriting() } func testObjectDeletion() { var realmObject: RealmObject = RealmObject.create() as! RealmObject realmObject.name = "Realmy" realmObject.age = 22 realmObject.email = "[email protected]" realmObject.city = "TestCity" realmObject.birthday = NSDate() let saved: Bool = realmObject.save() realmObject.beginWriting().delete().endWriting() XCTAssertEqual(RealmObject.all().find().count, 0, "The number of objects fetched after the deletion should be equal to 0") } func testAllObjectsDeletion() { var realmObject: RealmObject = RealmObject.create() as! RealmObject realmObject.name = "Realmy" realmObject.age = 22 realmObject.email = "[email protected]" realmObject.city = "TestCity" realmObject.birthday = NSDate() let saved: Bool = realmObject.save() var realmObject2: RealmObject = RealmObject.create() as! RealmObject realmObject2.name = "Realmy" realmObject2.age = 22 realmObject2.email = "[email protected]" realmObject2.city = "TestCity" realmObject2.birthday = NSDate() let saved2: Bool = realmObject2.save() realmObject.beginWriting().delete().endWriting() realmObject2.beginWriting().delete().endWriting() XCTAssertEqual(RealmObject.all().find().count, 0, "The number of objects fetched after the deletion should be equal to 0") } func testObjectsEdition() { var realmObject: RealmObject? = nil realmObject = RealmObject.create() as? RealmObject realmObject?.save() realmObject!.beginWriting() realmObject!.name = "Testy" realmObject!.endWriting() let fetchedObject: RealmObject = RealmObject.allObjects().firstObject() as! RealmObject XCTAssertEqual(fetchedObject.name, "Testy", "The name of the fetched object should be Testy") realmObject!.beginWriting().delete().endWriting() } func testObjectQuerying() { var realmObject: RealmObject? = nil var realmObject2: RealmObject? = nil realmObject = RealmObject.create() as? RealmObject realmObject!.name = "Realmy" realmObject!.age = 22 realmObject!.email = "[email protected]" realmObject!.city = "TestCity" realmObject!.birthday = NSDate() let saved: Bool = realmObject!.save() realmObject2 = RealmObject.create() as? RealmObject realmObject2!.name = "Realmy2" realmObject2!.age = 22 realmObject2!.email = "[email protected]" realmObject2!.city = "TestCity2" realmObject2!.birthday = NSDate() let saved2: Bool = realmObject2!.save() XCTAssertEqual(RealmObject.all().find().count, 2, "It should return 2 elements") XCTAssertEqual(RealmObject.by("age", equalTo: "22").find().count, 2, "It should return 2 elements with the age of 22") XCTAssertEqual(RealmObject.by("age", equalTo: "10").find().count, 0, "It should return 0 elements with the age of 10") XCTAssertEqual((RealmObject.sorted(by: "name", ascending: true).first().find().firstObject() as! RealmObject).name, "Realmy", "The name of the first object returned should be Realmy") XCTAssertEqual((RealmObject.sorted(by: "name", ascending: true).last().find().firstObject() as! RealmObject).name, "Realmy2", "The name of the first object returned should be Realmy2") XCTAssertEqual(RealmObject.sorted(by: "name", ascending: true).firsts(20).find().count, 2, "The number of fetched elements using firsts should be equal to 2") XCTAssertEqual(RealmObject.sorted(by: "name", ascending: true).lasts(20).find().count, 2, "The number of fetched elements using lasts should be equal to 2") realmObject!.beginWriting().delete().endWriting() realmObject2!.beginWriting().delete().endWriting() } func testObjectsCount() { var realmObject: RealmObject? = nil var realmObject2: RealmObject? = nil realmObject = RealmObject.create() as? RealmObject realmObject!.name = "Realmy" realmObject!.age = 22 realmObject!.email = "[email protected]" realmObject!.city = "TestCity" realmObject!.birthday = NSDate() let saved: Bool = realmObject!.save() realmObject2 = RealmObject.create() as? RealmObject realmObject2!.name = "Realmy2" realmObject2!.age = 22 realmObject2!.email = "[email protected]" realmObject2!.city = "TestCity2" realmObject2!.birthday = NSDate() let saved2: Bool = realmObject2!.save() XCTAssertEqual(RealmObject.count(), 2, "The count should be equal to 2") XCTAssertEqual(RealmObject.by("name", equalTo: "'Realmy2'").count(), 1, "The count should be equal to 1") realmObject!.beginWriting().delete().endWriting() realmObject2!.beginWriting().delete().endWriting() } func testObjectsWritingCancellation() { var realmObject: RealmObject? = nil realmObject = RealmObject.create() as? RealmObject realmObject!.name = "Realmy" realmObject!.age = 22 realmObject!.email = "[email protected]" realmObject!.city = "TestCity" realmObject!.birthday = NSDate() _ = realmObject!.save() realmObject!.beginWriting().delete().cancelWriting() XCTAssertEqual(RealmObject.all().find().count, 1, "It should return 1 element because the writing transaction was cancelled") let objects = RealmObject.all().find() (objects.firstObject() as! RealmObject).beginWriting().delete().endWriting() XCTAssertEqual(RealmObject.all().find().count, 0, "It should return 0 element because the writing transaction was commited") } }
44.02439
192
0.653047
232477f5135090ac20c91de8a5a81d0f1ce0295c
4,718
/* MIT License Copyright (c) 2017-2019 MessageKit 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 enum MessageStyle { // MARK: - TailCorner public enum TailCorner: String { case topLeft case bottomLeft case topRight case bottomRight internal var imageOrientation: UIImage.Orientation { switch self { case .bottomRight: return .up case .bottomLeft: return .upMirrored case .topLeft: return .down case .topRight: return .downMirrored } } } // MARK: - TailStyle public enum TailStyle { case curved case pointedEdge internal var imageNameSuffix: String { switch self { case .curved: return "_tail_v2" case .pointedEdge: return "_tail_v1" } } } // MARK: - MessageStyle case none case bubble case bubbleOutline(UIColor) case bubbleTail(TailCorner, TailStyle) case bubbleTailOutline(UIColor, TailCorner, TailStyle) case custom((MessageContainerView) -> Void) // MARK: - Public public var image: UIImage? { if let imageCacheKey = imageCacheKey, let cachedImage = MessageStyle.bubbleImageCache.object(forKey: imageCacheKey as NSString) { return cachedImage } guard let imageName = imageName, var image = UIImage(named: imageName, in: Bundle.messageKitAssetBundle, compatibleWith: nil) else { return nil } switch self { case .none, .custom: return nil case .bubble, .bubbleOutline: break case .bubbleTail(let corner, _), .bubbleTailOutline(_, let corner, _): guard let cgImage = image.cgImage else { return nil } image = UIImage(cgImage: cgImage, scale: image.scale, orientation: corner.imageOrientation) } let stretchedImage = stretch(image) if let imageCacheKey = imageCacheKey { MessageStyle.bubbleImageCache.setObject(stretchedImage, forKey: imageCacheKey as NSString) } return stretchedImage } // MARK: - Internal internal static let bubbleImageCache: NSCache<NSString, UIImage> = { let cache = NSCache<NSString, UIImage>() cache.name = "com.messagekit.MessageKit.bubbleImageCache" return cache }() // MARK: - Private private var imageCacheKey: String? { guard let imageName = imageName else { return nil } switch self { case .bubble, .bubbleOutline: return imageName case .bubbleTail(let corner, _), .bubbleTailOutline(_, let corner, _): return imageName + "_" + corner.rawValue default: return nil } } private var imageName: String? { switch self { case .bubble: return "bubble_full" case .bubbleOutline: return "bubble_outlined" case .bubbleTail(_, let tailStyle): return "bubble_full" + tailStyle.imageNameSuffix case .bubbleTailOutline(_, _, let tailStyle): return "bubble_outlined" + tailStyle.imageNameSuffix case .none, .custom: return nil } } private func stretch(_ image: UIImage) -> UIImage { let center = CGPoint(x: image.size.width / 2, y: image.size.height) let capInsets = UIEdgeInsets(top: center.y, left: center.x, bottom: center.y, right: center.x) return image.resizableImage(withCapInsets: capInsets, resizingMode: .stretch) } }
31.66443
137
0.636499
226f058c039182f3af8bbd32d870dc911824d981
2,858
// // WobblingViewHandler.swift // goSellSDK // // Copyright © 2019 Tap Payments. All rights reserved. // import CoreGraphics import class QuartzCore.CAAnimation.CAKeyframeAnimation import var QuartzCore.CAMediaTiming.kCAFillModeForwards import struct QuartzCore.CATransform3D.CATransform3D import func QuartzCore.CATransform3D.CATransform3DMakeRotation import class UIKit.UIView.UIView internal protocol WobblingViewHandler { var wobblingView: UIView { get } } internal extension WobblingViewHandler { func startWobbling(with angle: CGFloat = CGFloat.pi / 36.0, duration: TimeInterval = 0.3) { if self.wobblingView.layer.animation(forKey: WobblingConstants.wobbleAnimationKey) != nil { self.stopWobbling() } let timeOffset: Double = duration * TimeInterval(Float(arc4random()) / Float(UInt32.max)) let wobbleAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: WobblingConstants.animationKeyPath) wobbleAnimation.values = self.wobbleAnimationValues(for: angle) wobbleAnimation.keyTimes = self.animationTimings #if swift(>=4.2) wobbleAnimation.fillMode = .forwards #else wobbleAnimation.fillMode = kCAFillModeForwards #endif wobbleAnimation.isRemovedOnCompletion = false wobbleAnimation.repeatCount = Float.greatestFiniteMagnitude wobbleAnimation.timeOffset = timeOffset wobbleAnimation.duration = duration self.wobblingView.layer.add(wobbleAnimation, forKey: WobblingConstants.wobbleAnimationKey) } func stopWobbling() { self.wobblingView.layer.removeAnimation(forKey: WobblingConstants.wobbleAnimationKey) } private var animationTimings: [NSNumber] { return [0.0, 0.25, 0.75, 1.0] } private func wobbleAnimationValues(for angle: CGFloat) -> [NSValue] { let value1: CATransform3D = CATransform3DMakeRotation(0.0, 0.0, 0.0, 1.0) let value2: CATransform3D = CATransform3DMakeRotation(-angle, 0.0, 0.0, 1.0) let value3: CATransform3D = CATransform3DMakeRotation(angle, 0.0, 0.0, 1.0) let value4: CATransform3D = CATransform3DMakeRotation(0.0, 0.0, 0.0, 1.0) return [ NSValue(caTransform3D: value1), NSValue(caTransform3D: value2), NSValue(caTransform3D: value3), NSValue(caTransform3D: value4) ] } } private struct WobblingConstants { fileprivate static let animationKeyPath: String = "transform" fileprivate static let wobbleAnimationKey: String = "wobble" //@available(*, unavailable) private init() { } }
35.725
118
0.654304
26e73d379d17b281b5f0070a5735207508124791
905
// // SummflowerTests.swift // SummflowerTests // // Created by Sameh Mabrouk on 1/3/15. // Copyright (c) 2015 SMApps. All rights reserved. // import UIKit import XCTest class SummflowerTests: 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. } } }
24.459459
111
0.616575
61d6ee7e48fcba24c47a2c51dc264ca2aa859365
482
import Foundation // 69. Sqrt(x) // https://leetcode.com/problems/sqrtx/ class Solution { func mySqrt(_ x: Int) -> Int { return Int(sqrt(Double(x))) } } import XCTest // Executed 2 tests, with 0 failures (0 unexpected) in 0.005 (0.007) seconds class Tests: XCTestCase { private let s = Solution() func test0() { XCTAssertEqual(s.mySqrt(4), 2) } func test1() { XCTAssertEqual(s.mySqrt(8), 2) } } Tests.defaultTestSuite.run()
17.851852
76
0.616183
cce6d705d43121dfcbcf9bd090d96e553a25f68a
1,964
// // AnotherFakeAPI.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation extension PetstoreClient { open class AnotherFakeAPI { /** To test special tags - parameter body: (body) client model - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): completion(response.body, nil) case let .failure(error): completion(nil, error) } } } /** To test special tags - PATCH /another-fake/dummy - To test special tags and operation ID starting with number - parameter body: (body) client model - returns: RequestBuilder<Client> */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder<Client> { let path = "/another-fake/dummy" let URLString = PetstoreClient.basePath + path let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let urlComponents = URLComponents(string: URLString) let nillableHeaders: [String: Any?] = [ : ] let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder<Client>.Type = PetstoreClient.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) } } }
33.288136
193
0.675153
9ba576fce3afe7f566dc558cadaa324b2aef760d
11,128
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation import Alamofire /// Manages and sends APIRequests public class APIClient { public static var `default` = APIClient(baseURL: TBX.Server.main) /// A list of RequestBehaviours that can be used to monitor and alter all requests public var behaviours: [RequestBehaviour] = [] /// The base url prepended before every request path public var baseURL: String /// The Alamofire SessionManager used for each request public var sessionManager: SessionManager /// These headers will get added to every request public var defaultHeaders: [String: String] public var jsonDecoder = JSONDecoder() public var jsonEncoder = JSONEncoder() public var decodingQueue = DispatchQueue(label: "apiClient", qos: .utility, attributes: .concurrent) public init(baseURL: String, sessionManager: SessionManager = .default, defaultHeaders: [String: String] = [:], behaviours: [RequestBehaviour] = []) { self.baseURL = baseURL self.sessionManager = sessionManager self.behaviours = behaviours self.defaultHeaders = defaultHeaders jsonDecoder.dateDecodingStrategy = .custom(dateDecoder) jsonEncoder.dateEncodingStrategy = .formatted(TBX.dateEncodingFormatter) } /// Makes a network request /// /// - Parameters: /// - request: The API request to make /// - behaviours: A list of behaviours that will be run for this request. Merged with APIClient.behaviours /// - completionQueue: The queue that complete will be called on /// - complete: A closure that gets passed the APIResponse /// - Returns: A cancellable request. Not that cancellation will only work after any validation RequestBehaviours have run @discardableResult public func makeRequest<T>(_ request: APIRequest<T>, behaviours: [RequestBehaviour] = [], completionQueue: DispatchQueue = DispatchQueue.main, complete: @escaping (APIResponse<T>) -> Void) -> CancellableRequest? { // create composite behaviour to make it easy to call functions on array of behaviours let requestBehaviour = RequestBehaviourGroup(request: request, behaviours: self.behaviours + behaviours) // create the url request from the request var urlRequest: URLRequest do { urlRequest = try request.createURLRequest(baseURL: baseURL, encoder: jsonEncoder) } catch { let error = APIClientError.requestEncodingError(error) requestBehaviour.onFailure(error: error) let response = APIResponse<T>(request: request, result: .failure(error)) complete(response) return nil } // add the default headers if urlRequest.allHTTPHeaderFields == nil { urlRequest.allHTTPHeaderFields = [:] } for (key, value) in defaultHeaders { urlRequest.allHTTPHeaderFields?[key] = value } urlRequest = requestBehaviour.modifyRequest(urlRequest) let cancellableRequest = CancellableRequest(request: request.asAny()) requestBehaviour.validate(urlRequest) { result in switch result { case .success(let urlRequest): self.makeNetworkRequest(request: request, urlRequest: urlRequest, cancellableRequest: cancellableRequest, requestBehaviour: requestBehaviour, completionQueue: completionQueue, complete: complete) case .failure(let error): let error = APIClientError.validationError(error) let response = APIResponse<T>(request: request, result: .failure(error), urlRequest: urlRequest) requestBehaviour.onFailure(error: error) complete(response) } } return cancellableRequest } private func makeNetworkRequest<T>(request: APIRequest<T>, urlRequest: URLRequest, cancellableRequest: CancellableRequest, requestBehaviour: RequestBehaviourGroup, completionQueue: DispatchQueue, complete: @escaping (APIResponse<T>) -> Void) { requestBehaviour.beforeSend() if request.service.isUpload { sessionManager.upload( multipartFormData: { multipartFormData in for (name, value) in request.formParameters { if let file = value as? UploadFile { switch file.type { case let .url(url): if let fileName = file.fileName, let mimeType = file.mimeType { multipartFormData.append(url, withName: name, fileName: fileName, mimeType: mimeType) } else { multipartFormData.append(url, withName: name) } case let .data(data): if let fileName = file.fileName, let mimeType = file.mimeType { multipartFormData.append(data, withName: name, fileName: fileName, mimeType: mimeType) } else { multipartFormData.append(data, withName: name) } } } else if let url = value as? URL { multipartFormData.append(url, withName: name) } else if let data = value as? Data { multipartFormData.append(data, withName: name) } else if let string = value as? String { multipartFormData.append(Data(string.utf8), withName: name) } } }, with: urlRequest, encodingCompletion: { result in switch result { case .success(let uploadRequest, _, _): cancellableRequest.networkRequest = uploadRequest uploadRequest.responseData { dataResponse in self.handleResponse(request: request, requestBehaviour: requestBehaviour, dataResponse: dataResponse, completionQueue: completionQueue, complete: complete) } case .failure(let error): let apiError = APIClientError.requestEncodingError(error) requestBehaviour.onFailure(error: apiError) let response = APIResponse<T>(request: request, result: .failure(apiError)) completionQueue.async { complete(response) } } }) } else { let networkRequest = sessionManager.request(urlRequest) .responseData(queue: decodingQueue) { dataResponse in self.handleResponse(request: request, requestBehaviour: requestBehaviour, dataResponse: dataResponse, completionQueue: completionQueue, complete: complete) } cancellableRequest.networkRequest = networkRequest } } private func handleResponse<T>(request: APIRequest<T>, requestBehaviour: RequestBehaviourGroup, dataResponse: DataResponse<Data>, completionQueue: DispatchQueue, complete: @escaping (APIResponse<T>) -> Void) { let result: APIResult<T> switch dataResponse.result { case .success(let value): do { let statusCode = dataResponse.response!.statusCode let decoded = try T(statusCode: statusCode, data: value, decoder: jsonDecoder) result = .success(decoded) if decoded.successful { requestBehaviour.onSuccess(result: decoded.response as Any) } } catch let error { let apiError: APIClientError if let error = error as? DecodingError { apiError = APIClientError.decodingError(error) } else if let error = error as? APIClientError { apiError = error } else { apiError = APIClientError.unknownError(error) } result = .failure(apiError) requestBehaviour.onFailure(error: apiError) } case .failure(let error): let apiError = APIClientError.networkError(error) result = .failure(apiError) requestBehaviour.onFailure(error: apiError) } let response = APIResponse<T>(request: request, result: result, urlRequest: dataResponse.request, urlResponse: dataResponse.response, data: dataResponse.data, timeline: dataResponse.timeline) requestBehaviour.onResponse(response: response.asAny()) completionQueue.async { complete(response) } } } public class CancellableRequest { /// The request used to make the actual network request public let request: AnyRequest init(request: AnyRequest) { self.request = request } var networkRequest: Request? /// cancels the request public func cancel() { if let networkRequest = networkRequest { networkRequest.cancel() } } } // Helper extension for sending requests extension APIRequest { /// makes a request using the default APIClient. Change your baseURL in APIClient.default.baseURL public func makeRequest(complete: @escaping (APIResponse<ResponseType>) -> Void) { APIClient.default.makeRequest(self, complete: complete) } } // Create URLRequest extension APIRequest { /// pass in an optional baseURL, otherwise URLRequest.url will be relative public func createURLRequest(baseURL: String = "", encoder: RequestEncoder = JSONEncoder()) throws -> URLRequest { let url = URL(string: "\(baseURL)\(path)")! var urlRequest = URLRequest(url: url) urlRequest.httpMethod = service.method urlRequest.allHTTPHeaderFields = headers // filter out parameters with empty string value var queryParams: [String: Any] = [:] for (key, value) in queryParameters { if String.init(describing: value) != "" { queryParams[key] = value } } if !queryParams.isEmpty { urlRequest = try URLEncoding.queryString.encode(urlRequest, with: queryParams) } var formParams: [String: Any] = [:] for (key, value) in formParameters { if String.init(describing: value) != "" { formParams[key] = value } } if !formParams.isEmpty { urlRequest = try URLEncoding.httpBody.encode(urlRequest, with: formParams) } if let encodeBody = encodeBody { urlRequest.httpBody = try encodeBody(encoder) urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } return urlRequest } }
43.98419
247
0.603972
1ad72ca40350ec83558f0eecec5ec5e80ab91823
4,099
// // DIContainer+getGraph.swift // DITranquillity // // Created by Alexander Ivlev on 30.06.2020. // Copyright © 2020 Alexander Ivlev. All rights reserved. // extension DIContainer { /// Make graph for public usage. /// Your can call `checkIsValid` for check for correct. /// Or Your can use this graph for dependency analysis. /// - Returns: Dependency graph public func makeGraph() -> DIGraph { let components = componentContainer.components var edgeId: Int = 0 var vertices: [DIVertex] = components.map { .component(DIComponentVertex(component: $0)) } var adjacencyList: DIGraph.AdjacencyList = Array(repeating: [], count: vertices.count) for (index, component) in components.enumerated() { // get all paramaters - from init and injection let parametersInfo = componentParametersInfo(component: component) for (parameter, initial, cycle) in parametersInfo { // ignore reference on self if parameter.parsedType.useObject { continue } edgeId += 1 let edge = DIEdge(by: parameter, id: edgeId, initial: initial, cycle: cycle) if addArgumentIfNeeded(by: parameter.parsedType, adjacencyList: &adjacencyList, vertices: &vertices) { adjacencyList[index].append((edge, [vertices.count - 1])) continue } let candidates = resolver.findComponents(by: parameter.parsedType, with: parameter.name, from: component.framework) let toIndices = candidates.compactMap { findIndex(for: $0, in: components) } assert(candidates.count == toIndices.count) // not found candidates - need add reference on unknown type if toIndices.isEmpty { addUnknown(by: parameter.parsedType, adjacencyList: &adjacencyList, vertices: &vertices) adjacencyList[index].append((edge, [vertices.count - 1])) continue } adjacencyList[index].append((edge, toIndices)) } } return DIGraph(vertices: vertices, adjacencyList: adjacencyList) } private func findIndex(for component: Component, in components: [Component]) -> Int? { if components.isEmpty { return nil } let count = components.count var left = 0 var right = count while left <= right { let center = (right + left) / 2 if components[center] === component { return center } if component.order < components[center].order { right = center - 1 } else { left = center + 1 } } return nil } private func addArgumentIfNeeded(by parsedType: ParsedType, adjacencyList: inout DIGraph.AdjacencyList, vertices: inout [DIVertex]) -> Bool { if !parsedType.arg { return false } let baseType = parsedType.base let argType = baseType.sType?.type ?? baseType.type let id = vertices.count addVertex(DIVertex.argument(DIArgumentVertex(id: id, type: argType)), adjacencyList: &adjacencyList, vertices: &vertices) return true } private func addUnknown(by parsedType: ParsedType, adjacencyList: inout DIGraph.AdjacencyList, vertices: inout [DIVertex]) { let id = vertices.count let baseType = parsedType.base let unknownType = baseType.sType?.type ?? baseType.type addVertex(DIVertex.unknown(DIUnknownVertex(id: id, type: unknownType)), adjacencyList: &adjacencyList, vertices: &vertices) } private func addVertex(_ vertex: DIVertex, adjacencyList: inout DIGraph.AdjacencyList, vertices: inout [DIVertex]) { adjacencyList.append([]) vertices.append(vertex) } typealias ParameterInfo = (parameter: MethodSignature.Parameter, initial: Bool, cycle: Bool) private func componentParametersInfo(component: Component) -> [ParameterInfo] { var result: [ParameterInfo] = [] if let initial = component.initial { result.append(contentsOf: initial.parameters.map { ($0, true, false) }) } for injection in component.injections { result.append(contentsOf: injection.signature.parameters.map{ ($0, false, injection.cycle) }) } return result } }
33.325203
143
0.675531
f7c48fd40fee8d61aeac7a482280907d3bec7794
248
// // User.swift // FilmApp // // Struct to save user data. // // Created by Sophie Ensing on 24-01-18. // Copyright © 2018 Sophie Ensing. All rights reserved. // import Foundation struct User { var id: String var username: String }
14.588235
56
0.649194
fe154d07c22480881ec7653f72d042c79ee88907
253
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum S { let end = [ { extension NSSet { class A { init { protocol B { class case ,
19.461538
87
0.727273
29410fe7b51af84aa795e4c70e1694c13de2ca2e
126
import Database func makeCommitMultiStore(database: Database) -> CommitMultiStore { RootMultiStore(database: database) }
21
67
0.793651
56dd3ca437211487e1f65daec4a8a81fe974bc1a
11,195
// // URLQueryItemsEncoder.swift // URLQueryItemsCoder // // Created by Koji Murata on 2020/01/08. // import Foundation open class URLQueryItemsEncoder { public init() {} public func encode<T: Encodable>(_ value: T) throws -> [URLQueryItem] { return try NodeEncoder().encode(value).toURLQueryItems() } } fileprivate final class Node { var dict: [(String, Node)]? var array: [Node]? var value: String? static var empty: Node { Node(dict: nil, array: nil, value: nil, kind: .empty) } static func single(_ value: String) -> Node { Node(dict: nil, array: nil, value: value, kind: .single) } init(dict: [(String, Node)]?, array: [Node]?, value: String?, kind: Kind) { self.dict = dict self.array = array self.value = value self.kind = kind } private var kind = Kind.empty enum Kind { case keyed case unkeyed case single case empty } func addChild(node: Node, forKey key: String) throws { switch kind { case .empty: kind = .keyed dict = [(key, node)] case .keyed: dict!.append((key, node)) default: throw Errors.crossContainer } } func addChild(node: Node) throws { switch kind { case .empty: kind = .unkeyed array = [node] case .unkeyed: array!.append(node) default: throw Errors.crossContainer } } func setValue(_ value: String) throws { switch kind { case .empty: kind = .single self.value = value case .single: self.value = value default: throw Errors.crossContainer } } func forceCopy(_ target: Node) { self.dict = target.dict self.array = target.array self.value = target.value self.kind = target.kind } func toURLQueryItems() throws -> [URLQueryItem] { switch kind { case .keyed: return dict!.flatMap { $1.toKeyValues(parentKey: $0).map { URLQueryItem(name: $0, value: $1) } } case .empty: return [] default: throw Errors.unsupported } } private func toKeyValues(parentKey: String) -> [(String, String)] { switch kind { case .keyed: return dict!.flatMap { $1.toKeyValues(parentKey: "\(parentKey)[\($0)]") } case .unkeyed: return array!.enumerated().flatMap { $1.toKeyValues(parentKey: "\(parentKey)[\($0)]") } case .single: return [(parentKey, value!)] case .empty: return [] } } } fileprivate class NodeEncoder: Encoder { var codingPath: [CodingKey] var userInfo: [CodingUserInfoKey : Any] { [:] } private var node = Node.empty fileprivate init(codingPath: [CodingKey] = []) { self.codingPath = codingPath } func container<Key: CodingKey>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> { KeyedEncodingContainer(KeyedContainer(targetNode: node, encoder: self, codingPath: codingPath)) } func unkeyedContainer() -> UnkeyedEncodingContainer { UnkeyedContainer(targetNode: node, encoder: self, codingPath: codingPath) } func singleValueContainer() -> SingleValueEncodingContainer { SingleValueContainer(targetNode: node, encoder: self, codingPath: codingPath) } func encode<T: Encodable>(_ value: T) throws -> Node { try value.encode(to: self) return node } private class KeyedContainer<Key: CodingKey>: KeyedEncodingContainerProtocol { private(set) var codingPath: [CodingKey] private let encoder: NodeEncoder private let targetNode: Node init(targetNode: Node, encoder: NodeEncoder, codingPath: [CodingKey]) { self.targetNode = targetNode self.encoder = encoder self.codingPath = codingPath } private func setNode(_ node: Node, forKey key: Key) throws { try targetNode.addChild(node: node, forKey: key.stringValue) } private func setNode<T: CustomStringConvertible>(_ value: T, forKey key: Key) throws { try setNode(.single(value.description), forKey: key) } func encodeNil(forKey key: Key) throws {} func encode(_ value: Bool, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: String, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: Double, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: Float, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: Int, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: Int8, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: Int16, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: Int32, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: Int64, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: UInt, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: UInt8, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: UInt16, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: UInt32, forKey key: Key) throws { try setNode(value, forKey: key) } func encode(_ value: UInt64, forKey key: Key) throws { try setNode(value, forKey: key) } func encode<T: Encodable>(_ value: T, forKey key: Key) throws { try setNode(try NodeEncoder().encode(value), forKey: key) } func nestedContainer<NestedKey: CodingKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { let nestedNode = Node.empty try! setNode(nestedNode, forKey: key) return KeyedEncodingContainer(KeyedContainer<NestedKey>(targetNode: nestedNode, encoder: encoder, codingPath: codingPath)) } func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { let nestedNode = Node.empty try! setNode(nestedNode, forKey: key) return UnkeyedContainer(targetNode: nestedNode, encoder: encoder, codingPath: codingPath) } func superEncoder() -> Encoder { encoder } func superEncoder(forKey key: Key) -> Encoder { encoder } } private class UnkeyedContainer: UnkeyedEncodingContainer { var count: Int { encoder.node.array?.count ?? 0 } private(set) var codingPath: [CodingKey] private let encoder: NodeEncoder private let targetNode: Node init(targetNode: Node, encoder: NodeEncoder, codingPath: [CodingKey]) { self.targetNode = targetNode self.encoder = encoder self.codingPath = codingPath } private func setNode(_ node: Node) throws { try targetNode.addChild(node: node) } private func setNode<T: CustomStringConvertible>(_ value: T) throws { try setNode(.single(value.description)) } func encodeNil() throws { throw Errors.unsupported } func encode(_ value: Bool) throws { try setNode(value) } func encode(_ value: String) throws { try setNode(value) } func encode(_ value: Double) throws { try setNode(value) } func encode(_ value: Float) throws { try setNode(value) } func encode(_ value: Int) throws { try setNode(value) } func encode(_ value: Int8) throws { try setNode(value) } func encode(_ value: Int16) throws { try setNode(value) } func encode(_ value: Int32) throws { try setNode(value) } func encode(_ value: Int64) throws { try setNode(value) } func encode(_ value: UInt) throws { try setNode(value) } func encode(_ value: UInt8) throws { try setNode(value) } func encode(_ value: UInt16) throws { try setNode(value) } func encode(_ value: UInt32) throws { try setNode(value) } func encode(_ value: UInt64) throws { try setNode(value) } func encode<T: Encodable>(_ value: T) throws { try setNode(try NodeEncoder().encode(value)) } func nestedContainer<NestedKey: CodingKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { let nestedNode = Node.empty try! setNode(nestedNode) return KeyedEncodingContainer(KeyedContainer<NestedKey>(targetNode: nestedNode, encoder: encoder, codingPath: codingPath)) } func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { let nestedNode = Node.empty try! setNode(nestedNode) return UnkeyedContainer(targetNode: nestedNode, encoder: encoder, codingPath: codingPath) } func superEncoder() -> Encoder { encoder } struct IndexCodingKey: CodingKey { init?(stringValue: String) { nil } let stringValue = "" var intValue: Int? init?(intValue: Int) { self.intValue = intValue } init(index: Int) { intValue = index } } } private class SingleValueContainer: SingleValueEncodingContainer { private(set) var codingPath: [CodingKey] private let encoder: NodeEncoder private let targetNode: Node init(targetNode: Node, encoder: NodeEncoder, codingPath: [CodingKey]) { self.targetNode = targetNode self.encoder = encoder self.codingPath = codingPath } private func setNode<T: CustomStringConvertible>(_ value: T) throws { try targetNode.setValue(value.description) } func encodeNil() throws {} func encode(_ value: Bool) throws { try setNode(value) } func encode(_ value: String) throws { try setNode(value) } func encode(_ value: Double) throws { try setNode(value) } func encode(_ value: Float) throws { try setNode(value) } func encode(_ value: Int) throws { try setNode(value) } func encode(_ value: Int8) throws { try setNode(value) } func encode(_ value: Int16) throws { try setNode(value) } func encode(_ value: Int32) throws { try setNode(value) } func encode(_ value: Int64) throws { try setNode(value) } func encode(_ value: UInt) throws { try setNode(value) } func encode(_ value: UInt8) throws { try setNode(value) } func encode(_ value: UInt16) throws { try setNode(value) } func encode(_ value: UInt32) throws { try setNode(value) } func encode(_ value: UInt64) throws { try setNode(value) } func encode<T: Encodable>(_ value: T) throws { targetNode.forceCopy(try NodeEncoder().encode(value)) } } }
38.078231
139
0.61063
e86543c47d045e51c4b7442e21537401879d9f39
12,694
// // ReflectionSpaceImagePickerManager.swift // MFL-Common // // Created by Alex Miculescu on 16/11/2017. // import Foundation import UIKit import PKHUD import DKImagePickerController import Photos import AVFoundation import MobileCoreServices import MBProgressHUD class ReflectionSpaceImagePickerManager : NSObject { fileprivate weak var navigationController : UINavigationController? fileprivate var contentCallback : ReflectionSpaceContentCallback? init(_ navigationController: UINavigationController?) { self.navigationController = navigationController } func presentImagePicker(from source: UIImagePickerControllerSourceType, callback: ReflectionSpaceContentCallback?) { contentCallback = callback if source == .photoLibrary { requestAccessToLibrary() { if let alert = $0 { self.handleCallback(with: alert) return } self.presentImageFetcher(from: .photoLibrary) } } else { requestAccessToCamera() { if let alert = $0 { self.handleCallback(with: alert) return } self.requestAccessToMicrophone() { if let alert = $0 { self.handleCallback(with: alert) return } self.presentImageFetcher(from: .camera) } } } } private func requestAccessToLibrary(callback: @escaping (UIAlertController?) -> Void) { switch PHPhotoLibrary.authorizationStatus() { case .authorized: callback(nil) case .denied: callback(libraryDeniedAlert()) case .restricted: callback(libraryRestrictedAlert()) case .notDetermined: PHPhotoLibrary.requestAuthorization() { switch $0 { case .authorized: DispatchQueue.main.async { callback(nil) } case .denied: DispatchQueue.main.async { callback(self.libraryDeniedAlert()) } case .restricted: DispatchQueue.main.async { callback(self.libraryRestrictedAlert()) } case .notDetermined: DispatchQueue.main.async{ self.requestAccessToLibrary(callback: callback) } // should not be possible to get here } } } } private func requestAccessToCamera(callback: @escaping (UIAlertController?) -> Void) { switch AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) { case .authorized: DispatchQueue.main.async { callback(nil) } case .denied: callback(cameraDeniedAlert()) case .restricted: callback(cameraRestrictedAlert()) case .notDetermined: AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { granted in if granted { DispatchQueue.main.async { callback(nil) } } else { DispatchQueue.main.async { callback(self.cameraDeniedAlert()) } } } } } private func requestAccessToMicrophone(callback: @escaping (UIAlertController?) -> Void) { AVAudioSession.sharedInstance().requestRecordPermission() { granted in if granted { DispatchQueue.main.async { callback(nil) } } else { DispatchQueue.main.async { callback(self.microphoneDeniedAlert()) } } } } private func libraryDeniedAlert() -> UIAlertController { return UIAlertController.okAlertWith(title: NSLocalizedString("Denied", comment: ""), message: NSLocalizedString("You have denied us access to your photo library. To allow access please do so via \"Settings\".", comment: "")) } private func libraryRestrictedAlert() -> UIAlertController { return UIAlertController.okAlertWith(title: NSLocalizedString("Restricted", comment: ""), message: NSLocalizedString("It seems you do not have permission to access this device's photo library.", comment: "")) } private func cameraDeniedAlert() -> UIAlertController { return UIAlertController.okAlertWith(title: NSLocalizedString("Denied", comment: ""), message: NSLocalizedString("You have denied us access to your camera. To allow access please do so via \"Settings\".", comment: "")) } private func cameraRestrictedAlert() -> UIAlertController { return UIAlertController.okAlertWith(title: NSLocalizedString("Restricted", comment: ""), message: NSLocalizedString("It seems you do not have permission to access this device's camera.", comment: "")) } private func microphoneDeniedAlert() -> UIAlertController { return UIAlertController.okAlertWith(title: NSLocalizedString("Denied", comment: ""), message: NSLocalizedString("You have denied us access to your microphone. To allow access please do so via \"Settings\".", comment: "")) } private func handleCallback(with alert: UIAlertController) { contentCallback?([ReflectionSpaceItemType](), alert) contentCallback = nil } private func presentImageFetcher(from source: UIImagePickerControllerSourceType) { if source == .photoLibrary { presentLibraryPicker() } else { presentCameraPicker() } } private func presentCameraPicker() { let imagePicker = UIImagePickerController() imagePicker.view.backgroundColor = .white imagePicker.delegate = self imagePicker.sourceType = .camera imagePicker.mediaTypes = [kUTTypeMovie, kUTTypeImage].map { $0 as String } self.navigationController?.present(imagePicker, animated: true, completion: nil) } private func presentLibraryPicker() { let pickerController = DKImagePickerController() pickerController.maxSelectableCount = 25 pickerController.didSelectAssets = { [unowned self] (assets: [DKAsset]) in DispatchQueue(label: "saveAssets").async { var hud : MBProgressHUD? DispatchQueue.main.async { guard let view = self.navigationController?.view else { return } hud = MBProgressHUD.showAdded(to: view, animated: true) hud?.mode = .annularDeterminate hud?.label.text = NSLocalizedString("Processing your photos...", comment: "") } var items = [ReflectionSpaceItemType]() for (index, asset) in assets.enumerated() { DispatchQueue.main.async { hud?.progress = Float(index) / Float(assets.count) } guard let phAsset = asset.originalAsset else { continue } do { if let item = try self.save(phAsset) { items.append(item) } else { continue } } catch { continue } } DispatchQueue.main.async { hud?.hide(animated: true) self.contentCallback?(items, nil) self.contentCallback = nil } } } navigationController?.present(pickerController, animated: true) {} } } //MARK: - UINavigationControllerDelegate extension ReflectionSpaceImagePickerManager : UINavigationControllerDelegate { /* Empty */ } //MARK: - UIImagePickerControllerDelegate extension ReflectionSpaceImagePickerManager : UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { var item: ReflectionSpaceItemType? = nil // IS IMAGE if let image = image(from: info) { HUD.show(.progress) DispatchQueue(label: "save_image").async { do { item = try self.save(image) } catch { /* Empty */ } DispatchQueue.main.async { HUD.hide() self.closeImagePicker(with: item) } } } // IS VIDEO else if let url = videoURL(from: info) { HUD.show(.progress) DispatchQueue(label: "save_video").async { do { item = try self.saveVideo(from: url) } catch { /* Empty */ } DispatchQueue.main.async { HUD.hide() self.closeImagePicker(with: item) } } } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { contentCallback = nil navigationController?.dismiss(animated: true, completion: nil) } } func image(from info: [String : Any]) -> UIImage? { if info[UIImagePickerControllerMediaType] as! String == kUTTypeImage as String { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { return image } } return nil } func videoURL(from info: [String : Any]) -> URL? { if info[UIImagePickerControllerMediaType] as! String == kUTTypeMovie as String { if let url = info[UIImagePickerControllerMediaURL] as? URL { return url } } return nil } extension ReflectionSpaceImagePickerManager { func save(_ asset: PHAsset) throws -> ReflectionSpaceItemType? { switch asset.mediaType { case .image: return try save(asset.image()) case .video: let videoData = asset.videoData() return videoData == nil ? nil : try saveVideo(videoData!, name: nil) default: return nil } } func save(_ image: UIImage) throws -> ReflectionSpaceItemType { let orientationFixedImage = image.fixOrientation() if let imageData = UIImagePNGRepresentation(orientationFixedImage), let thumbData = UIImagePNGRepresentation(orientationFixedImage.thumbnail()) { let imageName = uniqueNameForImage() let thumbName = imageName + "_thumb" _ = try FileManager.save(imageData, with: imageName) _ = try FileManager.save(thumbData, with: thumbName) return .image(name: imageName, thumbName: thumbName) } throw NSError(domain: "Cannot create image data", code: 90000, userInfo: nil) } func saveVideo(from url: URL) throws -> ReflectionSpaceItemType? { let name = url.absoluteString.components(separatedBy: "/").last! let data = try Data(contentsOf: url) return try saveVideo(data, name: name) } func saveVideo(_ data: Data, name: String?) throws -> ReflectionSpaceItemType? { let videoName = name ?? uniqueNameForVideo() _ = try FileManager.save(data, with: videoName) var thumbName = "" if let image = FileManager.videoSnapshotWith(videoName), let thumbData = UIImagePNGRepresentation(image.thumbnail()) { thumbName = "thumb_" + videoName _ = try FileManager.save(thumbData, with: thumbName) } else { throw NSError(domain: "Cannot create thumbnail data", code: 90000, userInfo: nil) } return .video(name: videoName, thumbName: thumbName) } func uniqueNameForImage() -> String { return "ReflectionImage-\(Int(Date.timeIntervalSinceReferenceDate * 1000))" } func uniqueNameForVideo() -> String { return "ReflectionVideo-\(Int(Date.timeIntervalSinceReferenceDate * 1000)).mp4" } func closeImagePicker(with item: ReflectionSpaceItemType?) { navigationController?.dismiss(animated: true) { let items = item == nil ? [ReflectionSpaceItemType]() : [item!] self.contentCallback?(items, nil) self.contentCallback = nil } } }
38.819572
184
0.577832
ffec4970d32e78fa82b5cf5455568011054e1980
197
import Foundation @objc protocol TMUtilHelperXPC: CommonHelperXPC { func setExcluded(_ value: Bool, privilege: TMPrivilegedExclusionKind, paths: [String], reply: @escaping (Error?) -> Void) }
32.833333
125
0.761421
017b45e5f88f5547ef8b4e385ccc3aec2f3105ad
5,637
import Foundation import Capacitor import Intercom /** * Please read the Capacitor iOS Plugin Development Guide * here: https://capacitorjs.com/docs/plugins/ios */ @objc(IntercomPlugin) public class IntercomPlugin: CAPPlugin { public override func load() { let apiKey = getConfigValue("iosApiKey") as? String ?? "ADD_IN_CAPACITOR_CONFIG_JSON" let appId = getConfigValue("iosAppId") as? String ?? "ADD_IN_CAPACITOR_CONFIG_JSON" Intercom.setApiKey(apiKey, forAppId: appId) NotificationCenter.default.addObserver(self, selector: #selector(self.didRegisterWithToken(notification:)), name: Notification.Name.capacitorDidRegisterForRemoteNotifications, object: nil ) NotificationCenter.default.addObserver(self, selector: #selector(self.onUnreadConversationCountChange), name: NSNotification.Name.IntercomUnreadConversationCountDidChange, object: nil ) } @objc func didRegisterWithToken(notification: NSNotification) { guard let deviceToken = notification.object as? Data else { return } Intercom.setDeviceToken(deviceToken) } @objc func onUnreadConversationCountChange() { let unreadCount = Intercom.unreadConversationCount() self.notifyListeners("onUnreadCountChange", data: ["value":unreadCount]) } @objc func boot(_ call: CAPPluginCall) { call.unimplemented("Not implemented on iOS. Use `registerIdentifiedUser` instead.") } @objc func registerIdentifiedUser(_ call: CAPPluginCall) { let userId = call.getString("userId") let email = call.getString("email") if (userId != nil && email != nil) { Intercom.registerUser(withUserId: userId!, email: email!) call.resolve() } else if (userId != nil) { Intercom.registerUser(withUserId: userId!) call.resolve() } else if (email != nil) { Intercom.registerUser(withEmail: email!) call.resolve() } else { call.reject("No user registered. You must supply an email, userId or both") } } @objc func registerUnidentifiedUser(_ call: CAPPluginCall) { Intercom.registerUnidentifiedUser() call.resolve() } @objc func updateUser(_ call: CAPPluginCall) { let userAttributes = ICMUserAttributes() let userId = call.getString("userId") if (userId != nil) { userAttributes.userId = userId } let email = call.getString("email") if (email != nil) { userAttributes.email = email } let name = call.getString("name") if (name != nil) { userAttributes.name = name } let phone = call.getString("phone") if (phone != nil) { userAttributes.phone = phone } let languageOverride = call.getString("languageOverride") if (languageOverride != nil) { userAttributes.languageOverride = languageOverride } let customAttributes = call.getObject("customAttributes") userAttributes.customAttributes = customAttributes Intercom.updateUser(userAttributes) call.resolve() } @objc func logout(_ call: CAPPluginCall) { Intercom.logout() call.resolve() } @objc func logEvent(_ call: CAPPluginCall) { let eventName = call.getString("name") let metaData = call.getObject("data") if (eventName != nil && metaData != nil) { Intercom.logEvent(withName: eventName!, metaData: metaData!) }else if (eventName != nil) { Intercom.logEvent(withName: eventName!) } call.resolve() } @objc func displayMessenger(_ call: CAPPluginCall) { Intercom.presentMessenger(); call.resolve() } @objc func displayMessageComposer(_ call: CAPPluginCall) { guard let initialMessage = call.getString("message") else { call.reject("Enter an initial message") return } Intercom.presentMessageComposer(initialMessage); call.resolve() } @objc func displayHelpCenter(_ call: CAPPluginCall) { Intercom.presentHelpCenter() call.resolve() } @objc func hideMessenger(_ call: CAPPluginCall) { Intercom.hide() call.resolve() } @objc func displayLauncher(_ call: CAPPluginCall) { Intercom.setLauncherVisible(true) call.resolve() } @objc func hideLauncher(_ call: CAPPluginCall) { Intercom.setLauncherVisible(false) call.resolve() } @objc func displayInAppMessages(_ call: CAPPluginCall) { Intercom.setInAppMessagesVisible(true) call.resolve() } @objc func hideInAppMessages(_ call: CAPPluginCall) { Intercom.setInAppMessagesVisible(false) call.resolve() } @objc func displayCarousel(_ call: CAPPluginCall) { if let carouselId = call.getString("carouselId") { Intercom.presentCarousel(carouselId) call.resolve() }else{ call.reject("carouselId not provided to displayCarousel.") } } @objc func setUserHash(_ call: CAPPluginCall) { let hmac = call.getString("hmac") if (hmac != nil) { Intercom.setUserHash(hmac!) call.resolve() print("hmac sent to intercom") }else{ call.reject("No hmac found. Read intercom docs and generate it.") } } @objc func setBottomPadding(_ call: CAPPluginCall) { if let value = call.getString("value"), let number = NumberFormatter().number(from: value) { Intercom.setBottomPadding(CGFloat(truncating: number)) call.resolve() print("set bottom padding") } else { call.reject("Enter a value for padding bottom") } } @objc func unreadConversationCount(_ call: CAPPluginCall) { let value = Intercom.unreadConversationCount() call.resolve([ "value": value ]) } }
28.044776
89
0.677665
9b3613ba4467b6b0ead6b687cb01331aa140984d
11,413
// // IalEdxMaths2018JanList.swift // Pastpaper2021 // // Created by ZhuPinxi on 2021/12/23. // import SwiftUI import WebKit struct IalEdxMaths2018JanView: View { @State var selected = 1 var body: some View { VStack{ Picker(selection: $selected, label: Text("")){ Text("Question Paper").tag(1) Text("Mark Scheme").tag(2) Text("Examiner Report").tag(3) } .pickerStyle(SegmentedPickerStyle()) .padding(.horizontal, 10) .padding(.vertical, 6.5) if selected == 1{ IalEdxMaths2018JanList1() } if selected == 2{ IalEdxMaths2018JanList2() } if selected == 3{ IalEdxMaths2018JanList3() } } .navigationBarTitle("18 Spring", displayMode: .inline) .listStyle(.plain) .toolbar { ToolbarItem(placement: .primaryAction){ Menu() { ToolBarView() } label: { Image(systemName: "ellipsis.circle") } } } } } struct IalEdxMaths2018JanView1: View { @State var selected = 1 var body: some View { VStack{ Picker(selection: $selected, label: Text("")){ Text("Question Paper").tag(1) Text("Mark Scheme").tag(2) Text("Examiner Report").tag(3) } .pickerStyle(SegmentedPickerStyle()) .padding(.horizontal, 10) .padding(.vertical, 6.5) if selected == 1{ IalEdxMaths2018JanList1() } if selected == 2{ IalEdxMaths2018JanList2() } if selected == 3{ IalEdxMaths2018JanList3() } } .navigationBarTitle("18 Spring", displayMode: .inline) .listStyle(.plain) .toolbar { ToolbarItem(placement: .primaryAction){ Menu() { ToolBarView() } label: { Image(systemName: "ellipsis.circle") } } } } } struct IalEdxMaths2018JanList1: View { var body: some View { List { ForEach(IalMaths2018JanData1) { ialMaths2018Jan1 in NavigationLink(destination: IalEdxMaths2018JanWebView1(ialMaths2018Jan1: ialMaths2018Jan1)) { Text(ialMaths2018Jan1.name) } } } } } struct IalEdxMaths2018JanList2: View { var body: some View { List { ForEach(IalMaths2018JanData2) { ialMaths2018Jan2 in NavigationLink(destination: IalEdxMaths2018JanWebView2(ialMaths2018Jan2: ialMaths2018Jan2)) { Text(ialMaths2018Jan2.name) } } } } } struct IalEdxMaths2018JanList3: View { var body: some View { List { ForEach(IalMaths2018JanData3) { ialMaths2018Jan3 in NavigationLink(destination: IalEdxMaths2018JanWebView3(ialMaths2018Jan3: ialMaths2018Jan3)) { Text(ialMaths2018Jan3.name) } } } } } struct IalEdxMaths2018JanWebView1: View { @Environment(\.horizontalSizeClass) var horizontalSizeClass @Environment(\.verticalSizeClass) var verticalSizeClass @State private var isPresented = false @State private var isActivityPopoverPresented = false @State private var isActivitySheetPresented = false var ialMaths2018Jan1: IalMaths2018Jan1 var body: some View { Webview(url: ialMaths2018Jan1.url) .edgesIgnoringSafeArea(.all) .navigationBarTitle(ialMaths2018Jan1.name, displayMode: .inline) .navigationBarItems(trailing: shareButton) .sheet(isPresented: $isActivitySheetPresented, content: activityView) } private var shareButton: some View { Button(action: { switch (self.horizontalSizeClass, self.verticalSizeClass) { case (.regular, .regular): self.isActivityPopoverPresented.toggle() default: self.isActivitySheetPresented.toggle() let impactLight = UIImpactFeedbackGenerator(style: .light) impactLight.impactOccurred() } }, label: { Image(systemName: "square.and.arrow.up") .font(.system(size: 17)) .frame(width: 30, height: 30) .popover(isPresented: $isActivityPopoverPresented, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) { activityView() } }) } private func activityView() -> some View { let url = URL(string: ialMaths2018Jan1.url)! let filename = url.pathComponents.last! let fileManager = FileManager.default let itemURL = fileManager.temporaryDirectory.appendingPathComponent(filename) let data: Data if fileManager.fileExists(atPath: itemURL.path) { data = try! Data(contentsOf: itemURL) } else { data = try! Data(contentsOf: url) fileManager.createFile(atPath: itemURL.path, contents: data, attributes: nil) } let activityView = ActivityView(activityItems: [itemURL], applicationActivities: nil) return Group { if self.horizontalSizeClass == .regular && self.verticalSizeClass == .regular { activityView.frame(width: 333, height: 480) } else { activityView .edgesIgnoringSafeArea(.all) } } } } struct IalEdxMaths2018JanWebView2: View { @Environment(\.horizontalSizeClass) var horizontalSizeClass @Environment(\.verticalSizeClass) var verticalSizeClass @State private var isPresented = false @State private var isActivityPopoverPresented = false @State private var isActivitySheetPresented = false var ialMaths2018Jan2: IalMaths2018Jan2 var body: some View { Webview(url: ialMaths2018Jan2.url) .edgesIgnoringSafeArea(.all) .navigationBarTitle(ialMaths2018Jan2.name, displayMode: .inline) .navigationBarItems(trailing: shareButton) .sheet(isPresented: $isActivitySheetPresented, content: activityView) } private var shareButton: some View { Button(action: { switch (self.horizontalSizeClass, self.verticalSizeClass) { case (.regular, .regular): self.isActivityPopoverPresented.toggle() default: self.isActivitySheetPresented.toggle() let impactLight = UIImpactFeedbackGenerator(style: .light) impactLight.impactOccurred() } }, label: { Image(systemName: "square.and.arrow.up") .font(.system(size: 17)) .frame(width: 30, height: 30) .popover(isPresented: $isActivityPopoverPresented, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) { activityView() } }) } private func activityView() -> some View { let url = URL(string: ialMaths2018Jan2.url)! let filename = url.pathComponents.last! let fileManager = FileManager.default let itemURL = fileManager.temporaryDirectory.appendingPathComponent(filename) let data: Data if fileManager.fileExists(atPath: itemURL.path) { data = try! Data(contentsOf: itemURL) } else { data = try! Data(contentsOf: url) fileManager.createFile(atPath: itemURL.path, contents: data, attributes: nil) } let activityView = ActivityView(activityItems: [itemURL], applicationActivities: nil) return Group { if self.horizontalSizeClass == .regular && self.verticalSizeClass == .regular { activityView.frame(width: 333, height: 480) } else { activityView .edgesIgnoringSafeArea(.all) } } } } struct IalEdxMaths2018JanWebView3: View { @Environment(\.horizontalSizeClass) var horizontalSizeClass @Environment(\.verticalSizeClass) var verticalSizeClass @State private var isPresented = false @State private var isActivityPopoverPresented = false @State private var isActivitySheetPresented = false var ialMaths2018Jan3: IalMaths2018Jan3 var body: some View { Webview(url: ialMaths2018Jan3.url) .edgesIgnoringSafeArea(.all) .navigationBarTitle(ialMaths2018Jan3.name, displayMode: .inline) .navigationBarItems(trailing: shareButton) .sheet(isPresented: $isActivitySheetPresented, content: activityView) } private var shareButton: some View { Button(action: { switch (self.horizontalSizeClass, self.verticalSizeClass) { case (.regular, .regular): self.isActivityPopoverPresented.toggle() default: self.isActivitySheetPresented.toggle() let impactLight = UIImpactFeedbackGenerator(style: .light) impactLight.impactOccurred() } }, label: { Image(systemName: "square.and.arrow.up") .font(.system(size: 17)) .frame(width: 30, height: 30) .popover(isPresented: $isActivityPopoverPresented, attachmentAnchor: .point(.bottom), arrowEdge: .bottom) { activityView() } }) } private func activityView() -> some View { let url = URL(string: ialMaths2018Jan3.url)! let filename = url.pathComponents.last! let fileManager = FileManager.default let itemURL = fileManager.temporaryDirectory.appendingPathComponent(filename) let data: Data if fileManager.fileExists(atPath: itemURL.path) { data = try! Data(contentsOf: itemURL) } else { data = try! Data(contentsOf: url) fileManager.createFile(atPath: itemURL.path, contents: data, attributes: nil) } let activityView = ActivityView(activityItems: [itemURL], applicationActivities: nil) return Group { if self.horizontalSizeClass == .regular && self.verticalSizeClass == .regular { activityView.frame(width: 333, height: 480) } else { activityView .edgesIgnoringSafeArea(.all) } } } } struct IalMaths2018Jan1: Hashable, Codable, Identifiable { var id: Int var name: String var url: String } struct IalMaths2018Jan2: Hashable, Codable, Identifiable { var id: Int var name: String var url: String } struct IalMaths2018Jan3: Hashable, Codable, Identifiable { var id: Int var name: String var url: String } let IalMaths2018JanData1: [IalMaths2018Jan1] = load("IalMaths2018Jan1.json") let IalMaths2018JanData2: [IalMaths2018Jan2] = load("IalMaths2018Jan2.json") let IalMaths2018JanData3: [IalMaths2018Jan3] = load("IalMaths2018Jan3.json")
35.116923
123
0.584509
64b95721d92d1eac614222d4c9426342e37fcc8d
1,373
// // ModularizeAppUITests.swift // ModularizeAppUITests // // Created by Kumar, Sumit on 28/09/19. // Copyright © 2019 sk. All rights reserved. // import XCTest class ModularizeAppUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() { // This measures how long it takes to launch your application from the home screen. measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { XCUIApplication().launch() } } }
32.690476
182
0.674436
1196196baa6c60097523e2086bc021c2ec271206
23,199
// // NetTCPSSL.swift // PerfectLib // // Created by Kyle Jessup on 2015-09-23. // Copyright (C) 2015 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import COpenSSL import PerfectCrypto #if os(Linux) import SwiftGlibc #else import Darwin #endif private typealias passwordCallbackFunc = @convention(c) (UnsafeMutablePointer<Int8>?, Int32, Int32, UnsafeMutableRawPointer?) -> Int32 public typealias VerifyCACallbackFunc = @convention (c) (Int32, UnsafeMutablePointer<X509_STORE_CTX>?) -> Int32 public struct OpenSSLVerifyMode: OptionSet { public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } public static let sslVerifyNone = OpenSSLVerifyMode(rawValue: SSL_VERIFY_NONE) public static let sslVerifyPeer = OpenSSLVerifyMode(rawValue: SSL_VERIFY_PEER) public static let sslVerifyFailIfNoPeerCert = OpenSSLVerifyMode(rawValue: SSL_VERIFY_FAIL_IF_NO_PEER_CERT) public static let sslVerifyClientOnce = OpenSSLVerifyMode(rawValue: SSL_VERIFY_CLIENT_ONCE) public static let sslVerifyPeerWithFailIfNoPeerCert: OpenSSLVerifyMode = [.sslVerifyPeer, .sslVerifyFailIfNoPeerCert] public static let sslVerifyPeerClientOnce: OpenSSLVerifyMode = [.sslVerifyPeer, .sslVerifyClientOnce] public static let sslVerifyPeerWithFailIfNoPeerCertClientOnce: OpenSSLVerifyMode = [.sslVerifyPeer, .sslVerifyFailIfNoPeerCert, .sslVerifyClientOnce] } public enum TLSMethod { case tlsV1 case tlsV1_1 case tlsV1_2 } private class AutoFreeSSLCTX { let sslCtx: UnsafeMutablePointer<SSL_CTX>? init(_ sslCtx: UnsafeMutablePointer<SSL_CTX>?) { self.sslCtx = sslCtx } deinit { if let sslCtx = self.sslCtx { SSL_CTX_free(sslCtx) } } } public class NetTCPSSL : NetTCP { public static var opensslVersionText : String { return OPENSSL_VERSION_TEXT } public static var opensslVersionNumber : Int { return OPENSSL_VERSION_NUMBER } public class X509 { private let ptr: UnsafeMutablePointer<COpenSSL.X509> init(ptr: UnsafeMutablePointer<COpenSSL.X509>) { self.ptr = ptr } deinit { X509_free(self.ptr) } public var publicKeyBytes: [UInt8] { let pk = X509_get_pubkey(self.ptr) let len = Int(i2d_PUBKEY(pk, nil)) var mp = UnsafeMutablePointer<UInt8>(nil as OpaquePointer?) i2d_PUBKEY(pk, &mp) var ret = [UInt8]() guard let ensure = mp else { return ret } defer { if let mp = mp { free(mp) } EVP_PKEY_free(pk) } ret.reserveCapacity(len) for b in 0..<len { ret.append(ensure[b]) } return ret } } static var sslCtxALPNBufferIndex = 0 as Int32 static var sslCtxALPNBufferSizeIndex = 0 as Int32 static var sslAcceptingNetIndex = 0 as Int32 static var initOnce: Bool = { guard PerfectCrypto.isInitialized else { return false } copenssl_SSL_library_init() sslCtxALPNBufferIndex = SSL_CTX_get_ex_new_index(0, nil, nil, nil, { (p1:UnsafeMutableRawPointer?, p2:UnsafeMutableRawPointer?, d:UnsafeMutablePointer<CRYPTO_EX_DATA>?, i1:Int32, i2:Int, p3:UnsafeMutableRawPointer?) in if let p2 = p2 { copenssl_CRYPTO_free(p2, #file, #line) } }) sslCtxALPNBufferSizeIndex = SSL_CTX_get_ex_new_index(0, nil, nil, nil, nil) sslAcceptingNetIndex = SSL_get_ex_new_index(0, nil, nil, nil, nil) return true }() fileprivate var trackCtx: AutoFreeSSLCTX? fileprivate var sslCtx: UnsafeMutablePointer<SSL_CTX>? { get { return trackCtx?.sslCtx } set { trackCtx = AutoFreeSSLCTX(newValue) } } fileprivate var ssl: UnsafeMutablePointer<SSL>? public var tlsMethod: TLSMethod = .tlsV1_2 fileprivate var sniContextMap = [String:AutoFreeSSLCTX]() public var keyFilePassword: String = "" public var peerCertificate: X509? { guard let ssl = self.ssl else { return nil } guard let cert = SSL_get_peer_certificate(ssl) else { return nil } return X509(ptr: cert) } public var cipherList: [String] { get { var a = [String]() guard let ssl = self.ssl else { return a } var i = Int32(0) while true { guard let n = SSL_get_cipher_list(ssl, i) else { break } a.append(String(validatingUTF8: n)!) i += 1 } return a } set(list) { let listStr = list.joined(separator: ",") if let ctx = self.sslCtx { if 0 == SSL_CTX_set_cipher_list(ctx, listStr) { print("SSL_CTX_set_cipher_list failed: \(self.errorStr(forCode: Int32(self.errorCode())))") } } if let ssl = self.ssl { if 0 == SSL_set_cipher_list(ssl, listStr) { print("SSL_CTX_set_cipher_list failed: \(self.errorStr(forCode: Int32(self.errorCode())))") } } } } public var initializedCallback: ((NetTCPSSL) -> ())? public func setTmpDH(path: String) -> Bool { guard let ctx = self.sslCtx, let bio = BIO_new_file(path, "r") else { return false } defer { BIO_free(bio) } guard let dh = PEM_read_bio_DHparams(bio, nil, nil, nil) else { return false } defer { DH_free(dh) } SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TMP_DH, 0, dh) return true } public var usingSSL: Bool { return self.ssl != nil } public override init() { super.init() _ = NetTCPSSL.initOnce } func passwordCallback(_ buf:UnsafeMutablePointer<Int8>, size:Int32, rwflag:Int32) -> Int32 { let chars = self.keyFilePassword.utf8 memmove(buf, self.keyFilePassword, chars.count) buf[chars.count] = 0 return Int32(chars.count) } fileprivate func makeSSLCTX() -> UnsafeMutablePointer<SSL_CTX>? { let newSslCtx: UnsafeMutablePointer<SSL_CTX>? switch self.tlsMethod { case .tlsV1_2: newSslCtx = SSL_CTX_new(TLSv1_2_method()) case .tlsV1_1: newSslCtx = SSL_CTX_new(TLSv1_1_method()) case .tlsV1: newSslCtx = SSL_CTX_new(TLSv1_method()) } guard let sslCtx = newSslCtx else { return nil } copenssl_SSL_CTX_set_options(sslCtx) return sslCtx } override public func initSocket(family: Int32) { super.initSocket(family: family) guard self.sslCtx == nil else { return } self.sslCtx = makeSSLCTX() guard let _ = self.sslCtx else { return } initializedCallback?(self) if !keyFilePassword.isEmpty { let opaqueMe = Unmanaged.passUnretained(self).toOpaque() let callback: passwordCallbackFunc = { (buf, size, rwflag, userData) -> Int32 in guard let userDataCheck = userData, let bufCheck = buf else { return 0 } let crl = Unmanaged<NetTCPSSL>.fromOpaque(UnsafeMutableRawPointer(userDataCheck)).takeUnretainedValue() return crl.passwordCallback(bufCheck, size: size, rwflag: rwflag) } SSL_CTX_set_default_passwd_cb_userdata(self.sslCtx!, opaqueMe) SSL_CTX_set_default_passwd_cb(self.sslCtx!, callback) } } public func errorCode() -> UInt { let err = ERR_get_error() return err } public func sslErrorCode(resultCode code: Int32) -> Int32 { if let ssl = self.ssl { let err = SSL_get_error(ssl, code) return err } return -1 } public func errorStr(forCode errorCode: Int32) -> String { let maxLen = 1024 let buf = UnsafeMutablePointer<Int8>.allocate(capacity: maxLen) defer { buf.deallocate() } ERR_error_string_n(UInt(errorCode), buf, maxLen) let ret = String(validatingUTF8: buf) ?? "" return ret } public func reasonErrorStr(errorCode: Int32) -> String { guard let buf = ERR_reason_error_string(UInt(errorCode)) else { return "" } let ret = String(validatingUTF8: buf) ?? "" return ret } override func isEAgain(err er: Int) -> Bool { if er == -1 && self.usingSSL { let sslErr = SSL_get_error(self.ssl!, Int32(er)) if sslErr != SSL_ERROR_SYSCALL { return sslErr == SSL_ERROR_WANT_READ || sslErr == SSL_ERROR_WANT_WRITE } } return super.isEAgain(err: er) } override func recv(into buf: UnsafeMutableRawPointer, count: Int) -> Int { if self.usingSSL { let i = Int(SSL_read(self.ssl!, buf, Int32(count))) return i } return super.recv(into: buf, count: count) } override func send(_ buf: [UInt8], offsetBy: Int, count: Int) -> Int { return buf.withUnsafeBytes { let ptr = $0.baseAddress?.advanced(by: offsetBy) if self.usingSSL { let i = Int(SSL_write(self.ssl!, ptr, Int32(count))) return i } return super.send(buf, offsetBy: offsetBy, count: count) } } override func readBytesFullyIncomplete(into to: ReferenceBuffer, read: Int, remaining: Int, timeoutSeconds: Double, completion: @escaping ([UInt8]?) -> ()) { guard usingSSL else { return super.readBytesFullyIncomplete(into: to, read: read, remaining: remaining, timeoutSeconds: timeoutSeconds, completion: completion) } var what = NetEvent.Filter.write let sslErr = SSL_get_error(self.ssl!, -1) if sslErr == SSL_ERROR_WANT_READ { what = NetEvent.Filter.read } NetEvent.add(socket: fd.fd, what: what, timeoutSeconds: NetEvent.noTimeout) { fd, w in if case .timer = w { completion(nil) // timeout or error } else { self.readBytesFully(into: to, read: read, remaining: remaining, timeoutSeconds: timeoutSeconds, completion: completion) } } } override func writeIncomplete(bytes: [UInt8], offsetBy: Int, count: Int, completion: @escaping (Int) -> ()) { guard usingSSL else { return super.writeIncomplete(bytes: bytes, offsetBy: offsetBy, count: count, completion: completion) } var what = NetEvent.Filter.write let sslErr = SSL_get_error(self.ssl!, -1) if sslErr == SSL_ERROR_WANT_READ { what = NetEvent.Filter.read } NetEvent.add(socket: fd.fd, what: what, timeoutSeconds: NetEvent.noTimeout) { [weak self] fd, w in self?.write(bytes: bytes, offsetBy: offsetBy, count: count, completion: completion) } } public override func close() { if let ssl = self.ssl { SSL_shutdown(ssl) SSL_free(ssl) self.ssl = nil } self.sslCtx = nil super.close() } public func beginSSL(closure: @escaping (Bool) -> ()) { self.beginSSL(timeoutSeconds: 5.0, closure: closure) } public func beginSSL(timeoutSeconds timeout: Double, closure: @escaping (Bool) -> ()) { guard self.fd.fd != invalidSocket else { closure(false) return } if self.ssl == nil { self.ssl = SSL_new(self.sslCtx!) SSL_set_fd(self.ssl!, self.fd.fd) } guard let ssl = self.ssl else { closure(false) return } SSL_set_ex_data(ssl, NetTCPSSL.sslAcceptingNetIndex, Unmanaged.passUnretained(self).toOpaque()) let res = SSL_connect(ssl) switch res { case 1: closure(true) case 0: closure(false) case -1: let sslErr = SSL_get_error(ssl, res) if sslErr == SSL_ERROR_WANT_WRITE { NetEvent.add(socket: fd.fd, what: .write, timeoutSeconds: timeout) { [weak self] fd, w in if case .write = w { self?.beginSSL(timeoutSeconds: timeout, closure: closure) } else { closure(false) } } return } else if sslErr == SSL_ERROR_WANT_READ { NetEvent.add(socket: fd.fd, what: .read, timeoutSeconds: timeout) { [weak self] fd, w in if case .read = w { self?.beginSSL(timeoutSeconds: timeout, closure: closure) } else { closure(false) } } return } else { closure(false) } default: closure(false) } } public func endSSL() { if let ssl = self.ssl { SSL_free(ssl) self.ssl = nil } if let sslCtx = self.sslCtx { SSL_CTX_free(sslCtx) self.sslCtx = nil } } override public func shutdown() { if let ssl = self.ssl { SSL_shutdown(ssl) } super.shutdown() } public func setConnectState() { if let ssl = self.ssl { SSL_set_connect_state(ssl) } } public func setAcceptState() { if let ssl = self.ssl { SSL_set_accept_state(ssl) } } override func makeFromFd(_ fd: Int32) -> NetTCP { return NetTCPSSL(fd: fd) } override public func listen(backlog: Int32 = 128) { enableSNIServer() super.listen(backlog: backlog) } override public func connect(address addrs: String, port: UInt16, timeoutSeconds: Double, callBack: @escaping (NetTCP?) -> ()) throws { _ = setDefaultVerifyPaths() try super.connect(address: addrs, port: port, timeoutSeconds: timeoutSeconds) { net in guard let netSSL = net as? NetTCPSSL else { return callBack(net) } netSSL.beginSSL { success in guard success else { netSSL.close() return callBack(nil) } callBack(netSSL) } } } private func accepted(_ net: NetTCP?, callBack: @escaping (NetTCP?) -> ()) { if let netSSL = net as? NetTCPSSL { netSSL.trackCtx = self.trackCtx netSSL.ssl = SSL_new(self.sslCtx!) SSL_set_fd(netSSL.ssl!, netSSL.fd.fd) self.finishAccept(timeoutSeconds: -1, net: netSSL, callBack: callBack) } else { callBack(net) } } override public func forEachAccept(callBack: @escaping (NetTCP?) -> ()) { super.forEachAccept { [unowned self] (net:NetTCP?) -> () in self.accepted(net, callBack: callBack) } } override public func accept(timeoutSeconds timeout: Double, callBack: @escaping (NetTCP?) -> ()) throws { try super.accept(timeoutSeconds: timeout, callBack: { [unowned self] (net:NetTCP?) -> () in self.accepted(net, callBack: callBack) }) } func finishAccept(timeoutSeconds timeout: Double, net: NetTCPSSL, callBack: @escaping (NetTCP?) -> ()) { SSL_set_ex_data(net.ssl!, NetTCPSSL.sslAcceptingNetIndex, Unmanaged.passUnretained(net).toOpaque()) let res = SSL_accept(net.ssl!) let sslErr = SSL_get_error(net.ssl!, res) if res == -1 { if sslErr == SSL_ERROR_WANT_WRITE { NetEvent.add(socket: net.fd.fd, what: .write, timeoutSeconds: timeout) { [weak self] fd, w in if case .timer = w { callBack(nil) } else { self?.finishAccept(timeoutSeconds: timeout, net: net, callBack: callBack) } } } else if sslErr == SSL_ERROR_WANT_READ { NetEvent.add(socket: net.fd.fd, what: .read, timeoutSeconds: timeout) { [weak self] fd, w in if case .timer = w { callBack(nil) } else { self?.finishAccept(timeoutSeconds: timeout, net: net, callBack: callBack) } } } else { callBack(nil) } } else { callBack(net) } } } extension NetTCPSSL { fileprivate func getCtx(forHost: String?) -> AutoFreeSSLCTX? { guard let forHost = forHost else { return trackCtx } let auto: AutoFreeSSLCTX if let foundSSLCtx = sniContextMap[forHost] { auto = foundSSLCtx } else { let newCtx = makeSSLCTX() auto = AutoFreeSSLCTX(newCtx) sniContextMap[forHost] = auto } return auto } public func setDefaultVerifyPaths(forHost: String? = nil) -> Bool { guard let sslCtx = getCtx(forHost: forHost)?.sslCtx else { return false } let r = SSL_CTX_set_default_verify_paths(sslCtx) return r == 1 } public func setVerifyLocations(caFilePath: String, caDirPath: String, forHost: String? = nil) -> Bool { guard let sslCtx = getCtx(forHost: forHost)?.sslCtx else { return false } let r = SSL_CTX_load_verify_locations(sslCtx, caFilePath, caDirPath) return r == 1 } public func useCertificateFile(cert: String, forHost: String? = nil) -> Bool { guard let sslCtx = getCtx(forHost: forHost)?.sslCtx else { return false } let r = SSL_CTX_use_certificate_file(sslCtx, cert, SSL_FILETYPE_PEM) return r == 1 } public func useCertificateChainFile(cert crt: String, forHost: String? = nil) -> Bool { guard let sslCtx = getCtx(forHost: forHost)?.sslCtx else { return false } let r = SSL_CTX_use_certificate_chain_file(sslCtx, crt) return r == 1 } public func useCertificateChain(cert crt: String, forHost: String? = nil) -> Bool { guard let sslCtx = getCtx(forHost: forHost)?.sslCtx else { return false } let bio = BIO_new(BIO_s_mem()) defer { BIO_free(bio) } BIO_puts(bio, crt) let certificate = PEM_read_bio_X509(bio, nil, nil, nil) let r = SSL_CTX_use_certificate(sslCtx, certificate) return r == 1 } public func usePrivateKeyFile(cert crt: String, forHost: String? = nil) -> Bool { guard let sslCtx = getCtx(forHost: forHost)?.sslCtx else { return false } let r = SSL_CTX_use_PrivateKey_file(sslCtx, crt, SSL_FILETYPE_PEM) return r == 1 } /// Use a stringified version of the certificate. public func usePrivateKey(cert crt: String, forHost: String? = nil) -> Bool { guard let sslCtx = getCtx(forHost: forHost)?.sslCtx else { return false } let bio = BIO_new(BIO_s_mem()) defer { BIO_free(bio) } BIO_puts(bio, crt) let pKey = PEM_read_bio_PrivateKey(bio, nil, nil, nil) let r = SSL_CTX_use_PrivateKey(sslCtx, pKey) return r == 1 } public func checkPrivateKey(forHost: String? = nil) -> Bool { guard let sslCtx = getCtx(forHost: forHost)?.sslCtx else { return false } let r = SSL_CTX_check_private_key(sslCtx) return r == 1 } public func setClientCA(path: String, verifyMode: OpenSSLVerifyMode, forHost: String? = nil) -> Bool { guard let sslCtx = getCtx(forHost: forHost)?.sslCtx else { return false } let oldList = SSL_CTX_get_client_CA_list(sslCtx) SSL_CTX_set_client_CA_list(sslCtx, SSL_load_client_CA_file(path)) let newList = SSL_CTX_get_client_CA_list(sslCtx) if let oldNb = oldList, let newNb = newList, copenssl_stack_st_X509_NAME_num(oldNb) + 1 == copenssl_stack_st_X509_NAME_num(newNb) { SSL_CTX_set_verify(sslCtx, verifyMode.rawValue, nil) return true } return false } public func subscribeCAVerify(verifyMode: OpenSSLVerifyMode, forHost: String? = nil, callback: @escaping VerifyCACallbackFunc) { guard let sslCtx = getCtx(forHost: forHost)?.sslCtx else { return } SSL_CTX_set_verify(sslCtx, verifyMode.rawValue, callback) } } extension NetTCPSSL { /// If ALPN is used, this will be the negotiated protocol for this accepted socket. /// This will be nil if ALPN is not enabled OR if the client and server share no common protocols. public var alpnNegotiated: String? { guard let ssl = self.ssl else { return nil } var ptr: UnsafePointer<UInt8>? = nil var len: UInt32 = 0 SSL_get0_alpn_selected(ssl, &ptr, &len) if len > 0, let ptr = ptr { var selectedChars = [UInt8]() for n in 0..<Int(len) { selectedChars.append(ptr[n]) } let negotiated = String(validatingUTF8: selectedChars) return negotiated } return nil } /// Given a list of protocol names, such as h2, http/1.1, this will enable ALPN protocol selection. /// The name of the server+client matched protocol will be available in the `.alpnNegotiated` property. /// This protocol list can be set on the server or client socket. Accepted/connected sockets /// will have `.alpnNegotiated` set to the negotiated protocol. public func enableALPN(protocols: [String], forHost: String? = nil) { let buffer: [UInt8] = protocols.map { Array($0.utf8) } .map { [UInt8($0.count)] + $0 } .reduce([], +) enableALPN(buffer: buffer, forHost: forHost) } func enableALPN(buffer: [UInt8], forHost: String? = nil) { guard let ctx = getCtx(forHost: forHost)?.sslCtx, !buffer.isEmpty else { return } if let ptr = copenssl_CRYPTO_malloc(buffer.count, #file, #line) { memcpy(ptr, buffer, buffer.count) SSL_CTX_set_ex_data(ctx, NetTCPSSL.sslCtxALPNBufferIndex, ptr) SSL_CTX_set_ex_data(ctx, NetTCPSSL.sslCtxALPNBufferSizeIndex, UnsafeMutableRawPointer(bitPattern: buffer.count)) enableALPNServer(forHost: forHost) SSL_CTX_set_alpn_protos(ctx, ptr.assumingMemoryBound(to: UInt8.self), UInt32(buffer.count)) } } func enableALPNServer(forHost: String? = nil) { guard let ctx = getCtx(forHost: forHost)?.sslCtx else { return } typealias alpnSelectCallbackFunc = @convention(c) (UnsafeMutablePointer<SSL>?, UnsafeMutablePointer<UnsafePointer<UInt8>?>?, UnsafeMutablePointer<UInt8>?, UnsafePointer<UInt8>?, UInt32, UnsafeMutableRawPointer?) -> Int32 let callback: alpnSelectCallbackFunc = { (ssl: UnsafeMutablePointer<SSL>?, outBuf: UnsafeMutablePointer<UnsafePointer<UInt8>?>?, outLen: UnsafeMutablePointer<UInt8>?, clientBuf: UnsafePointer<UInt8>?, clientLen: UInt32, userData: UnsafeMutableRawPointer?) -> Int32 in guard let ctx = SSL_get_SSL_CTX(ssl), let ptr = SSL_CTX_get_ex_data(ctx, NetTCPSSL.sslCtxALPNBufferIndex) else { return OPENSSL_NPN_NO_OVERLAP } let ptrLength = Int(bitPattern: SSL_CTX_get_ex_data(ctx, NetTCPSSL.sslCtxALPNBufferSizeIndex)) let serverBuf = ptr.assumingMemoryBound(to: UInt8.self) guard let clientBuf = clientBuf, let outBuf = outBuf else { return OPENSSL_NPN_NO_OVERLAP } let serverLen = UInt32(ptrLength) return outBuf.withMemoryRebound(to: Optional<UnsafeMutablePointer<UInt8>>.self, capacity: 1) { outBuf in let result = SSL_select_next_proto(outBuf, outLen, serverBuf, serverLen, clientBuf, clientLen) if result == OPENSSL_NPN_NEGOTIATED { return SSL_TLSEXT_ERR_OK } return SSL_TLSEXT_ERR_NOACK } } SSL_CTX_set_alpn_select_cb(ctx, callback, nil) } } extension NetTCPSSL { public var serverNameIdentified: String? { guard let ssl = self.ssl else { return nil } guard let serverNameRaw = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name), let serverName = String(validatingUTF8: serverNameRaw) else { return nil } return serverName } func enableSNIServer() { guard let ctx = self.sslCtx, !sniContextMap.isEmpty else { return } typealias sniCallback = @convention(c) (UnsafeMutablePointer<SSL>?, UnsafeMutablePointer<Int32>?, UnsafeMutableRawPointer?) -> Int32 typealias ctxCallback = (@convention(c) () -> Swift.Void) let callback: sniCallback = { (ssl: UnsafeMutablePointer<SSL>?, doNotKnow: UnsafeMutablePointer<Int32>?, arg: UnsafeMutableRawPointer?) -> Int32 in guard let userDataCheck = arg else { return 1 } guard let serverNameRaw = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name), let serverName = String(validatingUTF8: serverNameRaw) else { return 1 } guard let raw = SSL_get_ex_data(ssl, NetTCPSSL.sslAcceptingNetIndex) else { return 1 } let child = Unmanaged<NetTCPSSL>.fromOpaque(raw).takeUnretainedValue() let parent = Unmanaged<NetTCPSSL>.fromOpaque(UnsafeMutableRawPointer(userDataCheck)).takeUnretainedValue() if let fndCtx = parent.sniContextMap[serverName] { SSL_set_SSL_CTX(ssl, fndCtx.sslCtx) child.trackCtx = fndCtx } else if let fndCtx = parent.sniContextMap["*"] { SSL_set_SSL_CTX(ssl, fndCtx.sslCtx) child.trackCtx = fndCtx } return 1 } let opaqueCallback = unsafeBitCast(callback, to: ctxCallback.self) SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, opaqueCallback) let opaqueMe = Unmanaged.passUnretained(self).toOpaque() SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, opaqueMe) } }
28.535055
222
0.690375
ac6a5dbf63c3c249ae6039418aa237adba7fb641
3,011
//------------------------------------------------------------------------------ // Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: test.fbe // FBE version: 1.10.0.0 //------------------------------------------------------------------------------ import ChronoxorFbe // Fast Binary Encoding StructOptional final model public class StructOptionalFinalModel: Model { private let _model: FinalModelStructOptional public override init(buffer: Buffer = Buffer()) { _model = FinalModelStructOptional(buffer: buffer, offset: 8) super.init(buffer: buffer) } // Model type public var fbeType: Int = fbeTypeConst static let fbeTypeConst: Int = FinalModelStructOptional.fbeTypeConst // Check if the struct value is valid public func verify() -> Bool { if (buffer.offset + _model.fbeOffset) > buffer.size { return false } let fbeStructSize = Int(readUInt32(offset: _model.fbeOffset - 8)) let fbeStructType = Int(readUInt32(offset: _model.fbeOffset - 4)) if (fbeStructSize <= 0) || (fbeStructType != fbeType) { return false } return ((8 + _model.verify()) == fbeStructSize) } // Serialize the struct value public func serialize(value: StructOptional) throws -> Int { let fbeInitialSize = buffer.size let fbeStructType = fbeType var fbeStructSize = 8 + _model.fbeAllocationSize(value: value) let fbeStructOffset = try buffer.allocate(size: fbeStructSize) - buffer.offset if (buffer.offset + fbeStructOffset + fbeStructSize) > buffer.size { assertionFailure("Model is broken!") return 0 } fbeStructSize = try _model.set(value: value) + 8 try buffer.resize(size: fbeInitialSize + fbeStructSize) write(offset: _model.fbeOffset - 8, value: UInt32(fbeStructSize)) write(offset: _model.fbeOffset - 4, value: UInt32(fbeStructType)) return fbeStructSize } // Deserialize the struct value public func deserialize() -> StructOptional { var value = StructOptional(); _ = deserialize(value: &value); return value } public func deserialize(value: inout StructOptional) -> Int { if (buffer.offset + _model.fbeOffset) > buffer.size { assertionFailure("Model is broken!") return 0 } let fbeStructSize = Int32(readUInt32(offset: _model.fbeOffset - 8)) let fbeStructType = Int32(readUInt32(offset: _model.fbeOffset - 4)) if (fbeStructSize <= 0) || (fbeStructType != fbeType) { assertionFailure("Model is broken!") return 8 } var fbeSize = Size() value = _model.get(size: &fbeSize, fbeValue: &value) return 8 + fbeSize.value } // Move to the next struct value public func next(prev: Int) { _model.fbeShift(size: prev) } }
34.609195
126
0.610096
f96068cf5028972e73198bc72ba40dcf18b26523
21,832
// // AbstractUPnPService.swift // // Copyright (c) 2015 David Robles // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import Ono import AFNetworking open class AbstractUPnPService: AbstractUPnP { // public open var serviceType: String { return urn } open fileprivate(set) var serviceID: String! // TODO: Should ideally be a constant, see Github issue #10 open var serviceDescriptionURL: URL { return (URL(string: _relativeServiceDescriptionURL.absoluteString, relativeTo: baseURL)?.absoluteURL)! } open var controlURL: URL { return (URL(string: _relativeControlURL.absoluteString, relativeTo: baseURL)?.absoluteURL)! } open var eventURL: URL { return (URL(string: _relativeEventURL.absoluteString, relativeTo: baseURL)?.absoluteURL)! } override open var baseURL: URL! { if let baseURL = _baseURLFromXML { return baseURL } return super.baseURL as URL! } open weak var deviceSource: UPnPDeviceSource? open var device: AbstractUPnPDevice? { return deviceSource?.device(forUSN: _deviceUSN) } /// protected open fileprivate(set) var soapSessionManager: SOAPSessionManager! // TODO: Should ideally be a constant, see Github issue #10 // private fileprivate var _baseURLFromXML: URL? // TODO: Should ideally be a constant, see Github issue #10 fileprivate var _relativeServiceDescriptionURL: URL! // TODO: Should ideally be a constant, see Github issue #10 fileprivate var _relativeControlURL: URL! // TODO: Should ideally be a constant, see Github issue #10 fileprivate var _relativeEventURL: URL! // TODO: Should ideally be a constant, see Github issue #10 fileprivate var _deviceUSN: UniqueServiceName! // TODO: Should ideally be a constant, see Github issue #10 fileprivate var _serviceDescriptionDocument: ONOXMLDocument? fileprivate static let _serviceDescriptionDefaultPrefix = "service" /// Must be accessed within dispatch_sync() or dispatch_async() and updated within dispatch_barrier_async() to the concurrent queue fileprivate var _soapActionsSupportCache = [String: Bool]() // MARK: UPnP Event handling related /// Must be accessed within dispatch_sync() or dispatch_async() and updated within dispatch_barrier_async() to the concurrent queue lazy fileprivate var _eventObservers = [EventObserver]() fileprivate var _concurrentEventObserverQueue: DispatchQueue! fileprivate var _concurrentSOAPActionsSupportCacheQueue = DispatchQueue(label: "com.upnatom.abstract-upnp-service.soap-actions-support-cache-queue", attributes: DispatchQueue.Attributes.concurrent) fileprivate weak var _eventSubscription: AnyObject? required public init?(usn: UniqueServiceName, descriptionURL: URL, descriptionXML: Data) { super.init(usn: usn, descriptionURL: descriptionURL, descriptionXML: descriptionXML) soapSessionManager = SOAPSessionManager(baseURL: baseURL, sessionConfiguration: nil) _concurrentEventObserverQueue = DispatchQueue(label: "com.upnatom.abstract-upnp-service.event-observer-queue.\(usn.rawValue)", attributes: DispatchQueue.Attributes.concurrent) let serviceParser = UPnPServiceParser(upnpService: self, descriptionXML: descriptionXML) let parsedService = serviceParser.parse().value if let baseURL = parsedService?.baseURL { _baseURLFromXML = baseURL } guard let serviceID = parsedService?.serviceID, let relativeServiceDescriptionURL = parsedService?.relativeServiceDescriptionURL, let relativeControlURL = parsedService?.relativeControlURL, let relativeEventURL = parsedService?.relativeEventURL, let deviceUSN = parsedService?.deviceUSN else { return nil } self.serviceID = serviceID self._relativeServiceDescriptionURL = relativeServiceDescriptionURL self._relativeControlURL = relativeControlURL self._relativeEventURL = relativeEventURL self._deviceUSN = deviceUSN } /* Comment for confliction method swift 3.2 + unusage required public init?(usn: UniqueServiceName, descriptionURL: NSURL, descriptionXML: NSData) { fatalError("init(usn:descriptionURL:descriptionXML:) has not been implemented") } */ deinit { // deinit may be called during init if init returns nil, queue var may not be set guard _concurrentEventObserverQueue != nil else { return } var eventObservers: [EventObserver]! _concurrentEventObserverQueue.sync(execute: { () -> Void in eventObservers = self._eventObservers }) for eventObserver in eventObservers { NotificationCenter.default.removeObserver(eventObserver.notificationCenterObserver) } } /// The service description document can be used for querying for service specific support i.e. SOAP action arguments open func serviceDescriptionDocument(_ completion: @escaping (_ serviceDescriptionDocument: ONOXMLDocument?, _ defaultPrefix: String) -> Void) { if let serviceDescriptionDocument = _serviceDescriptionDocument { completion(serviceDescriptionDocument, AbstractUPnPService._serviceDescriptionDefaultPrefix) } else { let httpSessionManager = AFHTTPSessionManager() httpSessionManager.requestSerializer = AFHTTPRequestSerializer() httpSessionManager.responseSerializer = AFHTTPResponseSerializer() httpSessionManager.get(serviceDescriptionURL.absoluteString, parameters: nil, success: { (task, responseObject) in if #available(OSX 10.10, iOS 8.0, *) { DispatchQueue.global(qos: .default).async(execute: { guard let xmlData = responseObject as? NSData else { completion(nil, AbstractUPnPService._serviceDescriptionDefaultPrefix) return } do { let serviceDescriptionDocument = try ONOXMLDocument(data: xmlData as Data!) LogVerbose("Parsing service description XML:\nSTART\n\(NSString(data: xmlData as Data, encoding: String.Encoding.utf8.rawValue))\nEND") serviceDescriptionDocument.definePrefix(AbstractUPnPService._serviceDescriptionDefaultPrefix, forDefaultNamespace: "urn:schemas-upnp-org:service-1-0") self._serviceDescriptionDocument = serviceDescriptionDocument completion(serviceDescriptionDocument, AbstractUPnPService._serviceDescriptionDefaultPrefix) } catch let parseError as NSError { LogError("Failed to parse service description for SOAP action support check: \(parseError)") completion(nil, AbstractUPnPService._serviceDescriptionDefaultPrefix) } }) } else { // Fallback on earlier versions LogError("OSX / iOS version error") completion(nil, AbstractUPnPService._serviceDescriptionDefaultPrefix) } }, failure: { (task, error) in LogError("Failed to retrieve service description for SOAP action support check: \(error)") completion(nil, AbstractUPnPService._serviceDescriptionDefaultPrefix) }) } } /// Used for determining support of optional SOAP actions for this service. open func supportsSOAPAction(actionParameters: SOAPRequestSerializer.Parameters, completion: @escaping (_ isSupported: Bool) -> Void) { let soapActionName = actionParameters.soapAction // only reading SOAP actions support cache, so distpach_async is appropriate to allow for concurrent reads _concurrentSOAPActionsSupportCacheQueue.async(execute: { () -> Void in let soapActionsSupportCache = self._soapActionsSupportCache DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async { () -> Void in if let isSupported = soapActionsSupportCache[soapActionName] { completion(isSupported) } else { self.serviceDescriptionDocument { (serviceDescriptionDocument: ONOXMLDocument?, defaultPrefix: String) -> Void in if let serviceDescriptionDocument = serviceDescriptionDocument { DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async { () -> Void in // For better performance, check the action name only for now. If this proves inadequite in the future the argument list can also be compared with the SOAP parameters passed in. let prefix = defaultPrefix let xPathQuery = "/\(prefix):scpd/\(prefix):actionList/\(prefix):action[\(prefix):name='\(soapActionName)']" let isSupported = serviceDescriptionDocument.firstChild(withXPath: xPathQuery) != nil ? true : false self._concurrentSOAPActionsSupportCacheQueue.async(flags: .barrier, execute: { () -> Void in self._soapActionsSupportCache[soapActionName] = isSupported }) completion(isSupported) } } else { // Failed to retrieve service description. This result does not warrant recording false in the cache as the service description may still show the action as supported when retreived in a subsequent attempt. completion(false) } } } } }) } /// overridable by service subclasses open func createEvent(_ eventXML: Data) -> UPnPEvent { return UPnPEvent(eventXML: eventXML, service: self) } } // MARK: UPnP Event handling extension AbstractUPnPService: UPnPEventSubscriber { fileprivate static let _upnpEventKey = "UPnPEventKey" fileprivate class EventObserver { let notificationCenterObserver: AnyObject init(notificationCenterObserver: AnyObject) { self.notificationCenterObserver = notificationCenterObserver } } fileprivate func UPnPEventReceivedNotification() -> String { return "UPnPEventReceivedNotification.\(usn.rawValue)" } /// Returns an opaque object to act as the observer. Use it when the event observer needs to be removed. public func addEventObserver(_ queue: OperationQueue?, callBackBlock: @escaping (_ event: UPnPEvent) -> Void) -> AnyObject { /// Use callBackBlock for event notifications. While the notifications are backed by NSNotifications for broadcasting, they should only be used internally in order to keep track of how many subscribers there are. let observer = EventObserver(notificationCenterObserver: NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: UPnPEventReceivedNotification()), object: nil, queue: queue) { (notification: Notification!) -> Void in if let event = notification.userInfo?[AbstractUPnPService._upnpEventKey] as? UPnPEvent { callBackBlock(event) } }) _concurrentEventObserverQueue.async(flags: .barrier, execute: { () -> Void in self._eventObservers.append(observer) if self._eventObservers.count >= 1 { // subscribe UPnPEventSubscriptionManager.sharedInstance.subscribe(self, eventURL: self.eventURL, completion: { (subscription: Result<AnyObject>) -> Void in switch subscription { case .success(let value): self._eventSubscription = value case .failure(let error): let errorDescription = error.localizedDescription("Unknown subscribe error") LogError("Unable to subscribe to UPnP events from \(self.eventURL): \(errorDescription)") } }) } }) return observer } public func removeEventObserver(_ observer: AnyObject) { _concurrentEventObserverQueue.async(flags: .barrier, execute: { () -> Void in if let observer = observer as? EventObserver { self._eventObservers.removeObject(observer) NotificationCenter.default.removeObserver(observer.notificationCenterObserver) } if self._eventObservers.count == 0 { // unsubscribe if let eventSubscription: AnyObject = self._eventSubscription { self._eventSubscription = nil UPnPEventSubscriptionManager.sharedInstance.unsubscribe(eventSubscription, completion: { (result: EmptyResult) -> Void in if let error = result.error { let errorDescription = error.localizedDescription("Unknown unsubscribe error") LogError("Unable to unsubscribe to UPnP events from \(self.eventURL): \(errorDescription)") } }) } } }) } func handleEvent(_ eventSubscriptionManager: UPnPEventSubscriptionManager, eventXML: Data) { NotificationCenter.default.post(name: Notification.Name(rawValue: UPnPEventReceivedNotification()), object: nil, userInfo: [AbstractUPnPService._upnpEventKey: self.createEvent(eventXML)]) } func subscriptionDidFail(_ eventSubscriptionManager: UPnPEventSubscriptionManager) { LogWarn("Event subscription did fail for service: \(self)") } } extension AbstractUPnPService.EventObserver: Equatable { } private func ==(lhs: AbstractUPnPService.EventObserver, rhs: AbstractUPnPService.EventObserver) -> Bool { return lhs.notificationCenterObserver === rhs.notificationCenterObserver } /// for objective-c type checking extension AbstractUPnP { public func isAbstractUPnPService() -> Bool { return self is AbstractUPnPService } } /// overrides ExtendedPrintable protocol implementation extension AbstractUPnPService { //override open var className: String { return "\(type(of: self))" } override open var description: String { var properties = PropertyPrinter() properties.add(super.className, property: super.description) properties.add("deviceUSN", property: _deviceUSN) properties.add("serviceType", property: serviceType) properties.add("serviceID", property: serviceID) properties.add("serviceDescriptionURL", property: serviceDescriptionURL.absoluteString) properties.add("controlURL", property: controlURL.absoluteString) properties.add("eventURL", property: eventURL.absoluteString) return properties.description } } @objc public protocol UPnPDeviceSource: class { func device(forUSN usn: UniqueServiceName) -> AbstractUPnPDevice? } class UPnPServiceParser: AbstractSAXXMLParser { /// Using a class instead of struct since it's much easier and safer to continuously update from references rather than values directly as it's easy to accidentally update a copy and not the original. class ParserUPnPService { var baseURL: URL? var serviceType: String? var serviceID: String? var relativeServiceDescriptionURL: URL? var relativeControlURL: URL? var relativeEventURL: URL? var deviceUSN: UniqueServiceName? } fileprivate unowned let _upnpService: AbstractUPnPService fileprivate let _descriptionXML: Data fileprivate var _baseURL: URL? fileprivate var _deviceType: String? fileprivate var _currentParserService: ParserUPnPService? fileprivate var _foundParserService: ParserUPnPService? init(supportNamespaces: Bool, upnpService: AbstractUPnPService, descriptionXML: Data) { self._upnpService = upnpService self._descriptionXML = descriptionXML super.init(supportNamespaces: supportNamespaces) /// NOTE: URLBase is deprecated in UPnP v2.0, baseURL should be derived from the SSDP discovery description URL self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["root", "URLBase"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in self._baseURL = URL(string: text) })) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "deviceType"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in self._deviceType = text })) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "serviceList", "service"], didStartParsingElement: { (elementName, attributeDict) -> Void in self._currentParserService = ParserUPnPService() }, didEndParsingElement: { (elementName) -> Void in if let serviceType = self._currentParserService?.serviceType, serviceType == self._upnpService.urn { self._foundParserService = self._currentParserService } }, foundInnerText: nil)) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "serviceList", "service", "serviceType"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in let currentService = self._currentParserService currentService?.serviceType = text })) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "serviceList", "service", "serviceId"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in let currentService = self._currentParserService currentService?.serviceID = text })) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "serviceList", "service", "SCPDURL"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in let currentService = self._currentParserService currentService?.relativeServiceDescriptionURL = URL(string: text) })) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "serviceList", "service", "controlURL"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in let currentService = self._currentParserService currentService?.relativeControlURL = URL(string: text) })) self.addElementObservation(SAXXMLParserElementObservation(elementPath: ["*", "device", "serviceList", "service", "eventSubURL"], didStartParsingElement: nil, didEndParsingElement: nil, foundInnerText: { [unowned self] (elementName, text) -> Void in let currentService = self._currentParserService currentService?.relativeEventURL = URL(string: text) })) } convenience init(upnpService: AbstractUPnPService, descriptionXML: Data) { self.init(supportNamespaces: false, upnpService: upnpService, descriptionXML: descriptionXML) } func parse() -> Result<ParserUPnPService> { switch super.parse(data: _descriptionXML) { case .success: if let foundParserService = _foundParserService { foundParserService.baseURL = _baseURL if let deviceType = _deviceType { foundParserService.deviceUSN = UniqueServiceName(uuid: _upnpService.uuid, urn: deviceType) } return .success(foundParserService) } else { return .failure(createError("Parser error")) } case .failure(let error): return .failure(error) } } }
54.173697
256
0.666774
0301271b08c5e79615423358efb991b6b9231128
4,924
// // DocumentFile.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2018-03-05. // // --------------------------------------------------------------------------- // // © 2018-2020 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation extension FileAttributeKey { static let extendedAttributes = FileAttributeKey("NSFileExtendedAttributes") } enum FileExtendedAttributeName { static let encoding = "com.apple.TextEncoding" static let verticalText = "com.coteditor.VerticalText" } struct DocumentFile { /// Maximal length to scan encoding declaration private static let maxEncodingScanLength = 2000 // MARK: Properties let data: Data let string: String let attributes: [FileAttributeKey: Any] let lineEnding: LineEnding? let encoding: String.Encoding let hasUTF8BOM: Bool let xattrEncoding: String.Encoding? let isVerticalText: Bool // MARK: - // MARK: Lifecycle init(fileURL: URL, readingEncoding: String.Encoding, defaults: UserDefaults = .standard) throws { let data = try Data(contentsOf: fileURL) // FILE_READ let attributes = try FileManager.default.attributesOfItem(atPath: fileURL.path) // FILE_READ // check extended attributes let extendedAttributes = attributes[.extendedAttributes] as? [String: Data] self.xattrEncoding = extendedAttributes?[FileExtendedAttributeName.encoding]?.decodingXattrEncoding self.isVerticalText = (extendedAttributes?[FileExtendedAttributeName.verticalText] != nil) // decode Data to String let content: String let encoding: String.Encoding switch readingEncoding { case .autoDetection: (content, encoding) = try Self.string(data: data, xattrEncoding: self.xattrEncoding, suggestedCFEncodings: defaults[.encodingList], refersToEncodingTag: defaults[.referToEncodingTag]) default: encoding = readingEncoding if !data.isEmpty { guard let string = String(bomCapableData: data, encoding: encoding) else { throw CocoaError.error(.fileReadInapplicableStringEncoding, userInfo: [NSStringEncodingErrorKey: encoding.rawValue], url: fileURL) } content = string } else { content = "" } } // set properties self.data = data self.attributes = attributes self.string = content self.encoding = encoding self.hasUTF8BOM = (encoding == .utf8) && data.starts(with: UTF8.bom) self.lineEnding = content.detectedLineEnding } // MARK: Private Methods /// read String from Dada detecting file encoding automatically private static func string(data: Data, xattrEncoding: String.Encoding?, suggestedCFEncodings: [CFStringEncoding], refersToEncodingTag: Bool) throws -> (String, String.Encoding) { // try interpreting with xattr encoding if let xattrEncoding = xattrEncoding { // just trust xattr encoding if content is empty if let string = data.isEmpty ? "" : String(bomCapableData: data, encoding: xattrEncoding) { return (string, xattrEncoding) } } // detect encoding from data var usedEncoding: String.Encoding? let string = try String(data: data, suggestedCFEncodings: suggestedCFEncodings, usedEncoding: &usedEncoding) // try reading encoding declaration and take priority of it if it seems well if refersToEncodingTag, let scannedEncoding = string.scanEncodingDeclaration(upTo: self.maxEncodingScanLength, suggestedCFEncodings: suggestedCFEncodings), scannedEncoding != usedEncoding, let string = String(bomCapableData: data, encoding: scannedEncoding) { return (string, scannedEncoding) } guard let encoding = usedEncoding else { throw CocoaError(.fileReadUnknownStringEncoding) } return (string, encoding) } }
35.42446
182
0.623477
7997c51d4f39950da23a17aa0e59990847d37a79
2,576
// // XMLParserExtension.swift // EVEAPI // // Created by Artem Shimanski on 27.11.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import Foundation private class ASXMLElement: NSObject, XMLParserDelegate { weak var parent: XMLParserDelegate? var name: String? var children = [String:[ASXMLElement]]() var string = "" init(name:String?, attributes:[String:String]?, parser:XMLParser) { super.init() self.name = name parent = parser.delegate if attributes != nil { for (key, value) in attributes! { let child = ASXMLElement(name: key, attributes:nil, parser:parser) child.string = value addChild(child) } } parser.delegate = self } func addChild(_ child: ASXMLElement) -> Void { if children[child.name!]?.append(child) == nil { children[child.name!] = [child] } } var object:Any { get { if children.isEmpty { var decimal: Decimal = 0 let scanner = Scanner(string: string) if scanner.scanDecimal(&decimal) && scanner.isAtEnd { return decimal as NSNumber } else { return string } } else { var dictionary = [String: Any]() if !string.isEmpty { dictionary["_"] = string } for (key, value) in children { if value.count == 1 { dictionary[key] = value[0].object } else if value.count > 1 { dictionary[key] = value.map{$0.object} } } return dictionary } } } //MARK: XMLParserDelegate public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { addChild(ASXMLElement(name: elementName, attributes: attributeDict, parser: parser)) } public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { parser.delegate = parent } public func parser(_ parser: XMLParser, foundCharacters string: String) { self.string += string } public func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) { if let s = String(data: CDATABlock, encoding:.utf8) { self.string += s } } } extension XMLParser { public class func xmlObject(data: Data) throws -> Any? { let parser = XMLParser(data:data) let root = ASXMLElement(name: nil, attributes: nil, parser: parser) parser.delegate = root parser.shouldProcessNamespaces = true if parser.parse() { return root.object } else if parser.parserError != nil { throw parser.parserError! } return nil } }
24.074766
183
0.665373
39cbe491b62d192bc11c14cc6b2d6339ecc40948
1,573
// // Instantiable.swift // iOSRouteDemo // // Created by andy on 2020/10/6. // import UIKit protocol StringConvertible { var rawValue: String {get} } /// 讓ViewContoller快速由Storyboard實例化,並轉型為該物件。 protocol Instantiable { static var storyboardName: StringConvertible {get} } extension Instantiable { // 如果有多個Storyboard,必須在各自的ViewController裡,去定義storyboardName。 // 以下要刪除 /// UIViewController所在的Storyboard的名稱 static var storyboardName: StringConvertible { return "Main" } /// Creates the view controller with the specified identifier and initializes it with the data from the storyboard. /// - Returns: The view controller corresponding to the specified identifier string of same the class name. If no view controller has the given identifier, this method throws an exception. static func instantiateFromStoryboard() -> Self { return instantiableFromStoryboardHelper() } /// 寫兩段是為了要讓自定義ViewController可以利用泛型轉型 /// - Returns: 回傳泛型UIViewController private static func instantiableFromStoryboardHelper<T>() -> T { let identifier = String(describing: self) let storyboard = UIStoryboard(name: storyboardName.rawValue, bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: identifier) guard let vcc = vc as? T else { fatalError() } return vcc } } extension String: StringConvertible { var rawValue: String { return self } } // 預設將所有ViewController都套用Instantiable extension UIViewController: Instantiable { }
28.6
192
0.716465
500cb8926f46b7f08ae26a41b5f42ee9e2d56139
1,489
import Dispatch /// A view of a byte buffer of a numeric values. /// /// The elements generated are the concatenation of the bytes in the base /// buffer. public struct DataGenerator<T: UnsignedIntegerType>: GeneratorType { private var bytes: FlattenGenerator<DataRegions.Generator> private init(_ bytes: FlattenCollection<DataRegions>) { self.bytes = bytes.generate() } private init(_ bytes: FlattenGenerator<DataRegions.Generator>) { self.bytes = bytes.generate() } private mutating func nextByte() -> UInt8? { return bytes.next() } /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Requires: No preceding call to `self.next()` has returned `nil`. public mutating func next() -> T? { return (0 ..< sizeof(T)).reduce(T.allZeros) { (current, byteIdx) -> T? in guard let current = current, byte = nextByte() else { return nil } return current | numericCast(byte.toUIntMax() << UIntMax(byteIdx * 8)) } } } extension DataGenerator: SequenceType { /// Restart enumeration of the data. public func generate() -> DataGenerator<T> { return DataGenerator(bytes) } } extension Data: SequenceType { /// Return a *generator* over the `T`s that comprise this *data*. public func generate() -> DataGenerator<T> { return DataGenerator(bytes) } }
28.09434
82
0.623237
e05790f5c4ba38ac621e23d4d2d75afe1dfb33de
18,730
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation @objc protocol SwiftObjCProto {} class SwiftSuperPort : NSPort { } class SwiftSubPort : SwiftSuperPort { } class SwiftSuper { } class SwiftSub : SwiftSuper { } extension NSPort : SwiftObjCProto {} var obj : AnyObject func genericCast<T>(x: AnyObject, _: T.Type) -> T? { return x as? T } func genericCastObjCBound<T: NSObject>(x: AnyObject, _: T.Type) -> T? { return x as? T } // Test instance of Swift subclass of Objective-C class obj = SwiftSubPort() _ = obj as! SwiftSubPort _ = obj as! SwiftSuperPort _ = (obj as? NSPort) _ = (obj as? NSObject)! if (obj as? SwiftSubPort) == nil { abort() } if (obj as? SwiftSuperPort) == nil { abort() } if (obj as? NSPort) == nil { abort() } if (obj as? NSObject) == nil { abort() } if (obj as? NSArray) != nil { abort() } if (obj as? SwiftSub) != nil { abort() } if (obj as? SwiftSuper) != nil { abort() } obj = SwiftSuperPort() _ = obj as! SwiftSuperPort _ = obj as! NSPort _ = obj as! NSObject if (obj as? SwiftSubPort) != nil { abort() } if (obj as? SwiftSuperPort) == nil { abort() } if (obj as? NSPort) == nil { abort() } if (obj as? NSObject) == nil { abort() } if (obj as? NSArray) != nil { abort() } if (obj as? SwiftSub) != nil { abort() } if (obj as? SwiftSuper) != nil { abort() } // Test instance of Objective-C class that has Swift subclass obj = NSPort() _ = obj as! NSPort _ = obj as! NSObject if (obj as? SwiftSubPort) != nil { abort() } if (obj as? SwiftSuperPort) != nil { abort() } if (obj as? NSPort) == nil { abort() } if (obj as? NSObject) == nil { abort() } if (obj as? NSArray) != nil { abort() } if (obj as? SwiftSub) != nil { abort() } if (obj as? SwiftSuper) != nil { abort() } if (obj as? SwiftObjCProto) == nil { abort() } obj = NSPort() _ = genericCast(obj, NSPort.self)! _ = genericCast(obj, NSObject.self)! if genericCast(obj, SwiftSubPort.self) != nil { abort() } if genericCast(obj, SwiftSuperPort.self) != nil { abort() } if genericCast(obj, NSPort.self) == nil { abort() } if genericCast(obj, NSObject.self) == nil { abort() } if genericCast(obj, NSArray.self) != nil { abort() } if genericCast(obj, SwiftSub.self) != nil { abort() } if genericCast(obj, SwiftSuper.self) != nil { abort() } _ = genericCastObjCBound(obj, NSPort.self)! _ = genericCastObjCBound(obj, NSObject.self)! if genericCastObjCBound(obj, SwiftSubPort.self) != nil { abort() } if genericCastObjCBound(obj, SwiftSuperPort.self) != nil { abort() } if genericCastObjCBound(obj, NSPort.self) == nil { abort() } if genericCastObjCBound(obj, NSObject.self) == nil { abort() } if genericCastObjCBound(obj, NSArray.self) != nil { abort() } obj = NSObject() _ = obj as! NSObject if (obj as? SwiftSubPort) != nil { abort() } if (obj as? SwiftSuperPort) != nil { abort() } if (obj as? NSPort) != nil { abort() } if (obj as? NSObject) == nil { abort() } if (obj as? NSCopying) != nil { abort() } if (obj as? NSArray) != nil { abort() } if (obj as? SwiftSub) != nil { abort() } if (obj as? SwiftSuper) != nil { abort() } if (obj as? SwiftObjCProto) != nil { abort() } // Test instance of a tagged pointer type obj = NSNumber(int: 1234567) _ = obj as! NSNumber _ = obj as! NSValue _ = obj as! NSObject _ = obj as! NSCopying if (obj as? SwiftSubPort) != nil { abort() } if (obj as? SwiftSuperPort) != nil { abort() } if (obj as? NSNumber) == nil { abort() } if (obj as? NSValue) == nil { abort() } if (obj as? NSObject) == nil { abort() } if (obj as? NSCopying) == nil { abort() } if (obj as? NSArray) != nil { abort() } if (obj as? SwiftSub) != nil { abort() } if (obj as? SwiftSuper) != nil { abort() } // Test instance of a Swift class with no Objective-C inheritance obj = SwiftSub() _ = obj as! SwiftSub _ = obj as! SwiftSuper if (obj as? SwiftSubPort) != nil { abort() } if (obj as? SwiftSuperPort) != nil { abort() } if (obj as? NSObject) != nil { abort() } if (obj as? NSArray) != nil { abort() } if (obj as? SwiftSub) == nil { abort() } if (obj as? SwiftSuper) == nil { abort() } obj = SwiftSuper() _ = obj as! SwiftSuper if (obj as? SwiftSubPort) != nil { abort() } if (obj as? SwiftSuperPort) != nil { abort() } if (obj as? NSObject) != nil { abort() } if (obj as? NSArray) != nil { abort() } if (obj as? SwiftSub) != nil { abort() } if (obj as? SwiftSuper) == nil { abort() } // Test optional and non-optional bridged conversions var ao: AnyObject = "s" ao as! String ao is String var auo: AnyObject! = "s" var s: String = auo as! String var auoo: AnyObject? = "s" auoo! as? String // Test bridged casts. // CHECK: Downcast to hello obj = NSString(string: "hello") if let str = obj as? String { print("Downcast to \(str)") } else { print("Not a string?") } // Forced cast using context // CHECK-NEXT: Forced to string hello let forcedStr: String = obj as! String print("Forced to string \(forcedStr)") // CHECK-NEXT: Downcast to Swift var objOpt: AnyObject? = NSString(string: "Swift") if let str = objOpt as? String { print("Downcast to \(str)") } else { print("Not a string?") } // Forced cast using context // CHECK-NEXT: Forced to string Swift let forcedStrOpt: String = objOpt as! String print("Forced to string \(forcedStrOpt)") // CHECK-NEXT: Downcast to world var objImplicitOpt: AnyObject! = NSString(string: "world") if let str = objImplicitOpt as? String { print("Downcast to \(str)") } else { print("Not a string?") } // Forced cast using context // CHECK-NEXT: Forced to string world let forcedStrImplicitOpt: String = objImplicitOpt as! String print("Forced to string \(forcedStrImplicitOpt)") // CHECK-NEXT: Downcast correctly failed due to nil objOpt = nil if let str = objOpt as? String { print("Downcast should not succeed for nil") } else { print("Downcast correctly failed due to nil") } // CHECK-NEXT: Downcast correctly failed due to nil objImplicitOpt = nil if let str = objImplicitOpt as? String { print("Downcast should not succeed for nil") } else { print("Downcast correctly failed due to nil") } // Test bridged "isa" checks. // CHECK: It's a string! obj = NSString(string: "hello") if obj is String { print("It's a string!") } else { print("Not a string?") } // CHECK-NEXT: It's a string! objOpt = NSString(string: "Swift") if objOpt is String { print("It's a string!") } else { print("Not a string?") } // CHECK-NEXT: It's a string! objImplicitOpt = NSString(string: "world") if objImplicitOpt is String { print("It's a string!") } else { print("Not a string?") } // CHECK-NEXT: Isa correctly failed due to nil objOpt = nil if objOpt is String { print("Isa should not succeed for nil") } else { print("Isa correctly failed due to nil") } // CHECK-NEXT: Isa correctly failed due to nil objImplicitOpt = nil if objImplicitOpt is String { print("Isa should not succeed for nil") } else { print("Isa correctly failed due to nil") } let words = ["Hello", "Swift", "World"] // CHECK-NEXT: Object-to-bridged-array cast produced ["Hello", "Swift", "World"] obj = words as AnyObject if let strArr = obj as? [String] { print("Object-to-bridged-array cast produced \(strArr)") } else { print("Object-to-bridged-array cast failed") } // Check downcast from the bridged type itself. // CHECK-NEXT: NSArray-to-bridged-array cast produced ["Hello", "Swift", "World"] var nsarr = words as NSArray if let strArr = nsarr as? [String] { print("NSArray-to-bridged-array cast produced \(strArr)") } else { print("NSArray-to-bridged-array cast failed") } // CHECK-NEXT: NSArray?-to-bridged-array cast produced ["Hello", "Swift", "World"] var nsarrOpt = words as NSArray? if let strArr = nsarrOpt as? [String] { print("NSArray?-to-bridged-array cast produced \(strArr)") } else { print("NSArray?-to-bridged-array cast failed") } // CHECK-NEXT: NSArray!-to-bridged-array cast produced ["Hello", "Swift", "World"] var nsarrImplicitOpt = words as NSArray! if let strArr = nsarrImplicitOpt as? [String] { print("NSArray!-to-bridged-array cast produced \(strArr)") } else { print("NSArray!-to-bridged-array cast failed") } // Check downcast from a superclass of the bridged type. // CHECK-NEXT: NSObject-to-bridged-array cast produced ["Hello", "Swift", "World"] var nsobj: NSObject = nsarr if let strArr = nsobj as? [String] { print("NSObject-to-bridged-array cast produced \(strArr)") } else { print("NSObject-to-bridged-array cast failed") } // CHECK-NEXT: NSArray is [String] if nsarr is [String] { print("NSArray is [String]") } else { print("NSArray is not a [String]") } // CHECK-NEXT: NSArray? is [String] if nsarrOpt is [String] { print("NSArray? is [String]") } else { print("NSArray? is not a [String]") } // CHECK-NEXT: NSArray! is [String] if nsarrImplicitOpt is [String] { print("NSArray! is [String]") } else { print("NSArray! is not a [String]") } // CHECK-NEXT: NSObject is [String] if nsobj is [String] { print("NSObject is [String]") } else { print("NSObject is not a [String]") } // Forced downcast based on context. // CHECK-NEXT: Forced to string array ["Hello", "Swift", "World"] var forcedStrArray: [String] = obj as! [String] print("Forced to string array \(forcedStrArray)") // CHECK-NEXT: Forced NSArray to string array ["Hello", "Swift", "World"] forcedStrArray = nsarr as! [String] print("Forced NSArray to string array \(forcedStrArray)") // CHECK-NEXT: Forced NSArray? to string array ["Hello", "Swift", "World"] forcedStrArray = nsarrOpt as! [String] print("Forced NSArray? to string array \(forcedStrArray)") // CHECK-NEXT: Forced NSArray! to string array ["Hello", "Swift", "World"] forcedStrArray = nsarrImplicitOpt as! [String] print("Forced NSArray! to string array \(forcedStrArray)") // CHECK-NEXT: Object-to-array cast produced [Hello, Swift, World] if let strArr = obj as? [NSString] { print("Object-to-array cast produced \(strArr)") } else { print("Object-to-array cast failed") } // CHECK-NEXT: Object-to-bridged-array cast failed due to bridge mismatch if let strArr = obj as? [Int] { print("Object-to-bridged-array cast should not have succeeded") } else { print("Object-to-bridged-array cast failed due to bridge mismatch") } // CHECK-NEXT: Array of strings is not an array of ints if obj is [Int] { print("Array of strings should not be an array of ints!") } else { print("Array of strings is not an array of ints") } // Implicitly unwrapped optional of object to array casts. // CHECK-NEXT: Object-to-bridged-array cast produced ["Hello", "Swift", "World"] objOpt = words as AnyObject? if let strArr = objOpt as? [String] { print("Object-to-bridged-array cast produced \(strArr)") } else { print("Object-to-bridged-array cast failed") } // Forced downcast based on context. // CHECK-NEXT: Forced to string array ["Hello", "Swift", "World"] let forcedStrArrayOpt: [String] = objOpt as! [String] print("Forced to string array \(forcedStrArrayOpt)") // CHECK-NEXT: Object-to-array cast produced [Hello, Swift, World] if let strArr = objOpt as? [NSString] { print("Object-to-array cast produced \(strArr)") } else { print("Object-to-array cast failed") } // CHECK: Object-to-bridged-array cast failed due to bridge mismatch if let intArr = objOpt as? [Int] { print("Object-to-bridged-array cast should not have succeeded") } else { print("Object-to-bridged-array cast failed due to bridge mismatch") } // CHECK: Object-to-bridged-array cast failed due to nil objOpt = nil if let strArr = objOpt as? [String] { print("Cast from nil succeeded?") } else { print("Object-to-bridged-array cast failed due to nil") } // Optional of object to array casts. // CHECK-NEXT: Object-to-bridged-array cast produced ["Hello", "Swift", "World"] objImplicitOpt = words as AnyObject! if let strArr = objImplicitOpt as? [String] { print("Object-to-bridged-array cast produced \(strArr)") } else { print("Object-to-bridged-array cast failed") } // Forced downcast based on context. // CHECK-NEXT: Forced to string array ["Hello", "Swift", "World"] let forcedStrArrayImplicitOpt: [String] = objImplicitOpt as! [String] print("Forced to string array \(forcedStrArrayImplicitOpt)") // CHECK-NEXT: Object-to-array cast produced [Hello, Swift, World] if let strArr = objImplicitOpt as? [NSString] { print("Object-to-array cast produced \(strArr)") } else { print("Object-to-array cast failed") } // CHECK: Object-to-bridged-array cast failed due to bridge mismatch if let intArr = objImplicitOpt as? [Int] { print("Object-to-bridged-array cast should not have succeeded") } else { print("Object-to-bridged-array cast failed due to bridge mismatch") } // CHECK: Object-to-bridged-array cast failed due to nil objImplicitOpt = nil if let strArr = objImplicitOpt as? [String] { print("Cast from nil succeeded?") } else { print("Object-to-bridged-array cast failed due to nil") } // Casting an array of numbers to different numbers. // CHECK: Numbers-as-doubles cast produces [3.9375, 2.71828, 0.0] obj = ([3.9375, 2.71828, 0] as [Double]) as AnyObject if let doubleArr = obj as? [Double] { print(sizeof(Double.self)) print("Numbers-as-doubles cast produces \(doubleArr)") } else { print("Numbers-as-doubles failed") } // CHECK: Numbers-as-floats cast produces [3.9375, 2.71828{{.*}}, 0.0] if let floatArr = obj as? [Float] { print(sizeof(Float.self)) print("Numbers-as-floats cast produces \(floatArr)") } else { print("Numbers-as-floats failed") } // CHECK: Numbers-as-ints cast produces [3, 2, 0] if let intArr = obj as? [Int] { print("Numbers-as-ints cast produces \(intArr)") } else { print("Numbers-as-ints failed") } // CHECK: Numbers-as-bools cast produces [true, true, false] if let boolArr = obj as? [Bool] { print("Numbers-as-bools cast produces \(boolArr)") } else { print("Numbers-as-bools failed") } class Base : NSObject { override var description: String { return "Base" } } class Derived : Base { override var description: String { return "Derived" } } // CHECK: Array-of-base cast produces [Derived, Derived, Base] obj = [Derived(), Derived(), Base()] if let baseArr = obj as? [Base] { print("Array-of-base cast produces \(baseArr)") } else { print("Not an array of base") } // CHECK: Not an array of derived if let derivedArr = obj as? [Derived] { print("Array-of-derived cast produces \(derivedArr)") } else { print("Not an array of derived") } // CHECK: Dictionary-of-base-base cast produces obj = [Derived() : Derived(), Derived() : Base(), Derived() : Derived() ] as AnyObject if let baseDict = obj as? Dictionary<Base, Base> { print("Dictionary-of-base-base cast produces \(baseDict)") } else { print("Not a dictionary of base/base") } // CHECK: Dictionary-of-derived-base cast produces if let baseDict = obj as? Dictionary<Derived, Base> { print("Dictionary-of-derived-base cast produces \(baseDict)") } else { print("Not a dictionary of derived/base") } // CHECK: Not a dictionary of derived/derived if let dict = obj as? Dictionary<Derived, Derived> { print("Dictionary-of-derived-derived cast produces \(dict)") } else { print("Not a dictionary of derived/derived") } let strArray: AnyObject = ["hello", "world"] let intArray: AnyObject = [1, 2, 3] let dictArray: AnyObject = [["hello" : 1, "world" : 2], ["swift" : 1, "speedy" : 2]] // CHECK: Dictionary<String, AnyObject> is obj = ["a" : strArray, "b" : intArray, "c": dictArray] if let dict = obj as? Dictionary<String, [AnyObject]> { print("Dictionary<String, AnyObject> is \(dict)") } else { print("Not a Dictionary<String, AnyObject>") } // CHECK: Not a Dictionary<String, String> if let dict = obj as? Dictionary<String, [String]> { print("Dictionary<String, String> is \(dict)") } else { print("Not a Dictionary<String, String>") } // CHECK: Not a Dictionary<String, Int> if let dict = obj as? Dictionary<String, [Int]> { print("Dictionary<String, Int> is \(dict)") } else { print("Not a Dictionary<String, Int>") } // CHECK: [Dictionary<String, Int>] is obj = dictArray if let array = obj as? [Dictionary<String, Int>] { print("[Dictionary<String, Int>] is \(array)") } else { print("Not a [Dictionary<String, Int>]") } // CHECK: Not a [Dictionary<String, String>] if let array = obj as? [Dictionary<String, String>] { print("[Dictionary<String, String>] is \(array)") } else { print("Not a [Dictionary<String, String>]") } // CHECK: Dictionary<String, [Dictionary<String, Int>]> is ["a": [ obj = ["a" : dictArray] if let dict = obj as? Dictionary<String, [Dictionary<String, Int>]> { print("Dictionary<String, [Dictionary<String, Int>]> is \(dict)") } else { print("Not a Dictionary<String, [Dictionary<String, Int>]>") } // CHECK: Not a Dictionary<String, [Dictionary<String, String>]> if let dict = obj as? Dictionary<String, [Dictionary<String, String>]> { print("Dictionary<String, [Dictionary<String, String>]> is \(dict)") } else { print("Not a Dictionary<String, [Dictionary<String, String>]>") } // CHECK: [Dictionary<String, [Dictionary<String, Int>]>] is obj = [obj, obj, obj] if let array = obj as? [Dictionary<String, [Dictionary<String, Int>]>] { print("[Dictionary<String, [Dictionary<String, Int>]>] is \(array)") } else { print("Not a [Dictionary<String, [Dictionary<String, Int>]>]") } // CHECK: Not a Dictionary<String, [Dictionary<String, String>]>[] if let array = obj as? Dictionary<String, [Dictionary<String, String>]> { print("Dictionary<String, [Dictionary<String, String>]>[] is \(array)") } else { print("Not a Dictionary<String, [Dictionary<String, String>]>[]") } // Helper function that downcasts func downcastToStringArrayOptOpt(obj: AnyObject??!!) { if let strArrOptOpt = obj as? [String]?? { if let strArrOpt = strArrOptOpt { if let strArr = strArrOpt { print("some(some(some(\(strArr))))") } else { print("some(some(none))") } } else { print("some(none)") } } else { print("none") } } // CHECK: {{^}}some(some(some(["a", "b", "c"]))){{$}} var objOptOpt: AnyObject?? = .Some(.Some(["a", "b", "c"])) downcastToStringArrayOptOpt(objOptOpt) // CHECK: {{^}}none{{$}} objOptOpt = .Some(.Some([1 : "hello", 2 : "swift", 3 : "world"])) downcastToStringArrayOptOpt(objOptOpt) // CHECK: {{^}}none{{$}} objOptOpt = .Some(.Some([1, 2, 3])) downcastToStringArrayOptOpt(objOptOpt) print("ok") // CHECK: ok
30.704918
86
0.659637
6aa9d1050afd543d5d32a7529611e68e7e87325b
2,810
// // SMHSInformation.swift // SMHSSchedule (iOS) // // Created by Jevon Mao on 6/3/21. // import SwiftUI struct SMHSInformation: View { var body: some View { VStack { Text("Contact SMCHS") .font(.title, weight: .bold) .textAlign(.leading) .padding(.top, 20) .padding(.bottom, 10) .lineLimit(1) .minimumScaleFactor(0.5) Text("General Inquries") .font(.title3, weight: .bold) .textAlign(.leading) .foregroundColor(.platformSecondaryLabel) .padding(.bottom) .lineLimit(1) .minimumScaleFactor(0.5) HStack { Text("Phone:") .font(.body, weight: .semibold) Link("949-766-6000", destination: URL(string: "tel:9497666000")!) .font(.body) Spacer() } .padding(.leading, 40) HStack { Text("Fax:") .font(.body, weight: .semibold) Link("949-766-6005", destination: URL(string: "tel:9497666005")!) .font(.body) Spacer() } .padding(.leading, 40) Text("Attendance or Dean's Office") .font(.title3, weight: .bold) .textAlign(.leading) .foregroundColor(.platformSecondaryLabel) .padding(.vertical) .lineLimit(1) .minimumScaleFactor(0.5) HStack { Text("Phone:") .font(.body, weight: .semibold) Link("949-766-6000", destination: URL(string: "tel:9497666000")!) .font(.body) Spacer() } .padding(.leading, 40) .padding(.bottom) } Text("Please call attendance/dean's office regarding: ") .font(.callout, weight: .medium) .lineLimit(1) .minimumScaleFactor(0.5) .textAlign(.leading) .padding(.bottom) Group { Text("\u{2022} Abensce and Tardienss").textAlign(.leading) Text("\u{2022} Dress code").textAlign(.leading) Text("\u{2022} Detentions").textAlign(.leading) Text("\u{2022} Disciplinary problems").textAlign(.leading) Text("\u{2022} Theft and vandalism").textAlign(.leading) Text("\u{2022} Parking permits").textAlign(.leading) } .padding(.bottom, 2) .foregroundColor(.platformSecondaryLabel) } } struct SMHSInformation_Previews: PreviewProvider { static var previews: some View { SMHSInformation() } }
33.058824
81
0.485409
1e5cac508ce97a4588d633e23514cebaafd64e87
5,501
/// Copyright (c) 2018 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import UIKit @IBDesignable public class Knob: UIControl { /** Contains the minimum value of the receiver. */ public var minimumValue: Float = 0 /** Contains the maximum value of the receiver. */ public var maximumValue: Float = 1 /** Contains the receiver’s current value. */ public private (set) var value: Float = 0 /** Sets the receiver’s current value, allowing you to animate the change visually. */ public func setValue(_ newValue: Float, animated: Bool = false) { value = min(maximumValue, max(minimumValue, newValue)) let angleRange = endAngle - startAngle let valueRange = maximumValue - minimumValue let angleValue = CGFloat(value - minimumValue) / CGFloat(valueRange) * angleRange + startAngle renderer.setPointerAngle(angleValue, animated: animated) } /** Contains a Boolean value indicating whether changes in the sliders value generate continuous update events. */ public var isContinuous = true private let renderer = KnobRenderer() /** Specifies the width in points of the knob control track. Defaults to 2 */ @IBInspectable public var lineWidth: CGFloat { get { return renderer.lineWidth } set { renderer.lineWidth = newValue } } /** Specifies the angle of the start of the knob control track. Defaults to -11π/8 */ public var startAngle: CGFloat { get { return renderer.startAngle } set { renderer.startAngle = newValue } } /** Specifies the end angle of the knob control track. Defaults to 3π/8 */ public var endAngle: CGFloat { get { return renderer.endAngle } set { renderer.endAngle = newValue } } /** Specifies the length in points of the pointer on the knob. Defaults to 6 */ @IBInspectable public var pointerLength: CGFloat { get { return renderer.pointerLength } set { renderer.pointerLength = newValue } } /** Specifies the color of the knob, including the pointer. Defaults to blue */ @IBInspectable public var color: UIColor { get { return renderer.color } set { renderer.color = newValue } } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override public func tintColorDidChange() { renderer.color = tintColor } private func commonInit() { renderer.updateBounds(bounds) renderer.color = tintColor renderer.setPointerAngle(renderer.startAngle) layer.addSublayer(renderer.trackLayer) layer.addSublayer(renderer.pointerLayer) let gestureRecognizer = RotationGestureRecognizer(target: self, action: #selector(Knob.handleGesture(_:))) addGestureRecognizer(gestureRecognizer) } @objc private func handleGesture(_ gesture: RotationGestureRecognizer) { // 1 let midPointAngle = (2 * CGFloat(Double.pi) + startAngle - endAngle) / 2 + endAngle // 2 var boundedAngle = gesture.touchAngle if boundedAngle > midPointAngle { boundedAngle -= 2 * CGFloat(Double.pi) } else if boundedAngle < (midPointAngle - 2 * CGFloat(Double.pi)) { boundedAngle -= 2 * CGFloat(Double.pi) } // 3 boundedAngle = min(endAngle, max(startAngle, boundedAngle)) // 4 let angleRange = endAngle - startAngle let valueRange = maximumValue - minimumValue let angleValue = Float(boundedAngle - startAngle) / Float(angleRange) * valueRange + minimumValue // 5 setValue(angleValue) if isContinuous { sendActions(for: .valueChanged) } else { if gesture.state == .ended || gesture.state == .cancelled { sendActions(for: .valueChanged) } } } } extension Knob { public override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() renderer.updateBounds(bounds) } }
36.190789
110
0.713688
c102727f9ba77cc006a5caa1af9b4f358f8fce6a
735
// // HumidityCollectionViewCell.swift // hackcity // // Created by Remi Robert on 26/03/2017. // Copyright © 2017 Remi Robert. All rights reserved. // import UIKit class HumidityCollectionViewCell: UICollectionViewCell { @IBOutlet weak var humidityLabel: UILabel! @IBOutlet weak var containerView: UIView! override func awakeFromNib() { super.awakeFromNib() self.containerView.layer.cornerRadius = 5 self.layer.masksToBounds = false self.layer.shadowOffset = CGSize(width: 0, height: 0) self.layer.shadowRadius = 5 self.layer.shadowOpacity = 0.1 } func configure(value: Double) { self.humidityLabel.text = "\(String(format: "%.0f", value))" } }
25.344828
68
0.669388
26b4cdd83926e142a892a8d2152b50355857ff40
558
// // MainNavigationController.swift // DY // // Created by 佘红响 on 16/12/7. // Copyright © 2016年 佘红响. All rights reserved. // import UIKit class MainNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() setupUI() } } // MARK: - 设置UI extension MainNavigationController { fileprivate func setupUI() { let navigationBar = UINavigationBar.appearance() navigationBar.setBackgroundImage(UIImage.imageWithColor(color: UIColor.orange), for: .default) } }
19.241379
102
0.673835
4bee9e39cd7ca36c3cfcb87f452bdf35bbd3d102
435
// // ViewController.swift // Tools // // Created by shanayyy on 03/19/2019. // Copyright (c) 2019 shanayyy. All rights reserved. // import UIKit import Tools class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
17.4
58
0.662069
62bb4dfb5dc1f0f32353037027eb89fefb9d3ef4
3,953
// // CameraViewController.swift // SnapChatMenu <https://github.com/DeveloperLY/30DaysOfSwift> // // Created by Liu Y on 16/4/10. // Copyright © 2016年 DeveloperLY. All rights reserved. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // import UIKit import AVFoundation class CameraViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var cameraView: UIView! @IBOutlet weak var tempImageView: UIImageView! var captureSession: AVCaptureSession? var stillImageOutput: AVCaptureStillImageOutput? var previewLayer: AVCaptureVideoPreviewLayer? override var prefersStatusBarHidden : Bool { return true } override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) previewLayer?.frame = cameraView.bounds } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) captureSession = AVCaptureSession() captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080 let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) var error: NSError? var input: AVCaptureDeviceInput! do { input = try AVCaptureDeviceInput(device: backCamera) } catch let error1 as NSError { error = error1 input = nil } if (error == nil && captureSession?.canAddInput(input) != nil) { captureSession?.addInput(input) stillImageOutput = AVCaptureStillImageOutput() stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG] if (captureSession?.canAddOutput(stillImageOutput) != nil) { captureSession?.addOutput(stillImageOutput) previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait cameraView.layer.addSublayer(previewLayer!) captureSession?.startRunning() } } } func didPressTakePhoto() { if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo) { videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) -> Void in if sampleBuffer != nil { let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) let dataProvider = CGDataProvider(data: imageData! as CFData) let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right) self.tempImageView.image = image self.tempImageView.isHidden = false } }) } } var didTakePhoto = Bool() func didPressTakeAnother() { if didTakePhoto == true { tempImageView.isHidden = true didTakePhoto = false } else { captureSession?.startRunning() didTakePhoto = true didPressTakePhoto() } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { didPressTakePhoto() } }
35.936364
167
0.635973
2800d39d72b7b89233e03864836e333e042c5a01
6,709
// // Indicator.swift // Kingfisher // // Created by João D. Moreira on 30/08/16. // // Copyright (c) 2018 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif #if os(macOS) public typealias IndicatorView = NSView #else public typealias IndicatorView = UIView #endif public enum IndicatorType { /// No indicator. case none /// Use system activity indicator. case activity /// Use an image as indicator. GIF is supported. case image(imageData: Data) /// Use a custom indicator, which conforms to the `Indicator` protocol. case custom(indicator: Indicator) } // MARK: - Indicator Protocol public protocol Indicator { func startAnimatingView() func stopAnimatingView() var viewCenter: CGPoint { get set } var view: IndicatorView { get } } extension Indicator { #if os(macOS) public var viewCenter: CGPoint { get { let frame = view.frame return CGPoint(x: frame.origin.x + frame.size.width / 2.0, y: frame.origin.y + frame.size.height / 2.0 ) } set { let frame = view.frame let newFrame = CGRect(x: newValue.x - frame.size.width / 2.0, y: newValue.y - frame.size.height / 2.0, width: frame.size.width, height: frame.size.height) view.frame = newFrame } } #else public var viewCenter: CGPoint { get { return view.center } set { view.center = newValue } } #endif } // MARK: - ActivityIndicator // Displays a NSProgressIndicator / UIActivityIndicatorView final class ActivityIndicator: Indicator { #if os(macOS) private let activityIndicatorView: NSProgressIndicator #else private let activityIndicatorView: UIActivityIndicatorView #endif private var animatingCount = 0 var view: IndicatorView { return activityIndicatorView } func startAnimatingView() { animatingCount += 1 // Already animating if animatingCount == 1 { #if os(macOS) activityIndicatorView.startAnimation(nil) #else activityIndicatorView.startAnimating() #endif activityIndicatorView.isHidden = false } } func stopAnimatingView() { animatingCount = max(animatingCount - 1, 0) if animatingCount == 0 { #if os(macOS) activityIndicatorView.stopAnimation(nil) #else activityIndicatorView.stopAnimating() #endif activityIndicatorView.isHidden = true } } init() { #if os(macOS) activityIndicatorView = NSProgressIndicator(frame: CGRect(x: 0, y: 0, width: 16, height: 16)) activityIndicatorView.controlSize = .small activityIndicatorView.style = .spinning #else #if os(tvOS) let indicatorStyle = UIActivityIndicatorViewStyle.white #else let indicatorStyle = UIActivityIndicatorViewStyle.gray #endif activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:indicatorStyle) activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleTopMargin] #endif } } // MARK: - ImageIndicator // Displays an ImageView. Supports gif final class ImageIndicator: Indicator { private let animatedImageIndicatorView: ImageView var view: IndicatorView { return animatedImageIndicatorView } init?(imageData data: Data, processor: ImageProcessor = DefaultImageProcessor.default, options: KingfisherOptionsInfo = KingfisherEmptyOptionsInfo) { var options = options // Use normal image view to show animations, so we need to preload all animation data. if !options.preloadAllAnimationData { options.append(.preloadAllAnimationData) } guard let image = processor.process(item: .data(data), options: options) else { return nil } animatedImageIndicatorView = ImageView() animatedImageIndicatorView.image = image animatedImageIndicatorView.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) #if os(macOS) // Need for gif to animate on macOS self.animatedImageIndicatorView.imageScaling = .scaleNone self.animatedImageIndicatorView.canDrawSubviewsIntoLayer = true #else animatedImageIndicatorView.contentMode = .center animatedImageIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleTopMargin] #endif } func startAnimatingView() { #if os(macOS) animatedImageIndicatorView.animates = true #else animatedImageIndicatorView.startAnimating() #endif animatedImageIndicatorView.isHidden = false } func stopAnimatingView() { #if os(macOS) animatedImageIndicatorView.animates = false #else animatedImageIndicatorView.stopAnimating() #endif animatedImageIndicatorView.isHidden = true } }
33.545
153
0.629602
efa43dea14ed03953c4f65f03aef9cbed4293581
2,041
/* MIT License Copyright (c) 2017-2018 MessageKit Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import UIKit class MediaMessageSizeCalculator: MessageSizeCalculator { open override func messageContainerSize(for message: MessageType) -> CGSize { let maxWidth = messageContainerMaxWidth(for: message) let sizeForMediaItem = { (maxWidth: CGFloat, item: MediaItem) -> CGSize in if maxWidth < item.size.width { // Maintain the ratio if width is too great let height = maxWidth * item.size.height / item.size.width return CGSize(width: maxWidth, height: height) } return item.size } switch message.kind { case .photo(let item): return sizeForMediaItem(maxWidth, item) case .video(let item): return sizeForMediaItem(maxWidth, item) default: fatalError("messageContainerSize received unhandled MessageDataType: \(message.kind)") } } }
40.82
98
0.712396
f4edd3f85fed854352f06eed0361d37a10b27e8f
1,046
// 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: "SmoothieModels", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "SmoothieModels", targets: ["SmoothieModels"]), ], 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: "SmoothieModels", dependencies: []), .testTarget( name: "SmoothieModelsTests", dependencies: ["SmoothieModels"]), ] )
36.068966
117
0.630019
335c893ff97d19525da80dfa4f0277442e51c21d
1,992
// // ViewController.swift // DoTryCatch // // Created by Tim Miller on 6/24/19. // Copyright © 2019 Tim Miller. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! enum LoginError: Error { case incompleteForm case invalidEmail case incorrectPasswordLength } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func loginButtonTapped(_ sender: UIButton) { do { try login() } catch LoginError.incompleteForm { Alert.showBasic(title: "Incomplete Form", message: "Please fill out both email and password fields", vc: self) } catch LoginError.invalidEmail { Alert.showBasic(title: "Invalid Email", message: "Please make sure you format you email correctly", vc: self) } catch LoginError.incorrectPasswordLength { Alert.showBasic(title: "Password Too Short", message: "Password should be at least 8 characters", vc: self) } catch { Alert.showBasic(title: "Unable To Login", message: "There was an error when attempting to login", vc: self) } } func login() throws { if let email = emailTextField.text, let password = passwordTextField.text { if email.isEmpty || password.isEmpty { throw LoginError.incompleteForm } if !email.isValidEmail { throw LoginError.invalidEmail } if password.count < 8 { throw LoginError.incorrectPasswordLength } } else { throw LoginError.incompleteForm } // Pretend this is great code that logs in my user // It really is amazing... } }
29.731343
122
0.595382
bf9890edb443699603f79a51af7c2bc7e6328ecc
7,470
// // GeoJSON.swift // PassengerApp // // Created by Guy Kogus on 21/12/2018. // Copyright © 2018 Guy Kogus. All rights reserved. // import CodableJSON /// A GeoJSON type. public enum GeoJSON: Equatable { /// A spatially bounded entity. public struct Feature: Codable, Equatable { /// The identifier of the feature. May be either a string or integer. public let id: GeoJSONFeatureIdentifier? /// The geometry of the feature. public let geometry: Geometry? /// Additional properties of the feature. public let properties: CodableJSON.JSON? /// The type of the feature. public let type: String } /// A list of `Feature` objects. public struct FeatureCollection: Codable, Equatable { /// The features of the collection. public let features: [Feature] } /// A region of space. public enum Geometry: Equatable { /// A single position. case point(coordinates: PointGeometry.Coordinates) /// An array of positions. case multiPoint(coordinates: MultiPointGeometry.Coordinates) /// An array of 2 or more positions. case lineString(coordinates: LineStringGeometry.Coordinates) /// An array of `lineString` coordinate arrays. case multiLineString(coordinates: MultiLineStringGeometry.Coordinates) /// An array of linear rings. case polygon(coordinates: PolygonGeometry.Coordinates) /// An array of `polygon` coordinate arrays. case multiPolygon(coordinates: MultiPolygonGeometry.Coordinates) /// An array of geometries. case geometryCollection(geometries: GeometryCollection.Geometries) } /// A spatially bounded entity. case feature(feature: Feature, boundingBox: [Double]?) /// A list of `feature`s. case featureCollection(featureCollection: FeatureCollection, boundingBox: [Double]?) /// A region of space. case geometry(geometry: Geometry, boundingBox: [Double]?) } extension GeoJSON: Codable { private enum CodingKeys: String, CodingKey { case type case bbox } private enum ObjectType: String, Codable { case feature = "Feature" case featureCollection = "FeatureCollection" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let type = try container.decode(String.self, forKey: .type) let boundingBox = try container.decodeIfPresent([Double].self, forKey: .bbox) switch type { case ObjectType.feature.rawValue: self = .feature(feature: try Feature(from: decoder), boundingBox: boundingBox) case ObjectType.featureCollection.rawValue: self = .featureCollection(featureCollection: try FeatureCollection(from: decoder), boundingBox: boundingBox) default: self = .geometry(geometry: try Geometry(from: decoder), boundingBox: boundingBox) } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(type, forKey: .type) switch self { case .feature(let feature, let boundingBox): try container.encodeIfPresent(boundingBox, forKey: .bbox) try feature.encode(to: encoder) case .featureCollection(let featureCollection, let boundingBox): try container.encodeIfPresent(boundingBox, forKey: .bbox) try featureCollection.encode(to: encoder) case .geometry(let geometry, let boundingBox): try container.encodeIfPresent(boundingBox, forKey: .bbox) try geometry.encode(to: encoder) } } private var type: String { switch self { case .feature(_, _): return ObjectType.feature.rawValue case .featureCollection(_, _): return ObjectType.featureCollection.rawValue case .geometry(let geometry, _): return geometry.type.rawValue } } } extension GeoJSON.Geometry: Codable { fileprivate enum GeometryType: String, Codable { case point = "Point" case multiPoint = "MultiPoint" case lineString = "LineString" case multiLineString = "MultiLineString" case polygon = "Polygon" case multiPolygon = "MultiPolygon" case geometryCollection = "GeometryCollection" } private enum CodingKeys: String, CodingKey { case type case coordinates case geometries } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let type = try container.decode(GeometryType.self, forKey: .type) switch type { case .point: self = .point(coordinates: try container.decode(PointGeometry.Coordinates.self, forKey: .coordinates)) case .multiPoint: self = .multiPoint(coordinates: try container.decode(MultiPointGeometry.Coordinates.self, forKey: .coordinates)) case .lineString: self = .lineString(coordinates: try container.decode(LineStringGeometry.Coordinates.self, forKey: .coordinates)) case .multiLineString: self = .multiLineString(coordinates: try container.decode(MultiLineStringGeometry.Coordinates.self, forKey: .coordinates)) case .polygon: self = .polygon(coordinates: try container.decode(PolygonGeometry.Coordinates.self, forKey: .coordinates)) case .multiPolygon: self = .multiPolygon(coordinates: try container.decode(MultiPolygonGeometry.Coordinates.self, forKey: .coordinates)) case .geometryCollection: self = .geometryCollection(geometries: try container.decode([GeoJSON.Geometry].self, forKey: .geometries)) } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(type, forKey: .type) switch self { case .point(let coordinates): try container.encode(coordinates, forKey: .coordinates) case .multiPoint(let coordinates): try container.encode(coordinates, forKey: .coordinates) case .lineString(let coordinates): try container.encode(coordinates, forKey: .coordinates) case .multiLineString(let coordinates): try container.encode(coordinates, forKey: .coordinates) case .polygon(let coordinates): try container.encode(coordinates, forKey: .coordinates) case .multiPolygon(let coordinates): try container.encode(coordinates, forKey: .coordinates) case .geometryCollection(let geometries): try container.encode(geometries, forKey: .geometries) } } fileprivate var type: GeometryType { switch self { case .point(_): return GeometryType.point case .multiPoint(_): return GeometryType.multiPoint case .lineString(_): return GeometryType.lineString case .multiLineString(_): return GeometryType.multiLineString case .polygon(_): return GeometryType.polygon case .multiPolygon(_): return GeometryType.multiPolygon case .geometryCollection(_): return GeometryType.geometryCollection } } }
39.734043
134
0.657564
8a7a1fc29009d7abcdee695eb0d7efec6c0899ad
9,663
// // ItemsRepositoryMock.swift // Mocky // // Created by przemyslaw.wosko on 19/05/2017. // Copyright © 2017 MakeAWishFoundation. All rights reserved. // import Foundation import SwiftyMocky import XCTest @testable import Mocky_Example_tvOS // sourcery: mock = "ItemsRepository" class ItemsRepositoryMock: ItemsRepository, Mock { // sourcery:inline:auto:ItemsRepositoryMock.autoMocked var matcher: Matcher = Matcher.default var stubbingPolicy: StubbingPolicy = .wrap var sequencingPolicy: SequencingPolicy = .lastWrittenResolvedFirst private var invocations: [MethodType] = [] private var methodReturnValues: [Given] = [] private var methodPerformValues: [Perform] = [] private var file: StaticString? private var line: UInt? public typealias PropertyStub = Given public typealias MethodStub = Given public typealias SubscriptStub = Given /// Convenience method - call setupMock() to extend debug information when failure occurs public func setupMock(file: StaticString = #file, line: UInt = #line) { self.file = file self.line = line } open func storeItems(items: [Item]) { addInvocation(.m_storeItems__items_items(Parameter<[Item]>.value(`items`))) let perform = methodPerformValue(.m_storeItems__items_items(Parameter<[Item]>.value(`items`))) as? ([Item]) -> Void perform?(`items`) } open func storeDetails(details: ItemDetails) { addInvocation(.m_storeDetails__details_details(Parameter<ItemDetails>.value(`details`))) let perform = methodPerformValue(.m_storeDetails__details_details(Parameter<ItemDetails>.value(`details`))) as? (ItemDetails) -> Void perform?(`details`) } open func storedItems() -> [Item]? { addInvocation(.m_storedItems) let perform = methodPerformValue(.m_storedItems) as? () -> Void perform?() var __value: [Item]? = nil do { __value = try methodReturnValue(.m_storedItems).casted() } catch { // do nothing } return __value } open func storedDetails(item: Item) -> ItemDetails? { addInvocation(.m_storedDetails__item_item(Parameter<Item>.value(`item`))) let perform = methodPerformValue(.m_storedDetails__item_item(Parameter<Item>.value(`item`))) as? (Item) -> Void perform?(`item`) var __value: ItemDetails? = nil do { __value = try methodReturnValue(.m_storedDetails__item_item(Parameter<Item>.value(`item`))).casted() } catch { // do nothing } return __value } fileprivate enum MethodType { case m_storeItems__items_items(Parameter<[Item]>) case m_storeDetails__details_details(Parameter<ItemDetails>) case m_storedItems case m_storedDetails__item_item(Parameter<Item>) static func compareParameters(lhs: MethodType, rhs: MethodType, matcher: Matcher) -> Bool { switch (lhs, rhs) { case (.m_storeItems__items_items(let lhsItems), .m_storeItems__items_items(let rhsItems)): guard Parameter.compare(lhs: lhsItems, rhs: rhsItems, with: matcher) else { return false } return true case (.m_storeDetails__details_details(let lhsDetails), .m_storeDetails__details_details(let rhsDetails)): guard Parameter.compare(lhs: lhsDetails, rhs: rhsDetails, with: matcher) else { return false } return true case (.m_storedItems, .m_storedItems): return true case (.m_storedDetails__item_item(let lhsItem), .m_storedDetails__item_item(let rhsItem)): guard Parameter.compare(lhs: lhsItem, rhs: rhsItem, with: matcher) else { return false } return true default: return false } } func intValue() -> Int { switch self { case let .m_storeItems__items_items(p0): return p0.intValue case let .m_storeDetails__details_details(p0): return p0.intValue case .m_storedItems: return 0 case let .m_storedDetails__item_item(p0): return p0.intValue } } } open class Given: StubbedMethod { fileprivate var method: MethodType private init(method: MethodType, products: [StubProduct]) { self.method = method super.init(products) } public static func storedItems(willReturn: [Item]?...) -> MethodStub { return Given(method: .m_storedItems, products: willReturn.map({ StubProduct.return($0 as Any) })) } public static func storedDetails(item: Parameter<Item>, willReturn: ItemDetails?...) -> MethodStub { return Given(method: .m_storedDetails__item_item(`item`), products: willReturn.map({ StubProduct.return($0 as Any) })) } public static func storedItems(willProduce: (Stubber<[Item]?>) -> Void) -> MethodStub { let willReturn: [[Item]?] = [] let given: Given = { return Given(method: .m_storedItems, products: willReturn.map({ StubProduct.return($0 as Any) })) }() let stubber = given.stub(for: ([Item]?).self) willProduce(stubber) return given } public static func storedDetails(item: Parameter<Item>, willProduce: (Stubber<ItemDetails?>) -> Void) -> MethodStub { let willReturn: [ItemDetails?] = [] let given: Given = { return Given(method: .m_storedDetails__item_item(`item`), products: willReturn.map({ StubProduct.return($0 as Any) })) }() let stubber = given.stub(for: (ItemDetails?).self) willProduce(stubber) return given } } public struct Verify { fileprivate var method: MethodType public static func storeItems(items: Parameter<[Item]>) -> Verify { return Verify(method: .m_storeItems__items_items(`items`))} public static func storeDetails(details: Parameter<ItemDetails>) -> Verify { return Verify(method: .m_storeDetails__details_details(`details`))} public static func storedItems() -> Verify { return Verify(method: .m_storedItems)} public static func storedDetails(item: Parameter<Item>) -> Verify { return Verify(method: .m_storedDetails__item_item(`item`))} } public struct Perform { fileprivate var method: MethodType var performs: Any public static func storeItems(items: Parameter<[Item]>, perform: @escaping ([Item]) -> Void) -> Perform { return Perform(method: .m_storeItems__items_items(`items`), performs: perform) } public static func storeDetails(details: Parameter<ItemDetails>, perform: @escaping (ItemDetails) -> Void) -> Perform { return Perform(method: .m_storeDetails__details_details(`details`), performs: perform) } public static func storedItems(perform: @escaping () -> Void) -> Perform { return Perform(method: .m_storedItems, performs: perform) } public static func storedDetails(item: Parameter<Item>, perform: @escaping (Item) -> Void) -> Perform { return Perform(method: .m_storedDetails__item_item(`item`), performs: perform) } } public func given(_ method: Given) { methodReturnValues.append(method) } public func perform(_ method: Perform) { methodPerformValues.append(method) methodPerformValues.sort { $0.method.intValue() < $1.method.intValue() } } public func verify(_ method: Verify, count: Count = Count.moreOrEqual(to: 1), file: StaticString = #file, line: UInt = #line) { let invocations = matchingCalls(method.method) MockyAssert(count.matches(invocations.count), "Expected: \(count) invocations of `\(method.method)`, but was: \(invocations.count)", file: file, line: line) } private func addInvocation(_ call: MethodType) { invocations.append(call) } private func methodReturnValue(_ method: MethodType) throws -> StubProduct { let candidates = sequencingPolicy.sorted(methodReturnValues, by: { $0.method.intValue() > $1.method.intValue() }) let matched = candidates.first(where: { $0.isValid && MethodType.compareParameters(lhs: $0.method, rhs: method, matcher: matcher) }) guard let product = matched?.getProduct(policy: self.stubbingPolicy) else { throw MockError.notStubed } return product } private func methodPerformValue(_ method: MethodType) -> Any? { let matched = methodPerformValues.reversed().first { MethodType.compareParameters(lhs: $0.method, rhs: method, matcher: matcher) } return matched?.performs } private func matchingCalls(_ method: MethodType) -> [MethodType] { return invocations.filter { MethodType.compareParameters(lhs: $0, rhs: method, matcher: matcher) } } private func matchingCalls(_ method: Verify) -> Int { return matchingCalls(method.method).count } private func givenGetterValue<T>(_ method: MethodType, _ message: String) -> T { do { return try methodReturnValue(method).casted() } catch { onFatalFailure(message) Failure(message) } } private func optionalGivenGetterValue<T>(_ method: MethodType, _ message: String) -> T? { do { return try methodReturnValue(method).casted() } catch { return nil } } private func onFatalFailure(_ message: String) { #if Mocky guard let file = self.file, let line = self.line else { return } // Let if fail if cannot handle gratefully SwiftyMockyTestObserver.handleMissingStubError(message: message, file: file, line: line) #endif } // sourcery:end }
42.381579
164
0.664079
48905ff62168fa580a7a37717f72f475e362826a
1,265
// // Tip_CalculatorUITests.swift // Tip CalculatorUITests // // Created by Fred Werbel on 12/30/15. // Copyright © 2015 Hannah Werbel. All rights reserved. // import XCTest class Tip_CalculatorUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } 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() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.189189
182
0.667194
e43b3202649abeb9f7a4a697285f835bd85ef323
4,915
// // ActivityView.swift // Firefly Activity // // Created by Denis Bohm on 12/28/17. // Copyright © 2017 Firefly Design LLC. All rights reserved. // import UIKit @IBDesignable class ActivityView: PlotView { var spans: [Activity.Span] = [] func setTimeAxisAll() { if spans.isEmpty { setTimeAxis(min: 0.0, max: 1.0) return } let min = spans.first!.timeRange().start let max = spans.last!.timeRange().end setTimeAxis(min: min, max: max) } func setVmaAxisAll() { let epsilon: Float = 0.0 valueAxis.max = Double(spans.reduce(epsilon) { max($0, $1.vmas.reduce(epsilon) { max($0, $1) }) }) } override func setTimeAxisEnded() { } func setSpans(spans: [Activity.Span]) { self.spans = spans } override func query(identifier: String, start: Date, end: Date) { let datastore = Datastore(identifier: identifier) self.spans = datastore.query(start: start.timeIntervalSince1970, end: end.timeIntervalSince1970) } func gaps() -> [(start: TimeInterval, end: TimeInterval)] { var gaps: [(start: TimeInterval, end: TimeInterval)] = [] if spans.count > 1 { var end = spans.first!.timeRange().end for span in spans.suffix(from: 1) { let (start, nextEnd) = span.timeRange() gaps.append((start: end, end: start)) end = nextEnd } } return gaps } func summarize(currentPath: UIBezierPath, previousCount: Int, previousX: Int, previousSum: Float, previousMin: Float, previousMax: Float) { let px = Double(plotInsets.left) + Double(previousX) let mean = Double(previousSum) / Double(previousCount) let h = Double(self.frame.size.height - plotInsets.bottom) let valueScale = valueAxis.scale(CGFloat(h)) let y = h - (mean - valueAxis.min) * valueScale addPoint(path: currentPath, x: px, y: y) let y0 = h - (Double(previousMin) - valueAxis.min) * valueScale let y1 = h - (Double(previousMax) - valueAxis.min) * valueScale let height = y0 - y1 UIBezierPath(rect: CGRect(x: px, y: y1, width: 1.0, height: height)).fill() } override func drawContent(_ dirtyRect: CGRect) { let timeScale = timeAxis.scale(bounds.size.width) for span in spans { let timeRange = span.timeRange() if (timeRange.end < timeAxis.min) || (timeRange.start > timeAxis.max) { continue } // for performance, calculate which vmas will just extend outside view and only draw between those... let first = Swift.max(Int(timeAxis.min - timeRange.start) / span.interval - 1, 0) let last = Swift.min(Int(timeAxis.max - timeRange.start) / span.interval + 1, span.vmas.count) var time = timeRange.start + Double(first * span.interval) let vmas = span.vmas[first ..< last] var previousCount = 0 var previousX = 0 var previousSum: Float = 0.0 var previousMin: Float = 0.0 var previousMax: Float = 0.0 UIColor.lightGray.setFill() UIColor.black.setStroke() let currentPath = UIBezierPath() for vma in vmas { let x = Int(round((time - timeAxis.min) * timeScale)) if (previousCount == 0) { previousX = x previousMin = vma previousMax = vma } else { if x != previousX { summarize(currentPath: currentPath, previousCount: previousCount, previousX: previousX, previousSum: previousSum, previousMin: previousMin, previousMax: previousMax) previousCount = 0 previousX = x previousSum = 0.0 previousMin = vma previousMax = vma } } previousCount += 1 previousSum += vma if vma < previousMin { previousMin = vma } if vma > previousMax { previousMax = vma } time += TimeInterval(span.interval) } if previousCount > 0 { summarize(currentPath: currentPath, previousCount: previousCount, previousX: previousX, previousSum: previousSum, previousMin: previousMin, previousMax: previousMax) } currentPath.stroke() } UIColor.red.setFill() drawGaps(gaps: gaps()) } }
36.407407
189
0.532655
abb6ad3f34f064fc83b3aa399cf6e99fe8407378
591
// // Color+Constants.swift // CodeMonkeyApple // // Created by Kyle Hughes on 7/11/21. // import SwiftUI #if canImport(UIKit) && !os(watchOS) import UIKit extension Color { // MARK: Grays public static let lightGray = Color(.lightGray) // MARK: System Grouped Backgrounds public static let secondarySystemGroupedBackground = Color(.secondarySystemGroupedBackground) public static let systemGroupedBackground = Color(.systemGroupedBackground) public static let tertiarySystemGroupedBackground = Color(.tertiarySystemGroupedBackground) } #endif
21.888889
97
0.736041
9b701b9da189d3c6f0e105c7151ae208a0473a43
350
// // SavePassportResponseModel.swift // OtiNetwork // // Created by odeon on 24.06.2021. // import UIKit import ObjectMapper public class SavePassportResponseModel: Mappable { public var idList: [Int]? public required init?(map: Map) { } public func mapping(map: Map) { idList <- map[""] } }
15.217391
50
0.602857
e4d08b85603410e27a7f5a6c23d389b45c6879f5
6,426
// // TableScene.swift // OCTGNPlayer // // Created by Greg Langmead on 2/20/19. // Copyright © 2019 Greg Langmead. All rights reserved. // import Foundation import SpriteKit class TableScene : SKScene, UIGestureRecognizerDelegate { var table : Table let tapAction : (() -> ()) var cardNodes : [Card:CardNode] var deckNodes : [Deck:DeckNode] var scale : CGFloat { didSet { self.table.config["scale"] = String(Float(scale)) } } var selectedNode : SKNode? = nil var longPressTakingPlace = false var tapGR : UITapGestureRecognizer var dragGR : UIPanGestureRecognizer var doubleTapGR : UITapGestureRecognizer var longPressGR : UILongPressGestureRecognizer var textureDB : TextureDB init(table: Table, size: CGSize, tapAction: @escaping (() -> ()) ){ self.table = table self.tapAction = tapAction self.scale = CGFloat(Float(table.config["scale", default: "0.2"])!) self.cardNodes = [:] self.deckNodes = [:] self.tapGR = UITapGestureRecognizer() self.dragGR = UIPanGestureRecognizer() self.doubleTapGR = UITapGestureRecognizer() self.longPressGR = UILongPressGestureRecognizer() self.textureDB = TextureDB() super.init(size: size) for gr in [self.tapGR, self.dragGR, self.doubleTapGR, self.longPressGR] { gr.delegate = self } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) not supported") } override func didMove(to view: SKView) { let background = SKSpriteNode(imageNamed: "background.jpg") background.position = CGPoint(x: 512, y: 384) background.blendMode = .replace background.zPosition = -1 addChild(background) self.tapGR.addTarget(self, action: #selector(callTapAction)) self.dragGR.addTarget(self, action: #selector(handlePanFrom)) self.doubleTapGR.addTarget(self, action: #selector(callTapAction)) self.longPressGR.addTarget(self, action: #selector(longPressAction)) self.view?.addGestureRecognizer(self.tapGR) self.view?.addGestureRecognizer(self.dragGR) self.view?.addGestureRecognizer(self.doubleTapGR) self.view?.addGestureRecognizer(self.longPressGR) } func syncFromModel(tableSize: CGSize) { for card in self.table.cards { if let cardNode = cardNodes[card] { cardNode.update(db: textureDB, tableSize: tableSize, tableScale: self.scale) } else { let node = CardNode(card: card, db: textureDB, tableSize: tableSize, tableScale: self.scale) cardNodes[card] = node node.position = CGPoint(x: tableSize.width * CGFloat(card.posX), y: tableSize.height * CGFloat(card.posY)) self.addChild(node) } } for deck in self.table.decks { if let deckNode = deckNodes[deck] { deckNode.update(db: textureDB, tableSize: tableSize, tableScale: self.scale) } else { let node = DeckNode(deck: deck, db: textureDB, tableSize: tableSize, tableScale: self.scale) deckNodes[deck] = node node.position = CGPoint(x: tableSize.width * CGFloat(deck.posX), y: tableSize.height * CGFloat(deck.posY)) self.addChild(node) } } } func syncToModel() { self.cardNodes.values.forEach {$0.syncToModel()} self.deckNodes.values.forEach {$0.syncToModel()} self.table.cards = self.cardNodes.keys.sorted() self.table.decks = self.deckNodes.keys.sorted() } @objc func longPressAction() { self.longPressTakingPlace = true self.selectedNode = nil } @objc func callTapAction(recognizer: UITapGestureRecognizer) { // intended to be for actions like toggling the toolbar, i.e. table-wide UI self.longPressTakingPlace = false self.tapAction() } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == self.longPressGR && otherGestureRecognizer == self.dragGR { return true } return false } func selectNodeForTouch(_ touchLocation: CGPoint) { let touchedNode = self.atPoint(touchLocation) if touchedNode is SKSpriteNode { if selectedNode == nil || !selectedNode!.isEqual(touchedNode) { if touchedNode is DeckNode && !self.longPressTakingPlace { let topCardNode = (touchedNode as! DeckNode).newCardNodeFromTop(db: textureDB, tableSize: self.size, tableScale: self.scale) cardNodes[topCardNode.card] = topCardNode topCardNode.position = touchedNode.position self.addChild(topCardNode) self.selectedNode = topCardNode } else { self.selectedNode?.removeAllActions() self.selectedNode = touchedNode as! SKSpriteNode } } } } func panForTranslation(_ translation: CGPoint) { let position = selectedNode!.position self.selectedNode!.position = CGPoint(x: position.x + translation.x, y: position.y + translation.y) } @objc func handlePanFrom(recognizer: UIPanGestureRecognizer) { if recognizer.state == .began { self.selectedNode = nil var touchLocation = recognizer.location(in: recognizer.view) touchLocation = self.convertPoint(fromView: touchLocation) self.selectNodeForTouch(touchLocation) } else if recognizer.state == .changed { var translation = recognizer.translation(in: recognizer.view!) translation = CGPoint(x: translation.x, y: -translation.y) self.panForTranslation(translation) recognizer.setTranslation(CGPoint.zero, in: recognizer.view) } else if recognizer.state == .ended { self.selectedNode!.removeAllActions() syncToModel() self.selectedNode = nil } self.longPressTakingPlace = false } }
38.25
157
0.617803
f9c65c0de985c3bae13dd68fed9333eaf1e0272c
2,530
// // SceneDelegate.swift // Converter // // Created by Eric Lewis on 6/20/19. // Copyright © 2019 Eric Lewis, Inc. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Use a UIHostingController as window root view controller if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: RootView()) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
40.806452
143
0.73913
acd6586f9314ec42fda3dff7d8a22e71a3467201
3,373
import Foundation import azureSwiftRuntime public protocol ConnectorsListByHub { var nextLink: String? { get } var hasAdditionalPages : Bool { get } var headerParameters: [String: String] { get set } var resourceGroupName : String { get set } var hubName : String { get set } var subscriptionId : String { get set } var apiVersion : String { get set } func execute(client: RuntimeClient, completionHandler: @escaping (ConnectorListResultProtocol?, Error?) -> Void) -> Void ; } extension Commands.Connectors { // ListByHub gets all the connectors in the specified hub. internal class ListByHubCommand : BaseCommand, ConnectorsListByHub { var nextLink: String? public var hasAdditionalPages : Bool { get { return nextLink != nil } } public var resourceGroupName : String public var hubName : String public var subscriptionId : String public var apiVersion = "2017-04-26" public init(resourceGroupName: String, hubName: String, subscriptionId: String) { self.resourceGroupName = resourceGroupName self.hubName = hubName self.subscriptionId = subscriptionId super.init() self.method = "Get" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/connectors" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{hubName}"] = String(describing: self.hubName) self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.queryParameters["api-version"] = String(describing: self.apiVersion) } public override func returnFunc(data: Data) throws -> Decodable? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let decoder = try CoderFactory.decoder(for: mimeType) if var pageDecoder = decoder as? PageDecoder { pageDecoder.isPagedData = true pageDecoder.nextLinkName = "NextLink" } let result = try decoder.decode(ConnectorListResultData?.self, from: data) if var pageDecoder = decoder as? PageDecoder { self.nextLink = pageDecoder.nextLink } return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (ConnectorListResultProtocol?, Error?) -> Void) -> Void { if self.nextLink != nil { self.path = nextLink! self.nextLink = nil; self.pathType = .absolute } client.executeAsync(command: self) { (result: ConnectorListResultData?, error: Error?) in completionHandler(result, error) } } } }
43.24359
156
0.600949
ab7614f93da0190da81276ce6916ab1b9b7e380f
538
// // FLAxesLabelConfig.swift // FLCharts // // Created by Francesco Leoni on 13/01/22. // import UIKit public struct FLAxesLabelConfig { /// The color of the axes labels. public var color: UIColor = FLColor.darkGray /// The font of the axes label. public var font: UIFont = .preferredFont(for: .footnote, weight: .regular) public init(color: UIColor = FLColor.darkGray, font: UIFont = .preferredFont(for: .footnote, weight: .regular)) { self.color = color self.font = font } }
23.391304
117
0.644981
16afcb854b5bc2ce48e366737b3f41d3c33e4c49
2,120
// // QuickBrickExceptionManager.swift // QuickBrickApple // // Created by Alex Zchut on 02/16/22. // import os.log import React import UIKit import XrayLogger import ZappCore class QuickBrickExceptionManager: RCTExceptionsManager, RCTExceptionsManagerDelegate { public lazy var logger = Logger.getLogger(for: ReactNativeManagerLogs.subsystem) func handleSoftJSException(withMessage message: String?, stack: [Any]?, exceptionId: NSNumber) { guard let message = message, let stack = stack else { return } let logOrigin = OSLog(subsystem: "\(Self.self)", category: "handleSoftJSException") os_log("handleSoftJSException message: %{public}@, stack: %{public}@", log: logOrigin, type: .error, message, stack) logger?.errorLog(message: ReactNativeManagerLogs.handleSoftJSException.message, category: ReactNativeManagerLogs.handleSoftJSException.category, data: [ "message": message, "stack": stack, "exceptionId": "\(exceptionId)", ]) } func handleFatalJSException(withMessage message: String?, stack: [Any]?, exceptionId: NSNumber) { guard let message = message, let stack = stack else { return } let logOrigin = OSLog(subsystem: "\(Self.self)", category: "handleFatalJSException") os_log("handleFatalJSException message: %{public}@, stack: %{public}@", log: logOrigin, type: .error, message, stack) logger?.errorLog(message: ReactNativeManagerLogs.handleFatalJSException.message, category: ReactNativeManagerLogs.handleFatalJSException.category, data: [ "message": message, "stack": stack, "exceptionId": "\(exceptionId)", ]) } }
34.754098
101
0.558019
e6a45e22ea777fcaa5b061c45c174b8fd8e04a7f
573
// // ViewController.swift // image-filtering // // Created by Leo Thomas on 17.11.17. // Copyright © 2017 Leonard Thomas. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let image = #imageLiteral(resourceName: "Camel.jpg") let result = image.convolve(with: .gaussian(size: 1001, sigma: 101 / 6)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
22.92
80
0.663176
89577201f0db7f9a433fd2c3183a696b18a6969c
1,463
// // GFButton.swift // GHFollowers // // Created by Mr Kes on 11/7/21. // Copyright © 2021 Sean Allen. All rights reserved. // import UIKit class GFButton: UIButton { //since we will create custom stuff in it. override init(frame: CGRect) { // initialize the parent class (UIButton) defaults first. super.init(frame: frame) configure() } // This required for storyboard. (in case if we initialize it in storyboard.) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } //custom initilazers convenience init(backgroundColor: UIColor, title: String){ //super.init(frame: .zero) self.init(frame: .zero) self.backgroundColor = backgroundColor self.setTitle(title, for: .normal) //configure() } //Configure custom button private func configure() { layer.cornerRadius = 10 //titleLabel?.textColor = .white setTitleColor(.white, for: .normal) // scalable font sizes (preferredFont) titleLabel?.font = UIFont.preferredFont(forTextStyle: .headline) // this means use auto layout automatically translatesAutoresizingMaskIntoConstraints = false } func set(backgroundColor: UIColor, title: String) { self.backgroundColor = backgroundColor setTitle(title, for: .normal) } }
26.6
81
0.619959
8a604cea931b36308eb33fd9491bbadd2a4e384a
5,651
// // ViewController.swift // Miji // // Created by Panja on 11/26/15. // Copyright © 2015 Panja. All rights reserved. // import Cocoa class ViewController: NSViewController { //Connections @IBOutlet weak var AdminPassword: NSSecureTextField! @IBOutlet weak var AdminPanel: NSButton! @IBOutlet weak var JobLabel: NSTextField! @IBOutlet weak var SubmitN: NSButton! @IBOutlet weak var NumberBox: NSTextField! @IBOutlet weak var JobButton: NSButton! @IBOutlet weak var LockButton: NSButton! //Variables var psub = false; //If # of Players Have Been Submited var players = 4; var i = 0; var positions:Array = [""]; var showing = false; var mTest = false; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. AdminPanel.hidden = true; LockButton.hidden = true; APanel(); } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } //Passing Positions to Admin Panel let shareData = ShareData.sharedInstance //^^^ // -*- Admin Panel -*- // @IBAction func AdminLogin(sender: AnyObject) { if(AdminPassword.stringValue == "admin"){ if(psub == true){ AdminPanel.hidden = false; AdminPassword.stringValue = ""; LockButton.hidden = false; }else{ let PasInsert:NSAlert = NSAlert(); PasInsert.messageText = "Please Input The # of Players First!"; PasInsert.informativeText = ""; PasInsert.runModal(); } }else{ let IncorAdmin:NSAlert = NSAlert(); IncorAdmin.messageText = "Incorrect Password"; IncorAdmin.informativeText = ""; IncorAdmin.runModal(); } } func APanel() { } @IBAction func LockPanel(sender: AnyObject) { AdminPassword.stringValue = ""; AdminPanel.hidden = true; LockButton.hidden = true; print("Panel Locked"); } // -*- ^ Admin Panel ^ -*- // @IBAction func Submit(sender: AnyObject) { players = Int(NumberBox.stringValue)!; psub = true; AdminPanel.hidden = true; LockButton.hidden = true; i = 0; showing = false; JobButton.stringValue = "Click For Your Job"; JobLabel.stringValue = "Click ^"; SA(players); } //Print Job On Screen @IBAction func ToggleJob(sender: AnyObject) { JobButton.stringValue = "Click To Clear"; positions = self.shareData.positions; if(showing == false){ if !(i >= players){ if !(positions[i] == "Murderer"){ JobLabel.stringValue = "\(positions[i])" }else{ if(players >= 7){ if(mTest == false){ JobLabel.stringValue = "Murderer - Kill 2!" }else{ JobLabel.stringValue = "Murderer - Kill 1" } }else if(players >= 5){ let randomNumber = arc4random_uniform(2) if(randomNumber == 1){ JobLabel.stringValue = "Murderer - Kill 1" }else if(randomNumber == 2){ if(mTest == false){ JobLabel.stringValue = "Murderer - Kill 2" mTest = true; }else{ JobLabel.stringValue = "Murderer - Kill 1" } } } } i++; showing = true; }else{ JobLabel.stringValue = "Done" } }else if(showing == true){ JobLabel.stringValue = ""; showing = false; } } //Setup Array With Positions func SA(players: Int){ positions = ["Murderer", "Judge", "Innocent", "Innocent"]; //Pre-set Positions if(players == 5){ positions += (["Co-Judge"]); }else if(players == 6){ positions += (["Innocent", "Co-Judge"]); }else if(players == 7){ positions += (["Murderer-2!", "Innocent", "Co-Judge"]); }else if(players == 8){ positions += (["Murderer-2!", "Innocent", "Co-Judge", "Angel"]); }else if(players == 9){ positions += (["Murderer-2", "Innocent", "Co-Judge", "Angel", "Innocent"]); } //Shuffle Job Order positions.shuffle(); positions = positions.shuffle(); print("\(positions)"); self.shareData.positions = positions; } } //Randomizers extension CollectionType { /// Return a copy of `self` with its elements shuffled func shuffle() -> [Generator.Element] { var positions = Array(self) positions.shuffleInPlace() return positions } } extension MutableCollectionType where Index == Int { /// Shuffle the elements of `self` in-place. mutating func shuffleInPlace() { // empty and single-element collections don't shuffle if count < 2 { return } for i in 0..<count - 1 { let j = Int(arc4random_uniform(UInt32(count - i))) + i guard i != j else { continue } swap(&self[i], &self[j]) } } }
31.220994
87
0.504159
61366f982572f89ff8d4acedaf12f50895f9f7b3
7,623
// // DetailTopSellController.swift // ExpectationSneakers // // Created by Edgar Barragan on 1/4/19. // Copyright © 2019 Brian Morales. All rights reserved. // import UIKit import Firebase class ChooseSneakerController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var detailPhoto: UIImageView! @IBOutlet weak var modelLabel: UILabel! @IBOutlet weak var sizeCollectionView: UICollectionView! @IBOutlet weak var sizeInfoLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var ModelName: UILabel! @IBOutlet weak var Pricelabel: UILabel! @IBOutlet weak var tallaARK: UIButton! @IBOutlet weak var addToCar: UIButton! var sneakerDetail: Sneaker? var sneakerDetailFirebase: SneakerFirebase? //Reference to size catalog node from sneaker node child var refCatSize: DatabaseReference! var refCart: DatabaseReference! var sizeCollection = [SizeFirebase]() var sizesChoose = [SizeFirebase]() var carFirebas: CartFirebase? override func viewDidLoad() { super.viewDidLoad() //self.tabBarController?.tabBar.isHidden = true sizeCollectionView.delegate = self sizeCollectionView.dataSource = self detailPhoto.image = getImageFromBase64(base64: (sneakerDetailFirebase?.image64)!) modelLabel.text = sneakerDetailFirebase?.model priceLabel.text = ("$" + (sneakerDetailFirebase?.price.description)!) refCart = Database.database().reference(withPath: "cart-db") getDataSizeFirebase() tallaARK.layer.cornerRadius = 5 tallaARK.layer.borderWidth = 1 tallaARK.layer.borderColor = UIColor.lightGray.cgColor addToCar.layer.cornerRadius = 5 addToCar.layer.borderWidth = 1 addToCar.layer.borderColor = UIColor.lightGray.cgColor } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //guard let sneakerDetail = sneakerDetail else {return 0} return sizeCollection.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellSize", for: indexPath) as! SizeViewCell cell.sizeCellLabel.text = sizeCollection[indexPath.row].size //.sizes[indexPath.row].size cell.propiertiesSizeCell(label: cell.sizeCellLabel) return cell } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session //self.navigationController?.setNavigationBarHidden(false, animated: false) //self.tabBarController?.tabBar.isHidden = false } func getImageFromBase64(base64:String) -> UIImage { let data = Data(base64Encoded: base64) return UIImage(data: data!)! } func getDataSizeFirebase(){ refCatSize = Database.database().reference(withPath: "sneaker-db").child((sneakerDetailFirebase?.key)!).child("sizesAvailable") //get data from catalog node refCatSize.observe(.value, with: { snapshot in var newItems: [SizeFirebase] = [] for child in snapshot.children { if let snapshot = child as? DataSnapshot, let sizeFirebaseItem = SizeFirebase(snapshot: snapshot) { newItems.append(sizeFirebaseItem) } } //once all data load from database , sorted size-array and add to array of size object self.sizeCollection = newItems.sorted(by: { $0.size < $1.size }) //reload the collection view once all data are load and sorted //self.sizesChoose = self.sizeCollection for var sizeChooseItem in self.sizeCollection{ sizeChooseItem.count = 0 self.sizesChoose.append(sizeChooseItem) } self.sizeCollectionView.reloadData() }) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let alert = UIAlertController(title: "There are \(sizeCollection[indexPath.row].count) items on stock", message: "Add a Quantity", preferredStyle: .alert) let saveAction = UIAlertAction(title: "Save", style: .default) { _ in let textField = alert.textFields![0] let valor = Int(textField.text!) ?? 0 self.sizesChoose[indexPath.row].count = valor } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) alert.addTextField() alert.addAction(saveAction) alert.addAction(cancelAction) present(alert, animated: true, completion: nil) } @IBAction func addToCart(_ sender: Any) { if (!validSizeArrayAvailable()){ let alert = UIAlertController(title: "Oops", message: "Please choose a size", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true) } else{ let cartItem = CartFirebase(model: (sneakerDetailFirebase?.model)!, price: Double((sneakerDetailFirebase?.price)!)) if (idTransaction.id == "" ){ idTransaction.id = self.refCart.childByAutoId().key! } // 3 let refCart = self.refCart.child(idTransaction.id).child((sneakerDetailFirebase?.model)!.lowercased()) refCart.setValue(cartItem.toAnyObject()) { (error:Error?, refCart:DatabaseReference) in if let error = error { print("Data could not be saved: \(error).") } else { print("Added to Cart!") //Add sizes to sneaker and save on database self.saveSneakerSizes(modelSneaker: (self.sneakerDetailFirebase?.model.lowercased())!, referenceCart: refCart) let alert = UIAlertController(title: "Saved", message: "Snaker info was saved", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) self.present(alert, animated: true) } } } } func saveSneakerSizes(modelSneaker:String, referenceCart: DatabaseReference){ for size in self.sizesChoose { if size.count != 0 { let sizeItem = SizeFirebase(size: size.size, count: size.count, sizeCM: size.sizeCM) let sizeItemRef = referenceCart.child("sizesAvailable").child(size.size.replacingOccurrences(of: ".", with: "-").lowercased()) sizeItemRef.setValue(sizeItem.toAnyObject()) //self.sizesAvailable.remove(at: itemIndex) } } } func validSizeArrayAvailable()-> Bool{ var result: Bool = false for size in self.sizesChoose { if size.count != 0 { result = true } } return result } }
38.892857
142
0.609603
761d27c18301f03e15b62490ebf1cb1e574c887e
594
// // ElementGroup.swift // VFCounter // // Created by Sunmi on 2020/11/01. // Copyright © 2020 creativeSun. All rights reserved. // import Foundation enum Status: String { case add, edit, delete, refetch var status: String { return rawValue } } struct ItemGroup: Hashable { var date: String? var category: Category? init(date: String?, category: Category?) { self.date = date self.category = category } } struct UpdateItem { var olddate: String = "" var date: String = "" var itemCount: Int = 0 var status: Status? }
16.971429
54
0.621212
ac5a236b4571cc1bdea936d1bf21ab60fa5090d4
368
// // ServiceResource.swift // FilterProviderLib // // Created by Kent Friesen on 5/23/19. // Copyright © 2019 CloudVeil Technology, Inc. All rights reserved. // import Foundation public enum ServiceResource { case getToken case userDataSumCheck case userConfigSumCheck case userConfigRequest case ruleDataSumCheck case ruleDataRequest }
19.368421
68
0.736413