repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
huonw/swift | test/ClangImporter/attr-swift_name_renaming.swift | 18 | 1486 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules -Xcc -w -typecheck -verify %s
import SwiftName
func test() {
// Function name remapping
drawString("hello", x: 3, y: 5)
drawString("hello", 3, 5) // expected-error{{missing argument labels 'x:y:' in call}}
// Enum name remapping.
var color: ColorKind = CT_red
var color2: ColorType = CT_Red // expected-error{{'ColorType' has been renamed to 'ColorKind'}}{{15-24=ColorKind}}
// Enumerator remapping.
var excuse: HomeworkExcuse = .dogAteIt
excuse = .overslept // expected-error{{type 'HomeworkExcuse' has no member 'overslept'; did you mean 'Overslept'?}} {{13-22=Overslept}}
excuse = .tired
excuse = .tooHard // expected-error{{type 'HomeworkExcuse' has no member 'tooHard'; did you mean 'TooHard'?}} {{13-20=TooHard}}
excuse = .challenging
// Typedef-of-anonymous-type-name renaming
var p = Point()
var p2 = PointType() // FIXME: should provide Fix-It expected-error{{use of unresolved identifier 'PointType'}} {{none}}
// Field name remapping
p.x = 7
// Typedef renaming
var mi: MyInt = 5
var mi2: my_int_t = 7 // expected-error{{'my_int_t' has been renamed to 'MyInt'}}{{12-20=MyInt}}
spuriousAPINotedSwiftName(0)
nicelyRenamedFunction("go apinotes!")
_ = AnonymousEnumConstant // expected-error {{'AnonymousEnumConstant' has been renamed to 'BoxForConstants.anonymousEnumConstant'}}
_ = BoxForConstants.anonymousEnumConstant // okay
}
| apache-2.0 | 3b20dbfb0df74d6bd38d4a4dc110aab2 | 39.162162 | 137 | 0.699865 | 3.423963 | false | false | false | false |
Yoloabdo/CS-193P | Calculator/Calculator/CalculatorBrain.swift | 1 | 11827 | //
// CalculatorBrain.swift
// Calculator
//
// Created by abdelrahman mohamed on 1/18/16.
// Copyright © 2016 Abdulrhman dev. All rights reserved.
//
import Foundation
/// #### Calcaulator class
/// - simply doing all the work
/// - class uses recursive method to get operands from a stack
class CalculatorBrain {
/// custom type of enum to save the operation.
/// this type is decribable.
private enum Op: CustomStringConvertible{
case operand(Double)
case variable(String)
case constantValue(String, Double)
case unaryOperation(String, (Double) ->Double, (Double -> String?)?)
case binaryOperation(String, (Double, Double) ->Double, ((Double) -> String?)?)
var description: String {
get{
switch self {
case .operand(let operand):
return "\(operand)"
case .variable(let symbol):
return "\(symbol)"
case .constantValue(let symbol, _):
return "\(symbol)"
case .unaryOperation(let symbol, _, _):
return "\(symbol)"
case .binaryOperation(let symbol, _, _):
return "\(symbol)"
}
}
}
var precedence: Int {
get{
switch self{
case .binaryOperation(let symbol, _, _):
switch symbol{
case "×", "%", "÷":
return 2
case "+", "-":
return 1
default: return Int.max
}
default:
return Int.max
}
}
}
}
// contains all the operation entered through the user to calcluator.
private var opStack = [Op]()
// knownOps contains all known operations to the calculator.
private var knownOps = Dictionary<String, Op>()
// saving variables into the stack
var variableValues = [String: Double]()
/// String to save error if there's one.
private var error: String?
/// A properity gets the program to public.
/// caller won't have any idea what's it.
/// this's good if we want to save the information as cookie or something alike.
/// it's a ProperityList.
var program: AnyObject {
set{
if let opSymbols = newValue as? Array<String> {
var newOpStack = [Op]()
for opSymbol in opSymbols {
if let op = knownOps[opSymbol]{
newOpStack.append(op)
}else if let operand = Double(opSymbol){
newOpStack.append(.operand(operand))
}else{
newOpStack.append(.variable(opSymbol))
}
}
opStack = newOpStack
}
}
get{
return opStack.map { $0.description }
}
}
init(){
/// this function is just there to not type the string of the function twice.
/// - Parameter op: takes the operation type declarition in order to iniate the ops Stack.
func learnOps(op: Op){
knownOps[op.description] = op
}
learnOps(Op.constantValue("π", M_PI))
learnOps(Op.binaryOperation("+", +, nil))
learnOps(Op.binaryOperation("−", { $1 - $0}, nil))
learnOps(Op.binaryOperation("×", *, nil))
learnOps(Op.binaryOperation("%", { $1 % $0},
{ $0 == 0.0 ? "Division by zero" : nil }))
learnOps(Op.binaryOperation("÷", { $1 / $0},
{ $0 == 0.0 ? "Division by zero" : nil }))
learnOps(Op.unaryOperation("√", sqrt, {$0 < 0 ? "square root zero": nil}))
learnOps(Op.unaryOperation("sin", sin, nil))
learnOps(Op.unaryOperation("cos", cos, nil))
learnOps(Op.unaryOperation("tan", tan, nil))
learnOps(Op.unaryOperation("+/-", { -$0 }, nil))
learnOps(Op.unaryOperation("x²", { $0 * $0 }, nil))
learnOps(Op.variable("M"))
}
/// Evaluation function. It works recursivly through the array.
/// - Parameter ops: Array of Op enum special type defined earlier.
/// - Returns: a list contains result and the rest of the input array.
/// Error test handling has been added to the function as a closure.
///
private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]){
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case .operand(let operand):
return (operand, remainingOps)
case .variable(let symbol):
if let value = variableValues[symbol]{
return (value, remainingOps)
}
error = "Variable Not Set"
return (nil, remainingOps)
case .constantValue(_, let operand):
return (operand, remainingOps)
case .unaryOperation(_, let operation, let errorTest):
let operandEvaluation = evaluate(remainingOps)
if let operand = operandEvaluation.result {
// checking error test closure
if let errorMessage = errorTest?(operand) {
error = errorMessage
return (nil, operandEvaluation.remainingOps)
}
return (operation(operand), operandEvaluation.remainingOps)
}
case .binaryOperation(_, let operation, let errorTest):
let op1Evaluation = evaluate(remainingOps)
if let operand1 = op1Evaluation.result {
// checking error test closure
if let errorMessage = errorTest?(operand1) {
error = errorMessage
return (nil, op1Evaluation.remainingOps)
}
let op2Evaluation = evaluate(op1Evaluation.remainingOps)
if let operand2 = op2Evaluation.result {
return (operation(operand1, operand2), op2Evaluation.remainingOps)
}
}
}
if error == nil {
error = "Not Enough Operands"
}
}
return (nil, ops)
}
/// Evalute second function, calls insider function with same name in order to get the results.
/// - Returns: nil or Double, depends if there's error in calculating what's inside the Op stack.
func evaluate() -> Double? {
error = nil
let (result, _) = evaluate(opStack)
// print("\(opStack) = \(result) with \(remainder) leftover")
return result
}
// evaluateAndReportErrors()
func evaluateAndReportErrors() -> AnyObject? {
let (result, _) = evaluate(opStack)
return result != nil ? result : error
}
/// description of what's inside the stack without evaluation, works recursively as evaluate function.
/// - Parameter ops : operation stack
/// - returns: results as a string, plus remaining operations and presedence of the rest.
private func description (ops: [Op]) -> (result: String?, remainingOps: [Op], precedence: Int?){
if !ops.isEmpty{
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case.operand(let operand):
return (String(format: "%g", operand), remainingOps, op.precedence)
case .variable(let symbol):
return ("\(symbol)", remainingOps, op.precedence)
case .constantValue(let symbol, _):
return ("\(symbol)", remainingOps, op.precedence)
case .unaryOperation(let symbol, _, _):
let operandEvaluation = description(remainingOps)
if var operand = operandEvaluation.result {
if op.precedence > operandEvaluation.precedence {
operand = "(\(operand))"
}
return ("\(symbol)\(operand)", operandEvaluation.remainingOps, op.precedence)
}
case .binaryOperation(let symbol, _, _):
let op1Evaluation = description(remainingOps)
if var operand1 = op1Evaluation.result {
if op.precedence > op1Evaluation.precedence {
operand1 = "(\(operand1))"
}
let op2Evaluation = description(op1Evaluation.remainingOps)
if var operand2 = op2Evaluation.result {
if op.precedence > op2Evaluation.precedence {
operand2 = "(\(operand2))"
}
return ("\(operand2) \(symbol) \(operand1)",
op2Evaluation.remainingOps, op.precedence)
}
}
}
}
return("?", ops, Int.max)
}
/// calling description function through this var.
var discription: String {
get{
var (result, ops) = ("", opStack)
repeat {
var current: String?
(current, ops, _) = description(ops)
// result adds up if no operations added to the stack and sepreated by comma ,.
result = result == "" ? current! : "\(current!), \(result)"
} while ops.count > 0
return result
}
}
/// private method to get the last operand in the stack into vars dic
/// i guess there's simple ways, but this one looks appealing now
private func addVarValue(ops: [Op]){
if !ops.isEmpty{
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case.operand(let operand):
variableValues["M"] = operand
default:
break
}
}
}
/// public version of previous func.
func addOperandValueM() -> Bool{
addVarValue(opStack)
return popOperand()
}
/// Pushing operand inside the OpStack and then calls evaluate function.
/// - Parameter operand: takes an operand into the stack.
/// - Returns: The result from the evaluation.
func pushOperand(operand: Double) -> Double? {
opStack.append(Op.operand(operand))
return evaluate()
}
/// Pushing operation into the OpStack
/// - Parameter symbol: takes variable such as X, Y, check if it's known to our variableValues Dic.
/// - Returns: evaluate, as usual optional!
func pushOperand(symbol: String) -> Double? {
opStack.append(Op.variable(symbol))
return evaluate()
}
/// Pushing operation into the OpStack
/// - Parameter symbol: takes any operation that to be applied, check if it's known to our knownOps Stack.
/// - Returns: evaluate, as usual optional!
func performOperation(symbol: String) -> Double? {
if let operation = knownOps[symbol] {
opStack.append(operation)
}
return evaluate()
}
func popOperand() -> Bool{
if !opStack.isEmpty{
opStack.popLast()
return true
}
return false
}
} | mit | f5cc5233a162f4a2d45ae474d97864f6 | 35.248466 | 110 | 0.514472 | 5.093103 | false | false | false | false |
wolfposd/Caffeed | FeedbackBeaconContext/FeedbackBeaconContext/FeedbackSheet/Controller/FSViewControllerHelper.swift | 1 | 1862 | //
// FSViewControllerHelper.swift
// FeedbackBeaconContext
//
// Created by Wolf Posdorfer on 03.11.14.
// Copyright (c) 2014 Wolf Posdorfer. All rights reserved.
//
import Foundation
import UIKit
public class FSViewControllerHelper : NSObject
{
public class func registerModuleCells(tableView: UITableView)
{
let nibNames = ["ListCell", "LongListCell", "TextFieldCell", "TextAreaCell", "CheckboxCell", "SliderCell", "StarRatingCell", "DateCell", "PhotoCell", "ToSCell"]
let identifier = [FeedbackSheetModuleType.List.rawValue, FeedbackSheetModuleType.LongList.rawValue, FeedbackSheetModuleType.TextField.rawValue, FeedbackSheetModuleType.TextArea.rawValue, FeedbackSheetModuleType.Checkbox.rawValue, FeedbackSheetModuleType.Slider.rawValue, FeedbackSheetModuleType.StarRating.rawValue, FeedbackSheetModuleType.Date.rawValue, FeedbackSheetModuleType.Photo.rawValue, FeedbackSheetModuleType.ToS.rawValue]
for (index, name) in enumerate(nibNames) {
tableView.registerNib(UINib(nibName: name, bundle: NSBundle.mainBundle()), forCellReuseIdentifier: identifier[index])
}
}
public class func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, dictionary: Dictionary<String, NSObject>, page: FeedbackSheetPage, delegate: ModuleCellDelegate) -> UITableViewCell {
let module = page.modulesVisible[indexPath.section]
let type = module.type
let moduleCell = tableView.dequeueReusableCellWithIdentifier(type.rawValue) as ModuleCell
moduleCell.delegate = delegate;
moduleCell.setModule(module);
// Reload persisted state
if let data = dictionary[module.ID] {
moduleCell.reloadWithResponseData(data)
}
return moduleCell
}
} | gpl-3.0 | b124415ef23ed003861bf18e6b3f041e | 40.4 | 440 | 0.722879 | 4.737913 | false | false | false | false |
frajaona/LiFXSwiftKit | Sources/LiFXCASSocket.swift | 1 | 2383 | /*
* Copyright (C) 2016 Fred Rajaona
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import CocoaAsyncSocket
class LiFXCASSocket: NSObject, LiFXSocket {
var messageHandler: ((LiFXMessage, String) -> ())?
var udpSocket: Socket? {
return rawSocket
}
fileprivate var rawSocket: UdpCASSocket<LiFXMessage>?
func openConnection() {
let socket = UdpCASSocket<LiFXMessage>(destPort: LiFXCASSocket.UdpPort, shouldBroadcast: true, socketDelegate: self)
rawSocket = socket
if !socket.openConnection() {
closeConnection()
} else {
}
}
func closeConnection() {
rawSocket?.closeConnection()
rawSocket = nil
}
func isConnected() -> Bool {
return udpSocket != nil
}
}
extension LiFXCASSocket: GCDAsyncUdpSocketDelegate {
func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
Log.debug("socked did send data with tag \(tag)")
}
func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) {
Log.debug("socked did not send data with tag \(tag)")
}
func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) {
Log.debug("Socket closed: \(error?.localizedDescription)")
}
func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
Log.debug("\nReceive data from isIPv4=\(GCDAsyncUdpSocket.isIPv4Address(address)) address: \(GCDAsyncUdpSocket.host(fromAddress: address))")
//Log.debug(data.description)
let message = LiFXMessage(fromData: data)
messageHandler?(message, GCDAsyncUdpSocket.host(fromAddress: address)!)
}
}
| apache-2.0 | 0c46df7019de932ee82573d70fe9075d | 31.643836 | 148 | 0.668065 | 4.521822 | false | false | false | false |
aipeople/PokeIV | Pods/PGoApi/PGoApi/Classes/Unknown6/subFuncH.swift | 1 | 33652 | //
// subFuncA.swift
// Pods
//
// Created by PokemonGoSucks on 2016-08-10
//
//
import Foundation
public class subFuncH {
public func subFuncH(input_: Array<UInt32>) -> Array<UInt32> {
var v = Array<UInt32>(count: 471, repeatedValue: 0);
var input = input_
v[0] = ~input[7]
v[1] = (v[0] & input[42])
v[2] = input[42]
v[3] = ~v[1]
v[4] = (input[7] ^ v[2])
v[5] = (v[1] & input[23])
v[6] = (v[0] & input[42])
v[7] = ~input[61]
v[8] = (~v[1] & input[23])
v[9] = (v[1] & v[7])
v[10] = ~input[61]
let part0 = ((input[7] ^ (v[1] & v[7])))
let part1 = ((input[31] | ~part0))
let part2 = ((v[1] ^ input[72]))
let part3 = ((input[183] ^ (part2 & input[61])))
let part4 = ((v[5] | input[61]))
v[11] = (((((v[4] ^ input[28]) ^ v[8]) ^ part4) ^ (input[31] & ~part3)) ^ (part1 & input[15]))
v[12] = (v[0] & input[23])
v[13] = (v[12] & input[61])
v[14] = (input[6] & v[11])
v[15] = (input[6] & ~v[14])
let part5 = ((input[7] ^ (v[1] & v[7])))
let part6 = ((input[31] | ~part5))
let part7 = ((v[1] ^ input[72]))
let part8 = ((input[183] ^ (part7 & input[61])))
let part9 = ((v[5] | input[61]))
v[16] = (((((v[4] ^ input[28]) ^ v[8]) ^ part9) ^ (input[31] & ~part8)) ^ (part6 & input[15]))
v[17] = (input[6] | v[11])
let part10 = (((~v[1] & input[61]) ^ v[6]))
v[18] = ((input[31] & ~part10) ^ (v[12] & input[61]))
v[19] = (v[11] & input[36])
v[20] = (input[36] & ~v[15])
let part11 = ((v[5] ^ (v[0] & input[42])))
let part12 = (((part11 & v[7]) ^ input[23]))
v[21] = (((input[89] ^ input[23]) ^ v[4]) ^ (part12 & input[31]))
v[22] = (input[36] & ~v[15])
v[23] = (((input[16] ^ input[141]) ^ input[96]) ^ input[152])
v[24] = (input[36] & ~v[17])
input[16] = v[23]
v[25] = input[6]
v[26] = v[19]
input[176] = v[12]
v[27] = input[15]
input[116] = v[21]
v[28] = ((v[27] & ~v[18]) ^ v[21])
input[28] = v[16]
v[29] = (v[22] ^ v[25])
v[30] = (v[17] ^ input[126])
v[31] = (v[24] ^ input[6])
v[32] = input[7]
v[33] = (v[32] & ~v[2])
v[34] = input[23]
input[138] = (v[22] ^ v[25])
v[35] = (v[2] | v[32])
v[36] = (v[33] & ~v[7])
let part13 = ((v[2] | v[32]))
v[37] = (v[34] & ~part13)
let part14 = ((v[8] ^ v[33]))
v[38] = (part14 & v[7])
v[39] = input[175]
v[40] = (input[23] & ~v[33])
v[41] = (v[16] ^ input[12])
input[126] = v[30]
v[42] = v[41]
v[43] = (v[39] & ~v[41])
v[44] = input[12]
input[150] = v[31]
v[45] = (v[16] | v[44])
v[46] = (v[16] & ~v[44])
v[47] = input[5]
v[48] = v[44]
v[49] = v[42]
v[50] = (input[32] ^ v[28])
input[168] = v[13]
v[51] = ((v[47] & v[50]) ^ input[49])
v[52] = input[117]
v[53] = (v[19] ^ v[16])
v[54] = (input[29] & v[50])
input[202] = (v[19] ^ v[16])
v[55] = v[2]
v[56] = v[46]
v[57] = (v[43] ^ v[48])
v[58] = (v[50] & ~v[52])
v[59] = (v[3] & v[2])
v[60] = v[50]
v[61] = (v[55] & input[7])
v[62] = (v[54] ^ input[198])
v[63] = ((input[37] ^ input[122]) ^ (v[50] & ~input[92]))
v[64] = ((input[139] & v[50]) ^ input[30])
v[65] = input[137]
v[66] = ((v[58] ^ input[1]) ^ input[146])
v[67] = input[87]
v[68] = input[34]
input[32] = v[60]
v[69] = (v[67] ^ v[68])
v[70] = input[199]
v[71] = (v[70] & ~v[51])
v[72] = (v[63] ^ (v[70] & ~v[62]))
input[130] = v[28]
v[73] = (v[66] ^ (v[64] & v[70]))
v[74] = v[72]
v[75] = ((v[69] ^ (v[65] & v[60])) ^ v[71])
input[87] = v[75]
v[76] = input[20]
input[37] = v[72]
v[77] = (v[16] & v[76])
v[78] = input[99]
v[79] = input[78]
v[80] = v[73]
input[1] = v[73]
v[81] = v[77]
v[82] = (v[56] ^ v[78])
v[83] = (v[45] & input[175])
v[84] = (v[43] ^ v[45])
v[85] = (v[16] & input[12])
v[86] = (v[56] & input[175])
v[87] = (input[20] & ~v[57])
v[88] = (v[60] & input[111])
v[89] = (input[175] & ~v[45])
v[90] = (input[23] & ~v[59])
v[91] = ((v[60] & input[155]) ^ input[131])
v[92] = (v[61] & input[23])
v[93] = v[87]
v[94] = ((v[23] & v[79]) ^ input[77])
let part15 = (((v[33] ^ input[201]) ^ v[38]))
let part16 = ((input[118] ^ v[36]))
let part17 = (((((part16 & input[31]) ^ input[7]) ^ input[81]) ^ v[37]))
v[95] = (((((input[15] & ~part17) ^ input[54]) ^ v[9]) ^ v[40]) ^ (input[31] & ~part15))
v[96] = (v[95] & input[140])
v[97] = (v[95] & input[39])
v[98] = ((v[95] & ~input[80]) ^ input[115])
v[99] = input[19]
v[100] = input[61]
v[101] = input[145]
v[102] = (input[129] & v[95])
let part18 = (((v[60] & input[178]) ^ input[102]))
input[178] = ((((v[60] & input[160]) ^ input[15]) ^ input[108]) ^ (input[199] & ~part18))
v[103] = ((v[100] ^ v[101]) ^ v[102])
v[104] = (input[148] ^ (v[95] & ~v[99]))
v[105] = (input[61] & ~v[4])
v[106] = (v[95] & ~input[191])
v[107] = (v[40] ^ v[4])
v[108] = ((input[9] ^ input[192]) ^ (v[95] & input[170]))
v[109] = input[38]
v[110] = (v[96] ^ input[167])
input[54] = v[95]
v[111] = (v[110] | v[109])
v[112] = ((input[11] ^ input[120]) ^ (v[95] & ~input[135]))
v[113] = input[38]
v[114] = ((v[106] ^ input[185]) | v[113])
let part19 = ((v[97] ^ input[26]))
v[115] = (part19 & ~v[113])
v[116] = (v[104] ^ input[59])
v[117] = (v[103] ^ (v[98] & ~v[113]))
input[80] = v[117]
v[118] = (v[108] ^ v[111])
v[119] = input[149]
v[120] = (v[112] ^ v[114])
v[121] = input[166]
v[122] = v[120]
v[123] = (v[116] ^ v[115])
input[59] = (v[116] ^ v[115])
v[124] = (v[60] & v[119])
v[125] = (v[88] ^ input[62])
let part20 = ((v[105] ^ input[7]))
v[126] = (input[31] & ~part20)
v[127] = input[106]
v[128] = (v[91] | input[24])
v[129] = (v[81] ^ v[45])
v[130] = input[84]
let part21 = ((v[127] | v[121]))
v[131] = (part21 ^ input[174])
v[132] = v[118]
v[133] = input[186]
input[9] = v[118]
v[134] = v[122]
input[11] = v[122]
v[135] = (input[20] & ~v[82])
let part22 = ((v[131] | ~v[130]))
v[136] = (part22 & input[113])
v[137] = (v[83] ^ v[85])
v[138] = (input[175] & ~v[56])
v[139] = (v[93] ^ input[4])
v[140] = (((input[47] ^ input[200]) ^ v[133]) ^ v[136])
v[141] = (v[83] ^ v[56])
v[142] = input[175]
v[143] = (((input[47] ^ input[200]) ^ v[133]) ^ v[136])
let part23 = ((input[119] | v[140]))
v[144] = ((v[130] ^ input[143]) ^ part23)
v[145] = (input[20] & ~v[84])
let part24 = ((v[45] ^ v[142]))
v[146] = (input[20] & ~part24)
v[147] = input[61]
v[148] = ((v[127] ^ v[35]) ^ v[12])
v[149] = (v[90] | v[147])
v[150] = (v[16] & input[175])
let part25 = ((v[35] | v[147]))
v[151] = ((part25 ^ v[35]) ^ v[126])
v[152] = v[92]
let part26 = (((v[60] & ~input[62]) ^ input[62]))
v[153] = (((input[24] & ~part26) ^ (v[60] & ~input[62])) ^ input[111])
v[154] = (v[6] ^ v[152])
v[155] = input[20]
let part27 = (((~v[16] & input[175]) ^ v[45]))
v[156] = (part27 & v[155])
v[157] = (v[155] & ~v[150])
let part28 = (((v[142] & v[49]) ^ v[16]))
v[158] = ((v[150] ^ v[49]) ^ (input[20] & part28))
v[159] = (v[89] ^ v[49])
v[160] = (v[60] & ~input[155])
v[161] = (v[107] & v[10])
v[162] = (v[160] ^ input[66])
v[163] = (v[140] | input[93])
v[164] = (v[60] & input[62])
v[165] = v[124]
v[166] = (((~v[16] & input[12]) ^ v[86]) ^ v[156])
v[167] = (v[94] ^ v[165])
v[168] = input[24]
let part29 = (((v[60] & input[75]) ^ input[62]))
v[169] = (part29 & input[24])
input[8] ^= (input[58] ^ v[163])
v[170] = (v[168] & ~v[125])
v[171] = (v[129] ^ v[138])
v[172] = (v[137] ^ v[135])
v[173] = (v[60] & ~input[77])
v[174] = ~v[144]
v[175] = (v[159] ^ v[145])
v[176] = (v[89] ^ v[146])
v[177] = (input[0] & v[60])
v[178] = (v[157] ^ v[141])
v[179] = (v[88] ^ input[149])
v[180] = (v[148] ^ v[149])
v[181] = (input[15] & ~v[151])
v[182] = (v[161] ^ v[154])
v[183] = (input[24] & ~v[88])
v[184] = ((input[24] & ~v[177]) ^ v[179])
let part30 = (((v[60] & input[24]) ^ v[162]))
v[185] = (v[23] & ~part30)
v[186] = (v[164] ^ input[62])
v[187] = ((v[164] & ~input[24]) & v[23])
v[188] = (v[169] ^ v[179])
v[189] = (v[60] & ~input[75])
v[190] = (v[189] ^ input[77])
v[191] = (input[27] ^ v[190])
v[192] = (v[60] & input[77])
v[193] = input[24]
let part31 = (((v[173] ^ input[155]) | v[193]))
v[194] = (v[190] ^ part31)
let part32 = ((v[128] ^ v[179]))
v[195] = (v[23] & ~part32)
let part33 = ((v[160] ^ input[149]))
let part34 = (((v[160] ^ input[0]) ^ (part33 & input[24])))
v[196] = (part34 & v[23])
let part35 = ((input[149] ^ v[177]))
v[197] = ((v[162] ^ input[13]) ^ (part35 & input[24]))
v[198] = ((v[186] ^ ((input[24] & ~input[0]) & v[60])) ^ ((v[186] & ~input[24]) & v[23]))
v[199] = (v[188] ^ (v[153] & v[23]))
let part36 = ((v[173] ^ input[77]))
let part37 = ((((v[193] & ~part36) ^ v[189]) ^ input[75]))
v[200] = ((((input[155] ^ input[31]) ^ input[73]) ^ v[192]) ^ (part37 & v[23]))
v[201] = input[36]
let part38 = ((v[172] | v[144]))
v[202] = ((v[171] ^ input[63]) ^ part38)
v[203] = ~input[36]
let part39 = ((v[175] ^ (v[158] & v[144])))
v[204] = (((v[178] ^ input[35]) ^ (v[144] & ~v[166])) ^ (part39 & v[203]))
v[205] = ((v[180] ^ v[181]) ^ (input[31] & ~v[182]))
v[206] = input[41]
input[96] = v[205]
v[207] = ((v[184] ^ v[185]) ^ v[206])
v[208] = (v[197] ^ v[195])
v[209] = input[8]
v[210] = (v[198] | v[209])
v[211] = ((v[191] ^ v[183]) ^ v[196])
let part40 = ((v[167] ^ v[170]))
v[212] = (part40 & ~v[209])
v[213] = (~v[209] & v[199])
v[214] = ((v[194] ^ v[187]) | input[8])
input[84] = v[144]
v[215] = v[204]
let part41 = ((((v[139] & ~v[144]) ^ v[176]) | v[201]))
input[63] = (part41 ^ v[202])
v[216] = (v[207] ^ v[210])
v[217] = (v[211] ^ v[213])
v[218] = (v[200] ^ v[214])
v[219] = input[103]
v[220] = input[125]
v[221] = v[218]
input[41] = (v[207] ^ v[210])
v[222] = ((v[205] ^ v[220]) | v[219])
v[223] = ~v[219]
v[224] = (v[205] ^ v[220])
v[225] = (v[205] & ~input[125])
v[226] = input[125]
input[27] = v[217]
v[227] = v[225]
v[228] = (v[208] ^ v[212])
input[13] = (v[208] ^ v[212])
v[229] = v[221]
v[230] = ((v[205] & v[226]) & v[223])
input[31] = v[221]
v[231] = ~v[143]
v[232] = (v[205] & v[226])
v[233] = ((v[223] & v[226]) & ~v[205])
v[234] = (input[161] & ~v[143])
let part42 = ((v[222] ^ v[227]))
v[235] = (input[195] & ~part42)
v[236] = input[125]
v[237] = v[215]
v[238] = (input[153] ^ input[60])
input[35] = v[215]
v[239] = v[233]
v[240] = (v[238] ^ v[234])
v[241] = ((v[235] ^ (v[205] & v[223])) ^ v[236])
v[242] = (v[205] | v[236])
v[243] = ~input[195]
v[244] = ~input[6]
v[245] = input[195]
v[246] = (v[16] & v[244])
let part43 = ((v[230] ^ v[205]))
v[247] = (v[245] & ~part43)
v[248] = ((v[233] ^ v[205]) | v[245])
v[249] = (v[240] & v[244])
v[250] = v[240]
let part44 = ((v[26] ^ input[6]))
v[251] = ((part44 & v[240]) ^ v[29])
v[252] = (v[31] ^ v[249])
v[253] = (v[242] ^ input[103])
let part45 = ((v[227] ^ (v[205] & v[223])))
let part46 = ((((part45 & v[243]) ^ input[188]) | v[144]))
v[254] = ((part46 ^ v[248]) ^ v[253])
v[255] = (~v[16] & input[6])
v[256] = ((v[240] & ~v[26]) ^ input[3])
v[257] = (v[246] & input[36])
v[258] = input[52]
v[259] = (v[252] | v[258])
v[260] = (v[251] | v[258])
v[261] = (v[166] & ~v[144])
v[262] = (v[255] & input[36])
let part47 = ((v[241] | v[144]))
let part48 = (((v[247] ^ v[230]) ^ part47))
v[263] = ((v[254] ^ input[57]) ^ (part48 & input[175]))
let part49 = (((v[158] & ~v[144]) ^ v[175]))
v[264] = (part49 & v[203])
let part50 = (((((v[257] & v[250]) ^ v[30]) ^ v[259]) | input[44]))
v[265] = ((((v[256] ^ v[262]) ^ v[14]) ^ v[260]) ^ part50)
let part51 = ((input[50] | v[250]))
v[266] = ((input[157] ^ input[33]) ^ part51)
v[267] = (v[237] & ~v[263])
let part52 = ((v[205] ^ input[123]))
v[268] = (input[195] & ~part52)
v[269] = (v[232] ^ input[172])
v[270] = (((v[178] ^ input[196]) ^ v[261]) ^ v[264])
v[271] = v[144]
v[272] = (v[263] & ~v[237])
v[273] = (v[143] ^ v[242])
v[274] = (v[139] & v[144])
v[275] = (v[269] ^ input[124])
v[276] = (v[269] & input[195])
v[277] = ((input[195] & ~v[253]) ^ input[188])
v[278] = (v[237] & ~v[75])
v[279] = (v[216] & v[266])
v[280] = (input[195] & ~v[239])
input[57] = v[263]
v[281] = (v[176] ^ v[274])
v[282] = v[275]
v[283] = v[271]
v[284] = (v[172] & v[271])
v[285] = (v[282] & v[174])
v[286] = (v[277] | v[271])
v[287] = (v[281] | input[36])
v[288] = (v[14] ^ input[71])
input[33] = v[266]
input[196] = v[270]
input[3] = v[265]
input[60] = v[250]
v[289] = (v[288] & v[250])
v[290] = (v[255] & v[250])
input[117] = (v[216] & v[266])
v[291] = (v[15] ^ input[105])
v[292] = (input[6] ^ input[36])
v[293] = (v[262] ^ v[249])
v[294] = (v[250] & ~v[262])
v[295] = ((input[53] ^ v[171]) ^ v[284])
v[296] = ((v[242] & v[223]) ^ input[7])
v[297] = ((v[227] & v[223]) ^ input[125])
let part53 = ((input[103] | v[242]))
v[298] = (part53 ^ v[224])
v[299] = v[295]
v[300] = (((v[227] & v[223]) ^ (~v[205] & v[242])) ^ v[276])
v[301] = (v[205] & ~v[232])
v[302] = (v[205] | input[103])
v[303] = (v[296] ^ v[301])
let part54 = ((((v[224] & v[223]) ^ v[224]) ^ (v[227] & v[243])))
v[304] = (part54 & v[174])
let part55 = ((v[301] | input[103]))
v[305] = ((((v[224] & v[223]) & input[195]) ^ v[232]) ^ part55)
v[306] = input[195]
let part56 = (((v[268] ^ (v[224] & v[223])) ^ v[224]))
v[307] = (v[300] ^ (part56 & v[174]))
let part57 = ((v[232] | input[103]))
v[308] = ((v[273] ^ part57) ^ (v[297] & input[195]))
v[309] = ((v[263] ^ v[278]) | v[265])
let part58 = (((v[278] ^ v[237]) | v[265]))
v[310] = ((part58 ^ input[103]) ^ v[267])
let part59 = (((((v[306] & v[205]) & v[223]) ^ v[302]) | v[283]))
v[311] = (v[305] ^ part59)
v[312] = input[195]
let part60 = ((v[302] | v[306]))
let part61 = ((part60 ^ (v[205] & v[223])))
v[313] = (part61 & v[174])
v[314] = ((v[298] & ~v[312]) ^ v[304])
v[315] = (v[263] & ~v[75])
v[316] = ((input[21] ^ v[224]) ^ v[280])
v[317] = (v[263] & ~v[272])
let part62 = ((v[237] | v[75]))
let part63 = ((v[272] ^ part62))
let part64 = (((v[265] & ~part63) ^ (v[267] & v[75])))
v[318] = (part64 & v[134])
v[319] = ((v[303] ^ (v[312] & ~v[298])) ^ v[286])
v[320] = ((v[263] & v[237]) & ~v[75])
let part65 = ((v[263] | v[237]))
let part66 = (((v[263] | v[237]) | v[75]))
let part67 = (((part66 ^ part65) ^ (v[267] & ~v[265])))
v[321] = ((((~v[265] & v[267]) & v[75]) ^ (part67 & v[134])) ^ v[75])
let part68 = ((v[263] | v[237]))
let part69 = ((v[263] | v[237]))
let part70 = ((v[267] | v[75]))
let part71 = (((part70 ^ part68) | v[265]))
v[322] = (((((v[265] & v[134]) & ~v[317]) ^ part71) ^ v[320]) ^ part69)
let part72 = (((v[263] ^ v[237]) | v[75]))
let part73 = ((part72 ^ v[267]))
v[323] = ((((v[263] ^ v[237]) ^ v[75]) ^ input[38]) ^ (part73 & ~v[265]))
let part74 = ((v[263] | v[237]))
let part75 = ((v[267] | v[75]))
let part76 = ((((v[315] & v[265]) ^ part75) ^ part74))
v[324] = (v[134] & ~part76)
let part77 = ((v[237] | v[75]))
let part78 = ((part77 ^ v[237]))
v[325] = ((((v[263] ^ v[237]) ^ v[75]) ^ (v[265] & ~part78)) ^ input[24])
let part79 = ((v[320] ^ (v[263] & v[237])))
let part80 = ((v[263] ^ v[237]))
let part81 = (((v[267] & v[75]) ^ (v[265] & ~part80)))
v[326] = ((v[134] & ~part81) ^ (part79 & ~v[265]))
let part82 = ((v[267] | v[75]))
let part83 = (((v[263] | v[237]) | v[265]))
let part84 = ((part83 ^ v[315]))
v[327] = ((v[134] & ~part84) ^ part82)
v[328] = ((v[216] & v[266]) & v[263])
let part85 = ((v[263] ^ v[237]))
let part86 = ((part85 & v[265]))
let part87 = ((v[317] | v[75]))
v[329] = ((((input[44] ^ v[237]) ^ v[309]) ^ part87) ^ (v[134] & ~part86))
let part88 = ((v[216] & v[266]))
v[330] = (~part88 & v[216])
v[331] = (v[310] ^ v[320])
let part89 = ((~v[237] ^ ~v[75]))
let part90 = ((v[263] | v[237]))
let part91 = (((v[272] & ~v[75]) ^ part90))
let part92 = (((part91 & ~v[265]) ^ (part89 & v[263])))
v[332] = (v[134] & ~part92)
v[333] = (v[330] ^ (~v[216] & v[263]))
v[334] = (input[175] & ~v[311])
v[335] = (input[175] & ~v[314])
v[336] = (input[175] & ~v[307])
input[192] = ((v[263] & v[216]) ^ v[266])
v[337] = ((v[330] ^ (~v[216] & v[263])) | v[270])
v[338] = (v[331] ^ v[332])
v[339] = (v[263] & ~v[330])
v[340] = (v[337] ^ input[192])
v[341] = ((v[316] ^ v[313]) ^ v[334])
v[342] = ((v[308] ^ v[285]) ^ v[335])
v[343] = (v[319] ^ v[336])
v[344] = (v[299] ^ v[287])
input[38] = ((v[323] ^ v[324]) ^ (v[217] & ~v[321]))
input[191] = (v[329] ^ (v[322] & v[217]))
v[345] = (v[338] ^ (v[327] & v[217]))
v[346] = ((v[325] ^ v[318]) ^ (v[217] & ~v[326]))
input[103] = v[345]
input[24] = v[346]
v[347] = (v[216] ^ v[266])
v[348] = (v[216] | v[266])
input[53] = (v[299] ^ v[287])
v[349] = input[36]
let part93 = ((((v[263] & ~v[270]) ^ v[328]) | v[265]))
input[26] = ((((v[216] & ~v[266]) & ~v[270]) ^ part93) ^ v[339])
let part94 = ((v[216] | v[266]))
v[350] = (part94 & ~v[216])
v[351] = input[23]
v[352] = (v[289] ^ input[189])
let part95 = ((v[216] & v[266]))
let part96 = ((~part95 ^ v[263]))
let part97 = (((part96 & v[216]) | v[270]))
let part98 = (((v[263] ^ v[216]) ^ part97))
input[167] = ((part98 & v[265]) ^ v[340])
v[353] = ((v[17] ^ v[349]) ^ v[351])
v[354] = input[52]
input[7] = v[343]
v[355] = ((v[216] & v[266]) ^ v[263])
input[137] = (v[328] ^ v[266])
input[115] = v[342]
input[21] = v[341]
v[356] = ~v[354]
v[357] = input[55]
v[358] = input[184]
v[359] = (v[250] | input[151])
input[161] = (v[216] ^ v[266])
input[155] = (v[216] | v[266])
let part99 = ((v[216] & v[266]))
v[360] = (~part99 & v[263])
v[361] = ((v[216] & ~v[266]) & v[263])
v[362] = ((v[358] ^ v[357]) ^ v[359])
v[363] = ((v[263] & v[216]) ^ (v[216] & v[266]))
let part100 = ((v[216] ^ v[266]))
v[364] = ((v[350] ^ (part100 & v[263])) | v[270])
let part101 = ((v[216] ^ v[266]))
v[365] = ((v[355] & ~v[270]) ^ (v[263] & ~part101))
v[366] = ((((v[266] & ~v[263]) & ~v[270]) ^ v[328]) ^ v[266])
v[367] = (v[229] & v[362])
v[368] = (v[364] ^ v[266])
v[369] = (v[350] ^ v[270])
v[370] = (v[229] | v[362])
let part102 = ((((v[290] & v[354]) ^ v[291]) | input[44]))
v[371] = (((v[353] ^ (v[352] & ~v[354])) ^ v[294]) ^ part102)
v[372] = ((v[337] ^ v[348]) | v[265])
let part103 = ((v[368] | v[265]))
let part104 = ((v[363] | v[270]))
v[373] = (((v[361] ^ v[348]) ^ part104) ^ part103)
let part105 = ((((v[347] & v[263]) ^ v[348]) | v[270]))
let part106 = (((v[360] ^ v[347]) ^ part105))
v[374] = (part106 & ~v[265])
v[375] = (v[366] | v[265])
v[376] = (v[333] & ~v[270])
let part107 = ((v[365] ^ v[279]))
v[377] = (part107 & ~v[265])
v[378] = (v[369] ^ v[339])
v[379] = ~v[229]
let part108 = ((v[355] | v[270]))
v[380] = (((v[263] ^ v[348]) ^ v[265]) ^ part108)
v[381] = (v[342] & ~v[362])
v[382] = (~v[229] & v[342])
v[383] = ((v[229] & v[362]) & v[342])
v[384] = (v[229] ^ v[362])
let part109 = ((v[229] & v[362]))
let part110 = ((v[229] & ~part109))
v[385] = (v[342] & ~part110)
v[386] = (v[342] & v[229])
let part111 = ((v[229] | v[362]))
v[387] = (part111 & v[342])
v[388] = (input[162] ^ input[51])
input[5] = v[373]
input[148] = v[380]
v[389] = (~v[250] & input[158])
input[153] = (v[374] ^ v[340])
input[88] = (v[376] ^ v[372])
input[23] = v[371]
input[66] = (v[375] ^ v[378])
input[108] = (v[377] ^ v[328])
input[94] = (v[371] | v[117])
let part112 = ((v[229] | v[117]))
input[34] = ((part112 ^ v[229]) | v[371])
input[71] = (v[371] & ~v[117])
input[136] = ((v[229] ^ v[362]) ^ v[381])
input[185] = (v[382] ^ v[362])
let part113 = ((v[229] ^ v[362]))
input[132] = (v[342] & part113)
input[151] = (v[381] ^ v[362])
input[145] = v[383]
input[184] = v[381]
input[105] = (v[229] ^ v[362])
input[73] = (v[383] ^ v[362])
input[107] = ((v[229] & v[362]) ^ v[383])
input[141] = ((v[383] ^ v[229]) ^ v[362])
let part114 = ((v[229] & v[362]))
let part115 = ((v[229] & ~part114))
input[102] = (((v[342] & ~part115) ^ v[229]) ^ v[362])
input[29] = ((v[229] & v[362]) ^ (v[342] & v[229]))
let part116 = ((v[229] & v[362]))
input[75] = ((v[229] & ~part116) ^ v[382])
input[55] = v[362]
v[390] = (v[388] ^ v[389])
let part117 = ((v[229] | v[362]))
input[140] = ((v[342] & ~part117) ^ v[229])
input[146] = (v[387] ^ (v[229] & v[362]))
v[391] = input[52]
let part118 = ((v[229] | v[362]))
input[61] = (v[387] ^ part118)
v[392] = (((v[292] ^ v[16]) ^ v[250]) ^ input[197])
v[393] = input[70]
let part119 = ((v[257] ^ v[246]))
v[394] = ((part119 & v[250]) ^ input[36])
input[51] = (v[388] ^ v[389])
v[395] = (~v[237] & v[123])
let part120 = (((((v[250] & ~v[16]) ^ v[53]) ^ (v[293] & v[356])) | input[44]))
let part121 = ((v[391] | v[394]))
v[396] = ((v[392] ^ part121) ^ part120)
v[397] = ((v[393] ^ input[154]) ^ (~v[250] & input[142]))
let part122 = ((v[388] ^ v[389]))
v[398] = (~v[123] & part122)
v[399] = (v[343] & ~v[117])
v[400] = (~v[237] & v[390])
v[401] = (v[237] & ~v[123])
v[402] = (~v[395] & v[390])
let part123 = ((v[123] ^ v[237]))
v[403] = (part123 & v[390])
let part124 = ((v[123] ^ v[237]))
v[404] = (v[390] & ~part124)
v[405] = (v[228] ^ v[396])
v[406] = (~v[343] & v[117])
v[407] = (v[403] & v[396])
v[408] = (~v[362] & v[386])
v[409] = (v[250] & v[246])
v[410] = ((~v[395] & v[123]) ^ v[400])
v[411] = (v[395] ^ (v[237] & v[390]))
let part125 = ((v[403] ^ v[395]))
v[412] = (part125 & v[396])
v[413] = ((v[403] ^ v[401]) | v[396])
v[414] = ((v[390] & ~v[401]) ^ (v[403] & v[396]))
v[415] = (v[17] & ~input[36])
v[416] = (v[386] ^ v[362])
v[417] = (v[408] ^ v[367])
input[123] = (v[385] ^ (v[370] & v[379]))
input[152] = ((v[370] & v[379]) ^ v[342])
input[118] = ((v[382] & v[362]) ^ v[384])
v[418] = (v[384] ^ v[408])
v[419] = (v[408] ^ v[362])
input[89] = v[417]
input[124] = ((v[370] & v[379]) ^ v[382])
v[420] = (v[228] | v[396])
v[421] = (v[396] & ~v[397])
v[422] = ((v[228] ^ v[396]) | v[397])
input[50] = v[419]
input[111] = (v[370] ^ v[342])
input[170] = v[418]
input[149] = v[416]
let part126 = ((v[228] & v[396]))
v[423] = (v[396] & ~part126)
let part127 = ((v[237] | v[123]))
input[90] = ((part127 & v[396]) ^ v[410])
let part128 = ((v[228] | v[396]))
v[424] = (part128 & ~v[396])
let part129 = ((~v[237] & v[123]))
let part130 = ((~part129 & v[123]))
let part131 = (((v[390] & ~part130) ^ (v[237] & ~v[123])))
input[133] = (v[411] ^ (part131 & v[396]))
input[197] = v[396]
let part132 = ((v[402] ^ v[237]))
input[30] = ((v[396] & ~part132) ^ v[402])
v[425] = (v[396] & ~v[228])
let part133 = ((v[237] ^ (~v[123] & v[390])))
input[188] = ((v[400] ^ (part133 & v[396])) ^ v[123])
let part134 = ((v[237] | v[123]))
let part135 = ((v[400] ^ v[237]))
input[198] = ((v[396] & ~part135) ^ part134)
let part136 = ((v[237] | v[123]))
let part137 = ((~v[237] & v[123]))
input[183] = ((((~part137 & v[396]) ^ (part136 & v[390])) ^ v[123]) ^ v[237])
let part138 = ((v[237] & v[390]))
input[92] = (((v[400] ^ v[123]) ^ v[237]) ^ (v[396] & ~part138))
let part139 = ((v[404] ^ v[123]))
input[158] = (v[404] ^ (v[396] & ~part139))
let part140 = ((v[404] ^ v[401]))
let part141 = ((v[237] | v[123]))
input[143] = ((part141 ^ v[398]) ^ (v[396] & ~part140))
let part142 = ((v[237] | v[123]))
input[139] = (v[412] ^ part142)
let part143 = ((v[237] | v[123]))
input[15] = (v[407] ^ part143)
input[119] = (v[410] ^ v[413])
input[78] = (v[414] ^ v[401])
let part144 = ((v[404] ^ (v[237] & v[123])))
input[201] = (((v[123] ^ v[237]) ^ (v[390] & v[123])) ^ (part144 & v[396]))
let part145 = ((v[402] | v[396]))
input[135] = (part145 ^ v[402])
v[426] = (v[415] ^ v[409])
let part146 = (((v[399] & v[344]) ^ (v[343] & v[117])))
input[4] = (part146 & v[397])
v[427] = (v[228] & ~v[396])
let part147 = ((v[406] | ~v[117]))
input[180] = (((v[343] & ~v[117]) & v[397]) ^ (part147 & v[344]))
v[428] = (v[424] ^ v[421])
v[429] = (v[228] | v[397])
input[162] = v[424]
let part148 = ((v[422] ^ (v[228] & v[396])))
let part149 = ((v[423] | v[397]))
v[430] = ((part149 ^ v[228]) ^ (v[341] & ~part148))
let part150 = ((v[396] | v[397]))
v[431] = ((v[228] ^ v[396]) ^ part150)
input[154] = v[397]
input[100] = v[427]
v[432] = (v[424] ^ (v[228] & ~v[397]))
v[433] = ((v[16] & ~v[250]) ^ v[257])
v[434] = ((v[257] ^ v[17]) | v[250])
v[435] = ((v[426] & v[356]) ^ input[189])
v[436] = ((v[292] ^ v[16]) ^ input[17])
let part151 = ((v[422] ^ v[420]))
v[437] = (((part151 & v[341]) ^ (v[425] & ~v[397])) ^ v[423])
v[438] = input[52]
input[164] = ((v[420] & ~v[397]) ^ v[405])
let part152 = ((v[396] | v[397]))
let part153 = ((v[423] ^ part152))
let part154 = (((v[341] & part153) ^ v[431]))
v[439] = (((v[423] ^ (v[422] & v[341])) ^ (v[420] & ~v[397])) ^ (part154 & v[74]))
let part155 = (((v[341] & ~v[428]) ^ v[425]))
let part156 = ((v[429] ^ v[427]))
v[440] = (((v[341] & ~part156) ^ input[164]) ^ (part155 & v[74]))
v[441] = (((v[420] ^ v[397]) ^ (v[341] & ~v[432])) ^ (v[74] & ~v[437]))
let part157 = ((v[420] | v[397]))
let part158 = ((v[421] ^ v[396]))
v[442] = ((((v[341] & ~part158) ^ v[405]) ^ part157) ^ (v[430] & v[74]))
v[443] = ((v[442] ^ input[62]) ^ (v[439] & ~v[123]))
let part159 = ((v[20] ^ v[16]))
let part160 = ((v[435] ^ (v[250] & ~part159)))
let part161 = ((v[433] | v[438]))
v[444] = (((part161 ^ v[434]) ^ v[436]) ^ (part160 & ~input[44]))
let part162 = ((v[343] | v[117]))
v[445] = (v[344] & ~part162)
v[446] = ((v[343] ^ v[117]) ^ (v[343] & v[344]))
v[447] = ((v[441] ^ input[125]) ^ (v[440] & ~v[123]))
v[448] = ((v[441] ^ input[199]) ^ (v[123] & ~v[440]))
v[449] = (v[123] & ~v[439])
v[450] = (v[442] ^ input[52])
input[17] = v[444]
input[39] = (v[346] & ~v[443])
input[52] = (v[444] | v[80])
let part163 = ((v[406] | ~v[117]))
input[142] = ((v[117] ^ (~v[397] & v[343])) ^ (part163 & v[344]))
let part164 = ((v[343] | v[117]))
let part165 = ((((~v[343] & v[344]) ^ part164) | v[397]))
input[113] = ((part165 ^ (~v[343] & v[344])) ^ v[343])
let part166 = ((v[343] & v[344]))
input[182] = (v[397] & ~part166)
input[174] = ((~v[397] & v[445]) ^ v[344])
let part167 = ((v[445] | v[397]))
input[70] = (((v[344] ^ v[343]) ^ v[117]) ^ part167)
let part168 = (((~v[343] & v[344]) ^ v[399]))
input[160] = ((v[406] ^ (v[343] & v[344])) ^ (part168 & ~v[397]))
let part169 = ((((v[399] & v[344]) ^ v[343]) | v[397]))
input[99] = (part169 ^ v[446])
let part170 = ((v[343] | v[397]))
input[19] = ((part170 ^ v[343]) ^ (v[406] & v[344]))
let part171 = ((((v[406] & v[344]) ^ v[117]) | v[397]))
input[186] = (v[446] ^ part171)
let part172 = ((~v[343] ^ v[344]))
let part173 = (((part172 & v[117]) | v[397]))
let part174 = ((v[343] | v[117]))
input[120] = ((part174 ^ v[344]) ^ part173)
input[65] = (v[447] & v[345])
input[58] = v[447]
input[199] = v[448]
input[122] = (v[450] ^ v[449])
input[74] = (~v[346] & v[443])
let part175 = ((v[344] ^ v[117]))
input[166] = ((~v[343] & part175) & ~v[397])
v[451] = input[39]
input[62] = v[443]
input[131] = (~v[346] & v[448])
let part176 = ((v[343] | v[117]))
input[93] = ((v[117] & v[397]) ^ (v[344] & ~part176))
v[452] = (v[346] ^ v[443])
v[453] = (v[346] & v[443])
let part177 = ((v[343] ^ v[117]))
let part178 = (((((v[344] & ~part177) ^ v[343]) ^ v[117]) | v[397]))
input[172] = ((part178 ^ (~v[343] & v[344])) ^ v[343])
v[454] = (v[443] | v[346])
input[82] = v[454]
input[200] = v[454]
input[44] = (~v[444] & v[132])
v[455] = input[159]
input[106] = v[453]
input[69] = (v[346] & ~v[451])
input[77] = v[452]
input[91] = (v[444] ^ v[132])
v[456] = input[10]
input[112] = (v[444] | v[132])
let part179 = ((v[444] | v[132]))
input[72] = (part179 & ~v[444])
v[457] = input[79]
v[458] = input[193]
let part180 = ((v[444] & v[132]))
input[129] = (v[444] & ~part180)
v[459] = ((v[456] ^ v[458]) ^ (v[455] & v[231]))
v[460] = input[64]
v[461] = ((v[459] & ~v[457]) ^ v[457])
v[462] = input[2]
v[463] = ((v[459] & input[195]) ^ input[181])
v[464] = (v[459] & v[457])
v[465] = (v[459] & ~input[194])
v[466] = ((v[459] & v[243]) ^ input[18])
input[10] = v[459]
v[467] = ((v[459] & v[243]) ^ v[457])
v[468] = (v[459] ^ v[457])
v[469] = (v[464] ^ v[460])
v[470] = input[56]
input[157] = v[463]
input[68] = (v[444] & v[132])
input[194] = v[465]
input[47] = v[468]
input[193] = v[464]
input[159] = v[469]
input[109] = (v[461] & ~v[470])
let part181 = ((v[466] | v[462]))
input[81] = (v[467] ^ part181)
input[79] = (v[463] & v[462])
return input;
}
} | gpl-3.0 | 7346f7051ab05e055e2fe5c087ff5ba2 | 39.890644 | 102 | 0.395965 | 2.4308 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | v2.x/Showcase/SwiftUtil/SCIGenericWrapper.swift | 2 | 8447 | //******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// SCIGenericWrapper.swift is part of SCICHART®, High Performance Scientific Charts
// For full terms and conditions of the license, see http://www.scichart.com/scichart-eula/
//
// This source code is protected by international copyright law. Unauthorized
// reproduction, reverse-engineering, or distribution of all or any portion of
// this source code is strictly prohibited.
//
// This source code contains confidential and proprietary trade secrets of
// SciChart Ltd., and should at no time be copied, transferred, sold,
// distributed or made available without express written permission.
//******************************************************************************
/** \addtogroup SCIGenericType
* @{
*/
import Foundation
import SciChart
/**
@file SCIGenericType
*/
#if swift(>=3.0)
/**
* @brief It is wrapper function that constructs SCIGenericType
* @code
* let generic1 = SCIGeneric(0)
* let variable = 1
* let generic2 = SCIGeneric( variable )
* let generic3 = SCIGeneric( NSDate() )
* let doubleVariable = SCIGenericDouble(generic1)
* let intVariable = SCIGenericInt(generic2)
* let floatVariable = SCIGenericFloat(generic2)
* let date = SCIGenericDate(generic3)
* let timeIntervalSince1970 = SCIGenericDouble(generic3)
* @endcode
* @see SCIGenericType
*/
public protocol SCIGenericInfo {
func getInfoType() -> SCIDataType
}
extension Int16 : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.int16
}
}
extension Int32 : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.int32
}
}
extension Int : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.int32
}
}
extension Int64 : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.int64
}
}
extension UInt : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.int32
}
}
extension UInt8 : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.byte
}
}
extension UInt16 : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.int16
}
}
extension UInt64 : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.int64
}
}
extension UInt32 : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.int32
}
}
extension Double : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.double
}
}
extension Float : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.float
}
}
extension Character : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.byte
}
}
extension CChar : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.byte
}
}
extension NSArray : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.array
}
}
extension NSDate : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.dateTime
}
}
extension Date : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.swiftDateTime
}
}
extension UnsafeMutablePointer : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
if let pointerType = pointee as? SCIGenericInfo {
switch pointerType.getInfoType() {
case .int16:
return SCIDataType.int16Ptr
case .int32:
return SCIDataType.int32Ptr
case .int64:
return SCIDataType.int64Ptr
case .byte:
return SCIDataType.charPtr
case .float:
return SCIDataType.floatPtr
case .double:
return SCIDataType.doublePtr
default:
return SCIDataType.voidPtr
}
}
return SCIDataType.voidPtr
}
}
extension UnsafeMutableRawPointer : SCIGenericInfo {
public func getInfoType() -> SCIDataType {
return SCIDataType.voidPtr
}
}
public func SCIGeneric<T: SCIGenericInfo>(_ x: T) -> SCIGenericType {
var data = x
var typeData = data.getInfoType()
if typeData == .swiftDateTime {
if let date = x as? Date {
let timeInterval = date.timeIntervalSince1970
var nsDate = NSDate.init(timeIntervalSince1970: timeInterval)
typeData = .dateTime
return SCI_constructGenericTypeWithInfo(&nsDate, typeData)
}
}
return SCI_constructGenericTypeWithInfo(&data, typeData)
}
public func SCIGeneric<T:SCIGenericInfo>(_ x: [T]) -> SCIGenericType {
let data = x
let unsafePointer = UnsafeMutablePointer(mutating: data)
return SCIGeneric(unsafePointer)
}
#else
/**
@brief It is wrapper function that constructs SCIGenericType
@code
let generic1 = SCIGeneric(0)
let variable = 1
let generic2 = SCIGeneric( variable )
let generic3 = SCIGeneric( NSDate() )
let doubleVariable = SCIGenericDouble(generic1)
let intVariable = SCIGenericInt(generic2)
let floatVariable = SCIGenericFloat(generic2)
let date = SCIGenericDate(generic3)
let timeIntervalSince1970 = SCIGenericDouble(generic3)
@endcode
@see SCIGenericType
*/
public func SCIGeneric<T>(x: T) -> SCIGenericType {
var data = x
if x is Double {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Double)
} else if x is Float {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Float)
} else if x is Int32 {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int32)
} else if x is Int16 {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int16)
} else if x is Int64 {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int64)
} else if x is Int8 {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Byte)
} else if x is NSDate {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.DateTime)
} else if x is NSArray {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Array)
} else if x is Int {
// TODO: implement correct unsigned type handling
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int32)
} else if x is UInt32 {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int32)
} else if x is UInt16 {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int16)
} else if x is UInt64 {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int64)
} else if x is UInt8 {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Byte)
} else if x is UInt {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.Int32)
} else {
return SCI_constructGenericTypeWithInfo(&data, SCIDataType.None)
}
}
public func SCIGeneric<T:SCIGenericInfo>(_ x: [T]) -> SCIGenericType {
let data = x
let unsafePointer = UnsafeMutablePointer(mutating: data)
return SCIGeneric(unsafePointer)
}
#endif
/** @} */
| mit | 0e98dc567f9295d8bc7215389c1f392c | 31.232824 | 91 | 0.595974 | 4.970571 | false | false | false | false |
edmw/Volumio_ios | Volumio/AppDelegate.swift | 1 | 4080 | //
// AppDelegate.swift
// Volumio
//
// Created by Federico Sintucci on 20/09/16.
// Copyright © 2016 Federico Sintucci. All rights reserved.
//
import UIKit
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
) -> Bool {
Log.setLog(level: BundleInfo[.logLevel])
Fabric.with([Crashlytics.self])
handleArguments()
UIBarButtonItem.appearance()
.setTitleTextAttributes(
[NSForegroundColorAttributeName: UIColor.clear], for: UIControlState.normal
)
UIBarButtonItem.appearance()
.setTitleTextAttributes(
[NSForegroundColorAttributeName: UIColor.clear], for: UIControlState.highlighted
)
UINavigationBar.appearance().tintColor = UIColor.black
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
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.
VolumioIOManager.shared.closeConnection()
}
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.
VolumioIOManager.shared.connectCurrent()
}
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:.
}
}
extension InfoKeys {
static let logLevel = InfoKey<String?>("AppLogLevel")
}
extension DefaultsKeys {
static let selectedPlayer = DefaultsKey<Player?>("selectedPlayer")
}
// MARK: - App Launch Arguments
extension AppDelegate {
func handleArguments() {
if ProcessInfo.shouldResetUserDefaults {
Defaults.removeAll()
}
if ProcessInfo.shouldDefaultUserDefaults {
Defaults.removeAll()
let defaultPlayer = Player(
name: "Volumio",
host: "volumio.local.",
port: 3000
)
Defaults[.selectedPlayer] = defaultPlayer
}
}
}
extension ProcessInfo {
/**
Used to reset user defaults on startup.
let app = XCUIApplication()
app.launchArguments.append("reset-user-defaults")
*/
class var shouldResetUserDefaults: Bool {
return processInfo.arguments.contains("reset-user-defaults")
}
/**
Used to set user defaults to default values on startup.
let app = XCUIApplication()
app.launchArguments.append("default-user-defaults")
*/
class var shouldDefaultUserDefaults: Bool {
return processInfo.arguments.contains("default-user-defaults")
}
}
| gpl-3.0 | 6d01a407020285bbaa4e6f9c323e4407 | 33.567797 | 285 | 0.695268 | 5.367105 | false | false | false | false |
soffes/clock-saver | ClockDemo/Classes/AppDelegate.swift | 1 | 1762 | import AppKit
import ScreenSaver
@NSApplicationMain final class AppDelegate: NSObject {
// MARK: - Properties
@IBOutlet var window: NSWindow!
let view: ScreenSaverView! = {
let view = MainView(frame: .zero, isPreview: false)
view?.autoresizingMask = [.width, .height]
return view
}()
// MARK: - Initializers
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Actions
@IBAction func showPreferences(_ sender: Any?) {
guard let sheet = view.configureSheet else { return }
window.beginSheet(sheet) { [weak sheet] _ in
sheet?.close()
}
}
// MARK: - Private
@objc private func preferencesDidChange(_ notification: NSNotification?) {
let preferences = (notification?.object as? Preferences) ?? Preferences()
window.title = "Clock.saver — \(preferences.modelName)\(preferences.styleName)"
}
}
extension AppDelegate: NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
guard let contentView = window.contentView else {
fatalError("Missing window content view")
}
// Add the clock view to the window
view.frame = contentView.bounds
contentView.addSubview(view)
// Start animating the clock
view.startAnimation()
Timer.scheduledTimer(timeInterval: view.animationTimeInterval, target: view, selector: #selector(ScreenSaverView.animateOneFrame), userInfo: nil, repeats: true)
NotificationCenter.default.addObserver(self, selector: #selector(preferencesDidChange), name: .PreferencesDidChange, object: nil)
preferencesDidChange(nil)
}
}
extension AppDelegate: NSWindowDelegate {
func windowWillClose(_ notification: Notification) {
// Quit the app if the main window is closed
NSApplication.shared.terminate(window)
}
}
| mit | 01088fab2063621c0f6f36dcd1ce5be0 | 24.507246 | 162 | 0.738636 | 4.131455 | false | false | false | false |
tndatacommons/Compass-iOS | Compass/src/Controller/BadgeController.swift | 1 | 1404 | //
// BadgeController.swift
// Compass
//
// Created by Ismael Alonso on 6/30/16.
// Copyright © 2016 Tennessee Data Commons. All rights reserved.
//
import UIKit
import Nuke
class BadgeController: UIViewController{
@IBOutlet weak var imageContainer: UIView!
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var name: UILabel!
//Apparently, description is a superclass variable
@IBOutlet weak var badgeDescription: UILabel!
var badge: Badge!;
override func viewDidLoad(){
Nuke.taskWith(NSURL(string: badge.getImageUrl())!){
self.image.image = $0.image;
}.resume();
name.text = badge.getName();
badgeDescription.text = badge.getDescription();
DefaultsManager.removeNewAward(badge)
if let tabController = tabBarController{
if let items = tabController.tabBar.items{
let newAwardCount = DefaultsManager.getNewAwardCount()
if newAwardCount == 0{
items[2].badgeValue = nil
}
else{
items[2].badgeValue = "\(newAwardCount)"
}
}
}
}
override func viewDidAppear(animated: Bool){
imageContainer.layer.cornerRadius = imageContainer.frame.size.width/2;
imageContainer.hidden = false;
}
}
| mit | c5919039b7355a045ae33ea696771dca | 27.06 | 78 | 0.593728 | 4.854671 | false | false | false | false |
zpz1237/NirSeller | NirSeller/OrderViewController.swift | 1 | 5871 | //
// OrderViewController.swift
// NirSeller
//
// Created by Nirvana on 9/9/15.
// Copyright © 2015 NSNirvana. All rights reserved.
//
import UIKit
class OrderViewController: UIViewController {
var pageMenu: CAPSPageMenu?
var newOrderViewController: OrderContentViewController!
var oldOrderViewController: OrderContentViewController!
override func viewDidLoad() {
super.viewDidLoad()
//self.navigationController?.navigationBar.translucent = false
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
var controllerArray: [UIViewController] = []
let testDataA = FoodModel(symbolViewColor: UIColor.lightGrayColor(), foodName: "经典奥尔良鸡排米饭小套餐", foodNumber: "1", foodPrice: "¥12")
let testDataB = FoodModel(symbolViewColor: UIColor.lightGrayColor(), foodName: "琵琶鸡腿饭", foodNumber: "1", foodPrice: "¥15")
let testDataC = InfoModel(orderNumber: "2015090917432800", orderTime: "2015-09-09 17:43:28", phoneNumber: "18463103027", delayTime: "30分钟后")
let testDataD = FoodModel(symbolViewColor: UIColor.lightGrayColor(), foodName: "宝岛招牌饭", foodNumber: "1", foodPrice: "¥13")
let testDataE = InfoModel(orderNumber: "2015091011234900", orderTime: "2015-09-10 11:23:49", phoneNumber: "18953831358", delayTime: "45分钟后")
newOrderViewController = storyBoard.instantiateViewControllerWithIdentifier("OrderContentViewID") as! OrderContentViewController
oldOrderViewController = storyBoard.instantiateViewControllerWithIdentifier("OrderContentViewID") as! OrderContentViewController
NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToSecondPageFunction", name: "switchToSecondPage", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToFirstPageFunction", name: "switchToFirstPage", object: nil)
newOrderViewController.orderDataArray.append(testDataA)
newOrderViewController.orderDataArray.append(testDataB)
newOrderViewController.orderDataArray.append(testDataC)
oldOrderViewController.orderDataArray.append(testDataD)
oldOrderViewController.orderDataArray.append(testDataE)
newOrderViewController.title = "新订单"
oldOrderViewController.title = "已处理"
controllerArray.append(newOrderViewController)
controllerArray.append(oldOrderViewController)
//pageMenu的UI配置参数
let parameters: [CAPSPageMenuOption] = [
.MenuItemSeparatorWidth(4.3),
.ScrollMenuBackgroundColor(UIColor.whiteColor()),
.ViewBackgroundColor(UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0)),
.BottomMenuHairlineColor(UIColor(red: 20.0/255.0, green: 20.0/255.0, blue: 20.0/255.0, alpha: 0.1)),
.SelectionIndicatorColor(UIColor(red: 18.0/255.0, green: 150.0/255.0, blue: 225.0/255.0, alpha: 1.0)),
.MenuMargin(20.0),
.MenuHeight(40.0),
.SelectedMenuItemLabelColor(UIColor(red: 18.0/255.0, green: 150.0/255.0, blue: 225.0/255.0, alpha: 1.0)),
.UnselectedMenuItemLabelColor(UIColor(red: 40.0/255.0, green: 40.0/255.0, blue: 40.0/255.0, alpha: 1.0)),
.MenuItemFont(UIFont(name: "HelveticaNeue-Medium", size: 14.0)!),
.UseMenuLikeSegmentedControl(true),
.MenuItemSeparatorRoundEdges(true),
.SelectionIndicatorHeight(2.0),
.MenuItemSeparatorPercentageHeight(0.1)
]
pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, 64.0, self.view.frame.width, self.view.frame.height - 64), pageMenuOptions: parameters)
self.view.addSubview(pageMenu!.view)
}
func switchToSecondPageFunction() {
self.navigationItem.rightBarButtonItem?.title = ""
}
func switchToFirstPageFunction() {
self.navigationItem.rightBarButtonItem?.title = "下一单"
}
@IBAction func didClickedNextButton(sender: UIBarButtonItem) {
let num = 3
for i in 1...num {
oldOrderViewController.orderDataArray.insert(newOrderViewController.orderDataArray[num-i], atIndex: 0)
}
for _ in 1...num {
newOrderViewController.orderDataArray.removeFirst()
}
// print(newOrderViewController.orderDataArray)
newOrderViewController.orderTableView.beginUpdates()
newOrderViewController.orderTableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0), NSIndexPath(forRow: 1, inSection: 0), NSIndexPath(forRow: 2, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Top)
newOrderViewController.orderTableView.endUpdates()
// oldOrderViewController.orderTableView.beginUpdates()
// oldOrderViewController.orderTableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0), NSIndexPath(forRow: 1, inSection: 0), NSIndexPath(forRow: 2, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Top)
// oldOrderViewController.orderTableView.endUpdates()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 6d4c9ffcaa2437a2469deafffe918f8a | 45.24 | 233 | 0.683218 | 4.529781 | false | true | false | false |
akshayg13/Game | Games/GamesVC.swift | 1 | 13157 | //
// GamesVC.swift
// Games
//
// Created by Appinventiv on 16/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import UIKit
class GamesVC: UIViewController {
//MARK: IBOutlets
@IBOutlet weak var GameCategoryTableView: UITableView!
//MARK: Properties
var indicesOfTableCell : [IndexPath] = []
var indicesOfSactionToCollapse : [Int] = []
let sectionHeader = ["From A","From S","From C","From R"]
let keys = ["Action","Adventure","Shooting","Strategy","Cards","Cars","Racing","Rock"]
var fetchedImages : [[[ImageModel]]] = []
//MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
//TableCell Nib registration
let tableCellNib = UINib(nibName: "SubCategoryTableCell", bundle: nil)
GameCategoryTableView.register(tableCellNib, forCellReuseIdentifier: "SubCategoryTableCellID")
//TableHeader Nib registration
let tableHeaderNib = UINib(nibName: "CategoryHeader", bundle: nil)
GameCategoryTableView.register(tableHeaderNib, forHeaderFooterViewReuseIdentifier: "CategoryHeaderID")
// Defining deligates and DataSources
GameCategoryTableView.delegate = self
GameCategoryTableView.dataSource = self
hitServer()
}// Ended viewDidLoad
//IBActions
@IBAction func favourite(_ sender: UIButton) {
var fav : [ImageModel] = []
for section in fetchedImages {
for row in section {
for model in row {
if(model.isFav){
fav.append(model)
}
}
}
}
let FavVC = self.navigationController?.storyboard?.instantiateViewController(withIdentifier: "FavouriteVCID") as! FavouriteVC
FavVC.favList = fav
UIView.animate(withDuration: 0.33, delay: 0, options: .curveEaseInOut, animations: {
self.navigationController?.pushViewController(FavVC, animated: true)}, completion: nil)
}
}// Ended GamesVC
//MARK: Functions
extension GamesVC{
// CollectionViewCell Favourate Button Function
func favButtonAction(button: UIButton) {
guard let collectionViewCell = button.getCollectionViewCell as? GameCollectionViewCell else { return }
guard let tableViewCell = collectionViewCell.getTableViewCell as? SubCategoryTableCell else { return }
let tableViewCellIndexPath = self.GameCategoryTableView.indexPath(for : tableViewCell)!
let collectionViewCellIndexPath = tableViewCell.subCategoryCollectionView.indexPath(for: collectionViewCell)!
button.isSelected = !button.isSelected
if (button.isSelected){
fetchedImages[tableViewCellIndexPath.section][tableViewCellIndexPath.row][collectionViewCellIndexPath.row].isFav = true
} else {
fetchedImages[tableViewCellIndexPath.section][tableViewCellIndexPath.row][collectionViewCellIndexPath.row].isFav = false
}
} // Ended favButtonAction
// TableViewCell expandCollapse Button Action
func expandCollapseButtonAction (_ sender: UIButton ) {
guard let tableViewCell = sender.getTableViewCell as? SubCategoryTableCell else { return }
let indexOfTableViewCell = self.GameCategoryTableView.indexPath(for: tableViewCell)!
sender.isSelected = !sender.isSelected
if (sender.isSelected){
indicesOfTableCell.append(indexOfTableViewCell)
} else {
indicesOfTableCell = indicesOfTableCell.filter({ (index: IndexPath) -> Bool in
return index != indexOfTableViewCell })
}
self.GameCategoryTableView.reloadRows(at: [indexOfTableViewCell], with: UITableViewRowAnimation.fade)
} // Ended expandCollapseButtonAction
func categoryHeaderCollapseExpand(_ button: UIButton) {
let headerSection = button.tag
button.isSelected = !button.isSelected
if(button.isSelected){
indicesOfSactionToCollapse.append(headerSection)
} else {
indicesOfSactionToCollapse = indicesOfSactionToCollapse.filter({ (section: Int) -> Bool in
return headerSection != section })
}
self.GameCategoryTableView.reloadSections([headerSection], with: .fade)
}//Ended categoryHeaderCollapseExpand function
func hitServer(){
var index = 0
for section in 0...3 {
self.fetchedImages.append([])
for _ in 0...1 {
Webservices().fetchDataFromPixabay(withQuery: keys[index],
success: {(data: [ImageModel]) in
self.fetchedImages[section].append(data)
self.GameCategoryTableView.reloadData() },
failure: {(error: Error) in
print("error") })
index += 1
}
}
}
}
//MARK: UITableViewDelegate, UITableViewDataSource
extension GamesVC: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return fetchedImages.count
}//Ended numberOfSection
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let headerView = GameCategoryTableView.dequeueReusableHeaderFooterView(withIdentifier: "CategoryHeaderID") as? CategoryHeader else {fatalError("Header not found ")}
headerView.categoryHeaderLabel.text = sectionHeader[section]
headerView.categoryHeaderLabel.backgroundColor = UIColor.cyan
headerView.layer.borderColor = UIColor.black.cgColor
headerView.layer.borderWidth = 1
headerView.categoryHeaderCollapseExpand.tag = section
headerView.categoryHeaderCollapseExpand.addTarget(self, action: #selector(categoryHeaderCollapseExpand(_:)), for: .touchUpInside)
if(indicesOfSactionToCollapse.contains(section)){
headerView.categoryHeaderCollapseExpand.isSelected = true
}
return headerView
}//Ended viewForHeaderInSection function
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}//Ended heightForHeaderInSection function
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if(indicesOfSactionToCollapse.contains(section)){
return 0
} else {
return fetchedImages[section].count
}
}//Ended numberOfRowsInSection function
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
guard let tableViewCell = GameCategoryTableView.dequeueReusableCell(withIdentifier: "SubCategoryTableCellID", for: indexPath) as? SubCategoryTableCell else { fatalError("Table View Cell Not Found") }
tableViewCell.backgroundColor = .green
tableViewCell.layer.borderColor = UIColor.black.cgColor
tableViewCell.layer.borderWidth = 1
tableViewCell.tableCellIndexPath = indexPath
tableViewCell.subCategoryLabel.text = keys[(indexPath.section * 2 + indexPath.row)]
//Assigning CollectionView DataSource and Deligate
tableViewCell.subCategoryCollectionView.dataSource = self
tableViewCell.subCategoryCollectionView.delegate = self
// Collection Cell nib
let collectionCellNib = UINib(nibName: "GameCollectionViewCell", bundle: nil)
tableViewCell.subCategoryCollectionView.register(collectionCellNib, forCellWithReuseIdentifier: "GameCollectionViewCellID")
// Collection View FlowLayout
let flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = CGSize(width: 90, height: 120)
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = 0
flowLayout.scrollDirection = .horizontal
tableViewCell.subCategoryCollectionView.collectionViewLayout = flowLayout
//Persisting State of expandCollapse button of SubCategoryTableCell
if(indicesOfTableCell.contains(indexPath)) {
tableViewCell.expandCollapse.isSelected = true
}
// Adding target of the expandCollapse Button
tableViewCell.expandCollapse.addTarget(self, action: #selector(expandCollapseButtonAction(_:)), for: .touchUpInside)
return tableViewCell
}//Ended cellForRowAt function
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if(indicesOfTableCell.contains(indexPath)){
return 30
} else {
return 150
}
}//Ended heightForRowAt function
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let tableCell = cell as! SubCategoryTableCell
tableCell.subCategoryCollectionView.reloadData()
}
}
//MARK: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
extension GamesVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
guard let tableCell = collectionView.getTableViewCell as? SubCategoryTableCell else { fatalError("Cell not Found ") }
return self.fetchedImages[tableCell.tableCellIndexPath.section][tableCell.tableCellIndexPath.row].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let collectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "GameCollectionViewCellID", for: indexPath) as? GameCollectionViewCell else { fatalError("Collection View Cell not found") }
collectionViewCell.gameImage.backgroundColor = .random
collectionViewCell.favButton.backgroundColor = .clear
collectionViewCell.layer.borderWidth = 1
collectionViewCell.layer.borderColor = UIColor.black.cgColor
collectionViewCell.favButton.addTarget(self, action: #selector (favButtonAction), for: .touchUpInside)
return collectionViewCell
}//Ended cellForItemAt function
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let imageViewVC = self.navigationController?.storyboard?.instantiateViewController(withIdentifier: "ImageViewVCID") as! ImageViewVC
let cell = collectionView.cellForItem(at: indexPath) as! GameCollectionViewCell
guard let tableCell = cell.getTableViewCell as? SubCategoryTableCell else { return }
let collectionCellModel : ImageModel = fetchedImages[tableCell.tableCellIndexPath.section][tableCell.tableCellIndexPath.row][indexPath.row]
imageViewVC.imageToShow = collectionCellModel
//Pushing ViewController ImageViewVC with Animation
UIView.animate(withDuration: 0.33, delay: 0, options: .curveEaseInOut, animations: {
self.navigationController?.pushViewController(imageViewVC, animated: true)}, completion: nil)
}//Ended didSelectItemAt function
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let collectionCell = cell as! GameCollectionViewCell
guard let tableCell = collectionCell.getTableViewCell as? SubCategoryTableCell else { return }
let collectionCellModel : ImageModel = fetchedImages[tableCell.tableCellIndexPath.section][tableCell.tableCellIndexPath.row][indexPath.row]
if(collectionCellModel.isFav){
collectionCell.favButton.isSelected = true
} else {
collectionCell.favButton.isSelected = false
}
let url = URL(string: collectionCellModel.previewURL)
collectionCell.gameImage.af_setImage(withURL: url!)
collectionCell.gameName.text = collectionCellModel.id
}
}
| mit | 548111a714b4ab8d4f4ccaa1cbe9c905 | 34.556757 | 219 | 0.642673 | 6.12762 | false | false | false | false |
mmick66/CalendarView | KDCalendar/CalendarView/CalendarView+Style.swift | 1 | 3835 | //
// CalendarView+Style.swift
// CalendarView
//
// Created by Vitor Mesquita on 17/01/2018.
// Copyright © 2018 Karmadust. All rights reserved.
//
import UIKit
extension CalendarView {
public class Style {
public static var Default: Style = Style()
public enum CellShapeOptions {
case round
case square
case bevel(CGFloat)
var isRound: Bool {
switch self {
case .round:
return true
default:
return false
}
}
}
public enum FirstWeekdayOptions{
case sunday
case monday
}
public enum CellOutOfRangeDisplayOptions {
case normal
case hidden
case grayed
}
public enum WeekDaysTransform {
case capitalized, uppercase
}
public init()
{
}
//Event
public var cellEventColor = UIColor(red: 254.0/255.0, green: 73.0/255.0, blue: 64.0/255.0, alpha: 0.8)
//Header
public var headerHeight: CGFloat = 80.0
public var headerTopMargin: CGFloat = 5.0
public var headerTextColor = UIColor.gray
public var headerBackgroundColor = UIColor.white
public var headerFont = UIFont.systemFont(ofSize: 20) // Used for the month
public var weekdaysTopMargin: CGFloat = 5.0
public var weekdaysBottomMargin: CGFloat = 5.0
public var weekdaysHeight: CGFloat = 35.0
public var weekdaysTextColor = UIColor.gray
public var weekdaysBackgroundColor = UIColor.white
public var weekdaysFont = UIFont.systemFont(ofSize: 14) // Used for days of the week
//Common
public var cellShape = CellShapeOptions.bevel(4.0)
public var firstWeekday = FirstWeekdayOptions.monday
public var showAdjacentDays = false
//Default Style
public var cellColorDefault = UIColor(white: 0.0, alpha: 0.1)
public var cellTextColorDefault = UIColor.gray
public var cellBorderColor = UIColor.clear
public var cellBorderWidth = CGFloat(0.0)
public var cellFont = UIFont.systemFont(ofSize: 17)
//Today Style
public var cellTextColorToday = UIColor.gray
public var cellColorToday = UIColor(red: 254.0/255.0, green: 73.0/255.0, blue: 64.0/255.0, alpha: 0.3)
public var cellColorOutOfRange = UIColor(white: 0.0, alpha: 0.5)
public var cellColorAdjacent = UIColor.clear
//Selected Style
public var cellSelectedBorderColor = UIColor(red: 254.0/255.0, green: 73.0/255.0, blue: 64.0/255.0, alpha: 0.8)
public var cellSelectedBorderWidth = CGFloat(2.0)
public var cellSelectedColor = UIColor.clear
public var cellSelectedTextColor = UIColor.black
//Weekend Style
public var cellTextColorWeekend = UIColor(red:1.00, green:0.84, blue:0.65, alpha:1.00)
//Locale Style
public var locale = Locale.current
//Calendar Identifier Style
public lazy var calendar: Calendar = {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(abbreviation: "UTC")!
return calendar
}()
public var weekDayTransform = WeekDaysTransform.capitalized
}
}
| mit | eddbda2e65b2822040a604326f380d81 | 34.174312 | 121 | 0.542775 | 4.972763 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/Analytics/Flights/Hotels/HotelsBuyEvent.swift | 1 | 1564 | //
// HotelsBuyEvent.swift
// AviasalesSDKTemplate
//
// Created by Dim on 07.09.2018.
// Copyright © 2018 Go Travel Un Limited. All rights reserved.
//
class HotelsBuyEvent: AnalyticsEvent {
let name: String = "Hotels_Buy"
let payload: [String : String]
init(variant: HLResultVariant, room: HDKRoom) {
var payload = [String: String]()
let formatter = DateFormatter(format: "yyyy-MM-dd")
payload["Hotel_Search_Type"] = variant.searchInfo.searchInfoType.description()
payload["Hotel_ID"] = variant.hotel.hotelId
payload["Hotel_Name"] = variant.hotel.latinName
payload["Hotel_City_ID"] = variant.hotel.city?.cityId
payload["Hotel_City_Name"] = variant.hotel.city?.latinName
payload["Hotel_Country_ID"] = variant.hotel.city?.countryCode
payload["Hotel_Country_Name"] = variant.hotel.city?.countryLatinName
payload["Hotel_Check_In"] = format(variant.searchInfo.checkInDate, with: formatter)
payload["Hotel_Check_Out"] = format(variant.searchInfo.checkOutDate, with: formatter)
payload["Hotel_Adults_Count"] = String(variant.searchInfo.adultsCount)
payload["Hotel_Kids_Count"] = String(variant.searchInfo.kidsCount)
payload["Hotel_Room_Price"] = String(room.priceUsd)
payload["Hotel_Room_Gate"] = room.gate.name
self.payload = payload
}
}
private func format(_ date: Date?, with formatter: DateFormatter) -> String {
guard let date = date else {
return ""
}
return formatter.string(from: date)
}
| mit | c99de1289c6255c4a435a1dd3cb68364 | 39.076923 | 93 | 0.671785 | 3.739234 | false | false | false | false |
KanChen2015/DRCRegistrationKit | DRCRegistrationKit/DRCRegistrationKit/DRCLoginRootViewController.swift | 1 | 2963 | //
// DRCLoginRootViewController.swift
// DRCRegistrationKit
//
// Created by Kan Chen on 6/6/16.
// Copyright © 2016 drchrono. All rights reserved.
//
import UIKit
@objc public protocol DRCLoginRootViewControllerDelegate {
func drcLoginRootControllerDidAuthenticateSuccess(controller: DRCLoginRootViewController)
func drcLoginRootController(controller: DRCLoginRootViewController, didAttemptSignInWithUsername username: String, password: String, twoFactorCode: String, complete: (success: Bool, twoFactorRequired: Bool, error: NSError?) -> Void)
func drcLoginRootController(controller: DRCLoginRootViewController, didAttemptSignInWithPINCode PINCode: String) -> Bool
}
public class DRCLoginRootViewController: UIViewController {
static public func instantiateFromStoryBoardWithDelegate(delegate: DRCLoginRootViewControllerDelegate?) -> DRCLoginRootViewController {
let storyboard = UIStoryboard(name: "DRCLogin", bundle: NSBundle(forClass: self))
guard let vc = storyboard.instantiateViewControllerWithIdentifier("LoginRoot") as? DRCLoginRootViewController else {
fatalError("failed to init from storyboard")
}
vc.delegate = delegate
return vc
}
var delegate: DRCLoginRootViewControllerDelegate?
public var networkingDelegate: DRCRegistrationNetworkingDelegate?
override public func viewDidLoad() {
super.viewDidLoad()
DelegateProvider.shared.networkingDelegate = networkingDelegate
// Do any additional setup after loading the view.
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let pageController = segue.destinationViewController as? DRCLoginPageViewController where segue.identifier == "embedPageView" {
pageController.loginDelegate = self
}
}
}
extension DRCLoginRootViewController: DRCLoginViewControllerDelegate {
func drcLoginControllerDidAuthenticateSuccess(controller: DRCLoginViewController) {
delegate?.drcLoginRootControllerDidAuthenticateSuccess(self)
}
func drcLoginController(controller: DRCLoginViewController, didAttemptSignInWithPINCode PINCode: String) -> Bool {
return delegate?.drcLoginRootController(self, didAttemptSignInWithPINCode: PINCode) ?? false
}
func drcLoginController(controller: DRCLoginViewController, didAttemptSignInWithUserName username: String, password: String, twoFactorCode: String, complete: (success: Bool, twoFactorRequired: Bool, error: NSError?) -> Void) {
delegate?.drcLoginRootController(self, didAttemptSignInWithUsername: username, password: password, twoFactorCode: twoFactorCode, complete: complete)
}
}
internal class DelegateProvider {
static let shared = DelegateProvider()
var networkingDelegate: DRCRegistrationNetworkingDelegate?
}
| mit | 8fd26abb5d31a74bb6ba5297006b9f31 | 48.366667 | 236 | 0.775152 | 4.903974 | false | false | false | false |
tkremenek/swift | test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-struct-1argument-1distinct_use.swift | 14 | 3215 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main9NamespaceV5ValueVySS_SiGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32{{(, \[4 x i8\])?}},
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// i8** @"$sB[[INT]]_WV",
// i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main9NamespaceV5ValueVySS_SiGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main9NamespaceV5ValueVMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSSN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
struct Namespace<Arg> {
struct Value<First> {
let first: First
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32{{(, \[4 x i8\])?}},
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main9NamespaceV5ValueVySS_SiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Namespace<String>.Value(first: 13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceV5ValueVMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE_1]],
// CHECK-SAME: i8* [[ERASED_TYPE_2]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.+}}$s4main9NamespaceV5ValueVMn{{.+}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | e45279f7dacf322f58dccb399f283bbe | 37.73494 | 157 | 0.581649 | 3.013121 | false | false | false | false |
achillara/forgetmenot | MainTableViewController.swift | 1 | 3489 | //
// MainTableViewController.swift
// Forget Me Not
//
// Created by Anusha Chillara on 2/17/15.
// Copyright (c) 2015 Chillara. All rights reserved.
//
import UIKit
class MainTableViewController: UITableViewController {
var items:[Item]=[]
@IBAction func cancelToDetailViewController(segue:UIStoryboardSegue){
}
@IBAction func saveItemDetail(segue:UIStoryboardSegue){
let detailTableViewController = segue.sourceViewController as DetailTableViewController;
items.append(detailTableViewController.item)
let indexPath = NSIndexPath(forRow: items.count-1, inSection: 0)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
let item=items[indexPath.row] as Item
cell.textLabel?.text=item.name
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | cea7108370e73e18a222b40c33102fc2 | 31.305556 | 157 | 0.678418 | 5.573482 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/Utility/UIImage+Grayscale.swift | 1 | 1448 | //
// UIImage+Grayscale.swift
// YourGoals
//
// Created by André Claaßen on 09.05.18.
// Copyright © 2018 André Claaßen. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
/// convert image to gray scale
///
/// - Returns: a gray scaled image
func convertToGrayScale() -> UIImage? {
let imageRect:CGRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
guard let cgImage = self.cgImage else {
NSLog("no cgImage in image: \(self)")
return nil
}
let colorSpace = CGColorSpaceCreateDeviceGray()
let width = self.size.width
let height = self.size.height
// let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
guard let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else {
NSLog("couldnt create context")
return nil
}
context.draw(cgImage, in: imageRect)
guard let imageRef = context.makeImage() else {
NSLog("couldn't create a cgimage")
return nil
}
let newImage = UIImage(cgImage: imageRef)
return newImage
}
}
| lgpl-3.0 | e5d7d1f0a0a8ae32b0e85ccd28e64194 | 30.369565 | 184 | 0.613306 | 4.715686 | false | false | false | false |
lorentey/swift | test/SILGen/scalar_to_tuple_args.swift | 10 | 3872 |
// RUN: %target-swift-emit-silgen -module-name scalar_to_tuple_args %s | %FileCheck %s
func inoutWithDefaults(_ x: inout Int, y: Int = 0, z: Int = 0) {}
func inoutWithCallerSideDefaults(_ x: inout Int, y: Int = #line) {}
func scalarWithDefaults(_ x: Int, y: Int = 0, z: Int = 0) {}
func scalarWithCallerSideDefaults(_ x: Int, y: Int = #line) {}
func tupleWithDefaults(x: (Int, Int), y: Int = 0, z: Int = 0) {}
func variadicFirst(_ x: Int...) {}
func variadicSecond(_ x: Int, _ y: Int...) {}
var x = 0
// CHECK: [[X_ADDR:%.*]] = global_addr @$s20scalar_to_tuple_args1xSivp : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[INOUT_WITH_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args17inoutWithDefaults_1y1zySiz_S2itF
// CHECK: apply [[INOUT_WITH_DEFAULTS]]([[WRITE]], [[DEFAULT_Y]], [[DEFAULT_Z]])
inoutWithDefaults(&x)
// CHECK: [[LINE_VAL:%.*]] = integer_literal
// CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[INOUT_WITH_CALLER_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args27inoutWithCallerSideDefaults_1yySiz_SitF
// CHECK: apply [[INOUT_WITH_CALLER_DEFAULTS]]([[WRITE]], [[LINE]])
inoutWithCallerSideDefaults(&x)
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X:%.*]] = load [trivial] [[READ]]
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[SCALAR_WITH_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args0A12WithDefaults_1y1zySi_S2itF
// CHECK: apply [[SCALAR_WITH_DEFAULTS]]([[X]], [[DEFAULT_Y]], [[DEFAULT_Z]])
scalarWithDefaults(x)
// CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]]
// CHECK: [[LINE_VAL:%.*]] = integer_literal
// CHECK: [[LINE:%.*]] = apply {{.*}}([[LINE_VAL]]
// CHECK: [[SCALAR_WITH_CALLER_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args0A22WithCallerSideDefaults_1yySi_SitF
// CHECK: apply [[SCALAR_WITH_CALLER_DEFAULTS]]([[X]], [[LINE]])
scalarWithCallerSideDefaults(x)
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X1:%.*]] = load [trivial] [[READ]]
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X2:%.*]] = load [trivial] [[READ]]
// CHECK: [[DEFAULT_Y:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[DEFAULT_Z:%.*]] = apply {{.*}} : $@convention(thin) () -> Int
// CHECK: [[TUPLE_WITH_DEFAULTS:%.*]] = function_ref @$s20scalar_to_tuple_args0C12WithDefaults1x1y1zySi_Sit_S2itF
// CHECK: apply [[TUPLE_WITH_DEFAULTS]]([[X1]], [[X2]], [[DEFAULT_Y]], [[DEFAULT_Z]])
tupleWithDefaults(x: (x,x))
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: ([[ARRAY:%.*]], [[MEMORY:%.*]]) = destructure_tuple [[ALLOC_ARRAY]]
// CHECK: [[ADDR:%.*]] = pointer_to_address [[MEMORY]]
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: copy_addr [[READ]] to [initialization] [[ADDR]]
// CHECK: [[VARIADIC_FIRST:%.*]] = function_ref @$s20scalar_to_tuple_args13variadicFirstyySid_tF
// CHECK: apply [[VARIADIC_FIRST]]([[ARRAY]])
variadicFirst(x)
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int
// CHECK: [[X:%.*]] = load [trivial] [[READ]]
// CHECK: [[ALLOC_ARRAY:%.*]] = apply {{.*}} -> (@owned Array<τ_0_0>, Builtin.RawPointer)
// CHECK: ([[ARRAY:%.*]], [[MEMORY:%.*]]) = destructure_tuple [[ALLOC_ARRAY]]
// CHECK: [[VARIADIC_SECOND:%.*]] = function_ref @$s20scalar_to_tuple_args14variadicSecondyySi_SidtF
// CHECK: apply [[VARIADIC_SECOND]]([[X]], [[ARRAY]])
variadicSecond(x)
| apache-2.0 | 11a04a11b189894f5907624221efa9c0 | 53.507042 | 126 | 0.601034 | 3.138686 | false | false | false | false |
Obbut/LogKit | LogKit/LogMessage.swift | 1 | 1730 | //
// LogMessage.swift
// LogKit
//
// Created by Robbert Brandsma on 17-03-15.
// Copyright (c) 2015 Robbert Brandsma. All rights reserved.
//
import Foundation
public struct LogMessage {
public init(text someText: AttributedString, logLevel aLevel: LogKitLevel, function aFunction: String? = nil, fullFilePath aFilePath: String? = nil, line aLine: Int? = nil, column aColumn: Int? = nil, frameworkIdentifier anIdentifier: String? = nil) {
attributedText = someText
logLevel = aLevel
function = aFunction
fullFilePath = aFilePath
line = aLine
column = aColumn
frameworkIdentifier = anIdentifier
}
public init(text someText: String, logLevel aLevel: LogKitLevel, function aFunction: String? = nil, fullFilePath aFilePath: String? = nil, line aLine: Int? = nil, column aColumn: Int? = nil, frameworkIdentifier anIdentifier: String? = nil) {
let attrString = AttributedString(string: someText)
self.init(text: attrString, logLevel: aLevel, function: aFunction, fullFilePath: aFilePath, line: aLine, column: aColumn, frameworkIdentifier: anIdentifier)
}
public var text: String {
get {
return attributedText.string
}
set {
attributedText = AttributedString(string: text)
}
}
public var attributedText: AttributedString
public var logLevel: LogKitLevel
public var function: String?
public var fullFilePath: String?
public var line: Int?
public var column: Int?
public var frameworkIdentifier: String?
public var date = Date()
public var fileName: String? { return (fullFilePath as NSString?)?.lastPathComponent }
}
| mit | d56d48e321db419834bfedb7d1b81a2c | 35.808511 | 255 | 0.676879 | 4.493506 | false | false | false | false |
calvinWen/SwiftMusicPlayer | SwiftMusic 2/SwiftMusic/MuiscListViewController.swift | 1 | 3038 | //
// MuiscListViewController.swift
// SwiftMusic
//
// Created by 科文 on 2017/5/3.
// Copyright © 2017年 科文. All rights reserved.
//
import UIKit
import AVFoundation
final class MuiscListViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableVIew: UITableView!
// var modalVC :DetailMusicViewController!
var musicArry:Array<Music>!
var musicPlayByTableViewCell: ((Int) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
// self.modalVC=self.storyboard?.instantiateViewController(withIdentifier: "DetailMusicViewController") as! DetailMusicViewController
// self.modalVC.modalPresentationStyle = .overFullScreen//弹出属性
tableVIew.dataSource=self
tableVIew.delegate=self
self.musicArry=Music.getALL()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.musicArry.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MusicListTableViewCell
cell.setModel(model: self.musicArry[indexPath.row])
// cell.musicAuthor.text=self.musicArry[indexPath.row].musicAuthor
// cell.musicName.text=self.musicArry[indexPath.row].musicName
// cell.isSelected=false
// cell.selectionStyle=UITableViewCellSelectionStyle.none
// if cell.isSelected{
// cell.activeImg.isHidden=false;
// cell.setSelected(false, animated: false)
// cell.selectedBackgroundView?.tintColor=UIColor.green
// }else{
// cell.activeImg.isHidden=true;
// }
// cell.musicNumber.text=String(indexPath.row+1)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
musicPlayByTableViewCell?(indexPath.row)
// let cell = tableView.cellForRow(at: indexPath) as! MusicListTableViewCell
// cell.selectionStyle=UITableViewCellSelectionStyle.default
// cell.setSelected(false, animated: true)
tableView.deselectRow(at: indexPath, animated: true)//取消被选中状态
// musicPlayByTableViewCell?(["wen":"123"])
// self.present(self.modalVC, animated:true , completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 8226c8e7db8998f0dd535bf443723c4d | 37.525641 | 140 | 0.686522 | 4.6302 | false | false | false | false |
dreamsxin/swift | stdlib/public/core/InputStream.swift | 3 | 2374 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// Returns `Character`s read from standard input through the end of the
/// current line or until EOF is reached, or `nil` if EOF has already been
/// reached.
///
/// If `strippingNewline` is `true`, newline characters and character
/// combinations will be stripped from the result. This is the default.
///
/// Standard input is interpreted as `UTF-8`. Invalid bytes
/// will be replaced by Unicode [replacement characters](http://en.wikipedia.org/wiki/Specials_(Unicode_block)#Replacement_character).
public func readLine(strippingNewline: Bool = true) -> String? {
var linePtrVar: UnsafeMutablePointer<CChar>? = nil
var readBytes = swift_stdlib_readLine_stdin(&linePtrVar)
if readBytes == -1 {
return nil
}
_sanityCheck(readBytes >= 0,
"unexpected return value from swift_stdlib_readLine_stdin")
if readBytes == 0 {
return ""
}
let linePtr = linePtrVar!
if strippingNewline {
// FIXME: Unicode conformance. To fix this, we need to reimplement the
// code we call above to get a line, since it will only stop on LF.
//
// <rdar://problem/20013999> Recognize Unicode newlines in readLine()
//
// Recognize only LF and CR+LF combinations for now.
let cr = CChar(UInt8(ascii: "\r"))
let lf = CChar(UInt8(ascii: "\n"))
if readBytes == 1 && linePtr[0] == lf {
return ""
}
if readBytes >= 2 {
switch (linePtr[readBytes - 2], linePtr[readBytes - 1]) {
case (cr, lf):
readBytes -= 2
break
case (_, lf):
readBytes -= 1
break
default:
()
}
}
}
let result = String._fromCodeUnitSequenceWithRepair(UTF8.self,
input: UnsafeMutableBufferPointer(
start: UnsafeMutablePointer<UTF8.CodeUnit>(linePtr),
count: readBytes)).0
_swift_stdlib_free(linePtr)
return result
}
| apache-2.0 | 998cfc8dd2fbe21fc13b02cc351e9566 | 33.911765 | 134 | 0.624263 | 4.285199 | false | false | false | false |
sharath-cliqz/browser-ios | Utils/KeychainCache.swift | 2 | 2268 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import XCGLogger
import SwiftKeychainWrapper
import SwiftyJSON
private let log = Logger.keychainLogger
public protocol JSONLiteralConvertible {
func asJSON() -> JSON
}
open class KeychainCache<T: JSONLiteralConvertible> {
open let branch: String
open let label: String
open var value: T? {
didSet {
checkpoint()
}
}
public init(branch: String, label: String, value: T?) {
self.branch = branch
self.label = label
self.value = value
}
open class func fromBranch(_ branch: String, withLabel label: String?, withDefault defaultValue: T? = nil, factory: (JSON) -> T?) -> KeychainCache<T> {
if let l = label {
if let s = KeychainWrapper.standard.string(forKey: "\(branch).\(l)") {
if let t = factory(JSON.parse(s)) {
log.info("Read \(branch) from Keychain with label \(branch).\(l).")
return KeychainCache(branch: branch, label: l, value: t)
} else {
log.warning("Found \(branch) in Keychain with label \(branch).\(l), but could not parse it.")
}
} else {
log.warning("Did not find \(branch) in Keychain with label \(branch).\(l).")
}
} else {
log.warning("Did not find \(branch) label in Keychain.")
}
// Fall through to missing.
log.warning("Failed to read \(branch) from Keychain.")
let label = label ?? Bytes.generateGUID()
return KeychainCache(branch: branch, label: label, value: defaultValue)
}
open func checkpoint() {
log.info("Storing \(self.branch) in Keychain with label \(self.branch).\(self.label).")
// TODO: PII logging.
if let value = value,
let jsonString = value.asJSON().stringValue() {
KeychainWrapper.sharedAppContainerKeychain.set(jsonString, forKey: "\(branch).\(label)")
} else {
KeychainWrapper.sharedAppContainerKeychain.removeObject(forKey: "\(branch).\(label)")
}
}
}
| mpl-2.0 | 3202a1a43af4b7c82a09d2afed81016b | 35 | 155 | 0.608466 | 4.395349 | false | false | false | false |
kgaidis/KGViewSeparators | Example/Swift/KGViewSeparatorsExample/ViewController.swift | 1 | 1467 | //
// ViewController.swift
// KGViewSeparatorsExample
//
// Created by Krisjanis Gaidis on 12/28/15.
// Copyright © 2015 KG. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: - Constants -
private let kNumberOfRows = 100
private let kCellHeight: CGFloat = 44.0
// MARK: - IBOutlets -
@IBOutlet private weak var tableView: UITableView!
// MARK: - Lifecycle -
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .None
}
// MARK: - Overrides -
override func prefersStatusBarHidden() -> Bool {
return true
}
}
// MARK: - <UITableViewDataSource, UITableViewDelegate> -
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return kNumberOfRows
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.showTopSeparator(indexPath.row == 0)
cell.showBottomSeparator(true)
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return kCellHeight
}
} | mit | 92484329651b3a00f7d73c48c8fa40a7 | 26.166667 | 109 | 0.673261 | 5.217082 | false | false | false | false |
jasonwedepohl/udacity-ios-on-the-map | On The Map/On The Map/LocationFinder.swift | 1 | 779 | //
// LocationFinder.swift
// On The Map
//
// Created by Jason Wedepohl on 2017/09/22.
//
import CoreLocation
class LocationFinder {
static func find(_ searchString: String, _ findCompletion: @escaping (_ coordinate: CLLocationCoordinate2D?) -> Void) {
CLGeocoder().geocodeAddressString(searchString, completionHandler: { (placemarks, error) in
if error != nil {
print(error!.localizedDescription)
findCompletion(nil)
return
}
if placemarks == nil || placemarks!.count == 0 {
findCompletion(nil)
return
}
guard let coordinate = placemarks![0].location?.coordinate else {
findCompletion(nil)
return
}
print("Coordinate: \(coordinate.latitude), \(coordinate.longitude)")
findCompletion(coordinate)
})
}
}
| mit | 66421e4ea1839fa5cd12fa6458feaa9c | 22.606061 | 120 | 0.679076 | 3.818627 | false | false | false | false |
certificate-helper/TLS-Inspector | TLS Inspector/View Controllers/AboutViewController.swift | 1 | 4763 | import UIKit
import CertificateKit
class AboutTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let projectGithubURL = "https://tlsinspector.com/github.html"
let projectURL = "https://tlsinspector.com/"
let projectContributeURL = "https://tlsinspector.com/contribute.html"
let testflightURL = "https://tlsinspector.com/beta.html"
@IBOutlet weak var lockCircle: UIImageView!
var quotes: [String] = []
var taps = 0
override func viewDidLoad() {
super.viewDidLoad()
if let q = loadQuotes() {
self.quotes = q
}
let tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapPicture(target:)))
self.lockCircle.isUserInteractionEnabled = true
self.lockCircle.addGestureRecognizer(tap)
}
func loadQuotes() -> [String]? {
guard let quotesPath = Bundle.main.path(forResource: "QuoteList", ofType: "plist") else {
return nil
}
guard let quotes = NSArray.init(contentsOfFile: quotesPath) as? [String] else {
return nil
}
return quotes
}
@objc func didTapPicture(target: UIImageView) {
if self.quotes.count == 0 {
return
}
self.taps += 1
if self.taps >= 3 {
self.taps = 0
UIHelper(self).presentAlert(title: self.quotes.randomElement() ?? "", body: "", dismissed: nil)
}
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 3
} else if section == 1 {
return 2
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Basic", for: indexPath)
if indexPath.section == 0 && indexPath.row == 0 {
cell.textLabel?.text = lang(key: "Share TLS Inspector")
} else if indexPath.section == 0 && indexPath.row == 1 {
cell.textLabel?.text = lang(key: "Rate in App Store")
} else if indexPath.section == 0 && indexPath.row == 2 {
cell.textLabel?.text = lang(key: "Provide Feedback")
} else if indexPath.section == 1 && indexPath.row == 0 {
cell.textLabel?.text = lang(key: "Contribute to TLS Inspector")
} else if indexPath.section == 1 && indexPath.row == 1 {
cell.textLabel?.text = lang(key: "Test New Features")
}
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return lang(key: "Share & Feedback")
} else if section == 1 {
return lang(key: "Get Involved")
}
return nil
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 0 {
let opensslVersion = CertificateKit.opensslVersion()
let libcurlVersion = CertificateKit.libcurlVersion()
return "App: \(AppInfo.version()) (\(AppInfo.build())), OpenSSL: \(opensslVersion), cURL: \(libcurlVersion)"
} else if section == 1 {
return lang(key: "copyright_license_footer")
}
return nil
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) else {
return
}
if indexPath.section == 0 && indexPath.row == 0 {
let blub = lang(key: "Trust & Safety On-The-Go with TLS Inspector: {url}", args: [projectURL])
let activityController = UIActivityViewController(activityItems: [blub], applicationActivities: nil)
ActionTipTarget(view: cell).attach(to: activityController.popoverPresentationController)
self.present(activityController, animated: true, completion: nil)
} else if indexPath.section == 0 && indexPath.row == 1 {
AppLinks().showAppStore(self, dismissed: nil)
} else if indexPath.section == 0 && indexPath.row == 2 {
ContactTableViewController.show(self) { (support) in
AppLinks.current.showEmailCompose(viewController: self, object: support, includeLogs: false, dismissed: nil)
}
} else if indexPath.section == 1 && indexPath.row == 0 {
OpenURLInSafari(projectContributeURL)
} else if indexPath.section == 1 && indexPath.row == 1 {
OpenURLInSafari(testflightURL)
}
}
}
| gpl-3.0 | 1a01b0c0f69b1d66fedb817710df555e | 37.723577 | 124 | 0.6097 | 4.593057 | false | false | false | false |
wj2061/ios7ptl-swift3.0 | ch21-Text/DuplicateLayout/DuplicateLayout/LayoutView.swift | 1 | 1085 | //
// LayoutView.swift
// DuplicateLayout
//
// Created by WJ on 15/11/25.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
class LayoutView: UIView ,NSLayoutManagerDelegate{
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer()
@IBOutlet weak var textView: UITextView!
override func awakeFromNib() {
var size = bounds.size
size.width /= 2
textContainer.size = size
layoutManager.delegate = self
layoutManager.addTextContainer(textContainer)
textView.textStorage.addLayoutManager(layoutManager)
}
//MARK:- NSLayoutManagerDelegate
func layoutManagerDidInvalidateLayout(_ sender: NSLayoutManager) {
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
let range = layoutManager.glyphRange(for: textContainer)
let point = CGPoint.zero
layoutManager.drawBackground(forGlyphRange: range, at: point)
layoutManager.drawGlyphs(forGlyphRange: range , at: point)
}
}
| mit | 9de44cd4998f64448d1016c29139c0e6 | 24.162791 | 70 | 0.656192 | 5.032558 | false | false | false | false |
muneebm/AsterockX | AsterockX/SkyViewController.swift | 1 | 3290 | //
// SkyViewController.swift
// AsterockX
//
// Created by Muneeb Rahim Abdul Majeed on 1/19/16.
// Copyright © 2016 beenum. All rights reserved.
//
import UIKit
class SkyViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var image: UIImage!
var observation: Observation!
@IBOutlet weak var infoButton: UIButton!
@IBOutlet weak var observationDataView: UIScrollView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var observationIDLabel: UILabel!
@IBOutlet weak var tripletLabel: UILabel!
@IBOutlet weak var absoluteMagnitudeLabel: UILabel!
@IBOutlet weak var offsetLabel: UILabel!
@IBOutlet weak var predictedRALabel: UILabel!
@IBOutlet weak var predictedDecLabel: UILabel!
@IBOutlet weak var centerRALabel: UILabel!
@IBOutlet weak var centerDecLabel: UILabel!
@IBOutlet weak var weVelocityLabel: UILabel!
@IBOutlet weak var snVelocityLabel: UILabel!
@IBOutlet weak var majorPositionalErrorLabel: UILabel!
@IBOutlet weak var minorPositionalErrorLabel: UILabel!
@IBOutlet weak var positionalAngleErrorLabel: UILabel!
@IBOutlet weak var pixelLocationY: UILabel!
@IBOutlet weak var pixelLocationX: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
observationDataView.hidden = true
imageView.image = image
if let time = observation.Time {
timeLabel.text = Utility.getFormattedStringFromDate(time, format: Utility.Constants.ObservationDateFormat)
}
observationIDLabel.text = observation.ObservationId
tripletLabel.text = observation.Triplet
setValueToLabel(absoluteMagnitudeLabel, value: observation.AbsoluteMagnitude)
setValueToLabel(offsetLabel, value: observation.Offset)
setValueToLabel(predictedRALabel, value: observation.PredictedRA)
setValueToLabel(predictedDecLabel, value: observation.PredictedDec)
setValueToLabel(centerRALabel, value: observation.CenterRA)
setValueToLabel(centerDecLabel, value: observation.CenterDec)
setValueToLabel(weVelocityLabel, value: observation.VelocityWE)
setValueToLabel(snVelocityLabel, value: observation.VelocitySN)
majorPositionalErrorLabel.text = observation.PositionErrorMajor
minorPositionalErrorLabel.text = observation.PositionErrorMinor
positionalAngleErrorLabel.text = observation.PositionErrorAngle
setValueToLabel(pixelLocationX, value: observation.PixelLocationX)
setValueToLabel(pixelLocationY, value: observation.PixelLocationY)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func setValueToLabel(label: UILabel, value: Double?) {
if let value = value {
label.text = "\(value)"
}
}
@IBAction func displayObservationData(sender: UIButton) {
let hidden = observationDataView.hidden
observationDataView.hidden = !hidden
infoButton.tintColor = hidden ? Utility.Constants.Accent : UIColor.whiteColor()
}
@IBAction func close() {
dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | f190932f62efe7b03addb55856730185 | 35.544444 | 119 | 0.703557 | 4.923653 | false | false | false | false |
mercadopago/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/FeesDetail.swift | 1 | 879 | //
// FeesDetail.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 6/3/15.
// Copyright (c) 2015 com.mercadopago. All rights reserved.
//
import Foundation
public class FeesDetail : NSObject {
public var amount : Double = 0
public var amountRefunded : Double = 0
public var feePayer : String!
public var type : String!
public class func fromJSON(json : NSDictionary) -> FeesDetail {
let fd : FeesDetail = FeesDetail()
fd.type = JSON(json["type"]!).asString
fd.feePayer = JSON(json["fee_payer"]!).asString
if json["amount"] != nil && !(json["amount"]! is NSNull) {
fd.amount = JSON(json["amount"]!).asDouble!
}
if json["amount_refunded"] != nil && !(json["amount_refunded"]! is NSNull) {
fd.amountRefunded = JSON(json["amount_refunded"]!).asDouble!
}
return fd
}
} | mit | b51504b13efc2501f57f14deeb6133dc | 28.333333 | 84 | 0.615472 | 3.788793 | false | false | false | false |
Palleas/BetaSeriesKit | BetaSeriesKit/FetchMemberInfos.swift | 1 | 1222 | //
// FetchMemberInfos.swift
// BetaSeriesKit
//
// Created by Romain Pouclet on 2016-02-02.
// Copyright © 2016 Perfectly-Cooked. All rights reserved.
//
import UIKit
import SwiftyJSON
import ReactiveCocoa
public class Member: Model {
public let id: Int
public let login: String
public let avatar: NSURL?
public let shows: [Show]
required public init(payload: JSON) {
id = payload["member"]["id"].intValue
login = payload["member"]["login"].stringValue
avatar = payload["member"]["avatar"].URL
shows = payload["member"]["shows"].arrayValue.map { Show(payload: $0) }
}
}
public class FetchMemberInfos: NSObject, Request {
typealias ObjectModel = Member
var endpoint = "/members/infos"
var method: RequestMethod = .Get
var body: [String: AnyObject]? {
return nil
}
var params: [String: AnyObject]? {
return nil
}
func send(session: NSURLSession, baseURL: NSURL, key: String, token: String?) -> SignalProducer<FetchMemberInfos.ObjectModel, RequestError> {
return performRequest(session, baseURL: baseURL, key: key, token: token)
.mapObject(Member.self)
}
}
| mit | 453435b0e52eeb0943f04baf18e64ad5 | 24.978723 | 145 | 0.641278 | 4.239583 | false | false | false | false |
weichsel/ZIPFoundation | Sources/ZIPFoundation/Data+Compression.swift | 1 | 18260 | //
// Data+Compression.swift
// ZIPFoundation
//
// Copyright © 2017-2021 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
#if canImport(zlib)
import zlib
#endif
/// The compression method of an `Entry` in a ZIP `Archive`.
public enum CompressionMethod: UInt16 {
/// Indicates that an `Entry` has no compression applied to its contents.
case none = 0
/// Indicates that contents of an `Entry` have been compressed with a zlib compatible Deflate algorithm.
case deflate = 8
}
/// An unsigned 32-Bit Integer representing a checksum.
public typealias CRC32 = UInt32
/// A custom handler that consumes a `Data` object containing partial entry data.
/// - Parameters:
/// - data: A chunk of `Data` to consume.
/// - Throws: Can throw to indicate errors during data consumption.
public typealias Consumer = (_ data: Data) throws -> Void
/// A custom handler that receives a position and a size that can be used to provide data from an arbitrary source.
/// - Parameters:
/// - position: The current read position.
/// - size: The size of the chunk to provide.
/// - Returns: A chunk of `Data`.
/// - Throws: Can throw to indicate errors in the data source.
public typealias Provider = (_ position: Int64, _ size: Int) throws -> Data
extension Data {
enum CompressionError: Error {
case invalidStream
case corruptedData
}
/// Calculate the `CRC32` checksum of the receiver.
///
/// - Parameter checksum: The starting seed.
/// - Returns: The checksum calculated from the bytes of the receiver and the starting seed.
public func crc32(checksum: CRC32) -> CRC32 {
#if canImport(zlib)
return withUnsafeBytes { bufferPointer in
let length = UInt32(count)
return CRC32(zlib.crc32(UInt(checksum), bufferPointer.bindMemory(to: UInt8.self).baseAddress, length))
}
#else
return self.builtInCRC32(checksum: checksum)
#endif
}
/// Compress the output of `provider` and pass it to `consumer`.
/// - Parameters:
/// - size: The uncompressed size of the data to be compressed.
/// - bufferSize: The maximum size of the compression buffer.
/// - provider: A closure that accepts a position and a chunk size. Returns a `Data` chunk.
/// - consumer: A closure that processes the result of the compress operation.
/// - Returns: The checksum of the processed content.
public static func compress(size: Int64, bufferSize: Int, provider: Provider, consumer: Consumer) throws -> CRC32 {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
return try self.process(operation: COMPRESSION_STREAM_ENCODE, size: size, bufferSize: bufferSize,
provider: provider, consumer: consumer)
#else
return try self.encode(size: size, bufferSize: bufferSize, provider: provider, consumer: consumer)
#endif
}
/// Decompress the output of `provider` and pass it to `consumer`.
/// - Parameters:
/// - size: The compressed size of the data to be decompressed.
/// - bufferSize: The maximum size of the decompression buffer.
/// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance.
/// - provider: A closure that accepts a position and a chunk size. Returns a `Data` chunk.
/// - consumer: A closure that processes the result of the decompress operation.
/// - Returns: The checksum of the processed content.
public static func decompress(size: Int64, bufferSize: Int, skipCRC32: Bool,
provider: Provider, consumer: Consumer) throws -> CRC32 {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
return try self.process(operation: COMPRESSION_STREAM_DECODE, size: size, bufferSize: bufferSize,
skipCRC32: skipCRC32, provider: provider, consumer: consumer)
#else
return try self.decode(bufferSize: bufferSize, skipCRC32: skipCRC32, provider: provider, consumer: consumer)
#endif
}
}
// MARK: - Apple Platforms
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Compression
extension Data {
static func process(operation: compression_stream_operation, size: Int64, bufferSize: Int, skipCRC32: Bool = false,
provider: Provider, consumer: Consumer) throws -> CRC32 {
var crc32 = CRC32(0)
let destPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
defer { destPointer.deallocate() }
let streamPointer = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
defer { streamPointer.deallocate() }
var stream = streamPointer.pointee
var status = compression_stream_init(&stream, operation, COMPRESSION_ZLIB)
guard status != COMPRESSION_STATUS_ERROR else { throw CompressionError.invalidStream }
defer { compression_stream_destroy(&stream) }
stream.src_size = 0
stream.dst_ptr = destPointer
stream.dst_size = bufferSize
var position: Int64 = 0
var sourceData: Data?
repeat {
let isExhausted = stream.src_size == 0
if isExhausted {
do {
sourceData = try provider(position, Int(Swift.min((size - position), Int64(bufferSize))))
position += Int64(stream.prepare(for: sourceData))
} catch { throw error }
}
if let sourceData = sourceData {
sourceData.withUnsafeBytes { rawBufferPointer in
if let baseAddress = rawBufferPointer.baseAddress {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
stream.src_ptr = pointer.advanced(by: sourceData.count - stream.src_size)
let flags = sourceData.count < bufferSize ? Int32(COMPRESSION_STREAM_FINALIZE.rawValue) : 0
status = compression_stream_process(&stream, flags)
}
}
if operation == COMPRESSION_STREAM_ENCODE &&
isExhausted && skipCRC32 == false { crc32 = sourceData.crc32(checksum: crc32) }
}
switch status {
case COMPRESSION_STATUS_OK, COMPRESSION_STATUS_END:
let outputData = Data(bytesNoCopy: destPointer, count: bufferSize - stream.dst_size, deallocator: .none)
try consumer(outputData)
if operation == COMPRESSION_STREAM_DECODE && !skipCRC32 { crc32 = outputData.crc32(checksum: crc32) }
stream.dst_ptr = destPointer
stream.dst_size = bufferSize
default: throw CompressionError.corruptedData
}
} while status == COMPRESSION_STATUS_OK
return crc32
}
}
private extension compression_stream {
mutating func prepare(for sourceData: Data?) -> Int {
guard let sourceData = sourceData else { return 0 }
self.src_size = sourceData.count
return sourceData.count
}
}
// MARK: - Linux
#else
import CZlib
extension Data {
static func encode(size: Int64, bufferSize: Int, provider: Provider, consumer: Consumer) throws -> CRC32 {
var stream = z_stream()
let streamSize = Int32(MemoryLayout<z_stream>.size)
var result = deflateInit2_(&stream, Z_DEFAULT_COMPRESSION,
Z_DEFLATED, -MAX_WBITS, 9, Z_DEFAULT_STRATEGY, ZLIB_VERSION, streamSize)
defer { deflateEnd(&stream) }
guard result == Z_OK else { throw CompressionError.invalidStream }
var flush = Z_NO_FLUSH
var position: Int64 = 0
var zipCRC32 = CRC32(0)
repeat {
let readSize = Int(Swift.min((size - position), Int64(bufferSize)))
var inputChunk = try provider(position, readSize)
zipCRC32 = inputChunk.crc32(checksum: zipCRC32)
stream.avail_in = UInt32(inputChunk.count)
try inputChunk.withUnsafeMutableBytes { (rawBufferPointer) in
if let baseAddress = rawBufferPointer.baseAddress {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
stream.next_in = pointer
flush = position + Int64(bufferSize) >= size ? Z_FINISH : Z_NO_FLUSH
} else if rawBufferPointer.count > 0 {
throw CompressionError.corruptedData
} else {
stream.next_in = nil
flush = Z_FINISH
}
var outputChunk = Data(count: bufferSize)
repeat {
stream.avail_out = UInt32(bufferSize)
try outputChunk.withUnsafeMutableBytes { (rawBufferPointer) in
guard let baseAddress = rawBufferPointer.baseAddress, rawBufferPointer.count > 0 else {
throw CompressionError.corruptedData
}
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
stream.next_out = pointer
result = deflate(&stream, flush)
}
guard result >= Z_OK else { throw CompressionError.corruptedData }
outputChunk.count = bufferSize - Int(stream.avail_out)
try consumer(outputChunk)
} while stream.avail_out == 0
}
position += Int64(readSize)
} while flush != Z_FINISH
return zipCRC32
}
static func decode(bufferSize: Int, skipCRC32: Bool, provider: Provider, consumer: Consumer) throws -> CRC32 {
var stream = z_stream()
let streamSize = Int32(MemoryLayout<z_stream>.size)
var result = inflateInit2_(&stream, -MAX_WBITS, ZLIB_VERSION, streamSize)
defer { inflateEnd(&stream) }
guard result == Z_OK else { throw CompressionError.invalidStream }
var unzipCRC32 = CRC32(0)
var position: Int64 = 0
repeat {
stream.avail_in = UInt32(bufferSize)
var chunk = try provider(position, bufferSize)
position += Int64(chunk.count)
try chunk.withUnsafeMutableBytes { (rawBufferPointer) in
if let baseAddress = rawBufferPointer.baseAddress, rawBufferPointer.count > 0 {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
stream.next_in = pointer
repeat {
var outputData = Data(count: bufferSize)
stream.avail_out = UInt32(bufferSize)
try outputData.withUnsafeMutableBytes { (rawBufferPointer) in
if let baseAddress = rawBufferPointer.baseAddress, rawBufferPointer.count > 0 {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
stream.next_out = pointer
} else {
throw CompressionError.corruptedData
}
result = inflate(&stream, Z_NO_FLUSH)
guard result != Z_NEED_DICT &&
result != Z_DATA_ERROR &&
result != Z_MEM_ERROR else {
throw CompressionError.corruptedData
}
}
let remainingLength = UInt32(bufferSize) - stream.avail_out
outputData.count = Int(remainingLength)
try consumer(outputData)
if !skipCRC32 { unzipCRC32 = outputData.crc32(checksum: unzipCRC32) }
} while stream.avail_out == 0
}
}
} while result != Z_STREAM_END
return unzipCRC32
}
}
#endif
/// The lookup table used to calculate `CRC32` checksums when using the built-in
/// CRC32 implementation.
private let crcTable: [CRC32] = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832,
0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a,
0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab,
0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4,
0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074,
0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525,
0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76,
0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6,
0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7,
0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7,
0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330,
0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d]
extension Data {
/// Lookup table-based CRC32 implenetation that is used
/// if `zlib` isn't available.
/// - Parameter checksum: Running checksum or `0` for the initial run.
/// - Returns: The calculated checksum of the receiver.
func builtInCRC32(checksum: CRC32) -> CRC32 {
// The typecast is necessary on 32-bit platforms because of
// https://bugs.swift.org/browse/SR-1774
let mask = 0xffffffff as CRC32
var result = checksum ^ mask
#if swift(>=5.0)
crcTable.withUnsafeBufferPointer { crcTablePointer in
self.withUnsafeBytes { bufferPointer in
var bufferIndex = 0
while bufferIndex < self.count {
let byte = bufferPointer[bufferIndex]
let index = Int((result ^ CRC32(byte)) & 0xff)
result = (result >> 8) ^ crcTablePointer[index]
bufferIndex += 1
}
}
}
#else
self.withUnsafeBytes { (bytes) in
let bins = stride(from: 0, to: self.count, by: 256)
for bin in bins {
for binIndex in 0..<256 {
let byteIndex = bin + binIndex
guard byteIndex < self.count else { break }
let byte = bytes[byteIndex]
let index = Int((result ^ CRC32(byte)) & 0xff)
result = (result >> 8) ^ crcTable[index]
}
}
}
#endif
return result ^ mask
}
}
#if !swift(>=5.0)
// Since Swift 5.0, `Data.withUnsafeBytes()` passes an `UnsafeRawBufferPointer` instead of an `UnsafePointer<UInt8>`
// into `body`.
// We provide a compatible method for targets that use Swift 4.x so that we can use the new version
// across all language versions.
extension Data {
func withUnsafeBytes<T>(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T {
let count = self.count
return try withUnsafeBytes { (pointer: UnsafePointer<UInt8>) throws -> T in
try body(UnsafeRawBufferPointer(start: pointer, count: count))
}
}
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#else
mutating func withUnsafeMutableBytes<T>(_ body: (UnsafeMutableRawBufferPointer) throws -> T) rethrows -> T {
let count = self.count
guard count > 0 else {
return try body(UnsafeMutableRawBufferPointer(start: nil, count: count))
}
return try withUnsafeMutableBytes { (pointer: UnsafeMutablePointer<UInt8>) throws -> T in
try body(UnsafeMutableRawBufferPointer(start: pointer, count: count))
}
}
#endif
}
#endif
| mit | a54d2d3174fdde3b76401c75105e5c28 | 48.752044 | 120 | 0.630757 | 3.526265 | false | false | false | false |
xuech/OMS-WH | OMS-WH/Classes/OrderDetail/View/ReceiverView.swift | 1 | 1954 | //
// ReceiverView.swift
// OMS
//
// Created by gwy on 16/10/19.
// Copyright © 2016年 文羿 顾. All rights reserved.
//
import UIKit
class ReceiverView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setUP()
}
required init?(coder aDecoder: NSCoder) {
fatalError("initCoder has not been completed")
}
func setUP(){
self.addSubview(image)
self.addSubview(receiverLB)
self.addSubview(addressLB)
image.snp.makeConstraints { (make) in
make.left.top.equalTo(10)
make.width.height.equalTo(35)
}
receiverLB.snp.makeConstraints { (make) in
make.left.equalTo(image.snp.right).offset(10)
make.top.equalTo(self).offset(5)
make.height.equalTo(25)
make.right.equalTo(self).offset(-5)
}
addressLB.snp.makeConstraints { (make) in
make.left.equalTo(image.snp.right).offset(10)
make.top.equalTo(receiverLB.snp.bottom).offset(5)
make.right.equalTo(self).offset(-5)
make.height.equalTo(25)
}
let lineView = UIView()
lineView.backgroundColor = UIColor.colorHexStr("e3e3e3", alpha: 1)
self.addSubview(lineView)
lineView.snp.makeConstraints { (make) in
make.left.right.top.equalTo(self)
make.height.equalTo(1)
}
}
lazy var image:UIImageView = {
let image = UIImageView()
image.contentMode = UIViewContentMode.scaleToFill
return image
}()
lazy var receiverLB:UILabel = self.createLB()
lazy var addressLB:UILabel = self.createLB()
fileprivate func createLB() ->UILabel{
let lb = UILabel()
// lb.backgroundColor = UIColor.yellowColor()
lb.font = UIFont.systemFont(ofSize: 14)
return lb
}
}
| mit | ded57869f8d5b5a79e34ecda69be5e93 | 26.013889 | 74 | 0.57635 | 4.077568 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/HotelPricesVC.swift | 1 | 3896 | import UIKit
@objc protocol BookRoomDelegate: class, NSObjectProtocol {
func bookRoom(_ room: HDKRoom)
}
class HotelPricesVC: HotelDetailsMoreTableVC, PeekVCProtocol, UIViewControllerPreviewingDelegate {
weak var delegate: BookRoomDelegate?
var commitBlock: (() -> Void)?
// MARK: - Override methods
override func viewDidLoad() {
super.viewDidLoad()
title = NSLS("HL_HOTEL_DETAIL_SEGMENTED_ALLPRICES_SECTION")
contentTable.allowsSelection = true
contentTable.hl_registerNib(withName: HLHotelDetailsPriceTableCell.hl_reuseIdentifier())
contentTable.hl_registerNib(withName: HLShowMorePricesCell.hl_reuseIdentifier())
contentTable.contentInset.top += 5
sections = createSections()
}
// MARK: - Private methods
private func createSections() -> [TableSection] {
var result: [TableSection] = []
let collectedRooms = variant.roomsByType
for rooms in collectedRooms {
let room = rooms[0]
let section = PriceSection(rooms: rooms, name: room.localizedType ?? "", variant: variant)
result.append(section)
}
(result.last as? PriceSection)?.shouldShowSeparator = false
return result
}
private func expandSection(_ section: PriceSection) {
section.expanded = !section.expanded
contentTable.reloadData()
}
// MARK: - UITableViewDelegate methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = sections[indexPath.section].items[indexPath.row]
if let roomItem = item as? RoomItem {
delegate?.bookRoom(roomItem.room)
} else if let expandItem = item as? ExpandPriceItem {
expandSection(expandItem.section)
}
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: IndexPath) {
cell.backgroundColor = UIColor.clear
if #available(iOS 9.0, *) {
if let cell = cell as? HLHotelDetailsPriceTableCell, cell.forceTouchAdded != true {
registerForPreviewing(with: self, sourceView: cell)
cell.forceTouchAdded = true
}
}
}
// MARK: - UIViewControllerPreviewingDelegate
@available(iOS 9.0, *)
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
if let cell = previewingContext.sourceView as? HLHotelDetailsPriceTableCell {
previewingContext.sourceRect = previewingContext.sourceView.bounds
return createBookingPeekVC(variant, room: cell.room)
}
return nil
}
public func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
if let peekVC = viewControllerToCommit as? PeekVCProtocol {
peekVC.commitBlock?()
}
}
private func createBookingPeekVC(_ variant: HLResultVariant?, room: HDKRoom) -> BookingPeekVC {
let peekVC = BookingPeekVC(nibName: "PeekTableVC", bundle: nil)
peekVC.room = room
peekVC.variant = variant
peekVC.viewControllerToShowBrowser = self
let width = UIScreen.main.bounds.width
let height = peekVC.heightForVariant(variant, peekWidth: width)
peekVC.preferredContentSize = CGSize(width: width, height: height)
peekVC.commitBlock = {[weak self] in self?.delegate?.bookRoom(room) }
return peekVC
}
func priceCellRect(_ cell: HLHotelDetailsPriceTableCell) -> CGRect? {
if contentTable.visibleCells.contains(cell) {
return view.convert(cell.highlightView.frame, from: cell)
}
return nil
}
}
| mit | 9bfbc87c5ddfc5d97099f415e22eafba | 35.411215 | 143 | 0.672485 | 4.857855 | false | false | false | false |
domenicosolazzo/practice-swift | CoreData/SuperDB/SuperDB/Hero.swift | 1 | 2667 | //
// Hero.swift
// SuperDB
//
// Created by Domenico on 02/06/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
import CoreData
let kHeroValidationDomain = "com.oz-apps.SuperDB.HeroValidationDomain"
let kHeroValidationBirthdateCode = 1000
let kHeroValidationNameOrSecretIdentityCode = 1001
class Hero: NSManagedObject {
@NSManaged var birthDate: NSDate
@NSManaged var name: String
@NSManaged var secretIdentity: String
@NSManaged var sex: String
@NSManaged var favoriteColor: UIColor
var age:NSNumber {
get {
if self.birthDate != NSNull() {
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
var today = NSDate()
let components = gregorian?.components(NSCalendarUnit.Year, fromDate: self.birthDate, toDate: NSDate(), options: [])
let years = components?.year
return years!
}
return 0
}
}
override func awakeFromInsert() {
super.awakeFromInsert()
self.favoriteColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
self.birthDate = NSDate()
}
func validateBirthDate(ioValue: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws {
var date = ioValue.memory as! NSDate
if date.compare(NSDate()) == .OrderedDescending {
var errorStr = NSLocalizedString("Birthdate cannot be in the future",
comment: "Birthdate cannot be in the future")
var userInfo = NSDictionary(object: errorStr, forKey: NSLocalizedDescriptionKey)
var outError = NSError(domain: kHeroValidationDomain, code: kHeroValidationBirthdateCode, userInfo: userInfo as! [NSObject : AnyObject])
throw outError
}
}
func validateNameOrSecretIdentity() throws{
if self.name.characters.count < 2 && self.secretIdentity.characters.count == 0 {
var errorStr = NSLocalizedString("Must provide name or secret identity.",
comment: "Must provide name or secret identity.")
var userInfo = NSDictionary(object: errorStr, forKey: NSLocalizedDescriptionKey)
var outError = NSError(domain: kHeroValidationDomain, code: kHeroValidationNameOrSecretIdentityCode, userInfo: userInfo as! [NSObject : AnyObject])
throw outError
}
}
override func validateForInsert() throws {
try self.validateNameOrSecretIdentity()
}
override func validateForUpdate() throws {
try self.validateNameOrSecretIdentity()
}
}
| mit | 69d4569a3cc2cc74245ea0344d873bb8 | 34.092105 | 159 | 0.648294 | 4.96648 | false | false | false | false |
FrancisBaileyH/Swift-Sociables | Sociables/GameViewController.swift | 1 | 7829 | //
// ViewController.swift
// Sociables
//
// Created by Francis Bailey on 2015-03-08.
//
//
import UIKit
class GameViewController: UIViewController, NavControllerDelegate, SettingsDelegate {
@IBOutlet weak var cardImage : UIImageView!
@IBOutlet weak var topRank: UILabel!
@IBOutlet weak var bottomRank: UILabel!
@IBOutlet weak var topSuit: UIImageView!
@IBOutlet weak var bottomSuit: UIImageView!
@IBOutlet weak var cardCount: UILabel!
@IBOutlet weak var cardRule : UILabel!
@IBOutlet weak var cardTitle : UILabel!
let deck = CardDeck.sharedInstance
let rules = RuleManager.sharedInstance
let settings = Settings.sharedInstance
var newGame: Bool = true
var delaySettings: Bool = false
let redTextColor = UIColor(red: 230, green: 0, blue: 0, alpha: 1)
override func viewDidLoad() {
super.viewDidLoad()
bottomRank.layer.setAffineTransform(CGAffineTransformMakeRotation(CGFloat(M_PI)))
bottomSuit.layer.setAffineTransform(CGAffineTransformMakeRotation(CGFloat(M_PI)))
deck.setDeckBias(settings.getBias())
deck.setDeckSize(settings.getDeckSize())
deck.buildDeck()
let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector( "handleCardSwipe:"))
let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector( "handleCardSwipe:"))
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("handleCardTap:"))
leftSwipe.direction = .Left
rightSwipe.direction = .Right
cardImage.userInteractionEnabled = true;
view.addGestureRecognizer( leftSwipe )
view.addGestureRecognizer( rightSwipe )
cardImage.addGestureRecognizer(tapGesture)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "settingsDidChange", name: settings.notificationKey, object: nil)
let nav = self.navigationController as? NavController
nav?.customDelegate = self
}
/*
* Handle menu button press in UI
*/
@IBAction func toggleMenu(action: AnyObject) {
toggleSideMenuView()
}
/*
* Used to catch events fired from the menu
*/
func menuEventDidFire(action: AnyObject) {
let event = action as! String
if event == "New Game" {
self.startNewGame()
}
}
/*
* Handles the tap gesture on a card image
*/
func handleCardTap( sender: UITapGestureRecognizer ) {
let card: Card?
if sender.state == .Ended {
card = self.deck.oneOffTheTop()
if let c = card {
updateCardView(c)
}
else if self.deck.endOfDeck {
showGameOverAlert()
}
}
}
/*
* Update all UI elements for the game view
*/
func updateCardView( card: Card ) {
if newGame {
self.cardImage.image = UIImage(named: "blank-card")
newGame = false
}
let textColor: UIColor!
let suit : String! = card.suit
let img = UIImage(named: suit.lowercaseString)
var rank : String! = card.rank
let rule = rules.getRule(rank)
if (rank?.toInt() == nil) {
rank = rank.substringToIndex(advance(rank.startIndex, 1)).capitalizedString
}
if suit == "Hearts" || suit == "Diamonds" {
textColor = redTextColor
}
else {
textColor = UIColor.blackColor()
}
self.topSuit.image = img
self.bottomSuit.image = img
self.topRank.text = rank
self.bottomRank.text = rank
self.topRank.textColor = textColor
self.bottomRank.textColor = textColor
self.cardTitle.textColor = textColor
self.cardRule.textColor = textColor
self.cardTitle.text = rule.rule.title
self.cardRule.text = rule.rule.explanation
self.cardCount.textColor = textColor
self.cardCount.text = "\(self.deck.getDeckPtr() + 1)/\(self.deck.getDeckSize())"
}
/*
* When a swipe event is fired, run appropriate actions against card deck
*/
func handleCardSwipe( sender: UISwipeGestureRecognizer )
{
var card : Card?
if sender.direction == .Left
{
card = self.deck.oneOffTheTop()
}
else if sender.direction == .Right
{
card = self.deck.returnToTop()
}
else if sender.state == .Ended {
card = self.deck.oneOffTheTop()
}
if let c = card {
updateCardView(c)
}
else if sender.direction == .Left && self.deck.endOfDeck {
showGameOverAlert()
}
}
/*
* Initialize and show alert corresponding to the end of a game
*/
func showGameOverAlert() {
var alert = UIAlertController(title: "Gameover!", message: "You've reached the end of the deck. Did you want to play another round?", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: handleNewGameOkayButtonPressed))
self.presentViewController(alert, animated: true, completion: nil)
}
/*
func showSettingsChangedPrompt() {
var alert = UIAlertController(title: "Settings Changed", message: "Game settings have changed while a game was in progress. Do you want to apply the settings now and start a new game?", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: handleSettingsPromptAction))
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: handleSettingsPromptAction))
self.presentViewController(alert, animated: true, completion: nil)
}
func handleSettingsPromptAction( action: UIAlertAction? ) {
if action?.title == "Okay" {
self.startNewGame()
} else {
delaySettings = true
}
}*/
/*
* When settings have changed, this function is called automatically
* updating the deck with the latest changes
*/
func settingsDidChange() {
/*if !newGame {
//showSettingsChangedPrompt()
} else {
updateDeckSettings()
}*/
updateDeckSettings()
startNewGame()
}
func updateDeckSettings() {
self.deck.setDeckBias(settings.getBias())
self.deck.setDeckSize(settings.getDeckSize())
self.deck.buildDeck()
}
/*
* Method that handles button press from UIAlertController
*/
func handleNewGameOkayButtonPressed( action: UIAlertAction? ) {
self.startNewGame()
}
func startNewGame()
{
if delaySettings {
updateDeckSettings()
delaySettings = false
}
self.cardImage.image = UIImage(named: "start-card")
self.deck.shuffle()
self.topRank.text = ""
self.bottomRank.text = ""
self.bottomSuit.image = nil
self.topSuit.image = nil
self.cardRule.text = ""
self.cardTitle.text = ""
self.cardCount.text = ""
newGame = true
}
}
| gpl-3.0 | b923f6761b2cde373def410df87dc2af | 27.677656 | 239 | 0.58973 | 4.955063 | false | false | false | false |
wilfreddekok/Antidote | Antidote/Results.swift | 1 | 2308 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import Foundation
/// Swift wrapper for RLMResults
class Results<T: OCTObject> {
private let results: RLMResults
var count: Int {
get {
return Int(results.count)
}
}
var firstObject: T {
get {
return results.firstObject() as! T
}
}
var lastObject: T {
get {
return results.lastObject() as! T
}
}
init(results: RLMResults) {
let name = NSStringFromClass(T.self)
assert(name == results.objectClassName, "Specified wrong generic class")
self.results = results
}
func indexOfObject(object: T) -> Int {
return Int(results.indexOfObject(object))
}
func sortedResultsUsingProperty(property: String, ascending: Bool) -> Results<T> {
let sortedResults = results.sortedResultsUsingProperty(property, ascending: ascending)
return Results<T>(results: sortedResults)
}
func sortedResultsUsingDescriptors(properties: Array<RLMSortDescriptor>) -> Results<T> {
let sortedResults = results.sortedResultsUsingDescriptors(properties)
return Results<T>(results: sortedResults)
}
func addNotificationBlock(block: ResultsChange<T> -> Void) -> RLMNotificationToken {
return results.addNotificationBlock { rlmResults, changes, error in
if let error = error {
block(ResultsChange.Error(error))
return
}
let results: Results<T>? = (rlmResults != nil) ? Results<T>(results: rlmResults!) : nil
if let changes = changes {
block(ResultsChange.Update(results,
deletions: changes.deletions as! [Int],
insertions: changes.insertions as! [Int],
modifications: changes.modifications as! [Int]))
return
}
block(ResultsChange.Initial(results))
}
}
subscript(index: Int) -> T {
return results[UInt(index)] as! T
}
}
| mpl-2.0 | 20cb43c60eb1ee57c612a8fc9a2fd20f | 30.189189 | 99 | 0.585789 | 4.838574 | false | false | false | false |
yichizhang/YZKeyboardInputAccessoryView | Source/YZKeyboardInputAccessoryView.swift | 1 | 7930 | //
// YZKeyboardInputAccessoryView.swift
// NumberKeyboardViewDemo
//
// Created by Yichi on 12/03/2015.
// Copyright (c) 2015 Yichi. All rights reserved.
//
import Foundation
import UIKit
struct YZKeyboardConstants {
init(keyboardSize: CGSize, useCalculatedWidth: Bool = true, maxInRow: Int = 10, useCalculatedHeight: Bool = false) {
var keyHeight:CGFloat = 0
var keyWidth:CGFloat = 0
var topInset:CGFloat = 0
var sideInset:CGFloat = 0
switch keyboardSize.width {
case 320:
// iPhone 5 or older
spaceInBetweenKeys = 6
spaceInBetweenRows = 15
keyWidth = 26
keyHeight = 39
topInset = 12
sideInset = 3
case 375:
// iPhone 6
spaceInBetweenKeys = 6
spaceInBetweenRows = 11
keyWidth = 31.5
keyHeight = 43 // = width * 0.115
topInset = 10
sideInset = 3
case 414:
// iPhone 6 Plus or larger
spaceInBetweenKeys = 6
spaceInBetweenRows = 10
keyWidth = 35
keyHeight = 46 // = width * 0.111
topInset = 8
sideInset = 4
case 480:
// iPhone 4 landscape
spaceInBetweenKeys = 6
spaceInBetweenRows = 7
keyWidth = 42
keyHeight = 33
topInset = 5
sideInset = 3
case 568:
// iPhone 5 landscape
spaceInBetweenKeys = 5
spaceInBetweenRows = 7
keyWidth = 51
keyHeight = 33
topInset = 5
sideInset = 3
case 667...736:
// iPhone 6 landscape and iPhone 6 Plus landscape
spaceInBetweenKeys = 5
spaceInBetweenRows = 7
keyWidth = 48
keyHeight = 33
topInset = 6
sideInset = 3
default:
spaceInBetweenKeys = 6
spaceInBetweenRows = 15
keyWidth = 0
keyHeight = 39
topInset = 12
sideInset = 3
}
keyboardInset = UIEdgeInsets(top: topInset, left: sideInset, bottom: sideInset, right: sideInset)
if useCalculatedWidth || keyWidth == 0 {
let keysCount = CGFloat(maxInRow)
keyWidth = ( (keyboardSize.width - keyboardInset.left - keyboardInset.right) - (keysCount - 1) * spaceInBetweenKeys ) / keysCount
}
if useCalculatedHeight {
// Doesn't work
let rowsCount = CGFloat(4)
keyHeight = ( (keyboardSize.height - keyboardInset.top - keyboardInset.bottom) - (rowsCount - 1) * spaceInBetweenRows ) / rowsCount
}
keySize = CGSize(width: keyWidth, height: keyHeight)
}
var spaceInBetweenKeys:CGFloat = 0
var keyboardInset = UIEdgeInsetsZero
var spaceInBetweenRows:CGFloat = 0
var keySize = CGSizeZero
}
class YZNumberKeyboardInputAccessoryView : YZKeyboardInputAccessoryView {
init() {
let begin = 1, end = 10
var keys:[String] = Array()
for i in begin...end {
keys.append("\(i%10)")
}
super.init(keys: keys)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class YZKeyboardInputAccessoryView : UIView, UIInputViewAudioFeedback {
weak var textField:UITextField?
weak var textView:UITextView?
var numberKeyButtons:[CYRKeyboardButton] = Array()
var numberKeyButtonsContainerView = UIView()
var keyboardConstants = YZKeyboardConstants(keyboardSize: CGSizeZero)
class func heightWith(keyboardConstants c:YZKeyboardConstants, extraHeight:CGFloat = 9) -> CGFloat {
return (c.spaceInBetweenRows - c.keyboardInset.top) + c.keySize.height + c.keyboardInset.top + extraHeight
}
lazy var dismissTouchArea:UIView = {
let v = UIImageView(image: YZKeyboardStyle.imageOfArrowLight)
v.contentMode = UIViewContentMode.Center
v.backgroundColor = UIColor(red:0.684, green:0.700, blue:0.724, alpha:1.000)
v.userInteractionEnabled = true
return v
}()
var dismissTouchAreaHeight:CGFloat = 9
var keyboardBackgroundColor:UIColor {
return UIColor(red:0.784, green:0.800, blue:0.824, alpha:1.000)
}
// MARK: UIInputViewAudioFeedback
var enableInputClicksWhenVisible:Bool {
return true
}
// MARK: Attach to a text input.
func attachTo(#textInput:UITextInput) {
textField = nil
textView = nil
if(textInput.isKindOfClass(UITextField)) {
var t = textInput as! UITextField
t.inputAccessoryView = self
textField = t
}
else if(textInput.isKindOfClass(UITextView)) {
var t = textInput as! UITextView
t.inputAccessoryView = self
textView = t
}
}
// MARK: Init methods
init(keys:[String]) {
var frame = CGRectZero
switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) {
case .OrderedSame, .OrderedDescending:
// iOS >= 8.0
break
case .OrderedAscending:
// iOS < 8.0
let c = YZKeyboardConstants(keyboardSize: UIScreen.mainScreen().bounds.size)
frame.size.height = YZKeyboardInputAccessoryView.heightWith(keyboardConstants: c)
break
}
super.init(frame: frame)
backgroundColor = keyboardBackgroundColor
addSubview(numberKeyButtonsContainerView)
numberKeyButtonsContainerView.backgroundColor = keyboardBackgroundColor
for key in keys{
let b = CYRKeyboardButton()
b.addTarget(self, action: "numberKeyTapped:", forControlEvents: .TouchUpInside)
b.input = key
numberKeyButtons.append(b)
numberKeyButtonsContainerView.addSubview(b)
}
dismissTouchArea.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "dissmissButtonTapped:"))
addSubview(dismissTouchArea)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: Set up layout
override func layoutSubviews() {
superview?.layoutSubviews()
configureSubviewFrames()
}
private func configureSubviewFrames() {
dismissTouchArea.frame = CGRect(
x: 0,
y: 0,
width: bounds.width,
height: dismissTouchAreaHeight
)
let keyCount = CGFloat(numberKeyButtons.count)
let c = keyboardConstants
let inset = c.keyboardInset
var lastX:CGFloat = 0
for (index, keyButton) in enumerate(numberKeyButtons) {
let i = CGFloat(index)
let x = (c.spaceInBetweenKeys + c.keySize.width) * i
keyButton.frame = CGRect(
origin: CGPoint(x: x, y: 0),
size: c.keySize
)
lastX = x
}
let keysWidth = lastX + c.keySize.width
numberKeyButtonsContainerView.frame = CGRect(
origin: CGPoint(x: bounds.midX - keysWidth / 2, y: dismissTouchAreaHeight + inset.top ),
size: CGSize(width: keysWidth, height: c.keySize.height)
)
}
func configureHeightConstraint() {
if let viewConstraints = constraints() as? [NSLayoutConstraint] {
if let constraint = viewConstraints.first {
constraint.constant = YZKeyboardInputAccessoryView.heightWith(keyboardConstants: keyboardConstants, extraHeight: dismissTouchAreaHeight)
}
}
}
// MARK: Keyboard show
func keyboardWillShow(notification:NSNotification) {
configureKeyboardConstantsAndViewHeightUsing(notification)
setNeedsLayout()
}
func keyboardWillChangeFrame(notification:NSNotification) {
configureKeyboardConstantsAndViewHeightUsing(notification)
}
private func configureKeyboardConstantsAndViewHeightUsing(notification:NSNotification) {
if let info = notification.userInfo {
if let keyboardSize = info[UIKeyboardFrameBeginUserInfoKey]?.CGRectValue().size {
keyboardConstants = YZKeyboardConstants(keyboardSize: keyboardSize, useCalculatedWidth: false)
}
}
configureHeightConstraint()
}
// MARK: Dissmiss button tapped.
func dissmissButtonTapped(sender:AnyObject) {
textField?.resignFirstResponder()
textView?.resignFirstResponder()
}
// MARK: Number button tapped
func numberKeyTapped(sender:CYRKeyboardButton) {
self.textView?.insertText(sender.input)
self.textField?.insertText(sender.input)
}
}
| mit | 19660458e68adcfb157c0ee3b41d8f77 | 25.258278 | 152 | 0.717781 | 3.814334 | false | false | false | false |
roytornado/Flow-iOS | Flow/Classes/Flow.swift | 1 | 9054 | import Foundation
public typealias FlowWillStartBlock = (Flow) -> Void
public typealias FlowDidFinishBlock = (Flow) -> Void
public class Flow {
private static var runningFlow = [String: Flow]()
final private let identifier = UUID().uuidString
let internalLoggingQueue = OperationQueue()
let internalCallbackQueue = OperationQueue()
let internalOperationQueue = OperationQueue()
private var rootNode = FlowOperationTreeNode()
private var currentAddedNode: FlowOperationTreeNode!
private var currentCasesRootNode: FlowOperationTreeNode?
private var currentRunningNode: FlowOperationTreeNode?
public var dataBucket = [String: Any]()
public var isSuccess = true
public var error: Error?
private var willStartBlock: FlowWillStartBlock?
private var didFinishBlock: FlowDidFinishBlock?
private var logs = [String]()
var isStopping = false
var isRunning: Bool { return Flow.runningFlow[identifier] != nil }
private func free() {
Flow.runningFlow[self.identifier] = nil
}
public init() {
Flow.runningFlow[identifier] = self
setup()
}
func setup() {
internalLoggingQueue.name = "LoggingQueue"
internalLoggingQueue.qualityOfService = .userInteractive
internalLoggingQueue.maxConcurrentOperationCount = 1
internalCallbackQueue.maxConcurrentOperationCount = 1
internalOperationQueue.maxConcurrentOperationCount = 1
internalOperationQueue.qualityOfService = .userInteractive
currentAddedNode = rootNode
}
@discardableResult public func setDataBucket(dataBucket: [String: Any]) -> Flow {
self.dataBucket = dataBucket
return self
}
@discardableResult public func setWillStartBlock(block: @escaping FlowWillStartBlock) -> Flow {
willStartBlock = block
return self
}
@discardableResult public func setDidFinishBlock(block: @escaping FlowDidFinishBlock) -> Flow {
didFinishBlock = block
return self
}
@discardableResult public func add(operation: FlowOperation, flowCase: FlowCase? = nil) -> Flow {
let node = FlowOperationTreeNode(singleOperation: operation)
if let flowCase = flowCase { node.flowCase = flowCase }
addNodeToTree(node: node)
return self
}
@discardableResult public func combine() -> Flow {
combineCases()
return self
}
@discardableResult public func addGrouped(operationCreator: FlowOperationCreator.Type, dispatcher: FlowGroupDispatcher) -> Flow {
let node = FlowOperationTreeNode(operationCreator: operationCreator, dispatcher: dispatcher)
addNodeToTree(node: node)
return self
}
public func start() {
var dataLog = "[DataBucket] start with:"
dataBucket.forEach { key, value in
dataLog += "\n\(key): \(value)"
}
log(message: dataLog)
callWillStartBlockAtMain()
currentRunningNode = rootNode
pickOperationToRun()
}
public func operationWillStart(operation: FlowOperation) {
log(message: "\(operation.displayName) WillStart")
internalCallbackQueue.addOperation {
self.internalOperationWillStart(operation: operation)
}
}
private func internalOperationWillStart(operation: FlowOperation) {
}
public func operationDidFinish(operation: FlowOperation, type: FlowOperationStateFinishType) {
if isStopping { return }
internalCallbackQueue.addOperation {
self.internalOperationDidFinish(operation: operation, type: type)
}
}
private func internalOperationDidFinish(operation: FlowOperation, type: FlowOperationStateFinishType) {
if isStopping { return }
switch type {
case .successfully:
log(message: "\(operation.displayName) DidFinish: successfully")
continuingCaseHandling(operation: operation)
break
case .withError(let error):
log(message: "\(operation.displayName) DidFinish: withError: \(error)")
self.error = error
stopingCaseHandling(operation: operation)
break
case .withInsufficientInputData(let message):
log(message: "\(operation.displayName) DidFinish: withInsufficientInputData: \(message)")
stopingCaseHandling(operation: operation)
break
case .withMismatchInputDataType(let message):
log(message: "\(operation.displayName) DidFinish: withMismatchInputDataType: \(message)")
stopingCaseHandling(operation: operation)
break
}
}
private func stopingCaseHandling(operation: FlowOperation) {
let currentNode = currentRunningNode!
if currentNode.isGroup {
if !currentNode.dispatcher.allowFailure {
log(message: "[Group] not allow failure in group. stop immediately.")
internalOperationQueue.cancelAllOperations()
isSuccess = false
callDidFinishBlockAtMain()
} else {
continuingCaseHandling(operation: operation)
}
} else {
isSuccess = false
callDidFinishBlockAtMain()
}
}
private func continuingCaseHandling(operation: FlowOperation) {
let currentNode = currentRunningNode!
if currentNode.isGroup {
currentNode.postGroupOperation(flow: self, operation: operation)
if !currentNode.isFinished {
return
}
}
pickOperationToRun()
}
public func setData(name: String, value: Any) {
if let data = dataBucket[name] {
log(message: "[DataBucket] replace for \(name): \(data) -> \(value)")
} else {
log(message: "[DataBucket] add for \(name): \(value)")
}
dataBucket[name] = value
}
// MARK: Private
private func addNodeToTree(node: FlowOperationTreeNode) {
if node.flowCase != nil {
if let currentCasesRootNode = currentCasesRootNode {
currentCasesRootNode.childNodes.append(node)
} else {
currentCasesRootNode = currentAddedNode
currentAddedNode.childNodes.append(node)
}
} else {
currentAddedNode.childNodes.append(node)
}
currentAddedNode = node
}
private func combineCases() {
if let currentCasesRootNode = currentCasesRootNode {
let dummyNode = FlowOperationTreeNode()
currentAddedNode = dummyNode
let leaves = currentCasesRootNode.findAllLeaves()
for leaf in leaves {
leaf.childNodes = [dummyNode]
}
}
currentCasesRootNode = nil
}
private func pickOperationToRun() {
var nextNode: FlowOperationTreeNode?
let lastNode = currentRunningNode!
if lastNode.childNodes.count == 1 {
nextNode = lastNode.childNodes[0]
} else if lastNode.childNodes.count > 1 {
for child in lastNode.childNodes {
if let flowCase = child.flowCase, let caseValue = dataBucket[flowCase.key] as? String, caseValue == flowCase.value! {
nextNode = child
break
}
}
if nextNode == nil {
log(message: "[Cases] no case is matached. finished in early.")
}
}
guard let targetNode = nextNode else {
callDidFinishBlockAtMain()
return
}
currentRunningNode = targetNode
if let singleOperation = targetNode.singleOperation {
internalOperationQueue.maxConcurrentOperationCount = 1
singleOperation.flowManager = self
internalOperationQueue.addOperation(singleOperation)
} else if targetNode.isGroup {
internalOperationQueue.maxConcurrentOperationCount = targetNode.dispatcher.maxConcurrentOperationCount
let operations = targetNode.createGroupOperations(flow: self)
operations.forEach() { operation in
operation.flowManager = self
internalOperationQueue.addOperation(operation)
}
if operations.count == 0 {
log(message: "[Group] no operation to run for group; please make sure the input data: <\(targetNode.dispatcher.inputKey!)> is not empty")
isSuccess = false
callDidFinishBlockAtMain()
}
} else if targetNode.isDummyNode {
pickOperationToRun()
}
}
private func callWillStartBlockAtMain() {
DispatchQueue.main.async { [weak self] in
if let me = self {
me.willStartBlock?(me)
}
}
}
private func callDidFinishBlockAtMain() {
isStopping = true
var dataLog = "[DataBucket] end with:"
dataBucket.forEach { key, value in
dataLog += "\n\(key): \(value)"
}
log(message: dataLog)
internalLoggingQueue.waitUntilAllOperationsAreFinished()
DispatchQueue.main.async {
self.didFinishBlock?(self)
self.free()
}
}
// MARK: Log & Summary
public func log(message: String) {
internalLoggingQueue.addOperation {
self.internalLog(message: message)
}
}
private func internalLog(message: String) {
let df = DateFormatter()
df.timeStyle = .medium
let time = df.string(from: Date())
logs.append("\(time) \(message)")
}
public func generateSummary() -> String {
var summary = ""
summary += "====== Flow Summary ======" + "\n"
logs.forEach { summary += $0 + "\n" }
summary += "Flow isSuccess: \(isSuccess)\n"
summary += "====== Ending ======" + "\n"
return summary
}
}
| mit | a3c1102eadd948de34152c3d610828a4 | 30.768421 | 145 | 0.687873 | 4.617032 | false | false | false | false |
shuoli84/RxSwift | RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift | 3 | 2858 | //
// RxTableViewDataSourceProxy.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/15/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
let tableViewDataSourceNotSet = TableViewDataSourceNotSet()
class TableViewDataSourceNotSet : NSObject
, UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return rxAbstractMethodWithMessage(dataSourceNotSet)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rxAbstractMethodWithMessage(dataSourceNotSet)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return rxAbstractMethodWithMessage(dataSourceNotSet)
}
}
// Please take a look at `DelegateProxyType.swift`
class RxTableViewDataSourceProxy : DelegateProxy
, UITableViewDataSource
, DelegateProxyType {
unowned let tableView: UITableView
unowned var dataSource: UITableViewDataSource = tableViewDataSourceNotSet
required init(parentObject: AnyObject) {
self.tableView = parentObject as! UITableView
super.init(parentObject: parentObject)
}
// data source delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.dataSource.numberOfSectionsInTableView?(tableView) ?? 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.tableView(tableView, numberOfRowsInSection: section)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return self.dataSource.tableView(tableView, cellForRowAtIndexPath: indexPath)
}
// proxy
override class func delegateAssociatedObjectTag() -> UnsafePointer<Void> {
return _pointer(&dataSourceAssociatedTag)
}
class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) {
let collectionView: UITableView = castOrFatalError(object)
collectionView.dataSource = castOptionalOrFatalError(delegate)
}
class func currentDelegateFor(object: AnyObject) -> AnyObject? {
let collectionView: UITableView = castOrFatalError(object)
return collectionView.dataSource
}
override func setForwardToDelegate(forwardToDelegate: AnyObject?, retainDelegate: Bool) {
let dataSource: UITableViewDataSource? = castOptionalOrFatalError(forwardToDelegate)
self.dataSource = dataSource ?? tableViewDataSourceNotSet
super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate)
}
} | mit | d976d35a26189efcff93db495bd5b675 | 35.189873 | 109 | 0.713086 | 6.351111 | false | false | false | false |
manGoweb/BLE | Example/BLE/ViewController.swift | 1 | 3640 | //
// ViewController.swift
// BLE
//
// Created by Ondrej Rafaj on 04/03/2016.
// Copyright (c) 2016 Ondrej Rafaj. All rights reserved.
//
import UIKit
import SnapKit
import CoreBluetooth
import BLE
struct BLEUUIDs {
internal static let RedBearDuoServiceUUID: String = "713D0000-503E-4C75-BA94-3148F18D941E"
internal static let RedBearDuoWriteUUID: String = "713D0003-503E-4C75-BA94-3148F18D941E"
internal static let RedBearDuoReadUUID: String = "713D0002-503E-4C75-BA94-3148F18D941E"
}
class ViewController: UIViewController, BLEDelegate {
private let ble: BLE = BLE()
private let scanButton: UIButton = UIButton()
private let scanRedBearDuoButton: UIButton = UIButton()
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Enable debug mode
self.ble.debugMode = true
// Set delegate
self.ble.delegate = self
// Create interface
self.createInterface()
}
// MARK: Actions
private func enableButtons(enable: Bool) {
}
internal func didPressScanButton(sender: UIButton) {
// Start scanning
self.ble.startScanning(10) // Scan for 10 seconds
}
internal func didPressScanRBDButton(sender: UIButton) {
// Start scanning
self.ble.startScanning(10, serviceUUIDs: [BLEUUIDs.RedBearDuoServiceUUID]) // Scan for 10 seconds
}
// MARK: BLE delegate methods
func bleDidFinishScanning(ble: BLE) {
}
func bleDidUpdateState(ble: BLE, state: CBCentralManagerState) {
}
func bleDidConnectToPeripheral(ble: BLE, peripheral: CBPeripheral) {
}
func bleDidDiscoverPeripherals(ble: BLE, peripherals: [CBPeripheral]) {
for peripheral: CBPeripheral in peripherals {
// Connect to peripheral
self.ble.connectToPeripheral(peripheral)
}
}
func bleFailedConnectToPeripheral(ble: BLE, peripheral: CBPeripheral) {
}
func bleDidDisconnectFromPeripheral(ble: BLE, peripheral: CBPeripheral) {
}
func bleDidReceiveData(ble: BLE, peripheral: CBPeripheral, characteristic: String, data: NSData?) {
}
// MARK: Create interface
private func createInterface() {
// Creating basic scan button
self.scanButton.setTitle("Scan (results in console)", forState: .Normal)
self.scanButton.backgroundColor = UIColor.lightGrayColor()
self.scanButton.addTarget(self, action: #selector(ViewController.didPressScanButton(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(self.scanButton)
self.scanButton.snp_makeConstraints { (make) in
make.top.left.equalTo(40)
make.right.equalTo(-40)
make.height.equalTo(44)
}
// Create connect to redbear button
self.scanRedBearDuoButton.setTitle("Scan & connect to RedBear Duo", forState: .Normal)
self.scanRedBearDuoButton.backgroundColor = UIColor.lightGrayColor()
self.scanRedBearDuoButton.addTarget(self, action: #selector(ViewController.didPressScanRBDButton(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(self.scanRedBearDuoButton)
self.scanRedBearDuoButton.snp_makeConstraints { (make) in
make.top.equalTo(self.scanButton.snp_bottom).offset(20)
make.left.equalTo(40)
make.right.equalTo(-40)
make.height.equalTo(44)
}
}
}
| mit | 1367c1ac8d2d23f7e2f972af0bcb9674 | 28.12 | 144 | 0.643407 | 4.493827 | false | false | false | false |
pmark/MartianRover | Playgrounds/MyPlayground4.playground/Contents.swift | 1 | 4021 | import Cocoa // (or UIKit for iOS)
import SceneKit
import QuartzCore // for the basic animation
import XCPlayground // for the live preview
// create a scene view with an empty scene
let sceneSize = 700
var sceneView = SCNView(frame: CGRect(x: 0, y: 0, width: sceneSize, height: sceneSize))
var scene = SCNScene()
sceneView.scene = scene
sceneView.backgroundColor = NSColor.darkGrayColor()
sceneView.autoenablesDefaultLighting = true
// start a live preview of that view
XCPShowView("The Scene View!", sceneView)
/*
// a geometry object
var torus = SCNTorus(ringRadius: 3, pipeRadius: 1)
var torusNode = SCNNode(geometry: torus)
scene.rootNode.addChildNode(torusNode)
// configure the geometry object
torus.firstMaterial?.diffuse.contents = NSColor.yellowColor() // (or UIColor on iOS)
torus.firstMaterial?.specular.contents = NSColor.yellowColor() // (or UIColor on iOS)
// set a rotation axis (no angle) to be able to
// use a nicer keypath below and avoid needing
// to wrap it in an NSValue
torusNode.rotation = SCNVector4(x: 1.0, y: 0.0, z: 0.0, w: 0.0)
// animate the rotation of the torus
var spin = CABasicAnimation(keyPath: "rotation.w") // only animate the angle
spin.toValue = 2.0*M_PI
spin.duration = 1.5
spin.repeatCount = HUGE // for infinity
torusNode.addAnimation(spin, forKey: "spin around")
*/
let tileSize:CGFloat = 1.0
let duration:CFTimeInterval = 5
var colorToggle = false
for x in -4...3 {
colorToggle = (x % 2 == 0) ? true : false
for y in -4...3 {
var extra = CGFloat((abs(x)+abs(y))/3)
var cube = SCNBox(
width: tileSize,
height: tileSize,
length: tileSize,
chamferRadius: 0)
var cubeNode = SCNNode(geometry: cube)
cubeNode.position.x = CGFloat(x * Int(tileSize*2) + 1);
cubeNode.position.y = CGFloat(y * Int(tileSize*2) + 1);
// cubeNode.position.z = CGFloat(-extra*2.0);
cube.firstMaterial?.diffuse.contents = (colorToggle ? NSColor.blackColor() : NSColor.redColor())
cube.firstMaterial?.specular.contents = NSColor.whiteColor()// (colorToggle ? NSColor.redColor() : NSColor.whiteColor())
colorToggle = !colorToggle
cubeNode.rotation = SCNVector4(x: 1, y: 1, z: 0.0, w: 0.0)
var spin = CABasicAnimation(keyPath: "rotation.w") // only animate the angle
spin.fromValue = -M_PI*2.0
spin.toValue = M_PI*2.0
spin.duration = duration + CFTimeInterval(abs(x)+abs(y))
spin.autoreverses = false
spin.repeatCount = HUGE // for infinity
cubeNode.addAnimation(spin, forKey: "spin around")
scene.rootNode.addChildNode(cubeNode)
}
}
// a camera
var camera = SCNCamera()
var cameraNode = SCNNode()
cameraNode.camera = camera
cameraNode.position = SCNVector3(
x: 0, y: 0, z: 15)
camera.automaticallyAdjustsZRange = true
scene.rootNode.addChildNode(cameraNode)
cameraNode.rotation = SCNVector4(
x: 0,
y: 0, z: -1.0, w: 0.0)
//var camspin = CABasicAnimation(keyPath: "rotation.w")
//camspin.fromValue = 0
//camspin.toValue = 2 * M_PI
//camspin.duration = duration*2
//camspin.autoreverses = false
//camspin.repeatCount = HUGE // for infinity
//cameraNode.addAnimation(camspin, forKey: "group")
//
//var fly = CABasicAnimation(keyPath: "position.x")
//fly.fromValue = -5
//fly.toValue = 5
//fly.duration = duration
//fly.autoreverses = true
//fly.repeatCount = HUGE // for infinity
//cameraNode.addAnimation(fly, forKey: "group")
//var g = CAAnimationGroup()
//g.animations = [camspin]
//cameraNode.addAnimation(g, forKey: "group")
let move:SCNAction = SCNAction.moveByX(0, y: 0, z: -30, duration: duration)
let rot:SCNAction = SCNAction.rotateByAngle(3.14, aroundAxis: SCNVector3(x: 0, y: -1, z: 0), duration: duration)
let r = SCNAction.reversedAction(move)
let g = SCNAction.group([move, rot])
let sequence = SCNAction.sequence([g, g.reversedAction()])
cameraNode.runAction(SCNAction.repeatActionForever(sequence))
| mit | 0e6665956c6c0b9072ff217093fe26b2 | 31.691057 | 128 | 0.681423 | 3.599821 | false | false | false | false |
RaylnJiang/Swift_Learning_Project | Second Chapter-集合类型/Second Chapter-集合类型/集合类型/集合.playground/Contents.swift | 1 | 6455 | //: Playground - noun: a place where people can play
import UIKit
/* 集合 */
/* -------------------------------------------------------------------
集合(Set)用来存储相同类型并且没有确定顺序的值。
当集合元素顺序不重要时或希望确保每个元素只出现一次时可以使用集合而不是数组。
------------------------------------------------------------------ */
/* 集合类型的哈希值 */
/* -------------------------------------------------------------------
一个类型为了存储在集合中,该类型必须是可哈希化的,也就是说,该类型必须提供一个方法
来计算它的哈希值。
一个哈希值时Int类型的,相等的对象哈希值必须相同:a == b,
因此a.hashValue == b.hashValue
Swift所有基本数据类型(String、Int、Double、Bool)默认都是可以哈希化的,
可以作为集合的值的类型或字典的键的类型。
没有关联值的枚举成员值默认也是可以哈希化的(在枚举处有讲)
------------------------------------------------------------------ */
/* 集合类型语法 */
/* -------------------------------------------------------------------
Swift中的Set类型被写为Set<Element>,这里的Element表示Set中允许存储的类型,
和数组不同的是,集合没有等价的简化形式。
------------------------------------------------------------------ */
/* 创建和构造一个空的集合 */
/* -------------------------------------------------------------------
可以通过构造器语法创建一个特定类型的空集合。
注意:
通过构造器,这里的letters变量的类型被推断为Set<Character>
可以通过一个空的数组字面量创建一个空的Set
------------------------------------------------------------------ */
var letters = Set<Character>()
print("letters' characters count = \(letters.count)")
letters.insert("a")
print("\(letters)")
letters = []
/* 用数组字面量创建一个集合 */
/* -------------------------------------------------------------------
可以通过数组字面量来构造集合,并可以使用简化形式写一个或多个值作为集合元素。
如果你想使用一个数组字面量构造一个Set并且该数组字面量中的所有元素类型相同,
那么你无需写出Set的具体类型。
------------------------------------------------------------------ */
var homeSet: Set<String> = ["Jsl", "lj"]
var homeSet_B: Set = ["jsl", "lj", "son", "daughter"]
/* 访问和修改一个集合 */
/* -------------------------------------------------------------------
可以通过Set的属性和方法来修改一个Set。
可以使用其只读属性count,找出一个Set中元素的数量。
可以使用布尔属性isEmpty作为一个缩写形式去检查count属性是否为0。
可以使用Set的insert(_:)方法来添加一个新元素。
可以通过Set的remove(_:)方法删除一个元素,如果该值是该Set的一个元素则删除该元素
并且返回被删除的元素的值,否则如果该Set不包含该值,则返回nil。
可以通过removeAll()方法删除Set中的所有元素。
可以使用contains(_:)方法检查Set中是否包含一个特定的值。
------------------------------------------------------------------ */
print("homeSet_B's members count = \(homeSet_B.count)")
if homeSet_B.isEmpty {
print("家里没人")
} else {
print("家里有人")
}
homeSet_B.insert("pet Dog")
print("\(homeSet_B)")
homeSet_B.removeAll()
print(homeSet_B)
var homeSet_C: Set<String> = ["father", "mother", "me"]
if homeSet_C.contains("me") {
print("我在家")
} else {
print("我不在家")
}
/* 遍历一个集合 */
/* -------------------------------------------------------------------
可以在for-in循环中遍历一个Set中的所有值。
------------------------------------------------------------------ */
var fruiteSet: Set = ["apple", "banana", "orange"]
for fruite in fruiteSet {
print("fruite = \(fruite)")
}
/* 集合操作 */
/* -------------------------------------------------------------------
可以高效的完成Set的一些基本操作,比如把两个集合组合到一起,判断两个集合共有元素,
或者判断两个集合是否全包含、部分包含或者不相交。
基本集合操作:
使用intersect(_:)方法根据两个集合中都包含的值创建一个新的集合。
使用exclusiveOr(_:)方法根据在一个集合中但不在两个集合中的值创建一个新集合。
使用union(_:)方法根据两个集合的值创建一个新的集合。
使用subtract(_:)方法根据不在该集合中的值创建一个新的集合。
集合成员关系和相等:
使用“是否相等”运算符(==)来判断两个集合是否包含全部相同的值。
使用isSubsetOf:(_:)方法来判断一个集合中的值是否也被包含在另一个集合中。
使用isSupersetOf(_:)方法来判断一个集合中包含另一个集合中所有的值。
使用isStrictSubsetOf(_:)或者isStrictSupersetOf(_:)方法来判断一个集合
是否是另外一个集合的子集合或者父集合并且两个集合并不相等。
使用isDisjoinWith(_:)方法来判断两个集合是否不含有相同的值(是否没有交集)。
------------------------------------------------------------------ */
let jsSet: Set = [1, 3, 5, 7, 9]
let osSet: Set = [2, 4, 6, 8, 10]
let anotherSet: Set = [2, 3, 5, 7]
let jiaojiSet: Set = jsSet.intersect(anotherSet)
let exclusiveSet: Set = osSet.exclusiveOr(anotherSet)
let unionSet = jsSet.union(osSet).sort()
let jsSubtractSet = jsSet.subtract(anotherSet)
let anotherSubtractSet = anotherSet.subtract(jsSet)
let numberSet_A: Set = [1, 2, 3, 4, 5]
let numberSet_B: Set = [1, 2, 3]
let numberSet_B1: Set = [1, 2, 3]
let numberSet_C: Set = [4, 5, 6, 7, 8]
numberSet_B.isSubsetOf(numberSet_A)
numberSet_A.isSupersetOf(numberSet_B)
numberSet_B.isStrictSubsetOf(numberSet_A)
numberSet_A.isStrictSupersetOf(numberSet_B1)
numberSet_A.isDisjointWith(numberSet_C)
numberSet_B.isDisjointWith(numberSet_C)
| apache-2.0 | e67f2390c68d4aa100f25d1d59418a60 | 21.004926 | 70 | 0.49944 | 3.351088 | false | false | false | false |
quran/quran-ios | Sources/QuranTextKit/Search/Searchers/CompositeSearcher.swift | 1 | 3288 | //
// CompositeSearcher.swift
//
//
// Created by Mohamed Afifi on 2021-11-17.
//
import Foundation
import PromiseKit
import QuranKit
import TranslationService
import VLogging
public struct CompositeSearcher: AsyncSearcher {
private let simpleSearchers: [Searcher]
private let translationsSearcher: AsyncSearcher
init(quran: Quran,
quranVerseTextPersistence: VerseTextPersistence,
localTranslationRetriever: LocalTranslationsRetriever,
versePersistenceBuilder: @escaping (Translation, Quran) -> TranslationVerseTextPersistence)
{
let numberSearcher = NumberSearcher(quran: quran, quranVerseTextPersistence: quranVerseTextPersistence)
let quranSearcher = PersistenceSearcher(versePersistence: quranVerseTextPersistence, source: .quran)
let suraSearcher = SuraSearcher(quran: quran)
let translationSearcher = TranslationSearcher(
localTranslationRetriever: localTranslationRetriever,
versePersistenceBuilder: versePersistenceBuilder,
quran: quran
)
let simpleSearchers: [Searcher] = [numberSearcher, suraSearcher, quranSearcher]
self.simpleSearchers = simpleSearchers
translationsSearcher = translationSearcher
}
public init(databasesPath: String, quranFileURL: URL) {
let quran = Quran.madani
let persistence = SQLiteQuranVerseTextPersistence(quran: quran, fileURL: quranFileURL)
let localTranslationRetriever = TranslationService.LocalTranslationsRetriever(databasesPath: databasesPath)
self.init(quran: quran,
quranVerseTextPersistence: persistence,
localTranslationRetriever: localTranslationRetriever,
versePersistenceBuilder: { translation, quran in
SQLiteTranslationVerseTextPersistence(fileURL: translation.localURL, quran: quran)
})
}
public func autocomplete(term: String) -> Promise<[SearchAutocompletion]> {
logger.info("Autocompleting term: \(term)")
return DispatchQueue.global()
.async(.promise) {
try self.simpleSearchers.flatMap { try $0.autocomplete(term: term) }
}
.then { results -> Promise<[SearchAutocompletion]> in
if !results.isEmpty {
return .value(results)
}
return self.translationsSearcher.autocomplete(term: term)
}
.map { [SearchAutocompletion(text: term, term: term)] + $0 }
.map { $0.orderedUnique() }
}
public func search(for term: String) -> Promise<[SearchResults]> {
logger.info("Search for: \(term)")
return DispatchQueue.global()
.async(.promise) {
try self.simpleSearchers.flatMap { try $0.search(for: term) }
}
.map {
$0.filter { !$0.items.isEmpty }
}
.then { results -> Promise<[SearchResults]> in
if !results.isEmpty {
return .value(results)
}
return self.translationsSearcher.search(for: term)
}
.map {
$0.filter { !$0.items.isEmpty }
}
}
}
| apache-2.0 | 2a184494ef1433a3af164172b167e380 | 38.142857 | 115 | 0.629258 | 5.058462 | false | false | false | false |
quran/quran-ios | Sources/BatchDownloader/Entities/Download.swift | 1 | 1479 | //
// Download.swift
// Quran
//
// Created by Mohamed Afifi on 2/14/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
public struct Download {
public enum Status: Int {
case downloading = 0
case completed = 1
// case failed = 2 // we shouldn't keep a failed download
case pending = 3
}
public let batchId: Int64
public let request: DownloadRequest
public var status: Status
public var taskId: Int?
public init(taskId: Int? = nil, request: DownloadRequest, status: Status = .downloading, batchId: Int64) {
self.taskId = taskId
self.request = request
self.status = status
self.batchId = batchId
}
}
public struct DownloadBatch {
public let id: Int64
public let downloads: [Download]
public init(id: Int64, downloads: [Download]) {
self.id = id
self.downloads = downloads
}
}
| apache-2.0 | 06beba7ab6c993ce125a9c5f1de60726 | 28.58 | 110 | 0.665314 | 4.085635 | false | false | false | false |
lexrus/LexNightmare | LexNightmare/GameScene+Lex.swift | 1 | 989 | //
// GameScene+Lex.swift
// LexNightmare
//
// Created by Lex Tang on 3/16/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import UIKit
import SpriteKit
extension GameScene
{
func lexNode() -> SKSpriteNode {
if let lex = childNodeWithName("lex") as! SKSpriteNode? {
return lex
} else {
let texture = SKTexture(image: UIImage(named: "LexAwake")!)
let node = SKSpriteNode(texture: texture)
node.name = "lex"
node.size = CGSizeMake(300, 300)
node.anchorPoint = CGPointMake(0.5, 0)
node.position = CGPointMake(screenWidth / 2, 0)
node.zPosition = 2
addChild(node)
return node
}
}
func showLexAwake() {
lexNode().texture = SKTexture(image: UIImage(named: "LexAwake")!)
}
func showLexAsleep() {
lexNode().texture = SKTexture(image: UIImage(named: "LexAsleep")!)
}
}
| mit | c796a472942682726d94fcd8d5dc21ed | 25.026316 | 74 | 0.564206 | 4.120833 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Binary Search/74_Search a 2D Matrix.swift | 1 | 1882 | // 74_Search a 2D Matrix
// https://leetcode.com/problems/search-a-2d-matrix/
//
// Created by Honghao Zhang on 10/17/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
//
//Integers in each row are sorted from left to right.
//The first integer of each row is greater than the last integer of the previous row.
//Example 1:
//
//Input:
//matrix = [
// [1, 3, 5, 7],
// [10, 11, 16, 20],
// [23, 30, 34, 50]
//]
//target = 3
//Output: true
//Example 2:
//
//Input:
//matrix = [
// [1, 3, 5, 7],
// [10, 11, 16, 20],
// [23, 30, 34, 50]
//]
//target = 13
//Output: false
//
// 在一个sorted matrix中找数字
import Foundation
class Num74 {
// MARK: - Binary search
// 只是需要做一个1d index 到 2d coordinate的转换
func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
let m = matrix.count
guard m > 0 else {
return false
}
let n = matrix[0].count
guard n > 0 else {
return false
}
var start = 0
var end = m * n - 1
while start + 1 < end {
let mid = start + (end - start) / 2
let (x, y) = getCoordinate(mid, m, n)
let midNum = matrix[x][y]
if target < midNum {
end = mid
}
else if target > midNum {
start = mid
}
else {
return true
}
}
let (startX, startY) = getCoordinate(start, m, n)
if matrix[startX][startY] == target {
return true
}
let (endX, endY) = getCoordinate(end, m, n)
if matrix[endX][endY] == target {
return true
}
return false
}
// m rows
// n columns
private func getCoordinate(_ index: Int, _ m: Int, _ n: Int) -> (Int, Int) {
let x = index / n
let y = index % n
return (x, y)
}
}
| mit | c5d5bcd0a8beb61179fba64c8b1d0f5f | 20.453488 | 119 | 0.561518 | 3.132428 | false | false | false | false |
wfleming/SwiftLint | Source/SwiftLintFramework/Extensions/File+SwiftLint.swift | 1 | 9374 | //
// File+SwiftLint.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
internal func regex(pattern: String) -> NSRegularExpression {
// all patterns used for regular expressions in SwiftLint are string literals which have been
// confirmed to work, so it's ok to force-try here.
// swiftlint:disable:next force_try
return try! NSRegularExpression.cached(pattern: pattern)
}
extension File {
internal func regions() -> [Region] {
var regions = [Region]()
var disabledRules = Set<String>()
let commands = self.commands()
let commandPairs = zip(commands, Array(commands.dropFirst().map(Optional.init)) + [nil])
for (command, nextCommand) in commandPairs {
switch command.action {
case .Disable: disabledRules.insert(command.ruleIdentifier)
case .Enable: disabledRules.remove(command.ruleIdentifier)
}
let start = Location(file: path, line: command.line, character: command.character)
let end = endOfNextCommand(nextCommand)
regions.append(Region(start: start, end: end, disabledRuleIdentifiers: disabledRules))
}
return regions
}
private func commands() -> [Command] {
let contents = self.contents as NSString
return matchPattern("swiftlint:(enable|disable)(:previous|:this|:next)?\\ [^\\s]+",
withSyntaxKinds: [.Comment]).flatMap { range in
return Command(string: contents, range: range)
}.flatMap { command in
return command.expand()
}
}
private func endOfNextCommand(nextCommand: Command?) -> Location {
guard let nextCommand = nextCommand else {
return Location(file: path, line: Int.max, character: Int.max)
}
let nextLine: Int
let nextCharacter: Int?
if let nextCommandCharacter = nextCommand.character {
nextLine = nextCommand.line
if nextCommand.character > 0 {
nextCharacter = nextCommandCharacter - 1
} else {
nextCharacter = nil
}
} else {
nextLine = max(nextCommand.line - 1, 0)
nextCharacter = Int.max
}
return Location(file: path, line: nextLine, character: nextCharacter)
}
internal func matchPattern(pattern: String,
withSyntaxKinds syntaxKinds: [SyntaxKind]) -> [NSRange] {
return matchPattern(pattern).filter { _, kindsInRange in
return kindsInRange.count == syntaxKinds.count &&
zip(kindsInRange, syntaxKinds).filter({ $0.0 != $0.1 }).isEmpty
}.map { $0.0 }
}
internal func rangesAndTokensMatching(pattern: String) -> [(NSRange, [SyntaxToken])] {
return rangesAndTokensMatching(regex(pattern))
}
internal func rangesAndTokensMatching(regex: NSRegularExpression) ->
[(NSRange, [SyntaxToken])] {
let contents = self.contents as NSString
let range = NSRange(location: 0, length: contents.length)
let syntax = syntaxMap
return regex.matchesInString(self.contents, options: [], range: range).map { match in
let matchByteRange = contents.NSRangeToByteRange(start: match.range.location,
length: match.range.length) ?? match.range
let tokensInRange = syntax.tokensIn(matchByteRange)
return (match.range, tokensInRange)
}
}
internal func matchPattern(pattern: String) -> [(NSRange, [SyntaxKind])] {
return matchPattern(regex(pattern))
}
internal func matchPattern(regex: NSRegularExpression) -> [(NSRange, [SyntaxKind])] {
return rangesAndTokensMatching(regex).map { range, tokens in
(range, tokens.map({ $0.type }).flatMap(SyntaxKind.init))
}
}
internal func syntaxKindsByLine() -> [[SyntaxKind]] {
var results = [[SyntaxKind]](count: lines.count + 1, repeatedValue: [])
var tokenGenerator = syntaxMap.tokens.generate()
var lineGenerator = lines.generate()
var maybeLine = lineGenerator.next()
var maybeToken = tokenGenerator.next()
while let line = maybeLine, token = maybeToken {
let tokenRange = NSRange(location: token.offset, length: token.length)
if NSLocationInRange(token.offset, line.byteRange) ||
NSLocationInRange(line.byteRange.location, tokenRange) {
results[line.index].append(SyntaxKind(rawValue: token.type)!)
}
let tokenEnd = NSMaxRange(tokenRange)
let lineEnd = NSMaxRange(line.byteRange)
if tokenEnd < lineEnd {
maybeToken = tokenGenerator.next()
} else if tokenEnd > lineEnd {
maybeLine = lineGenerator.next()
} else {
maybeLine = lineGenerator.next()
maybeToken = tokenGenerator.next()
}
}
return results
}
//Added by S2dent
/**
This function returns only matches that are not contained in a syntax kind
specified.
- parameter pattern: regex pattern to be matched inside file.
- parameter excludingSyntaxKinds: syntax kinds the matches to be filtered
when inside them.
- returns: An array of [NSRange] objects consisting of regex matches inside
file contents.
*/
internal func matchPattern(pattern: String,
excludingSyntaxKinds syntaxKinds: [SyntaxKind]) -> [NSRange] {
return matchPattern(pattern).filter {
$0.1.filter(syntaxKinds.contains).isEmpty
}.map { $0.0 }
}
internal func matchPattern(pattern: String,
excludingSyntaxKinds: [SyntaxKind],
excludingPattern: String) -> [NSRange] {
let contents = self.contents as NSString
let range = NSRange(location: 0, length: contents.length)
let matches = matchPattern(pattern, excludingSyntaxKinds: excludingSyntaxKinds)
if matches.isEmpty {
return []
}
let exclusionRanges = regex(excludingPattern).matchesInString(self.contents,
options: [],
range: range)
.ranges()
return matches.filter { !$0.intersectsRanges(exclusionRanges) }
}
internal func validateVariableName(dictionary: [String: SourceKitRepresentable],
kind: SwiftDeclarationKind) -> (name: String, offset: Int)? {
guard let name = dictionary["key.name"] as? String,
offset = (dictionary["key.offset"] as? Int64).flatMap({ Int($0) }) where
SwiftDeclarationKind.variableKinds().contains(kind) && !name.hasPrefix("$") else {
return nil
}
return (name.nameStrippingLeadingUnderscoreIfPrivate(dictionary), offset)
}
internal func append(string: String) {
guard let stringData = string.dataUsingEncoding(NSUTF8StringEncoding) else {
fatalError("can't encode '\(string)' with UTF8")
}
guard let path = path, fileHandle = NSFileHandle(forWritingAtPath: path) else {
fatalError("can't write to path '\(self.path)'")
}
fileHandle.seekToEndOfFile()
fileHandle.writeData(stringData)
fileHandle.closeFile()
contents += string
lines = contents.lines()
}
internal func write(string: String) {
guard let path = path else {
fatalError("file needs a path to call write(_:)")
}
guard let stringData = string.dataUsingEncoding(NSUTF8StringEncoding) else {
fatalError("can't encode '\(string)' with UTF8")
}
stringData.writeToFile(path, atomically: true)
contents = string
lines = contents.lines()
}
internal func ruleEnabledViolatingRanges(violatingRanges: [NSRange], forRule rule: Rule)
-> [NSRange] {
let fileRegions = regions()
let violatingRanges = violatingRanges.filter { range in
let region = fileRegions.filter {
$0.contains(Location(file: self, characterOffset: range.location))
}.first
return region?.isRuleEnabled(rule) ?? true
}
return violatingRanges
}
private func numberOfCommentAndWhitespaceOnlyLines(startLine: Int, endLine: Int) -> Int {
let commentKinds = Set(SyntaxKind.commentKinds())
return syntaxKindsByLines[startLine...endLine].filter { kinds in
kinds.filter { !commentKinds.contains($0) }.isEmpty
}.count
}
internal func exceedsLineCountExcludingCommentsAndWhitespace(start: Int, _ end: Int,
_ limit: Int) -> (Bool, Int) {
if end - start <= limit {
return (false, end - start)
}
let count = end - start - numberOfCommentAndWhitespaceOnlyLines(start, endLine: end)
return (count > limit, count)
}
}
| mit | 2381e3d93327c839b1634f309867dbe6 | 40.114035 | 98 | 0.599957 | 4.90272 | false | false | false | false |
mbcltd/swiftli | swiftliTests/ArrayListTests.swift | 1 | 1312 | //
// ArrayListTests.swift
// swiftli
//
// Created by David Morgan-Brown on 05/06/2014.
// Copyright (c) 2014 David Morgan-Brown. All rights reserved.
//
import XCTest
import swiftli
class ArrayListTests: XCTestCase {
let a = ArrayList(array:["a","B","c"])
func testFind() {
let f1 = a.find({ $0.lowercaseString != $0 })
XCTAssert(f1 == "B")
let f2 = a.find({ $0 == "D" })
XCTAssert(f2 == nil)
}
func testSubscript() {
XCTAssert( a.element(0) == "a" )
XCTAssert( a.element(1) == "B" )
XCTAssert( a.element(2) == "c" )
}
func testHead() {
XCTAssert( a.head() == "a" )
}
func testTail() {
XCTAssert( a.tail().length() == 2 )
XCTAssert( a.tail().head() == "B" )
XCTAssert( a.tail().tail().head() == "c" )
XCTAssert( a.tail().tail().tail().isEmpty() )
}
func testIsEmpty() {
XCTAssert( !a.isEmpty() )
let b = ArrayList(array:String[]())
XCTAssert( b.isEmpty() )
}
func testLength() {
XCTAssert( a.length() == 3 )
XCTAssert( a.tail().length() == 2 )
XCTAssert( a.tail().tail().length() == 1 )
XCTAssert( a.tail().tail().tail().length() == 0 )
}
}
| mit | c9e8d4bf1633f217f1686496a5b7056b | 22.428571 | 63 | 0.490854 | 3.555556 | false | true | false | false |
ostatnicky/kancional-ios | Cancional/UI/Main/SelectNumberButtonView.swift | 1 | 2529 | //
// SelectNumberButtonView.swift
// Cancional
//
// Created by Jiri Ostatnicky on 17/06/2017.
// Copyright © 2017 Jiri Ostatnicky. All rights reserved.
//
import UIKit
class SelectNumberButtonView: UIView {
// MARK: - Static things
static let prefferedWidth: CGFloat = 200
static let prefferedHeight: CGFloat = 50
static func make() -> SelectNumberButtonView {
let view = SelectNumberButtonView()
view.setupUI()
return view
}
// MARK: - Public properties
var onTapAction: (() -> Void)?
// MARK: - Private properties
fileprivate var button: UIButton!
fileprivate var shadowView: UIView!
}
private extension SelectNumberButtonView {
func setupUI() {
backgroundColor = .clear
clipsToBounds = false
// Shadow
shadowView = UIView()
shadowView.backgroundColor = Persistence.instance.songAppearance.backgroundColor
shadowView.clipsToBounds = false
shadowView.layer.cornerRadius = SelectNumberButtonView.prefferedHeight / 2
shadowView.layer.shadowRadius = 20
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOpacity = 0.3
shadowView.layer.shadowOffset = CGSize(width: 0, height: 10)
addSubview(shadowView)
shadowView.autoPinEdgesToSuperviewEdges()
// Content container
let content = UIView()
content.backgroundColor = UIColor.Cancional.tintColor()
content.clipsToBounds = true
content.layer.cornerRadius = SelectNumberButtonView.prefferedHeight / 2
addSubview(content)
content.autoPinEdgesToSuperviewEdges()
// Button
button = UIButton(type: .system)
button.setTitle(AppConfig.searchNumberButtonTitle, for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.Cancional.mediumFontOfSize(18)
button.addTarget(self, action: #selector(didTouchButton), for: .touchUpInside)
content.addSubview(button)
button.autoPinEdgesToSuperviewEdges()
NotificationCenter.addObserver(forName: Constants.Notification.refreshUI, object: nil, queue: OperationQueue.main) { [weak self] _ in
self?.updateUI()
}
}
func updateUI() {
shadowView.backgroundColor = Persistence.instance.songAppearance.backgroundColor
}
@objc func didTouchButton() {
onTapAction?()
}
}
| mit | 3144ead236702e43822f8ec3e8c44f3d | 31.410256 | 141 | 0.661392 | 4.966601 | false | false | false | false |
snark/jumpcut | Jumpcut/Jumpcut/StatusItem.swift | 1 | 3679 | //
// StatusItem.swift
// Jumpcut
//
// Created by Steve Cook on 4/16/22.
//
import Cocoa
class StatusItem {
// Annoyingly, our shotgun approach to monitoring preference state change
// means that we have to track what the state is supposed to be, because
// we'll call it repeatedly on change, causing a crash in the naïve case.
private var shown = false
private var statusItem: NSStatusItem?
private var visibilityObserver: NSKeyValueObservation?
func setVisibility() {
let headless = UserDefaults.standard.value(forKey: SettingsPath.hideStatusItem.rawValue) as? Bool ?? false
if headless && shown {
hide()
} else if !headless && !shown {
show()
}
}
init() {
makeItem()
}
public func displayMenu(_ activeMenu: NSMenu) {
guard statusItem != nil else {
return
}
statusItem!.highlightMode = true // Highlight bodge: Stop the highlight flicker (see async call below).
statusItem!.button?.isHighlighted = true
statusItem!.menu = activeMenu
statusItem!.popUpMenu(activeMenu)
statusItem!.menu = nil // Otherwise clicks won't be processed again
}
private func makeItem() {
let delegate = (NSApplication.shared.delegate as? AppDelegate)!
let menuIconPref = UserDefaults.standard.value(forKey: SettingsPath.menuIcon.rawValue) as? Int ?? 0
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
if menuIconPref == 1 {
statusItem!.button?.title = "✄"
} else {
statusItem!.button?.image = NSImage(named: NSImage.Name("scissors_bw"))
statusItem!.button?.image!.isTemplate = true
}
statusItem!.button?.action = #selector(delegate.statusItemClicked(sender:))
// See https://stackoverflow.com/questions/40062510/swift-nsstatusitem-remains-highlighted-after-right-click
// for details on why we're using mouseup instead of mousedown.
statusItem!.button?.sendAction(on: [
NSEvent.EventTypeMask.leftMouseUp,
NSEvent.EventTypeMask.rightMouseUp,
NSEvent.EventTypeMask.otherMouseUp
])
if #available(OSX 10.12, *) {
statusItem!.behavior = .removalAllowed
statusItem!.autosaveName = "JumpcutStatusItem"
visibilityObserver = statusItem!.observe(\.isVisible, options: [.old, .new]) { _, change in
if !change.newValue! {
UserDefaults.standard.set(true, forKey: SettingsPath.hideStatusItem.rawValue)
self.hide()
}
}
}
}
public func hide() {
shown = false
guard statusItem != nil else {
return
}
if #available(OSX 10.12, *) {
if !statusItem!.isVisible {
return
}
statusItem!.isVisible = false
} else {
NSStatusBar.system.removeStatusItem(statusItem!)
visibilityObserver = nil
statusItem = nil
}
}
func show() {
/*
* Trickier logic; if we're pre-10.12 we *should* have a nil
* statusItem.
*/
shown = true
if #available(OSX 10.12, *) {
guard statusItem != nil else {
return
}
if statusItem!.isVisible {
return
}
statusItem!.isVisible = true
} else {
guard statusItem == nil else {
return
}
makeItem()
}
}
}
| mit | 585a1b467f8b126b7b63a0ea720e4306 | 32.418182 | 116 | 0.575354 | 4.862434 | false | false | false | false |
wesbillman/JSONFeed | JSONFeedTests/JSONFeedTests.swift | 1 | 3534 | //
// Created by Wes Billman on 5/19/17.
// Copyright © 2017 wesbillman. All rights reserved.
//
import XCTest
@testable import JSONFeed
class JSONFeedTests: XCTestCase {
let url = "https://jsonfeed.org/version/1"
let text = "Some Text"
func testInvalidVersion() {
XCTAssertThrowsError(try JSONFeed(json: [:])) { error in
XCTAssertEqual(error as? JSONFeedError, JSONFeedError.invalidVersion)
}
}
func testInvalidTitle() {
let json = ["version": url]
XCTAssertThrowsError(try JSONFeed(json: json)) { error in
XCTAssertEqual(error as? JSONFeedError, JSONFeedError.invalidTitle)
}
}
func testInvalidData() {
guard let data = "bogus".data(using: .utf8) else {
XCTFail()
return
}
XCTAssertThrowsError(try JSONFeed(data: data)) { error in
XCTAssertEqual(error as? JSONFeedError, JSONFeedError.invalidData)
}
}
func testInvalidString() {
XCTAssertThrowsError(try JSONFeed(string: "")) { error in
XCTAssertEqual(error as? JSONFeedError, JSONFeedError.invalidString)
}
}
func testEmptyFeed() {
let json = ["version": url, "title": text]
let feed = try? JSONFeed(json: json)
XCTAssertEqual(feed?.version.absoluteString, url)
XCTAssertEqual(feed?.title, text)
}
func testFullyPopulatedFeed() {
let json: [String : Any] = [
"version": url,
"title": text,
"home_page_url": url,
"feed_url": url,
"description": text,
"user_comment": text,
"next_url": url,
"icon": url,
"favicon": url,
"author": ["name": text, "url": url, "avatar": url],
"hubs": [["type": text, "url": url]],
"items": [["id": text]]
]
let feed = try? JSONFeed(json: json)
XCTAssertEqual(feed?.version.absoluteString, url)
XCTAssertEqual(feed?.title, text)
XCTAssertEqual(feed?.homePage?.absoluteString, url)
XCTAssertEqual(feed?.feed?.absoluteString, url)
XCTAssertEqual(feed?.description, text)
XCTAssertEqual(feed?.userComment, text)
XCTAssertEqual(feed?.next?.absoluteString, url)
XCTAssertEqual(feed?.icon?.absoluteString, url)
XCTAssertEqual(feed?.favicon?.absoluteString, url)
XCTAssertEqual(feed?.author?.name, text)
XCTAssertEqual(feed?.author?.url?.absoluteString, url)
XCTAssertEqual(feed?.author?.avatar?.absoluteString, url)
XCTAssertEqual(feed?.hubs?.count, 1)
XCTAssertEqual(feed?.hubs?.first?.type, text)
XCTAssertEqual(feed?.hubs?.first?.url.absoluteString, url)
XCTAssertEqual(feed?.items.count, 1)
XCTAssertEqual(feed?.items.first?.id, text)
}
func testFeedFromData() {
let json = ["version": url, "title": text]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
XCTFail()
return
}
let feed = try? JSONFeed(data: data)
XCTAssertEqual(feed?.version.absoluteString, url)
XCTAssertEqual(feed?.title, text)
}
func testFeedFromString() {
let string = "{\"version\": \"\(url)\", \"title\": \"\(text)\"}"
let feed = try? JSONFeed(string: string)
XCTAssertEqual(feed?.version.absoluteString, url)
XCTAssertEqual(feed?.title, text)
}
}
| mit | a0237f8d80ef18e8effc06dcc411798c | 33.300971 | 106 | 0.598075 | 4.350985 | false | true | false | false |
Quick/Nimble | Sources/Nimble/Matchers/PostNotification.swift | 4 | 3286 | #if !os(WASI)
#if canImport(Foundation)
import Foundation
internal class NotificationCollector {
private(set) var observedNotifications: [Notification]
private let notificationCenter: NotificationCenter
private let names: Set<Notification.Name>
private var tokens: [NSObjectProtocol]
required init(notificationCenter: NotificationCenter, names: Set<Notification.Name> = []) {
self.notificationCenter = notificationCenter
self.observedNotifications = []
self.names = names
self.tokens = []
}
func startObserving() {
func addObserver(forName name: Notification.Name?) -> NSObjectProtocol {
return notificationCenter.addObserver(forName: name, object: nil, queue: nil) { [weak self] notification in
// linux-swift gets confused by .append(n)
self?.observedNotifications.append(notification)
}
}
if names.isEmpty {
tokens.append(addObserver(forName: nil))
} else {
names.forEach { name in
tokens.append(addObserver(forName: name))
}
}
}
deinit {
tokens.forEach { token in
notificationCenter.removeObserver(token)
}
}
}
private let mainThread = pthread_self()
private func _postNotifications<Out>(
_ predicate: Predicate<[Notification]>,
from center: NotificationCenter,
names: Set<Notification.Name> = []
) -> Predicate<Out> {
_ = mainThread // Force lazy-loading of this value
let collector = NotificationCollector(notificationCenter: center, names: names)
collector.startObserving()
var once: Bool = false
return Predicate { actualExpression in
let collectorNotificationsExpression = Expression(
memoizedExpression: { _ in
return collector.observedNotifications
},
location: actualExpression.location,
withoutCaching: true
)
assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.")
if !once {
once = true
_ = try actualExpression.evaluate()
}
let actualValue: String
if collector.observedNotifications.isEmpty {
actualValue = "no notifications"
} else {
actualValue = "<\(stringify(collector.observedNotifications))>"
}
var result = try predicate.satisfies(collectorNotificationsExpression)
result.message = result.message.replacedExpectation { message in
return .expectedCustomValueTo(message.expectedMessage, actual: actualValue)
}
return result
}
}
public func postNotifications<Out>(
_ predicate: Predicate<[Notification]>,
from center: NotificationCenter = .default
) -> Predicate<Out> {
_postNotifications(predicate, from: center)
}
#if os(macOS)
public func postDistributedNotifications<Out>(
_ predicate: Predicate<[Notification]>,
from center: DistributedNotificationCenter = .default(),
names: Set<Notification.Name>
) -> Predicate<Out> {
_postNotifications(predicate, from: center, names: names)
}
#endif
#endif // #if canImport(Foundation)
#endif // #if !os(WASI)
| apache-2.0 | 8c9785c0cccd26eedf33f1820dab981e | 30.596154 | 120 | 0.65003 | 5.086687 | false | false | false | false |
T1V/Criollo | Apps/Criollo tvOS App/HelloWorldViewController.swift | 2 | 840 | //
// HelloWorldViewController.swift
// HelloWorld-Swift
//
// Created by Cătălin Stan on 11/24/15.
//
//
import Criollo
class HelloWorldViewController: CRViewController {
override func present(with request: CRRequest, response: CRResponse) -> String {
self.vars["title"] = String(describing: type(of: self))
var text:String = String()
text += "<h3>Request Query:</h2><pre>"
for (key, object) in request.query {
text += "\(key): \(object)\n"
}
text += "</pre>"
text += "<h3>Request Environment:</h2><pre>"
for (key, object) in request.env {
text += "\(key): \(object)\n"
}
text += "</pre>"
self.vars["text"] = text
return super.present(with: request, response: response)
}
}
| mit | a48302087dccb54b16d8b8a4c8e6d837 | 23.647059 | 84 | 0.544153 | 3.826484 | false | false | false | false |
wuhduhren/Mr-Ride-iOS | Mr-Ride-iOS/Model/CoreData/RunDataModel.swift | 1 | 1787 | //
// RunData.swift
// Mr-Ride-iOS
//
// Created by Eph on 2016/6/3.
// Copyright © 2016年 AppWorks School WuDuhRen. All rights reserved.
//
import Foundation
import CoreData
class RunDataModel {
class runDataStruct {
var date: NSDate?
var distance: Double?
var speed: Double?
var calories: Double?
var time: String?
var polyline: NSData?
var objectID: NSManagedObjectID?
}
private let context = DataController().managedObjectContext
var runDataStructArray: [runDataStruct] = []
func getData() -> [runDataStruct] {
do {
let getRequest = NSFetchRequest(entityName: "Entity")
let sortDesriptor = NSSortDescriptor(key: "date", ascending: true)
getRequest.sortDescriptors = [sortDesriptor]
let data = try context.executeFetchRequest(getRequest)
runDataStructArray = [] //reset
for eachData in data {
let tempStruct = runDataStruct()
tempStruct.date = eachData.valueForKey("date")! as? NSDate
tempStruct.distance = eachData.valueForKey("distance")! as? Double
tempStruct.speed = eachData.valueForKey("speed")! as? Double
tempStruct.calories = eachData.valueForKey("calories")! as? Double
tempStruct.time = eachData.valueForKey("time")! as? String
tempStruct.polyline = eachData.valueForKey("polyline")! as? NSData
tempStruct.objectID = eachData.objectID
runDataStructArray.append(tempStruct)
}
return runDataStructArray
} catch {
fatalError("error appear when fetching")
}
}
}
| mit | ec51f6ad051eac163d55591993fa7c89 | 31.436364 | 82 | 0.59417 | 4.874317 | false | false | false | false |
bradhilton/Table | Table/UIControl.swift | 1 | 2610 | //
// UIControl.swift
// Table
//
// Created by Bradley Hilton on 2/20/18.
// Copyright © 2018 Brad Hilton. All rights reserved.
//
fileprivate class EventTarget<Control : NSObjectProtocol> : NSObject {
var handler: (Control) -> ()
init(_ handler: @escaping (Control) -> ()) {
self.handler = handler
}
@objc func action(control: UIControl) {
guard let control = control as? Control else { return }
handler(control)
}
}
public struct Events<Control : UIControl> {
private weak var control: Control?
fileprivate init(_ control: Control) {
self.control = control
}
public subscript(events: UIControl.Event) -> ((Control) -> ())? {
get {
return control?.targets[events.rawValue]?.handler
}
set {
control?.setHandler(newValue, for: events)
}
}
}
public protocol Control : NSObjectProtocol {}
extension Control where Self : UIControl {
public var events: Events<Self> {
get {
return Events(self)
}
set {}
}
func setHandler(_ handler: ((Self) -> ())?, for events: UIControl.Event) {
switch (handler, targets[events.rawValue]) {
case let (handler?, target?):
target.handler = handler
case let (handler?, nil):
let target = EventTarget(handler)
addTarget(target, action: #selector(EventTarget<Self>.action), for: events)
targets[events.rawValue] = target
case let (nil, target?):
removeTarget(target, action: #selector(EventTarget<Self>.action), for: events)
targets.removeValue(forKey: events.rawValue)
case (nil, nil):
break
}
}
fileprivate var targets: [UInt : EventTarget<Self>] {
get {
return storage[\.targets, default: [:]]
}
set {
storage[\.targets] = newValue
}
}
}
extension UIControl : Control {}
public protocol ValueControl : class {}
extension ValueControl where Self : UIControl {
public var valueChanged: ((Self) -> ())? {
get {
return events[.valueChanged]
}
set {
events[.valueChanged] = newValue
}
}
}
#if os(iOS)
extension UIDatePicker : ValueControl {}
extension UISlider : ValueControl {}
extension UIStepper : ValueControl {}
extension UISwitch : ValueControl {}
#endif
extension UIPageControl : ValueControl {}
extension UISegmentedControl : ValueControl {}
| mit | 3badc8b5c5d3c4cc341278e4d83acdb2 | 23.383178 | 90 | 0.5757 | 4.642349 | false | false | false | false |
dathtcheapgo/Jira-Demo | Driver/MVC/Core/View/CGMapView/CGLocation.swift | 1 | 946 | //
// CGLocation.swift
// CGMapView
//
// Created by Đinh Anh Huy on 10/25/16.
// Copyright © 2016 Đinh Anh Huy. All rights reserved.
//
import UIKit
import ObjectMapper
import CoreLocation
public class CGLocation: Mappable {
var lat: Double = 0
var long: Double = 0
var timeStamp: TimeInterval = 0 //time in second
var clLocation: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: lat, longitude: self.long)
}
init() {
}
init(location: CLLocationCoordinate2D) {
lat = location.latitude
long = location.longitude
}
required public init?(map: Map) {
}
public func mapping(map: Map) {
lat <- map["lat"]
long <- map["long"]
}
}
extension CGLocation {
static func ==(left: CGLocation, right: CGLocation) -> Bool {
return left.lat == right.lat && left.long == right.long
}
}
| mit | 839da809f2728296ead453b73e64fb3a | 19.955556 | 74 | 0.601273 | 4.029915 | false | false | false | false |
alessiobrozzi/firefox-ios | Client/Frontend/Home/ActivityStreamPanel.swift | 1 | 30396 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import UIKit
import Deferred
import Storage
import WebImage
import XCGLogger
private let log = Logger.browserLogger
private let DefaultSuggestedSitesKey = "topSites.deletedSuggestedSites"
// MARK: - Lifecycle
struct ASPanelUX {
static let backgroundColor = UIColor(white: 1.0, alpha: 0.5)
static let topSitesCacheSize = 12
static let historySize = 10
static let rowSpacing: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 30 : 20
static let highlightCellHeight: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 250 : 195
static let PageControlOffsetSize: CGFloat = 40
static let SectionInsetsForIpad: CGFloat = 100
static let SectionInsetsForIphone: CGFloat = 14
static let CompactWidth: CGFloat = 320
}
class ActivityStreamPanel: UICollectionViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate?
fileprivate let profile: Profile
fileprivate let telemetry: ActivityStreamTracker
fileprivate let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
fileprivate let topSitesManager = ASHorizontalScrollCellManager()
fileprivate var isInitialLoad = true //Prevents intro views from flickering while content is loading
fileprivate let events = [NotificationFirefoxAccountChanged, NotificationProfileDidFinishSyncing, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged]
fileprivate var sessionStart: Timestamp?
lazy var longPressRecognizer: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: #selector(ActivityStreamPanel.longPress(_:)))
}()
// Not used for displaying. Only used for calculating layout.
lazy var topSiteCell: ASHorizontalScrollCell = {
let customCell = ASHorizontalScrollCell(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 0))
customCell.delegate = self.topSitesManager
return customCell
}()
var highlights: [Site] = []
init(profile: Profile, telemetry: ActivityStreamTracker? = nil) {
self.profile = profile
self.telemetry = telemetry ?? ActivityStreamTracker(eventsTracker: PingCentre.clientForTopic(.ActivityStreamEvents, clientID: profile.clientID), sessionsTracker: PingCentre.clientForTopic(.ActivityStreamSessions, clientID: profile.clientID))
super.init(collectionViewLayout: flowLayout)
self.collectionView?.delegate = self
self.collectionView?.dataSource = self
collectionView?.addGestureRecognizer(longPressRecognizer)
self.profile.history.setTopSitesCacheSize(Int32(ASPanelUX.topSitesCacheSize))
events.forEach { NotificationCenter.default.addObserver(self, selector: #selector(self.notificationReceived(_:)), name: $0, object: nil) }
}
deinit {
events.forEach { NotificationCenter.default.removeObserver(self, name: $0, object: nil) }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
Section.allValues.forEach { self.collectionView?.register(Section($0.rawValue).cellType, forCellWithReuseIdentifier: Section($0.rawValue).cellIdentifier) }
self.collectionView?.register(ASHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header")
collectionView?.backgroundColor = ASPanelUX.backgroundColor
collectionView?.keyboardDismissMode = .onDrag
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
sessionStart = Date.now()
all([invalidateTopSites(), invalidateHighlights()]).uponQueue(DispatchQueue.main) { _ in
self.isInitialLoad = false
self.collectionView?.reloadData()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
telemetry.reportSessionStop(Date.now() - (sessionStart ?? 0))
sessionStart = nil
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: {context in
self.collectionViewLayout.invalidateLayout()
self.collectionView?.reloadData()
}, completion: nil)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.topSitesManager.currentTraits = self.traitCollection
}
}
// MARK: - Section management
extension ActivityStreamPanel {
enum Section: Int {
case topSites
case highlights
case highlightIntro
static let count = 3
static let allValues = [topSites, highlights, highlightIntro]
var title: String? {
switch self {
case .highlights: return Strings.ASHighlightsTitle
case .topSites: return nil
case .highlightIntro: return nil
}
}
var headerHeight: CGSize {
switch self {
case .highlights: return CGSize(width: 50, height: 40)
case .topSites: return CGSize(width: 0, height: 0)
case .highlightIntro: return CGSize(width: 50, height: 2)
}
}
func cellHeight(_ traits: UITraitCollection, width: CGFloat) -> CGFloat {
switch self {
case .highlights: return ASPanelUX.highlightCellHeight
case .topSites: return 0 //calculated dynamically
case .highlightIntro: return 200
}
}
func sectionInsets() -> CGFloat {
switch self {
case .highlights:
return UIDevice.current.userInterfaceIdiom == .pad ? ASPanelUX.SectionInsetsForIpad + ASHorizontalScrollCellUX.MinimumInsets : ASPanelUX.SectionInsetsForIphone
case .topSites:
return UIDevice.current.userInterfaceIdiom == .pad ? ASPanelUX.SectionInsetsForIpad : 0
case .highlightIntro:
return 0
}
}
func cellSize(for traits: UITraitCollection, frameWidth: CGFloat) -> CGSize {
let height = cellHeight(traits, width: frameWidth)
let inset = sectionInsets() * 2
switch self {
case .highlights:
if UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight {
return CGSize(width: (frameWidth - inset) / 4 - 10, height: height)
} else if UIDevice.current.userInterfaceIdiom == .pad {
return CGSize(width: (frameWidth - inset) / 3 - 10, height: height)
} else {
return CGSize(width: (frameWidth - inset) / 2 - 10, height: height)
}
case .topSites:
return CGSize(width: frameWidth - inset, height: height)
case .highlightIntro:
return CGSize(width: frameWidth - inset, height: height)
}
}
var headerView: UIView? {
switch self {
case .highlights:
let view = ASHeaderView()
view.title = title
return view
case .topSites:
return nil
case .highlightIntro:
let view = ASHeaderView()
view.title = title
return view
}
}
var cellIdentifier: String {
switch self {
case .topSites: return "TopSiteCell"
case .highlights: return "HistoryCell"
case .highlightIntro: return "HighlightIntroCell"
}
}
var cellType: UICollectionViewCell.Type {
switch self {
case .topSites: return ASHorizontalScrollCell.self
case .highlights: return ActivityStreamHighlightCell.self
case .highlightIntro: return HighlightIntroCell.self
}
}
init(at indexPath: IndexPath) {
self.init(rawValue: indexPath.section)!
}
init(_ section: Int) {
self.init(rawValue: section)!
}
}
}
// MARK: - Tableview Delegate
extension ActivityStreamPanel: UICollectionViewDelegateFlowLayout {
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! ASHeaderView
let title = Section(indexPath.section).title
switch Section(indexPath.section) {
case .highlights:
view.title = title
return view
case .topSites:
return UICollectionReusableView()
case .highlightIntro:
view.title = title
return view
}
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectItemAtIndex(indexPath.item, inSection: Section(indexPath.section))
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellSize = Section(indexPath.section).cellSize(for: self.traitCollection, frameWidth: self.view.frame.width)
switch Section(indexPath.section) {
case .highlights:
if highlights.isEmpty {
return CGSize.zero
}
return cellSize
case .topSites:
// Create a temporary cell so we can calculate the height.
let layout = topSiteCell.collectionView.collectionViewLayout as! HorizontalFlowLayout
let estimatedLayout = layout.calculateLayout(for: CGSize(width: cellSize.width, height: 0))
return CGSize(width: cellSize.width, height: estimatedLayout.size.height)
case .highlightIntro:
return cellSize
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
switch Section(section) {
case .highlights:
return highlights.isEmpty ? CGSize.zero : Section(section).headerHeight
case .highlightIntro:
return !highlights.isEmpty ? CGSize.zero : Section(section).headerHeight
case .topSites:
return Section(section).headerHeight
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return ASPanelUX.rowSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let insets = Section(section).sectionInsets()
return UIEdgeInsets(top: 0, left: insets, bottom: 0, right: insets)
}
fileprivate func showSiteWithURLHandler(_ url: URL) {
let visitType = VisitType.bookmark
homePanelDelegate?.homePanel(self, didSelectURL: url, visitType: visitType)
}
}
// MARK: - Tableview Data Source
extension ActivityStreamPanel {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch Section(section) {
case .topSites:
return topSitesManager.content.isEmpty ? 0 : 1
case .highlights:
return self.highlights.count
case .highlightIntro:
return self.highlights.isEmpty && !self.isInitialLoad ? 1 : 0
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let identifier = Section(indexPath.section).cellIdentifier
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
switch Section(indexPath.section) {
case .topSites:
return configureTopSitesCell(cell, forIndexPath: indexPath)
case .highlights:
return configureHistoryItemCell(cell, forIndexPath: indexPath)
case .highlightIntro:
return configureHighlightIntroCell(cell, forIndexPath: indexPath)
}
}
//should all be collectionview
func configureTopSitesCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let topSiteCell = cell as! ASHorizontalScrollCell
topSiteCell.delegate = self.topSitesManager
return cell
}
func configureHistoryItemCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let site = highlights[indexPath.row]
let simpleHighlightCell = cell as! ActivityStreamHighlightCell
simpleHighlightCell.configureWithSite(site)
return simpleHighlightCell
}
func configureHighlightIntroCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) -> UICollectionViewCell {
let introCell = cell as! HighlightIntroCell
//The cell is configured on creation. No need to configure. But leave this here in case we need it.
return introCell
}
}
// MARK: - Data Management
extension ActivityStreamPanel {
func notificationReceived(_ notification: Notification) {
switch notification.name {
case NotificationProfileDidFinishSyncing, NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged:
self.invalidateTopSites().uponQueue(DispatchQueue.main) { _ in
self.collectionView?.reloadData()
}
default:
log.warning("Received unexpected notification \(notification.name)")
}
}
fileprivate func invalidateHighlights() -> Success {
return self.profile.recommendations.getHighlights().bindQueue(DispatchQueue.main) { result in
self.highlights = result.successValue?.asArray() ?? self.highlights
return succeed()
}
}
fileprivate func invalidateTopSites() -> Success {
let frecencyLimit = ASPanelUX.topSitesCacheSize
// Update our top sites cache if it's been invalidated
return self.profile.history.updateTopSitesCacheIfInvalidated() >>== { _ in
return self.profile.history.getTopSitesWithLimit(frecencyLimit) >>== { topSites in
let mySites = topSites.asArray()
let defaultSites = self.defaultTopSites()
// Merge default topsites with a user's topsites.
let mergedSites = mySites.union(defaultSites, f: { (site) -> String in
return URL(string: site.url)?.hostSLD ?? ""
})
// Favour topsites from defaultSites as they have better favicons.
let newSites = mergedSites.map { site -> Site in
let domain = URL(string: site.url)?.hostSLD
return defaultSites.find { $0.title.lowercased() == domain } ?? site
}
self.topSitesManager.currentTraits = self.view.traitCollection
self.topSitesManager.content = newSites.count > ASPanelUX.topSitesCacheSize ? Array(newSites[0..<ASPanelUX.topSitesCacheSize]) : newSites
self.topSitesManager.urlPressedHandler = { [unowned self] url, indexPath in
self.longPressRecognizer.isEnabled = false
self.telemetry.reportEvent(.Click, source: .TopSites, position: indexPath.item)
self.showSiteWithURLHandler(url as URL)
}
return succeed()
}
}
}
func hideURLFromTopSites(_ siteURL: URL) {
guard let host = siteURL.normalizedHost else {
return
}
let url = siteURL.absoluteString
// if the default top sites contains the siteurl. also wipe it from default suggested sites.
if defaultTopSites().filter({$0.url == url}).isEmpty == false {
deleteTileForSuggestedSite(url)
}
profile.history.removeHostFromTopSites(host).uponQueue(DispatchQueue.main) { result in
guard result.isSuccess else { return }
self.invalidateTopSites().uponQueue(DispatchQueue.main) { _ in
self.collectionView?.reloadData()
}
}
}
func hideFromHighlights(_ site: Site) {
profile.recommendations.removeHighlightForURL(site.url).uponQueue(DispatchQueue.main) { result in
guard result.isSuccess else { return }
self.invalidateHighlights().uponQueue(DispatchQueue.main) { _ in
self.collectionView?.reloadData()
}
}
}
fileprivate func deleteTileForSuggestedSite(_ siteURL: String) {
var deletedSuggestedSites = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? []
deletedSuggestedSites.append(siteURL)
profile.prefs.setObject(deletedSuggestedSites, forKey: DefaultSuggestedSitesKey)
}
func defaultTopSites() -> [Site] {
let suggested = SuggestedSites.asArray()
let deleted = profile.prefs.arrayForKey(DefaultSuggestedSitesKey) as? [String] ?? []
return suggested.filter({deleted.index(of: $0.url) == .none})
}
@objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return }
let point = longPressGestureRecognizer.location(in: self.collectionView)
guard let indexPath = self.collectionView?.indexPathForItem(at: point) else { return }
switch Section(indexPath.section) {
case .highlights:
presentContextMenuForHighlightCellWithIndexPath(indexPath)
case .topSites:
let topSiteCell = self.collectionView?.cellForItem(at: indexPath) as! ASHorizontalScrollCell
let pointInTopSite = longPressGestureRecognizer.location(in: topSiteCell.collectionView)
guard let topSiteIndexPath = topSiteCell.collectionView.indexPathForItem(at: pointInTopSite) else { return }
presentContextMenuForTopSiteCellWithIndexPath(topSiteIndexPath)
case .highlightIntro:
break
}
}
func presentContextMenu(_ contextMenu: ActionOverlayTableViewController) {
contextMenu.modalPresentationStyle = .overFullScreen
contextMenu.modalTransitionStyle = .crossDissolve
self.present(contextMenu, animated: true, completion: nil)
}
func presentContextMenuForTopSiteCellWithIndexPath(_ indexPath: IndexPath) {
let topsiteIndex = IndexPath(row: 0, section: Section.topSites.rawValue)
guard let topSiteCell = collectionView?.cellForItem(at: topsiteIndex) as? ASHorizontalScrollCell else { return }
guard let topSiteItemCell = topSiteCell.collectionView.cellForItem(at: indexPath) as? TopSiteItemCell else { return }
let siteImage = topSiteItemCell.imageView.image
let siteBGColor = topSiteItemCell.contentView.backgroundColor
let site = self.topSitesManager.content[indexPath.item]
presentContextMenuForSite(site, atIndex: indexPath.item, forSection: .topSites, siteImage: siteImage, siteBGColor: siteBGColor)
}
func presentContextMenuForHighlightCellWithIndexPath(_ indexPath: IndexPath) {
guard let highlightCell = self.collectionView?.cellForItem(at: indexPath) as? ActivityStreamHighlightCell else { return }
let siteImage = highlightCell.siteImageView.image
let siteBGColor = highlightCell.siteImageView.backgroundColor
let site = highlights[indexPath.row]
presentContextMenuForSite(site, atIndex: indexPath.row, forSection: .highlights, siteImage: siteImage, siteBGColor: siteBGColor)
}
fileprivate func fetchBookmarkStatusThenPresentContextMenu(_ site: Site, atIndex index: Int, forSection section: Section, siteImage: UIImage?, siteBGColor: UIColor?) {
profile.bookmarks.modelFactory >>== {
$0.isBookmarked(site.url).uponQueue(DispatchQueue.main) { result in
guard let isBookmarked = result.successValue else {
log.error("Error getting bookmark status: \(result.failureValue).")
return
}
site.setBookmarked(isBookmarked)
self.presentContextMenuForSite(site, atIndex: index, forSection: section, siteImage: siteImage, siteBGColor: siteBGColor)
}
}
}
func presentContextMenuForSite(_ site: Site, atIndex index: Int, forSection section: Section, siteImage: UIImage?, siteBGColor: UIColor?) {
guard let _ = site.bookmarked else {
fetchBookmarkStatusThenPresentContextMenu(site, atIndex: index, forSection: section, siteImage: siteImage, siteBGColor: siteBGColor)
return
}
guard let contextMenu = contextMenuForSite(site, atIndex: index, forSection: section, siteImage: siteImage, siteBGColor: siteBGColor) else {
return
}
self.presentContextMenu(contextMenu)
}
func contextMenuForSite(_ site: Site, atIndex index: Int, forSection section: Section, siteImage: UIImage?, siteBGColor: UIColor?) -> ActionOverlayTableViewController? {
guard let siteURL = URL(string: site.url) else {
return nil
}
let pingSource: ASPingSource
switch section {
case .topSites:
pingSource = .TopSites
case .highlights:
pingSource = .Highlights
case .highlightIntro:
pingSource = .HighlightsIntro
}
let openInNewTabAction = ActionOverlayTableViewAction(title: Strings.OpenInNewTabContextMenuTitle, iconString: "action_new_tab") { action in
self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: false)
}
let openInNewPrivateTabAction = ActionOverlayTableViewAction(title: Strings.OpenInNewPrivateTabContextMenuTitle, iconString: "action_new_private_tab") { action in
self.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(siteURL, isPrivate: true)
}
let bookmarkAction: ActionOverlayTableViewAction
if site.bookmarked ?? false {
bookmarkAction = ActionOverlayTableViewAction(title: Strings.RemoveBookmarkContextMenuTitle, iconString: "action_bookmark_remove", handler: { action in
self.profile.bookmarks.modelFactory >>== {
$0.removeByURL(siteURL.absoluteString)
site.setBookmarked(false)
}
})
} else {
bookmarkAction = ActionOverlayTableViewAction(title: Strings.BookmarkContextMenuTitle, iconString: "action_bookmark", handler: { action in
let shareItem = ShareItem(url: site.url, title: site.title, favicon: site.icon)
self.profile.bookmarks.shareItem(shareItem)
var userData = [QuickActions.TabURLKey: shareItem.url]
if let title = shareItem.title {
userData[QuickActions.TabTitleKey] = title
}
QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark,
withUserData: userData,
toApplication: UIApplication.shared)
site.setBookmarked(true)
})
}
let deleteFromHistoryAction = ActionOverlayTableViewAction(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { action in
self.telemetry.reportEvent(.Delete, source: pingSource, position: index)
self.profile.history.removeHistoryForURL(site.url)
})
let shareAction = ActionOverlayTableViewAction(title: Strings.ShareContextMenuTitle, iconString: "action_share", handler: { action in
let helper = ShareExtensionHelper(url: siteURL, tab: nil, activities: [])
let controller = helper.createActivityViewController { completed, activityType in
self.telemetry.reportEvent(.Share, source: pingSource, position: index, shareProvider: activityType)
}
self.present(controller, animated: true, completion: nil)
})
let removeTopSiteAction = ActionOverlayTableViewAction(title: Strings.RemoveFromASContextMenuTitle, iconString: "action_close", handler: { action in
self.telemetry.reportEvent(.Dismiss, source: pingSource, position: index)
self.hideURLFromTopSites(site.tileURL)
})
let dismissHighlightAction = ActionOverlayTableViewAction(title: Strings.RemoveFromASContextMenuTitle, iconString: "action_close", handler: { action in
self.telemetry.reportEvent(.Dismiss, source: pingSource, position: index)
self.hideFromHighlights(site)
})
var actions = [openInNewTabAction, openInNewPrivateTabAction, bookmarkAction, shareAction]
switch section {
case .highlights: actions.append(contentsOf: [dismissHighlightAction, deleteFromHistoryAction])
case .topSites: actions.append(removeTopSiteAction)
case .highlightIntro: break
}
return ActionOverlayTableViewController(site: site, actions: actions, siteImage: siteImage, siteBGColor: siteBGColor)
}
func selectItemAtIndex(_ index: Int, inSection section: Section) {
switch section {
case .highlights:
telemetry.reportEvent(.Click, source: .Highlights, position: index)
let site = self.highlights[index]
showSiteWithURLHandler(URL(string:site.url)!)
case .topSites, .highlightIntro:
return
}
}
}
// MARK: Telemetry
enum ASPingEvent: String {
case Click = "CLICK"
case Delete = "DELETE"
case Dismiss = "DISMISS"
case Share = "SHARE"
}
enum ASPingSource: String {
case Highlights = "HIGHLIGHTS"
case TopSites = "TOP_SITES"
case HighlightsIntro = "HIGHLIGHTS_INTRO"
}
struct ActivityStreamTracker {
let eventsTracker: PingCentreClient
let sessionsTracker: PingCentreClient
func reportEvent(_ event: ASPingEvent, source: ASPingSource, position: Int, shareProvider: String? = nil) {
var eventPing: [String: Any] = [
"event": event.rawValue,
"page": "NEW_TAB",
"source": source.rawValue,
"action_position": position,
"app_version": AppInfo.appVersion,
"build": AppInfo.buildNumber,
"locale": Locale.current.identifier,
"release_channel": AppConstants.BuildChannel.rawValue
]
if let provider = shareProvider {
eventPing["share_provider"] = provider
}
eventsTracker.sendPing(eventPing as [String : AnyObject], validate: true)
}
func reportSessionStop(_ duration: UInt64) {
sessionsTracker.sendPing([
"session_duration": NSNumber(value: duration),
"app_version": AppInfo.appVersion,
"build": AppInfo.buildNumber,
"locale": Locale.current.identifier,
"release_channel": AppConstants.BuildChannel.rawValue
], validate: true)
}
}
// MARK: - Section Header View
struct ASHeaderViewUX {
static let SeperatorColor = UIColor(rgb: 0xedecea)
static let TextFont = DynamicFontHelper.defaultHelper.DefaultMediumBoldFont
static let SeperatorHeight = 1
static let Insets: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? ASPanelUX.SectionInsetsForIpad : ASPanelUX.SectionInsetsForIphone
static let TitleTopInset: CGFloat = 5
}
class ASHeaderView: UICollectionReusableView {
lazy fileprivate var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.text = self.title
titleLabel.textColor = UIColor.gray
titleLabel.font = ASHeaderViewUX.TextFont
return titleLabel
}()
var title: String? {
willSet(newTitle) {
titleLabel.text = newTitle
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(titleLabel)
let leftInset = UIDevice.current.userInterfaceIdiom == .pad ? ASHorizontalScrollCellUX.MinimumInsets : 0
titleLabel.snp.makeConstraints { make in
make.leading.equalTo(self).inset(ASHeaderViewUX.Insets + leftInset)
make.trailing.equalTo(self).inset(-ASHeaderViewUX.Insets)
make.top.equalTo(self).inset(ASHeaderViewUX.TitleTopInset)
make.bottom.equalTo(self)
}
let seperatorLine = UIView()
seperatorLine.backgroundColor = ASHeaderViewUX.SeperatorColor
self.backgroundColor = UIColor.clear
addSubview(seperatorLine)
seperatorLine.snp.makeConstraints { make in
make.height.equalTo(ASHeaderViewUX.SeperatorHeight)
make.leading.equalTo(self.snp.leading)
make.trailing.equalTo(self.snp.trailing)
make.top.equalTo(self.snp.top)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | dddc679a058ed388cd6d13ab38cbe5c1 | 42.299145 | 249 | 0.667127 | 5.342004 | false | false | false | false |
AstroCB/Whos-in-Space | Astronauts/SceneDelegate.swift | 1 | 2839 | //
// SceneDelegate.swift
// Astronauts
//
// Created by Cameron Bernhardt on 6/25/20.
// Copyright © 2020 Cameron Bernhardt. 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).
// Create the SwiftUI view that provides the window contents.
let response = retrieveData()
let contentView = AstronautView(astronauts: response.people)
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
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.
}
}
| mit | 54dfed63389c49d6b7c509a7500ece2f | 42.661538 | 147 | 0.705426 | 5.275093 | false | false | false | false |
haawa799/WaniKani-iOS | WaniKani/ViewControllers/LoginWebViewController.swift | 1 | 4672 | //
// LoginWebViewController.swift
// WaniKani
//
// Created by Andriy K. on 10/15/15.
// Copyright © 2015 Andriy K. All rights reserved.
//
import UIKit
import WebKit
import UIImageView_PlayGIF
protocol LoginWebViewControllerDelegate: class {
func apiKeyReceived(apiKey: String)
}
private enum ScriptHandler: String {
case ApiKey = "apikey"
case Password = "password"
case Username = "username"
}
class LoginWebViewController: UIViewController {
weak var delegate: LoginWebViewControllerDelegate?
private var webView: WKWebView!
private var credentials: (user: String, password: String)? = {
if let usr = appDelegate.keychainManager.user, let psw = appDelegate.keychainManager.password {
return (usr, psw)
}
return nil
}()
@IBOutlet weak var shibaSpinnerImageView: UIImageView! {
didSet {
shibaSpinnerImageView?.gifPath = NSBundle.mainBundle().pathForResource("3dDoge", ofType: "gif")
shibaSpinnerImageView?.startGIF()
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupWebView()
addBackground(BackgroundOptions.Dashboard.rawValue)
}
private let script = UserScript(filename: "api_key_script", scriptName: "api_key_script")
private func setupWebView() {
let source = script.script
let userScript = WKUserScript(source: source, injectionTime: .AtDocumentEnd, forMainFrameOnly: true)
let userContentController = WKUserContentController()
userContentController.addUserScript(userScript)
userContentController.addScriptMessageHandler(self, name: ScriptHandler.ApiKey.rawValue)
userContentController.addScriptMessageHandler(self, name: ScriptHandler.Username.rawValue)
userContentController.addScriptMessageHandler(self, name: ScriptHandler.Password.rawValue)
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
webView = WKWebView(frame: self.view.bounds, configuration: configuration)
let request = NSURLRequest(URL: NSURL(string: "https://www.wanikani.com/dashboard")!, cachePolicy: NSURLRequestCachePolicy.ReloadRevalidatingCacheData, timeoutInterval: 15.0)
webView.loadRequest(request)
webView.navigationDelegate = self
view.addSubview(webView)
if credentials != nil {
webView.userInteractionEnabled = false
webView.hidden = true
}
}
@IBAction func donePressed(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
var isDeepParsing = false {
didSet {
if isDeepParsing == true {
webView.alpha = 0
}
}
}
}
extension LoginWebViewController: WKNavigationDelegate {
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
if let credentials = credentials {
webView.evaluateJavaScript("loginIfNeeded('\(credentials.user)','\(credentials.password)');", completionHandler: nil)
}
}
}
extension LoginWebViewController: WKScriptMessageHandler {
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard let handler = ScriptHandler(rawValue: message.name) else { return }
switch handler {
case .ApiKey:
guard let apiKey = message.body as? String else { return }
if apiKey == "no" || apiKey == "" {
if isDeepParsing == false {
isDeepParsing = true
webView.evaluateJavaScript("openSettings()", completionHandler: { (response, error) -> Void in
delay(2.0, closure: { () -> () in
self.webView.evaluateJavaScript("generateNewKey();", completionHandler: { (response, error) -> Void in
delay(2.0, closure: { () -> () in
self.webView.evaluateJavaScript("findKey();", completionHandler: { (response, error) -> Void in
if let apiK = response as? String where apiK.characters.count == 32 {
self.submitApiKey(apiK)
}
self.isDeepParsing = false
})
})
})
})
})
}
} else {
submitApiKey(apiKey)
}
case .Username:
if let string = message.body as? String {
appDelegate.keychainManager.setUsername(string)
}
case .Password:
if let string = message.body as? String {
appDelegate.keychainManager.setPassword(string)
}
}
}
func submitApiKey(apiKey: String) {
dismissViewControllerAnimated(true) { () -> Void in
self.delegate?.apiKeyReceived(apiKey)
}
}
}
| gpl-3.0 | 914d6e3a8a3708dcc007db34995475c3 | 31.213793 | 178 | 0.673517 | 4.870699 | false | false | false | false |
yizzuide/Lego-swift | LegoExample/LegoExample/Classes/Application/Login/LoginViewController.swift | 1 | 2438 | //
// LoginViewController.swift
// LegoExample
//
// Created by yizzuide on 2020/5/16.
// Copyright © 2020 yizzuide. All rights reserved.
//
import UIKit
import XFLegoVIPER
class LoginViewController: XFComponentViewController {
//MARK:- Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
print("LoginViewController -- URL参数数据: \(self.urlParams["id"]!)")
}
override func componentWillBecomeFocus() {
print("LoginViewController -- componentWillBecomeFocus")
}
// 上一个组件可能设置的意图数据(注意:只要这个方法调用,intentData一定会有值)
override func onNewIntent(_ intentData: Any) {
print("LoginViewController -- 接收上一个组件返回数据:\(intentData)")
}
// 接收组件事件函数
override func receiveComponentEventName(_ eventName: String, intentData: Any?) {
if eventName == "Event_ReloadData" {
print("LoginViewController -- 收到刷新数据的事件")
return
}
if eventName == "Event_Register_load" {
print("LoginViewController -- 收到注册加载的事件")
return
}
}
//MARK:- Action
@IBAction func indexAction() {
// 设置意图数据(可以是任意类型数据,包括自定义对象)
self.intentData = ["username" : "yii"]
// push到下一个组件
self.uiBus.openURL(forPush: "xf://mainIndex?navTitle=主页")
}
@IBAction func registerAction() {
self.intentData = ["username" : "yii"]
// 跳转到OC实现的模块组件(使用动态参数+自定义操作代码)
self.uiBus.openURL(forPush: XFURLParse.url(fromPath: "xf://login/register", params: ["navTitle": "注册"])) { (nextInterface) in
nextInterface.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: nil, action: nil)
}
// 自定义跳转
/*self.uiBus.openURL("xf://login/register", withTransitionBlock: { (thisInterface, nextInterface, TransitionCompletionBlock) in
}) { (nextInterface) in
}*/
}
@IBAction func losePwdAction() {
// 跳转到一个没有类前辍的控制器
self.uiBus.openURL(forPush: "xf://login/findLosePwd?navTitle=找回密码")
}
}
| mit | 5acf7b4eb12a584b9a583cb3bb104ee1 | 28.788732 | 135 | 0.611348 | 3.945896 | false | false | false | false |
zype/ZypeAppleTVBase | ZypeAppleTVBase/Models/ResponseModels/BaseModel.swift | 1 | 1517 | //
// BaseModel.swift
// Zype
//
// Created by Ilya Sorokin on 10/11/15.
// Copyright © 2015 Eugene Lizhnyk. All rights reserved.
//
import UIKit
open class BaseModel : NSObject {
open var titleString: String = ""
fileprivate(set) open var ID: String = ""
var userData = Dictionary<String, AnyObject>()
init(json: Dictionary<String, AnyObject>)
{
super.init()
do
{
self.ID = try SSUtils.stringFromDictionary(json, key: kJSON_Id)
self.titleString = try SSUtils.stringFromDictionary(json, key: kJSONTitle)
}
catch _
{
ZypeLog.error("Exception: BaseModel")
}
}
init(json: Dictionary<String, AnyObject>, title: String)
{
super.init()
self.titleString = title
do
{
self.ID = try SSUtils.stringFromDictionary(json, key: kJSON_Id)
}
catch _
{
ZypeLog.error("Exception: BaseModel")
}
}
public init(ID: String, title: String)
{
super.init()
self.ID = ID
self.titleString = title
}
}
public func == (lhs: BaseModel, rhs: BaseModel) -> Bool
{
return lhs.ID == rhs.ID
}
public func <=(lhs: BaseModel, rhs: BaseModel) -> Bool
{
return lhs.ID <= rhs.ID
}
public func >(lhs: BaseModel, rhs: BaseModel) -> Bool
{
return lhs.ID > rhs.ID
}
public func >=(lhs: BaseModel, rhs: BaseModel) -> Bool
{
return lhs.ID >= rhs.ID
}
| mit | 50a6195ce048d56f20528d1b9ee80d7d | 19.767123 | 86 | 0.559367 | 3.799499 | false | false | false | false |
Can-Sahin/Moya-PromiseKit-Service | Example/MoyaPromiseExample/Examples/SSLPinningService/SomeSSLPinningDataService.swift | 1 | 2073 | //
// SomeSSLPinningDataService.swift
// Moya-PromiseKit-Service
//
// Created by Can Sahin on 01/11/2017.
// Copyright © 2017 Can Sahin. All rights reserved.
//
import Foundation
import Moya
import PromiseKit
import Alamofire
import MoyaPromise
/*
Make your own concrete DataService from DataServiceProtocol and implement SSL PublicKey pinning at init
*/
public class SSLPinningDataService<Target: TargetType> : DataServiceProtocol {
public typealias MoyaTarget = Target
public var moyaProvider: MoyaProvider<Target>
init(){
/*
- Creating a certificate file of remote server using 'openssl' -
Install openssl (brew recommended)
Type the following commands (First produces .pem file then converts it to .der file)
openssl s_client -showcerts -connect {HOST}:{PORT} -prexit > {FILENAME}.pem </dev/null;
openssl x509 -outform der -in {FILENAME}.pem -out {CERTIFICATENAME}.der
Import your .der file in a bundle (main bundle default) and Alamofire will look for all the public keys in all .der files. No need to specify the file's location
*/
let HOST = "{YOUR_HOST_URL}"
let trustPolicy = ServerTrustPolicy.pinPublicKeys(publicKeys: ServerTrustPolicy.publicKeys(), validateCertificateChain: true, validateHost: true)
let serverTrustPolicies = [
HOST:trustPolicy
]
let policyManager = ServerTrustPolicyManager(policies: serverTrustPolicies)
let manager = Manager(configuration: URLSessionConfiguration.default, delegate: SessionDelegate(),serverTrustPolicyManager:policyManager)
// ALL requests that fails the pinning return NSCancelledError.
self.moyaProvider = MoyaProvider<Target>(manager: manager)
}
}
// Initialize from your concrete class
public class SomeSSLPinningDataService: SSLPinningDataService<CarAPI>{
public func getSomething() -> Promise<String>{
return self.request(target: CarAPI.Wheels).asString().promise
}
}
| mit | f51c193b4db8525002b25363e5e86b33 | 36.672727 | 170 | 0.702703 | 4.829837 | false | false | false | false |
artursDerkintis/Starfly | Starfly/SFSearchTable.swift | 1 | 8010 | //
// SFSearchTable.swift
// Starfly
//
// Created by Arturs Derkintis on 10/3/15.
// Copyright © 2015 Starfly. All rights reserved.
//
import UIKit
import CoreData
let querie = "http://suggestqueries.google.com/complete/search?client=toolbar&hl=en&q="
class SFSearchTable: UIView, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate{
private var googleTable : UITableView?
private var historyTable : UITableView?
private var array = [String]()
let app = UIApplication.sharedApplication().delegate as! AppDelegate
private var fetchController : NSFetchedResultsController?
private var textForSearch = ""
override init(frame: CGRect) {
super.init(frame: frame)
fetchController = NSFetchedResultsController(fetchRequest: simpleHistoryRequest, managedObjectContext: SFDataHelper.sharedInstance.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
fetchController?.delegate = self
googleTable = UITableView(frame: CGRect.zero)
googleTable!.registerClass(SFSearchTableCell.self, forCellReuseIdentifier: "search")
googleTable!.delegate = self
googleTable!.dataSource = self
googleTable!.backgroundColor = UIColor(white: 0.9, alpha: 0.0)
googleTable?.separatorColor = UIColor.whiteColor().colorWithAlphaComponent(0.6)
historyTable = UITableView(frame: CGRect.zero)
historyTable!.registerClass(SFHistoryCellSearch.self, forCellReuseIdentifier: "search2")
historyTable!.delegate = self
historyTable!.dataSource = self
historyTable!.backgroundColor = UIColor(white: 0.9, alpha: 0.0)
historyTable?.separatorColor = UIColor.whiteColor().colorWithAlphaComponent(0.6)
let stackView = UIStackView(arrangedSubviews: [googleTable!, historyTable!])
stackView.distribution = .FillEqually
stackView.spacing = 20
addSubview(stackView)
stackView.snp_makeConstraints { (make) -> Void in
make.top.bottom.right.left.equalTo(0)
}
}
lazy var simpleHistoryRequest : NSFetchRequest = {
let request : NSFetchRequest = NSFetchRequest(entityName: "HistoryHit")
request.sortDescriptors = [NSSortDescriptor(key: "arrangeIndex", ascending: false)]
return request
}()
func getSuggestions(forText string : String){
if string != ""{
textForSearch = string
let what : NSString = string.stringByReplacingOccurrencesOfString(" ", withString: "+")
let set = NSCharacterSet.URLQueryAllowedCharacterSet()
let formated : String = NSString(format: "%@%@", querie, what).stringByAddingPercentEncodingWithAllowedCharacters(set)!
NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: NSURL(string: formated)!)) { (data : NSData?, res, error : NSError?) -> Void in
if error == nil{
do {
let xmlDoc = try AEXMLDocument(xmlData: data! as NSData)
self.array.removeAll()
for chilcd in xmlDoc["toplevel"].children {
let string = chilcd["suggestion"].attributes["data"] as String?
if let str = string{
self.array.append(str)
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.googleTable!.delegate = self
self.googleTable!.reloadData()
})
} catch _ {
}
}else{
print(error?.localizedDescription)
}
}.resume()
let resultPredicate1 : NSPredicate = NSPredicate(format: "titleOfIt CONTAINS[cd] %@", string)
let resultPredicate2 : NSPredicate = NSPredicate(format: "urlOfIt CONTAINS[cd] %@", string)
let compound = NSCompoundPredicate(orPredicateWithSubpredicates: [resultPredicate1, resultPredicate2])
fetchController?.fetchRequest.predicate = compound
do{
try fetchController?.performFetch()
historyTable?.reloadData()
}catch _{
}
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if tableView == googleTable{
if array.count > 0{
if let url = NSURL(string: parseUrl(array[indexPath.row])!){
print("google \(url)")
NSNotificationCenter.defaultCenter().postNotificationName("OPEN", object:url)
}
}
}else if tableView == historyTable{
let object = fetchController?.objectAtIndexPath(indexPath) as! HistoryHit
print("google \(object.getURL())")
NSNotificationCenter.defaultCenter().postNotificationName("OPEN", object: object.getURL())
}
UIApplication.sharedApplication().delegate?.window!?.endEditing(true)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == self.googleTable{
let cell = tableView.dequeueReusableCellWithIdentifier("search", forIndexPath: indexPath) as! SFSearchTableCell
if array.count > indexPath.row{
let text = array[indexPath.row]
cell.label?.text = text
}
return cell
}else if tableView == self.historyTable{
let cell = tableView.dequeueReusableCellWithIdentifier("search2", forIndexPath: indexPath) as! SFHistoryCellSearch
let object = fetchController?.objectAtIndexPath(indexPath) as! HistoryHit
let title = NSMutableAttributedString(string: object.titleOfIt!)
let rangeT = (object.titleOfIt! as NSString).rangeOfString(textForSearch, options: NSStringCompareOptions.CaseInsensitiveSearch)
title.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSMakeRange(0, title.length))
title.addAttribute(NSForegroundColorAttributeName, value: UIColor(white: 0.75, alpha: 1.0), range: rangeT)
let url = NSMutableAttributedString(string: object.urlOfIt!)
let rangeU = (object.urlOfIt! as NSString).rangeOfString(textForSearch, options: NSStringCompareOptions.CaseInsensitiveSearch)
url.addAttribute(NSForegroundColorAttributeName, value: UIColor(white: 0.9, alpha: 1.0), range: NSMakeRange(0, url.length))
url.addAttribute(NSForegroundColorAttributeName, value: UIColor(white: 0.8, alpha: 1.0), range: rangeU)
cell.titleLabel?.textColor = nil
cell.urlLabel?.textColor = nil
cell.titleLabel?.attributedText = title
cell.urlLabel?.attributedText = url
return cell
}
return UITableViewCell()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == googleTable{
return array.count
}else if tableView == historyTable{
if self.fetchController!.sections != nil{
let sectionInfo = self.fetchController!.sections![section] as NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
}
return 0
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 0b8f430b00cdc5dde4b44b28fc8238db | 46.390533 | 201 | 0.611437 | 5.652082 | false | false | false | false |
Fenrikur/ef-app_ios | Eurofurence/Director/ApplicationModuleRepository.swift | 1 | 14192 | import EurofurenceModel
import UIKit
struct ApplicationModuleRepository: ModuleRepository {
private let webModuleProviding: WebModuleProviding
private let rootModuleProviding: RootModuleProviding
private let tutorialModuleProviding: TutorialModuleProviding
private let preloadModuleProviding: PreloadModuleProviding
private let newsModuleProviding: NewsModuleProviding
private let scheduleModuleProviding: ScheduleModuleProviding
private let dealersModuleProviding: DealersModuleProviding
private let dealerDetailModuleProviding: DealerDetailModuleProviding
private let collectThemAllModuleProviding: CollectThemAllModuleProviding
private let messagesModuleProviding: MessagesModuleProviding
private let loginModuleProviding: LoginModuleProviding
private let messageDetailModuleProviding: MessageDetailModuleProviding
private let knowledgeListModuleProviding: KnowledgeGroupsListModuleProviding
private let knowledgeGroupEntriesModule: KnowledgeGroupEntriesModuleProviding
private let knowledgeDetailModuleProviding: KnowledgeDetailModuleProviding
private let mapsModuleProviding: MapsModuleProviding
private let mapDetailModuleProviding: MapDetailModuleProviding
private let announcementsModuleFactory: AnnouncementsModuleProviding
private let announcementDetailModuleProviding: AnnouncementDetailModuleProviding
private let eventDetailModuleProviding: EventDetailModuleProviding
private let eventFeedbackModuleProviding: EventFeedbackModuleProviding
private let additionalServicesModuleProviding: AdditionalServicesModuleProviding
// swiftlint:disable function_body_length
init(services: Services, repositories: Repositories) {
let subtleMarkdownRenderer = SubtleDownMarkdownRenderer()
let defaultMarkdownRenderer = DefaultDownMarkdownRenderer()
let shareService = ActivityShareService()
let activityFactory = PlatformActivityFactory()
rootModuleProviding = RootModuleBuilder(sessionStateService: services.sessionState).build()
tutorialModuleProviding = TutorialModuleBuilder().build()
let preloadInteractor = ApplicationPreloadInteractor(refreshService: services.refresh)
preloadModuleProviding = PreloadModuleBuilder(preloadInteractor: preloadInteractor).build()
let newsInteractor = DefaultNewsInteractor(announcementsService: services.announcements,
authenticationService: services.authentication,
privateMessagesService: services.privateMessages,
daysUntilConventionService: services.conventionCountdown,
eventsService: services.events,
relativeTimeIntervalCountdownFormatter: FoundationRelativeTimeIntervalCountdownFormatter.shared,
hoursDateFormatter: FoundationHoursDateFormatter.shared,
clock: SystemClock.shared,
refreshService: services.refresh,
announcementsDateFormatter: FoundationAnnouncementDateFormatter.shared,
announcementsMarkdownRenderer: subtleMarkdownRenderer)
newsModuleProviding = NewsModuleBuilder(newsInteractor: newsInteractor).build()
let scheduleInteractor = DefaultScheduleInteractor(eventsService: services.events,
hoursDateFormatter: FoundationHoursDateFormatter.shared,
shortFormDateFormatter: FoundationShortFormDateFormatter.shared,
shortFormDayAndTimeFormatter: FoundationShortFormDayAndTimeFormatter.shared,
refreshService: services.refresh)
scheduleModuleProviding = ScheduleModuleBuilder(interactor: scheduleInteractor).build()
let defaultDealerIcon = #imageLiteral(resourceName: "defaultAvatar")
guard let defaultDealerIconData = defaultDealerIcon.pngData() else { fatalError("Default dealer icon is not a PNG") }
let dealersInteractor = DefaultDealersInteractor(dealersService: services.dealers, defaultIconData: defaultDealerIconData, refreshService: services.refresh)
dealersModuleProviding = DealersModuleBuilder(interactor: dealersInteractor).build()
let dealerIntentDonor = ConcreteViewDealerIntentDonor()
let dealerInteractionRecorder = DonateIntentDealerInteractionRecorder(
viewDealerIntentDonor: dealerIntentDonor,
dealersService: services.dealers,
activityFactory: activityFactory
)
let dealerDetailInteractor = DefaultDealerDetailInteractor(dealersService: services.dealers, shareService: shareService)
dealerDetailModuleProviding = DealerDetailModuleBuilder(dealerDetailInteractor: dealerDetailInteractor, dealerInteractionRecorder: dealerInteractionRecorder).build()
collectThemAllModuleProviding = CollectThemAllModuleBuilder(service: services.collectThemAll).build()
messagesModuleProviding = MessagesModuleBuilder(authenticationService: services.authentication, privateMessagesService: services.privateMessages).build()
loginModuleProviding = LoginModuleBuilder(authenticationService: services.authentication).build()
messageDetailModuleProviding = MessageDetailModuleBuilder(privateMessagesService: services.privateMessages).build()
let knowledgeListInteractor = DefaultKnowledgeGroupsInteractor(service: services.knowledge)
knowledgeListModuleProviding = KnowledgeGroupsModuleBuilder(knowledgeListInteractor: knowledgeListInteractor).build()
let knowledgeGroupEntriesInteractor = DefaultKnowledgeGroupEntriesInteractor(service: services.knowledge)
knowledgeGroupEntriesModule = KnowledgeGroupEntriesModuleBuilder(interactor: knowledgeGroupEntriesInteractor).build()
let knowledgeDetailSceneInteractor = DefaultKnowledgeDetailSceneInteractor(
knowledgeService: services.knowledge,
renderer: defaultMarkdownRenderer,
shareService: shareService
)
knowledgeDetailModuleProviding = KnowledgeDetailModuleBuilder(knowledgeDetailSceneInteractor: knowledgeDetailSceneInteractor).build()
let mapsInteractor = DefaultMapsInteractor(mapsService: services.maps)
mapsModuleProviding = MapsModuleBuilder(interactor: mapsInteractor).build()
let mapDetailInteractor = DefaultMapDetailInteractor(mapsService: services.maps)
mapDetailModuleProviding = MapDetailModuleBuilder(interactor: mapDetailInteractor).build()
let announcementsInteractor = DefaultAnnouncementsInteractor(announcementsService: services.announcements,
announcementDateFormatter: FoundationAnnouncementDateFormatter.shared,
markdownRenderer: subtleMarkdownRenderer)
announcementsModuleFactory = AnnouncementsModuleBuilder(announcementsInteractor: announcementsInteractor).build()
let announcementDetailInteractor = DefaultAnnouncementDetailInteractor(announcementsService: services.announcements,
markdownRenderer: defaultMarkdownRenderer)
announcementDetailModuleProviding = AnnouncementDetailModuleBuilder(announcementDetailInteractor: announcementDetailInteractor).build()
let eventIntentDonor = ConcreteEventIntentDonor()
let eventInteractionRecorder = SystemEventInteractionsRecorder(
eventsService: services.events,
eventIntentDonor: eventIntentDonor,
activityFactory: activityFactory
)
let eventDetailInteractor = DefaultEventDetailInteractor(dateRangeFormatter: FoundationDateRangeFormatter.shared,
eventsService: services.events,
markdownRenderer: DefaultDownMarkdownRenderer(),
shareService: shareService)
eventDetailModuleProviding = EventDetailModuleBuilder(interactor: eventDetailInteractor, interactionRecorder: eventInteractionRecorder).build()
let eventFeedbackPresenterFactory = EventFeedbackPresenterFactoryImpl(eventService: services.events,
dayOfWeekFormatter: FoundationDayOfWeekFormatter.shared,
startTimeFormatter: FoundationHoursDateFormatter.shared,
endTimeFormatter: FoundationHoursDateFormatter.shared,
successHaptic: CocoaTouchSuccessHaptic(),
failureHaptic: CocoaTouchFailureHaptic(),
successWaitingRule: ShortDelayEventFeedbackSuccessWaitingRule())
let eventFeedbackSceneFactory = StoryboardEventFeedbackSceneFactory()
eventFeedbackModuleProviding = EventFeedbackModuleProvidingImpl(presenterFactory: eventFeedbackPresenterFactory, sceneFactory: eventFeedbackSceneFactory)
webModuleProviding = SafariWebModuleProviding()
additionalServicesModuleProviding = AdditionalServicesModuleBuilder(repository: repositories.additionalServices).build()
}
func makeRootModule(_ delegate: RootModuleDelegate) {
rootModuleProviding.makeRootModule(delegate)
}
func makeTutorialModule(_ delegate: TutorialModuleDelegate) -> UIViewController {
return tutorialModuleProviding.makeTutorialModule(delegate)
}
func makePreloadModule(_ delegate: PreloadModuleDelegate) -> UIViewController {
return preloadModuleProviding.makePreloadModule(delegate)
}
func makeNewsModule(_ delegate: NewsModuleDelegate) -> UIViewController {
return newsModuleProviding.makeNewsModule(delegate)
}
func makeLoginModule(_ delegate: LoginModuleDelegate) -> UIViewController {
return loginModuleProviding.makeLoginModule(delegate)
}
func makeAnnouncementsModule(_ delegate: AnnouncementsModuleDelegate) -> UIViewController {
return announcementsModuleFactory.makeAnnouncementsModule(delegate)
}
func makeAnnouncementDetailModule(for announcement: AnnouncementIdentifier) -> UIViewController {
return announcementDetailModuleProviding.makeAnnouncementDetailModule(for: announcement)
}
func makeEventDetailModule(for event: EventIdentifier, delegate: EventDetailModuleDelegate) -> UIViewController {
return eventDetailModuleProviding.makeEventDetailModule(for: event, delegate: delegate)
}
func makeEventFeedbackModule(for event: EventIdentifier, delegate: EventFeedbackModuleDelegate) -> UIViewController {
return eventFeedbackModuleProviding.makeEventFeedbackModule(for: event, delegate: delegate)
}
func makeWebModule(for url: URL) -> UIViewController {
return webModuleProviding.makeWebModule(for: url)
}
func makeMessagesModule(_ delegate: MessagesModuleDelegate) -> UIViewController {
return messagesModuleProviding.makeMessagesModule(delegate)
}
func makeMessageDetailModule(message: MessageIdentifier) -> UIViewController {
return messageDetailModuleProviding.makeMessageDetailModule(for: message)
}
func makeScheduleModule(_ delegate: ScheduleModuleDelegate) -> UIViewController {
return scheduleModuleProviding.makeScheduleModule(delegate)
}
func makeDealersModule(_ delegate: DealersModuleDelegate) -> UIViewController {
return dealersModuleProviding.makeDealersModule(delegate)
}
func makeDealerDetailModule(for identifier: DealerIdentifier) -> UIViewController {
return dealerDetailModuleProviding.makeDealerDetailModule(for: identifier)
}
func makeKnowledgeListModule(_ delegate: KnowledgeGroupsListModuleDelegate) -> UIViewController {
return knowledgeListModuleProviding.makeKnowledgeListModule(delegate)
}
func makeKnowledgeDetailModule(_ identifier: KnowledgeEntryIdentifier, delegate: KnowledgeDetailModuleDelegate) -> UIViewController {
return knowledgeDetailModuleProviding.makeKnowledgeListModule(identifier, delegate: delegate)
}
func makeKnowledgeGroupEntriesModule(_ knowledgeGroup: KnowledgeGroupIdentifier, delegate: KnowledgeGroupEntriesModuleDelegate) -> UIViewController {
return knowledgeGroupEntriesModule.makeKnowledgeGroupEntriesModule(knowledgeGroup, delegate: delegate)
}
func makeMapsModule(_ delegate: MapsModuleDelegate) -> UIViewController {
return mapsModuleProviding.makeMapsModule(delegate)
}
func makeMapDetailModule(for identifier: MapIdentifier, delegate: MapDetailModuleDelegate) -> UIViewController {
return mapDetailModuleProviding.makeMapDetailModule(for: identifier, delegate: delegate)
}
func makeCollectThemAllModule() -> UIViewController {
return collectThemAllModuleProviding.makeCollectThemAllModule()
}
func makeAdditionalServicesModule() -> UIViewController {
return additionalServicesModuleProviding.makeAdditionalServicesModule()
}
}
| mit | 9d1c6aea9a12c8c937388b4597eabf23 | 61.519824 | 173 | 0.703143 | 7.124498 | false | false | false | false |
stevethomp/ViDIA-Playgrounds | ImportantWorkProject/Carthage/Checkouts/airg-ios-tools/airgiOSTools/Designables.swift | 1 | 5044 | //
// Designables.swift
// airG-iOS-Tools
//
// Created by Steven Thompson on 2016-07-26.
// Copyright © 2016 airg. All rights reserved.
//
import UIKit
//MARK: @IBDesignable
@IBDesignable
public extension UIView {
@IBInspectable public var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
get {
return layer.cornerRadius
}
}
@IBInspectable public var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable public var borderColor: UIColor? {
set {
layer.borderColor = newValue?.cgColor
}
get {
if let layerColor = layer.borderColor {
return UIColor(cgColor: layerColor)
} else {
return nil
}
}
}
@IBInspectable public var shadowColor: UIColor? {
set {
layer.shadowColor = newValue?.cgColor
}
get {
if let shadowColor = layer.shadowColor {
return UIColor(cgColor: shadowColor)
} else {
return nil
}
}
}
@IBInspectable public var shadowRadius: CGFloat? {
set {
layer.shadowRadius = newValue ?? 0
}
get {
return layer.shadowRadius
}
}
}
//MARK:-
extension UIButton {
override open var intrinsicContentSize : CGSize {
let s = super.intrinsicContentSize
return CGSize(width: s.width + titleEdgeInsets.left + titleEdgeInsets.right, height: s.height + titleEdgeInsets.top + titleEdgeInsets.bottom)
}
}
//MARK:-
@IBDesignable
open class ExtraPaddingTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBInspectable open var horizontalPadding: CGFloat = 0 {
didSet {
edgeInsets = UIEdgeInsets(top: 0, left: horizontalPadding, bottom: 0, right: horizontalPadding)
invalidateIntrinsicContentSize()
}
}
fileprivate var edgeInsets: UIEdgeInsets = UIEdgeInsets.zero
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, edgeInsets)
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, edgeInsets)
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, edgeInsets)
}
override open func rightViewRect(forBounds bounds: CGRect) -> CGRect {
if let rightView = rightView {
return CGRect(x: bounds.size.width - horizontalPadding - rightView.frame.size.width,
y: bounds.size.height/2 - rightView.frame.size.height/2,
width: rightView.frame.size.width,
height: rightView.frame.size.height)
}
return CGRect()
}
}
//MARK:-
@IBDesignable
open class ExtraPaddingLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBInspectable open var extraHorizontalPadding: CGFloat = 0 {
didSet {
invalidateIntrinsicContentSize()
}
}
@IBInspectable open var extraVerticalPadding: CGFloat = 0 {
didSet {
invalidateIntrinsicContentSize()
}
}
override open var intrinsicContentSize : CGSize {
let s = super.intrinsicContentSize
return CGSize(width: s.width + 2 * extraHorizontalPadding, height: s.height + 2 * extraVerticalPadding)
}
}
//MARK:-
@IBDesignable
open class ExtraPaddingTextView: UITextView {
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBInspectable var horizontalPadding: CGFloat = 0 {
didSet {
textContainerInset = UIEdgeInsets(top: textContainerInset.top, left: horizontalPadding, bottom: textContainerInset.bottom, right: horizontalPadding)
invalidateIntrinsicContentSize()
}
}
@IBInspectable var verticalPadding: CGFloat = 8 {
didSet {
textContainerInset = UIEdgeInsets(top: verticalPadding, left: textContainerInset.left, bottom: verticalPadding, right: textContainerInset.right)
invalidateIntrinsicContentSize()
}
}
override open var intrinsicContentSize : CGSize {
let s = super.intrinsicContentSize
return CGSize(width: s.width + 2 * horizontalPadding, height: s.height + 2 * verticalPadding)
}
}
| apache-2.0 | 387a810517ec1361aba6cf4c2df69277 | 27.331461 | 160 | 0.618283 | 5.151175 | false | false | false | false |
codefellows/sea-b29-iOS | Sample Projects/Week 1/TweetFellows/TweetFellows/TweetViewController.swift | 1 | 2054 | //
// TweetViewController.swift
// TweetFellows
//
// Created by Bradley Johnson on 1/8/15.
// Copyright (c) 2015 BPJ. All rights reserved.
//
import UIKit
class TweetViewController: UIViewController {
var tweet : Tweet!
@IBOutlet weak var favoritesLabel: UILabel!
@IBOutlet weak var tweetTextLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var userButton: UIButton!
var networkController : NetworkController!
override func viewDidLoad() {
super.viewDidLoad()
// self.userButton.setImage(self.tweet.image!, forState: .Normal)
self.userButton.setBackgroundImage(self.tweet.image!, forState: UIControlState.Normal)
self.tweetTextLabel.text = tweet.text
self.usernameLabel.text = tweet.username
// Do any additional setup after loading the view.
self.networkController.fetchInfoForTweet(tweet.id, completionHandler: { (infoDictionary, errorDescription) -> () in
println(infoDictionary)
if errorDescription == nil {
self.tweet.updateWithInfo(infoDictionary!)
self.favoritesLabel.text = self.tweet.favoriteCount
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func userButtonPressed(sender: AnyObject) {
let userVC = self.storyboard?.instantiateViewControllerWithIdentifier("USER_VC") as UserViewController
userVC.networkController = self.networkController
userVC.userID = self.tweet.userID
self.navigationController?.pushViewController(userVC, animated: true)
}
}
| mit | 4f44589594a53e97a1e99746c468c2bd | 32.672131 | 121 | 0.706426 | 4.902148 | false | false | false | false |
trvslhlt/games-for-impact-final | projects/WinkWink_11/WinkWink/Views/NavigationView.swift | 1 | 2949 | //
// NavigationView.swift
// WinkWink_11
//
// Created by trvslhlt on 4/11/17.
// Copyright © 2017 travis holt. All rights reserved.
//
import UIKit
protocol NavigationViewDelegate: class {
func navigationRightCancelTapped()
}
class NavigationView: AppView {
weak var delegate: NavigationViewDelegate?
private let rightControl = CancelButton()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override func commonInit() {
super.commonInit()
rightControl.addTarget(self, action: #selector(NavigationView.didTapRightControl), for: .touchUpInside)
addSubview(rightControl)
rightControl.translatesAutoresizingMaskIntoConstraints = false
let rightControlDimension = Configuration.layout.navigationHeight - Configuration.layout.paddingDefault * 2
let centerY = NSLayoutConstraint(item: rightControl,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: self,
attribute: NSLayoutAttribute.centerY,
multiplier: 1, constant: 0)
let width = NSLayoutConstraint(item: rightControl,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: rightControlDimension)
let height = NSLayoutConstraint(item: rightControl,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: rightControlDimension)
let rightSpacing = NSLayoutConstraint(item: rightControl,
attribute: NSLayoutAttribute.right,
relatedBy: NSLayoutRelation.equal,
toItem: self,
attribute: NSLayoutAttribute.right,
multiplier: 1,
constant: -Configuration.layout.paddingDefault)
addConstraints([centerY, width, height, rightSpacing])
}
func didTapRightControl() {
delegate?.navigationRightCancelTapped()
}
}
| mit | 6cb290bee04a2dca204e7a351a9714ce | 43 | 115 | 0.504749 | 7.019048 | false | false | false | false |
rectinajh/leetCode_Swift | Jump_Game/Jump_Game/Jump_Game.swift | 1 | 1168 | //
// Jump_Game.swift
// Jump_Game
//
// Created by hua on 16/8/24.
// Copyright © 2016年 212. All rights reserved.
//
import Foundation
/*
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
» Solve this problem
[解题报告]
一维DP,定义 jump[i]为从index 0 走到第i步时,剩余的最大步数。
那么转移方程可定义为
jump[i] = max(jump[i-1], A[i-1]) -1, i!=0
= 0 , i==0
然后从左往右扫描,当jump[i]<0的时候,意味着不可能走到i步,所以return false; 如果走到最右端,那么return true.
Inspired by http://fisherlei.blogspot.com/2012/12/leetcode-jump-game.html
*/
class Solution {
static func canJump(nums: [Int]) -> Bool {
var i = 0
var reach = 0
while i < nums.count && i <= reach {
reach = max (i + nums[i],reach)
i += 1
}
return i == nums.count
}
}
| mit | 9fb8329b8b6da1cfe18413ef07667fd9 | 22.767442 | 103 | 0.626223 | 2.862745 | false | false | false | false |
grandiere/box | box/View/Handler/VHandlerField.swift | 1 | 2738 | import UIKit
class VHandlerField:UITextField, UITextFieldDelegate
{
private weak var controller:CHandler?
private let kBorderHeight:CGFloat = 1
private let kMaxCharacter:Int = 10
init(controller:CHandler)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = UIColor.clear
font = UIFont.regular(size:34)
textColor = UIColor.white
tintColor = UIColor.white
autocorrectionType = UITextAutocorrectionType.no
autocapitalizationType = UITextAutocapitalizationType.none
spellCheckingType = UITextSpellCheckingType.no
keyboardType = UIKeyboardType.alphabet
keyboardAppearance = UIKeyboardAppearance.light
borderStyle = UITextBorderStyle.none
clearButtonMode = UITextFieldViewMode.never
text = MSession.sharedInstance.handler
delegate = self
self.controller = controller
let border:VBorder = VBorder(color:UIColor(white:1, alpha:0.5))
addSubview(border)
NSLayoutConstraint.bottomToBottom(
view:border,
toView:self)
NSLayoutConstraint.height(
view:border,
constant:1)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: field delegate
func textFieldShouldReturn(_ textField:UITextField) -> Bool
{
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField:UITextField)
{
guard
let handler:String = textField.text
else
{
return
}
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{
MSession.sharedInstance.updateHandler(handler:handler)
DispatchQueue.main.async
{ [weak self] in
self?.controller?.updateWarning()
}
}
}
func textField(_ textField:UITextField, shouldChangeCharactersIn range:NSRange, replacementString string:String) -> Bool
{
guard
let text:String = textField.text
else
{
return false
}
let nsString:NSString = text as NSString
let replaced:String = nsString.replacingCharacters(in:range, with:string)
if replaced.characters.count > kMaxCharacter
{
return false
}
return true
}
}
| mit | 2c62d2c490483a22cb8e2913c153bb83 | 25.843137 | 124 | 0.589481 | 6.017582 | false | false | false | false |
fedepo/phoneid_iOS | Pod/Classes/ui/controllers/ImageEditViewController.swift | 2 | 6332 | //
// ImageEditViewController.swift
// phoneid_iOS
//
// Copyright 2015 phone.id - 73 knots, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
open class ImageEditViewController: UIViewController, PhoneIdConsumer, Customizable {
var sourceImage: UIImage!;
fileprivate(set) var editingImageView: PanZoomImageView!
fileprivate(set) var overlayView: CircleOverlayView!
fileprivate(set) var hintLabel: UILabel!
fileprivate(set) var doneBarButton: UIBarButtonItem!
fileprivate(set) var cancelBarButton: UIBarButtonItem!
var imageEditingCompleted: ((_ editedImage:UIImage) -> Void)?
var imageEditingCancelled: (() -> Void)?
open var colorScheme: ColorScheme! {
get {
return self.phoneIdComponentFactory.colorScheme
}
}
open var localizationBundle: Bundle! {
get {
return self.phoneIdComponentFactory.localizationBundle
}
}
open var localizationTableName: String! {
get {
return self.phoneIdComponentFactory.localizationTableName }
}
required public init(image: UIImage) {
super.init(nibName: nil, bundle: nil)
sourceImage = image
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func loadView() {
super.loadView()
editingImageView = PanZoomImageView(image: nil)
overlayView = CircleOverlayView()
hintLabel = UILabel()
hintLabel.numberOfLines = 0
hintLabel.textAlignment = .center
let subviews: [UIView] = [editingImageView, overlayView, hintLabel]
for (_, element) in subviews.enumerated() {
element.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(element)
}
var c: [NSLayoutConstraint] = []
let topPadding: CGFloat = UIScreen.main.bounds.size.height < 500 ? 20 : 40
c.append(NSLayoutConstraint(item: editingImageView, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 0.95, constant: 0))
c.append(NSLayoutConstraint(item: editingImageView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 0.95, constant: 0))
c.append(NSLayoutConstraint(item: editingImageView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0))
c.append(NSLayoutConstraint(item: editingImageView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: topPadding))
c.append(NSLayoutConstraint(item: overlayView, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 0.95, constant: 0))
c.append(NSLayoutConstraint(item: overlayView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 0.95, constant: 0))
c.append(NSLayoutConstraint(item: overlayView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0))
c.append(NSLayoutConstraint(item: overlayView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: topPadding))
c.append(NSLayoutConstraint(item: hintLabel, attribute: .top, relatedBy: .equal, toItem: self.overlayView, attribute: .bottom, multiplier: 1, constant: topPadding))
c.append(NSLayoutConstraint(item: hintLabel, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 0.8, constant: topPadding))
c.append(NSLayoutConstraint(item: hintLabel, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0))
self.view.addConstraints(c)
doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(ImageEditViewController.doneButtonTapped(_:)))
cancelBarButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(ImageEditViewController.cancelButtonTapped(_:)))
doneBarButton.tintColor = self.colorScheme.headerButtonText
cancelBarButton.tintColor = self.colorScheme.headerButtonText
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: self.colorScheme.headerTitleText]
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.barStyle = UIBarStyle.default
self.navigationController?.navigationBar.barTintColor = self.colorScheme.headerBackground
self.title = localizedString("title.public.profile")
self.hintLabel.text = localizedString("profile.hint.about.picture")
self.hintLabel.textColor = self.colorScheme.profilePictureEditingHintText
}
override open func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = UIRectEdge();
self.extendedLayoutIncludesOpaqueBars = false;
self.automaticallyAdjustsScrollViewInsets = false;
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
editingImageView.image = sourceImage
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.hidesBackButton = true
self.navigationItem.leftBarButtonItems = [cancelBarButton]
self.navigationItem.rightBarButtonItems = [doneBarButton]
}
@objc func doneButtonTapped(_ sender: UIButton) {
imageEditingCompleted?(self.editingImageView.editedImage())
}
@objc func cancelButtonTapped(_ sender: UIButton) {
imageEditingCancelled?()
}
}
| apache-2.0 | 2ebf0e99ebd8708c4a63ef1a7ad01ca6 | 45.218978 | 172 | 0.712255 | 4.793338 | false | false | false | false |
veeman961/RiseRight | RoutinePlus-Xcode/RoutinePlus/UIColorExtensions.swift | 1 | 747 | //
// UIColorExtensions.swift
// RiseRight
//
// Created by Kevin Rajan on 1/3/16.
// Copyright © 2016 veeman961. All rights reserved.
//
import UIKit
class UIColorExtensions: UIColor {
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
}
| apache-2.0 | f6a5c027e7df2bd93ad8618c7cc86f56 | 26.62963 | 116 | 0.603217 | 3.330357 | false | false | false | false |
GreatfeatServices/gf-mobile-app | olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observable.swift | 54 | 1113 | //
// Observable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/// A type-erased `ObservableType`.
///
/// It represents a push style sequence.
public class Observable<Element> : ObservableType {
/// Type of elements in sequence.
public typealias E = Element
init() {
#if TRACE_RESOURCES
let _ = Resources.incrementTotal()
#endif
}
public func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
abstractMethod()
}
public func asObservable() -> Observable<E> {
return self
}
deinit {
#if TRACE_RESOURCES
let _ = Resources.decrementTotal()
#endif
}
// this is kind of ugly I know :(
// Swift compiler reports "Not supported yet" when trying to override protocol extensions, so ¯\_(ツ)_/¯
/// Optimizations for map operator
internal func composeMap<R>(_ selector: @escaping (Element) throws -> R) -> Observable<R> {
return Map(source: self, transform: selector)
}
}
| apache-2.0 | 278f1b324d4c7b9e60c4264fd4ae3df4 | 23.086957 | 107 | 0.630866 | 4.229008 | false | false | false | false |
lanjing99/iOSByTutorials | iOS 8 by tutorials/Chapter 16 - Intermediate CloudKit/BabiFud-Starter/BabiFud/Establishment.swift | 1 | 8617 | /*
* Copyright (c) 2014 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.
*
* 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 CloudKit
import MapKit
struct ChangingTableLocation : OptionSetType, BooleanType {
var rawValue: UInt = 0
var boolValue:Bool {
get {
return self.rawValue != 0
}
}
init(rawValue: UInt) { self.rawValue = rawValue }
init(nilLiteral: ()) { self.rawValue = 0 }
func toRaw() -> UInt { return self.rawValue }
static func convertFromNilLiteral() -> ChangingTableLocation { return .None}
static func fromRaw(raw: UInt) -> ChangingTableLocation? { return self.init(rawValue: raw) }
static func fromMask(raw: UInt) -> ChangingTableLocation { return self.init(rawValue: raw) }
static var allZeros: ChangingTableLocation { return self.init(rawValue: 0) }
static var None: ChangingTableLocation { return self.init(rawValue: 0) } //0
static var Mens: ChangingTableLocation { return self.init(rawValue: 1 << 0) } //1
static var Womens: ChangingTableLocation { return self.init(rawValue: 1 << 1) } //2
static var Family: ChangingTableLocation { return self.init(rawValue: 1 << 2) } //4
func images() -> [UIImage] {
var images = [UIImage]()
if self & .Mens {
images.append(UIImage(named: "man")!)
}
if self & .Womens {
images.append(UIImage(named: "woman")!)
}
return images
}
}
func == (lhs: ChangingTableLocation, rhs: ChangingTableLocation) -> Bool { return lhs.rawValue == rhs.rawValue }
func | (lhs: ChangingTableLocation, rhs: ChangingTableLocation) -> ChangingTableLocation { return ChangingTableLocation(rawValue: lhs.rawValue | rhs.rawValue) }
func & (lhs: ChangingTableLocation, rhs: ChangingTableLocation) -> ChangingTableLocation { return ChangingTableLocation(rawValue: lhs.rawValue & rhs.rawValue) }
func ^ (lhs: ChangingTableLocation, rhs: ChangingTableLocation) -> ChangingTableLocation { return ChangingTableLocation(rawValue: lhs.rawValue ^ rhs.rawValue) }
struct SeatingType : RawOptionSetTypeooleanType {
var rawValue: UInt = 0
var boolValue:Bool {
get {
return self.rawValue != 0
}
}
init(rawValue: UInt) { self.rawValue = rawValue }
init(nilLiteral: ()) { self.rawValue = 0 }
func toRaw() -> UInt { return self.rawValue }
static func convertFromNilLiteral() -> SeatingType { return .None}
static func fromRaw(raw: UInt) -> SeatingType? { return self(rawValue: raw) }
static func fromMask(raw: UInt) -> SeatingType { return self(rawValue: raw) }
static var allZeros: SeatingType { return self(rawValue: 0) }
static var None: SeatingType { return self(rawValue: 0) } //0
static var Booster: SeatingType { return self(rawValue: 1 << 0) } //1
static var HighChair: SeatingType { return self(rawValue: 1 << 1) } //2
func images() -> [UIImage] {
var images = [UIImage]()
if self & .Booster {
images.append(UIImage(named: "booster")!)
}
if self & .HighChair {
images.append(UIImage(named: "highchair")!)
}
return images
}
}
func == (lhs: SeatingType, rhs: SeatingType) -> Bool { return lhs.rawValue == rhs.rawValue }
func | (lhs: SeatingType, rhs: SeatingType) -> SeatingType { return SeatingType(rawValue: lhs.rawValue | rhs.rawValue) }
func & (lhs: SeatingType, rhs: SeatingType) -> SeatingType { return SeatingType(rawValue: lhs.rawValue & rhs.rawValue) }
func ^ (lhs: SeatingType, rhs: SeatingType) -> SeatingType { return SeatingType(rawValue: lhs.rawValue ^ rhs.rawValue) }
class Establishment : NSObject, MKAnnotation {
var record : CKRecord! {
didSet {
name = record.objectForKey("Name") as String!
location = record.objectForKey("Location") as CLLocation!
}
}
var name : String!
var location : CLLocation!
weak var database : CKDatabase!
var assetCount = 0
var healthyChoice : Bool {
get {
let obj: AnyObject! = record.objectForKey("HealthyOption")
if (obj != nil) {
return obj.boolValue
}
return false
}
}
var kidsMenu: Bool {
get {
let obj: AnyObject! = record.objectForKey("KidsMenu")
if (obj != nil) {
return obj.boolValue
}
return false
}
}
init(record : CKRecord, database: CKDatabase) {
super.init()
self.record = record
self.database = database
self.name = record.objectForKey("Name") as String!
self.location = record.objectForKey("Location") as CLLocation!
}
func fetchRating(completion: (rating: Double, isUser: Bool) -> ()) {
Model.sharedInstance().userInfo.userID() { userRecord, error in
self.fetchRating(userRecord, completion: completion)
}
}
func fetchRating(userRecord: CKRecordID!,
completion: (rating: Double, isUser: Bool) -> ()) {
// 1
let predicate = NSPredicate(format: "Establishment == %@", record)
// 2
let query = CKQuery(recordType: "Rating", predicate: predicate)
database.performQuery(query, inZoneWithID: nil) {
results, error in
if error != nil {
completion(rating: 0, isUser: false)
} else {
let resultsArray = results as NSArray
// 3
let rating = resultsArray.valueForKeyPath("@avg.Rating") as Double?
if (rating != nil) {
completion(rating: rating!, isUser: userRecord != nil)
} else {
completion(rating: 0, isUser: false)
}
}
}
}
func fetchNote(completion: (note: String!) -> ()) {
Model.sharedInstance().fetchNote(self) { note, error in
completion(note: note)
}
}
func fetchPhotos(completion:(assets: [CKRecord]!)->()) {
let predicate = NSPredicate(format: "Establishment == %@", record)
let query = CKQuery(recordType: "EstablishmentPhoto", predicate: predicate);
//Intermediate Extension Point - with cursors
database.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil {
self.assetCount = results.count
}
completion(assets: results as [CKRecord]!)
}
}
func changingTable() -> ChangingTableLocation {
let changingTable = record?.objectForKey("ChangingTable") as NSNumber!
var val:UInt = 0
if let changingTableNum = changingTable {
val = changingTableNum.unsignedLongValue
}
return ChangingTableLocation(rawValue: val)
}
func seatingType() -> SeatingType {
let seatingType = record?.objectForKey("SeatingType") as NSNumber!
var val:UInt = 0
if let seatingTypeNum = seatingType {
val = seatingTypeNum.unsignedLongValue
}
return SeatingType(rawValue: val)
}
func loadCoverPhoto(completion:(photo: UIImage!) -> ()) {
// 1
dispatch_async(
dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)){
var image: UIImage!
// 2
let coverPhoto = self.record.objectForKey("CoverPhoto") as CKAsset!
if let asset = coverPhoto {
// 3
if let url = asset.fileURL {
let imageData = NSData(contentsOfFile: url.path!)
// 4
image = UIImage(data: imageData!)
}
}
// 5
completion(photo: image)
}
}
//MARK: - map annotation
var coordinate : CLLocationCoordinate2D {
get {
return location.coordinate
}
}
var title : String! {
get {
return name
}
}
}
//Mark: Equatable
func == (lhs: Establishment, rhs: Establishment) -> Bool {
return lhs.record.recordID == rhs.record.recordID
}
| mit | 34c02f7fb7906738bdc3358e70d44b2d | 32.925197 | 160 | 0.65777 | 4.109204 | false | false | false | false |
salemoh/GoldenQuraniOS | GoldenQuranSwift/GoldenQuranSwift/Mus7af.swift | 1 | 2393 | //
// Mus7af.swift
// GoldenQuranSwift
//
// Created by Omar Fraiwan on 2/12/17.
// Copyright © 2017 Omar Fraiwan. All rights reserved.
//
import UIKit
enum MushafType:String{
case HAFS = "HAFS"
case WARSH = "WARSH"
}
class Mus7af: NSObject {
var id:Int?
var guid:String?
var numberOfPages:Int?
var type:MushafType?
var baseImagesDownloadUrl:String?
var name:String?
var startOffset:Int?
var dbName:String?
var currentPage:Int?
var currentSurah:Int?
var currentAyah:Int?
var createdAt:Double?
var updatedAt:Double?
var imagesNameFormat:String?
var recitationId:Int?
var logo:UIImage?{
get {
let imageName = String(format:"MUSHAF_ICON_%d", self.id!)
return UIImage(named:imageName)
}
}
var tableOfContents:[TableOfContentItem]?
// var logo:String?
//bookmarks
//readers[]
//userLocalDBLocation
func getImageForPage(pageNumber:Int) -> UIImage {
//0002-phone.png
let sub:String?
switch self.id! {
case 1:
sub = "medina1"
case 2:
sub = "warsh"
case 3:
sub = "kingFahad"
default:
sub = "kingFahad"
}
let subPath = String(format:"GoldenQuranRes/images/%@",sub!)
let imageName = String(format:self.imagesNameFormat! , pageNumber + self.startOffset! )
let imageURL = Bundle.main.url(forResource: imageName, withExtension:"png", subdirectory:subPath)
if let _ = imageURL , let image = UIImage(contentsOfFile: imageURL!.path) {
return image
}
return UIImage()
// let nsLibraryDirectory = FileManager.SearchPathDirectory.libraryDirectory
// let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
// let paths = NSSearchPathForDirectoriesInDomains(nsLibraryDirectory, nsUserDomainMask, true)
//
// if let dirPath = paths.first
// {
// let subPath = String(format:"/%@/page%03d",self.type! ,pageNumber )
// let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(subPath)
// let image = UIImage(contentsOfFile: imageURL.path)
// return image!
// }
// return UIImage()
}
}
| mit | 9c8b4a5fe3f7ef56f267b017dc13d41f | 26.181818 | 115 | 0.595318 | 4.138408 | false | false | false | false |
m3rkus/Mr.Weather | Mr.Weather/UserDefaultsController.swift | 1 | 3720 | //
// UserDefaultsController.swift
// Mr.Weather
//
// Created by Роман Анистратенко on 13/09/2017.
// Copyright © 2017 m3rk edge. All rights reserved.
//
import Foundation
struct ObtainingWeatherMode {
static let manual = "manual"
static let geolocation = "geolocation"
}
enum UserDefaultsControllerNotification: String {
case viewSettingsDidChange = "viewSettingsDidChange"
}
class UserDefaultsController {
fileprivate static let useFahrenheitTemperatureKey = "useFahrenheitTemperature"
fileprivate static let useMilesPerHourWindSpeedKey = "useMilesPerHourWindSpeed"
fileprivate static let timeOfLastGeoWeatherUpdateKey = "timeOfLastGeoWeatherUpdate"
fileprivate static let lastCityNameForManualModeKey = "lastCityNameForManualMode"
fileprivate static let obtainingWeatherModeKey = "obtainingWeatherMode"
fileprivate static let timeOfLastManualWeatherUpdateKey = "timeOfLastManualWeatherUpdate"
static var lastNotification: Notification?
static private func viewSettingsDidChangeNotification() {
let notification = Notification(name: NSNotification.Name(rawValue: UserDefaultsControllerNotification.viewSettingsDidChange.rawValue))
self.lastNotification = notification
NotificationCenter.default.post(notification)
}
static func registerDefaults() {
UserDefaults.standard.register(defaults: [
useFahrenheitTemperatureKey: false,
useMilesPerHourWindSpeedKey: false,
timeOfLastGeoWeatherUpdateKey: Date.distantPast,
timeOfLastManualWeatherUpdateKey: Date.distantPast,
obtainingWeatherModeKey: ObtainingWeatherMode.geolocation
])
}
static func sync() {
UserDefaults.standard.synchronize()
}
static var useFahrenheitTemperature: Bool {
get {
return UserDefaults.standard.bool(forKey: useFahrenheitTemperatureKey)
}
set {
UserDefaults.standard.set(newValue, forKey: useFahrenheitTemperatureKey)
self.viewSettingsDidChangeNotification()
}
}
static var useMilesPerHourWindSpeed: Bool {
get {
return UserDefaults.standard.bool(forKey: useMilesPerHourWindSpeedKey)
}
set {
UserDefaults.standard.set(newValue, forKey: useMilesPerHourWindSpeedKey)
self.viewSettingsDidChangeNotification()
}
}
static var timeOfLastGeoWeatherUpdate: Date {
get {
return UserDefaults.standard.object(forKey: timeOfLastGeoWeatherUpdateKey) as? Date ?? Date.distantPast
}
set {
UserDefaults.standard.set(newValue, forKey: timeOfLastGeoWeatherUpdateKey)
}
}
static var timeOfLastManualWeatherUpdate: Date {
get {
return UserDefaults.standard.object(forKey: timeOfLastManualWeatherUpdateKey) as? Date ?? Date.distantPast
}
set {
UserDefaults.standard.set(newValue, forKey: timeOfLastManualWeatherUpdateKey)
}
}
static var lastCityNameForManualMode: String {
get {
return UserDefaults.standard.object(forKey: lastCityNameForManualModeKey) as! String
}
set {
UserDefaults.standard.set(newValue, forKey: lastCityNameForManualModeKey)
}
}
static var obtainingWeatherMode: String {
get {
return UserDefaults.standard.object(forKey: obtainingWeatherModeKey) as? String ?? ObtainingWeatherMode.geolocation
}
set {
UserDefaults.standard.set(newValue, forKey: obtainingWeatherModeKey)
}
}
}
| mit | 2c90181c84367d92f7ed353bb2a053da | 33.598131 | 143 | 0.690978 | 5.01626 | false | false | false | false |
swernimo/iOS | UI Kit Fundamentals 1/Text Delegate Challenge/Text Delegate Challenge/ViewController.swift | 1 | 1109 | //
// ViewController.swift
// Text Delegate Challenge
//
// Created by Sean Wernimont on 10/27/15.
// Copyright © 2015 Just One Guy. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var zipCodeTextField: UITextField!
@IBOutlet weak var cashTextField: UITextField!
@IBOutlet weak var lockedTextField: UITextField!
@IBOutlet weak var lockedSwitch: UISwitch!
let zipCodeDelegate = ZipCodeDelegate();
let cashDelegate = CashFieldDelegate();
override func viewDidLoad() {
super.viewDidLoad()
self.zipCodeTextField.delegate = zipCodeDelegate;
self.cashTextField.delegate = cashDelegate;
self.lockedTextField.delegate = self;
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return (lockedSwitch.on);
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder();
return true;
}
} | mit | 20828a0168849743bb9ab5a44108f628 | 27.435897 | 132 | 0.687726 | 5.082569 | false | false | false | false |
JeremyJacquemont/SchoolProjects | IUT/iOS-Projects/Locations/Locations/ViewController.swift | 1 | 5040 | //
// ViewController.swift
// Locations
//
// Created by iem on 02/04/2015.
// Copyright (c) 2015 JeremyJacquemont. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
//MARK: - Variables
var locations = [Location]()
var locationManager = LocationManager.sharedManager
//MARK: - Override Functions
override func viewDidLoad() {
super.viewDidLoad()
setUpNavigation()
}
override func viewDidAppear(animated: Bool) {
if let locationsResult = locationManager.getAll() {
locations = locationsResult as [Location]
self.tableView.reloadData()
}
}
//MARK: - Functions
func setUpNavigation() {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "showAdd")
self.refreshControl?.addTarget(self, action: "pullToRefresh", forControlEvents: UIControlEvents.ValueChanged)
}
func showAdd() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var destination: LocationViewController = storyboard.instantiateViewControllerWithIdentifier("Location") as LocationViewController
let navigation = UINavigationController(rootViewController: destination)
self.presentViewController(navigation, animated: true, completion: nil)
}
func pullToRefresh() {
viewDidAppear(false)
self.refreshControl?.endRefreshing()
}
//MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.locations.count
}
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
//Add Edit button
let editAction = UITableViewRowAction(style: .Default, title: "Edit") { (rowAction, indexPath) -> Void in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var destination: LocationViewController = storyboard.instantiateViewControllerWithIdentifier("Location") as LocationViewController
destination.location = self.locations[indexPath.row]
let navigation = UINavigationController(rootViewController: destination)
self.presentViewController(navigation, animated: true, completion: nil)
}
editAction.backgroundColor = UIColor.purpleColor()
//Add Delete button
let deleteAction = UITableViewRowAction(style: .Default, title: "Delete") { (rowAction, indexPath) -> Void in
var alert = UIAlertController(title: "Delete Location", message: "Please, confirm delete!", preferredStyle: UIAlertControllerStyle.Alert)
var cancelBtn = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (_) -> Void in
alert.dismissViewControllerAnimated(true, completion: nil)
})
var okBtn = UIAlertAction(title: "Delete", style: UIAlertActionStyle.Default, handler: { (_) -> Void in
self.tableView(tableView, commitEditingStyle: .Delete, forRowAtIndexPath: indexPath)
})
alert.addAction(cancelBtn)
alert.addAction(okBtn)
self.presentViewController(alert, animated: true, completion: nil)
}
return [deleteAction, editAction];
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
//Handler execute on click "Delete"
if (editingStyle == UITableViewCellEditingStyle.Delete) {
let entity = self.locations[indexPath.row]
locationManager.delete(entity)
self.locations.removeAtIndex(indexPath.row)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
//MARK: - UITableViewDataSource
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
cell.textLabel?.text = self.locations[indexPath.row].name
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "placeToBe" {
let indexPath = self.tableView.indexPathForSelectedRow()
if let index = indexPath {
let value = self.locations[index.row]
(segue.destinationViewController as PlaceToBeViewController).location = value
}
}
}
}
| apache-2.0 | 581e17f130a8f8af63fbebfa5eb60fab | 41 | 157 | 0.66369 | 5.753425 | false | false | false | false |
dtop/SwiftValidate | validateTests/ValidatorStrLenTests.swift | 1 | 3380 | //
// ValidatorStrLenTests.swift
// validate
//
// Created by Danilo Topalovic on 19.12.15.
// Copyright © 2015 Danilo Topalovic. All rights reserved.
//
import XCTest
@testable import SwiftValidate
class ValidatorStrLenTests: 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 testValidatorCanHandleOdds() {
let _ = ValidatorStrLen()
let validator = ValidatorStrLen() {
$0.maxLength = 10
$0.minLength = 2
}
do {
// must throw
let _ = try validator.validate(123456, context: nil)
XCTAssert(false, "my not reach this point")
} catch _ {
XCTAssert(true)
}
}
func testValidatorValidatesStrLen() {
let validator = ValidatorStrLen() {
$0.maxLength = 10
$0.minLength = 2
}
var result: Bool = true
do {
// handle too short
result = try validator.validate("A", context: nil)
XCTAssertFalse(result)
// handle too long
result = try validator.validate("aaaaaaaaaaaaaaaaaaa", context: nil)
XCTAssertFalse(result)
// handle correct
result = try validator.validate("aaaaa", context: nil)
XCTAssertTrue(result)
// handle exact max
result = try validator.validate("iiiiiiiiii", context: nil)
XCTAssertTrue(result)
// handle exact min
result = try validator.validate("ii", context: nil)
XCTAssertTrue(result)
validator.maxInclusive = false
validator.minInclusive = false
// handle exact max
result = try validator.validate("iiiiiiiiii", context: nil)
XCTAssertFalse(result)
// handle exact min
result = try validator.validate("ii", context: nil)
XCTAssertFalse(result)
} catch _ {
XCTAssert(false)
}
}
func testValidatorThrowsOnInvalidType() {
let validator = ValidatorStrLen() {
$0.maxLength = 10
$0.minLength = 2
}
do {
let _ = try validator.validate(true, context: nil)
XCTAssert(false, "may never be reached")
} catch _ {
XCTAssert(true)
}
}
func testValidatorCanHandleNil() {
let validator = ValidatorStrLen() {
$0.maxLength = 10
$0.minLength = 2
}
do {
let value: String? = nil
let result = try validator.validate(value, context: nil)
XCTAssertTrue(result)
} catch _ {
XCTAssert(false)
}
}
}
| mit | 2c8bca190c79312e96d90cd4d95d295b | 25.193798 | 111 | 0.492157 | 5.26324 | false | true | false | false |
tensorflow/swift-models | Datasets/COCO/COCO.swift | 1 | 19619 | // Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
// Code below is ported from https://github.com/cocometadata/cocoapi
/// Coco metadata API that loads annotation file and prepares
/// data structures for data set access.
public struct COCO {
public typealias Metadata = [String: Any]
public typealias Info = [String: Any]
public typealias Annotation = [String: Any]
public typealias AnnotationId = Int
public typealias Image = [String: Any]
public typealias ImageId = Int
public typealias Category = [String: Any]
public typealias CategoryId = Int
public var imagesDirectory: URL?
public var metadata: Metadata
public var info: Info = [:]
public var annotations: [AnnotationId: Annotation] = [:]
public var categories: [CategoryId: Category] = [:]
public var images: [ImageId: Image] = [:]
public var imageToAnnotations: [ImageId: [Annotation]] = [:]
public var categoryToImages: [CategoryId: [ImageId]] = [:]
public init(fromFile fileURL: URL, imagesDirectory imgDir: URL?) throws {
let contents = try String(contentsOfFile: fileURL.path)
let data = contents.data(using: .utf8)!
let parsed = try JSONSerialization.jsonObject(with: data)
self.metadata = parsed as! Metadata
self.imagesDirectory = imgDir
self.createIndex()
}
mutating func createIndex() {
if let info = metadata["info"] {
self.info = info as! Info
}
if let annotations = metadata["annotations"] as? [Annotation] {
for ann in annotations {
let ann_id = ann["id"] as! AnnotationId
let image_id = ann["image_id"] as! ImageId
self.imageToAnnotations[image_id, default: []].append(ann)
self.annotations[ann_id] = ann
}
}
if let images = metadata["images"] as? [Image] {
for img in images {
let img_id = img["id"] as! ImageId
self.images[img_id] = img
}
}
if let categories = metadata["categories"] as? [Category] {
for cat in categories {
let cat_id = cat["id"] as! CategoryId
self.categories[cat_id] = cat
}
}
if metadata["annotations"] != nil && metadata["categories"] != nil {
let anns = metadata["annotations"] as! [Annotation]
for ann in anns {
let cat_id = ann["category_id"] as! CategoryId
let image_id = ann["image_id"] as! ImageId
self.categoryToImages[cat_id, default: []].append(image_id)
}
}
}
/// Get annotation ids that satisfy given filter conditions.
public func getAnnotationIds(
imageIds: [ImageId] = [],
categoryIds: Set<CategoryId> = [],
areaRange: [Double] = [],
isCrowd: Int? = nil
) -> [AnnotationId] {
let filterByImageId = imageIds.count != 0
let filterByCategoryId = imageIds.count != 0
let filterByAreaRange = areaRange.count != 0
let filterByIsCrowd = isCrowd != nil
var anns: [Annotation] = []
if filterByImageId {
for imageId in imageIds {
if let imageAnns = self.imageToAnnotations[imageId] {
for imageAnn in imageAnns {
anns.append(imageAnn)
}
}
}
} else {
anns = self.metadata["annotations"] as! [Annotation]
}
var annIds: [AnnotationId] = []
for ann in anns {
if filterByCategoryId {
let categoryId = ann["category_id"] as! CategoryId
if !categoryIds.contains(categoryId) {
continue
}
}
if filterByAreaRange {
let area = ann["area"] as! Double
if !(area > areaRange[0] && area < areaRange[1]) {
continue
}
}
if filterByIsCrowd {
let annIsCrowd = ann["iscrowd"] as! Int
if annIsCrowd != isCrowd! {
continue
}
}
let id = ann["id"] as! AnnotationId
annIds.append(id)
}
return annIds
}
/// Get category ids that satisfy given filter conditions.
public func getCategoryIds(
categoryNames: Set<String> = [],
supercategoryNames: Set<String> = [],
categoryIds: Set<CategoryId> = []
) -> [CategoryId] {
let filterByName = categoryNames.count != 0
let filterBySupercategory = supercategoryNames.count != 0
let filterById = categoryIds.count != 0
var categoryIds: [CategoryId] = []
let cats = self.metadata["categories"] as! [Category]
for cat in cats {
let name = cat["name"] as! String
let supercategory = cat["supercategory"] as! String
let id = cat["id"] as! CategoryId
if filterByName && !categoryNames.contains(name) {
continue
}
if filterBySupercategory && !supercategoryNames.contains(supercategory) {
continue
}
if filterById && !categoryIds.contains(id) {
continue
}
categoryIds.append(id)
}
return categoryIds
}
/// Get image ids that satisfy given filter conditions.
public func getImageIds(
imageIds: [ImageId] = [],
categoryIds: [CategoryId] = []
) -> [ImageId] {
if imageIds.count == 0 && categoryIds.count == 0 {
return Array(self.images.keys)
} else {
var ids = Set(imageIds)
for (i, catId) in categoryIds.enumerated() {
if i == 0 && ids.count == 0 {
ids = Set(self.categoryToImages[catId]!)
} else {
ids = ids.intersection(Set(self.categoryToImages[catId]!))
}
}
return Array(ids)
}
}
/// Load annotations with specified ids.
public func loadAnnotations(ids: [AnnotationId] = []) -> [Annotation] {
var anns: [Annotation] = []
for id in ids {
anns.append(self.annotations[id]!)
}
return anns
}
/// Load categories with specified ids.
public func loadCategories(ids: [CategoryId] = []) -> [Category] {
var cats: [Category] = []
for id in ids {
cats.append(self.categories[id]!)
}
return cats
}
/// Load images with specified ids.
public func loadImages(ids: [ImageId] = []) -> [Image] {
var imgs: [Image] = []
for id in ids {
imgs.append(self.images[id]!)
}
return imgs
}
/// Convert segmentation in an annotation to RLE.
public func annotationToRLE(_ ann: Annotation) -> RLE {
let imgId = ann["image_id"] as! ImageId
let img = self.images[imgId]!
let h = img["height"] as! Int
let w = img["width"] as! Int
let segm = ann["segmentation"]
if let polygon = segm as? [Any] {
let rles = Mask.fromObject(polygon, width: w, height: h)
return Mask.merge(rles)
} else if let segmDict = segm as? [String: Any] {
if segmDict["counts"] is [Any] {
return Mask.fromObject(segmDict, width: w, height: h)[0]
} else if let countsStr = segmDict["counts"] as? String {
return RLE(fromString: countsStr, width: w, height: h)
} else {
fatalError("unrecognized annotation: \(ann)")
}
} else {
fatalError("unrecognized annotation: \(ann)")
}
}
public func annotationToMask(_ ann: Annotation) -> Mask {
let rle = annotationToRLE(ann)
let mask = Mask(fromRLE: rle)
return mask
}
}
public struct Mask {
var width: Int
var height: Int
var n: Int
var mask: [Bool]
init(width w: Int, height h: Int, n: Int, mask: [Bool]) {
self.width = w
self.height = h
self.n = n
self.mask = mask
}
init(fromRLE rle: RLE) {
self.init(fromRLEs: [rle])
}
init(fromRLEs rles: [RLE]) {
let w = rles[0].width
let h = rles[0].height
let n = rles.count
var mask = [Bool](repeating: false, count: w * h * n)
var cursor: Int = 0
for i in 0..<n {
var v: Bool = false
for j in 0..<rles[i].m {
for _ in 0..<rles[i].counts[j] {
mask[cursor] = v
cursor += 1
}
v = !v
}
}
self.init(width: w, height: h, n: n, mask: mask)
}
static func merge(_ rles: [RLE], intersect: Bool = false) -> RLE {
return RLE(merging: rles, intersect: intersect)
}
static func fromBoundingBoxes(_ bboxes: [[Double]], width w: Int, height h: Int) -> [RLE] {
var rles: [RLE] = []
for bbox in bboxes {
let rle = RLE(fromBoundingBox: bbox, width: w, height: h)
rles.append(rle)
}
return rles
}
static func fromPolygons(_ polys: [[Double]], width w: Int, height h: Int) -> [RLE] {
var rles: [RLE] = []
for poly in polys {
let rle = RLE(fromPolygon: poly, width: w, height: h)
rles.append(rle)
}
return rles
}
static func fromUncompressedRLEs(_ arr: [[String: Any]], width w: Int, height h: Int) -> [RLE] {
var rles: [RLE] = []
for elem in arr {
let counts = elem["counts"] as! [Int]
let m = counts.count
var cnts = [UInt32](repeating: 0, count: m)
for i in 0..<m {
cnts[i] = UInt32(counts[i])
}
let size = elem["size"] as! [Int]
let h = size[0]
let w = size[1]
rles.append(RLE(width: w, height: h, m: cnts.count, counts: cnts))
}
return rles
}
static func fromObject(_ obj: Any, width w: Int, height h: Int) -> [RLE] {
// encode rle from a list of json deserialized objects
if let arr = obj as? [[Double]] {
assert(arr.count > 0)
if arr[0].count == 4 {
return fromBoundingBoxes(arr, width: w, height: h)
} else {
assert(arr[0].count > 4)
return fromPolygons(arr, width: w, height: h)
}
} else if let arr = obj as? [[String: Any]] {
assert(arr.count > 0)
assert(arr[0]["size"] != nil)
assert(arr[0]["counts"] != nil)
return fromUncompressedRLEs(arr, width: w, height: h)
// encode rle from a single json deserialized object
} else if let arr = obj as? [Double] {
if arr.count == 4 {
return fromBoundingBoxes([arr], width: w, height: h)
} else {
assert(arr.count > 4)
return fromPolygons([arr], width: w, height: h)
}
} else if let dict = obj as? [String: Any] {
assert(dict["size"] != nil)
assert(dict["counts"] != nil)
return fromUncompressedRLEs([dict], width: w, height: h)
} else {
fatalError("input type is not supported")
}
}
}
public struct RLE {
var width: Int = 0
var height: Int = 0
var m: Int = 0
var counts: [UInt32] = []
var mask: Mask {
return Mask(fromRLE: self)
}
init(width w: Int, height h: Int, m: Int, counts: [UInt32]) {
self.width = w
self.height = h
self.m = m
self.counts = counts
}
init(fromString str: String, width w: Int, height h: Int) {
let data = str.data(using: .utf8)!
let bytes = [UInt8](data)
self.init(fromBytes: bytes, width: w, height: h)
}
init(fromBytes bytes: [UInt8], width w: Int, height h: Int) {
var m: Int = 0
var p: Int = 0
var cnts = [UInt32](repeating: 0, count: bytes.count)
while p < bytes.count {
var x: Int = 0
var k: Int = 0
var more: Int = 1
while more != 0 {
let c = Int8(bitPattern: bytes[p]) - 48
x |= (Int(c) & 0x1f) << 5 * k
more = Int(c) & 0x20
p += 1
k += 1
if more == 0 && (c & 0x10) != 0 {
x |= -1 << 5 * k
}
}
if m > 2 {
x += Int(cnts[m - 2])
}
cnts[m] = UInt32(truncatingIfNeeded: x)
m += 1
}
self.init(width: w, height: h, m: m, counts: cnts)
}
init(fromBoundingBox bb: [Double], width w: Int, height h: Int) {
let xs = bb[0]
let ys = bb[1]
let xe = bb[2]
let ye = bb[3]
let xy: [Double] = [xs, ys, xs, ye, xe, ye, xe, ys]
self.init(fromPolygon: xy, width: w, height: h)
}
init(fromPolygon xy: [Double], width w: Int, height h: Int) {
// upsample and get discrete points densely along the entire boundary
var k: Int = xy.count / 2
var j: Int = 0
var m: Int = 0
let scale: Double = 5
var x = [Int](repeating: 0, count: k + 1)
var y = [Int](repeating: 0, count: k + 1)
for j in 0..<k { x[j] = Int(scale * xy[j * 2 + 0] + 0.5) }
x[k] = x[0]
for j in 0..<k { y[j] = Int(scale * xy[j * 2 + 1] + 0.5) }
y[k] = y[0]
for j in 0..<k { m += max(abs(x[j] - x[j + 1]), abs(y[j] - y[j + 1])) + 1 }
var u = [Int](repeating: 0, count: m)
var v = [Int](repeating: 0, count: m)
m = 0
for j in 0..<k {
var xs: Int = x[j]
var xe: Int = x[j + 1]
var ys: Int = y[j]
var ye: Int = y[j + 1]
let dx: Int = abs(xe - xs)
let dy: Int = abs(ys - ye)
var t: Int
let flip: Bool = (dx >= dy && xs > xe) || (dx < dy && ys > ye)
if flip {
t = xs
xs = xe
xe = t
t = ys
ys = ye
ye = t
}
let s: Double = dx >= dy ? Double(ye - ys) / Double(dx) : Double(xe - xs) / Double(dy)
if dx >= dy {
for d in 0...dx {
t = flip ? dx - d : d
u[m] = t + xs
let vm = Double(ys) + s * Double(t) + 0.5
v[m] = vm.isNaN ? 0 : Int(vm)
m += 1
}
} else {
for d in 0...dy {
t = flip ? dy - d : d
v[m] = t + ys
let um = Double(xs) + s * Double(t) + 0.5
u[m] = um.isNaN ? 0 : Int(um)
m += 1
}
}
}
// get points along y-boundary and downsample
k = m
m = 0
var xd: Double
var yd: Double
x = [Int](repeating: 0, count: k)
y = [Int](repeating: 0, count: k)
for j in 1..<k {
if u[j] != u[j - 1] {
xd = Double(u[j] < u[j - 1] ? u[j] : u[j] - 1)
xd = (xd + 0.5) / scale - 0.5
if floor(xd) != xd || xd < 0 || xd > Double(w - 1) { continue }
yd = Double(v[j] < v[j - 1] ? v[j] : v[j - 1])
yd = (yd + 0.5) / scale - 0.5
if yd < 0 { yd = 0 } else if yd > Double(h) { yd = Double(h) }
yd = ceil(yd)
x[m] = Int(xd)
y[m] = Int(yd)
m += 1
}
}
// compute rle encoding given y-boundary points
k = m
var a = [UInt32](repeating: 0, count: k + 1)
for j in 0..<k { a[j] = UInt32(x[j] * Int(h) + y[j]) }
a[k] = UInt32(h * w)
k += 1
a.sort()
var p: UInt32 = 0
for j in 0..<k {
let t: UInt32 = a[j]
a[j] -= p
p = t
}
var b = [UInt32](repeating: 0, count: k)
j = 0
m = 0
b[m] = a[j]
m += 1
j += 1
while j < k {
if a[j] > 0 {
b[m] = a[j]
m += 1
j += 1
} else {
j += 1
}
if j < k {
b[m - 1] += a[j]
j += 1
}
}
self.init(width: w, height: h, m: m, counts: b)
}
init(merging rles: [RLE], intersect: Bool) {
var c: UInt32
var ca: UInt32
var cb: UInt32
var cc: UInt32
var ct: UInt32
var v: Bool
var va: Bool
var vb: Bool
var vp: Bool
var a: Int
var b: Int
var w: Int = rles[0].width
var h: Int = rles[0].height
var m: Int = rles[0].m
var A: RLE
var B: RLE
let n = rles.count
if n == 0 {
self.init(width: 0, height: 0, m: 0, counts: [])
return
}
if n == 1 {
self.init(width: w, height: h, m: m, counts: rles[0].counts)
return
}
var cnts = [UInt32](repeating: 0, count: h * w + 1)
for a in 0..<m {
cnts[a] = rles[0].counts[a]
}
for i in 1..<n {
B = rles[i]
if B.height != h || B.width != w {
h = 0
w = 0
m = 0
break
}
A = RLE(width: w, height: h, m: m, counts: cnts)
ca = A.counts[0]
cb = B.counts[0]
v = false
va = false
vb = false
m = 0
a = 1
b = 1
cc = 0
ct = 1
while ct > 0 {
c = min(ca, cb)
cc += c
ct = 0
ca -= c
if ca == 0 && a < A.m {
ca = A.counts[a]
a += 1
va = !va
}
ct += ca
cb -= c
if cb == 0 && b < B.m {
cb = B.counts[b]
b += 1
vb = !vb
}
ct += cb
vp = v
if intersect {
v = va && vb
} else {
v = va || vb
}
if v != vp || ct == 0 {
cnts[m] = cc
m += 1
cc = 0
}
}
}
self.init(width: w, height: h, m: m, counts: cnts)
}
}
| apache-2.0 | 02e75d2289ccfa2fdb8acbe377d8434f | 31.807692 | 100 | 0.458688 | 3.866575 | false | false | false | false |
acort3255/Emby.ApiClient.Swift | Emby.ApiClient/model/connect/ConnectUser.swift | 1 | 1132 | //
// ConnectUser.swift
// Emby.ApiClient
//
// Created by Vedran Ozir on 08/10/15.
// Copyright © 2015 Vedran Ozir. All rights reserved.
//
import Foundation
public struct ConnectUser: Codable
{
public let id: String
public let name: String
public let email: String
public let active: Bool
public let imageUrl: String?
public init?(jSON: JSON_Object) {
//{"Id":"79718","Name":"vedrano","DisplayName":"vedrano","Email":"[email protected]","IsActive":"true","ImageUrl":"http:\/\/www.gravatar.com\/avatar\/1231d710dfba30dd91868a20f737e0db?s=200&d=http%3A%2F%2Fmb3admin.com%2Fimages%2Fuser.png"}
if let id = jSON["Id"] as? String,
let name = jSON["Name"] as? String,
let email = jSON["Email"] as? String,
let activeString = jSON["IsActive"] as? NSString
{
self.id = id
self.name = name
self.email = email
self.active = activeString.boolValue
self.imageUrl = jSON["ImageUrl"] as? String
}
else {
return nil
}
}
}
| mit | edaaa74e9768ce199d382ee5a3da22d4 | 28.763158 | 250 | 0.581786 | 3.732673 | false | false | false | false |
ustwo/videoplayback-ios | DemoVideoPlaybackKit/DemoVideoPlaybackKit/DemoViewController.swift | 1 | 2815 | //
// ViewController.swift
// DemoVideoPlaybackKit
//
// Created by Sonam on 4/25/17.
// Copyright © 2017 ustwo. All rights reserved.
//
import UIKit
import RxSwift
import VideoPlaybackKit
private enum DemoOption: String {
case SingleVideoView, SingleViewViewAutoplay, CustomToolBar, FeedView, FeedAutoplayView
}
class DemoViewController: UIViewController {
private let tableView = UITableView(frame: .zero)
private let disposeBag = DisposeBag()
private let demoList = Variable([DemoOption.SingleVideoView, DemoOption.SingleViewViewAutoplay, DemoOption.CustomToolBar, DemoOption.FeedView, DemoOption.FeedAutoplayView])
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
private func setup() {
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalTo(view)
}
tableView.register(BasicTableViewCell.self, forCellReuseIdentifier: BasicTableViewCell.identifier)
tableView.estimatedRowHeight = 300
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = .none
setupDemoList()
}
private func setupDemoList() {
demoList.asObservable().bind(to: tableView.rx.items(cellIdentifier: BasicTableViewCell.identifier)) { index, model, cell in
guard let cell = cell as? BasicTableViewCell else { return }
cell.titleText = model.rawValue
}.addDisposableTo(disposeBag)
tableView.rx.modelSelected(DemoOption.self).subscribe(onNext: { demoOption in
switch demoOption {
case .SingleVideoView:
self.navigationController?.pushViewController(SingleVideoPlaybackViewController(), animated: true)
case .SingleViewViewAutoplay:
self.navigationController?.pushViewController(SingleVideoPlaybackViewController(shouldAutoPlay: true), animated: true)
case .FeedView:
self.navigationController?.pushViewController(FeedViewController(), animated: true)
case .FeedAutoplayView:
let feedVC = FeedViewController(true)
self.navigationController?.pushViewController(feedVC, animated: true)
case .CustomToolBar:
let toolBarTheme = ToolBarTheme.custom(bottomBackgroundColor: UIColor.purple, sliderBackgroundColor: UIColor.white, sliderIndicatorColor: UIColor.lightGray, sliderCalloutColors: [.red, .orange, .green])
let singleVC = SingleVideoPlaybackViewController(shouldAutoPlay: false, customTheme: toolBarTheme)
self.navigationController?.pushViewController(singleVC, animated: true)
}
}).addDisposableTo(disposeBag)
}
}
| mit | d5741569874a64933615c60ab179ac7d | 38.083333 | 218 | 0.689055 | 5.289474 | false | false | false | false |
ronaldho/visionproject | EMIT/StaticDates.swift | 1 | 897 | //
// StaticDates.swift
// EMIT
//
// Created by Andrew on 24/11/15.
// Copyright © 2015 Andrew. All rights reserved.
//
import Foundation
class StaticDates: NSObject {
static let sharedInstance = StaticDates();
var defaultDate: NSDate;
override init(){
let components:NSDateComponents = NSDateComponents();
components.year = 1970;
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
defaultDate = (calendar?.dateFromComponents(components))!;
}
static let oneYearFromToday: NSDate = NSCalendar.currentCalendar().dateByAddingUnit(
.Year, value: 1, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))!
static let yesterday: NSDate = NSCalendar.currentCalendar().dateByAddingUnit(
.Day, value: -1, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))!
} | mit | c4642e0f8ab00e19202c6d1ba6d7d293 | 28.9 | 88 | 0.670759 | 4.977778 | false | false | false | false |
wolf81/Nimbl3Survey | Nimbl3Survey/UIViewExtensions.swift | 1 | 1000 | //
// UIViewExtensions.swift
// Nimbl3Survey
//
// Created by Wolfgang Schreurs on 26/03/2017.
// Copyright © 2017 Wolftrail. All rights reserved.
//
import UIKit
extension UIView {
private static let zRotateAnimationKey = "transform.rotation.z"
func startRotation(_ duration: CFTimeInterval = 1, repeatCount: Float = Float.infinity, clockwise: Bool = true) {
if self.layer.animation(forKey: UIView.zRotateAnimationKey) != nil {
return
}
let animation = CABasicAnimation(keyPath: UIView.zRotateAnimationKey)
let direction = clockwise ? 1.0 : -1.0
animation.toValue = NSNumber(value: M_PI * 2 * direction)
animation.duration = duration
animation.isCumulative = true
animation.repeatCount = repeatCount
self.layer.add(animation, forKey:UIView.zRotateAnimationKey)
}
func stopRotation() {
self.layer.removeAnimation(forKey: UIView.zRotateAnimationKey)
}
}
| bsd-2-clause | 03d666a0f6b63f285767178ca4c1084d | 30.21875 | 117 | 0.663664 | 4.306034 | false | false | false | false |
CalvinChina/Demo | Swift3Demo/Swift3Demo/CoreImage/CoreImageViewController.swift | 1 | 4279 | //
// CoreImageViewController.swift
// Swift3Demo
//
// Created by pisen on 16/10/11.
// Copyright © 2016年 丁文凯. All rights reserved.
//
import UIKit
import CoreImage
class CoreImageViewController: UIViewController {
var sliderValue: Float = 0.0
@IBOutlet weak var myImage: UIImageView!
@IBAction func SepiaBtn(_ sender: AnyObject) {
applyfilter(1)
}
@IBAction func Vignette(_ sender: AnyObject) {
applyfilter(2)
}
@IBAction func invert(_ sender: UIButton) {
applyfilter(3)
}
@IBAction func photo(_ sender: UIButton) {
applyfilter(4)
}
@IBAction func perspective(_ sender: UIButton) {
applyfilter(5)
}
@IBAction func gaussian(_ sender: UIButton) {
applyfilter(6)
}
@IBAction func slider(_ sender: UISlider) {
sliderValue = sender.value
}
func applyfilter(_ numberFilter: Int) {
let filePath : String = Bundle.main.path(forResource: "imageCore", ofType: "jpg")!
let fileUrl : URL = URL (fileURLWithPath: filePath as String)
let inputImage : CIImage = CIImage (contentsOf: fileUrl)!
switch numberFilter {
case 1:
let filter = CIFilter(name: "CISepiaTone")
//var filter : CIFilter = CIFilter (name: "CISepiaTone")
filter!.setValue(inputImage, forKey: kCIInputImageKey)
filter!.setValue(sliderValue, forKey: "InputIntensity")
let outputImage : CIImage = filter!.value(forKey: kCIOutputImageKey) as! CIImage
let img : UIImage = UIImage (ciImage: outputImage)
myImage.image = img
case 2:
let filter : CIFilter = CIFilter (name: "CIVignette")!
filter.setValue(inputImage, forKey: kCIInputImageKey)
filter.setValue(sliderValue, forKey: "InputRadius")
filter.setValue(sliderValue, forKey: "InputIntensity")
let outputImage : CIImage = filter.value(forKey: kCIOutputImageKey) as! CIImage
let img : UIImage = UIImage (ciImage: outputImage)
myImage.image = img
case 3:
let filter : CIFilter = CIFilter (name: "CIColorInvert")!
filter.setValue(inputImage, forKey: kCIInputImageKey)
let outputImage : CIImage = filter.value(forKey: kCIOutputImageKey) as! CIImage
let img : UIImage = UIImage (ciImage: outputImage)
myImage.image = img
case 4:
let filter : CIFilter = CIFilter (name: "CIPhotoEffectMono")!
filter.setValue(inputImage, forKey: kCIInputImageKey)
let outputImage : CIImage = filter.value(forKey: kCIOutputImageKey) as! CIImage
let img : UIImage = UIImage (ciImage: outputImage)
myImage.image = img
case 5:
let filter : CIFilter = CIFilter (name: "CIPerspectiveTransform")!
filter.setValue(inputImage, forKey: kCIInputImageKey)
let outputImage : CIImage = filter.value(forKey: kCIOutputImageKey) as! CIImage
let img : UIImage = UIImage (ciImage: outputImage)
myImage.image = img
case 6:
let filter : CIFilter = CIFilter (name: "CIGaussianBlur")!
filter.setValue(inputImage, forKey: kCIInputImageKey)
let outputImage : CIImage = filter.value(forKey: kCIOutputImageKey) as! CIImage
let img : UIImage = UIImage (ciImage: outputImage)
myImage.image = img
default:
print("test")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | dbf79e11ae45674420ba1fe5a219929e | 32.888889 | 106 | 0.615222 | 4.908046 | false | false | false | false |
jacobwhite/firefox-ios | XCUITests/DatabaseFixtureTest.swift | 2 | 2108 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import XCTest
class DatabaseFixtureTest: BaseTestCase {
let fixtures = ["testOneBookmark": "testDatabaseFixture-browser.db", "testBookmarksDatabaseFixture": "testBookmarksDatabase1000-browser.db", "testHistoryDatabaseFixture": "testHistoryDatabase4000-browser.db"]
override func setUp() {
// Test name looks like: "[Class testFunc]", parse out the function name
let parts = name.replacingOccurrences(of: "]", with: "").split(separator: " ")
let key = String(parts[1])
// for the current test name, add the db fixture used
launchArguments = [LaunchArguments.SkipIntro, LaunchArguments.SkipWhatsNew, LaunchArguments.LoadDatabasePrefix + fixtures[key]!]
super.setUp()
}
func testOneBookmark() {
navigator.browserPerformAction(.openBookMarksOption)
let list = app.tables["Bookmarks List"].cells.count
XCTAssertEqual(list, 1, "There should be an entry in the bookmarks list")
}
func testBookmarksDatabaseFixture() {
navigator.goto(HomePanel_Bookmarks)
let loaded = NSPredicate(format: "count == 1013")
expectation(for: loaded, evaluatedWith: app.tables["Bookmarks List"].cells, handler: nil)
waitForExpectations(timeout: 10, handler: nil)
let bookmarksList = app.tables["Bookmarks List"].cells.count
XCTAssertEqual(bookmarksList, 1013, "There should be an entry in the bookmarks list")
}
func testHistoryDatabaseFixture() {
navigator.goto(HomePanel_History)
// History list has two cells that are for recently closed and synced devices that should not count as history items,
// the actual max number is 100
let loaded = NSPredicate(format: "count == 102")
expectation(for: loaded, evaluatedWith: app.tables["History List"].cells, handler: nil)
waitForExpectations(timeout: 5, handler: nil)
}
}
| mpl-2.0 | e73b6c9d605d1c20bdd681fd483866c1 | 45.844444 | 212 | 0.696395 | 4.523605 | false | true | false | false |
machelix/DKImagePickerController | DKImagePickerController/DKImageResource.swift | 1 | 1682 | //
// DKImageResource.swift
// DKImagePickerController
//
// Created by ZhangAo on 15/8/11.
// Copyright (c) 2015年 ZhangAo. All rights reserved.
//
import UIKit
private extension NSBundle {
class func imagePickerControllerBundle() -> NSBundle {
let assetPath = NSBundle(forClass: DKImageResource.self).resourcePath!
return NSBundle(path: assetPath.stringByAppendingPathComponent("DKImagePickerController.bundle"))!
}
}
internal class DKImageResource {
private class func imageForResource(name: String) -> UIImage {
let bundle = NSBundle.imagePickerControllerBundle()
let imagePath = bundle.pathForResource(name, ofType: "png", inDirectory: "Images")
let image = UIImage(contentsOfFile: imagePath!)
return image!
}
class func checkedImage() -> UIImage {
var image = imageForResource("checked_background")
let center = image.size.width / 2
image = image.resizableImageWithCapInsets(UIEdgeInsets(top: center, left: center, bottom: center, right: center))
return image
}
class func blueTickImage() -> UIImage {
return imageForResource("tick_blue")
}
class func cameraImage() -> UIImage {
return imageForResource("camera")
}
class func videoCameraIcon() -> UIImage {
return imageForResource("video_camera")
}
}
internal class DKImageLocalizedString {
class func localizedStringForKey(key: String) -> String {
return NSLocalizedString(key, tableName: "DKImagePickerController", bundle:NSBundle.imagePickerControllerBundle(), value: "", comment: "")
}
}
| mit | a7160a49601f1786fc7c755fcd2aa941 | 27.474576 | 146 | 0.670238 | 5.045045 | false | false | false | false |
CodetrixStudio/CSJson | CSJson/CSJson.swift | 1 | 6522 | //
// CSJson.swift
// CSJson
//
// Created by Parveen Khatkar on 11/3/15.
// Copyright © 2015 Codetrix Studio. All rights reserved.
//
import Foundation
protocol CSJsonDataSource
{
func settings() -> CSJsonSettings
}
open class CSJson
{
/// Deserializes JSON string to Object.
/// - parameter json: A valid JSON Object string.
/// - parameter settings: CSJsonSettings to use for this object.
/// - returns: A deserialized object.
open static func Deserialize<T>(_ json: String) -> T? where T: NSObject
{
if let jsonDictionary = json.toDictionary()
{
let obj: T = T();
obj.deserialize(jsonDictionary as AnyObject, settings: nil);
return obj;
}
else
{
return nil;
}
}
/// Deserializes JSON Dictionary data to Object.
/// - parameter json: Dictionary having JSON data.
/// - parameter settings: CSJsonSettings to use for this object.
/// - returns: A deserialized object.
open static func Deserialize<T>(_ json: [String:AnyObject]) -> T? where T: NSObject
{
let obj: T = T();
obj.deserialize(json as AnyObject, settings: nil);
return obj;
}
/// Deserializes JSON string to Object Array.
/// - parameter json: A valid JSON Array string.
/// - parameter settings: CSJsonSettings to use for the array objects.
/// - returns: A deserialized object array.
open static func Deserialize<T>(_ json: String, settings: CSJsonSettings?) -> [T]? where T: NSObject
{
// return nil;
// do
// {
// let obj: [T] = try [T](json: json, settings: settings);
// return obj;
// }
// catch
// {
// return nil;
// }
if let jsonDictionaryArray = json.toArray()
{
var array: [T] = [T]();
for item in jsonDictionaryArray
{
if let obj: T = CSJson.Deserialize(item as! [String:AnyObject])
{
array.append(obj);
}
}
return array;
}
else
{
return nil;
}
}
/// Deserializes JSON string to Object Array.
/// - parameter json: A valid JSON Array string.
/// - parameter settings: CSJsonSettings to use for the array objects.
/// - returns: A deserialized object array.
// public static func Deserialize<T where T: CSSerializable >(json: String, settings: CSJsonSettings?) -> [T]?
// {
// if let jsonDictionaryArray = json.toArray()
// {
// var array: [T] = [T]();
//
// for item in jsonDictionaryArray
// {
// let obj = T();
// obj.deserialize(val: String(item));
// array.append(obj);
// }
//
// return array;
// }
// else
// {
// return nil;
// }
// }
/// Deserialize JSON Dictionary data to Object Array
/// - parameter json: Dictionary Array having JSON data.
/// - parameter settings: CSJsonSettings to use for the array objects.
/// - returns: A deserialized object array.
open static func Deserialize<T>(_ json: [[String:AnyObject]], settings: CSJsonSettings?) -> [T]? where T: NSObject
{
let obj: [T] = [T]();
// obj.deserialize(json, settings: settings);
return obj;
}
// MARK: - Serialization
/// Serializes this object into JSON.
/// - parameter prettyPrinted: Whether to format JSON for easy read.
/// - returns: A JSON string.
// public func serialize(prettyPrinted: Bool = false) -> String
// {
// return CSJson.Serialize(self, prettyPrinted: prettyPrinted, settings: jsonSettings);
// }
/// Serializes this object into JSON.
/// - parameter object: CSObject/NSObject to serialize.
/// - parameter prettyPrinted: Whether to format JSON for easy read.
/// - parameter settings: CSJsonSettings to use for this object.
/// - returns: A JSON string.
open static func Serialize(_ object: NSObject, prettyPrinted: Bool = false) -> String
{
var jsonString: String = "";
let json = object.serialize() as! [String: AnyObject];
var jsonData = Data();
do
{
if prettyPrinted
{
jsonData = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted);
}
else
{
jsonData = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions(rawValue: 0));
}
}
catch
{
print("oops");
}
jsonString = String(data: jsonData, encoding: String.Encoding.utf8)!;
return jsonString;
}
/// Serializes this object into JSON.
/// - parameter object: NSObject to serialize.
/// - parameter prettyPrinted: Whether to format JSON for easy read.
/// - parameter settings: CSJsonSettings to use for this object.
/// - returns: A JSON string.
// public static func Serialize(object: CSJson, prettyPrinted: Bool = false, settings: CSJsonSettings?) -> String
// {
// return CSJson.Serialize(object, prettyPrinted: prettyPrinted, settings: settings);
// }
// MARK: - functions & helpers
static internal func dateFormat(_ key: String, settings: CSJsonSettings?) -> String
{
var settings: CSJsonSettings! = settings;
if settings == nil
{
settings = CSJsonSettings.GlobalSettings;
}
var format = settings.DateFormats[key];
if format == nil
{
format = settings.DateFormat;
}
return format!;
}
/// Registers Model Type for desrialization.
/// - returns: nil.
open static func registerModel<T>() -> T? where T: NSObject
{
CSJsonHelper.addModel(T.self);
return nil;
}
/// Registers Model Type of Array Element for desrialization.
/// - returns: nil.
open static func registerModelArray<T>() -> [T]? where T: NSObject
{
CSJsonHelper.addModelArray(T)
return nil;
}
}
| gpl-3.0 | d4822dec469a596a78e4f49aff14c447 | 30.65534 | 133 | 0.550529 | 4.621545 | false | false | false | false |
algolia/algoliasearch-client-swift | Tests/AlgoliaSearchClientTests/Doc/APIParameters/APIParameters+GeoSearch.swift | 1 | 6846 | //
// APIParameters+GeoSearch.swift
//
//
// Created by Vladislav Fitc on 07/07/2020.
//
import Foundation
import AlgoliaSearchClient
extension APIParameters {
//MARK: - GeoSearch
func geoSearch() {
func aroundLatLng() {
/*
aroundLatLng = Point(latitude, longitude)
*/
func search_around_a_position() {
let query = Query("query")
.set(\.aroundLatLng, to: Point(latitude: 40.71, longitude: -74.01))
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
func aroundLatLngViaIP() {
/*
aroundLatLngViaIP = true|false
*/
func search_around_server_ip() {
/// '94.228.178.246' should be replaced with the actual IP you would like
/// to search around. Depending on your stack there are multiple ways to get this
/// information.
let configuration = SearchConfiguration(
applicationID: "YourApplicationID",
apiKey: "YourSearchOnlyAPIKey"
)
.set(\.defaultHeaders, to: ["X-Forwarded-For": "94.228.178.246"])
let client = SearchClient(configuration: configuration)
let index = client.index(withName: "index_name")
let query = Query("query")
.set(\.aroundLatLngViaIP, to: true)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
func aroundRadius() {
/*
aroundRadius = .meters(#{radius_in_meters})|.#{all}
*/
func set_around_radius() {
let query = Query("query")
.set(\.aroundRadius, to: .meters(1000))
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func disable_automatic_radius() {
let query = Query("query")
.set(\.aroundRadius, to: .all)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
func aroundPrecision() {
/*
aroundPrecision = number_of_meters
*/
func set_geo_search_precision() {
let query = Query("query")
.set(\.aroundPrecision, to: [100]) // 100 meters precision
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func set_geo_search_precision_non_linear() {
let query = Query("query")
.set(\.aroundPrecision, to: [
.init(from: 0, value: 25), // 25 meters precision by default
.init(from: 2000, value: 1000) // 1,000 meters precision after 2 km
])
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
func minimumAroundRadius() {
/*
minimumAroundRadius = radius
*/
func set_minimum_geo_search_radius() {
let query = Query("query")
.set(\.minimumAroundRadius, to: 1000) // 1km
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
func insideBoundingBox() {
/*
insideBoundingBox = [
BoundingBox(
point1: Point(latitude: point1_lat, longitude: point1_lng),
point2: Point(latitude: point2_lat, longitude: point2_lng)
),
BoundingBox( // you can search in multiple rectangles
...
)
]
*/
func search_inside_rectangular_area() {
let query = Query("query")
.set(\.insideBoundingBox, to: [
BoundingBox(point1: (46.650828100116044, 7.123046875),
point2: (45.17210966999772, 1.009765625))
])
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func search_inside_multiple_rectangular_areas() {
let boundingBox1 = BoundingBox(
point1: (46.650828100116044, 7.123046875),
point2: (45.17210966999772, 1.009765625)
)
let boundingBox2 = BoundingBox(
point1: (49.62625916704081, 4.6181640625),
point2: (47.715070300900194, 0.482421875)
)
let query = Query("query")
.set(\.insideBoundingBox, to: [boundingBox1, boundingBox2])
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
func insidePolygon() {
/*
insidePolygon = [
[Polygon](#parameter-option-a-polygon)(
point1: Point,
point2: Point,
point3: Point,
...
),
Polygon(// you can search in #{multiple polygons})
]
*/
func search_inside_polygon_area() {
let polygon = Polygon(
(46.650828100116044, 7.123046875),
(45.17210966999772, 1.009765625),
(49.62625916704081, 4.6181640625),
(47.715070300900194, 0.482421875)
)
let query = Query("query")
.set(\.insidePolygon, to: [polygon])
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func search_inside_multiple_polygon_areas() {
let polygon1 = Polygon(
(46.650828100116044, 7.123046875),
(45.17210966999772, 1.009765625),
(49.62625916704081, 4.6181640625),
(47.715070300900194, 0.482421875)
)
let polygon2 = Polygon(
(47.650828100116044, 6.123046875),
(46.17210966999772, 1.009765625),
(48.62625916704081, 3.6181640625),
(45.715070300900194, 0.482421875)
)
let query = Query("query")
.set(\.insidePolygon, to: [
polygon1,
polygon2
])
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
}
}
| mit | 5a1c6560e5d77f0c148b99929260e4dd | 26.384 | 89 | 0.51227 | 4.161702 | false | false | false | false |
git-hushuai/MOMO | MMHSMeterialProject/LibaryFile/ThPullRefresh/Head/ThHeadRefreshView.swift | 1 | 3897 | //
// ThHeadRefresh.swift
// PullRefresh
//
// Created by tanhui on 15/12/28.
// Copyright © 2015年 tanhui. All rights reserved.
//
import Foundation
import UIKit
enum ThHeadRefreshState:Int{
case None=0
case Idle=1
case Pulling=2
case Refreshing=3
case WillRefresh=4
}
class ThHeadRefreshView: ThRefreshBasicView {
//public
override init(frame: CGRect) {
super.init(frame: frame)
}
func beginRefresh(){
if(self.window != nil){
self.state = .Refreshing
}else{
self.state = .WillRefresh
self.setNeedsDisplay()
}
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
if(self.state == .WillRefresh){
self.state = .Refreshing
}
}
//private method
func setStates (newState:ThHeadRefreshState , oldState:ThHeadRefreshState){
if newState==oldState{
return
}
switch(newState){
case .Idle:
if(oldState == .Refreshing){
UIView.animateWithDuration(ThHeadRefreshAnimation, animations: {
self.scrollView?.th_insetT -= self.height
}, completion: nil)
}
break
case .Pulling:
break
case .Refreshing:
if(oldState == .Pulling || oldState == .WillRefresh){
UIView.animateWithDuration(ThHeadRefreshAnimation, animations: {
self.scrollView?.th_insetT=(self.scrollView?.th_insetT)!+self.oringalheight!
}, completion: nil)
if((self.refreshClosure) != nil){
self.refreshClosure!()
}else{
self.refreshTarget?.performSelector(self.refreshAction!)
}
}
break
default:
break
}
}
func adjustStateWithContentOffset(){
print("scrollView contentoffset:\(self.scrollView?.contentOffset.y)")
let offset = self.scrollView?.th_offsetY
let headExistOffset = 0-(self.scrollView?.contentInset.top)!
let refreshPoint = headExistOffset - self.height
if(self.scrollView?.dragging == true){
if(self.state == .Idle && offset<refreshPoint){
self.state = .Pulling
}else if (self.state == .Pulling && offset>=refreshPoint){
self.state = .Idle
}
}else if (self.state == .Pulling){
self.state = .Refreshing
}
}
func stopRefreshing(){
UIView.animateWithDuration(ThHeadRefreshCompleteDuration) { () -> Void in
self.state = .Idle
}
}
//override
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if (keyPath==ThHeadRefreshContentOffset){
self.adjustStateWithContentOffset()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
if(newSuperview != nil){
self.Theight = ThHeadRefreshHeight
self.oringalheight = self.Theight
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.y = -self.Theight
}
var state : ThHeadRefreshState = .Idle
{
didSet {
self.setStates(state, oldState: oldValue)
}
}
var oringalheight : CGFloat?
var hideTimeLabel : Bool = false
var hideRefreshTextLabel : Bool = false
} | mit | b3942c4e0559b5c0edff931ad4fd6136 | 26.429577 | 157 | 0.549563 | 4.922882 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Synthesis.playground/Pages/Vocal Tract.xcplaygroundpage/Contents.swift | 1 | 2541 | //: ## Vocal Tract
//:
import AudioKitPlaygrounds
import AudioKit
import AudioKitUI
let voc = AKVocalTract()
AudioKit.output = voc
AudioKit.start()
class LiveView: AKLiveViewController {
var current = 0
var frequencySlider: AKSlider!
var tonguePositionSlider: AKSlider!
var tongueDiameterSlider: AKSlider!
var tensenessSlider: AKSlider!
var nasalitySlider: AKSlider!
override func viewDidLoad() {
addTitle("Vocal Tract")
addView(AKButton(title: "Start") { button in
if voc.isStarted {
voc.stop()
button.title = "Start"
} else {
voc.start()
button.title = "Stop"
}
})
frequencySlider = AKSlider(property: "Frequency",
value: voc.frequency,
range: 0 ... 2_000
) { sliderValue in
voc.frequency = sliderValue
}
addView(frequencySlider)
tonguePositionSlider = AKSlider(property: "Tongue Position", value: voc.tonguePosition) { sliderValue in
voc.tonguePosition = sliderValue
}
addView(tonguePositionSlider)
tongueDiameterSlider = AKSlider(property: "Tongue Diameter", value: voc.tongueDiameter) { sliderValue in
voc.tongueDiameter = sliderValue
}
addView(tongueDiameterSlider)
tensenessSlider = AKSlider(property: "Tenseness", value: voc.tenseness) { sliderValue in
voc.tenseness = sliderValue
}
addView(tensenessSlider)
nasalitySlider = AKSlider(property: "Nasality", value: voc.nasality) { sliderValue in
voc.nasality = sliderValue
}
addView(nasalitySlider)
addView(AKButton(title: "Randomize") { _ in
voc.frequency = self.frequencySlider.randomize()
voc.tonguePosition = self.tonguePositionSlider.randomize()
voc.tongueDiameter = self.tongueDiameterSlider.randomize()
voc.tenseness = self.tensenessSlider.randomize()
voc.nasality = self.nasalitySlider.randomize()
})
addView(AKSlider(property: "Ramp Time",
value: voc.rampTime,
range: 0 ... 10,
format: "%0.3f s"
) { time in
voc.rampTime = time
})
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
| mit | dd5a0463061aaffe928505171ca8a62e | 29.614458 | 112 | 0.593467 | 4.586643 | false | false | false | false |
openHPI/xikolo-ios | Binge/BingeControlsViewController.swift | 1 | 22420 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
// swiftlint:disable file_length type_body_length
import AVFoundation
import AVKit
import UIKit
class BingeControlsViewController: UIViewController {
private lazy var bufferProgressView: UIProgressView = {
let progress = UIProgressView()
progress.progressTintColor = UIColor(white: 0.9, alpha: 1.0)
progress.trackTintColor = UIColor(white: 0.6, alpha: 1.0)
progress.progress = 0
progress.translatesAutoresizingMaskIntoConstraints = false
return progress
}()
private lazy var timeSlider: BingeTimeSlider = {
let slider = BingeTimeSlider()
slider.isContinuous = true
slider.minimumTrackTintColor = .red
slider.maximumTrackTintColor = .clear
slider.tintColor = .red
slider.minimumValue = 0.0
slider.maximumValue = 1.0
slider.value = 0.0
slider.isEnabled = false
slider.translatesAutoresizingMaskIntoConstraints = false
let normalAlignmentRectInsets = UIEdgeInsets(top: 17, left: 17, bottom: 17, right: 17)
let normalThumbImage = UIImage.bingeImage(named: "thumb-small")?.withAlignmentRectInsets(normalAlignmentRectInsets)
slider.setThumbImage(normalThumbImage, for: .normal)
let highlightedAlignmentRectInsets = UIEdgeInsets(top: 12.5, left: 12.5, bottom: 12.5, right: 12.5)
let highlightedThumbImage = UIImage.bingeImage(named: "thumb-big")?.withAlignmentRectInsets(highlightedAlignmentRectInsets)
slider.setThumbImage(highlightedThumbImage, for: .highlighted)
slider.addTarget(self, action: #selector(changeProgress(sender:event:)), for: .valueChanged)
if #available(iOS 13.4, *) {
let interaction = UIPointerInteraction(delegate: nil)
slider.addInteraction(interaction)
}
return slider
}()
private lazy var currentTimeView: UILabel = {
let label = UILabel()
label.textColor = .white
label.text = "0:00"
label.font = UIFont.monospacedDigitSystemFont(ofSize: 13, weight: .semibold)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private lazy var totalTimeView: UILabel = {
let label = UILabel()
label.textColor = .white
label.text = "0:00"
label.font = UIFont.monospacedDigitSystemFont(ofSize: 13, weight: .semibold)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private lazy var fullScreenButton: UIButton = {
let button = UIButton()
button.tintColor = .white
button.setImage(UIImage.bingeImage(named: "ios-expand"), for: .normal)
button.setImage(UIImage.bingeImage(named: "ios-contract"), for: .selected)
button.addTarget(self, action: #selector(toggleFullScreenMode), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 13.4, *) {
let interaction = UIPointerInteraction(delegate: nil)
button.addInteraction(interaction)
}
return button
}()
private lazy var emptyView: UIView = { // To have at least one view in the top left stackview
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var closeButton: UIButton = {
let button = UIButton()
button.tintColor = .white
button.setImage(UIImage.bingeImage(named: "ios-close"), for: .normal)
button.addTarget(self, action: #selector(dismissPlayer), for: .touchUpInside)
button.isHidden = true
button.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 13.4, *) {
let interaction = UIPointerInteraction(delegate: nil)
button.addInteraction(interaction)
}
return button
}()
private lazy var offlineLabel: UILabel = {
let label = BingePaddedLabel()
label.text = BingeLocalizedString("offline-label.text",
comment: "Text indicating a video playback with a local source")
label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
label.textAlignment = .center
label.textColor = .white
label.isHidden = true
label.layer.borderColor = UIColor.white.cgColor
label.layer.borderWidth = 1.0
label.layer.cornerRadius = 3
label.layer.masksToBounds = true
label.translatesAutoresizingMaskIntoConstraints = false
label.setContentCompressionResistancePriority(.required, for: .horizontal)
return label
}()
private lazy var titleView: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
label.textColor = .white
label.isHidden = true
label.translatesAutoresizingMaskIntoConstraints = false
label.setContentHuggingPriority(UILayoutPriority.defaultLow - 1, for: .horizontal)
return label
}()
private lazy var pictureInPictureButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
let startPipImage = AVPictureInPictureController.pictureInPictureButtonStartImage(compatibleWith: nil).withRenderingMode(.alwaysTemplate)
button.setImage(startPipImage, for: .normal)
button.tintColor = .white
button.addTarget(self, action: #selector(togglePictureInPictureMode), for: .touchUpInside)
button.isHidden = !AVPictureInPictureController.isPictureInPictureSupported()
button.isEnabled = false
if #available(iOS 13.4, *) {
let interaction = UIPointerInteraction(delegate: nil)
button.addInteraction(interaction)
}
return button
}()
private lazy var airPlayButton: AVRoutePickerView = {
let view = AVRoutePickerView()
view.tintColor = .white
view.activeTintColor = .red
view.translatesAutoresizingMaskIntoConstraints = false
view.delegate = self.delegate
view.isHidden = true
if #available(iOS 13.0, *) {
view.prioritizesVideoDevices = true
}
return view
}()
private lazy var settingsButton: UIButton = {
let button = UIButton()
button.tintColor = .white
button.setImage(UIImage.bingeImage(named: "ios-options"), for: .normal)
button.addTarget(self, action: #selector(showMediaSelection), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 13.4, *) {
let interaction = UIPointerInteraction(delegate: nil)
button.addInteraction(interaction)
}
return button
}()
private lazy var topBarLeftStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .fill
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
private lazy var topBarRightStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .fill
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
private lazy var bottomBarRightStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .fill
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
private lazy var playPauseButton: UIButton = {
let button = UIButton()
button.tintColor = .white
button.setImage(UIImage.bingeImage(named: "ios-play"), for: .normal)
button.setImage(UIImage.bingeImage(named: "ios-pause"), for: .selected)
button.addTarget(self, action: #selector(playPauseVideo), for: .touchUpInside)
button.isEnabled = false
button.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 13.4, *) {
let interaction = UIPointerInteraction(delegate: nil)
button.addInteraction(interaction)
}
return button
}()
private lazy var seekForwardButton: UIButton = {
let button = UIButton()
button.tintColor = .white
if #available(iOS 13, *) {
let config = UIImage.SymbolConfiguration(pointSize: 22, weight: .regular, scale: .large)
button.setImage(UIImage(systemName: "goforward.10", withConfiguration: config), for: .normal)
} else {
button.setImage(UIImage.bingeImage(named: "ios-refresh"), for: .normal)
}
button.addTarget(self, action: #selector(seekForwards), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 13.4, *) {
let interaction = UIPointerInteraction(delegate: nil)
button.addInteraction(interaction)
}
return button
}()
private lazy var seekBackwardButton: UIButton = {
let button = UIButton()
button.tintColor = .white
if #available(iOS 13, *) {
let config = UIImage.SymbolConfiguration(pointSize: 22, weight: .regular, scale: .large)
button.setImage(UIImage(systemName: "gobackward.10", withConfiguration: config), for: .normal)
} else {
button.setImage(UIImage.bingeImage(named: "ios-refresh"), for: .normal)
button.imageView?.transform = CGAffineTransform(scaleX: -1, y: 1)
}
button.addTarget(self, action: #selector(seekBackwards), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 13.4, *) {
let interaction = UIPointerInteraction(delegate: nil)
button.addInteraction(interaction)
}
return button
}()
private weak var delegate: (BingeControlDelegate & AVRoutePickerViewDelegate)?
init(delegate: BingeControlDelegate & AVRoutePickerViewDelegate) {
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
let view = BingeClickThroughView()
view.backgroundColor = UIColor(white: 0.1, alpha: 0.75)
self.addSubviews(to: view)
self.addConstraints(with: view)
self.view = view
}
private func addSubviews(to parent: UIView) {
parent.addSubview(self.bufferProgressView)
parent.addSubview(self.timeSlider)
parent.addSubview(self.currentTimeView)
parent.addSubview(self.totalTimeView)
parent.addSubview(self.bottomBarRightStackView)
self.bottomBarRightStackView.addArrangedSubview(self.fullScreenButton)
parent.addSubview(self.topBarLeftStackView)
self.topBarLeftStackView.addArrangedSubview(self.emptyView)
self.topBarLeftStackView.addArrangedSubview(self.closeButton)
self.topBarLeftStackView.addArrangedSubview(self.offlineLabel)
parent.addSubview(self.titleView)
parent.addSubview(self.topBarRightStackView)
self.topBarRightStackView.addArrangedSubview(self.pictureInPictureButton)
self.topBarRightStackView.addArrangedSubview(self.airPlayButton)
self.topBarRightStackView.addArrangedSubview(self.settingsButton)
parent.addSubview(self.playPauseButton)
parent.addSubview(self.seekForwardButton)
parent.addSubview(self.seekBackwardButton)
}
private func addConstraints(with parent: UIView) { // swiftlint:disable:this function_body_length
let padding: CGFloat = 12
let parentMargins = parent.safeAreaLayoutGuide
let emptyViewWidthConstraint = self.emptyView.widthAnchor.constraint(equalToConstant: 0)
emptyViewWidthConstraint.priority = .required - 1
NSLayoutConstraint.activate([
// bottom bar
self.currentTimeView.leadingAnchor.constraint(equalTo: parentMargins.leadingAnchor, constant: padding),
self.currentTimeView.bottomAnchor.constraint(equalTo: parentMargins.bottomAnchor),
self.currentTimeView.heightAnchor.constraint(equalToConstant: 44),
self.bufferProgressView.leadingAnchor.constraint(equalTo: self.currentTimeView.trailingAnchor, constant: padding),
self.bufferProgressView.centerYAnchor.constraint(equalTo: self.currentTimeView.centerYAnchor),
self.bufferProgressView.heightAnchor.constraint(equalToConstant: 2),
self.timeSlider.leadingAnchor.constraint(equalTo: self.bufferProgressView.leadingAnchor, constant: -2),
self.timeSlider.trailingAnchor.constraint(equalTo: self.bufferProgressView.trailingAnchor, constant: -2),
self.timeSlider.centerYAnchor.constraint(equalTo: self.bufferProgressView.centerYAnchor),
self.totalTimeView.leadingAnchor.constraint(equalTo: self.bufferProgressView.trailingAnchor, constant: padding),
self.totalTimeView.bottomAnchor.constraint(equalTo: parentMargins.bottomAnchor),
self.totalTimeView.heightAnchor.constraint(equalToConstant: 44),
self.totalTimeView.trailingAnchor.constraint(lessThanOrEqualTo: parentMargins.trailingAnchor, constant: -padding),
self.bottomBarRightStackView.leadingAnchor.constraint(equalTo: self.totalTimeView.trailingAnchor),
self.bottomBarRightStackView.trailingAnchor.constraint(equalTo: parentMargins.trailingAnchor),
self.bottomBarRightStackView.bottomAnchor.constraint(equalTo: parentMargins.bottomAnchor),
self.bottomBarRightStackView.heightAnchor.constraint(equalToConstant: 44),
self.fullScreenButton.widthAnchor.constraint(equalToConstant: 44),
// top bar
self.topBarLeftStackView.leadingAnchor.constraint(equalTo: parentMargins.leadingAnchor),
self.topBarLeftStackView.topAnchor.constraint(equalTo: parentMargins.topAnchor),
self.topBarLeftStackView.heightAnchor.constraint(equalToConstant: 44),
emptyViewWidthConstraint,
self.closeButton.widthAnchor.constraint(equalToConstant: 44),
self.offlineLabel.leadingAnchor.constraint(greaterThanOrEqualTo: parentMargins.leadingAnchor, constant: padding),
self.titleView.leadingAnchor.constraint(equalTo: self.topBarLeftStackView.trailingAnchor, constant: padding),
self.titleView.topAnchor.constraint(equalTo: parentMargins.topAnchor),
self.titleView.heightAnchor.constraint(equalToConstant: 44),
self.topBarRightStackView.leadingAnchor.constraint(equalTo: self.titleView.trailingAnchor, constant: padding),
self.topBarRightStackView.topAnchor.constraint(equalTo: parentMargins.topAnchor),
self.topBarRightStackView.trailingAnchor.constraint(equalTo: parentMargins.trailingAnchor),
self.pictureInPictureButton.widthAnchor.constraint(equalToConstant: 44),
self.settingsButton.widthAnchor.constraint(equalToConstant: 44),
// center
self.playPauseButton.centerXAnchor.constraint(equalTo: parentMargins.centerXAnchor),
self.playPauseButton.centerYAnchor.constraint(equalTo: parentMargins.centerYAnchor),
self.playPauseButton.heightAnchor.constraint(equalToConstant: 66),
self.playPauseButton.widthAnchor.constraint(equalToConstant: 66),
NSLayoutConstraint(item: self.seekForwardButton,
attribute: .centerX,
relatedBy: .equal,
toItem: parentMargins,
attribute: .centerX,
multiplier: 1.5,
constant: 0),
self.seekForwardButton.centerYAnchor.constraint(equalTo: self.playPauseButton.centerYAnchor),
self.seekForwardButton.heightAnchor.constraint(equalToConstant: 44),
self.seekForwardButton.widthAnchor.constraint(equalToConstant: 44),
NSLayoutConstraint(item: self.seekBackwardButton,
attribute: .centerX,
relatedBy: .equal,
toItem: parentMargins,
attribute: .centerX,
multiplier: 0.5,
constant: 0),
self.seekBackwardButton.centerYAnchor.constraint(equalTo: self.playPauseButton.centerYAnchor),
self.seekBackwardButton.heightAnchor.constraint(equalToConstant: 44),
self.seekBackwardButton.widthAnchor.constraint(equalToConstant: 44),
])
self.airPlayButton.widthAnchor.constraint(equalToConstant: 44).isActive = true
}
private func formatTime(_ time: TimeInterval, forTotalDuration totalDuration: TimeInterval) -> String {
if time.isNaN || time.isInfinite {
return "0:00"
}
let seconds = Int(time) % 60
let minutes = (Int(time) / 60) % 60
let hours = Int(time) / 60 / 60
let safeTotalDuration = totalDuration.isNaN || totalDuration.isInfinite ? time : totalDuration
let totalDurationMinutes = (Int(safeTotalDuration) / 60) % 60
let totalDurationHours = Int(safeTotalDuration) / 60 / 60
if totalDurationHours > 0 {
return String(format: "%d:%02d:%02d", hours, minutes, seconds)
} else if totalDurationMinutes > 9 {
return String(format: "%02d:%02d", minutes, seconds)
} else {
return String(format: "%d:%02d", minutes, seconds)
}
}
@objc private func togglePictureInPictureMode() {
self.delegate?.togglePictureInPictureMode()
}
@objc private func showMediaSelection() {
self.delegate?.showMediaSelection(for: self.settingsButton)
}
@objc private func playPauseVideo() {
if self.playPauseButton.isSelected {
self.delegate?.pausePlayback()
} else {
self.delegate?.startPlayback()
}
}
@objc private func seekForwards() {
self.delegate?.seekForwards()
}
@objc private func seekBackwards() {
self.delegate?.seekBackwards()
}
@objc private func changeProgress(sender: UISlider, event: UIEvent) {
switch event.allTouches?.first?.phase {
case .began:
self.delegate?.stopAutoHideOfControlsOverlay()
case .moved:
self.delegate?.willSeekTo(progress: Double(sender.value))
case .ended:
self.delegate?.seekTo(progress: Double(sender.value))
default:
break
}
}
@objc private func toggleFullScreenMode() {
self.delegate?.toggleFullScreenMode()
}
@objc private func dismissPlayer() {
self.delegate?.dismissPlayer()
}
func setTitle(_ title: String?) {
self.titleView.text = title
}
func setTintColor(_ color: UIColor) {
self.timeSlider.tintColor = color
self.timeSlider.minimumTrackTintColor = color
self.airPlayButton.activeTintColor = color
}
func adaptToItem(_ item: AVPlayerItem) {
let duration = item.duration
let isValidDuration = duration.isNumeric && duration.value != 0
let seconds = isValidDuration ? CMTimeGetSeconds(duration): 0.0
let currentTime = CMTimeGetSeconds(item.currentTime())
self.timeSlider.value = isValidDuration ? Float(currentTime / seconds) : 0.0
self.playPauseButton.isEnabled = isValidDuration
self.timeSlider.isEnabled = isValidDuration
self.totalTimeView.text = self.formatTime(seconds, forTotalDuration: seconds)
self.offlineLabel.isHidden = !item.asset.isLocalAsset
}
func adaptToTimeControlStatus(_ timeControlStatus: AVPlayer.TimeControlStatus) {
self.playPauseButton.isSelected = timeControlStatus == .playing
self.playPauseButton.isHidden = timeControlStatus == .waitingToPlayAtSpecifiedRate
}
func adaptToTimeChange(currentTime: TimeInterval, totalTime: TimeInterval, isManualSeekPosition: Bool = false) {
self.currentTimeView.text = self.formatTime(currentTime, forTotalDuration: totalTime)
if !self.timeSlider.isHighlighted, !isManualSeekPosition {
let value = Float(currentTime / totalTime)
self.timeSlider.setValue(value, animated: true)
}
}
func adaptToBufferChange(availableTime: TimeInterval, totalTime: TimeInterval) {
self.bufferProgressView.progress = Float(availableTime / totalTime)
}
func adaptToLayoutState(_ state: LayoutState, allowFullScreenMode: Bool, isStandAlone: Bool) {
let hideFullScreenButton = state == .remote || !allowFullScreenMode || isStandAlone
self.fullScreenButton.isHidden = hideFullScreenButton
self.fullScreenButton.isSelected = state == .fullScreen
self.closeButton.isHidden = !isStandAlone
self.titleView.isHidden = state != .fullScreen
}
func adaptToPictureInPicturePossible(_ pictureInPicturePossible: Bool) {
self.pictureInPictureButton.isEnabled = pictureInPicturePossible
}
func adaptToMultiRouteOutput(for multipleRoutesDetected: Bool) {
DispatchQueue.main.async {
UIView.animate(withDuration: 0.25) {
self.airPlayButton.isHidden = !multipleRoutesDetected
}
}
}
}
extension AVAsset {
var isLocalAsset: Bool {
guard let urlAsset = self as? AVURLAsset else { return false }
return urlAsset.url.isFileURL
}
}
extension UIImage {
static func bingeImage(named name: String) -> UIImage? {
let bundle = Bundle(for: BingeControlsViewController.self)
return UIImage(named: name, in: bundle, compatibleWith: nil)
}
}
| gpl-3.0 | ef1f777d7b5c6e5151b70ecf6bf10207 | 39.910584 | 145 | 0.672242 | 5.104508 | false | false | false | false |
lpski/DepthButton | buttonTest/DepthButton.swift | 1 | 2846 | //
// DepthButton.swift
// buttonTest
//
// Created by Luke Porupski on 7/22/16.
// Copyright © 2016 Luke Porupski. All rights reserved.
//
import UIKit
class DepthButton: UIButton {
private var originalX: Int?
private var originalY: Int?
private var primaryBackground: UIColor?
@IBInspectable var rotateOnTouch: Bool = true
@IBInspectable var rotationModifier: CGFloat = 45 // higher = larger transformation on touches
@IBInspectable var scaleOnTouch: Bool = true
@IBInspectable var scalePercentage: CGFloat = 0.95
//@IBInspectable var touchAnimationEnabled: Bool = true
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
let touch = touches.first! as UITouch
let touchLocation = touch.locationInView(self)
transformFromTouchLocation(touchLocation)
}
private func transformFromTouchLocation(location: CGPoint){
//identity which will hold x & y axis shifts
var identity = CATransform3DIdentity
identity.m34 = 1.0 / -500
//gets absolute value of offset of touch from center of button
let absXOffset = abs(self.bounds.width / 2 - location.x)
let absYOffset = abs(self.bounds.height / 2 - location.y)
if(self.rotateOnTouch == true){
//indicates percentage of specified maxShiftAngle to shift on x axis based on y offset
let xDegreeModifier = absYOffset / self.bounds.height / 2
let xTrans = CATransform3DRotate(identity, xDegreeModifier * self.rotationModifier * CGFloat(M_PI) / 180.0, location.y < self.bounds.height / 2 ? 1.0 : -1.0, 0, 0)
//indicates percentage of specified maxShiftAngle to shift on y axis based on x offset
let yDegreeModifier = absXOffset / self.bounds.width / 2
let yTrans = CATransform3DRotate(identity, yDegreeModifier * self.rotationModifier * CGFloat(M_PI) / 180.0, 0, location.x > self.bounds.width / 2 ? 1.0 : -1.0, 0)
//concats two rotate transforms
identity = CATransform3DConcat(xTrans, yTrans)
}
if(self.scaleOnTouch == true){
let scaleTrans = CATransform3DScale(identity, self.scalePercentage, self.scalePercentage, 1.0)
identity = CATransform3DConcat(identity, scaleTrans)
}
self.layer.transform = identity
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
self.layer.transform = CATransform3DIdentity
}
}
| mit | ba73332e4576c3ddd0779c6910ca7265 | 32.081395 | 175 | 0.625659 | 4.663934 | false | false | false | false |
rivetlogic/liferay-mobile-directory-ios | Liferay-Screens/Source/DDL/DDLXSDParser.swift | 1 | 7336 | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
import Foundation
public class DDLXSDParser {
//MARK: Constructors
public init() {
}
//MARK: Public methods
public func parse(xsd: String, locale: NSLocale) -> [DDLField]? {
var result:[DDLField]? = nil
let xmlString = xsd as NSString?
if let xmlValue = xmlString {
let data = xmlValue.dataUsingEncoding(NSUTF8StringEncoding)
var outError: NSError?
if let document = SMXMLDocument(data: data, error: &outError) {
result = processDocument(document, locale: locale)
}
}
return result
}
//MARK: Private methods
private func processDocument(document:SMXMLDocument, locale: NSLocale) -> [DDLField]? {
var result:[DDLField]?
if let elements = document.root?.childrenNamed("dynamic-element") {
let defaultLocale = NSLocale(
localeIdentifier:document.root?.attributeNamed("default-locale") ?? "en_US")
result = []
for element in elements as! [SMXMLElement] {
if let formField = createFormField(element,
locale: locale,
defaultLocale: defaultLocale) {
result!.append(formField)
}
}
}
return result
}
private func createFormField(xmlElement:SMXMLElement,
locale: NSLocale,
defaultLocale: NSLocale)
-> DDLField? {
var result:DDLField?
let dataType = DDLField.DataType.from(xmlElement:xmlElement)
let localizedMetadata = processLocalizedMetadata(xmlElement,
locale: locale,
defaultLocale: defaultLocale)
let mergedAttributes = mergeDictionaries(
dict1: xmlElement.attributes as! [String:AnyObject],
dict2: localizedMetadata)
return dataType.createField(attributes: mergedAttributes, locale: locale)
}
private func mergeDictionaries(
#dict1:[String:AnyObject],
dict2:[String:AnyObject])
-> [String:AnyObject] {
var result:[String:AnyObject] = [:]
for (key1,value1) in dict1 {
result.updateValue(value1, forKey: key1)
}
for (key2,value2) in dict2 {
result.updateValue(value2, forKey: key2)
}
return result
}
private func processLocalizedMetadata(dynamicElement:SMXMLElement,
locale: NSLocale,
defaultLocale: NSLocale)
-> [String:AnyObject] {
var result:[String:AnyObject] = [:]
func addElement(
name elementName: String,
#metadata: SMXMLElement,
inout #result: [String:AnyObject]) {
if let element = metadata.childWithAttribute("name", value: elementName) {
result[elementName] = element.value
}
}
func findOptions(
#dynamicElement:SMXMLElement,
#locale: NSLocale,
#defaultLocale: NSLocale)
-> [[String:AnyObject]]? {
var options:[[String:AnyObject]] = []
let optionElements = childrenWithAttribute("type",
value: "option",
parent: dynamicElement)
for optionElement in optionElements {
var option:[String:AnyObject] = [:]
option["name"] = optionElement.attributeNamed("name")
option["value"] = optionElement.attributeNamed("value")
if let localizedMetadata = findMetadataElement(optionElement,
locale: locale, defaultLocale: defaultLocale) {
if let element = localizedMetadata.childWithAttribute("name", value: "label") {
option["label"] = element.value
}
}
options.append(option)
}
return options.count == 0 ? nil : options
}
if let localizedMetadata = findMetadataElement(dynamicElement,
locale: locale,
defaultLocale: defaultLocale) {
addElement(name: "label", metadata: localizedMetadata, result: &result)
addElement(name: "predefinedValue", metadata: localizedMetadata, result: &result)
addElement(name: "tip", metadata: localizedMetadata, result: &result)
}
if let options = findOptions(
dynamicElement: dynamicElement,
locale: locale,
defaultLocale: defaultLocale) {
result["options"] = options
}
return result
}
private func findMetadataElement(dynamicElement:SMXMLElement,
locale: NSLocale, defaultLocale: NSLocale)
-> SMXMLElement? {
// Locale matching fallback mechanism: it's designed in such a way to return
// the most suitable locale among the available ones. It minimizes the default
// locale fallback. It supports input both with one component (language) and
// two components (language and country).
//
// Examples for locale = "es_ES"
// a1. Matches elements with "es_ES" (full match)
// a2. Matches elements with "es"
// a3. Matches elements for any country: "es_ES", "es_AR"...
// a4. Matches elements for default locale
// Examples for locale = "es"
// b1. Matches elements with "es" (full match)
// b2. Matches elements for any country: "es_ES", "es_AR"...
// b3. Matches elements for default locale
let metadataElements = dynamicElement.childrenNamed("meta-data") as? [SMXMLElement]
if metadataElements == nil {
return nil
}
let currentLanguageCode = locale.objectForKey(NSLocaleLanguageCode) as! String
let currentCountryCode = locale.objectForKey(NSLocaleCountryCode) as? String
var resultElement:SMXMLElement?
if let metadataElement = findElementWithAttribute("locale",
value:locale.localeIdentifier, elements:metadataElements!) {
// cases 'a1' and 'b1'
resultElement = metadataElement
}
else {
if currentCountryCode != nil {
if let metadataElement = findElementWithAttribute("locale",
value:currentLanguageCode,
elements:metadataElements!) {
// case 'a2'
resultElement = metadataElement
}
}
}
if resultElement == nil {
// Pre-final fallback (a3, b2): find any metadata starting with language
let foundMetadataElements = metadataElements!.filter(
{ (metadataElement:SMXMLElement) -> Bool in
if let metadataLocale = metadataElement.attributes["locale"]?.description {
return metadataLocale.hasPrefix(currentLanguageCode + "_")
}
return false
})
resultElement = foundMetadataElements.first
}
if resultElement == nil {
// Final fallback (a4, b3): find default metadata
resultElement = findElementWithAttribute("locale",
value:defaultLocale.localeIdentifier, elements:metadataElements!)
}
return resultElement
}
private func childrenWithAttribute(attribute:String, value:String, parent:SMXMLElement) ->
[SMXMLElement] {
var result:[SMXMLElement] = []
for element in parent.children {
let child = element as! SMXMLElement
let attrValue = child.attributeNamed(attribute)
if attrValue != nil && attrValue == value {
result.append(child)
}
}
return result
}
private func findElementWithAttribute(attribute:String, value:String, elements:[SMXMLElement])
-> SMXMLElement? {
for element in elements {
let attrValue = element.attributeNamed(attribute)
if attrValue != nil && attrValue == value {
return element
}
}
return nil
}
}
| gpl-3.0 | 4da777ad740a436c8ef9acdf029bc0c3 | 25.2 | 95 | 0.705971 | 3.80893 | false | false | false | false |
TigerWolf/LoginKit | Example/Tests/Tests.swift | 1 | 1423 | // https://github.com/Quick/Quick
import Quick
import Nimble
@testable import LoginKit
class LoginKitSpec: QuickSpec {
override func spec() {
describe("LoginKitConfig"){
it("logoImage is an image") {
expect(LoginKitConfig.logoImage).to(beAnInstanceOf(UIImage))
}
it("authType is JWT by default") {
expect(LoginKitConfig.authType) == AuthType.JWT
}
}
describe("LoginController") {
let lc = LoginController()
it("saves password on tap") {
let _ = lc.view
expect(LoginService.storePassword) == false
expect(lc.savePasswordButton.selected) == false
lc.savePasswordTapped()
expect(LoginService.storePassword) == true
expect(lc.savePasswordButton.selected) == true
lc.savePasswordTapped()
expect(LoginService.storePassword) == false
expect(lc.savePasswordButton.selected) == false
}
it("token is saved") {
let _ = lc.view
json = "{'token':'aafafafserghfses'}"
lc.saveToken(json)
expect(LoginService.user.authToken).to(equal("Qaafafafserghfses"))
}
}
}
}
| bsd-3-clause | de8b911484f108e0e9dc4b3799c638cb | 29.276596 | 82 | 0.506676 | 5.010563 | false | true | false | false |
matthewpurcell/firefox-ios | Client/Frontend/Settings/Clearables.swift | 1 | 7053 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebKit
import Deferred
import WebImage
private let log = Logger.browserLogger
// Removed Clearables as part of Bug 1226654, but keeping the string around.
private let removedSavedLoginsLabel = NSLocalizedString("Saved Logins", tableName: "ClearPrivateData", comment: "Settings item for clearing passwords and login data")
// A base protocol for something that can be cleared.
protocol Clearable {
func clear() -> Success
var label: String { get }
}
class ClearableError: MaybeErrorType {
private let msg: String
init(msg: String) {
self.msg = msg
}
var description: String { return msg }
}
// Clears our browsing history, including favicons and thumbnails.
class HistoryClearable: Clearable {
let profile: Profile
init(profile: Profile) {
self.profile = profile
}
var label: String {
return NSLocalizedString("Browsing History", tableName: "ClearPrivateData", comment: "Settings item for clearing browsing history")
}
func clear() -> Success {
return profile.history.clearHistory().bind { success in
SDImageCache.sharedImageCache().clearDisk()
SDImageCache.sharedImageCache().clearMemory()
NSNotificationCenter.defaultCenter().postNotificationName(NotificationPrivateDataClearedHistory, object: nil)
log.debug("HistoryClearable succeeded: \(success).")
return Deferred(value: success)
}
}
}
struct ClearableErrorType: MaybeErrorType {
let err: ErrorType
init(err: ErrorType) {
self.err = err
}
var description: String {
return "Couldn't clear: \(err)."
}
}
// Clear the web cache. Note, this has to close all open tabs in order to ensure the data
// cached in them isn't flushed to disk.
class CacheClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Cache", tableName: "ClearPrivateData", comment: "Settings item for clearing the cache")
}
func clear() -> Success {
if #available(iOS 9.0, *) {
let dataTypes = Set([WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
WKWebsiteDataStore.defaultDataStore().removeDataOfTypes(dataTypes, modifiedSince: NSDate.distantPast(), completionHandler: {})
} else {
// First ensure we close all open tabs first.
tabManager.removeAll()
// Reset the process pool to ensure no cached data is written back
tabManager.resetProcessPool()
// Remove the basic cache.
NSURLCache.sharedURLCache().removeAllCachedResponses()
// Now let's finish up by destroying our Cache directory.
do {
try deleteLibraryFolderContents("Caches")
} catch {
return deferMaybe(ClearableErrorType(err: error))
}
}
log.debug("CacheClearable succeeded.")
return succeed()
}
}
private func deleteLibraryFolderContents(folder: String) throws {
let manager = NSFileManager.defaultManager()
let library = manager.URLsForDirectory(NSSearchPathDirectory.LibraryDirectory, inDomains: .UserDomainMask)[0]
let dir = library.URLByAppendingPathComponent(folder)
let contents = try manager.contentsOfDirectoryAtPath(dir.path!)
for content in contents {
do {
try manager.removeItemAtURL(dir.URLByAppendingPathComponent(content))
} catch where ((error as NSError).userInfo[NSUnderlyingErrorKey] as? NSError)?.code == Int(EPERM) {
// "Not permitted". We ignore this.
log.debug("Couldn't delete some library contents.")
}
}
}
private func deleteLibraryFolder(folder: String) throws {
let manager = NSFileManager.defaultManager()
let library = manager.URLsForDirectory(NSSearchPathDirectory.LibraryDirectory, inDomains: .UserDomainMask)[0]
let dir = library.URLByAppendingPathComponent(folder)
try manager.removeItemAtURL(dir)
}
// Removes all app cache storage.
class SiteDataClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Offline Website Data", tableName: "ClearPrivateData", comment: "Settings item for clearing website data")
}
func clear() -> Success {
if #available(iOS 9.0, *) {
let dataTypes = Set([WKWebsiteDataTypeOfflineWebApplicationCache])
WKWebsiteDataStore.defaultDataStore().removeDataOfTypes(dataTypes, modifiedSince: NSDate.distantPast(), completionHandler: {})
} else {
// First, close all tabs to make sure they don't hold anything in memory.
tabManager.removeAll()
// Then we just wipe the WebKit directory from our Library.
do {
try deleteLibraryFolder("WebKit")
} catch {
return deferMaybe(ClearableErrorType(err: error))
}
}
log.debug("SiteDataClearable succeeded.")
return succeed()
}
}
// Remove all cookies stored by the site. This includes localStorage, sessionStorage, and WebSQL/IndexedDB.
class CookiesClearable: Clearable {
let tabManager: TabManager
init(tabManager: TabManager) {
self.tabManager = tabManager
}
var label: String {
return NSLocalizedString("Cookies", tableName: "ClearPrivateData", comment: "Settings item for clearing cookies")
}
func clear() -> Success {
if #available(iOS 9.0, *) {
let dataTypes = Set([WKWebsiteDataTypeCookies, WKWebsiteDataTypeLocalStorage, WKWebsiteDataTypeSessionStorage, WKWebsiteDataTypeWebSQLDatabases, WKWebsiteDataTypeIndexedDBDatabases])
WKWebsiteDataStore.defaultDataStore().removeDataOfTypes(dataTypes, modifiedSince: NSDate.distantPast(), completionHandler: {})
} else {
// First close all tabs to make sure they aren't holding anything in memory.
tabManager.removeAll()
// Now we wipe the system cookie store (for our app).
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
if let cookies = storage.cookies {
for cookie in cookies {
storage.deleteCookie(cookie)
}
}
// And just to be safe, we also wipe the Cookies directory.
do {
try deleteLibraryFolderContents("Cookies")
} catch {
return deferMaybe(ClearableErrorType(err: error))
}
}
log.debug("CookiesClearable succeeded.")
return succeed()
}
} | mpl-2.0 | 9684a3161903b4e61e85373723fc704a | 34.989796 | 194 | 0.66213 | 5.347233 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | swift/modules/SwiftUtilities/Sources/SwiftUtilities/ValueList.swift | 1 | 4509 | // ValueOutput
//
// Output a set of data formatted neatly.
//
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0.
import Foundation
public struct ValueItem {
var title: String
var value: String
// What to print for values of true and false
var trueValue: String = ""
var falseValue: String = ""
init(title: String, value: Int = 0) {
self.title = title
self.value = String(value)
}
init(title: String, value: String) {
self.title = title
self.value = value
}
init(title: String, value: Bool, trueValue: String = "Yes", falseValue: String = "No") {
self.trueValue = trueValue
self.falseValue = falseValue
self.title = title
if value == true {
self.value = self.trueValue
} else {
self.value = self.falseValue
}
}
}
public class ValueList {
var header: String?
var items: [ValueItem] = []
let gap = 4
/// Initialize a new `ValueList`.
///
/// - Parameters:
/// - header: A title string for the entire list.
/// - gap: Minimum number of spaces that should separate the columns.
init(header: String? = nil) {
self.header = header
}
/// Add a new integer item to the list.
///
/// - Parameters:
/// - title: A title for the value.
/// - value: The `Int` value.
func addItem(title: String, value: Int) {
items.append(ValueItem(title: title, value: value))
}
/// Add a new string item to the list.
///
/// - Parameters:
/// - title: A title for the value.
/// - value: The `String` value.
func addItem(title: String, value: String) {
items.append(ValueItem(title: title, value: value))
}
/// Add a new Boolean item to the list.
///
/// - Parameters:
/// - title: A title for the value.
/// - value: The `Bool` value.
func addItem(title: String, value: Bool) {
items.append(ValueItem(title: title, value: value))
}
/// Return the number of items in the list.
func getItemCount() -> Int {
return self.items.count
}
/// The width of the title column, not including the gap.
private var titleWidth: Int {
var width = 0
for item in self.items {
if item.title.count > width {
width = item.title.count
}
}
return width
}
/// The width of the gap. Zero if no gap. This is computed to take into
/// account whether or not the list is empty, and any other factors.
var gapWidth: Int {
get {
if self.items.count == 0 {
return 0
} else {
return self.gap
}
}
}
/// The width of the value column in characters.
private var valueWidth: Int {
get {
var width = 0
for item in self.items {
if item.value.count > width {
width = item.value.count
}
}
return width
}
}
// The computed total width of the table's contents, including the title
// and value columns and the gap.
private var tableWidth: Int {
let dataWidth = self.titleWidth + self.gapWidth + self.valueWidth
guard let header = self.header else {
return dataWidth
}
if dataWidth > header.count {
return dataWidth
}
return header.count
}
/// A divider string the width of the entire output area.
private var divider: String {
if self.tableWidth > 0 {
return String(repeating: "=", count: self.tableWidth)
}
return ""
}
/// Return a string containing the formatted data ready for printing.
///
/// - Returns: A `String` containing the entire formatted output, ready to
/// be displayed on the console.
func getFormattedOutput() -> String {
var output = ""
if self.header != nil {
output += self.header! + "\n" + self.divider + "\n"
}
for item in items {
let titleLength = item.title.count
let padding = self.titleWidth + self.gapWidth - titleLength
output += "\(item.title)\(String(repeating: " ", count: padding))\(item.value)\n"
}
return output
}
} | apache-2.0 | c972aebbf7e2518e93c8a93008f42fe1 | 25.374269 | 93 | 0.547572 | 4.298379 | false | false | false | false |
sora0077/SimpleObserver | SimpleObserverTests/ObservingArrayTests.swift | 1 | 4363 | //
// ObservingArrayTests.swift
// SimpleObserver
//
// Created by 林達也 on 2015/02/12.
// Copyright (c) 2015年 spika.co.jp. All rights reserved.
//
import UIKit
import XCTest
class ObservingArrayTests: 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 test_Array() {
wait { done in
let hoge = ObservingArray([1], ==)
let expected = 2
hoge.watch(self) { (e, _) in
XCTAssertEqual(1, e.oldValue.count, "")
XCTAssertEqual(2, e.newValue.count, "")
switch e.change {
case let .Insertion(box, idx):
XCTAssertEqual(expected, box.unbox, "")
done()
default:
XCTAssertFalse(true, "error")
}
}
hoge.append(expected)
return {}
}
}
func test_Replace() {
wait { done in
var cnt = 0
let counter = { ++cnt }
let hoge = ObservingArray([1], ==)
hoge.watch(self) { (e, _) in
switch e.change {
case let .Replacement(box, idx):
XCTAssertEqual(box.unbox, 2, "")
counter()
done()
default:
XCTAssertFalse(true, "error \(e.change)")
}
}
hoge[0] = 2
return {
XCTAssertEqual(1, cnt, "")
}
}
}
func test_Replace_同じ値は呼ばれない() {
wait { done in
var cnt = 0
let counter = { ++cnt }
let hoge = ObservingArray([1], ==)
hoge.watch(self) { (e, _) in
switch e.change {
case let .Replacement(box, idx):
XCTAssertEqual(box.unbox, 2, "")
counter()
done()
default:
XCTAssertFalse(true, "error \(e.change)")
}
}
dispatch_after(when(0.1), dispatch_get_main_queue()) {
done()
}
hoge[0] = 1
return {
XCTAssertEqual(0, cnt, "")
}
}
}
func test_Arrayを丸ごと入れ替えた場合() {
wait { done in
var cnt = 0
let counter = { ++cnt }
let hoge = ObservingArray([1], ==)
let expected = [2]
hoge.watch(self) { (e, _) in
counter()
XCTAssertEqual(1, e.oldValue.count, "")
XCTAssertEqual(expected.count, e.newValue.count, "")
switch e.change {
case .Setting:
XCTAssertEqual(expected, e.newValue, "")
done()
default:
XCTAssertFalse(true, "error")
}
}
hoge.value = expected
return {
XCTAssertEqual(1, cnt, "")
}
}
}
func test_unwatchされたら通知されない() {
var cnt = 0
let counter = { ++cnt }
let hoge = ObservingArray([1], ==)
let expected = [2]
wait { done in
hoge.watch(self) { _ in
counter()
done()
}
dispatch_after(when(0.1), dispatch_get_main_queue()) {
done()
}
hoge.unwatch(self)
hoge.value = expected
return {
XCTAssertEqual(0, cnt, "")
}
}
}
}
| mit | fc30652d77ddc196578d94bf72c2b5a1 | 24.414201 | 111 | 0.3844 | 5.257038 | false | true | false | false |
hironytic/Moltonf-iOS | Moltonf/Model/Archive/ArchiveToJSON.swift | 1 | 49768 | //
// ArchiveToJSON.swift
// Moltonf
//
// Copyright (c) 2016 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import XMLPullitic
private typealias S = ArchiveSchema
private typealias K = ArchiveConstants
private let PERIOD_JSON_FORMAT = "period-%ld.json"
protocol ArchiveJSONWriter {
func writeArchiveJSON(fileName: String, object: [String: Any]) throws
}
public class ArchiveToJSON: ArchiveJSONWriter {
public enum ConvertError: Error {
case cantReadArchive
case invalidOutputDirectory(innerError: Error)
case parseError(innerError: Error)
case invalidAttrValue(attribute: String, value: String)
case missingAttr(attribute: String)
case failedInWritingFile(filePath: String, innerError: Error?)
}
private let _archivePath: String
private let _outDirPath: String
public init(fromArchive archivePath: String, toDirectory outDirPath: String) {
_archivePath = archivePath
_outDirPath = outDirPath
}
public func convert() throws {
// ready parser
guard let parser = XMLPullParser(contentsOfURL: URL(fileURLWithPath: _archivePath)) else { throw ConvertError.cantReadArchive }
parser.shouldProcessNamespaces = true
let parseContext = ParseContext(parser: parser)
// ready output directory
do {
let fileManager = FileManager.default
try fileManager.createDirectory(atPath: _outDirPath, withIntermediateDirectories: true, attributes: nil)
} catch let error {
throw ConvertError.invalidOutputDirectory(innerError: error)
}
// parse and convert
do {
parsing: while true {
let event = try parser.next()
switch event {
case .startElement(name: S.ELEM_VILLAGE, namespaceURI: S.NS_ARCHIVE?, element: let element):
try VillageElementConverter(parseContext: parseContext).convert(element, writer: self)
case .endDocument:
break parsing
default:
break
}
}
} catch XMLPullParserError.parseError(let error) {
throw ConvertError.parseError(innerError: error)
}
}
func writeArchiveJSON(fileName: String, object: [String: Any]) throws {
let filePath = (_outDirPath as NSString).appendingPathComponent(fileName)
guard let outStream = OutputStream(toFileAtPath: filePath, append: false) else {
throw ConvertError.failedInWritingFile(filePath: filePath, innerError: nil)
}
do {
outStream.open()
defer { outStream.close() }
var error: NSError?
let result = JSONSerialization.writeJSONObject(object, to: outStream, options: JSONSerialization.WritingOptions(), error: &error)
if (result == 0) {
throw ConvertError.failedInWritingFile(filePath: filePath, innerError: error)
}
}
}
class ParseContext {
let parser: XMLPullParser
private var _lastPublicTalkNo: Int = 0
init(parser: XMLPullParser) {
self.parser = parser
}
func nextPublicTalkNo() -> Int {
_lastPublicTalkNo += 1
return _lastPublicTalkNo
}
}
class ElementConverter {
let _parseContext: ParseContext
init(parseContext: ParseContext) {
_parseContext = parseContext
}
func skipElement() throws {
parsing: while true {
let event = try _parseContext.parser.next()
switch event {
case .startElement:
try skipElement()
break
case .endElement:
break parsing
default:
break
}
}
}
}
class VillageElementConverter: ElementConverter {
func convert(_ element: XMLElement, writer: ArchiveJSONWriter) throws {
let villageWrapper = ObjectWrapper(object: [:])
// attributes
let mapToVillage = map(toObject: villageWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_LANG: mapToVillage(K.LANG, asString),
S.ATTR_BASE: mapToVillage(K.BASE, asString),
S.ATTR_FULL_NAME: mapToVillage(K.FULL_NAME, asString),
S.ATTR_VID: mapToVillage(K.VID, asInt),
S.ATTR_COMMIT_TIME: mapToVillage(K.COMMIT_TIME, asString),
S.ATTR_STATE: mapToVillage(K.STATE, asString),
S.ATTR_DISCLOSURE: mapToVillage(K.DISCLOSURE, asString),
S.ATTR_IS_VALID: mapToVillage(K.IS_VALID, asBool),
S.ATTR_LAND_NAME: mapToVillage(K.LAND_NAME, asString),
S.ATTR_FORMAL_NAME: mapToVillage(K.FORMAL_NAME, asString),
S.ATTR_LAND_ID: mapToVillage(K.LAND_ID, asString),
S.ATTR_LAND_PREFIX: mapToVillage(K.LAND_PREFIX, asString),
S.ATTR_LOCALE: mapToVillage(K.LOCALE, asString),
S.ATTR_ORGENCODING: mapToVillage(K.ORGENCODING, asString),
S.ATTR_TIMEZONE: mapToVillage(K.TIMEZONE, asString),
S.ATTR_GRAVE_ICON_URI: mapToVillage(K.GRAVE_ICON_URI, asString),
S.ATTR_GENERATOR: mapToVillage(K.GENERATOR, asString),
],
required: [
S.ATTR_BASE, S.ATTR_FULL_NAME, S.ATTR_VID, S.ATTR_STATE,
S.ATTR_LAND_NAME, S.ATTR_FORMAL_NAME, S.ATTR_LAND_ID,
S.ATTR_LAND_PREFIX, S.ATTR_GRAVE_ICON_URI,
],
defaultValues: [
S.ATTR_LANG: S.VAL_LANG_JA_JP,
S.ATTR_DISCLOSURE: S.VAL_DISCLOSURE_COMPLETE,
S.ATTR_IS_VALID: S.VAL_BOOLEAN_TRUE,
S.ATTR_LOCALE: S.VAL_LANG_JA_JP,
S.ATTR_ORGENCODING: S.VAL_ENCODING_SHIFT_JIS,
S.ATTR_TIMEZONE: S.VAL_TIMEZONE_0900,
]
)
// children
var periods: [Any] = []
parsing: while true {
let event = try _parseContext.parser.next()
switch event {
case .startElement(name: S.ELEM_AVATAR_LIST, namespaceURI: S.NS_ARCHIVE?, element: let element):
villageWrapper.object[K.AVATAR_LIST] = try AvatarListElementConverter(parseContext: _parseContext).convert(element)
case .startElement(name: S.ELEM_PERIOD, namespaceURI: S.NS_ARCHIVE?, element: let element):
periods.append(try PeriodElementConverter(parseContext: _parseContext).convert(element, writer: writer))
case .startElement:
try skipElement()
break
case .endElement:
break parsing
default:
break
}
}
villageWrapper.object[K.PERIODS] = periods as Any?
// write to playdata.json
let village = villageWrapper.object
try writer.writeArchiveJSON(fileName: K.FILE_PLAYDATA_JSON, object: village)
}
}
class AvatarListElementConverter: ElementConverter {
func convert(_ element: XMLElement) throws -> [[String: Any]] {
// children
var avatars: [[String: Any]] = []
parsing: while true {
let event = try _parseContext.parser.next()
switch event {
case .startElement(name: S.ELEM_AVATAR, namespaceURI: S.NS_ARCHIVE?, element: let element):
avatars.append(try AvatarElementConverter(parseContext: _parseContext).convert(element))
case .startElement:
try skipElement()
break
case .endElement:
break parsing
default:
break
}
}
return avatars
}
}
class AvatarElementConverter: ElementConverter {
func convert(_ element: XMLElement) throws -> [String: Any] {
let avatarWrapper = ObjectWrapper(object: [:])
// attributes
let mapToAvatar = map(toObject: avatarWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_AVATAR_ID: mapToAvatar(K.AVATAR_ID, asString),
S.ATTR_FULL_NAME: mapToAvatar(K.FULL_NAME, asString),
S.ATTR_SHORT_NAME: mapToAvatar(K.SHORT_NAME, asString),
S.ATTR_FACE_ICON_URI: mapToAvatar(K.FACE_ICON_URI, asString),
],
required: [
S.ATTR_AVATAR_ID, S.ATTR_FULL_NAME, S.ATTR_SHORT_NAME
],
defaultValues: [:]
)
// children
try skipElement()
return avatarWrapper.object
}
}
class PeriodElementConverter: ElementConverter {
func convert(_ element: XMLElement, writer: ArchiveJSONWriter) throws -> [String: Any] {
let shallowPeriodWrapper = ObjectWrapper(object: [:])
let deepPeriodWrapper = ObjectWrapper(object: [:])
// attributes
let mapToPeriod = map(toObjects: [shallowPeriodWrapper, deepPeriodWrapper])
try convertAttribute(element,
mapping: [
S.ATTR_TYPE: mapToPeriod(K.TYPE, asString),
S.ATTR_DAY: mapToPeriod(K.DAY, asInt),
S.ATTR_DISCLOSURE: mapToPeriod(K.DISCLOSURE, asString),
S.ATTR_NEXT_COMMIT_DAY: mapToPeriod(K.NEXT_COMMIT_DAY, asString),
S.ATTR_COMMIT_TIME: mapToPeriod(K.COMMIT_TIME, asString),
S.ATTR_SOURCE_URI: mapToPeriod(K.SOURCE_URI, asString),
S.ATTR_LOADED_TIME: mapToPeriod(K.LOADED_TIME, asString),
S.ATTR_LOADED_BY: mapToPeriod(K.LOADED_BY, asString),
],
required: [
S.ATTR_TYPE, S.ATTR_DAY, S.ATTR_NEXT_COMMIT_DAY,
S.ATTR_COMMIT_TIME, S.ATTR_SOURCE_URI
],
defaultValues: [
S.ATTR_DISCLOSURE: S.VAL_DISCLOSURE_COMPLETE,
]
)
// children
var elements: [[String: Any]] = []
parsing: while true {
let event = try _parseContext.parser.next()
switch event {
case .startElement(name: S.ELEM_TALK, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try TalkElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_START_ENTRY, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try StartEntryElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_ON_STAGE, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try OnStageElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_START_MIRROR, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try StartMirrorElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_OPEN_ROLE, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try OpenRoleElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_MURDERED, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try MurderedElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_START_ASSAULT, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try StartAssaultElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_SURVIVOR, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try SurvivorElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_COUNTING, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try CountingElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_SUDDEN_DEATH, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try SuddenDeathElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_NO_MURDER, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try NoMurderElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_WIN_VILLAGE, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try WinVillageElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_WIN_WOLF, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try WinWolfElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_WIN_HAMSTER, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try WinHamsterElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_PLAYER_LIST, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try PlayerListElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_PANIC, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try PanicElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_EXECUTION, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try ExecutionElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_VANISH, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try VanishElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_CHECKOUT, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try CheckoutElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_SHORT_MEMBER, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try ShortMemberElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_ASK_ENTRY, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try AskEntryElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_ASK_COMMIT, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try AskCommitElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_NO_COMMENT, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try NoCommentElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_STAY_EPILOGUE, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try StayEpilogueElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_GAME_OVER, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try GameOverElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_JUDGE, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try JudgeElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_GUARD, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try GuardElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_COUNTING2, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try Counting2ElementConverter(parseContext: _parseContext).convert(element))
case .startElement(name: S.ELEM_ASSAULT, namespaceURI: S.NS_ARCHIVE?, element: let element):
elements.append(try AssaultElementConverter(parseContext: _parseContext).convert(element))
case .startElement:
try skipElement()
case .endElement:
break parsing
default:
break
}
}
deepPeriodWrapper.object[K.ELEMENTS] = elements as Any?
// write to period[n].json
let deepPeriod = deepPeriodWrapper.object
let day = deepPeriod[K.DAY] as! Int
let periodFileName = String(format: PERIOD_JSON_FORMAT, day)
try writer.writeArchiveJSON(fileName: periodFileName, object: deepPeriod)
shallowPeriodWrapper.object[K.HREF] = periodFileName as Any?
return shallowPeriodWrapper.object
}
}
class TalkElementConverter: TextLinesConverter {
override init(parseContext: ParseContext) {
super.init(parseContext: parseContext)
_objectWrapper.object[K.TYPE] = K.VAL_TALK
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToTalk = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_TYPE: mapToTalk(K.TALK_TYPE, asString),
S.ATTR_AVATAR_ID: mapToTalk(K.AVATAR_ID, asString),
S.ATTR_XNAME: mapToTalk(K.XNAME, asString),
S.ATTR_TIME: mapToTalk(K.TIME, asString),
S.ATTR_FACE_ICON_URI: mapToTalk(K.FACE_ICON_URI, asString),
],
required: [
S.ATTR_TYPE, S.ATTR_AVATAR_ID, S.ATTR_XNAME, S.ATTR_TIME,
],
defaultValues: [:]
)
if let talkType = _objectWrapper.object[K.TALK_TYPE] as? String {
if talkType == K.VAL_PUBLIC {
_objectWrapper.object[K.PUBLIC_TALK_NO] = _parseContext.nextPublicTalkNo()
}
}
return try super.convert(element)
}
}
class StartEntryElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_START_ENTRY)
}
}
class OnStageElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_ON_STAGE)
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToEvent = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_ENTRY_NO: mapToEvent(K.ENTRY_NO, asInt),
S.ATTR_AVATAR_ID: mapToEvent(K.AVATAR_ID, asString),
],
required: [
S.ATTR_ENTRY_NO, S.ATTR_AVATAR_ID,
],
defaultValues: [:]
)
return try super.convert(element)
}
}
class StartMirrorElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_START_MIRROR)
}
}
class OpenRoleElementConverter: EventAnnounceConverter {
var _roleHeads: [String: Any] = [:]
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_OPEN_ROLE)
}
override func onBegin() throws {
try super.onBegin()
_roleHeads = [:]
}
override func onEvent(_ event: XMLEvent) throws {
switch event {
case .startElement(name: S.ELEM_ROLE_HEADS, namespaceURI: S.NS_ARCHIVE?, element: let element):
let (role, heads) = try RoleHeadsElementConverter(parseContext: _parseContext).convert(element)
_roleHeads[role] = heads
default:
try super.onEvent(event)
}
}
override func onEnd() throws {
_objectWrapper.object[K.ROLE_HEADS] = _roleHeads as Any?
try super.onEnd()
}
}
class RoleHeadsElementConverter: ElementConverter {
func convert(_ element: XMLElement) throws -> (role: String, heads: Any) {
guard let role = element.attributes[S.ATTR_ROLE] else { throw ArchiveToJSON.ConvertError.missingAttr(attribute:S.ATTR_ROLE) }
guard let headsStr = element.attributes[S.ATTR_HEADS] else { throw ArchiveToJSON.ConvertError.missingAttr(attribute:S.ATTR_HEADS) }
let heads = try asInt(headsStr)
try self.skipElement()
return (role: role, heads: heads)
}
}
class MurderedElementConverter: EventAnnounceConverter {
var _avatarId: [String] = []
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_MURDERED)
}
override func onBegin() throws {
try super.onBegin()
_avatarId = []
}
override func onEvent(_ event: XMLEvent) throws {
switch event {
case .startElement(name: S.ELEM_AVATAR_REF, namespaceURI: S.NS_ARCHIVE?, element: let element):
_avatarId.append(try AvatarRefElementConverter(parseContext: _parseContext).convert(element))
default:
try super.onEvent(event)
}
}
override func onEnd() throws {
_objectWrapper.object[K.AVATAR_ID] = _avatarId as Any?
try super.onEnd()
}
}
class StartAssaultElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_START_ASSAULT)
}
}
class SurvivorElementConverter: EventAnnounceConverter {
var _avatarId: [String] = []
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_SURVIVOR)
}
override func onBegin() throws {
try super.onBegin()
_avatarId = []
}
override func onEvent(_ event: XMLEvent) throws {
switch event {
case .startElement(name: S.ELEM_AVATAR_REF, namespaceURI: S.NS_ARCHIVE?, element: let element):
_avatarId.append(try AvatarRefElementConverter(parseContext: _parseContext).convert(element))
default:
try super.onEvent(event)
}
}
override func onEnd() throws {
_objectWrapper.object[K.AVATAR_ID] = _avatarId as Any?
try super.onEnd()
}
}
class AvatarRefElementConverter: ElementConverter {
func convert(_ element: XMLElement) throws -> String {
guard let avatarId = element.attributes[S.ATTR_AVATAR_ID] else { throw ArchiveToJSON.ConvertError.missingAttr(attribute:S.ATTR_AVATAR_ID) }
try skipElement()
return avatarId
}
}
class CountingElementConverter: EventAnnounceConverter {
var _votes: [String: Any] = [:]
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_COUNTING)
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToEvent = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_VICTIM: mapToEvent(K.VICTIM, asString),
],
required: [
],
defaultValues: [:]
)
return try super.convert(element)
}
override func onBegin() throws {
try super.onBegin()
_votes = [:]
}
override func onEvent(_ event: XMLEvent) throws {
switch event {
case .startElement(name: S.ELEM_VOTE, namespaceURI: S.NS_ARCHIVE?, element: let element):
let (byWhom, target) = try VoteElementConverter(parseContext: _parseContext).convert(element)
_votes[byWhom] = target
default:
try super.onEvent(event)
}
}
override func onEnd() throws {
_objectWrapper.object[K.VOTES] = _votes as Any?
try super.onEnd()
}
}
class VoteElementConverter: ElementConverter {
func convert(_ element: XMLElement) throws -> (byWhom: String, target: Any) {
guard let byWhom = element.attributes[S.ATTR_BY_WHOM] else { throw ArchiveToJSON.ConvertError.missingAttr(attribute:S.ATTR_BY_WHOM) }
guard let target = element.attributes[S.ATTR_TARGET] else { throw ArchiveToJSON.ConvertError.missingAttr(attribute:S.ATTR_TARGET) }
try self.skipElement()
return (byWhom: byWhom, target: target)
}
}
class SuddenDeathElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_SUDDEN_DEATH)
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToEvent = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_AVATAR_ID: mapToEvent(K.AVATAR_ID, asString),
],
required: [
S.ATTR_AVATAR_ID
],
defaultValues: [:]
)
return try super.convert(element)
}
}
class NoMurderElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_NO_MURDER)
}
}
class WinVillageElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_WIN_VILLAGE)
}
}
class WinWolfElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_WIN_WOLF)
}
}
class WinHamsterElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_WIN_HAMSTER)
}
}
class PlayerListElementConverter: EventAnnounceConverter {
var _playerInfos: [[String: Any]] = []
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_PLAYER_LIST)
}
override func onBegin() throws {
try super.onBegin()
_playerInfos = []
}
override func onEvent(_ event: XMLEvent) throws {
switch event {
case .startElement(name: S.ELEM_PLAYER_INFO, namespaceURI: S.NS_ARCHIVE?, element: let element):
_playerInfos.append(try PlayerInfoElementConverter(parseContext: _parseContext).convert(element))
default:
try super.onEvent(event)
}
}
override func onEnd() throws {
_objectWrapper.object[K.PLAYER_INFOS] = _playerInfos as Any?
try super.onEnd()
}
}
class PlayerInfoElementConverter: ElementConverter {
func convert(_ element: XMLElement) throws -> [String: Any] {
let playerInfoWrapper = ObjectWrapper(object: [:])
// attributes
let mapToPlayerInfo = map(toObject: playerInfoWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_PLAYER_ID: mapToPlayerInfo(K.PLAYER_ID, asString),
S.ATTR_AVATAR_ID: mapToPlayerInfo(K.AVATAR_ID, asString),
S.ATTR_SURVIVE: mapToPlayerInfo(K.SURVIVE, asBool),
S.ATTR_ROLE: mapToPlayerInfo(K.ROLE, asString),
S.ATTR_URI: mapToPlayerInfo(K.URI, asString),
],
required: [
S.ATTR_PLAYER_ID, S.ATTR_AVATAR_ID, S.ATTR_SURVIVE, S.ATTR_ROLE
],
defaultValues: [:]
)
// children
try skipElement()
return playerInfoWrapper.object
}
}
class PanicElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_PANIC)
}
}
class ExecutionElementConverter: EventAnnounceConverter {
var _nominateds: [String: Any] = [:]
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_EXECUTION)
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToEvent = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_VICTIM: mapToEvent(K.VICTIM, asString),
],
required: [
],
defaultValues: [:]
)
return try super.convert(element)
}
override func onBegin() throws {
try super.onBegin()
_nominateds = [:]
}
override func onEvent(_ event: XMLEvent) throws {
switch event {
case .startElement(name: S.ELEM_NOMINATED, namespaceURI: S.NS_ARCHIVE?, element: let element):
let (avatarId, count) = try NominatedElementConverter(parseContext: _parseContext).convert(element)
_nominateds[avatarId] = count
default:
try super.onEvent(event)
}
}
override func onEnd() throws {
_objectWrapper.object[K.NOMINATEDS] = _nominateds as Any?
try super.onEnd()
}
}
class NominatedElementConverter: ElementConverter {
func convert(_ element: XMLElement) throws -> (avatarId: String, count: Any) {
guard let avatarId = element.attributes[S.ATTR_AVATAR_ID] else { throw ArchiveToJSON.ConvertError.missingAttr(attribute:S.ATTR_AVATAR_ID) }
guard let countStr = element.attributes[S.ATTR_COUNT] else { throw ArchiveToJSON.ConvertError.missingAttr(attribute:S.ATTR_COUNT) }
let count = try asInt(countStr)
try self.skipElement()
return (avatarId: avatarId, count: count)
}
}
class VanishElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_VANISH)
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToEvent = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_AVATAR_ID: mapToEvent(K.AVATAR_ID, asString),
],
required: [
S.ATTR_AVATAR_ID
],
defaultValues: [:]
)
return try super.convert(element)
}
}
class CheckoutElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_CHECKOUT)
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToEvent = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_AVATAR_ID: mapToEvent(K.AVATAR_ID, asString),
],
required: [
S.ATTR_AVATAR_ID
],
defaultValues: [:]
)
return try super.convert(element)
}
}
class ShortMemberElementConverter: EventAnnounceConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_SHORT_MEMBER)
}
}
class AskEntryElementConverter: EventOrderConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_ASK_ENTRY)
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToEvent = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_COMMIT_TIME: mapToEvent(K.COMMIT_TIME, asString),
S.ATTR_MIN_MEMBERS: mapToEvent(K.MIN_MEMBERS, asInt),
S.ATTR_MAX_MEMBERS: mapToEvent(K.MAX_MEMBERS, asInt),
],
required: [
S.ATTR_COMMIT_TIME,
S.ATTR_MIN_MEMBERS,
S.ATTR_MAX_MEMBERS,
],
defaultValues: [:]
)
return try super.convert(element)
}
}
class AskCommitElementConverter: EventOrderConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_ASK_COMMIT)
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToEvent = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_LIMIT_VOTE: mapToEvent(K.LIMIT_VOTE, asString),
S.ATTR_LIMIT_SPECIAL: mapToEvent(K.LIMIT_SPECIAL, asString),
],
required: [
S.ATTR_LIMIT_VOTE,
S.ATTR_LIMIT_SPECIAL,
],
defaultValues: [:]
)
return try super.convert(element)
}
}
class NoCommentElementConverter: EventOrderConverter {
var _avatarId: [String] = []
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_NO_COMMENT)
}
override func onBegin() throws {
try super.onBegin()
_avatarId = []
}
override func onEvent(_ event: XMLEvent) throws {
switch event {
case .startElement(name: S.ELEM_AVATAR_REF, namespaceURI: S.NS_ARCHIVE?, element: let element):
_avatarId.append(try AvatarRefElementConverter(parseContext: _parseContext).convert(element))
default:
try super.onEvent(event)
}
}
override func onEnd() throws {
_objectWrapper.object[K.AVATAR_ID] = _avatarId as Any?
try super.onEnd()
}
}
class StayEpilogueElementConverter: EventOrderConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_STAY_EPILOGUE)
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToEvent = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_WINNER: mapToEvent(K.WINNER, asString),
S.ATTR_LIMIT_TIME: mapToEvent(K.LIMIT_TIME, asString),
],
required: [
S.ATTR_WINNER,
S.ATTR_LIMIT_TIME,
],
defaultValues: [:]
)
return try super.convert(element)
}
}
class GameOverElementConverter: EventOrderConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_GAME_OVER)
}
}
class JudgeElementConverter: EventExtraConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_JUDGE)
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToEvent = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_BY_WHOM: mapToEvent(K.BY_WHOM, asString),
S.ATTR_TARGET: mapToEvent(K.TARGET, asString),
],
required: [
S.ATTR_BY_WHOM,
S.ATTR_TARGET,
],
defaultValues: [:]
)
return try super.convert(element)
}
}
class GuardElementConverter: EventExtraConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_GUARD)
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToEvent = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_BY_WHOM: mapToEvent(K.BY_WHOM, asString),
S.ATTR_TARGET: mapToEvent(K.TARGET, asString),
],
required: [
S.ATTR_BY_WHOM,
S.ATTR_TARGET,
],
defaultValues: [:]
)
return try super.convert(element)
}
}
class Counting2ElementConverter: EventExtraConverter {
var _votes: [String: Any] = [:]
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_COUNTING2)
}
override func onBegin() throws {
try super.onBegin()
_votes = [:]
}
override func onEvent(_ event: XMLEvent) throws {
switch event {
case .startElement(name: S.ELEM_VOTE, namespaceURI: S.NS_ARCHIVE?, element: let element):
let (byWhom, target) = try VoteElementConverter(parseContext: _parseContext).convert(element)
_votes[byWhom] = target
default:
try super.onEvent(event)
}
}
override func onEnd() throws {
_objectWrapper.object[K.VOTES] = _votes as Any?
try super.onEnd()
}
}
class AssaultElementConverter: EventExtraConverter {
init(parseContext: ParseContext) {
super.init(parseContext: parseContext, type: K.VAL_ASSAULT)
}
override func convert(_ element: XMLElement) throws -> [String : Any] {
// attributes
let mapToEvent = map(toObject: _objectWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_BY_WHOM: mapToEvent(K.BY_WHOM, asString),
S.ATTR_TARGET: mapToEvent(K.TARGET, asString),
S.ATTR_XNAME: mapToEvent(K.XNAME, asString),
S.ATTR_TIME: mapToEvent(K.TIME, asString),
S.ATTR_FACE_ICON_URI: mapToEvent(K.FACE_ICON_URI, asString),
],
required: [
S.ATTR_BY_WHOM,
S.ATTR_TARGET,
S.ATTR_XNAME,
S.ATTR_TIME,
],
defaultValues: [:]
)
return try super.convert(element)
}
}
class EventAnnounceConverter: EventConverter {
}
class EventOrderConverter: EventConverter {
}
class EventExtraConverter: EventConverter {
}
class EventConverter: TextLinesConverter {
init(parseContext: ParseContext, type: String) {
super.init(parseContext: parseContext)
_objectWrapper.object[K.TYPE] = type
}
}
class TextLinesConverter: ElementConverter {
let _objectWrapper = ObjectWrapper(object: [:])
var _parsing = true
var _lines: [Any] = []
func convert(_ element: XMLElement) throws -> [String: Any] {
try onBegin()
while _parsing {
let event = try _parseContext.parser.next()
try onEvent(event)
}
try onEnd()
return _objectWrapper.object
}
func onBegin() throws {
_parsing = true
_lines = []
}
func onEvent(_ event: XMLEvent) throws {
switch event {
case .startElement(name: S.ELEM_LI, namespaceURI: S.NS_ARCHIVE?, element: let element):
_lines.append(try LiElementConverter(parseContext: _parseContext).convert(element))
case .startElement:
try self.skipElement()
case .endElement:
_parsing = false
default:
break
}
}
func onEnd() throws {
_objectWrapper.object[K.LINES] = _lines as Any?
}
}
class LiElementConverter: ElementConverter {
func convert(_ element: XMLElement) throws -> Any {
var contents: [Any] = []
parsing: while true {
let event = try _parseContext.parser.next()
switch event {
case .characters(let string):
contents.append(string)
case .startElement(name: S.ELEM_RAWDATA, namespaceURI: S.NS_ARCHIVE?, element: let element):
contents.append(try RawdataElementConverter(parseContext: _parseContext).convert(element))
case .startElement:
try skipElement()
case .endElement:
break parsing
default:
break
}
}
switch contents.count {
case 0:
return ""
case 1:
return contents[0]
default:
return contents
}
}
}
class RawdataElementConverter: ElementConverter {
func convert(_ element: XMLElement) throws -> Any {
let contentWrapper = ObjectWrapper(object: [:])
// attributes
let mapToContent = map(toObject: contentWrapper)
try convertAttribute(element,
mapping: [
S.ATTR_ENCODING: mapToContent(K.ENCODING, asString),
S.ATTR_HEX_BIN: mapToContent(K.HEX_BIN, asString),
],
required: [
S.ATTR_ENCODING, S.ATTR_HEX_BIN,
],
defaultValues: [:]
)
// children
parsing: while true {
let event = try _parseContext.parser.next()
switch event {
case .characters(let string):
contentWrapper.object[K.CHAR] = string
case .startElement:
try skipElement()
case .endElement:
break parsing
default:
break
}
}
return contentWrapper.object
}
}
}
// MARK: - Helper Class and Functions
class ObjectWrapper {
var object: [String: Any]
init(object: [String: Any]) {
self.object = object
}
}
private func convertAttribute(_ element: XMLElement, mapping converters: [String: (String) throws -> Void], required requiredAttrs: [String], defaultValues: [String: String]) throws {
var attributes = element.attributes
for (attrName, defaultValue) in defaultValues {
if !attributes.keys.contains(attrName) {
attributes[attrName] = defaultValue
}
}
var requiredAttrSet = Set<String>(requiredAttrs)
for (attrName, value) in attributes {
if let converter = converters[attrName] {
do {
try converter(value)
} catch CastError.invalidValue {
throw ArchiveToJSON.ConvertError.invalidAttrValue(attribute: attrName, value: value)
}
}
requiredAttrSet.remove(attrName)
}
if !requiredAttrSet.isEmpty {
throw ArchiveToJSON.ConvertError.missingAttr(attribute: requiredAttrSet.first!)
}
}
private func map(toObject wrapper: ObjectWrapper) -> (String, (@escaping (String) throws -> Any)) -> (String) throws -> Void {
return { (key, valueConverter) in
return { value in
wrapper.object[key] = try valueConverter(value)
}
}
}
private func map(toObjects wrappers: [ObjectWrapper]) -> (String, (@escaping (String) throws -> Any)) -> (String) throws -> Void {
return { (key, valueConverter) in
return { value in
let convertedValue = try valueConverter(value)
for wrapper in wrappers {
wrapper.object[key] = convertedValue
}
}
}
}
private enum CastError: Error {
case invalidValue
}
private func asString(_ value: String) -> Any {
return value as Any
}
private func asInt(_ value: String) throws -> Any {
guard let integer = Int(value) else { throw CastError.invalidValue }
return integer as Any
}
private func asBool(_ value: String) throws -> Any {
switch value {
case "0":
fallthrough
case "false":
return false as Any
case "1":
fallthrough
case "true":
return true as Any
default:
throw CastError.invalidValue
}
}
| mit | 3a14eb625e2e6dd5bebb62576109edbc | 39.006431 | 183 | 0.550213 | 4.632167 | false | false | false | false |
material-motion/material-motion-swift | src/timeline/CALayer+Timeline.swift | 2 | 2437 | /*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import IndefiniteObservable
import UIKit
extension CALayer {
private class TimelineInfo {
var timeline: Timeline?
var lastState: Timeline.Snapshot?
var subscription: Subscription?
}
private struct AssociatedKeys {
static var timelineInfo = "MDMTimelineInfo"
}
var timeline: Timeline? {
get { return (objc_getAssociatedObject(self, &AssociatedKeys.timelineInfo) as? TimelineInfo)?.timeline }
set {
let timelineInfo = (objc_getAssociatedObject(self, &AssociatedKeys.timelineInfo) as? TimelineInfo) ?? TimelineInfo()
timelineInfo.timeline = newValue
objc_setAssociatedObject(self, &AssociatedKeys.timelineInfo, timelineInfo, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
guard let timeline = timelineInfo.timeline else {
timelineInfo.subscription = nil
return
}
timelineInfo.subscription = timeline.subscribeToValue { [weak self] state in
guard let strongSelf = self else { return }
timelineInfo.lastState = state
if state.paused {
strongSelf.speed = 0
strongSelf.timeOffset = TimeInterval(state.beginTime + state.timeOffset)
} else if strongSelf.speed == 0 { // Unpause the layer.
// The following logic is the magic sauce required to reconnect a CALayer with the
// render server's clock.
let pausedTime = strongSelf.timeOffset
strongSelf.speed = 1
strongSelf.timeOffset = 0
strongSelf.beginTime = 0
let timeSincePause = strongSelf.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
strongSelf.beginTime = timeSincePause
}
}
}
}
var lastTimelineState: Timeline.Snapshot? {
return (objc_getAssociatedObject(self, &AssociatedKeys.timelineInfo) as? TimelineInfo)?.lastState
}
}
| apache-2.0 | 9aaedbe56070c14b27fe8d83630f4595 | 34.838235 | 122 | 0.71112 | 4.854582 | false | false | false | false |
StevenUpForever/FBSimulatorControl | fbsimctl/FBSimulatorControlKit/Sources/SimulatorRunners.swift | 2 | 8307 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import Foundation
import FBSimulatorControl
extension FileOutput {
func makeWriter() throws -> FBFileWriter {
switch self {
case .path(let path):
return try FBFileWriter(forFilePath: path, blocking: true)
case .standardOut:
return FBFileWriter(fileHandle: FileHandle.standardOutput, blocking: true)
}
}
}
struct SimulatorCreationRunner : Runner {
let context: iOSRunnerContext<CreationSpecification>
func run() -> CommandResult {
do {
for configuration in self.configurations {
self.context.reporter.reportSimpleBridge(.create, .started, configuration)
let simulator = try self.context.simulatorControl.set.createSimulator(with: configuration)
self.context.defaults.updateLastQuery(FBiOSTargetQuery.udids([simulator.udid]))
self.context.reporter.reportSimpleBridge(.create, .ended, simulator)
}
return .success(nil)
} catch let error as NSError {
return .failure("Failed to Create Simulator \(error.description)")
}
}
fileprivate var configurations: [FBSimulatorConfiguration] { get {
switch self.context.value {
case .allMissingDefaults:
return self.context.simulatorControl.set.configurationsForAbsentDefaultSimulators()
case .individual(let configuration):
return [configuration.simulatorConfiguration]
}
}}
}
struct SimulatorActionRunner : Runner {
let context: iOSRunnerContext<(Action, FBSimulator)>
func run() -> CommandResult {
let (action, simulator) = self.context.value
let reporter = SimulatorReporter(simulator: simulator, format: self.context.format, reporter: self.context.reporter)
defer {
simulator.userEventSink = nil
}
let context = self.context.replace((action, simulator, reporter))
return SimulatorActionRunner.makeRunner(context).run()
}
static func makeRunner(_ context: iOSRunnerContext<(Action, FBSimulator, SimulatorReporter)>) -> Runner {
let (action, simulator, reporter) = context.value
let covariantTuple: (Action, FBiOSTarget, iOSReporter) = (action, simulator, reporter)
if let runner = iOSActionProvider(context: context.replace(covariantTuple)).makeRunner() {
return runner
}
switch action {
case .approve(let bundleIDs):
return iOSTargetRunner.simple(reporter, .approve, StringsSubject(bundleIDs)) {
try simulator.authorizeLocationSettings(bundleIDs)
}
case .clearKeychain(let maybeBundleID):
return iOSTargetRunner.simple(reporter, .clearKeychain, ControlCoreSubject(simulator)) {
if let bundleID = maybeBundleID {
try simulator.killApplication(withBundleID: bundleID)
}
try simulator.clearKeychain()
}
case .delete:
return iOSTargetRunner.simple(reporter, .delete, ControlCoreSubject(simulator)) {
try simulator.set!.delete(simulator)
}
case .erase:
return iOSTargetRunner.simple(reporter, .erase, ControlCoreSubject(simulator)) {
try simulator.erase()
}
case .focus:
return iOSTargetRunner.simple(reporter, .focus, ControlCoreSubject(simulator)) {
try simulator.focus()
}
case .keyboardOverride:
return iOSTargetRunner.simple(reporter, .keyboardOverride, ControlCoreSubject(simulator)) {
try simulator.setupKeyboard()
}
case .open(let url):
return iOSTargetRunner.simple(reporter, .open, url.bridgedAbsoluteString) {
try simulator.open(url)
}
case .relaunch(let appLaunch):
return iOSTargetRunner.simple(reporter, .relaunch, ControlCoreSubject(appLaunch)) {
try simulator.launchOrRelaunchApplication(appLaunch)
}
case .search(let search):
return SearchRunner(reporter, search)
case .serviceInfo(let identifier):
return ServiceInfoRunner(reporter: reporter, identifier: identifier)
case .shutdown:
return iOSTargetRunner.simple(reporter, .shutdown, ControlCoreSubject(simulator)) {
try simulator.set!.kill(simulator)
}
case .tap(let x, let y):
return iOSTargetRunner.simple(reporter, .tap, ControlCoreSubject(simulator)) {
let event = FBSimulatorHIDEvent.tapAt(x: x, y: y)
try event.perform(on: simulator.connect().connectToHID())
}
case .setLocation(let latitude, let longitude):
return iOSTargetRunner.simple(reporter, .setLocation, ControlCoreSubject(simulator)) {
try simulator.setLocation(latitude, longitude: longitude)
}
case .upload(let diagnostics):
return UploadRunner(reporter, diagnostics)
case .watchdogOverride(let bundleIDs, let timeout):
return iOSTargetRunner.simple(reporter, .watchdogOverride, StringsSubject(bundleIDs)) {
try simulator.overrideWatchDogTimer(forApplications: bundleIDs, withTimeout: timeout)
}
default:
return CommandResultRunner.unimplementedActionRunner(action, target: simulator, format: context.format)
}
}
}
private struct SearchRunner : Runner {
let reporter: SimulatorReporter
let search: FBBatchLogSearch
init(_ reporter: SimulatorReporter, _ search: FBBatchLogSearch) {
self.reporter = reporter
self.search = search
}
func run() -> CommandResult {
let simulator = self.reporter.simulator
let diagnostics = simulator.diagnostics.allDiagnostics()
let results = search.search(diagnostics)
self.reporter.report(.search, .discrete, ControlCoreSubject(results))
return .success(nil)
}
}
private struct ServiceInfoRunner : Runner {
let reporter: SimulatorReporter
let identifier: String
func run() -> CommandResult {
var pid: pid_t = 0
guard let _ = try? self.reporter.simulator.launchctl.serviceName(forBundleID: self.identifier, processIdentifierOut: &pid) else {
return .failure("Could not get service for name \(identifier)")
}
guard let processInfo = self.reporter.simulator.processFetcher.processFetcher.processInfo(for: pid) else {
return .failure("Could not get process info for pid \(pid)")
}
return .success(SimpleSubject(.serviceInfo, .discrete, ControlCoreSubject(processInfo)))
}
}
private struct UploadRunner : Runner {
let reporter: SimulatorReporter
let diagnostics: [FBDiagnostic]
init(_ reporter: SimulatorReporter, _ diagnostics: [FBDiagnostic]) {
self.reporter = reporter
self.diagnostics = diagnostics
}
func run() -> CommandResult {
var diagnosticLocations: [(FBDiagnostic, String)] = []
for diagnostic in diagnostics {
guard let localPath = diagnostic.asPath else {
return .failure("Could not get a local path for diagnostic \(diagnostic)")
}
diagnosticLocations.append((diagnostic, localPath))
}
let mediaPredicate = NSPredicate.forMediaPaths()
let media = diagnosticLocations.filter { (_, location) in
mediaPredicate.evaluate(with: location)
}
if media.count > 0 {
let paths = media.map { $0.1 }
let runner = iOSTargetRunner.simple(reporter, .upload, StringsSubject(paths)) {
try FBUploadMediaStrategy(simulator: self.reporter.simulator).uploadMedia(paths)
}
let result = runner.run()
switch result.outcome {
case .failure: return result
default: break
}
}
let basePath = self.reporter.simulator.auxillaryDirectory
let arbitraryPredicate = NSCompoundPredicate(notPredicateWithSubpredicate: mediaPredicate)
let arbitrary = diagnosticLocations.filter{ arbitraryPredicate.evaluate(with: $0.1) }
for (sourceDiagnostic, sourcePath) in arbitrary {
guard let destinationPath = try? sourceDiagnostic.writeOut(toDirectory: basePath as String) else {
return CommandResult.failure("Could not write out diagnostic \(sourcePath) to path")
}
let destinationDiagnostic = FBDiagnosticBuilder().updatePath(destinationPath).build()
self.reporter.report(.upload, .discrete, ControlCoreSubject(destinationDiagnostic))
}
return .success(nil)
}
}
| bsd-3-clause | ba63895e5ad26f02ce23508f607714e5 | 37.105505 | 133 | 0.713254 | 4.451768 | false | false | false | false |
jhihguan/JSON2Realm | JSON2RealmTests/GlossRealm.swift | 1 | 1566 | //
// GlossRealm.swift
// JSON2Realm
//
// Created by Wane Wang on 2016/1/4.
// Copyright © 2016年 Wane Wang. All rights reserved.
//
import Foundation
import Gloss
import RealmSwift
final class GlossClass: BasicClass, Glossy {
convenience required init?(json: JSON) {
self.init()
guard let name: String = "name" <~~ json,
let birthday: String = "birthday" <~~ json,
let age: Int = "age" <~~ json
else { return nil }
self.name = name
self.birthday = birthday
self.age = age
}
func toJSON() -> JSON? {
return jsonify([
"name" ~~> self.name,
"birthday" ~~> self.birthday,
"age" ~~> self.age
])
}
}
final class GlossOptionalClass: BasicOptionalClass, Glossy {
convenience required init?(json: JSON) {
self.init()
guard let value: Int = "value" <~~ json
else { return nil }
self.value = value
self.note = "note" <~~ json
self.distance.value = "distance" <~~ json
}
func toJSON() -> JSON? {
return jsonify([
"value" ~~> self.value,
Encoder.encodeStringNull("note")(self.note),
"distance" ~~> self.distance.value
])
}
}
extension Encoder {
static func encodeStringNull(key: String) -> String? -> JSON {
return {
string in
if let string = string {
return [key : string]
}
return [key : NSNull()]
}
}
} | mit | 018d51b6ca4a9fbacd850900571090ad | 23.825397 | 66 | 0.520154 | 4.179144 | false | false | false | false |