repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
juliangrosshauser/ToDo
|
ToDo/Sources/Classes/View Controllers/ListTableController.swift
|
1
|
3841
|
//
// ListTableController.swift
// ToDo
//
// Created by Julian Grosshauser on 21/07/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
import UIKit
import RealmSwift
import ReactiveCocoa
class ListTableController: BaseTableController {
//MARK: Properties
private let listViewModel = ListViewModel()
weak var delegate: ListControllerDelegate?
private let itemCount: MutableProperty<Int> = MutableProperty(0)
//MARK: Initialization
init() {
super.init(itemType: .List, viewModel: listViewModel)
itemCount <~ listViewModel.itemCount
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
//MARK: UITableViewDataSource
extension ListTableController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listViewModel.itemCount.value
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(String(TableViewCell)) as! TableViewCell
cell.configure(listViewModel.item(indexPath.row))
cell.accessoryType = .DisclosureIndicator
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = Color.lightBlue.colorWithAlphaComponent(0.3)
cell.selectedBackgroundView = selectedBackgroundView
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! TableViewCell
listViewModel.deleteItem.apply(cell.id).start()
}
}
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
listViewModel.moveItem.apply((sourceIndexPath.row, destinationIndexPath.row)).start()
}
}
//MARK: UITableViewDelegate
extension ListTableController {
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.listChanged(listViewModel.item(indexPath.row))
guard let splitViewController = splitViewController, detailViewController = delegate as? UIViewController else { return }
if splitViewController.collapsed {
splitViewController.showDetailViewController(detailViewController, sender: nil)
} else {
guard splitViewController.displayMode == .PrimaryOverlay else { return }
UIView.animateWithDuration(0.3) { splitViewController.preferredDisplayMode = .PrimaryHidden }
splitViewController.preferredDisplayMode = .Automatic
}
}
}
//MARK: UISplitViewControllerDelegate
extension ListTableController: UISplitViewControllerDelegate {
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// if detail view controller contains a `TodoTableController` and it's `list` property isn't set, show master view controller first, because the `TodoTableController` doesn't yet know what todos to show
if let navigationController = secondaryViewController as? UINavigationController, todoTableController = navigationController.topViewController as? TodoTableController where todoTableController.list.value == nil {
return true
}
return false
}
}
|
mit
|
ec56ebcab0e1b7df49eefc3c9e45a135
| 37.019802 | 224 | 0.74349 | 5.944272 | false | false | false | false |
RunningCharles/Arithmetic
|
src/20reversedPrintLinkedlist.swift
|
1
|
707
|
#!/usr/bin/swift
class LinkedNode {
var value: Int!
var next: LinkedNode?
init(_ value: Int) {
self.value = value
}
}
func insertList(_ head: LinkedNode, _ value: Int) {
var last = head
while last.next != nil {
last = last.next!
}
last.next = LinkedNode(value);
}
func printLinkedList(_ head: LinkedNode?) {
guard let head = head else { return }
printLinkedList(head.next);
print(head.value)
}
let head = LinkedNode(10)
insertList(head, 24);
insertList(head, 231);
insertList(head, 34);
insertList(head, 543);
insertList(head, 6);
insertList(head, 72);
insertList(head, 3);
insertList(head, 5);
insertList(head, 6);
printLinkedList(head)
|
bsd-3-clause
|
82382eba012ef8d7cc4679a9d72aa9e1
| 18.638889 | 51 | 0.64215 | 3.273148 | false | false | false | false |
rshuston/ClosestPointsWorkshop
|
ClosestPoints/ClosestPoints/ViewControllerLogic.swift
|
1
|
9792
|
//
// ViewControllerLogic.swift
// ClosestPoints
//
// Created by Robert Huston on 12/7/16.
// Copyright © 2016 Pinpoint Dynamics. All rights reserved.
//
import Cocoa
// We use a ViewControllerLogic as a companion to ViewController so that we can more
// easily isolate the logic that can be test-driven from the standard MVC logic that
// adheres to the Cocoa design patterns.
//
// (Eewww! A comment! How untrendy! The horror of it all! Whaah! What can it mean?)
class ViewControllerLogic: NSObject {
let minNumberOfPoints = 2
let maxNumberOfPoints = 100000
var pointCollection: PointCollection! = PointCollection()
var definitionManager: DefinitionManager! = DefinitionManager()
var controlManager: ControlManager! = ControlManager()
var solutionEngine: SolutionEngine! = SolutionEngine()
var hostViewController: ViewController!
var lastSolutionTime_ms: Float = 0.0
var startSolutionTime: CFTimeInterval = 0.0
var endSolutionTime: CFTimeInterval = 0.0
init(hostViewController: ViewController) {
self.hostViewController = hostViewController
}
func viewDidLoad() {
definitionManager.numberOfPoints = 3
definitionManager.pointDistribution = DefinitionManager.PointDistribution.Uniform
controlManager.solutionType = ControlManager.SolutionType.PermutationSearch
controlManager.solverOption = ControlManager.SolverOption.OneShot
hostViewController.setPlotViewPointCollectionDataSource(dataSource: pointCollection)
hostViewController.setNumberOfPoints(numberOfPoints: definitionManager.numberOfPoints)
hostViewController.updateSolutionTime(time_ms: lastSolutionTime_ms)
generatePoints()
activateGenerateButton()
activateControlButtonIfCanSolve()
configureControlAndProgressForSolvingState()
}
func updateNumberOfPointsBox() {
var value = hostViewController.getNumberOfPoints()
if value < minNumberOfPoints {
value = minNumberOfPoints
}
if value > maxNumberOfPoints {
value = maxNumberOfPoints
}
definitionManager.numberOfPoints = value
hostViewController.setNumberOfPoints(numberOfPoints: value)
}
internal func deactivateGenerateButton() {
hostViewController.setGenerateButtonEnableState(enabled: false)
}
internal func activateGenerateButton() {
hostViewController.setGenerateButtonEnableState(enabled: true)
}
internal func deactivateControlButton() {
hostViewController.setControlButtonEnableState(enabled: false)
}
internal func activateControlButtonIfCanSolve() {
hostViewController.setControlButtonEnableState(enabled: pointCollection.points.count >= 2)
}
internal func configureControlAndProgressForSolvingState() {
hostViewController.setControlButtonTitle(title: solutionEngine.solving ? "Cancel" : "Solve")
hostViewController.setProgressIndicatorState(enabled: solutionEngine.solving)
}
internal func requestPlotViewRedraw() {
hostViewController.requestPlotViewRedraw()
}
func generatePoints() {
deactivateGenerateButton()
deactivateControlButton()
pointCollection.clear()
let plotSize = hostViewController.getPlotViewSize()
let pointRadius = hostViewController.getPlotViewPointRadius()
switch definitionManager.pointDistribution {
case DefinitionManager.PointDistribution.Uniform:
pointCollection.generateUniformRandomPoints(numberOfPoints: definitionManager.numberOfPoints,
maxX: plotSize.width,
maxY: plotSize.height,
margin: pointRadius)
break
case DefinitionManager.PointDistribution.Clustered:
pointCollection.generateClusteredRandomPoints(numberOfPoints: definitionManager.numberOfPoints,
maxX: plotSize.width,
maxY: plotSize.height,
margin: pointRadius)
break
}
requestPlotViewRedraw()
activateGenerateButton()
activateControlButtonIfCanSolve()
requestLiveSolutionIfConfigured()
}
func findClosestPoints() {
solutionEngine.solving = true
var solver: Solver?
switch controlManager.solutionType {
case ControlManager.SolutionType.PermutationSearch:
solver = solutionEngine.permutationSolver
break
case ControlManager.SolutionType.CombinationSearch:
solver = solutionEngine.combinationSolver
break
case ControlManager.SolutionType.PlaneSweep:
solver = solutionEngine.planeSweepSolver
break
case ControlManager.SolutionType.DivideAndConquer_3:
solutionEngine.divideAndConquerSolver.maxSimpleRegionSize = 3
solver = solutionEngine.divideAndConquerSolver
break
case ControlManager.SolutionType.DivideAndConquer_5:
solutionEngine.divideAndConquerSolver.maxSimpleRegionSize = 5
solver = solutionEngine.divideAndConquerSolver
break
case ControlManager.SolutionType.DivideAndConquer_7:
solutionEngine.divideAndConquerSolver.maxSimpleRegionSize = 7
solver = solutionEngine.divideAndConquerSolver
break
}
if solver != nil {
deactivateGenerateButton()
pointCollection.clearAllDataExceptForPoints()
configureControlAndProgressForSolvingState()
let monitor: ((NSRect?, (Point, Point)?, (Point, Point)?) -> Bool)?
switch controlManager.solverOption {
case ControlManager.SolverOption.OneShot:
monitor = monitorCancelOnly
break
case ControlManager.SolverOption.SlowAnimation:
monitor = monitorWaitCancelSlow
break
case ControlManager.SolverOption.FastAnimation:
monitor = monitorWaitCancelFast
break
case ControlManager.SolverOption.Live:
monitor = monitorCancelOnly
break
}
startSolutionTime = 0.0
endSolutionTime = 0.0
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async {
self.startSolutionTime = CFAbsoluteTimeGetCurrent()
solver!.findClosestPoints(points: self.pointCollection.points,
monitor: monitor,
completion: self.completion)
}
} else {
solutionEngine.solving = false
}
}
internal func monitorCancelOnly(checkRect: NSRect?, checkPoints: (Point, Point)?, closestPointsSoFar: (Point, Point)?) -> Bool {
return solutionEngine.solving
}
internal func monitorWaitCancelSlow(checkRect: NSRect?, checkPoints: (Point, Point)?, closestPointsSoFar: (Point, Point)?) -> Bool {
pointCollection.closestPoints = closestPointsSoFar
pointCollection.closestPointsColor = NSColor.blue
pointCollection.checkPoints = checkPoints
pointCollection.checkPointsColor = NSColor.red
pointCollection.searchRect = checkRect
DispatchQueue.main.async {
self.requestPlotViewRedraw()
}
usleep(25000)
return solutionEngine.solving
}
internal func monitorWaitCancelFast(checkRect: NSRect?, checkPoints: (Point, Point)?, closestPointsSoFar: (Point, Point)?) -> Bool {
pointCollection.closestPoints = closestPointsSoFar
pointCollection.closestPointsColor = NSColor.blue
pointCollection.checkPoints = checkPoints
pointCollection.checkPointsColor = NSColor.red
pointCollection.searchRect = checkRect
DispatchQueue.main.async {
self.requestPlotViewRedraw()
}
usleep(1000)
return solutionEngine.solving
}
internal func completion(closestPoints: (Point, Point)?) {
endSolutionTime = CFAbsoluteTimeGetCurrent()
lastSolutionTime_ms = Float(endSolutionTime - startSolutionTime) * 1000.0
if solutionEngine.solving {
pointCollection.closestPoints = closestPoints
pointCollection.closestPointsColor = NSColor.blue
pointCollection.checkPoints = nil
pointCollection.checkPointsColor = nil
pointCollection.searchRect = nil
}
DispatchQueue.main.async {
self.requestPlotViewRedraw()
self.solutionEngine.solving = false
self.configureControlAndProgressForSolvingState()
self.activateGenerateButton()
self.activateControlButtonIfCanSolve()
self.hostViewController.updateSolutionTime(time_ms: self.lastSolutionTime_ms)
}
}
func isFindingClosestPoints() -> Bool {
return solutionEngine.solving
}
func requestLiveSolutionIfConfigured() {
switch controlManager.solverOption {
case ControlManager.SolverOption.OneShot:
break
case ControlManager.SolverOption.SlowAnimation:
break
case ControlManager.SolverOption.FastAnimation:
break
case ControlManager.SolverOption.Live:
findClosestPoints()
break
}
}
func updatePointDataSource() {
pointCollection.clearAllDataExceptForPoints()
}
}
|
mit
|
ca138814eaba40b3e1870a86ddab0715
| 36.51341 | 136 | 0.658768 | 5.324089 | false | false | false | false |
pixelmaid/DynamicBrushes
|
swift/Palette-Knife/models/behavior/BehaviorManager.swift
|
1
|
32767
|
//
// BehaviorManager.swift
// PaletteKnife
//
// Created by JENNIFER MARY JACOBS on 5/25/16.
// Copyright © 2016 pixelmaid. All rights reserved.
//
import Foundation
import SwiftyJSON
enum BehaviorError: Error {
case duplicateName
case behaviorDoesNotExist
case mappingDoesNotExist;
case transitionDoesNotExist;
case requestDoesNotExist;
}
class BehaviorManager{
static var behaviors = [String:BehaviorDefinition]()
var canvas:Canvas
init(canvas:Canvas){
self.canvas = canvas;
}
static func getBehaviorById(id:String)->BehaviorDefinition?{
if(BehaviorManager.behaviors[id] != nil){
return BehaviorManager.behaviors[id]
}
return nil
}
func refreshAllBehaviors(){
for (_,behavior) in BehaviorManager.behaviors{
behavior.createBehavior(canvas:canvas)
}
}
func loadBehavior(json:JSON){
self.loadBehaviorsFromJSON(json: json, rewriteAll: true)
}
func loadBehaviorsFromJSON(json:JSON,rewriteAll:Bool){
if(rewriteAll){
for(_,value) in BehaviorManager.behaviors{
value.clearBehavior();
}
BehaviorManager.behaviors.removeAll();
}
for(key,value) in json{
if let val = BehaviorManager.behaviors[key] {
val.clearBehavior();
}
let behavior = BehaviorDefinition(id:key,name:value["name"].stringValue);
behavior.parseJSON(json: value)
behavior.createBehavior(canvas:canvas);
BehaviorManager.behaviors[key] = behavior;
}
}
func handleAuthoringRequest(authoring_data:JSON) throws->JSON{
let data = authoring_data["data"] as JSON;
let type = data["type"].stringValue;
var resultJSON:JSON = [:]
resultJSON["type"] = JSON("authoring_response");
resultJSON["authoring_type"] = JSON(type);
switch(type){
case "set_behavior_active":
let behaviorId = data["behaviorId"].stringValue;
let behavior = BehaviorManager.behaviors[behaviorId]!;
let active_status = data["active_status"].boolValue;
behavior.setActiveStatus(status:active_status);
if(active_status){
behavior.setAutoSpawnNum(num: 1)
}
else{
behavior.setAutoSpawnNum(num: 0)
}
BehaviorManager.behaviors[behaviorId]!.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON;
case "refresh_behavior":
let behaviorId = data["behaviorId"].stringValue;
BehaviorManager.behaviors[behaviorId]!.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON;
case "request_behavior_json":
let behaviorId = data["behaviorId"].stringValue;
let behavior = BehaviorManager.behaviors[behaviorId]!;
let behaviorJSON:JSON = behavior.toJSON();
resultJSON["result"] = "success";
resultJSON["data"] = behaviorJSON
return resultJSON;
case "behavior_added":
let name = data["name"].stringValue;
let id = data["id"].stringValue;
let data = data["data"]
//let behavior = BehaviorDefinition(id:data["id"].stringValue, name: data["name"].stringValue);
let behavior = BehaviorDefinition(id:id,name:name);
behavior.parseJSON(json: data)
if(BehaviorManager.behaviors[id] != nil){
throw BehaviorError.duplicateName;
}
else{
BehaviorManager.behaviors[id] = behavior;
behavior.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON;
}
//request to check dependency
case "delete_behavior_request":
let behaviorId = data["behaviorId"].stringValue;
let behavior = BehaviorManager.behaviors[behaviorId]!;
let dependents = self.checkDependency(behaviorId:behavior.id);
if(dependents.count == 0){
resultJSON["result"] = "success";
}
else{
resultJSON["result"] = "check";
resultJSON["data"] = ["dependents":JSON(dependents)]
}
return resultJSON;
//hard delete despite any dependencies
case "hard_delete_behavior":
let behaviorId = data["behaviorId"].stringValue;
let behavior = BehaviorManager.behaviors[behaviorId]!;
BehaviorManager.behaviors.removeValue(forKey: behaviorId)
behavior.clearBehavior();
resultJSON["result"] = "success"
return resultJSON
case "state_added":
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.parseStateJSON(data:data);
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON;
case "state_moved":
let behaviorId = data["behaviorId"].stringValue;
let stateId = data["stateId"].stringValue;
let x = data["x"].floatValue
let y = data["y"].floatValue
BehaviorManager.behaviors[behaviorId]!.setStatePosition(stateId:stateId,x:x,y:y);
resultJSON["result"] = "success";
return resultJSON;
case "state_removed":
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.removeState(stateId: data["stateId"].stringValue);
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON;
case "transition_added","transition_event_added", "transition_event_condition_changed":
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.parseTransitionJSON(data:data)
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON;
case "transition_removed":
do{
try BehaviorManager.behaviors[data["behaviorId"].stringValue]!.removeTransition(id: data["transitionId"].stringValue);
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON; }
catch{
print("transition id does not exist, cannot remove");
resultJSON["result"] = "failure";
return resultJSON;
}
case "transition_event_removed" :
do{
try BehaviorManager.behaviors[data["behaviorId"].stringValue]!.setTransitionToDefaultEvent(transitionId: data["transitionId"].stringValue)
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.createBehavior(canvas:canvas);
resultJSON["result"] = "success";
return resultJSON; }
catch{
resultJSON["result"] = "failure";
return resultJSON; }
case "method_added","method_argument_changed":
let behaviorId = data["behaviorId"].stringValue
let methodJSON = BehaviorManager.behaviors[behaviorId]!.parseMethodJSON(data: data)
BehaviorManager.behaviors[behaviorId]!.createBehavior(canvas:canvas);
let targetMethod = data["targetMethod"].stringValue
if(targetMethod == "spawn"){
var behavior_list = methodJSON["argumentList"]
for (key,value) in BehaviorManager.behaviors{
if key != behaviorId {
behavior_list[key] = JSON(value.name);
}
}
}
resultJSON["result"] = "success";
resultJSON["data"] = methodJSON;
return resultJSON;
case "method_removed":
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.removeMethod(methodId: data["methodId"].stringValue)
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.createBehavior(canvas:canvas);
resultJSON["result"] = "success";
return resultJSON;
case "mapping_added":
let behaviorId = data["behaviorId"].stringValue;
BehaviorManager.behaviors[behaviorId]!.parseMappingJSON(data:data)
BehaviorManager.behaviors[behaviorId]!.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON;
case "mapping_updated":
let behaviorId = data["behaviorId"].stringValue;
BehaviorManager.behaviors[behaviorId]!.parseMappingJSON(data: data)
BehaviorManager.behaviors[behaviorId]!.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON;
case "expression_text_modified":
let behaviorId = data["behaviorId"].stringValue;
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.parseExpressionJSON(data:data)
BehaviorManager.behaviors[behaviorId]!.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON;
case "mapping_relative_removed":
do{
try BehaviorManager.behaviors[data["behaviorId"].stringValue]!.removeMapping(id: data["mappingId"].stringValue);
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON;
}
catch{
resultJSON["result"] = "failure";
return resultJSON;
}
case "mapping_reference_removed":
let behaviorId = data["behaviorId"].stringValue;
let mappingId = data["mappingId"].stringValue;
let containsActive = data["containsActive"].boolValue;
if(containsActive == false){
BehaviorManager.behaviors[behaviorId]!.setMappingPassive(mappingId:mappingId);
}
BehaviorManager.behaviors[behaviorId]!.parseExpressionJSON(data:data)
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON;
case "generator_added":
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.parseGeneratorJSON(data:data)
BehaviorManager.behaviors[data["behaviorId"].stringValue]!.createBehavior(canvas:canvas)
resultJSON["result"] = "success";
return resultJSON;
default:
break
}
resultJSON["result"] = "failure";
return resultJSON;
}
//checks to see if other behaviors reference the target behavior
func checkDependency(behaviorId:String)->[String:String]{
var dependentBehaviors = [String:String]()
for (_,value) in BehaviorManager.behaviors {
if(value.id != behaviorId){
let dependent = value.checkDependency(behaviorId: behaviorId);
if(dependent){
dependentBehaviors[value.id] = value.name;
}
}
}
return dependentBehaviors;
}
func getAllBehaviorJSON()->JSON {
var behaviorJSON = [JSON]()
for (_, behavior) in BehaviorManager.behaviors {
let data:JSON = behavior.toJSON();
behaviorJSON.append(data);
}
return JSON(behaviorJSON);
}
func getBehaviorJSON(name:String) throws->String{
if(BehaviorManager.behaviors[name] != nil){
var behaviorJSON:JSON = BehaviorManager.behaviors[name]!.toJSON();
return behaviorJSON.stringValue;
}
else{
throw BehaviorError.behaviorDoesNotExist;
}
}
func defaultSetup(name:String) throws->BehaviorDefinition {
let b = BehaviorDefinition(id:NSUUID().uuidString,name: name)
//TODO: add check for if name is a duplicate
if(BehaviorManager.behaviors[name] != nil){
throw BehaviorError.duplicateName;
}
else{
BehaviorManager.behaviors[name] = b;
b.addState(stateId: NSUUID().uuidString,stateName:"start", stateX: 20.0, stateY:150.0)
b.addState(stateId: NSUUID().uuidString,stateName:"default", stateX: 1000.0, stateY: 150.0)
b.addTransition(transitionId: NSUUID().uuidString, name: "setup", eventEmitter: nil, parentFlag: false, event: "STATE_COMPLETE", fromStateId: "start", toStateId:"default", condition: nil, displayName: "state complete")
return b;
}
}
func initSpawnTemplate(name:String)->BehaviorDefinition?{
do {
let b = try defaultSetup(name: name);
b.addMethod(targetTransition: "setup", methodId:NSUUID().uuidString, targetMethod: "newStroke", arguments:nil)
b.addMethod(targetTransition: "setup", methodId:NSUUID().uuidString, targetMethod: "setOrigin", arguments: ["parent"])
b.addMethod(targetTransition: "setup", methodId: NSUUID().uuidString, targetMethod: "startInterval", arguments: nil);
return b;
}
catch {
return nil;
}
}
func initStandardTemplate(name:String) ->BehaviorDefinition?{
do {
let b = try defaultSetup(name: name);
b.addTransition(transitionId: NSUUID().uuidString, name:"stylusDownTransition", eventEmitter: stylus, parentFlag:false, event: "STYLUS_DOWN", fromStateId: b.getStateByName(name: "default")!, toStateId: b.getStateByName(name: "default")!, condition:nil, displayName: "foo")
b.addTransition(transitionId: NSUUID().uuidString, name:"stylusUpTransition", eventEmitter: stylus, parentFlag:false, event: "STYLUS_UP", fromStateId: b.getStateByName(name: "default")!, toStateId: b.getStateByName(name: "default")!, condition:nil, displayName: "foo")
b.addMethod(targetTransition: "stylusDownTransition", methodId:NSUUID().uuidString, targetMethod: "setOrigin", arguments: [stylus.position])
b.addMethod(targetTransition: "stylusDownTransition", methodId:NSUUID().uuidString, targetMethod: "newStroke", arguments: nil)
b.addMethod(targetTransition: "stylusDownTransition", methodId:NSUUID().uuidString, targetMethod: "startInterval", arguments: nil)
b.addMethod(targetTransition: "stylusUpTransition", methodId:NSUUID().uuidString, targetMethod: "stopInterval", arguments: nil)
b.addMapping(id: NSUUID().uuidString, referenceProperty:stylus, referenceNames: ["dx"], relativePropertyName: "dx", stateId: "default", type:"active",relativePropertyItemName:"foo")
b.addMapping(id: NSUUID().uuidString, referenceProperty:stylus, referenceNames: ["dy"], relativePropertyName: "dy", stateId: "default", type:"active",relativePropertyItemName:"foo")
// b.addMapping(NSUUID().UUIDString, referenceProperty:stylus, referenceNames: ["force"], relativePropertyName: "weight", stateId: "default")
return b;
}
catch {
return nil;
}
}
//---------------------------------- HARDCODED BEHAVIORS ---------------------------------- //
func initBakeBehavior()->BehaviorDefinition?{
let b1 = initStandardTemplate(name: "b1");
b1!.addTransition(transitionId: NSUUID().uuidString, name:"stylusUpT", eventEmitter: stylus, parentFlag:false, event: "STYLUS_UP", fromStateId: b1!.getStateByName(name: "default")!, toStateId: b1!.getStateByName(name: "default")!, condition:nil, displayName: "foo");
b1!.addMethod(targetTransition: "stylusUpT", methodId:NSUUID().uuidString, targetMethod: "bake", arguments: nil)
//b1.addMethod("stylusUpT", methodId:NSUUID().UUIDString, targetMethod: "liftUp", arguments: nil)
b1!.addMethod(targetTransition: "stylusDownTransition",methodId:NSUUID().uuidString,targetMethod: "jogTo", arguments: [stylus.position])
return b1;
}
func initDripBehavior()->BehaviorDefinition?{
let dripBehavior = initSpawnTemplate(name: "dripBehavior");
dripBehavior!.addEaseGenerator(name: "weightGenerator", a:10,b:15,k:0.36);
// dripBehavior!.addExpression("weightExpression", emitter1: nil, operand1Names:["weight"], emitter2: nil, operand2Names: ["weightGenerator"], type: "add")
dripBehavior!.addRandomGenerator(name: "randomTimeGenerator", min:50, max: 100)
dripBehavior!.addCondition(name: "lengthCondition", reference: nil, referenceNames: ["distance"], relative: nil, relativeNames: ["randomTimeGenerator"], relational: ">")
dripBehavior!.addState(stateId: NSUUID().uuidString, stateName: "die",stateX:0,stateY:0);
dripBehavior!.addTransition(transitionId: NSUUID().uuidString, name: "tickTransition", eventEmitter: nil, parentFlag: false, event: "TICK", fromStateId: "default", toStateId: "default", condition: nil, displayName: "foo")
dripBehavior!.addMapping(id: NSUUID().uuidString, referenceProperty: Observable<Float>(2), referenceNames: nil, relativePropertyName: "dy", stateId: "default", type:"active",relativePropertyItemName:"foo")
dripBehavior!.addMapping(id: NSUUID().uuidString, referenceProperty: nil, referenceNames: ["weightExpression"], relativePropertyName: "weight", stateId: "default", type:"active",relativePropertyItemName:"foo")
dripBehavior!.addTransition(transitionId: NSUUID().uuidString, name: "dieTransition", eventEmitter: nil, parentFlag: false, event: "TICK", fromStateId: dripBehavior!.getStateByName(name: "default")!, toStateId: dripBehavior!.getStateByName(name: "die")!, condition: "lengthCondition", displayName: "foo")
let parentBehavior = initStandardTemplate(name: "parentBehavior");
parentBehavior!.addInterval(name: "lengthInterval", inc: 100, times: nil)
parentBehavior!.addCondition(name: "lengthCondition", reference: nil, referenceNames: ["distance"], relative: nil, relativeNames: ["lengthInterval"], relational: "within")
parentBehavior!.addTransition(transitionId: NSUUID().uuidString, name: "lengthTransition", eventEmitter: nil, parentFlag: false, event: "TICK", fromStateId: parentBehavior!.getStateByName(name: "default")!, toStateId: parentBehavior!.getStateByName(name: "default")!, condition: "lengthCondition", displayName: "foo")
parentBehavior!.addMethod(targetTransition: "lengthTransition", methodId: NSUUID().uuidString, targetMethod: "spawn", arguments: ["dripBehavior",dripBehavior as Any,1]);
return parentBehavior;
}
func initRadialBehavior()->BehaviorDefinition?{
do{
let radial_spawnBehavior = initSpawnTemplate(name: "radial_spawn_behavior");
// radial_spawnBehavior!.addExpression("angle_expression", emitter1: nil, operand1Names: ["index"], emitter2: Observable<Float>(60), operand2Names: nil, type: "mult")
radial_spawnBehavior!.addMapping(id: NSUUID().uuidString, referenceProperty: nil, referenceNames: ["angle_expression"], relativePropertyName: "angle", stateId: "start", type:"active",relativePropertyItemName:"foo")
radial_spawnBehavior!.addMapping(id: NSUUID().uuidString, referenceProperty:stylus, referenceNames: ["dx"], relativePropertyName: "dx", stateId: "default", type:"active",relativePropertyItemName:"foo")
radial_spawnBehavior!.addMapping(id: NSUUID().uuidString, referenceProperty:stylus, referenceNames: ["dy"], relativePropertyName: "dy", stateId: "default", type:"active",relativePropertyItemName:"foo")
radial_spawnBehavior!.addState(stateId: NSUUID().uuidString,stateName:"die",stateX:0,stateY:0)
radial_spawnBehavior!.addTransition(transitionId: NSUUID().uuidString, name: "dieTransition", eventEmitter: stylus, parentFlag: false, event: "STYLUS_UP", fromStateId: radial_spawnBehavior!.getStateByName(name: "default")!, toStateId: radial_spawnBehavior!.getStateByName(name: "die")!, condition: nil, displayName: "foo")
radial_spawnBehavior!.addMethod(targetTransition: "dieTransition", methodId:NSUUID().uuidString, targetMethod: "jogAndBake", arguments: nil)
let radial_behavior = try defaultSetup(name: "radial_behavior");
radial_behavior.addTransition(transitionId: NSUUID().uuidString, name:"stylusDownTransition", eventEmitter: stylus, parentFlag:false, event: "STYLUS_DOWN", fromStateId: radial_behavior.getStateByName(name: "default")!, toStateId: radial_behavior.getStateByName(name: "default")!, condition:nil, displayName: "foo")
radial_behavior.addTransition(transitionId: NSUUID().uuidString, name:"stylusUpTransition", eventEmitter: stylus, parentFlag:false, event: "STYLUS_UP", fromStateId: radial_behavior.getStateByName(name: "default")!, toStateId: radial_behavior.getStateByName(name: "default")!, condition:nil, displayName: "foo")
radial_behavior.addMethod(targetTransition: "stylusDownTransition", methodId:NSUUID().uuidString, targetMethod: "setOrigin", arguments: [stylus.position])
radial_behavior.addMethod(targetTransition: "stylusDownTransition", methodId:NSUUID().uuidString, targetMethod: "startInterval", arguments: nil)
radial_behavior.addMethod(targetTransition: "stylusUpTransition", methodId:NSUUID().uuidString, targetMethod: "stopInterval", arguments: nil)
radial_behavior.addMethod(targetTransition: "stylusDownTransition", methodId:NSUUID().uuidString, targetMethod: "spawn", arguments: ["radial_spawn_behavior",radial_spawnBehavior!,6])
radial_behavior.addMethod(targetTransition: "stylusDownTransition",methodId:NSUUID().uuidString,targetMethod: "jogTo", arguments: [stylus.position])
return radial_behavior
}
catch{
return nil;
}
}
func initFractalBehavior()->BehaviorDefinition?{
do{
let branchBehavior = try defaultSetup(name: "branch");
let rootBehavior = try defaultSetup(name: "root");
branchBehavior.addRandomGenerator(name: "random1", min: 2 , max: 5)
branchBehavior.addState(stateId: NSUUID().uuidString,stateName:"spawnEnd",stateX:0,stateY:0);
branchBehavior.addCondition(name: "spawnCondition", reference: nil, referenceNames: ["ancestors"], relative: Observable<Float>(2), relativeNames: nil, relational: "<")
branchBehavior.addCondition(name: "noSpawnCondition", reference: nil, referenceNames: ["ancestors"], relative: Observable<Float>(1), relativeNames: nil, relational: ">")
branchBehavior.addState(stateId: NSUUID().uuidString,stateName: "die",stateX:0,stateY:0);
branchBehavior.addCondition(name: "timeLimitCondition", reference: nil, referenceNames: ["time"], relative: nil, relativeNames: ["random1"], relational: ">")
branchBehavior.addCondition(name: "offCanvasCondition", reference: nil, referenceNames: ["offCanvas"], relative: Observable<Float>(1), relativeNames: nil, relational: "==")
branchBehavior.addTransition(transitionId: NSUUID().uuidString, name: "destroyTransition", eventEmitter: nil, parentFlag: false, event: "TICK", fromStateId: branchBehavior.getStateByName(name: "default")!, toStateId: branchBehavior.getStateByName(name: "die")!, condition: "timeLimitCondition", displayName: "foo")
branchBehavior.addTransition(transitionId: NSUUID().uuidString, name: "offCanvasTransition", eventEmitter: nil, parentFlag: false, event: "STATE_COMPLETE", fromStateId: branchBehavior.getStateByName(name: "default")!, toStateId: branchBehavior.getStateByName(name: "die")!, condition: "offCanvasCondition", displayName: "foo")
branchBehavior.addMethod(targetTransition: "destroyTransition",methodId:NSUUID().uuidString,targetMethod: "jogAndBake", arguments: nil)
branchBehavior.addMethod(targetTransition: "offCanvasTransition",methodId:NSUUID().uuidString,targetMethod: "jogAndBake", arguments: nil)
// branchBehavior.addMethod("destroyTransition", methodId: NSUUID().UUIDString, targetMethod: "destroy", arguments: nil)
// branchBehavior.addMethod("defaultdestroyTransition", methodId: NSUUID().UUIDString, targetMethod: "destroy", arguments: nil)
branchBehavior.addTransition(transitionId: NSUUID().uuidString, name:"spawnTransition" , eventEmitter: nil, parentFlag: false, event: "STATE_COMPLETE", fromStateId: branchBehavior.getStateByName(name: "die")!, toStateId: branchBehavior.getStateByName(name: "spawnEnd")!, condition: "spawnCondition", displayName: "foo")
// branchBehavior.addMethod("spawnTransition", methodId: NSUUID().UUIDString, targetMethod: "spawn", arguments: ["branchBehavior",branchBehavior,2])
branchBehavior.addMethod(targetTransition: "setup", methodId:NSUUID().uuidString, targetMethod: "newStroke", arguments:nil)
branchBehavior.addMethod(targetTransition: "setup", methodId:NSUUID().uuidString, targetMethod: "setOrigin", arguments: ["parent"])
branchBehavior.addMethod(targetTransition: "setup", methodId:NSUUID().uuidString, targetMethod: "startInterval", arguments:nil)
branchBehavior.addMethod(targetTransition: "spawnEnd", methodId:NSUUID().uuidString, targetMethod: "destroy", arguments:nil)
//branchBehavior.addExpression("xDeltaExp", emitter1: nil, operand1Names: ["parent","currentStroke","xBuffer"],emitter2: Observable<Float>(0.65), operand2Names: nil, type: "mult")
//branchBehavior.addExpression("yDeltaExp", emitter1: nil, operand1Names: ["parent","currentStroke","yBuffer"], emitter2: /Observable<Float>(0.65), operand2Names: nil, type: "mult")
// branchBehavior.addExpression("weightDeltaExp", emitter1: nil, operand1Names: ["parent","currentStroke","weightBuffer"], emitter2: Observable<Float>(0.45), operand2Names: nil,type: "mult")
branchBehavior.addMapping(id: NSUUID().uuidString, referenceProperty:nil, referenceNames: ["xDeltaExp"], relativePropertyName: "dx", stateId: "default", type:"active",relativePropertyItemName:"foo")
branchBehavior.addMapping(id: NSUUID().uuidString, referenceProperty:nil, referenceNames: ["yDeltaExp"], relativePropertyName: "dy", stateId: "default", type:"active",relativePropertyItemName:"foo")
branchBehavior.addMapping(id: NSUUID().uuidString, referenceProperty:nil, referenceNames:["weightDeltaExp"], relativePropertyName: "weight", stateId: "default", type:"active",relativePropertyItemName:"foo")
branchBehavior.addTransition(transitionId: NSUUID().uuidString, name: "tickTransition", eventEmitter: nil, parentFlag: false, event: "TICK", fromStateId: branchBehavior.getStateByName(name: "default")!, toStateId:branchBehavior.getStateByName(name: "default")!, condition: nil, displayName: "foo")
rootBehavior.addInterval(name: "timeInterval",inc:1,times:nil)
rootBehavior.addCondition(name: "stylusDownCondition", reference:stylus, referenceNames: ["penDown"], relative:Observable<Float>(1), relativeNames:nil, relational: "==")
rootBehavior.addCondition(name: "incrementCondition", reference: nil, referenceNames: ["time"], relative:nil, relativeNames: ["timeInterval"], relational: "within")
rootBehavior.addCondition(name: "stylusANDIncrement",reference: nil, referenceNames: ["stylusDownCondition"], relative:nil, relativeNames: ["incrementCondition"], relational: "&&");
rootBehavior.addTransition(transitionId: NSUUID().uuidString, name:"stylusDownT", eventEmitter: stylus, parentFlag:false, event: "STYLUS_DOWN", fromStateId: rootBehavior.getStateByName(name: "default")!, toStateId: rootBehavior.getStateByName(name: "default")!, condition:nil, displayName: "foo")
rootBehavior.addMethod(targetTransition: "stylusDownT", methodId:NSUUID().uuidString, targetMethod: "setOrigin", arguments: [stylus.position])
rootBehavior.addMethod(targetTransition: "stylusDownT", methodId:NSUUID().uuidString, targetMethod: "newStroke", arguments: nil)
rootBehavior.addMethod(targetTransition: "stylusDownT", methodId:NSUUID().uuidString, targetMethod: "startInterval", arguments: nil)
rootBehavior.addMapping(id: NSUUID().uuidString, referenceProperty:stylus, referenceNames: ["dx"], relativePropertyName: "dx", stateId: "default", type:"active",relativePropertyItemName:"foo")
rootBehavior.addMapping(id: NSUUID().uuidString, referenceProperty:stylus, referenceNames: ["dy"], relativePropertyName: "dy", stateId: "default", type:"active",relativePropertyItemName:"foo")
rootBehavior.addMapping(id: NSUUID().uuidString, referenceProperty:stylus, referenceNames: ["force"], relativePropertyName: "weight", stateId: "default", type:"active",relativePropertyItemName:"foo")
rootBehavior.addTransition(transitionId: NSUUID().uuidString, name: "spawnTransition", eventEmitter: nil, parentFlag: false, event: "TICK", fromStateId: rootBehavior.getStateByName(name: "default")!, toStateId: rootBehavior.getStateByName(name: "default")!, condition: "stylusANDIncrement", displayName: "foo")
rootBehavior.addTransition(transitionId: NSUUID().uuidString, name:"stylusUpT", eventEmitter: stylus, parentFlag:false, event: "STYLUS_UP", fromStateId: rootBehavior.getStateByName(name: "default")!, toStateId: rootBehavior.getStateByName(name: "default")!, condition:nil, displayName: "foo")
rootBehavior.addMethod(targetTransition: "spawnTransition", methodId: NSUUID().uuidString, targetMethod: "spawn", arguments: ["branchBehavior",branchBehavior,2])
//rootBehavior.addMethod("stylusUpT", methodId:NSUUID().UUIDString, targetMethod: "bake", arguments: nil)
rootBehavior.addMethod(targetTransition: "stylusUpT", methodId:NSUUID().uuidString, targetMethod: "jogAndBake", arguments: nil)
// rootBehavior.addMethod("stylusDownT",methodId:NSUUID().UUIDString,targetMethod: "jogTo", arguments: nil)
return rootBehavior;
}
catch{
return nil
}
}
//---------------------------------- END HARDCODED BEHAVIORS ---------------------------------- //
}
|
mit
|
ef59c8b03817ff8ff45f16d4e9c571f5
| 52.276423 | 338 | 0.627774 | 4.812014 | false | false | false | false |
narner/AudioKit
|
AudioKit/Common/Nodes/Effects/Reverb/Apple Reverb/AKReverb2.swift
|
1
|
9745
|
//
// AKReverb2.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// AudioKit version of Apple's Reverb2 Audio Unit
///
open class AKReverb2: AKNode, AKToggleable, AKInput {
fileprivate let cd = AudioComponentDescription(
componentType: kAudioUnitType_Effect,
componentSubType: kAudioUnitSubType_Reverb2,
componentManufacturer: kAudioUnitManufacturer_Apple,
componentFlags: 0,
componentFlagsMask: 0)
internal var internalEffect = AVAudioUnitEffect()
internal var internalAU: AudioUnit?
fileprivate var lastKnownMix: Double = 50
/// Dry Wet Mix (CrossFade) ranges from 0 to 1 (Default: 0.5)
@objc open dynamic var dryWetMix: Double = 0.5 {
didSet {
if dryWetMix < 0 {
dryWetMix = 0
}
if dryWetMix > 1 {
dryWetMix = 1
}
if let audioUnit = internalAU {
AudioUnitSetParameter(audioUnit,
kReverb2Param_DryWetMix,
kAudioUnitScope_Global, 0,
Float(dryWetMix * 100.0), 0)
}
}
}
/// Gain (Decibels) ranges from -20 to 20 (Default: 0)
@objc open dynamic var gain: Double = 0 {
didSet {
if gain < -20 {
gain = -20
}
if gain > 20 {
gain = 20
}
if let audioUnit = internalAU {
AudioUnitSetParameter(audioUnit,
kReverb2Param_Gain,
kAudioUnitScope_Global, 0,
Float(gain), 0)
}
}
}
/// Min Delay Time (Secs) ranges from 0.0001 to 1.0 (Default: 0.008)
@objc open dynamic var minDelayTime: Double = 0.008 {
didSet {
if minDelayTime < 0.000_1 {
minDelayTime = 0.000_1
}
if minDelayTime > 1.0 {
minDelayTime = 1.0
}
if let audioUnit = internalAU {
AudioUnitSetParameter(audioUnit,
kReverb2Param_MinDelayTime,
kAudioUnitScope_Global, 0,
Float(minDelayTime), 0)
}
}
}
/// Max Delay Time (Secs) ranges from 0.0001 to 1.0 (Default: 0.050)
@objc open dynamic var maxDelayTime: Double = 0.050 {
didSet {
if maxDelayTime < 0.000_1 {
maxDelayTime = 0.000_1
}
if maxDelayTime > 1.0 {
maxDelayTime = 1.0
}
if let audioUnit = internalAU {
AudioUnitSetParameter(audioUnit,
kReverb2Param_MaxDelayTime,
kAudioUnitScope_Global, 0,
Float(maxDelayTime), 0)
}
}
}
/// Decay Time At0 Hz (Secs) ranges from 0.001 to 20.0 (Default: 1.0)
@objc open dynamic var decayTimeAt0Hz: Double = 1.0 {
didSet {
if decayTimeAt0Hz < 0.001 {
decayTimeAt0Hz = 0.001
}
if decayTimeAt0Hz > 20.0 {
decayTimeAt0Hz = 20.0
}
if let audioUnit = internalAU {
AudioUnitSetParameter(audioUnit,
kReverb2Param_DecayTimeAt0Hz,
kAudioUnitScope_Global, 0,
Float(decayTimeAt0Hz), 0)
}
}
}
/// Decay Time At Nyquist (Secs) ranges from 0.001 to 20.0 (Default: 0.5)
@objc open dynamic var decayTimeAtNyquist: Double = 0.5 {
didSet {
if decayTimeAtNyquist < 0.001 {
decayTimeAtNyquist = 0.001
}
if decayTimeAtNyquist > 20.0 {
decayTimeAtNyquist = 20.0
}
if let audioUnit = internalAU {
AudioUnitSetParameter(audioUnit,
kReverb2Param_DecayTimeAtNyquist,
kAudioUnitScope_Global, 0,
Float(decayTimeAtNyquist), 0)
}
}
}
/// Randomize Reflections (Integer) ranges from 1 to 1000 (Default: 1)
@objc open dynamic var randomizeReflections: Double = 1 {
didSet {
if randomizeReflections < 1 {
randomizeReflections = 1
}
if randomizeReflections > 1_000 {
randomizeReflections = 1_000
}
if let audioUnit = internalAU {
AudioUnitSetParameter(audioUnit,
kReverb2Param_RandomizeReflections,
kAudioUnitScope_Global, 0,
Float(randomizeReflections), 0)
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted = true
/// Initialize the reverb2 node
///
/// - Parameters:
/// - input: Input node to process
/// - dryWetMix: Dry Wet Mix (CrossFade) ranges from 0 to 1 (Default: 0.5)
/// - gain: Gain (Decibels) ranges from -20 to 20 (Default: 0)
/// - minDelayTime: Min Delay Time (Secs) ranges from 0.0001 to 1.0 (Default: 0.008)
/// - maxDelayTime: Max Delay Time (Secs) ranges from 0.0001 to 1.0 (Default: 0.050)
/// - decayTimeAt0Hz: Decay Time At0 Hz (Secs) ranges from 0.001 to 20.0 (Default: 1.0)
/// - decayTimeAtNyquist: Decay Time At Nyquist (Secs) ranges from 0.001 to 20.0 (Default: 0.5)
/// - randomizeReflections: Randomize Reflections (Integer) ranges from 1 to 1000 (Default: 1)
///
@objc public init(
_ input: AKNode? = nil,
dryWetMix: Double = 0.5,
gain: Double = 0,
minDelayTime: Double = 0.008,
maxDelayTime: Double = 0.050,
decayTimeAt0Hz: Double = 1.0,
decayTimeAtNyquist: Double = 0.5,
randomizeReflections: Double = 1) {
self.dryWetMix = dryWetMix
self.gain = gain
self.minDelayTime = minDelayTime
self.maxDelayTime = maxDelayTime
self.decayTimeAt0Hz = decayTimeAt0Hz
self.decayTimeAtNyquist = decayTimeAtNyquist
self.randomizeReflections = randomizeReflections
internalEffect = AVAudioUnitEffect(audioComponentDescription: cd)
super.init()
self.avAudioNode = internalEffect
AudioKit.engine.attach(self.avAudioNode)
input?.connect(to: self)
internalAU = internalEffect.audioUnit
if let audioUnit = internalAU {
AudioUnitSetParameter(audioUnit,
kReverb2Param_DryWetMix,
kAudioUnitScope_Global,
0,
Float(dryWetMix * 100.0),
0)
AudioUnitSetParameter(audioUnit,
kReverb2Param_Gain,
kAudioUnitScope_Global,
0,
Float(gain),
0)
AudioUnitSetParameter(audioUnit,
kReverb2Param_MinDelayTime,
kAudioUnitScope_Global,
0,
Float(minDelayTime),
0)
AudioUnitSetParameter(audioUnit,
kReverb2Param_MaxDelayTime,
kAudioUnitScope_Global,
0,
Float(maxDelayTime),
0)
AudioUnitSetParameter(audioUnit,
kReverb2Param_DecayTimeAt0Hz,
kAudioUnitScope_Global,
0,
Float(decayTimeAt0Hz),
0)
AudioUnitSetParameter(audioUnit,
kReverb2Param_DecayTimeAtNyquist,
kAudioUnitScope_Global,
0,
Float(decayTimeAtNyquist),
0)
AudioUnitSetParameter(audioUnit,
kReverb2Param_RandomizeReflections,
kAudioUnitScope_Global,
0,
Float(randomizeReflections),
0)
}
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
if isStopped {
dryWetMix = lastKnownMix
isStarted = true
}
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
if isPlaying {
lastKnownMix = dryWetMix
dryWetMix = 0
isStarted = false
}
}
}
|
mit
|
ba89a3f8d09fb45a214c2e19f3490d30
| 37.0625 | 101 | 0.462028 | 5.434467 | false | false | false | false |
pandazheng/Spiral
|
Spiral/ZenHelpScene.swift
|
1
|
1191
|
//
// ZenHelpScene.swift
// Spiral
//
// Created by 杨萧玉 on 15/5/3.
// Copyright (c) 2015年 杨萧玉. All rights reserved.
//
import SpriteKit
class ZenHelpScene: SKScene {
func lightWithFinger(point:CGPoint){
if let light = self.childNodeWithName("light") as? SKLightNode {
light.lightColor = SKColor.whiteColor()
light.position = self.convertPointFromView(point)
}
}
func turnOffLight() {
(self.childNodeWithName("light") as? SKLightNode)?.lightColor = SKColor.brownColor()
}
func back() {
Data.sharedData.gameOver = false
let scene = ZenModeScene(size: self.size)
let push = SKTransition.pushWithDirection(SKTransitionDirection.Right, duration: 1)
push.pausesIncomingScene = false
self.scene?.view?.presentScene(scene, transition: push)
}
override func didMoveToView(view: SKView) {
let bg = childNodeWithName("background") as! SKSpriteNode
let w = bg.size.width
let h = bg.size.height
let scale = max(view.frame.width/w, view.frame.height/h)
bg.xScale = scale
bg.yScale = scale
}
}
|
mit
|
3981c25b0f5d94c0c4abba3302dc6a29
| 28.425 | 92 | 0.629567 | 4.188612 | false | false | false | false |
wireapp/wire-ios-data-model
|
Tests/Source/Model/Label/LabelTests.swift
|
1
|
2474
|
//
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// 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.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
@testable import WireDataModel
class LabelTests: ZMBaseManagedObjectTest {
func testThatFetchOrCreateFavoriteLabel_ReturnsLabelOfKindFavorite() {
// given
let favoriteLabel = Label.fetchOrCreateFavoriteLabel(in: uiMOC, create: true)
// then
XCTAssertEqual(favoriteLabel.kind, .favorite)
}
func testThatFetchOrCreateFavoriteLabel_ReturnsTheSameObject_WhenCalledTwice() {
// given
let favoriteLabel = Label.fetchOrCreateFavoriteLabel(in: uiMOC, create: true)
// then
XCTAssertEqual(Label.fetchOrCreateFavoriteLabel(in: uiMOC, create: true), favoriteLabel)
}
func testThatFetchOrCreate_ReturnsANewLabel_WhenCreateIsTrue() {
// given
var created = false
// when
let label = Label.fetchOrCreate(remoteIdentifier: UUID(), create: true, in: uiMOC, created: &created)
// then
XCTAssertTrue(created)
XCTAssertNotNil(label)
}
func testThatFetchOrCreate_ReturnsNil_WhenCreateIsFalse() {
// given
var created = false
// when
let label = Label.fetchOrCreate(remoteIdentifier: UUID(), create: false, in: uiMOC, created: &created)
// then
XCTAssertFalse(created)
XCTAssertNil(label)
}
func testThatFetchOrCreate_FetchesAnExistingLabel() {
// given
var created = false
let label = Label.fetchOrCreate(remoteIdentifier: UUID(), create: true, in: uiMOC, created: &created)
// when
let fetchedLabel = Label.fetchOrCreate(remoteIdentifier: label!.remoteIdentifier!, create: false, in: uiMOC, created: &created)
// then
XCTAssertFalse(created)
XCTAssertEqual(label, fetchedLabel)
}
}
|
gpl-3.0
|
58c56ee9f1969df1da5cfe68ca54dd73
| 31.12987 | 135 | 0.686742 | 4.730402 | false | true | false | false |
maghov/IS-213
|
LoginV1/LoginV1/ChooseBuildingViewController.swift
|
1
|
2005
|
//
// ChooseBuildingViewController.swift
// LoginV1
//
// Created by Gruppe10 on 30.05.2017.
// Copyright © 2017 Gruppe10. All rights reserved.
//
import UIKit
import Firebase
class ChooseBuildingViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var viewDropDownMenu: UIView!
@IBAction func showDropDownMenu(_ sender: UIBarButtonItem) {
if (viewDropDownMenu.isHidden == true){
viewDropDownMenu.isHidden = false
}
else if (viewDropDownMenu.isHidden == false){
viewDropDownMenu.isHidden = true
}
}
@IBAction func logoutButtonPressed(_ sender: UIButton) {
try! FIRAuth.auth()?.signOut()
performSegue(withIdentifier: "seguechooseBuildingToLogin", sender: self)
}
//Creates a list of buildings
let buildingList = ["Bygg 47", "Bygg 48", "Bygg 49", "Bygg 50", "Bygg 51"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return buildingList.count
}
//Creates a row for every building in the table.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let buildingCell = UITableViewCell (style: UITableViewCellStyle.default, reuseIdentifier: "buildingCell")
buildingCell.textLabel?.text = buildingList[indexPath.row]
return buildingCell
}
//Switches scene to RoomViewController when you tap a building.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "segueBuildingToRoom" , sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
viewDropDownMenu.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
d9d4cb27469713ef23a8586c437559c0
| 26.833333 | 113 | 0.661178 | 5.060606 | false | false | false | false |
milseman/swift
|
stdlib/public/core/ImplicitlyUnwrappedOptional.swift
|
4
|
4269
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// An optional type that allows implicit member access.
///
/// The `ImplicitlyUnwrappedOptional` type is deprecated. To create an optional
/// value that is implicitly unwrapped, place an exclamation mark (`!`) after
/// the type that you want to denote as optional.
///
/// // An implicitly unwrapped optional integer
/// let guaranteedNumber: Int! = 6
///
/// // An optional integer
/// let possibleNumber: Int? = 5
@_fixed_layout
public enum ImplicitlyUnwrappedOptional<Wrapped> : ExpressibleByNilLiteral {
// The compiler has special knowledge of the existence of
// `ImplicitlyUnwrappedOptional<Wrapped>`, but always interacts with it using
// the library intrinsics below.
/// The absence of a value. Typically written using the nil literal, `nil`.
case none
/// The presence of a value, stored as `Wrapped`.
case some(Wrapped)
/// Creates an instance that stores the given value.
public init(_ some: Wrapped) { self = .some(some) }
/// Creates an instance initialized with `nil`.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you initialize an `Optional` instance with a `nil` literal. For example:
///
/// let i: Index! = nil
@_transparent
public init(nilLiteral: ()) {
self = .none
}
}
extension ImplicitlyUnwrappedOptional : CustomStringConvertible {
/// A textual representation of the value, or `nil`.
public var description: String {
switch self {
case .some(let value):
return String(describing: value)
case .none:
return "nil"
}
}
}
/// Directly conform to CustomDebugStringConvertible to support
/// optional printing. Implementation of that feature relies on
/// _isOptional thus cannot distinguish ImplicitlyUnwrappedOptional
/// from Optional. When conditional conformance is available, this
/// outright conformance can be removed.
extension ImplicitlyUnwrappedOptional : CustomDebugStringConvertible {
public var debugDescription: String {
return description
}
}
#if _runtime(_ObjC)
extension ImplicitlyUnwrappedOptional : _ObjectiveCBridgeable {
public func _bridgeToObjectiveC() -> AnyObject {
switch self {
case .none:
_preconditionFailure("attempt to bridge an implicitly unwrapped optional containing nil")
case .some(let x):
return Swift._bridgeAnythingToObjectiveC(x)
}
}
public static func _forceBridgeFromObjectiveC(
_ x: AnyObject,
result: inout ImplicitlyUnwrappedOptional<Wrapped>?
) {
result = Swift._forceBridgeFromObjectiveC(x, Wrapped.self)
}
public static func _conditionallyBridgeFromObjectiveC(
_ x: AnyObject,
result: inout ImplicitlyUnwrappedOptional<Wrapped>?
) -> Bool {
let bridged: Wrapped? =
Swift._conditionallyBridgeFromObjectiveC(x, Wrapped.self)
if let value = bridged {
result = value
}
return false
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)
-> Wrapped! {
var result: ImplicitlyUnwrappedOptional<Wrapped>?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
#endif
extension ImplicitlyUnwrappedOptional {
@available(*, unavailable, message: "Please use nil literal instead.")
public init() {
Builtin.unreachable()
}
@available(*, unavailable, message: "Has been removed in Swift 3.")
public func map<U>(
_ f: (Wrapped) throws -> U
) rethrows -> ImplicitlyUnwrappedOptional<U> {
Builtin.unreachable()
}
@available(*, unavailable, message: "Has been removed in Swift 3.")
public func flatMap<U>(
_ f: (Wrapped) throws -> ImplicitlyUnwrappedOptional<U>
) rethrows -> ImplicitlyUnwrappedOptional<U> {
Builtin.unreachable()
}
}
|
apache-2.0
|
05b241f619ede15dc87e11e727ddc8a2
| 30.858209 | 95 | 0.680956 | 4.923875 | false | false | false | false |
hughbe/swift
|
test/SILGen/super.swift
|
2
|
7229
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
import resilient_class
public class Parent {
public final var finalProperty: String {
return "Parent.finalProperty"
}
public var property: String {
return "Parent.property"
}
public final class var finalClassProperty: String {
return "Parent.finalProperty"
}
public class var classProperty: String {
return "Parent.property"
}
public func methodOnlyInParent() {}
public final func finalMethodOnlyInParent() {}
public func method() {}
public final class func finalClassMethodOnlyInParent() {}
public class func classMethod() {}
}
public class Child : Parent {
// CHECK-LABEL: sil @_T05super5ChildC8propertySSfg : $@convention(method) (@guaranteed Child) -> @owned String {
// CHECK: bb0([[SELF:%.*]] : $Child):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T05super6ParentC8propertySSfg : $@convention(method) (@guaranteed Parent) -> @owned String
// CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]])
// CHECK: destroy_value [[CASTED_SELF_COPY]]
// CHECK: return [[RESULT]]
public override var property: String {
return super.property
}
// CHECK-LABEL: sil @_T05super5ChildC13otherPropertySSfg : $@convention(method) (@guaranteed Child) -> @owned String {
// CHECK: bb0([[SELF:%.*]] : $Child):
// CHECK: [[COPIED_SELF:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[COPIED_SELF]] : $Child to $Parent
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T05super6ParentC13finalPropertySSfg
// CHECK: [[RESULT:%.*]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]])
// CHECK: destroy_value [[CASTED_SELF_COPY]]
// CHECK: return [[RESULT]]
public var otherProperty: String {
return super.finalProperty
}
}
public class Grandchild : Child {
// CHECK-LABEL: sil @_T05super10GrandchildC06onlyInB0yyF
public func onlyInGrandchild() {
// CHECK: function_ref @_T05super6ParentC012methodOnlyInB0yyF : $@convention(method) (@guaranteed Parent) -> ()
super.methodOnlyInParent()
// CHECK: function_ref @_T05super6ParentC017finalMethodOnlyInB0yyF
super.finalMethodOnlyInParent()
}
// CHECK-LABEL: sil @_T05super10GrandchildC6methodyyF
public override func method() {
// CHECK: function_ref @_T05super6ParentC6methodyyF : $@convention(method) (@guaranteed Parent) -> ()
super.method()
}
}
public class GreatGrandchild : Grandchild {
// CHECK-LABEL: sil @_T05super15GreatGrandchildC6methodyyF
public override func method() {
// CHECK: function_ref @_T05super10GrandchildC6methodyyF : $@convention(method) (@guaranteed Grandchild) -> ()
super.method()
}
}
public class ChildToResilientParent : ResilientOutsideParent {
// CHECK-LABEL: sil @_T05super22ChildToResilientParentC6methodyyF : $@convention(method) (@guaranteed ChildToResilientParent) -> ()
public override func method() {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: super_method [[COPY]] : $ChildToResilientParent, #ResilientOutsideParent.method!1 : (ResilientOutsideParent) -> () -> (), $@convention(method) (@guaranteed ResilientOutsideParent) -> ()
// CHECK: return
super.method()
}
// CHECK-LABEL: sil @_T05super22ChildToResilientParentC11classMethodyyFZ : $@convention(method) (@thick ChildToResilientParent.Type) -> ()
public override class func classMethod() {
// CHECK: super_method %0 : $@thick ChildToResilientParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideParent.Type) -> ()
// CHECK: return
super.classMethod()
}
// CHECK-LABEL: sil @_T05super22ChildToResilientParentC11returnsSelfACXDyFZ : $@convention(method) (@thick ChildToResilientParent.Type) -> @owned ChildToResilientParent
public class func returnsSelf() -> Self {
// CHECK: super_method %0 : $@thick ChildToResilientParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> ()
// CHECK: unreachable
super.classMethod()
}
}
public class ChildToFixedParent : OutsideParent {
// CHECK-LABEL: sil @_T05super18ChildToFixedParentC6methodyyF : $@convention(method) (@guaranteed ChildToFixedParent) -> ()
public override func method() {
// CHECK: [[COPY:%.*]] = copy_value %0
// CHECK: super_method [[COPY]] : $ChildToFixedParent, #OutsideParent.method!1 : (OutsideParent) -> () -> (), $@convention(method) (@guaranteed OutsideParent) -> ()
// CHECK: return
super.method()
}
// CHECK-LABEL: sil @_T05super18ChildToFixedParentC11classMethodyyFZ : $@convention(method) (@thick ChildToFixedParent.Type) -> ()
public override class func classMethod() {
// CHECK: super_method %0 : $@thick ChildToFixedParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> (), $@convention(method) (@thick OutsideParent.Type) -> ()
// CHECK: return
super.classMethod()
}
// CHECK-LABEL: sil @_T05super18ChildToFixedParentC11returnsSelfACXDyFZ : $@convention(method) (@thick ChildToFixedParent.Type) -> @owned ChildToFixedParent
public class func returnsSelf() -> Self {
// CHECK: super_method %0 : $@thick ChildToFixedParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> ()
// CHECK: unreachable
super.classMethod()
}
}
public extension ResilientOutsideChild {
public func callSuperMethod() {
super.method()
}
public class func callSuperClassMethod() {
super.classMethod()
}
}
public class GenericBase<T> {
public func method() {}
}
public class GenericDerived<T> : GenericBase<T> {
public override func method() {
// CHECK-LABEL: sil private @_T05super14GenericDerivedC6methodyyFyycfU_ : $@convention(thin) <T> (@owned GenericDerived<T>) -> ()
// CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T>
// CHECK: return
{
super.method()
}()
// CHECK-LABEL: sil private @_T05super14GenericDerivedC6methodyyF13localFunctionL_yylF : $@convention(thin) <T> (@owned GenericDerived<T>) -> ()
// CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T>
// CHECK: return
func localFunction() {
super.method()
}
localFunction()
// CHECK-LABEL: sil private @_T05super14GenericDerivedC6methodyyF15genericFunctionL_yqd__r__lF : $@convention(thin) <T><U> (@in U, @owned GenericDerived<T>) -> ()
// CHECK: upcast {{.*}} : $GenericDerived<T> to $GenericBase<T>
// CHECK: return
func genericFunction<U>(_: U) {
super.method()
}
genericFunction(0)
}
}
|
apache-2.0
|
1176b4977f6a9b9358a74dcd13966fb6
| 41.274854 | 215 | 0.676719 | 3.847259 | false | false | false | false |
ismailbozk/ObjectScanner
|
ObjectScanner/ObjectScanner/Models/OSBaseFrame.swift
|
1
|
7759
|
//
// OSBaseFrame.swift
// ObjectScanner
//
// Created by Ismail Bozkurt on 19/07/2015.
// The MIT License (MIT)
//
// Copyright (c) 2015 Ismail Bozkurt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
import simd
import Metal
/// Single point representaion in 3D space. Look also Shared.h.
/// calibration matrix that calibrate depth frames onto rgb frame.
private var calibrationMatrix : [Float] = [9.9984628826577793e-01 , 1.2635359098409581e-03 , -1.7487233004436643e-02, 0,
-1.4779096108364480e-03, 9.9992385683542895e-01 , -1.2251380107679535e-02, 0,
1.7470421412464927e-02 , 1.2275341476520762e-02 , 9.9977202419716948e-01 , 0,
1.9985242312092553e-02 , -7.4423738761617583e-04, -1.0916736334336222e-02,1];
/**
This class represents a single Kinect camera frame.
It also constains the calibration process and the result point cloud in 3D space.
*/
class OSBaseFrame : OSContentLoadingProtocol{
// MARK: Properties
/// RGB Image of the frame
let image : UIImage;
/// Height of the frame
var height : Int{
get {
return (Int)(self.image.size.height);
}
}
/// Width of the frame
var width : Int{
get{
return (Int)(self.image.size.width);
}
}
/// Raw depth frame
fileprivate var notCalibratedDepth: [Float];
/// Calibrated but not transformed point cloud in 3D space
var pointCloud: [OSPoint];
/// Transformation matrix of the current frame in 3D space. This matrix trnasforms the current point cloud respect to the initial frame.
var transformationMatrix: Matrix4 = Matrix4.Identity;
// MARK: Lifecycle
required init(image :UIImage, depth: [Float]){
let size : Int = (Int)(image.size.width) * (Int)(image.size.height)
assert(size == depth.count, "depth frame and image must be equal size");
self.image = image;
self.notCalibratedDepth = depth;
self.pointCloud = [OSPoint](repeating: OSPoint(), count: size);
}
// subscript(row : Int, col : Int) -> OSPoint{
// get {
// return (self.pointCloud[row * self.width + col]);
// }
//// set (newValue) {
//// self.pointCloud[row * self.width + col] = newValue;
//// }
// }
//MARK: Metal
static fileprivate let device : MTLDevice = MTLCreateSystemDefaultDevice()!;
static fileprivate let commandQueue : MTLCommandQueue = device.makeCommandQueue();
static fileprivate let defaultLibrary : MTLLibrary = device.newDefaultLibrary()!;
static fileprivate let calibrateFrameFunction : MTLFunction = defaultLibrary.makeFunction(name: "calibrateFrame")!;
static fileprivate var metalComputePipelineState : MTLComputePipelineState?;//very costly
static fileprivate var calibrationMatrixBuffer : MTLBuffer?;
fileprivate var commandBuffer : MTLCommandBuffer?;
fileprivate var computeCommandEncoder : MTLComputeCommandEncoder?;
func preparePointCloud(_ completionHandler : (() -> Void)!)
{
let startTime = CACurrentMediaTime();
self.commandBuffer = OSBaseFrame.commandQueue.makeCommandBuffer();
self.computeCommandEncoder = self.commandBuffer?.makeComputeCommandEncoder();
self.computeCommandEncoder?.setComputePipelineState(OSBaseFrame.metalComputePipelineState!);
//pass the data to GPU
let dataSize : Int = self.notCalibratedDepth.count//self.height * self.width;
let imageTextureBuffer = OSTextureProvider.texture(with: self.image, device: OSBaseFrame.device);
self.computeCommandEncoder?.setTexture(imageTextureBuffer, at: 0);
let inputByteLength = dataSize * MemoryLayout<Float>.size;
let inVectorBuffer = OSBaseFrame.device.makeBuffer(bytes: &self.notCalibratedDepth, length: inputByteLength, options:[]);
self.computeCommandEncoder?.setBuffer(inVectorBuffer, offset: 0, at: 0);
let outputByteLength = dataSize * MemoryLayout<OSPoint>.size;
let outputBuffer = OSBaseFrame.device.makeBuffer(bytes: &self.pointCloud, length: outputByteLength, options: []);
self.computeCommandEncoder?.setBuffer(outputBuffer, offset: 0, at: 1);
self.computeCommandEncoder?.setBuffer(OSBaseFrame.calibrationMatrixBuffer, offset: 0, at: 2);
//prepare thread groups
let threadGroupCountX = dataSize / 512;
let threadGroupCount = MTLSize(width: threadGroupCountX, height: 1, depth: 1)
let threadGroups = MTLSize(width:(dataSize + threadGroupCountX - 1) / threadGroupCountX, height:1, depth:1);
self.computeCommandEncoder?.dispatchThreadgroups(threadGroupCount, threadsPerThreadgroup: threadGroups);
self.computeCommandEncoder?.endEncoding();
self.commandBuffer?.addCompletedHandler({[unowned self] (commandBuffer : MTLCommandBuffer) -> Void in
let data = NSData(bytesNoCopy: outputBuffer.contents(), length: (self.pointCloud.count) * MemoryLayout<OSPoint>.size, freeWhenDone: false);
data.getBytes(&self.pointCloud, length: outputByteLength);
let elapsedTime : CFTimeInterval = CACurrentMediaTime() - startTime;
print("Total process \(elapsedTime) seconds");
completionHandler?();
});
self.commandBuffer?.commit();
}
// MARK: OSContentLoadingProtocol
static func loadContent(_ completionHandler : (() -> Void)!)
{
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive).async { () -> Void in
OSBaseFrame.device
OSBaseFrame.commandQueue
OSBaseFrame.defaultLibrary
OSBaseFrame.calibrateFrameFunction
let calibrationMatrixBtyeLength = calibrationMatrix.count * MemoryLayout<Float>.size;
calibrationMatrixBuffer = OSBaseFrame.device.makeBuffer(bytes: &calibrationMatrix, length: calibrationMatrixBtyeLength, options: []);
if (OSBaseFrame.metalComputePipelineState == nil)
{
do{
OSBaseFrame.metalComputePipelineState = try OSBaseFrame.device.makeComputePipelineState(function: OSBaseFrame.calibrateFrameFunction);
} catch _ {
OSBaseFrame.metalComputePipelineState = nil
};
}
DispatchQueue.main.sync { () -> Void in
completionHandler?();
};
};
}
}
|
mit
|
d54b0ef682ce15077bb8887b095854a7
| 43.591954 | 154 | 0.662585 | 4.582989 | false | false | false | false |
pirishd/InstantMock
|
Sources/InstantMock/Interceptors/Expectation.swift
|
1
|
3694
|
//
// Expectation.swift
// InstantMock
//
// Created by Patrick on 06/05/2017.
// Copyright © 2017 pirishd. All rights reserved.
//
/** This class represents an expectation to be verified */
public final class Expectation: CallInterceptor {
/// Expected number of calls
private var expectedNumberOfCalls: Int?
/// Actual number of calls
private var numberOfCalls: Int = 0
/// Expectation must be rejected
private var reject: Bool
/// Stub instance
private let stub: Stub
/// Assertion
private let assertion: Assertion
// MARK: Initializers
/** Initialize with provided stub */
convenience init(withStub stub: Stub, reject: Bool = false) {
self.init(withStub: stub, reject: reject, assertion: AssertionImpl.instance)
}
/** Initialize with provided stub and assertion (for dependency injection) */
public init(withStub stub: Stub, reject: Bool = false, assertion: Assertion) {
self.stub = stub
self.reject = reject
self.assertion = assertion
}
// MARK: Call
/** Method is being called */
@discardableResult
override func handleCall(_ args: [Any?]) throws -> Any? {
self.numberOfCalls = self.numberOfCalls + 1
return nil // don't care about return values
}
}
// MARK: Registration
extension Expectation {
/** register call */
@discardableResult
public func call<T>(_ value: T, count: Int? = nil) -> Stub {
self.expectedNumberOfCalls = count
return self.stub
}
}
// MARK: Verification
extension Expectation {
/// Flag indicating if the expectation was verified
var verified: Bool {
if let expected = self.expectedNumberOfCalls {
return self.numberOfCalls == expected
}
return self.numberOfCalls > 0
}
/// Reason for a failure, nil if expectation verified
var reason: String? {
if self.reject {
return self.rejectedReason
}
return self.acceptedReason
}
/// Reason for an unfulfilled expectation
private var acceptedReason: String? {
var value: String?
if !self.verified, let configuration = self.configuration {
var details = configuration.function + " "
if let expected = self.expectedNumberOfCalls {
details = details + "not called the expected number of times (\(self.numberOfCalls) out of \(expected))"
} else {
details = details + "never called"
}
details = details + " with expected args (\(configuration.args))"
value = details
}
return value
}
/// Reason for an expectation that should have been rejected
private var rejectedReason: String? {
var value: String?
if self.verified, let configuration = self.configuration {
var details = configuration.function + " "
if let expected = self.expectedNumberOfCalls {
details = details + "called a wrong number of times (\(expected))"
} else {
details = details + "called"
}
details = details + " with unexpected args (\(configuration.args))"
value = details
}
return value
}
/** Verify current expectation */
func verify(file: StaticString?, line: UInt?) {
let success = (!self.reject && self.verified) || (self.reject && !self.verified)
if success {
self.assertion.success(file: file, line: line)
} else {
self.assertion.fail(self.reason, file: file, line: line)
}
}
}
|
mit
|
4878d21e2a0e06b4d2f73b39a17b396d
| 24.122449 | 120 | 0.603574 | 4.827451 | false | true | false | false |
yeziahehe/Gank
|
Gank/Views/Cells/DailyGank/DailyGankCell.swift
|
1
|
2193
|
//
// DailyGankCell.swift
// Gank
//
// Created by 叶帆 on 2016/11/20.
// Copyright © 2016年 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
import UIKit
final class DailyGankCell: UITableViewCell {
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var tagLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
func configure(withGankDetail gankDetail: Gank, isHiddenTag: Bool = true) {
timeLabel.text = gankDetail.publishedAt.toTimeFormat.toDateOfSecond()!.timeAgo
titleLabel.text = gankDetail.desc
titleLabel.setLineHeight(lineHeight: 1.2)
tagLabel.isHidden = isHiddenTag
if isHiddenTag == false {
tagLabel.text = String(format:" %@ ", gankDetail.type)
switch gankDetail.type {
case "iOS":
tagLabel.backgroundColor = UIColor.gankIosTagColor()
break
case "Android":
tagLabel.backgroundColor = UIColor.gankAndroidTagColor()
break
case "前端":
tagLabel.backgroundColor = UIColor.gankFrontendTagColor()
break
case "拓展资源":
tagLabel.backgroundColor = UIColor.gankResourceTagColor()
break
case "App":
tagLabel.backgroundColor = UIColor.gankAppTagColor()
break
case "瞎推荐":
tagLabel.backgroundColor = UIColor.gankRecommTagColor()
break
case "休息视频":
tagLabel.backgroundColor = UIColor.gankVideoTagColor()
break
case "福利":
tagLabel.backgroundColor = UIColor.gankMeiziTagColor()
break
default:
break
}
}
guard let who = gankDetail.who else {
authorLabel.text = String.titleDailyGankAuthorBot
return
}
authorLabel.text = String.titleDailyGankAuthor(who)
}
}
|
gpl-3.0
|
92c1fc9f8cec880fba4792d0b09283a7
| 31.179104 | 92 | 0.574675 | 5.037383 | false | false | false | false |
alessandrostone/DDUtils
|
swift/ddutils-common/model/NSURLConnection+ModifiedSince/ModifiedSinceDemo/ViewController.swift
|
1
|
1895
|
//
// ViewController.swift
// ModifiedSinceDemo
//
// Created by Dominik Pich on 12/07/15.
// Copyright (c) 2015 Dominik Pich. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
var string = "\n\n"
let urlString = "http://www.pich.info/testfile.txt";
let url = NSURL(string: urlString)!
var dataAndDate = NSURLConnection.cachedDataForModifiedSinceRequest(url)
if(dataAndDate != nil){
string += ("have cached data for \(url), cache is from \(dataAndDate!.date)\n\n")
string += ("Starting modified since request with modDate: \(dataAndDate!.date)\n\n")
}
else {
string += ("nothing cached locally\n\n");
string += ("Starting modified since request with modDate: null\n\n");
}
NSURLConnection.doModifiedSinceRequestForURL(url, completionHandler: { (url, contentData, modificationDate, fromCache, error) -> Void in
if(contentData != nil) {
if(fromCache) {
if(error != nil) {
string += ("Got cached data, request finished error though: \(error)\n\n")
}
else {
string += ("Got cached data\n\n");
}
}
else {
string += ("Got new data from server, last modified at \(modificationDate)\n\n");
}
}
else {
string += ("Got no data. Request failed: \(error)\n\n");
}
self.textView.text = string
//now go and try again to see all cached or modify the server to get fresh data
})
}
}
|
mit
|
620ef09acedf34d7062e98227599b270
| 32.839286 | 144 | 0.520317 | 4.785354 | false | false | false | false |
trd-jameshwart/FamilySNIOS
|
FamilySns/SignupVc.swift
|
1
|
4541
|
//
// SignupVc.swift
// FamilySns
//
// Created by Jameshwart Lopez on 12/8/15.
// Copyright © 2015 Minato. All rights reserved.
//
import UIKit
import SwiftyJSON
class SignupVc: UIViewController {
@IBOutlet weak var txtEmail: UITextField!
@IBOutlet weak var txtPassword: UITextField!
@IBOutlet weak var txtConfirmPassword: UITextField!
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.
}
func showAlertView(title: String, message:String){
let alertView:UIAlertController = UIAlertController()
alertView.title = title
alertView.message = message
alertView.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil))
self.presentViewController(alertView, animated: true, completion: nil)
}
@IBAction func signupTapped(sender: AnyObject) {
let email: NSString = txtEmail.text! as NSString
let password: NSString = txtPassword.text! as NSString
let confirmPassword: NSString = txtConfirmPassword.text! as NSString
if(email.isEqualToString("") || password.isEqualToString("")){
self.showAlertView("Sigup failed", message: "Please enter email and password.")
}else if(!password.isEqual(confirmPassword)){
self.showAlertView("Signup failed", message: "Password don't match.")
}else{
let post = "email=\(email)&password=\(password)&c_password=\(confirmPassword)";
NSLog("Post Data: %@", post)
let url:NSURL = NSURL(string: Globals.API_URL+"/service/signup.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = post.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data, response, error in
if error != nil {
if let err = error{
self.showAlertView("Signup failed", message: err.localizedDescription)
}
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
if let httpResponse = response as? NSHTTPURLResponse{
if(httpResponse.statusCode == 200){
let json = JSON(data: data!)
if json["OK"] == true{
dispatch_async(dispatch_get_main_queue(), {
self.performSegueWithIdentifier("goto_home", sender: self)
})
}else if json["error"] != nil{
self.showAlertView("Signup failed", message: json["error"].stringValue)
}
}
}
}
task.resume()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if "goto_home" == segue.identifier{
print("Please go to home")
}
}
@IBAction func gotoLogin(sender: UIButton) {
self.dismissViewControllerAnimated(true
, completion: nil)
}
/*
// 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
|
20f5c7472e6a88bbedb2c3a5cde8c2a4
| 32.382353 | 106 | 0.580617 | 5.550122 | false | false | false | false |
bradhowes/SynthInC
|
SwiftMIDI/Recording.swift
|
1
|
5105
|
// Recording.swift
// SynthInC
//
// Created by Brad Howes
// Copyright (c) 2016 Brad Howes. All rights reserved.
import Foundation
import AudioToolbox
import CoreAudio
import AVFoundation
import GameKit
extension Part {
func createMusicTrack(_ musicSequence: MusicSequence, rando: Rando) -> (MusicTrack, MusicTimeStamp)? {
var track: MusicTrack? = nil
if IsAudioError("MusicSequenceNewTrack", MusicSequenceNewTrack(musicSequence, &track)) {
return nil
}
let t = track!
var clock = 120.scaled
for (index, playCount) in playCounts.enumerated() {
let phrase = ScorePhrases[index]
for _ in 0..<playCount {
clock = phrase.record(clock: clock) {
$1.addToTrack(t, clock: $0, slop: rando.noteOnSlop())
}
}
}
print("\(index) createMusicTrack - \(t) \(clock)")
return (t, clock)
}
}
extension Note {
func addToTrack(_ track: MusicTrack, clock: MusicTimeStamp, slop: MusicTimeStamp = 0.0) -> Void {
let beatWhen = getStartTime(clock: clock, slop: slop)
if note != .re {
var msg = MIDINoteMessage(channel: 0,
note: UInt8(note.rawValue),
velocity: isGraceNote ? 64 : 127,
releaseVelocity: 0,
duration: Float32(duration - slop))
let status = MusicTrackNewMIDINoteEvent(track, beatWhen, &msg)
if status != OSStatus(noErr) {
print("*** failed creating note event: \(status)")
}
}
}
}
public final class Recording {
public let musicSequence: MusicSequence
public let sequenceLength: MusicTimeStamp
public let tracks: [MusicTrack]
public init?(performance: Performance, rando: Rando) {
var musicSequence: MusicSequence?
guard !IsAudioError("NewMusicSequence", NewMusicSequence(&musicSequence)) else { return nil }
self.musicSequence = musicSequence!
let tracks = performance.parts.compactMap { $0.createMusicTrack(musicSequence!, rando: rando) }
self.sequenceLength = tracks.max(by: { $0.1 < $1.1 })?.1 ?? MusicTimeStamp(0.0)
self.tracks = tracks.map { $0.0 }
print("sequenceLength: \(sequenceLength)")
}
public init?(data: Data) {
let decoder = NSKeyedUnarchiver(forReadingWith: data)
guard let sequenceData = decoder.decodeObject(forKey: "sequenceData") as? Data else {
print("** invalid NSData for sequence data")
return nil
}
var musicSequence: MusicSequence?
if IsAudioError("NewMusicSequence", NewMusicSequence(&musicSequence)) { return nil }
self.musicSequence = musicSequence!
if IsAudioError("MusicSequenceFileLoadData",
MusicSequenceFileLoadData(musicSequence!, sequenceData as CFData, .anyType,
MusicSequenceLoadFlags())) {
return nil
}
let trackCount = decoder.decodeInteger(forKey: "trackCount")
self.tracks = (0..<trackCount).compactMap {
var track: MusicTrack?
if IsAudioError("MusicSequenceGetIndTrack", MusicSequenceGetIndTrack(musicSequence!, UInt32($0), &track)) {
return nil
}
return track!
}
self.sequenceLength = decoder.decodeDouble(forKey: "sequenceLength")
}
deinit {
DisposeMusicSequence(musicSequence)
}
public func activate(audioController: AudioController) -> Bool {
guard let graph = audioController.graph else { return false }
guard audioController.ensemble.count == tracks.count else { return false }
if IsAudioError("MusicSequenceSetAUGraph", MusicSequenceSetAUGraph(musicSequence, graph)) {
return false
}
for (track, instrument) in zip(tracks, audioController.ensemble) {
if IsAudioError("MusicTrackSetDestNode", MusicTrackSetDestNode(track, instrument.samplerNode)) {
return false
}
}
return true
}
/**
Save the current MusicSequence instance.
- returns: true if successful
*/
public func saveMusicSequence() -> Data? {
print("-- saving music sequence")
let data = NSMutableData()
let encoder = NSKeyedArchiver(forWritingWith: data)
var cfData: Unmanaged<CFData>?
if IsAudioError("MusicSequenceFileCreateData", MusicSequenceFileCreateData(musicSequence, .midiType, .eraseFile, 480, &cfData)) {
return nil
}
let sequenceData: Data = cfData!.takeRetainedValue() as Data
encoder.encode(sequenceData, forKey: "sequenceData")
encoder.encode(tracks.count, forKey: "trackCount")
encoder.encode(sequenceLength, forKey: "sequenceLength")
encoder.finishEncoding()
return data as Data
}
}
|
mit
|
43ed818a074488948aa4e6ca5e626821
| 34.206897 | 137 | 0.602155 | 4.735622 | false | false | false | false |
ykyouhei/QiitaKit
|
QiitaKit/Sources/Requests/QiitaRequest.swift
|
1
|
2879
|
//
// QiitaRequest.swift
// Qiitag
//
// Created by 山口 恭兵 on 2015/12/28.
// Copyright © 2015年 kyo__hei. All rights reserved.
//
import Foundation
public enum HTTPMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
}
/// QiitaAPIリクエスト用のプロトコル
public protocol QiitaRequest {
associatedtype Response: QiitaResponse
/// HTTPMethod
var method: HTTPMethod { get }
/// APIパス
var path: String { get }
/// URLクエリ。optional
var queries: [String: String]? { get }
/// HTTPBody。optional
var bodyParames: [String: Any]? { get }
}
extension QiitaRequest {
/// APIバージョン
var version: String {
return "v2"
}
/// APIホスト
public var baseURL: URL {
let domain = AuthManager.sharedManager.teamDomain ?? "qiita.com"
return URL(string: "https://\(domain)/api/\(version)")!
}
/// HTTPHeader
public var headerFields: [String : String] {
var result = ["Content-Type": "application/json"]
guard let token = AuthManager.sharedManager.accessToken else {
return result
}
result["Authorization"] = "Bearer \(token)"
return result
}
public var queries: [String: String]? {
return nil
}
public var bodyParames: [String: Any]? {
return nil
}
public func asURLRequest() -> URLRequest {
let url: URL = {
var componets = URLComponents()
componets.scheme = "https"
componets.host = AuthManager.sharedManager.teamDomain ?? "qiita.com"
componets.path = "/api/\(version)/\(path)"
componets.queryItems = queries?.map { URLQueryItem(name: $0.key, value: $0.value) }
return componets.url!
}()
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 30)
request.allHTTPHeaderFields = headerFields
request.httpBody = bodyParames.map { try! JSONSerialization.data(withJSONObject: $0, options: []) }
request.httpMethod = method.rawValue
return request
}
}
/// ページ可能なリクエストのプロトコル
public protocol QiitaPageableRequestType: QiitaRequest {
/// ページ番号 (1から100まで)
var page: Int { get set }
/// 1ページあたりに含まれる要素数 (1から100まで)
var perPage: Int { get set }
}
public extension QiitaPageableRequestType {
/// ページング用パラメータ
var pageParamaters: [String: String] {
return [
"page" : "\(page)",
"per_page" : "\(perPage)"
]
}
}
|
mit
|
3a0684233900c8d06cd6dc189fb660db
| 22.495652 | 107 | 0.57587 | 4.093939 | false | false | false | false |
lightbluefox/rcgapp
|
IOS App/RCGApp/RCGApp/AppDelegate.swift
|
1
|
4526
|
//
// AppDelegate.swift
// RCGApp
//
// Created by iFoxxy on 12.05.15.
// Copyright (c) 2015 LightBlueFox. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true);
var itemsReceiver = NewsAndVacanciesReceiver()
//itemsReceiver.getAllNews();
//itemsReceiver.getAllVacancies();
var newsStack = itemsReceiver.newsStack;
var vacStack = itemsReceiver.vacStack
let navBarFont = UIFont(name: "Roboto-Regular", size: 17.0) ?? UIFont.systemFontOfSize(17.0);
var navBar = UINavigationBar.appearance();
var tabBar = UITabBar.appearance();
//UITabBar.appearance().backgroundImage = UIImage(named: "selectedItemImage");
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) //Для iOS 7 и старше
{
navBar.barTintColor = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 1.0);
tabBar.barTintColor = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 1.0);
tabBar.tintColor = UIColor.whiteColor();
}
else //ниже iOS 7
{
navBar.tintColor = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 1.0);
tabBar.tintColor = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 1.0);
}
//Стиль заголовка
navBar.titleTextAttributes = [NSFontAttributeName: navBarFont, NSForegroundColorAttributeName: UIColor.whiteColor()];
//Чтобы избавиться от стандартного выделения выбранного таба, используем такой костыль.
tabBar.selectionIndicatorImage = UIImage(named: "selectedItemImage");
//Mark: Регистрация на пуш-уведомления
//IOS 7 -
UIApplication.sharedApplication().registerForRemoteNotificationTypes(UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound);
//IOS 8 +
//UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationType.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert);
//UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings: UIUserNotificationSettings.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
gpl-2.0
|
15a29b5e619c1654b77a04e4beba4716
| 49.54023 | 285 | 0.712304 | 5.118743 | false | false | false | false |
Piwigo/Piwigo-Mobile
|
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/Categories/IQUITextFieldView+Additions.swift
|
4
|
4330
|
//
// IQUITextFieldView+Additions.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
/**
Uses default keyboard distance for textField.
*/
public let kIQUseDefaultKeyboardDistance = CGFloat.greatestFiniteMagnitude
private var kIQKeyboardDistanceFromTextField = "kIQKeyboardDistanceFromTextField"
private var kIQKeyboardEnableMode = "kIQKeyboardEnableMode"
private var kIQShouldResignOnTouchOutsideMode = "kIQShouldResignOnTouchOutsideMode"
private var kIQIgnoreSwitchingByNextPrevious = "kIQIgnoreSwitchingByNextPrevious"
/**
UIView category for managing UITextField/UITextView
*/
@objc public extension UIView {
/**
To set customized distance from keyboard for textField/textView. Can't be less than zero
*/
@objc var keyboardDistanceFromTextField: CGFloat {
get {
if let aValue = objc_getAssociatedObject(self, &kIQKeyboardDistanceFromTextField) as? CGFloat {
return aValue
} else {
return kIQUseDefaultKeyboardDistance
}
}
set(newValue) {
objc_setAssociatedObject(self, &kIQKeyboardDistanceFromTextField, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/**
If shouldIgnoreSwitchingByNextPrevious is true then library will ignore this textField/textView while moving to other textField/textView using keyboard toolbar next previous buttons. Default is false
*/
@objc var ignoreSwitchingByNextPrevious: Bool {
get {
if let aValue = objc_getAssociatedObject(self, &kIQIgnoreSwitchingByNextPrevious) as? Bool {
return aValue
} else {
return false
}
}
set(newValue) {
objc_setAssociatedObject(self, &kIQIgnoreSwitchingByNextPrevious, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// /**
// Override Enable/disable managing distance between keyboard and textField behaviour for this particular textField.
// */
@objc var enableMode: IQEnableMode {
get {
if let savedMode = objc_getAssociatedObject(self, &kIQKeyboardEnableMode) as? IQEnableMode {
return savedMode
} else {
return .default
}
}
set(newValue) {
objc_setAssociatedObject(self, &kIQKeyboardEnableMode, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/**
Override resigns Keyboard on touching outside of UITextField/View behaviour for this particular textField.
*/
@objc var shouldResignOnTouchOutsideMode: IQEnableMode {
get {
if let savedMode = objc_getAssociatedObject(self, &kIQShouldResignOnTouchOutsideMode) as? IQEnableMode {
return savedMode
} else {
return .default
}
}
set(newValue) {
objc_setAssociatedObject(self, &kIQShouldResignOnTouchOutsideMode, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
|
mit
|
566d687a6ea7b7b63c089c45b9de92f8
| 38.724771 | 204 | 0.6903 | 5.185629 | false | false | false | false |
yariksmirnov/Forms
|
Sources/FormFieldBehaviour.swift
|
1
|
3003
|
//
// FormFieldBehaviour.swift
// Forms
//
// Created by Yaroslav Smirnov on 16/06/2017.
// Copyright © 2017 Yaroslav Smirnov. All rights reserved.
//
import Foundation
public final class FieldBehavior: NSObject, UITextInputTraits {
public var autocapitalizationType: UITextAutocapitalizationType = .none
public var autocorrectionType: UITextAutocorrectionType = .no
public var spellCheckingType: UITextSpellCheckingType = .default
public var keyboardType: UIKeyboardType = .default
public var keyboardAppearance: UIKeyboardAppearance = .default
public var returnKeyType: UIReturnKeyType = .next
public var enablesReturnKeyAutomatically: Bool = false
public var isSecureTextEntry: Bool = false
public var isOptional = false
public static let email: FieldBehavior = {
let email = FieldBehavior()
email.keyboardType = .emailAddress
return email
}()
public static let username: FieldBehavior = {
let username = FieldBehavior()
username.keyboardType = .namePhonePad
return username
}()
public static let password: FieldBehavior = {
let password = FieldBehavior()
password.isSecureTextEntry = true
return password
}()
public static let phone: FieldBehavior = {
let phone = FieldBehavior()
phone.keyboardType = .phonePad
return phone
}()
public static let fullName: FieldBehavior = {
let fullName = FieldBehavior()
fullName.autocapitalizationType = .words
return fullName
}()
public static let bio: FieldBehavior = {
let bio = FieldBehavior()
bio.autocorrectionType = .yes
bio.autocapitalizationType = .sentences
bio.isOptional = true
return bio
}()
}
public protocol InputTraits: UITextInputTraits {
var autocapitalizationType: UITextAutocapitalizationType { get set }
var autocorrectionType: UITextAutocorrectionType { get set }
var spellCheckingType: UITextSpellCheckingType { get set }
var keyboardType: UIKeyboardType { get set }
var keyboardAppearance: UIKeyboardAppearance { get set }
var returnKeyType: UIReturnKeyType { get set }
var enablesReturnKeyAutomatically: Bool { get set }
var isSecureTextEntry: Bool { get set }
}
extension InputTraits {
func apply(behavior: FieldBehavior) {
autocapitalizationType = behavior.autocapitalizationType
autocorrectionType = behavior.autocorrectionType
spellCheckingType = behavior.spellCheckingType
keyboardType = behavior.keyboardType
keyboardAppearance = behavior.keyboardAppearance
returnKeyType = behavior.returnKeyType
enablesReturnKeyAutomatically = behavior.enablesReturnKeyAutomatically
isSecureTextEntry = behavior.isSecureTextEntry
}
}
extension UITextField: InputTraits {}
extension UITextView: InputTraits {}
extension UISearchBar: InputTraits {}
|
mit
|
26d8eab710aa1e487d8b412166e73978
| 32.355556 | 78 | 0.70553 | 5.968191 | false | false | false | false |
AlexZd/SwiftUtils
|
Pod/Utils/UIView+Helpers/Init/UITableView+Init.swift
|
1
|
1117
|
//
// UITableView+Helpers.swift
// Scene
//
// Created by Alex on 19.05.17.
// Copyright © 2017 AlexZd. All rights reserved.
//
import Foundation
import UIKit
extension UITableView {
public static func table(separatorInset: UIEdgeInsets = .zero, separatorColor: UIColor? = nil, multiply: Bool = false) -> UITableView {
let tableView = UITableView(frame: .zero, style: .plain)
tableView.prepareTable(separatorInset: separatorInset, separatorColor: separatorColor, multiply: multiply)
return tableView
}
public func prepareTable(separatorInset: UIEdgeInsets = .zero, separatorColor: UIColor? = nil, multiply: Bool = false) {
self.translatesAutoresizingMaskIntoConstraints = false
self.allowsMultipleSelection = multiply
self.separatorInset = separatorInset
self.tableFooterView = UIView()
self.showsVerticalScrollIndicator = false
self.estimatedSectionFooterHeight = 0
self.estimatedSectionHeaderHeight = 0
if let color = separatorColor {
self.separatorColor = color
}
}
}
|
mit
|
5b311482b458147618dffc450e17ec0c
| 32.818182 | 139 | 0.689964 | 5.190698 | false | false | false | false |
huonw/swift
|
test/SILGen/accessors.swift
|
1
|
11467
|
// RUN: %target-swift-emit-silgen -module-name accessors -Xllvm -sil-full-demangle -enable-sil-ownership %s | %FileCheck %s
// Hold a reference to do to magically become non-POD.
class Reference {}
// A struct with a non-mutating getter and a mutating setter.
struct OrdinarySub {
var ptr = Reference()
subscript(value: Int) -> Int {
get { return value }
set {}
}
}
class A { var array = OrdinarySub() }
func index0() -> Int { return 0 }
func index1() -> Int { return 1 }
func someValidPointer<T>() -> UnsafePointer<T> { fatalError() }
func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() }
// Verify that there is no unnecessary extra copy_value of ref.array.
// rdar://19002913
func test0(_ ref: A) {
ref.array[index0()] = ref.array[index1()]
}
// CHECK: sil hidden @$S9accessors5test0yyAA1ACF : $@convention(thin) (@guaranteed A) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $A):
// CHECK-NEXT: debug_value
// Formal evaluation of LHS.
// CHECK-NEXT: // function_ref accessors.index0() -> Swift.Int
// CHECK-NEXT: [[T0:%.*]] = function_ref @$S9accessors6index0SiyF
// CHECK-NEXT: [[INDEX0:%.*]] = apply [[T0]]()
// Formal evaluation of RHS.
// CHECK-NEXT: // function_ref accessors.index1() -> Swift.Int
// CHECK-NEXT: [[T0:%.*]] = function_ref @$S9accessors6index1SiyF
// CHECK-NEXT: [[INDEX1:%.*]] = apply [[T0]]()
// Formal access to RHS.
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $OrdinarySub
// CHECK-NEXT: [[T0:%.*]] = class_method [[ARG]] : $A, #A.array!getter.1
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[ARG]])
// CHECK-NEXT: store [[T1]] to [init] [[TEMP]]
// CHECK-NEXT: [[T0:%.*]] = load_borrow [[TEMP]]
// CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.getter : (Swift.Int) -> Swift.Int
// CHECK-NEXT: [[T1:%.*]] = function_ref @$S9accessors11OrdinarySubVyS2icig
// CHECK-NEXT: [[VALUE:%.*]] = apply [[T1]]([[INDEX1]], [[T0]])
// CHECK-NEXT: end_borrow [[T0]] from [[TEMP]]
// CHECK-NEXT: destroy_addr [[TEMP]]
// Formal access to LHS.
// CHECK-NEXT: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK-NEXT: [[BUFFER:%.*]] = alloc_stack $OrdinarySub
// CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER]]
// CHECK-NEXT: [[T1:%.*]] = class_method [[ARG]] : $A, #A.array!materializeForSet.1
// CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE]], [[ARG]])
// CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0
// CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1
// CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
// CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*OrdinarySub on [[ARG]] : $A
// CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.setter : (Swift.Int) -> Swift.Int
// CHECK-NEXT: [[SETTER:%.*]] = function_ref @$S9accessors11OrdinarySubVyS2icis
// CHECK-NEXT: apply [[SETTER]]([[VALUE]], [[INDEX0]], [[ADDR]])
// CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]]
// CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : @trivial $Builtin.RawPointer):
// CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed A, @thick A.Type) -> ()
// CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $A
// CHECK-NEXT: store_borrow [[ARG]] to [[TEMP2]] : $*A
// CHECK-NEXT: [[T0:%.*]] = metatype $@thick A.Type
// CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*OrdinarySub to $Builtin.RawPointer
// CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE]], [[TEMP2]], [[T0]])
// CHECK-NEXT: dealloc_stack [[TEMP2]]
// CHECK-NEXT: br [[CONT]]
// CHECK: [[CONT]]:
// CHECK-NEXT: dealloc_stack [[BUFFER]]
// CHECK-NEXT: dealloc_stack [[STORAGE]]
// CHECK-NEXT: dealloc_stack [[TEMP]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// A struct with a mutating getter and a mutating setter.
struct MutatingSub {
var ptr = Reference()
subscript(value: Int) -> Int {
mutating get { return value }
set {}
}
}
class B { var array = MutatingSub() }
func test1(_ ref: B) {
ref.array[index0()] = ref.array[index1()]
}
// CHECK-LABEL: sil hidden @$S9accessors5test1yyAA1BCF : $@convention(thin) (@guaranteed B) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $B):
// CHECK-NEXT: debug_value
// Formal evaluation of LHS.
// CHECK-NEXT: // function_ref accessors.index0() -> Swift.Int
// CHECK-NEXT: [[T0:%.*]] = function_ref @$S9accessors6index0SiyF
// CHECK-NEXT: [[INDEX0:%.*]] = apply [[T0]]()
// Formal evaluation of RHS.
// CHECK-NEXT: // function_ref accessors.index1() -> Swift.Int
// CHECK-NEXT: [[T0:%.*]] = function_ref @$S9accessors6index1SiyF
// CHECK-NEXT: [[INDEX1:%.*]] = apply [[T0]]()
// Formal access to RHS.
// CHECK-NEXT: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK-NEXT: [[BUFFER:%.*]] = alloc_stack $MutatingSub
// CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER]]
// CHECK-NEXT: [[T1:%.*]] = class_method [[ARG]] : $B, #B.array!materializeForSet.1
// CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE]], [[ARG]])
// CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0
// CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1
// CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
// CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*MutatingSub on [[ARG]] : $B
// CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.getter : (Swift.Int) -> Swift.Int
// CHECK-NEXT: [[T0:%.*]] = function_ref @$S9accessors11MutatingSubVyS2icig : $@convention(method) (Int, @inout MutatingSub) -> Int
// CHECK-NEXT: [[VALUE:%.*]] = apply [[T0]]([[INDEX1]], [[ADDR]])
// CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]]
//
// CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : @trivial $Builtin.RawPointer):
// CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed B, @thick B.Type) -> ()
// CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $B
// CHECK-NEXT: store_borrow [[ARG]] to [[TEMP2]] : $*B
// CHECK-NEXT: [[T0:%.*]] = metatype $@thick B.Type
// CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*MutatingSub to $Builtin.RawPointer
// CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE]], [[TEMP2]], [[T0]])
// CHECK-NEXT: dealloc_stack [[TEMP2]]
// CHECK-NEXT: br [[CONT]]
//
// CHECK: [[CONT]]:
// Formal access to LHS.
// CHECK-NEXT: [[STORAGE2:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK-NEXT: [[BUFFER2:%.*]] = alloc_stack $MutatingSub
// CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER2]]
// CHECK-NEXT: [[T1:%.*]] = class_method [[ARG]] : $B, #B.array!materializeForSet.1
// CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE2]], [[ARG]])
// CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0
// CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1
// CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
// CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*MutatingSub on [[ARG]] : $B
// CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.setter : (Swift.Int) -> Swift.Int
// CHECK-NEXT: [[SETTER:%.*]] = function_ref @$S9accessors11MutatingSubVyS2icis : $@convention(method) (Int, Int, @inout MutatingSub) -> ()
// CHECK-NEXT: apply [[SETTER]]([[VALUE]], [[INDEX0]], [[ADDR]])
// CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]]
//
// CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : @trivial $Builtin.RawPointer):
// CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed B, @thick B.Type) -> ()
// CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $B
// CHECK-NEXT: store_borrow [[ARG]] to [[TEMP2]] : $*B
// CHECK-NEXT: [[T0:%.*]] = metatype $@thick B.Type
// CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*MutatingSub to $Builtin.RawPointer
// CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE2]], [[TEMP2]], [[T0]])
// CHECK-NEXT: dealloc_stack [[TEMP2]]
// CHECK-NEXT: br [[CONT]]
//
// CHECK: [[CONT]]:
// CHECK-NEXT: dealloc_stack [[BUFFER2]]
// CHECK-NEXT: dealloc_stack [[STORAGE2]]
// CHECK-NEXT: dealloc_stack [[BUFFER]]
// CHECK-NEXT: dealloc_stack [[STORAGE]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
struct RecInner {
subscript(i: Int) -> Int {
get { return i }
}
}
struct RecOuter {
var inner : RecInner {
unsafeAddress { return someValidPointer() }
unsafeMutableAddress { return someValidPointer() }
}
}
func test_rec(_ outer: inout RecOuter) -> Int {
return outer.inner[0]
}
// This uses the immutable addressor.
// CHECK: sil hidden @$S9accessors8test_recySiAA8RecOuterVzF : $@convention(thin) (@inout RecOuter) -> Int {
// CHECK: function_ref @$S9accessors8RecOuterV5innerAA0B5InnerVvlu : $@convention(method) (RecOuter) -> UnsafePointer<RecInner>
struct Rec2Inner {
subscript(i: Int) -> Int {
mutating get { return i }
}
}
struct Rec2Outer {
var inner : Rec2Inner {
unsafeAddress { return someValidPointer() }
unsafeMutableAddress { return someValidPointer() }
}
}
func test_rec2(_ outer: inout Rec2Outer) -> Int {
return outer.inner[0]
}
// This uses the mutable addressor.
// CHECK: sil hidden @$S9accessors9test_rec2ySiAA9Rec2OuterVzF : $@convention(thin) (@inout Rec2Outer) -> Int {
// CHECK: function_ref @$S9accessors9Rec2OuterV5innerAA0B5InnerVvau : $@convention(method) (@inout Rec2Outer) -> UnsafeMutablePointer<Rec2Inner>
struct Foo {
private subscript(privateSubscript x: Void) -> Void {
// CHECK-DAG: sil private @$S9accessors3FooV16privateSubscriptyyt_tc33_D7F31B09EE737C687DC580B2014D759CLlig : $@convention(method) (Foo) -> () {
get {}
}
private(set) subscript(withPrivateSet x: Void) -> Void {
// CHECK-DAG: sil hidden @$S9accessors3FooV14withPrivateSetyyt_tcig : $@convention(method) (Foo) -> () {
get {}
// CHECK-DAG: sil private @$S9accessors3FooV14withPrivateSetyyt_tcis : $@convention(method) (@inout Foo) -> () {
set {}
}
subscript(withNestedClass x: Void) -> Void {
// Check for initializer of NestedClass
// CHECK-DAG: sil private @$S9accessors3FooV15withNestedClassyyt_tcig0dE0L_CAFycfc : $@convention(method) (@owned NestedClass) -> @owned NestedClass {
class NestedClass {}
}
// CHECK-DAG: sil private @$S9accessors3FooV15privateVariable33_D7F31B09EE737C687DC580B2014D759CLLytvg : $@convention(method) (Foo) -> () {
private var privateVariable: Void {
return
}
private(set) var variableWithPrivateSet: Void {
// CHECK-DAG: sil hidden @$S9accessors3FooV22variableWithPrivateSetytvg : $@convention(method) (Foo) -> () {
get {}
// CHECK-DAG: sil private @$S9accessors3FooV22variableWithPrivateSetytvs : $@convention(method) (@inout Foo) -> () {
set {}
}
var propertyWithNestedClass: Void {
// Check for initializer of NestedClass
// CHECK-DAG: sil private @$S9accessors3FooV23propertyWithNestedClassytvg0eF0L_CAFycfc : $@convention(method) (@owned NestedClass) -> @owned NestedClass {
class NestedClass {}
}
}
|
apache-2.0
|
56ecf911de198ef5552053a46d36257e
| 48.004274 | 216 | 0.640621 | 3.283792 | false | false | false | false |
PlugForMac/HypeMachineAPI
|
Tests/ArtistTests.swift
|
1
|
981
|
//
// ArtistTests.swift
// HypeMachineAPI
//
// Created by Alex Marchant on 5/11/15.
// Copyright (c) 2015 Plug. All rights reserved.
//
import Cocoa
import XCTest
@testable import HypeMachineAPI
class ArtistTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testBuildArtist() {
let json: AnyObject = Helpers.loadJSONFixtureFile("Artist", ofType: "json")
let artist = HypeMachineAPI.Artist(response: HTTPURLResponse(), representation: json)
XCTAssertNotNil(artist)
XCTAssert(artist!.name == "ducktails")
}
func testBuildArtistCollection() {
let json: AnyObject = Helpers.loadJSONFixtureFile("Artists", ofType: "json")
let artists = HypeMachineAPI.Artist.collection(from: HTTPURLResponse(), withRepresentation: json)
XCTAssertNotNil(artists)
XCTAssert(artists.count == 3)
}
}
|
mit
|
e599cb5c46311dde9b8657d6022e9744
| 26.25 | 105 | 0.651376 | 4.321586 | false | true | false | false |
StYaphet/firefox-ios
|
Client/Frontend/AuthenticationManager/SensitiveViewController.swift
|
7
|
4437
|
/* 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 SnapKit
import SwiftKeychainWrapper
enum AuthenticationState {
case notAuthenticating
case presenting
}
class SensitiveViewController: UIViewController {
var promptingForTouchID: Bool = false
var backgroundedBlur: UIImageView?
var authState: AuthenticationState = .notAuthenticating
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(checkIfUserRequiresValidation), name: UIApplication.willEnterForegroundNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(checkIfUserRequiresValidation), name: UIApplication.didBecomeActiveNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(blurContents), name: UIApplication.willResignActiveNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(hideLogins), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
@objc func checkIfUserRequiresValidation() {
guard authState != .presenting else {
return
}
presentedViewController?.dismiss(animated: false, completion: nil)
guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo(), authInfo.requiresValidation() else {
removeBackgroundedBlur()
return
}
promptingForTouchID = true
AppAuthenticator.presentAuthenticationUsingInfo(authInfo,
touchIDReason: AuthenticationStrings.loginsTouchReason,
success: {
self.promptingForTouchID = false
self.authState = .notAuthenticating
self.removeBackgroundedBlur()
},
cancel: {
self.view.alpha = 0
self.promptingForTouchID = false
self.authState = .notAuthenticating
_ = self.navigationController?.popToRootViewController(animated: false)
self.dismiss(animated: false)
},
fallback: {
self.promptingForTouchID = false
AppAuthenticator.presentPasscodeAuthentication(self.navigationController).uponQueue(.main) { isOk in
if isOk {
self.removeBackgroundedBlur()
self.navigationController?.dismiss(animated: true, completion: nil)
self.authState = .notAuthenticating
} else {
// On cancel, the login list can appear for a split-second, set the view to transparent to avoid this.
self.view.alpha = 0
_ = self.navigationController?.popToRootViewController(animated: false)
self.dismiss(animated: false)
self.authState = .notAuthenticating
}
}
}
)
authState = .presenting
}
@objc func hideLogins() {
_ = self.navigationController?.popToRootViewController(animated: true)
}
@objc func blurContents() {
if backgroundedBlur == nil {
backgroundedBlur = addBlurredContent()
}
}
func removeBackgroundedBlur() {
if !promptingForTouchID {
backgroundedBlur?.removeFromSuperview()
backgroundedBlur = nil
}
}
fileprivate func addBlurredContent() -> UIImageView? {
guard let snapshot = view.screenshot() else {
return nil
}
let blurredSnapshot = snapshot.applyBlur(withRadius: 10, blurType: BOXFILTER, tintColor: UIColor(white: 1, alpha: 0.3), saturationDeltaFactor: 1.8, maskImage: nil)
let blurView = UIImageView(image: blurredSnapshot)
view.addSubview(blurView)
blurView.snp.makeConstraints { $0.edges.equalTo(self.view) }
view.layoutIfNeeded()
return blurView
}
}
|
mpl-2.0
|
0fcc06c7954df848ab7dcaa3a14587ff
| 38.972973 | 171 | 0.643002 | 5.588161 | false | false | false | false |
Jnosh/swift
|
stdlib/public/Platform/Platform.swift
|
11
|
12967
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
//===----------------------------------------------------------------------===//
// MacTypes.h
//===----------------------------------------------------------------------===//
public var noErr: OSStatus { return 0 }
/// The `Boolean` type declared in MacTypes.h and used throughout Core
/// Foundation.
///
/// The C type is a typedef for `unsigned char`.
@_fixed_layout
public struct DarwinBoolean : ExpressibleByBooleanLiteral {
var _value: UInt8
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool {
return _value != 0
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
}
extension DarwinBoolean : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: boolValue)
}
}
extension DarwinBoolean : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
extension DarwinBoolean : Equatable {}
public func ==(lhs: DarwinBoolean, rhs: DarwinBoolean) -> Bool {
return lhs.boolValue == rhs.boolValue
}
public // COMPILER_INTRINSIC
func _convertBoolToDarwinBoolean(_ x: Bool) -> DarwinBoolean {
return DarwinBoolean(x)
}
public // COMPILER_INTRINSIC
func _convertDarwinBooleanToBool(_ x: DarwinBoolean) -> Bool {
return x.boolValue
}
#endif
//===----------------------------------------------------------------------===//
// sys/errno.h
//===----------------------------------------------------------------------===//
@_silgen_name("_swift_Platform_getErrno")
func _swift_Platform_getErrno() -> Int32
@_silgen_name("_swift_Platform_setErrno")
func _swift_Platform_setErrno(_: Int32)
public var errno : Int32 {
get {
return _swift_Platform_getErrno()
}
set(val) {
return _swift_Platform_setErrno(val)
}
}
//===----------------------------------------------------------------------===//
// stdio.h
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(PS4)
public var stdin : UnsafeMutablePointer<FILE> {
get {
return __stdinp
}
set {
__stdinp = newValue
}
}
public var stdout : UnsafeMutablePointer<FILE> {
get {
return __stdoutp
}
set {
__stdoutp = newValue
}
}
public var stderr : UnsafeMutablePointer<FILE> {
get {
return __stderrp
}
set {
__stderrp = newValue
}
}
public func dprintf(_ fd: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 {
return withVaList(args) { va_args in
vdprintf(Int32(fd), format, va_args)
}
}
public func snprintf(ptr: UnsafeMutablePointer<Int8>, _ len: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 {
return withVaList(args) { va_args in
return vsnprintf(ptr, len, format, va_args)
}
}
#endif
//===----------------------------------------------------------------------===//
// fcntl.h
//===----------------------------------------------------------------------===//
#if !os(Windows) || CYGWIN
@_silgen_name("_swift_Platform_open")
func _swift_Platform_open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t
) -> Int32
#else
@_silgen_name("_swift_Platform_open")
func _swift_Platform_open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: Int32
) -> Int32
#endif
#if !os(Windows) || CYGWIN
@_silgen_name("_swift_Platform_openat")
func _swift_Platform_openat(
_ fd: Int32,
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t
) -> Int32
#endif
public func open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32
) -> Int32 {
return _swift_Platform_open(path, oflag, 0)
}
#if !os(Windows) || CYGWIN
public func open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t
) -> Int32 {
return _swift_Platform_open(path, oflag, mode)
}
public func openat(
_ fd: Int32,
_ path: UnsafePointer<CChar>,
_ oflag: Int32
) -> Int32 {
return _swift_Platform_openat(fd, path, oflag, 0)
}
public func openat(
_ fd: Int32,
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t
) -> Int32 {
return _swift_Platform_openat(fd, path, oflag, mode)
}
#else
public func open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: Int32
) -> Int32 {
return _swift_Platform_open(path, oflag, mode)
}
#endif
#if !os(Windows) || CYGWIN
@_silgen_name("_swift_Platform_fcntl")
internal func _swift_Platform_fcntl(
_ fd: Int32,
_ cmd: Int32,
_ value: Int32
) -> Int32
@_silgen_name("_swift_Platform_fcntlPtr")
internal func _swift_Platform_fcntlPtr(
_ fd: Int32,
_ cmd: Int32,
_ ptr: UnsafeMutableRawPointer
) -> Int32
public func fcntl(
_ fd: Int32,
_ cmd: Int32
) -> Int32 {
return _swift_Platform_fcntl(fd, cmd, 0)
}
public func fcntl(
_ fd: Int32,
_ cmd: Int32,
_ value: Int32
) -> Int32 {
return _swift_Platform_fcntl(fd, cmd, value)
}
public func fcntl(
_ fd: Int32,
_ cmd: Int32,
_ ptr: UnsafeMutableRawPointer
) -> Int32 {
return _swift_Platform_fcntlPtr(fd, cmd, ptr)
}
#endif
#if !os(Windows) || CYGWIN
public var S_IFMT: mode_t { return mode_t(0o170000) }
public var S_IFIFO: mode_t { return mode_t(0o010000) }
public var S_IFCHR: mode_t { return mode_t(0o020000) }
public var S_IFDIR: mode_t { return mode_t(0o040000) }
public var S_IFBLK: mode_t { return mode_t(0o060000) }
public var S_IFREG: mode_t { return mode_t(0o100000) }
public var S_IFLNK: mode_t { return mode_t(0o120000) }
public var S_IFSOCK: mode_t { return mode_t(0o140000) }
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
public var S_IFWHT: mode_t { return mode_t(0o160000) }
#endif
public var S_IRWXU: mode_t { return mode_t(0o000700) }
public var S_IRUSR: mode_t { return mode_t(0o000400) }
public var S_IWUSR: mode_t { return mode_t(0o000200) }
public var S_IXUSR: mode_t { return mode_t(0o000100) }
public var S_IRWXG: mode_t { return mode_t(0o000070) }
public var S_IRGRP: mode_t { return mode_t(0o000040) }
public var S_IWGRP: mode_t { return mode_t(0o000020) }
public var S_IXGRP: mode_t { return mode_t(0o000010) }
public var S_IRWXO: mode_t { return mode_t(0o000007) }
public var S_IROTH: mode_t { return mode_t(0o000004) }
public var S_IWOTH: mode_t { return mode_t(0o000002) }
public var S_IXOTH: mode_t { return mode_t(0o000001) }
public var S_ISUID: mode_t { return mode_t(0o004000) }
public var S_ISGID: mode_t { return mode_t(0o002000) }
public var S_ISVTX: mode_t { return mode_t(0o001000) }
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
public var S_ISTXT: mode_t { return S_ISVTX }
public var S_IREAD: mode_t { return S_IRUSR }
public var S_IWRITE: mode_t { return S_IWUSR }
public var S_IEXEC: mode_t { return S_IXUSR }
#endif
#else
public var S_IFMT: Int32 { return Int32(0xf000) }
public var S_IFREG: Int32 { return Int32(0x8000) }
public var S_IFDIR: Int32 { return Int32(0x4000) }
public var S_IFCHR: Int32 { return Int32(0x2000) }
public var S_IFIFO: Int32 { return Int32(0x1000) }
public var S_IREAD: Int32 { return Int32(0x0100) }
public var S_IWRITE: Int32 { return Int32(0x0080) }
public var S_IEXEC: Int32 { return Int32(0x0040) }
#endif
//===----------------------------------------------------------------------===//
// ioctl.h
//===----------------------------------------------------------------------===//
#if !os(Windows) || CYGWIN
@_silgen_name("_swift_Platform_ioctl")
internal func _swift_Platform_ioctl(
_ fd: CInt,
_ request: UInt,
_ value: CInt
) -> CInt
@_silgen_name("_swift_Platform_ioctlPtr")
internal func _swift_Platform_ioctlPtr(
_ fd: CInt,
_ request: UInt,
_ ptr: UnsafeMutableRawPointer
) -> CInt
public func ioctl(
_ fd: CInt,
_ request: UInt,
_ value: CInt
) -> CInt {
return _swift_Platform_ioctl(fd, request, value)
}
public func ioctl(
_ fd: CInt,
_ request: UInt,
_ ptr: UnsafeMutableRawPointer
) -> CInt {
return _swift_Platform_ioctlPtr(fd, request, ptr)
}
public func ioctl(
_ fd: CInt,
_ request: UInt
) -> CInt {
return _swift_Platform_ioctl(fd, request, 0)
}
#endif
//===----------------------------------------------------------------------===//
// unistd.h
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
@available(*, unavailable, message: "Please use threads or posix_spawn*()")
public func fork() -> Int32 {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "Please use threads or posix_spawn*()")
public func vfork() -> Int32 {
fatalError("unavailable function can't be called")
}
#endif
//===----------------------------------------------------------------------===//
// signal.h
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
public var SIG_DFL: sig_t? { return nil }
public var SIG_IGN: sig_t { return unsafeBitCast(1, to: sig_t.self) }
public var SIG_ERR: sig_t { return unsafeBitCast(-1, to: sig_t.self) }
public var SIG_HOLD: sig_t { return unsafeBitCast(5, to: sig_t.self) }
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
public typealias sighandler_t = __sighandler_t
public var SIG_DFL: sighandler_t? { return nil }
public var SIG_IGN: sighandler_t {
return unsafeBitCast(1, to: sighandler_t.self)
}
public var SIG_ERR: sighandler_t {
return unsafeBitCast(-1, to: sighandler_t.self)
}
public var SIG_HOLD: sighandler_t {
return unsafeBitCast(2, to: sighandler_t.self)
}
#elseif os(Windows)
#if CYGWIN
public typealias sighandler_t = _sig_func_ptr
public var SIG_DFL: sighandler_t? { return nil }
public var SIG_IGN: sighandler_t {
return unsafeBitCast(1, to: sighandler_t.self)
}
public var SIG_ERR: sighandler_t {
return unsafeBitCast(-1, to: sighandler_t.self)
}
public var SIG_HOLD: sighandler_t {
return unsafeBitCast(2, to: sighandler_t.self)
}
#else
public var SIG_DFL: _crt_signal_t? { return nil }
public var SIG_IGN: _crt_signal_t {
return unsafeBitCast(1, to: _crt_signal_t.self)
}
public var SIG_ERR: _crt_signal_t {
return unsafeBitCast(-1, to: _crt_signal_t.self)
}
#endif
#else
internal var _ignore = _UnsupportedPlatformError()
#endif
//===----------------------------------------------------------------------===//
// semaphore.h
//===----------------------------------------------------------------------===//
#if !os(Windows) || CYGWIN
/// The value returned by `sem_open()` in the case of failure.
public var SEM_FAILED: UnsafeMutablePointer<sem_t>? {
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
// The value is ABI. Value verified to be correct for OS X, iOS, watchOS, tvOS.
return UnsafeMutablePointer<sem_t>(bitPattern: -1)
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || CYGWIN
// The value is ABI. Value verified to be correct on Glibc.
return UnsafeMutablePointer<sem_t>(bitPattern: 0)
#else
_UnsupportedPlatformError()
#endif
}
@_silgen_name("_swift_Platform_sem_open2")
internal func _swift_Platform_sem_open2(
_ name: UnsafePointer<CChar>,
_ oflag: Int32
) -> UnsafeMutablePointer<sem_t>?
@_silgen_name("_swift_Platform_sem_open4")
internal func _swift_Platform_sem_open4(
_ name: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t,
_ value: CUnsignedInt
) -> UnsafeMutablePointer<sem_t>?
public func sem_open(
_ name: UnsafePointer<CChar>,
_ oflag: Int32
) -> UnsafeMutablePointer<sem_t>? {
return _swift_Platform_sem_open2(name, oflag)
}
public func sem_open(
_ name: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t,
_ value: CUnsignedInt
) -> UnsafeMutablePointer<sem_t>? {
return _swift_Platform_sem_open4(name, oflag, mode, value)
}
#endif
//===----------------------------------------------------------------------===//
// Misc.
//===----------------------------------------------------------------------===//
// FreeBSD defines extern char **environ differently than Linux.
#if os(FreeBSD) || os(PS4)
@_silgen_name("_swift_FreeBSD_getEnv")
func _swift_FreeBSD_getEnv(
) -> UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>>
public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> {
return _swift_FreeBSD_getEnv().pointee
}
#endif
|
apache-2.0
|
98a8c091ceecce5b0fafc9464a6888a9
| 26.414376 | 127 | 0.59528 | 3.413267 | false | false | false | false |
corderoi/Microblast
|
Microblast/Antigen.swift
|
1
|
1604
|
//
// Antigen.swift
// Microblast
//
// Created by Ian Cordero on 11/13/14.
// Copyright (c) 2014 Ian Cordero. All rights reserved.
//
import Foundation
// Antigen ///////////////////////////////////////////////////////////////////////
class Antigen
{
init(positionX: Int, positionY: Int, virus: Virus, speed: Int = 8, name: String = "pin", animationSequence: [Int] = [1], priority: Int = 1)
{
self.positionX = positionX
self.positionY = positionY
self.virus = virus
directionX = 0
directionY = -1
self.speed = speed
self.priority = priority
self.animationSequence = animationSequence
self.name = name
}
var directionX: Int
var directionY: Int
var positionX: Int
var positionY: Int
var speed: Int
var virus: Virus?
var priority: Int
var name: String
var animationSequence: [Int]
}
class Snow: Antigen
{
init(positionX: Int, positionY: Int, virus: Virus)
{
super.init(positionX: positionX, positionY: positionY, virus: virus, speed: 4, name: "snow", animationSequence: [1, 2, 3, 2])
}
}
class Slash: Antigen
{
init(positionX: Int, positionY: Int, virus: Virus)
{
super.init(positionX: positionX, positionY: positionY, virus: virus, speed: 3, name: "slash", animationSequence: [1, 2, 3, 2], priority: 2)
}
}
class Zap: Antigen
{
init(positionX: Int, positionY: Int, virus: Virus)
{
super.init(positionX: positionX, positionY: positionY, virus: virus, speed: 14, name: "zap", animationSequence: [1, 2, 3, 2])
}
}
|
mit
|
e5aa28b12bfed4e5cba33edddfc0ab6f
| 25.311475 | 147 | 0.598504 | 3.695853 | false | false | false | false |
rporzuc/FindFriends
|
FindFriends/FindFriends/ControlNavigationController.swift
|
1
|
2061
|
//
// ControlNavigationController.swift
// FindFriends
//
// Created by MacOSXRAFAL on 20/11/17.
// Copyright © 2017 MacOSXRAFAL. All rights reserved.
//
import UIKit
var controlNavigationController : ControlNavigationController?
class ControlNavigationController: UINavigationController {
override func viewDidLoad() {
controlNavigationController = self
let reachability = Reachability()
let result = reachability.isConnectedToNetwork()
if result{
let dataManagement = DataManagement.shared
let data = dataManagement.getLoginAndPassword()
if data.login != nil && data.password != nil{
let connectionToServer = ConnectionToServer.shared
connectionToServer.signIn(u_login: data.login!, u_password: data.password!, completion: { (bool, msg) in
if bool{
self.loadMainNavigationController()
}else{
self.loadStartNavigationController()
}
})
}else{
self.loadStartNavigationController()
}
}else{
self.loadStartNavigationController()
}
}
func loadStartNavigationController(){
let BackgroundViewController = self.storyboard?.instantiateViewController(withIdentifier: "BackgroundViewController") as! FindFriendsViewController
_ = self.navigationController?.popToRootViewController(animated: true)
self.setViewControllers([BackgroundViewController], animated: true)
}
func loadMainNavigationController(){
let mainViewController = self.storyboard?.instantiateViewController(withIdentifier: "mainViewController") as! MainViewController
_ = self.navigationController?.popToRootViewController(animated: true)
self.setViewControllers([mainViewController], animated: false)
}
}
|
gpl-3.0
|
ec7968253ff6a98a3c210a746e52e3a1
| 30.212121 | 155 | 0.621359 | 6.167665 | false | false | false | false |
darkbrow/iina
|
iina/AppDelegate.swift
|
1
|
20081
|
//
// AppDelegate.swift
// iina
//
// Created by lhc on 8/7/16.
// Copyright © 2016 lhc. All rights reserved.
//
import Cocoa
import MediaPlayer
import Sparkle
/** Max time interval for repeated `application(_:openFile:)` calls. */
fileprivate let OpenFileRepeatTime = TimeInterval(0.2)
/** Tags for "Open File/URL" menu item when "ALways open file in new windows" is off. Vice versa. */
fileprivate let NormalMenuItemTag = 0
/** Tags for "Open File/URL in New Window" when "Always open URL" when "Open file in new windows" is off. Vice versa. */
fileprivate let AlternativeMenuItemTag = 1
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
/** Whether performed some basic initialization, like bind menu items. */
var isReady = false
/**
Becomes true once `application(_:openFile:)` or `droppedText()` is called.
Mainly used to distinguish normal launches from others triggered by drag-and-dropping files.
*/
var openFileCalled = false
var shouldIgnoreOpenFile = false
/** Cached URL when launching from URL scheme. */
var pendingURL: String?
/** Cached file paths received in `application(_:openFile:)`. */
private var pendingFilesForOpenFile: [String] = []
/** The timer for `OpenFileRepeatTime` and `application(_:openFile:)`. */
private var openFileTimer: Timer?
private var commandLineStatus = CommandLineStatus()
// Windows
lazy var openURLWindow: OpenURLWindowController = OpenURLWindowController()
lazy var aboutWindow: AboutWindowController = AboutWindowController()
lazy var fontPicker: FontPickerWindowController = FontPickerWindowController()
lazy var inspector: InspectorWindowController = InspectorWindowController()
lazy var historyWindow: HistoryWindowController = HistoryWindowController()
lazy var vfWindow: FilterWindowController = {
let w = FilterWindowController()
w.filterType = MPVProperty.vf
return w
}()
lazy var afWindow: FilterWindowController = {
let w = FilterWindowController()
w.filterType = MPVProperty.af
return w
}()
lazy var preferenceWindowController: NSWindowController = {
return PreferenceWindowController(viewControllers: [
PrefGeneralViewController(),
PrefUIViewController(),
PrefCodecViewController(),
PrefSubViewController(),
PrefNetworkViewController(),
PrefControlViewController(),
PrefKeyBindingViewController(),
PrefAdvancedViewController(),
PrefUtilsViewController(),
])
}()
@IBOutlet weak var menuController: MenuController!
@IBOutlet weak var dockMenu: NSMenu!
private func getReady() {
menuController.bindMenuItems()
PlayerCore.loadKeyBindings()
isReady = true
}
// MARK: - App Delegate
func applicationWillFinishLaunching(_ notification: Notification) {
registerUserDefaultValues()
Logger.log("App will launch")
// register for url event
NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(self.handleURLEvent(event:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
// beta channel
if FirstRunManager.isFirstRun(for: .joinBetaChannel) {
let result = Utility.quickAskPanel("beta_channel")
Preference.set(result, for: .receiveBetaUpdate)
}
SUUpdater.shared().feedURL = URL(string: Preference.bool(for: .receiveBetaUpdate) ? AppData.appcastBetaLink : AppData.appcastLink)!
// handle arguments
let arguments = ProcessInfo.processInfo.arguments.dropFirst()
guard arguments.count > 0 else { return }
var iinaArgs: [String] = []
var iinaArgFilenames: [String] = []
var dropNextArg = false
Logger.log("Got arguments \(arguments)")
for arg in arguments {
if dropNextArg {
dropNextArg = false
continue
}
if arg.first == "-" {
if arg[arg.index(after: arg.startIndex)] == "-" {
// args starting with --
iinaArgs.append(arg)
} else {
// args starting with -
dropNextArg = true
}
} else {
// assume args starting with nothing is a filename
iinaArgFilenames.append(arg)
}
}
Logger.log("IINA arguments: \(iinaArgs)")
Logger.log("Filenames from arguments: \(iinaArgFilenames)")
commandLineStatus.parseArguments(iinaArgs)
let (version, build) = Utility.iinaVersion()
print("IINA \(version) Build \(build)")
guard !iinaArgFilenames.isEmpty || commandLineStatus.isStdin else {
print("This binary is not intended for being used as a command line tool. Please use the bundled iina-cli.")
print("Please ignore this message if you are running in a debug environment.")
return
}
shouldIgnoreOpenFile = true
commandLineStatus.isCommandLine = true
commandLineStatus.filenames = iinaArgFilenames
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
Logger.log("App launched")
if !isReady {
getReady()
}
// show alpha in color panels
NSColorPanel.shared.showsAlpha = true
// other initializations at App level
if #available(macOS 10.12.2, *) {
NSApp.isAutomaticCustomizeTouchBarMenuItemEnabled = false
NSWindow.allowsAutomaticWindowTabbing = false
}
if #available(macOS 10.13, *) {
if RemoteCommandController.useSystemMediaControl {
Logger.log("Setting up MediaPlayer integration")
RemoteCommandController.setup()
NowPlayingInfoManager.updateState(.unknown)
}
}
let _ = PlayerCore.first
// if have pending open request
if let url = pendingURL {
parsePendingURL(url)
}
if !commandLineStatus.isCommandLine {
// check whether showing the welcome window after 0.1s
Timer.scheduledTimer(timeInterval: TimeInterval(0.1), target: self, selector: #selector(self.checkForShowingInitialWindow), userInfo: nil, repeats: false)
} else {
var lastPlayerCore: PlayerCore? = nil
let getNewPlayerCore = { () -> PlayerCore in
let pc = PlayerCore.newPlayerCore
self.commandLineStatus.assignMPVArguments(to: pc)
lastPlayerCore = pc
return pc
}
if commandLineStatus.isStdin {
getNewPlayerCore().openURLString("-")
} else {
let validFileURLs: [URL] = commandLineStatus.filenames.compactMap { filename in
if Regex.url.matches(filename) {
return URL(string: filename.addingPercentEncoding(withAllowedCharacters: .urlAllowed) ?? filename)
} else {
return FileManager.default.fileExists(atPath: filename) ? URL(fileURLWithPath: filename) : nil
}
}
if commandLineStatus.openSeparateWindows {
validFileURLs.forEach { url in
getNewPlayerCore().openURL(url)
}
} else {
getNewPlayerCore().openURLs(validFileURLs)
}
}
// enter PIP
if #available(macOS 10.12, *), let pc = lastPlayerCore, commandLineStatus.enterPIP {
pc.mainWindow.enterPIP()
}
}
NSRunningApplication.current.activate(options: [.activateIgnoringOtherApps, .activateAllWindows])
NSApplication.shared.servicesProvider = self
}
/** Show welcome window if `application(_:openFile:)` wasn't called, i.e. launched normally. */
@objc
func checkForShowingInitialWindow() {
if !openFileCalled {
showWelcomeWindow()
}
}
private func showWelcomeWindow(checkingForUpdatedData: Bool = false) {
let actionRawValue = Preference.integer(for: .actionAfterLaunch)
let action: Preference.ActionAfterLaunch = Preference.ActionAfterLaunch(rawValue: actionRawValue) ?? .welcomeWindow
switch action {
case .welcomeWindow:
let window = PlayerCore.first.initialWindow!
window.showWindow(nil)
if checkingForUpdatedData {
window.loadLastPlaybackInfo()
window.reloadData()
}
case .openPanel:
openFile(self)
default:
break
}
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
guard PlayerCore.active.mainWindow.loaded || PlayerCore.active.initialWindow.loaded else { return false }
guard !PlayerCore.active.mainWindow.isWindowHidden else { return false }
return Preference.bool(for: .quitWhenNoOpenedWindow)
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
Logger.log("App should terminate")
for pc in PlayerCore.playerCores {
pc.terminateMPV()
}
return .terminateNow
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
guard !flag else { return true }
Logger.log("Handle reopen")
showWelcomeWindow(checkingForUpdatedData: true)
return true
}
func applicationWillTerminate(_ notification: Notification) {
Logger.log("App will terminate")
Logger.closeLogFile()
}
/**
When dragging multiple files to App icon, cocoa will simply call this method repeatedly.
Therefore we must cache all possible calls and handle them together.
*/
func application(_ sender: NSApplication, openFile filename: String) -> Bool {
openFileCalled = true
openFileTimer?.invalidate()
pendingFilesForOpenFile.append(filename)
openFileTimer = Timer.scheduledTimer(timeInterval: OpenFileRepeatTime, target: self, selector: #selector(handleOpenFile), userInfo: nil, repeats: false)
return true
}
/** Handle pending file paths if `application(_:openFile:)` not being called again in `OpenFileRepeatTime`. */
@objc
func handleOpenFile() {
if !isReady {
getReady()
}
// if launched from command line, should ignore openFile once
if shouldIgnoreOpenFile {
shouldIgnoreOpenFile = false
return
}
// open pending files
let urls = pendingFilesForOpenFile.map { URL(fileURLWithPath: $0) }
pendingFilesForOpenFile.removeAll()
if PlayerCore.activeOrNew.openURLs(urls) == 0 {
Utility.showAlert("nothing_to_open")
}
}
// MARK: - Accept dropped string and URL
@objc
func droppedText(_ pboard: NSPasteboard, userData:String, error: NSErrorPointer) {
if let url = pboard.string(forType: .string) {
openFileCalled = true
PlayerCore.active.openURLString(url)
}
}
// MARK: - Dock menu
func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
return dockMenu
}
// MARK: - URL Scheme
@objc func handleURLEvent(event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
openFileCalled = true
guard let url = event.paramDescriptor(forKeyword: keyDirectObject)?.stringValue else { return }
Logger.log("URL event: \(url)")
if isReady {
parsePendingURL(url)
} else {
pendingURL = url
}
}
/**
Parses the pending iina:// url.
- Parameter url: the pending URL.
- Note:
The iina:// URL scheme currently supports the following actions:
__/open__
- `url`: a url or string to open.
- `new_window`: 0 or 1 (default) to indicate whether open the media in a new window.
- `enqueue`: 0 (default) or 1 to indicate whether to add the media to the current playlist.
- `full_screen`: 0 (default) or 1 to indicate whether open the media and enter fullscreen.
- `pip`: 0 (default) or 1 to indicate whether open the media and enter pip.
- `mpv_*`: additional mpv options to be passed. e.g. `mpv_volume=20`.
Options starting with `no-` are not supported.
*/
private func parsePendingURL(_ url: String) {
Logger.log("Parsing URL \(url)")
guard let parsed = URLComponents(string: url) else {
Logger.log("Cannot parse URL using URLComponents", level: .warning)
return
}
// handle url scheme
guard let host = parsed.host else { return }
if host == "open" || host == "weblink" {
// open a file or link
guard let queries = parsed.queryItems else { return }
let queryDict = [String: String](uniqueKeysWithValues: queries.map { ($0.name, $0.value ?? "") })
// url
guard let urlValue = queryDict["url"], !urlValue.isEmpty else {
Logger.log("Cannot find parameter \"url\", stopped")
return
}
// new_window
let player: PlayerCore
if let newWindowValue = queryDict["new_window"], newWindowValue == "1" {
player = PlayerCore.newPlayerCore
} else {
player = PlayerCore.active
}
// enqueue
if let enqueueValue = queryDict["enqueue"], enqueueValue == "1", !PlayerCore.lastActive.info.playlist.isEmpty {
PlayerCore.lastActive.addToPlaylist(urlValue)
PlayerCore.lastActive.postNotification(.iinaPlaylistChanged)
PlayerCore.lastActive.sendOSD(.addToPlaylist(1))
} else {
player.openURLString(urlValue)
}
// presentation options
if let fsValue = queryDict["full_screen"], fsValue == "1" {
// full_screeen
player.mpv.setFlag(MPVOption.Window.fullscreen, true)
} else if let pipValue = queryDict["pip"], pipValue == "1" {
// pip
if #available(macOS 10.12, *) {
player.mainWindow.enterPIP()
}
}
// mpv options
for query in queries {
if query.name.hasPrefix("mpv_") {
let mpvOptionName = String(query.name.dropFirst(4))
guard let mpvOptionValue = query.value else { continue }
Logger.log("Setting \(mpvOptionName) to \(mpvOptionValue)")
player.mpv.setString(mpvOptionName, mpvOptionValue)
}
}
Logger.log("Finished URL scheme handling")
}
}
// MARK: - Menu actions
@IBAction func openFile(_ sender: AnyObject) {
Logger.log("Menu - Open file")
let panel = NSOpenPanel()
panel.title = NSLocalizedString("alert.choose_media_file.title", comment: "Choose Media File")
panel.canCreateDirectories = false
panel.canChooseFiles = true
panel.canChooseDirectories = true
panel.allowsMultipleSelection = true
if panel.runModal() == .OK {
if Preference.bool(for: .recordRecentFiles) {
for url in panel.urls {
NSDocumentController.shared.noteNewRecentDocumentURL(url)
}
}
let isAlternative = (sender as? NSMenuItem)?.tag == AlternativeMenuItemTag
let playerCore = PlayerCore.activeOrNewForMenuAction(isAlternative: isAlternative)
if playerCore.openURLs(panel.urls) == 0 {
Utility.showAlert("nothing_to_open")
}
}
}
@IBAction func openURL(_ sender: AnyObject) {
Logger.log("Menu - Open URL")
openURLWindow.isAlternativeAction = sender.tag == AlternativeMenuItemTag
openURLWindow.showWindow(nil)
openURLWindow.resetFields()
}
@IBAction func menuNewWindow(_ sender: Any) {
PlayerCore.newPlayerCore.initialWindow.showWindow(nil)
}
@IBAction func menuOpenScreenshotFolder(_ sender: NSMenuItem) {
let screenshotPath = Preference.string(for: .screenshotFolder)!
let absoluteScreenshotPath = NSString(string: screenshotPath).expandingTildeInPath
let url = URL(fileURLWithPath: absoluteScreenshotPath, isDirectory: true)
NSWorkspace.shared.open(url)
}
@IBAction func menuSelectAudioDevice(_ sender: NSMenuItem) {
if let name = sender.representedObject as? String {
PlayerCore.active.setAudioDevice(name)
}
}
@IBAction func showPreferences(_ sender: AnyObject) {
preferenceWindowController.showWindow(self)
}
@IBAction func showVideoFilterWindow(_ sender: AnyObject) {
vfWindow.showWindow(self)
}
@IBAction func showAudioFilterWindow(_ sender: AnyObject) {
afWindow.showWindow(self)
}
@IBAction func showAboutWindow(_ sender: AnyObject) {
aboutWindow.showWindow(self)
}
@IBAction func showHistoryWindow(_ sender: AnyObject) {
historyWindow.showWindow(self)
}
@IBAction func helpAction(_ sender: AnyObject) {
NSWorkspace.shared.open(URL(string: AppData.wikiLink)!)
}
@IBAction func githubAction(_ sender: AnyObject) {
NSWorkspace.shared.open(URL(string: AppData.githubLink)!)
}
@IBAction func websiteAction(_ sender: AnyObject) {
NSWorkspace.shared.open(URL(string: AppData.websiteLink)!)
}
private func registerUserDefaultValues() {
UserDefaults.standard.register(defaults: [String: Any](uniqueKeysWithValues: Preference.defaultPreference.map { ($0.0.rawValue, $0.1) }))
}
}
struct CommandLineStatus {
var isCommandLine = false
var isStdin = false
var openSeparateWindows = false
var enterPIP = false
var mpvArguments: [(String, String)] = []
var iinaArguments: [(String, String)] = []
var filenames: [String] = []
mutating func parseArguments(_ args: [String]) {
mpvArguments.removeAll()
iinaArguments.removeAll()
for arg in args {
let splitted = arg.dropFirst(2).split(separator: "=", maxSplits: 1)
let name = String(splitted[0])
if (name.hasPrefix("mpv-")) {
// mpv args
if splitted.count <= 1 {
mpvArguments.append((String(name.dropFirst(4)), "yes"))
} else {
mpvArguments.append((String(name.dropFirst(4)), String(splitted[1])))
}
} else {
// other args
if splitted.count <= 1 {
iinaArguments.append((name, "yes"))
} else {
iinaArguments.append((name, String(splitted[1])))
}
if name == "stdin" {
isStdin = true
}
if name == "separate-windows" {
openSeparateWindows = true
}
if name == "pip" {
enterPIP = true
}
}
}
}
func assignMPVArguments(to playerCore: PlayerCore) {
for arg in mpvArguments {
playerCore.mpv.setString(arg.0, arg.1)
}
}
}
@available(macOS 10.13, *)
class RemoteCommandController {
static let remoteCommand = MPRemoteCommandCenter.shared()
static var useSystemMediaControl: Bool = Preference.bool(for: .useMediaKeys)
static func setup() {
remoteCommand.playCommand.addTarget { _ in
PlayerCore.lastActive.resume()
return .success
}
remoteCommand.pauseCommand.addTarget { _ in
PlayerCore.lastActive.pause()
return .success
}
remoteCommand.togglePlayPauseCommand.addTarget { _ in
PlayerCore.lastActive.togglePause()
return .success
}
remoteCommand.stopCommand.addTarget { _ in
PlayerCore.lastActive.stop()
return .success
}
remoteCommand.nextTrackCommand.addTarget { _ in
PlayerCore.lastActive.navigateInPlaylist(nextMedia: true)
return .success
}
remoteCommand.previousTrackCommand.addTarget { _ in
PlayerCore.lastActive.navigateInPlaylist(nextMedia: false)
return .success
}
remoteCommand.changeRepeatModeCommand.addTarget { _ in
PlayerCore.lastActive.togglePlaylistLoop()
return .success
}
remoteCommand.changeShuffleModeCommand.isEnabled = false
// remoteCommand.changeShuffleModeCommand.addTarget {})
remoteCommand.changePlaybackRateCommand.supportedPlaybackRates = [0.5, 1, 1.5, 2]
remoteCommand.changePlaybackRateCommand.addTarget { event in
PlayerCore.lastActive.setSpeed(Double((event as! MPChangePlaybackRateCommandEvent).playbackRate))
return .success
}
remoteCommand.skipForwardCommand.preferredIntervals = [15]
remoteCommand.skipForwardCommand.addTarget { event in
PlayerCore.lastActive.seek(relativeSecond: (event as! MPSkipIntervalCommandEvent).interval, option: .exact)
return .success
}
remoteCommand.skipBackwardCommand.preferredIntervals = [15]
remoteCommand.skipBackwardCommand.addTarget { event in
PlayerCore.lastActive.seek(relativeSecond: -(event as! MPSkipIntervalCommandEvent).interval, option: .exact)
return .success
}
remoteCommand.changePlaybackPositionCommand.addTarget { event in
PlayerCore.lastActive.seek(absoluteSecond: (event as! MPChangePlaybackPositionCommandEvent).positionTime)
return .success
}
}
}
|
gpl-3.0
|
d2d25b2833b628e9aca13c957b1d5c50
| 32.080725 | 206 | 0.684114 | 4.550193 | false | false | false | false |
chrisamanse/RadioButton
|
RadioButton/RadioButton.swift
|
1
|
3878
|
//
// RadioButton.swift
// RadioButton
//
// Created by Joe Amanse on 19/11/2015.
// Copyright © 2015 Joe Christopher Paul Amanse. All rights reserved.
//
import UIKit
@IBDesignable
public class RadioButton: UIButton {
// MARK: Circle properties
internal var circleLayer = CAShapeLayer()
internal var fillCircleLayer = CAShapeLayer()
@IBInspectable public var circleColor: UIColor = UIColor.redColor() {
didSet {
circleLayer.strokeColor = circleColor.CGColor
}
}
@IBInspectable public var fillCircleColor: UIColor = UIColor.greenColor() {
didSet {
loadFillCircleState()
}
}
@IBInspectable public var circleLineWidth: CGFloat = 2.0 {
didSet {
layoutCircleLayers()
}
}
@IBInspectable public var fillCircleGap: CGFloat = 2.0 {
didSet {
layoutCircleLayers()
}
}
internal var circleRadius: CGFloat {
let width = bounds.width
let height = bounds.height
let length = width > height ? height : width
return (length - circleLineWidth) / 2
}
private var circleFrame: CGRect {
let width = bounds.width
let height = bounds.height
let radius = circleRadius
let x: CGFloat
let y: CGFloat
if width > height {
y = circleLineWidth / 2
x = (width / 2) - radius
} else {
x = circleLineWidth / 2
y = (height / 2) - radius
}
let diameter = 2 * radius
return CGRect(x: x, y: y, width: diameter, height: diameter)
}
private var circlePath: UIBezierPath {
return UIBezierPath(ovalInRect: circleFrame)
}
private var fillCirclePath: UIBezierPath {
let trueGap = fillCircleGap + (circleLineWidth / 2)
return UIBezierPath(ovalInRect: CGRectInset(circleFrame, trueGap, trueGap))
}
// MARK: Initialization
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
customInitialization()
}
override public init(frame: CGRect) {
super.init(frame: frame)
customInitialization()
}
private func customInitialization() {
circleLayer.frame = bounds
circleLayer.lineWidth = circleLineWidth
circleLayer.fillColor = UIColor.clearColor().CGColor
circleLayer.strokeColor = circleColor.CGColor
layer.addSublayer(circleLayer)
fillCircleLayer.frame = bounds
fillCircleLayer.lineWidth = circleLineWidth
fillCircleLayer.fillColor = UIColor.clearColor().CGColor
fillCircleLayer.strokeColor = UIColor.clearColor().CGColor
layer.addSublayer(fillCircleLayer)
loadFillCircleState()
}
// MARK: Layout
override public func layoutSubviews() {
super.layoutSubviews()
layoutCircleLayers()
}
private func layoutCircleLayers() {
circleLayer.frame = bounds
circleLayer.lineWidth = circleLineWidth
circleLayer.path = circlePath.CGPath
fillCircleLayer.frame = bounds
fillCircleLayer.lineWidth = circleLineWidth
fillCircleLayer.path = fillCirclePath.CGPath
}
// MARK: Selection
override public var selected: Bool {
didSet {
loadFillCircleState()
}
}
// MARK: Custom
private func loadFillCircleState() {
if self.selected {
fillCircleLayer.fillColor = fillCircleColor.CGColor
} else {
fillCircleLayer.fillColor = UIColor.clearColor().CGColor
}
}
// MARK: Interface builder
override public func prepareForInterfaceBuilder() {
customInitialization()
}
}
|
mit
|
34a2e5a55c72351f35f9de680864d41d
| 26.7 | 83 | 0.605623 | 5.347586 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceComponents/Sources/XCTComponentBase/Formatters/FakeAnnouncementDateFormatter.swift
|
1
|
471
|
import ComponentBase
import Foundation
import TestUtilities
public class FakeAnnouncementDateFormatter: AnnouncementDateFormatter {
private var strings = [Date: String]()
public init() {
}
public func string(from date: Date) -> String {
var output = String.random
if let previous = strings[date] {
output = previous
} else {
strings[date] = output
}
return output
}
}
|
mit
|
46909bcab4cd9a42c0b262e8fd5b7cd4
| 18.625 | 71 | 0.598726 | 5.175824 | false | false | false | false |
creisterer-db/SwiftCharts
|
Examples/Examples/CandleStickExample.swift
|
2
|
7487
|
//
// CandleStickExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class CandleStickExample: UIViewController {
private var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
var readFormatter = NSDateFormatter()
readFormatter.dateFormat = "dd.MM.yyyy"
var displayFormatter = NSDateFormatter()
displayFormatter.dateFormat = "MMM dd"
let date = {(str: String) -> NSDate in
return readFormatter.dateFromString(str)!
}
let calendar = NSCalendar.currentCalendar()
let dateWithComponents = {(day: Int, month: Int, year: Int) -> NSDate in
let components = NSDateComponents()
components.day = day
components.month = month
components.year = year
return calendar.dateFromComponents(components)!
}
func filler(date: NSDate) -> ChartAxisValueDate {
let filler = ChartAxisValueDate(date: date, formatter: displayFormatter)
filler.hidden = true
return filler
}
let chartPoints = [
ChartPointCandleStick(date: date("01.10.2015"), formatter: displayFormatter, high: 40, low: 37, open: 39.5, close: 39),
ChartPointCandleStick(date: date("02.10.2015"), formatter: displayFormatter, high: 39.8, low: 38, open: 39.5, close: 38.4),
ChartPointCandleStick(date: date("03.10.2015"), formatter: displayFormatter, high: 43, low: 39, open: 41.5, close: 42.5),
ChartPointCandleStick(date: date("04.10.2015"), formatter: displayFormatter, high: 48, low: 42, open: 44.6, close: 44.5),
ChartPointCandleStick(date: date("05.10.2015"), formatter: displayFormatter, high: 45, low: 41.6, open: 43, close: 44),
ChartPointCandleStick(date: date("06.10.2015"), formatter: displayFormatter, high: 46, low: 42.6, open: 44, close: 46),
ChartPointCandleStick(date: date("07.10.2015"), formatter: displayFormatter, high: 47.5, low: 41, open: 42, close: 45.5),
ChartPointCandleStick(date: date("08.10.2015"), formatter: displayFormatter, high: 50, low: 46, open: 46, close: 49),
ChartPointCandleStick(date: date("09.10.2015"), formatter: displayFormatter, high: 45, low: 41, open: 44, close: 43.5),
ChartPointCandleStick(date: date("11.10.2015"), formatter: displayFormatter, high: 47, low: 35, open: 45, close: 39),
ChartPointCandleStick(date: date("12.10.2015"), formatter: displayFormatter, high: 45, low: 33, open: 44, close: 40),
ChartPointCandleStick(date: date("13.10.2015"), formatter: displayFormatter, high: 43, low: 36, open: 41, close: 38),
ChartPointCandleStick(date: date("14.10.2015"), formatter: displayFormatter, high: 42, low: 31, open: 38, close: 39),
ChartPointCandleStick(date: date("15.10.2015"), formatter: displayFormatter, high: 39, low: 34, open: 37, close: 36),
ChartPointCandleStick(date: date("16.10.2015"), formatter: displayFormatter, high: 35, low: 32, open: 34, close: 33.5),
ChartPointCandleStick(date: date("17.10.2015"), formatter: displayFormatter, high: 32, low: 29, open: 31.5, close: 31),
ChartPointCandleStick(date: date("18.10.2015"), formatter: displayFormatter, high: 31, low: 29.5, open: 29.5, close: 30),
ChartPointCandleStick(date: date("19.10.2015"), formatter: displayFormatter, high: 29, low: 25, open: 25.5, close: 25),
ChartPointCandleStick(date: date("20.10.2015"), formatter: displayFormatter, high: 28, low: 24, open: 26.7, close: 27.5),
ChartPointCandleStick(date: date("21.10.2015"), formatter: displayFormatter, high: 28.5, low: 25.3, open: 26, close: 27),
ChartPointCandleStick(date: date("22.10.2015"), formatter: displayFormatter, high: 30, low: 28, open: 28, close: 30),
ChartPointCandleStick(date: date("25.10.2015"), formatter: displayFormatter, high: 31, low: 29, open: 31, close: 31),
ChartPointCandleStick(date: date("26.10.2015"), formatter: displayFormatter, high: 31.5, low: 29.2, open: 29.6, close: 29.6),
ChartPointCandleStick(date: date("27.10.2015"), formatter: displayFormatter, high: 30, low: 27, open: 29, close: 28.5),
ChartPointCandleStick(date: date("28.10.2015"), formatter: displayFormatter, high: 32, low: 30, open: 31, close: 30.6),
ChartPointCandleStick(date: date("29.10.2015"), formatter: displayFormatter, high: 35, low: 31, open: 31, close: 33)
]
let yValues = 20.stride(through: 55, by: 5).map {ChartAxisValueFloat(CGFloat($0), labelSettings: labelSettings)}
func generateDateAxisValues(month: Int, year: Int) -> [ChartAxisValueDate] {
let date = dateWithComponents(1, month, year)
let calendar = NSCalendar.currentCalendar()
let monthDays = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: date)
return Array(monthDays.toRange()!).map {day in
let date = dateWithComponents(day, month, year)
let axisValue = ChartAxisValueDate(date: date, formatter: displayFormatter, labelSettings: labelSettings)
axisValue.hidden = !(day % 5 == 0)
return axisValue
}
}
let xValues = generateDateAxisValues(10, year: 2015)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
let coordsSpace = ChartCoordsSpaceRightBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let chartPointsLineLayer = ChartCandleStickLayer<ChartPointCandleStick>(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, itemWidth: Env.iPad ? 10 : 5, strokeWidth: Env.iPad ? 1 : 0.6)
let settings = ChartGuideLinesLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, onlyVisibleX: true)
let dividersSettings = ChartDividersLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth, start: Env.iPad ? 7 : 3, end: 0, onlyVisibleValues: true)
let dividersLayer = ChartDividersLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: dividersSettings)
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
dividersLayer,
chartPointsLineLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
|
apache-2.0
|
5bcc05f07cf1289976e85231351dcdfa
| 61.915966 | 220 | 0.649392 | 4.315274 | false | false | false | false |
ello/ello-ios
|
Sources/Views/InterpolatedLoadingView.swift
|
1
|
1371
|
////
/// InterpolatedLoadingView.swift
//
class InterpolatedLoadingView: UIView {
var round = false {
didSet { setNeedsLayout() }
}
private var animating = false
override func didMoveToWindow() {
super.didMoveToWindow()
self.animateIfPossible()
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
self.animateIfPossible()
}
override func layoutSubviews() {
super.layoutSubviews()
if round {
layer.cornerRadius = min(frame.size.width, frame.size.height) / 2
}
else {
layer.cornerRadius = 0
}
}
private func animateIfPossible() {
if !animating && window != nil && superview != nil {
animate()
}
else {
animating = false
}
}
private func animate() {
animating = true
self.layer.removeAnimation(forKey: "interpolate")
let rotate = CABasicAnimation(keyPath: "backgroundColor")
rotate.fromValue = UIColor(hex: 0xDDDDDD).cgColor
rotate.toValue = UIColor(hex: 0xC4C4C4).cgColor
rotate.duration = 3
if round {
rotate.beginTime = 0.25
}
rotate.repeatCount = 1_000_000
rotate.autoreverses = true
self.layer.add(rotate, forKey: "interpolate")
}
}
|
mit
|
57ea96e6483efd80db6ad7221aefcf4e
| 23.052632 | 77 | 0.574763 | 4.810526 | false | false | false | false |
audiokit/AudioKit
|
Sources/AudioKit/Internals/Utilities/Log.swift
|
3
|
1948
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import Foundation
import os
private let subsystem = "io.audiokit"
extension OSLog {
/// Generic AudioKit log
public static let general = OSLog(subsystem: subsystem, category: "general")
/// Generic AudioKit log
public static let settings = OSLog(subsystem: subsystem, category: "settings")
/// AudioKit MIDI related log
public static let midi = OSLog(subsystem: subsystem, category: "midi")
/// Log revolving around finding, reading, and writing files
public static let fileHandling = OSLog(subsystem: subsystem, category: "fileHandling")
}
/// Wrapper for os_log logging system. It currently shows filename, function, and line number,
/// but that might be removed if it shows any negative performance impact (Apple recommends against it).
///
/// Parameters:
/// - items: Output message or variable list of objects
/// - log: One of the log types from the Log struct, defaults to .general
/// - type: OSLogType, defaults to .info
/// - file: Filename from the log message, should not be set explicitly
/// - function: Function enclosing the log message, should not be set explicitly
/// - line: Line number of the log method, should not be set explicitly
///
@inline(__always)
public func Log(_ items: Any?...,
log: OSLog = OSLog.general,
type: OSLogType = .info,
file: String = #file,
function: String = #function,
line: Int = #line) {
guard Settings.enableLogging else { return }
let fileName = (file as NSString).lastPathComponent
let content = (items.map {
String(describing: $0 ?? "nil")
}).joined(separator: " ")
let message = "\(fileName):\(function):\(line):\(content)"
os_log("%s (%s:%s:%d)", log: log, type: type, message, fileName, function, line)
}
|
mit
|
1eedb53b31dd04be2bc57959ea2ed07c
| 37.96 | 104 | 0.659651 | 4.328889 | false | false | false | false |
lijie121210/JIEActionSheet
|
JIEActionSheetDemo/JIEActionSheet.swift
|
1
|
6300
|
//
// JIEActionSheet.swift
// JIEActionSheetDemo
//
// Created by Lijie on 15/9/12.
// Copyright (c) 2015年 HuatengIOT. All rights reserved.
//
import UIKit
extension UIActionSheet: UIActionSheetDelegate {
private struct Sheet {
static var sheet: UIActionSheet?
init(_ sheet: UIActionSheet?) {
Sheet.sheet = sheet
}
}
// 添加的方法
internal func actionSheet(title: String?, cancelTitle: String?, destructiveTitle: String?, actionBlock: ((UIActionSheet, Int) -> Void)?) -> UIActionSheet {
var sheet = UIActionSheet(title: title, delegate: nil, cancelButtonTitle: cancelTitle, destructiveButtonTitle: destructiveTitle)
Sheet(sheet)
Sheet.sheet!.delegate = ActionSheetDelegateHandler.shareActionSheetDelegateHandler()
if let block = actionBlock { self.actionBlock = block }
return Sheet.sheet!
}
internal func actionSheet(title: String?, cancelTitle: String?, destructiveTitle: String?, otherButtonTitles:[String]?, actionBlock: ((UIActionSheet, Int) -> Void)?) -> UIActionSheet {
var sheet = UIActionSheet(title: title, delegate: nil, cancelButtonTitle: cancelTitle, destructiveButtonTitle: destructiveTitle)
if let titles = otherButtonTitles {
for tit in titles {
sheet.addButtonWithTitle(tit)
}
}
Sheet(sheet)
Sheet.sheet!.delegate = ActionSheetDelegateHandler.shareActionSheetDelegateHandler()
if let block = actionBlock { self.actionBlock = block }
return Sheet.sheet!
}
internal func showInCanvas(canvas:AnyObject!) {
if let view: AnyObject = canvas {
if view.isKindOfClass(UIToolbar.self) {
Sheet.sheet!.showFromToolbar(view as! UIToolbar)
}
if view.isKindOfClass(UIBarButtonItem.self) {
Sheet.sheet!.showFromBarButtonItem(view as! UIBarButtonItem, animated: true)
}
if view.isKindOfClass(UITabBar.self) {
Sheet.sheet!.showFromTabBar(view as! UITabBar)
}
if view.isKindOfClass(UIView.self) {
Sheet.sheet!.showInView(view as! UIView)
}
}
}
// MARK: - Properties and Methon
var actionBlock: ((UIActionSheet, Int) -> Void)? {
get {
return ActionSheetDelegateHandler.shareActionSheetDelegateHandler().actionClosure
}
set {
ActionSheetDelegateHandler.shareActionSheetDelegateHandler().actionClosure = newValue
}
}
var willDismissBlock: ((UIActionSheet, Int) -> Void)? {
get {
return ActionSheetDelegateHandler.shareActionSheetDelegateHandler().willDismissClosure
}
set {
ActionSheetDelegateHandler.shareActionSheetDelegateHandler().willDismissClosure = newValue
}
}
var didDismissBlock: ((UIActionSheet, Int) -> Void)? {
get {
return ActionSheetDelegateHandler.shareActionSheetDelegateHandler().didDismissClosure
}
set {
ActionSheetDelegateHandler.shareActionSheetDelegateHandler().didDismissClosure = newValue
}
}
var willPresentBlock: ((UIActionSheet) -> Void)? {
get {
return ActionSheetDelegateHandler.shareActionSheetDelegateHandler().willPresentClosure
}
set {
ActionSheetDelegateHandler.shareActionSheetDelegateHandler().willPresentClosure = newValue
}
}
var didPresentBlock: ((UIActionSheet) -> Void)? {
get {
return ActionSheetDelegateHandler.shareActionSheetDelegateHandler().didPresentClosure
}
set {
ActionSheetDelegateHandler.shareActionSheetDelegateHandler().didPresentClosure = newValue
}
}
var cancelBlock: ((UIActionSheet) -> Void)? {
get {
return ActionSheetDelegateHandler.shareActionSheetDelegateHandler().cancelClosure
}
set {
ActionSheetDelegateHandler.shareActionSheetDelegateHandler().cancelClosure = newValue
}
}
}
class ActionSheetDelegateHandler: NSObject, UIActionSheetDelegate {
// MARK: - Single instance
class func shareActionSheetDelegateHandler() -> ActionSheetDelegateHandler{
struct Singleton{
static var predicate:dispatch_once_t = 0
static var instance:ActionSheetDelegateHandler? = nil
}
dispatch_once(&Singleton.predicate,{
Singleton.instance = ActionSheetDelegateHandler()
}
)
return Singleton.instance!
}
var actionClosure: ((UIActionSheet, Int) -> Void)?
var willDismissClosure: ((UIActionSheet, Int) -> Void)?
var didDismissClosure: ((UIActionSheet, Int) -> Void)?
var cancelClosure: ((UIActionSheet) -> Void)?
var willPresentClosure: ((UIActionSheet) -> Void)?
var didPresentClosure: ((UIActionSheet) -> Void)?
// MARK: - action Sheet Delegate
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
if let closure = self.actionClosure {
closure(actionSheet, buttonIndex)
}
}
func willPresentActionSheet(actionSheet: UIActionSheet) {
if let closure = self.willPresentClosure {
closure(actionSheet)
}
}
func didPresentActionSheet(actionSheet: UIActionSheet) {
if let closure = self.didPresentClosure {
closure(actionSheet)
}
}
func actionSheet(actionSheet: UIActionSheet, willDismissWithButtonIndex buttonIndex: Int) {
if let closure = self.willDismissClosure {
closure(actionSheet, buttonIndex)
}
}
func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {
if let closure = self.didDismissClosure {
closure(actionSheet, buttonIndex)
}
}
func actionSheetCancel(actionSheet: UIActionSheet) {
if let closure = self.cancelClosure {
closure(actionSheet)
}
}
}
|
mit
|
fc91aebdbad22da27f761a31890cb911
| 33.554945 | 188 | 0.628658 | 5.525483 | false | false | false | false |
NghiaTranUIT/Titan
|
TitanCore/TitanCore/PostgreSQLManager.swift
|
2
|
6150
|
//
// PostgreSQLManager.swift
// TitanCore
//
// Created by Nghia Tran on 4/18/17.
// Copyright © 2017 nghiatran. All rights reserved.
//
import Foundation
import SwiftyPostgreSQL
import RxSwift
public enum ConnectState {
case connected
case connecting
case none
}
//
// MARK: - PostgreSQLManager
open class PostgreSQLManager {
//
// MARK: - Singleton
static let shared = PostgreSQLManager()
//
// MARK: - Variable
fileprivate lazy var database: Database = {return Database()}()
fileprivate var currentDbConnection: Connection {
return self.database.connections.first!
}
// Connection State
fileprivate var _connectState = ConnectState.none
public var connectState: ConnectState { return self._connectState}
fileprivate var connectionParam: ConnectionParam!
//
// MARK: - Public
// Open connection
func openConnection(with databaseObj: DatabaseObj) -> Observable<Void> {
// Lock
objc_sync_exit(self._connectState)
defer {objc_sync_exit(self._connectState)}
// Guard
if self._connectState == .connecting {
let error = NSError.errorWithMessage(message: "Database is connecting")
return Observable.error(error)
}
guard self._connectState == .none else {
let error = NSError.errorWithMessage(message: "Database is connected")
return Observable.error(error)
}
// Connect
self._connectState = .connecting
// Observer
return Observable<Void>.create {[unowned self] (observer) -> Disposable in
// Connect postgreSQL on background
let param = databaseObj.buildConnectionParam()
let op = ConnectPostgreOperation(param: param, database: self.database)
op.executeOnBackground(block: { (resultOperation) in
switch resultOperation {
case .failed(let error):
// Error
observer.onError(error)
case .success(let result):
// Check result pointer
guard result.status == ConnectionStatus.CONNECTION_OK else {
let error = NSError.errorWithMessage(message: result.msgError)
self._connectState = .none
observer.onError(error)
return
}
// Check connection pointer
guard let _ = result.connection else {
let error = NSError.errorWithMessage(message: result.msgError)
self._connectState = .none
observer.onError(error)
return
}
// All success
self._connectState = .connected
observer.onNext()
observer.onCompleted()
}
})
// Dispose
return Disposables.create()
}
}
/// Close crrent connection
func closeConnection() -> Observable<Void> {
// Lock
objc_sync_exit(self._connectState)
defer {objc_sync_exit(self._connectState)}
guard self._connectState == .connected else {
let error = NSError.errorWithMessage(message: "No database connected")
return Observable.error(error)
}
// Observer
return Observable<Void>.create {[unowned self] (observer) -> Disposable in
// Close
self.database.closeAllConnection()
self._connectState = .none
// Success
observer.onNext()
observer.onCompleted()
return Disposables.create()
}
}
/// Fetch table schema
func fetchTableSchema() -> Observable<[Table]> {
guard self._connectState == .connected else {
let error = NSError.errorWithMessage(message: "No database connected")
return Observable.error(error)
}
return Observable<[Table]>.create({ observer -> Disposable in
let op = FetchTableSchemaOperation(connect: self.currentDbConnection)
op.executeOnBackground(block: { resultOperation in
switch resultOperation {
case .failed(let error):
// Error
observer.onError(error)
case .success(let result):
// All success
observer.onNext(result)
observer.onCompleted()
}
})
return Disposables.create()
})
}
/// Fetch query
func fetchQuery(_ query: PostgreQuery) -> Observable<QueryResult> {
guard self._connectState == .connected else {
let error = NSError.errorWithMessage(message: "No database connected")
return Observable.error(error)
}
return Observable<QueryResult>.create({ (observer) -> Disposable in
let op = QueryPostgreSQLOperation(connect: self.currentDbConnection, rawQuery: query.rawQuery)
op.executeOnBackground(block: { resultOperation in
switch resultOperation {
case .failed(let error):
// Error
observer.onError(error)
case .success(let result):
// All success
observer.onNext(result)
observer.onCompleted()
}
})
return Disposables.create()
})
}
}
|
mit
|
7895d4a6120caae9a0f8f24065c5d9e7
| 30.695876 | 106 | 0.509026 | 5.850618 | false | false | false | false |
pyconjp/pyconjp-ios
|
PyConJP/Model/Struct/Level.swift
|
1
|
592
|
//
// Level.swift
// PyConJP
//
// Created by Yutaro Muta on 2016/02/22.
// Copyright © 2016 PyCon JP. All rights reserved.
//
import Foundation
struct Level {
let id: Int
let name: String
}
extension Level {
init(dictionary: [String: Any]) {
id = dictionary["id"] as? Int ?? 0
name = dictionary["name"] as? String ?? ""
}
init?(dictionary: [String: Any]?) {
guard let dictionary = dictionary else { return nil }
id = dictionary["id"] as? Int ?? 0
name = dictionary["name"] as? String ?? ""
}
}
|
mit
|
dfeaec5aeec2d0e4ab92fb2a1ad3f87f
| 18.064516 | 61 | 0.548223 | 3.670807 | false | false | false | false |
StartAppsPe/StartAppsKitExtensions
|
Sources/CollectionTypeExtensions.swift
|
1
|
3933
|
//
// ArrayExtensions.swift
// StartApps
//
// Created by Gabriel Lanata on 7/14/15.
// Copyright (c) 2015 StartApps. All rights reserved.
//
import Foundation
extension Collection {
public func performEach(_ action: (Self.Iterator.Element) -> Void) {
for element in self { action(element) }
}
public func find(_ isElement: (Self.Iterator.Element) -> Bool) -> Self.Iterator.Element? {
if let index = firstIndex(where: isElement) {
return self[index]
}
return nil
}
public func shuffled() -> [Iterator.Element] {
var list = Array(self)
list.shuffle()
return list
}
}
extension Collection where Index == Int {
public var randomElement: Self.Iterator.Element? {
return self[Random.new(max: Int(Int64(count))-1)]
}
public func contains(index: Int) -> Bool {
guard index >= 0 else { return false }
guard index < Int(Int64(count)) else { return false }
return true
}
}
extension Collection where Iterator.Element : Equatable {
public func uniqued() -> [Self.Iterator.Element] {
var distinctElements: [Self.Iterator.Element] = []
for element in self {
if !distinctElements.contains(element) {
distinctElements.append(element)
}
}
return distinctElements
}
public func uniqued<T: Equatable>(_ by: (_ element: Self.Iterator.Element) -> T) -> [Self.Iterator.Element] {
var distinctElements: [Self.Iterator.Element] = []
for element in self {
if distinctElements.find({ by($0) == by(element) }) == nil {
distinctElements.append(element)
}
}
return distinctElements
}
}
extension Set {
public mutating func toggle(_ element: Element) -> Bool {
if contains(element) {
remove(element)
return false
} else {
insert(element)
return true
}
}
}
extension Array {
public mutating func popFirst() -> Element? {
if let first = first {
remove(at: 0)
return first
}
return nil
}
}
extension RangeReplaceableCollection where Iterator.Element: Equatable {
public mutating func appendUnique(_ element: Self.Iterator.Element) {
if !contains(element) {
append(element)
}
}
public mutating func appendIfExists(_ element: Self.Iterator.Element?) {
if let element = element {
append(element)
}
}
public mutating func appendUniqueIfExists(_ element: Self.Iterator.Element?) {
if let element = element , !contains(element) {
append(element)
}
}
@discardableResult
public mutating func remove(_ element: Self.Iterator.Element) -> Bool {
if let index = firstIndex(of: element) {
self.remove(at: index)
return true
}
return false
}
@discardableResult
public mutating func toggle(_ element: Self.Iterator.Element) -> Bool {
if let index = firstIndex(of: element) {
self.remove(at: index)
return false
} else {
self.append(element)
return true
}
}
}
//extension Range where Iterator.Element : Comparable {
//
// public func contains(element: Element) -> Bool {
// return self ~= element
// }
//
// public func contains(range: Range) -> Bool {
// return self ~= range
// }
//
//}
//public func ~=<I : Comparable>(pattern: Range<I>, value: Range<I>) -> Bool where I : Comparable {
// return pattern ~= value.lowerBound || pattern ~= value.upperBound || value ~= pattern.lowerBound || value ~= pattern.upperBound
//}
|
mit
|
fae13ccd70398fe82f9d00fb2a65adfb
| 24.050955 | 133 | 0.564709 | 4.424072 | false | false | false | false |
AlphaJian/LarsonApp
|
LarsonApp/LarsonApp/Class/JobDetail/SiteHistory/SiteHistoryTableView.swift
|
1
|
5829
|
//
// JobPartsTableView.swift
// LarsonApp
//
// Created by Jian Zhang on 11/8/16.
// Copyright © 2016 Jian Zhang. All rights reserved.
//
import UIKit
class SiteHistoryTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
var dataItems = NSMutableDictionary()
var buttonTapHandler : ButtonTouchUpBlock?
var partDeleteHandler : CellTouchUpBlock?
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.delegate = self
self.dataSource = self
self.separatorStyle = .none
self.register(SiteHistoryTableViewCell.self, forCellReuseIdentifier: "SiteHistoryTableViewCell")
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
func numberOfSections(in tableView: UITableView) -> Int {
return dataItems.allKeys.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
let arr = dataItems.value(forKey: "location-sitehistories") as! NSArray
return arr.count
} else if section == 1 {
let arr = dataItems.value(forKey: "location-pastNotes") as! NSArray
return arr.count
} else if section == 2 {
let arr = dataItems.value(forKey: "location-equipment") as! NSArray
return arr.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: SiteHistoryTableViewCell = (tableView.dequeueReusableCell(withIdentifier: "SiteHistoryTableViewCell") as? SiteHistoryTableViewCell)!
cell.selectionStyle = .none
cell.clearCell()
cell.frame = CGRect(x: 0, y: 0, width: self.width(), height: 60)
if indexPath.section == 0 {
let arr = dataItems.value(forKey: "location-sitehistories") as! NSArray
let model: SiteHistoryModel = arr[indexPath.row] as! SiteHistoryModel
cell.initSiteUI(model: model, index: indexPath)
} else if indexPath.section == 1 {
let arr = dataItems.value(forKey: "location-pastNotes") as! NSArray
let model: SiteHistoryNotesModel = arr[indexPath.row] as! SiteHistoryNotesModel
cell.initNotesUI(model: model, index: indexPath)
} else if indexPath.section == 2 {
let arr = dataItems.value(forKey: "location-equipment") as! NSArray
let model: SiteHistoryEquipModel = arr[indexPath.row] as! SiteHistoryEquipModel
cell.initEquipUI(model: model, index: indexPath)
}
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Site History"
} else if section == 1 {
return "Past Technician Notes"
} else if section == 2 {
return "Equipment"
} else {
return "aaaa"
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
var height = CGFloat()
if indexPath.section == 0 {
let arr = dataItems.value(forKey: "location-sitehistories") as! NSArray
let model: SiteHistoryModel = arr[indexPath.row] as! SiteHistoryModel
height = model.cellHeight
} else if indexPath.section == 1 {
let arr = dataItems.value(forKey: "location-pastNotes") as! NSArray
let model: SiteHistoryNotesModel = arr[indexPath.row] as! SiteHistoryNotesModel
height = model.cellHeight
} else if indexPath.section == 2 {
let arr = dataItems.value(forKey: "location-equipment") as! NSArray
let model: SiteHistoryEquipModel = arr[indexPath.row] as! SiteHistoryEquipModel
height = model.cellHeight
}
return height
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
let arr = dataItems.value(forKey: "location-sitehistories") as! NSArray
let model: SiteHistoryModel = arr[indexPath.row] as! SiteHistoryModel
model.isOpen = !model.isOpen
model.getCellHeight()
reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
} else if indexPath.section == 1 {
let arr = dataItems.value(forKey: "location-pastNotes") as! NSArray
let model: SiteHistoryNotesModel = arr[indexPath.row] as! SiteHistoryNotesModel
model.isOpen = !model.isOpen
model.getCellHeight()
reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
} else if indexPath.section == 2 {
let arr = dataItems.value(forKey: "location-equipment") as! NSArray
let model: SiteHistoryEquipModel = arr[indexPath.row] as! SiteHistoryEquipModel
model.isOpen = !model.isOpen
model.getCellHeight()
reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let head = view as! UITableViewHeaderFooterView
head.contentView.backgroundColor = UIColor.white
head.textLabel?.font = UIFont.boldSystemFont(ofSize: 13)
}
}
|
apache-2.0
|
d28a13decf4ced4caa5675043050560e
| 36.358974 | 150 | 0.613761 | 4.972696 | false | false | false | false |
sachin004/firefox-ios
|
Client/Frontend/Settings/Clearables.swift
|
3
|
7021
|
/* 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
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
|
4787c32561f900695e8396d5110b752c
| 35.195876 | 194 | 0.661159 | 5.347296 | false | false | false | false |
ConradoMateu/GOT-Challenge-Swift
|
GOT-Challenge-Swift/ServiceLocator.swift
|
1
|
2659
|
//
// ServiceLocator.swift
// GOT-Challenge-Swift
//
// Created by Conrado Mateu Gisbert on 27/05/17.
// Copyright © 2017 conradomateu. All rights reserved.
//
import UIKit
import Foundation
class ServiceLocator {
static var apiClient: CharactersAPIClient = FakeCharactersAPIClient()
//MARK: RootVC
func provideRootViewController() -> UIViewController {
let view = ServiceLocator().provideCharactersViewController()
return UINavigationController(rootViewController: view)
}
//MARK: CharactersVC Module
func provideCharactersViewController() -> CharactersViewController {
let charactersViewController = ServiceLocator.getBoard("CharactersViewController") as! CharactersViewController
let presenter = provideCharactersPresenter(view:
charactersViewController)
charactersViewController.presenter = presenter
return charactersViewController
}
fileprivate func provideCharactersPresenter(view: CharactersViewController) -> CharactersPresenter {
let router = provideCharacterRouter(viewController: view)
return CharactersPresenter(view: view, router: router)
}
func provideCharacterRouter(viewController: CharactersViewController) -> CharactersRouter {
return CharactersRouter(viewController: viewController)
}
func provideCharactersInteractor(output: CharactersInteractorOutput) -> CharactersInteractor {
return CharactersInteractor(output: output, apiclient: ServiceLocator.apiClient)
}
//MARK: CharacterDetailVC Module
func provideCharacterDetailViewController(forCharacter character: Character) -> CharacterDetailViewController {
let characterDetailViewController = ServiceLocator.getBoard("CharacterDetailViewController") as! CharacterDetailViewController
let presenter = provideCharacterDetailPresenter(forCharacter: character, view: characterDetailViewController
)
characterDetailViewController.presenter = presenter
return characterDetailViewController
}
fileprivate func provideCharacterDetailPresenter(forCharacter character: Character, view: DetailsView) -> DetailsPresenter {
return DetailsPresenter(view: view, character: character)
}
//MARK: ApiClient Configurator
static func config(_ apiClient: CharactersAPIClient) {
self.apiClient = apiClient
}
}
extension ServiceLocator {
static func getBoard(_ boardName: String) -> UIViewController {
let storyboard = UIStoryboard(name: "GOT", bundle: nil)
return storyboard.instantiateViewController(withIdentifier: boardName)
}
}
|
apache-2.0
|
c94ddcabafd35244fb5aa4629c80feb5
| 35.916667 | 134 | 0.753198 | 5.716129 | false | false | false | false |
stv-ekushida/STV-Extensions
|
STV-Extensions/Classes/UIKit/UIView+Helper.swift
|
1
|
2347
|
//
// UIView+Helper.swift
// ios-extension-demo
//
// Created by Eiji Kushida on 2017/03/13.
// Copyright © 2017年 Eiji Kushida. All rights reserved.
//
import UIKit
public extension UIView {
public var x: CGFloat{
get{
return self.frame.origin.x
}
set{
var r = self.frame
r.origin.x = newValue
self.frame = r
}
}
public var y: CGFloat{
get{
return self.frame.origin.y
}
set{
var r = self.frame
r.origin.y = newValue
self.frame = r
}
}
public var rightX: CGFloat{
get{
return self.x + self.width
}
set{
var r = self.frame
r.origin.x = newValue - frame.size.width
self.frame = r
}
}
public var bottomY: CGFloat{
get{
return self.y + self.height
}
set{
var r = self.frame
r.origin.y = newValue - frame.size.height
self.frame = r
}
}
public var centerX : CGFloat{
get{
return self.center.x
}
set{
self.center = CGPoint(x: newValue, y: self.center.y)
}
}
public var centerY : CGFloat{
get{
return self.center.y
}
set{
self.center = CGPoint(x: self.center.x, y: newValue)
}
}
public var width: CGFloat{
get{
return self.frame.size.width
}
set{
var r = self.frame
r.size.width = newValue
self.frame = r
}
}
public var height: CGFloat{
get{
return self.frame.size.height
}
set{
var r = self.frame
r.size.height = newValue
self.frame = r
}
}
public var origin: CGPoint{
get{
return self.frame.origin
}
set{
self.x = newValue.x
self.y = newValue.y
}
}
public var size: CGSize{
get{
return self.frame.size
}
set{
self.width = newValue.width
self.height = newValue.height
}
}
}
|
mit
|
352a211f62604b70400437cfc342c284
| 18.864407 | 64 | 0.440273 | 4.269581 | false | false | false | false |
ccrama/Slide-iOS
|
Slide for Reddit/RelatedContributionLoader.swift
|
1
|
2326
|
//
// RelatedContributionLoader.swift
// Slide for Reddit
//
// Created by Carlos Crane on 1/20/17.
// Copyright © 2017 Haptic Apps. All rights reserved.
//
import Foundation
import RealmSwift
import reddift
class RelatedContributionLoader: ContributionLoader {
func reset() {
content = []
}
var thing: RSubmission
var sub: String
var color: UIColor
init(thing: RSubmission, sub: String) {
self.thing = thing
self.sub = sub
color = ColorUtil.getColorForUser(name: sub)
paginator = Paginator()
content = []
}
var paginator: Paginator
var content: [Object]
var delegate: ContentListingViewController?
var paging = false
var canGetMore = false
func getData(reload: Bool) {
if delegate != nil {
do {
if reload {
paginator = Paginator()
}
let id = thing.name
try delegate?.session?.getDuplicatedArticles(paginator, name: id, completion: { (result) in
switch result {
case .failure:
self.delegate?.failed(error: result.error!)
case .success(let listing):
if reload {
self.content = []
}
let before = self.content.count
let baseContent = listing.1.children.compactMap({ $0 })
for item in baseContent {
if item is Comment {
self.content.append(RealmDataWrapper.commentToRComment(comment: item as! Comment, depth: 0))
} else {
self.content.append(RealmDataWrapper.linkToRSubmission(submission: item as! Link))
}
}
self.paginator = listing.1.paginator
DispatchQueue.main.async {
self.delegate?.doneLoading(before: before, filter: true)
}
}
})
} catch {
print(error)
}
}
}
}
|
apache-2.0
|
624cf7867329a05b5e2d688317a474b4
| 30.418919 | 124 | 0.471398 | 5.522565 | false | false | false | false |
iCrany/iOSExample
|
iOSExample/Module/TransitionExample/ViewController/Session4/Present/Error/Animation/ErrorPresentAnimation.swift
|
1
|
2349
|
//
// ErrorPresentAnimation.swift
// iOSExample
//
// Created by iCrany on 2017/12/9.
// Copyright © 2017 iCrany. All rights reserved.
//
import Foundation
class ErrorPresentAnimation: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.8
}
// This method can only be a nop if the transition is interactive and not a percentDriven interactive transition.
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// Get controllers from transition context
guard let toVC1 = transitionContext.viewController(forKey: .to) else {
return
}
//笔记:
//例子: vc1: UIViewController ------>(present的方式) UINavigationController(rootViewController: vc2) vc2: UIViewController
//如果是 UIViewController present UINavigationController 封装的 UIViewController 出来的时候不需要额外的检测该 toVC 是否是 UINavigationController,否则会导致
//注意: 这个是错误的写法
var toVC: UIViewController = toVC1
if toVC1.isKind(of: UINavigationController.self) {
let nav = (toVC1 as? UINavigationController)!
if !nav.viewControllers.isEmpty {
toVC = nav.viewControllers[0]
}
}
//错误的写法-end
// Set init frame for toVC
let screenBounds: CGRect = UIScreen.main.bounds
let finalFrame: CGRect = CGRect(x: 0, y: 0, width: screenBounds.width, height: screenBounds.height)//transitionContext.finalFrame(for: toVC)
toVC.view.frame = finalFrame.offsetBy(dx: 0, dy: screenBounds.size.height)
// Add toVC.view to containerView
let containerView: UIView = transitionContext.containerView
containerView.addSubview(toVC.view)
// Do animate now
let duration: TimeInterval = self.transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, animations: {
toVC.view.frame = finalFrame
}, completion: { (_: Bool) in
// Tell Context if we complete success
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
|
mit
|
75157866f08a7f7d1c2316762332fd0e
| 39.071429 | 148 | 0.682709 | 5.170507 | false | false | false | false |
Lopdo/SwiftData
|
SwiftData.swift
|
1
|
63593
|
//
// SwiftData.swift
//
// Copyright (c) 2015 Ryan Fowler
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
// MARK: - SwiftData
public struct SwiftData {
// MARK: - Public SwiftData Functions
// MARK: - Execute Statements
/**
Execute a non-query SQL statement (e.g. INSERT, UPDATE, DELETE, etc.)
This function will execute the provided SQL and return an Int with the error code, or nil if there was no error.
It is recommended to always verify that the return value is nil to ensure that the operation was successful.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- parameter sqlStr: The non-query string of SQL to be executed (INSERT, UPDATE, DELETE, etc.)
- returns: An Int with the error code, or nil if there was no error
*/
public static func executeChange(sqlStr: String) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.executeChange(sqlStr)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Execute a non-query SQL statement (e.g. INSERT, UPDATE, DELETE, etc.) along with arguments to be bound to the characters "?" (for values) and "i?" (for identifiers e.g. table or column names).
The objects in the provided array of arguments will be bound, in order, to the "i?" and "?" characters in the SQL string.
The quantity of "i?"s and "?"s in the SQL string must be equal to the quantity of arguments provided.
Objects that are to bind as an identifier ("i?") must be of type String.
Identifiers should be bound and escaped if provided by the user.
If "nil" is provided as an argument, the NULL value will be bound to the appropriate value in the SQL string.
For more information on how the objects will be escaped, refer to the functions "escapeValue()" and "escapeIdentifier()".
Note that the "escapeValue()" and "escapeIdentifier()" include the necessary quotations ' ' or " " to the arguments when being bound to the SQL.
It is recommended to always verify that the return value is nil to ensure that the operation was successful.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- binding errors (201 - 203)
- parameter sqlStr: The non-query string of SQL to be executed (INSERT, UPDATE, DELETE, etc.)
- parameter withArgs: An array of objects to bind to the "?" and "i?" characters in the sqlStr
- returns: An Int with the error code, or nil if there was no error
*/
public static func executeChange(sqlStr: String, withArgs: [AnyObject]) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.executeChange(sqlStr, withArgs: withArgs)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Execute multiple SQL statements (non-queries e.g. INSERT, UPDATE, DELETE, etc.)
This function will execute each SQL statment in the provided array, in order, and return an Int with the error code, or nil if there was no error.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- parameter sqlArr: An array of non-query strings of SQL to be executed (INSERT, UPDATE, DELETE, etc.)
- returns: An Int with the error code, or nil if there was no error
*/
public static func executeMultipleChanges(sqlArr: [String]) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
for sqlStr in sqlArr {
if let err = SQLiteDB.sharedInstance.executeChange(sqlStr) {
SQLiteDB.sharedInstance.close()
if let index = sqlArr.indexOf(sqlStr) {
print("Error occurred on array item: \(index) -> \"\(sqlStr)\"")
}
error = err
return
}
}
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Execute a SQLite query statement (e.g. SELECT)
This function will execute the provided SQL and return a tuple of:
- an Array of SDRow objects
- an Int with the error code, or nil if there was no error
The value for each column in an SDRow can be obtained using the column name in the subscript format similar to a Dictionary, along with the function to obtain the value in the appropriate type (.asString(), .asDate(), .asData(), .asInt(), .asDouble(), and .asBool()).
Without the function call to return a specific type, the SDRow will return an object with type AnyObject.
Note: NULL values in the SQLite database will be returned as 'nil'.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- parameter sqlStr: The query String of SQL to be executed (e.g. SELECT)
- returns: A tuple containing an Array of "SDRow"s, and an Int with the error code or nil if there was no error
*/
public static func executeQuery(sqlStr: String) -> (result: [SDRow], error: Int?) {
var result = [SDRow] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.executeQuery(sqlStr)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
/**
Execute a SQL query statement (e.g. SELECT) with arguments to be bound to the characters "?" (for values) and "i?" (for identifiers e.g. table or column names).
See the "executeChange(sqlStr: String, withArgs: [AnyObject?])" function for more information on the arguments provided and binding.
See the "executeQuery(sqlStr: String)" function for more information on the return value.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- binding errors (201 - 203)
- parameter sqlStr: The query String of SQL to be executed (e.g. SELECT)
- parameter withArgs: An array of objects that will be bound, in order, to the characters "?" (for values) and "i?" (for identifiers, e.g. table or column names) in the sqlStr.
- returns: A tuple containing an Array of "SDRow"s, and an Int with the error code or nil if there was no error
*/
public static func executeQuery(sqlStr: String, withArgs: [AnyObject]) -> (result: [SDRow], error: Int?) {
var result = [SDRow] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.executeQuery(sqlStr, withArgs: withArgs)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
/**
Execute functions in a closure on a single custom connection
Note: This function cannot be nested within itself, or inside a transaction/savepoint.
Possible errors returned by this function are:
- custom connection errors (301 - 306)
- parameter flags: The custom flag associated with the connection. Can be either:
- .ReadOnly
- .ReadWrite
- .ReadWriteCreate
- parameter closure: A closure containing functions that will be executed on the custom connection
- returns: An Int with the error code, or nil if there was no error
*/
public static func executeWithConnection(flags: SD.Flags, closure: ()->Void) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.openWithFlags(flags.toSQL()) {
error = err
return
}
closure()
if let err = SQLiteDB.sharedInstance.closeCustomConnection() {
error = err
return
}
}
putOnThread(task)
return error
}
// MARK: - Escaping Objects
/**
Escape an object to be inserted into a SQLite statement as a value
NOTE: Supported object types are: String, Int, Double, Bool, NSData, NSDate, and nil. All other data types will return the String value "NULL", and a warning message will be printed.
- parameter obj: The value to be escaped
- returns: The escaped value as a String, ready to be inserted into a SQL statement. Note: Single quotes (') will be placed around the entire value, if necessary.
*/
public static func escapeValue(obj: AnyObject?) -> String {
return SQLiteDB.sharedInstance.escapeValue(obj)
}
/**
Escape a string to be inserted into a SQLite statement as an indentifier (e.g. table or column name)
- parameter obj: The identifier to be escaped. NOTE: This object must be of type String.
- returns: The escaped identifier as a String, ready to be inserted into a SQL statement. Note: Double quotes (") will be placed around the entire identifier.
*/
public static func escapeIdentifier(obj: String) -> String {
return SQLiteDB.sharedInstance.escapeIdentifier(obj)
}
// MARK: - Tables
/**
Create A Table With The Provided Column Names and Types
Note: The ID field is created automatically as "INTEGER PRIMARY KEY AUTOINCREMENT"
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- parameter table: The table name to be created
- parameter columnNamesAndTypes: A dictionary where the key = column name, and the value = data type
- returns: An Int with the error code, or nil if there was no error
*/
public static func createTable(table: String, withColumnNamesAndTypes values: [String: SwiftData.DataType]) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.createSQLTable(table, withColumnsAndTypes: values)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Delete a SQLite table by name
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- parameter table: The table name to be deleted
- returns: An Int with the error code, or nil if there was no error
*/
public static func deleteTable(table: String) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.deleteSQLTable(table)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Adds Provided Column Names and Types to specified Table name
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- parameter table: The table name to be altered
- parameter columnNamesAndTypes: A dictionary where the key = column name, and the value = data type
- returns: An Int with the error code, or nil if there was no error
*/
public static func addColumns(table: String, columnNamesAndTypes values: [String: SwiftData.DataType]) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.addColumns(table, columnsAndTypes: values)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Obtain a list of the existing SQLite table names
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Table query error (403)
- returns: A tuple containing an Array of all existing SQLite table names, and an Int with the error code or nil if there was no error
*/
public static func existingTables() -> (result: [String], error: Int?) {
var result = [String] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.existingTables()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
// MARK: - Misc
/**
Obtain the error message relating to the provided error code
- parameter code: The error code provided
- returns: The error message relating to the provided error code
*/
public static func errorMessageForCode(code: Int) -> String {
return SwiftData.SDError.errorMessageFromCode(code)
}
/**
Obtain the database path
- returns: The path to the SwiftData database
*/
public static func databasePath() -> String {
return SQLiteDB.sharedInstance.dbPath
}
/**
Obtain the last inserted row id
Note: Care should be taken when the database is being accessed from multiple threads. The value could possibly return the last inserted row ID for another operation if another thread executes after your intended operation but before this function call.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- returns: A tuple of he ID of the last successfully inserted row's, and an Int of the error code or nil if there was no error
*/
public static func lastInsertedRowID() -> (rowID: Int, error: Int?) {
var result = 0
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
result = SQLiteDB.sharedInstance.lastInsertedRowID()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
/**
Obtain the number of rows modified by the most recently completed SQLite statement (INSERT, UPDATE, or DELETE)
Note: Care should be taken when the database is being accessed from multiple threads. The value could possibly return the number of rows modified for another operation if another thread executes after your intended operation but before this function call.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- returns: A tuple of the number of rows modified by the most recently completed SQLite statement, and an Int with the error code or nil if there was no error
*/
public static func numberOfRowsModified() -> (rowID: Int, error: Int?) {
var result = 0
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
result = SQLiteDB.sharedInstance.numberOfRowsModified()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
// MARK: - Indexes
/**
Create a SQLite index on the specified table and column(s)
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Index error (401)
- parameter name: The index name that is being created
- parameter onColumns: An array of column names that the index will be applied to (must be one column or greater)
- parameter inTable: The table name where the index is being created
- parameter isUnique: True if the index should be unique, false if it should not be unique (defaults to false)
- returns: An Int with the error code, or nil if there was no error
*/
public static func createIndex(name name: String, onColumns: [String], inTable: String, isUnique: Bool = false) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.createIndex(name, columns: onColumns, table: inTable, unique: isUnique)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Remove a SQLite index by its name
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- parameter indexName: The name of the index to be removed
- returns: An Int with the error code, or nil if there was no error
*/
public static func removeIndex(indexName: String) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.removeIndex(indexName)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Obtain a list of all existing indexes
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Index error (402)
- returns: A tuple containing an Array of all existing index names on the SQLite database, and an Int with the error code or nil if there was no error
*/
public static func existingIndexes() -> (result: [String], error: Int?) {
var result = [String] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.existingIndexes()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
/**
Obtain a list of all existing indexes on a specific table
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Index error (402)
- parameter table: The name of the table that is being queried for indexes
- returns: A tuple containing an Array of all existing index names in the table, and an Int with the error code or nil if there was no error
*/
public static func existingIndexesForTable(table: String) -> (result: [String], error: Int?) {
var result = [String] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.existingIndexesForTable(table)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
// MARK: - Transactions and Savepoints
/**
Execute commands within a single exclusive transaction
A connection to the database is opened and is not closed until the end of the transaction. A transaction cannot be embedded into another transaction or savepoint.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Transaction errors (501 - 502)
- parameter transactionClosure: A closure containing commands that will execute as part of a single transaction. If the transactionClosure returns true, the changes made within the closure will be committed. If false, the changes will be rolled back and will not be saved.
- returns: An Int with the error code, or nil if there was no error committing or rolling back the transaction
*/
public static func transaction(transactionClosure: ()->Bool) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
if let err = SQLiteDB.sharedInstance.beginTransaction() {
SQLiteDB.sharedInstance.close()
error = err
return
}
if transactionClosure() {
if let err = SQLiteDB.sharedInstance.commitTransaction() {
error = err
}
} else {
if let err = SQLiteDB.sharedInstance.rollbackTransaction() {
error = err
}
}
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Execute commands within a single savepoint
A connection to the database is opened and is not closed until the end of the savepoint (or the end of the last savepoint, if embedded).
NOTE: Unlike transactions, savepoints may be embedded into other savepoints or transactions.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- parameter savepointClosure: A closure containing commands that will execute as part of a single savepoint. If the savepointClosure returns true, the changes made within the closure will be released. If false, the changes will be rolled back and will not be saved.
- returns: An Int with the error code, or nil if there was no error releasing or rolling back the savepoint
*/
public static func savepoint(savepointClosure: ()->Bool) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
if let err = SQLiteDB.sharedInstance.beginSavepoint() {
SQLiteDB.sharedInstance.close()
error = err
return
}
if savepointClosure() {
if let err = SQLiteDB.sharedInstance.releaseSavepoint() {
error = err
}
} else {
if let err = SQLiteDB.sharedInstance.rollbackSavepoint() {
print("Error rolling back to savepoint")
SQLiteDB.sharedInstance.savepointsOpen -= 1
SQLiteDB.sharedInstance.close()
error = err
return
}
if let err = SQLiteDB.sharedInstance.releaseSavepoint() {
error = err
}
}
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Convenience function to save a UIImage to disk and return the ID
- parameter image: The UIImage to be saved
- returns: The ID of the saved image as a String, or nil if there was an error saving the image to disk
*/
public static func saveUIImage(image: UIImage) -> String? {
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
let imageDirPath = (docsPath as NSString).stringByAppendingPathComponent("SwiftDataImages")
if !NSFileManager.defaultManager().fileExistsAtPath(imageDirPath) {
do {
try NSFileManager.defaultManager().createDirectoryAtPath(imageDirPath, withIntermediateDirectories: false, attributes: nil)
} catch _ {
print("Error creating SwiftData image folder")
return nil
}
}
let imageID = NSUUID().UUIDString
let imagePath = (imageDirPath as NSString).stringByAppendingPathComponent(imageID)
if let imageAsData = UIImagePNGRepresentation(image) {
if !imageAsData.writeToFile(imagePath, atomically: true) {
print("Error saving image")
return nil
}
}
return imageID
}
/**
Convenience function to delete a UIImage with the specified ID
- parameter id: The id of the UIImage
- returns: True if the image was successfully deleted, or false if there was an error during the deletion
*/
public static func deleteUIImageWithID(id: String) -> Bool {
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
let imageDirPath = (docsPath as NSString).stringByAppendingPathComponent("SwiftDataImages")
let fullPath = (imageDirPath as NSString).stringByAppendingPathComponent(id)
do {
try NSFileManager.defaultManager().removeItemAtPath(fullPath)
return true
} catch _ {
return false
}
}
// MARK: - SQLiteDB Class
private class SQLiteDB {
class var sharedInstance: SQLiteDB {
struct Singleton {
static let instance = SQLiteDB()
}
return Singleton.instance
}
var sqliteDB: COpaquePointer = nil
var dbPath = SQLiteDB.createPath()
var inTransaction = false
var isConnected = false
var openWithFlags = false
var savepointsOpen = 0
let queue = dispatch_queue_create("SwiftData.DatabaseQueue", DISPATCH_QUEUE_SERIAL)
// MARK: - Database Handling Functions
//open a connection to the sqlite3 database
func open() -> Int? {
if inTransaction || openWithFlags || savepointsOpen > 0 {
return nil
}
if sqliteDB != nil || isConnected {
return nil
}
let status = sqlite3_open(dbPath.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB)
if status != SQLITE_OK {
print("SwiftData Error -> During: Opening Database")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
return Int(status)
}
isConnected = true
return nil
}
//open a connection to the sqlite3 database with flags
func openWithFlags(flags: Int32) -> Int? {
if inTransaction {
print("SwiftData Error -> During: Opening Database with Flags")
print(" -> Code: 302 - Cannot open a custom connection inside a transaction")
return 302
}
if openWithFlags {
print("SwiftData Error -> During: Opening Database with Flags")
print(" -> Code: 301 - A custom connection is already open")
return 301
}
if savepointsOpen > 0 {
print("SwiftData Error -> During: Opening Database with Flags")
print(" -> Code: 303 - Cannot open a custom connection inside a savepoint")
return 303
}
if isConnected {
print("SwiftData Error -> During: Opening Database with Flags")
print(" -> Code: 301 - A custom connection is already open")
return 301
}
let status = sqlite3_open_v2(dbPath.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB, flags, nil)
if status != SQLITE_OK {
print("SwiftData Error -> During: Opening Database with Flags")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
return Int(status)
}
isConnected = true
openWithFlags = true
return nil
}
//close the connection to to the sqlite3 database
func close() {
if inTransaction || openWithFlags || savepointsOpen > 0 {
return
}
if sqliteDB == nil || !isConnected {
return
}
let status = sqlite3_close(sqliteDB)
if status != SQLITE_OK {
print("SwiftData Error -> During: Closing Database")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
}
sqliteDB = nil
isConnected = false
}
//close a custom connection to the sqlite3 database
func closeCustomConnection() -> Int? {
if inTransaction {
print("SwiftData Error -> During: Closing Database with Flags")
print(" -> Code: 305 - Cannot close a custom connection inside a transaction")
return 305
}
if savepointsOpen > 0 {
print("SwiftData Error -> During: Closing Database with Flags")
print(" -> Code: 306 - Cannot close a custom connection inside a savepoint")
return 306
}
if !openWithFlags {
print("SwiftData Error -> During: Closing Database with Flags")
print(" -> Code: 304 - A custom connection is not currently open")
return 304
}
let status = sqlite3_close(sqliteDB)
sqliteDB = nil
isConnected = false
openWithFlags = false
if status != SQLITE_OK {
print("SwiftData Error -> During: Closing Database with Flags")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
return Int(status)
}
return nil
}
//create the database path
class func createPath() -> String {
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
let databaseStr = "SwiftData.sqlite"
let dbPath = (docsPath as NSString).stringByAppendingPathComponent(databaseStr)
return dbPath
}
//begin a transaction
func beginTransaction() -> Int? {
if savepointsOpen > 0 {
print("SwiftData Error -> During: Beginning Transaction")
print(" -> Code: 501 - Cannot begin a transaction within a savepoint")
return 501
}
if inTransaction {
print("SwiftData Error -> During: Beginning Transaction")
print(" -> Code: 502 - Cannot begin a transaction within another transaction")
return 502
}
if let error = executeChange("BEGIN EXCLUSIVE") {
return error
}
inTransaction = true
return nil
}
//rollback a transaction
func rollbackTransaction() -> Int? {
let error = executeChange("ROLLBACK")
inTransaction = false
return error
}
//commit a transaction
func commitTransaction() -> Int? {
let error = executeChange("COMMIT")
inTransaction = false
if let err = error {
rollbackTransaction()
return err
}
return nil
}
//begin a savepoint
func beginSavepoint() -> Int? {
if let error = executeChange("SAVEPOINT 'savepoint\(savepointsOpen + 1)'") {
return error
}
savepointsOpen += 1
return nil
}
//rollback a savepoint
func rollbackSavepoint() -> Int? {
return executeChange("ROLLBACK TO 'savepoint\(savepointsOpen)'")
}
//release a savepoint
func releaseSavepoint() -> Int? {
let error = executeChange("RELEASE 'savepoint\(savepointsOpen)'")
savepointsOpen -= 1
return error
}
//get last inserted row id
func lastInsertedRowID() -> Int {
let id = sqlite3_last_insert_rowid(sqliteDB)
return Int(id)
}
//number of rows changed by last update
func numberOfRowsModified() -> Int {
return Int(sqlite3_changes(sqliteDB))
}
//return value of column
func getColumnValue(statement: COpaquePointer, index: Int32, type: String) -> AnyObject? {
switch type {
case "INT", "INTEGER", "TINYINT", "SMALLINT", "MEDIUMINT", "BIGINT", "UNSIGNED BIG INT", "INT2", "INT8":
if sqlite3_column_type(statement, index) == SQLITE_NULL {
return nil
}
return Int(sqlite3_column_int(statement, index))
case "CHARACTER(20)", "VARCHAR(255)", "VARYING CHARACTER(255)", "NCHAR(55)", "NATIVE CHARACTER", "NVARCHAR(100)", "TEXT", "CLOB":
let text = UnsafePointer<Int8>(sqlite3_column_text(statement, index))
return String.fromCString(text)
case "BLOB", "NONE":
let blob = sqlite3_column_blob(statement, index)
if blob != nil {
let size = sqlite3_column_bytes(statement, index)
return NSData(bytes: blob, length: Int(size))
}
return nil
case "REAL", "DOUBLE", "DOUBLE PRECISION", "FLOAT", "NUMERIC", "DECIMAL(10,5)":
if sqlite3_column_type(statement, index) == SQLITE_NULL {
return nil
}
return Double(sqlite3_column_double(statement, index))
case "BOOLEAN":
if sqlite3_column_type(statement, index) == SQLITE_NULL {
return nil
}
return sqlite3_column_int(statement, index) != 0
case "DATE", "DATETIME":
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let text = UnsafePointer<Int8>(sqlite3_column_text(statement, index))
if let string = String.fromCString(text) {
return dateFormatter.dateFromString(string)
}
print("SwiftData Warning -> The text date at column: \(index) could not be cast as a String, returning nil")
return nil
default:
print("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil")
return nil
}
}
// MARK: SQLite Execution Functions
//execute a SQLite update from a SQL String
func executeChange(sqlStr: String, withArgs: [AnyObject]? = nil) -> Int? {
var sql = sqlStr
if let args = withArgs {
let result = bind(args, toSQL: sql)
if let error = result.error {
return error
} else {
sql = result.string
}
}
var pStmt: COpaquePointer = nil
var status = sqlite3_prepare_v2(SQLiteDB.sharedInstance.sqliteDB, sql, -1, &pStmt, nil)
if status != SQLITE_OK {
print("SwiftData Error -> During: SQL Prepare")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
sqlite3_finalize(pStmt)
return Int(status)
}
status = sqlite3_step(pStmt)
if status != SQLITE_DONE && status != SQLITE_OK {
print("SwiftData Error -> During: SQL Step")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
sqlite3_finalize(pStmt)
return Int(status)
}
sqlite3_finalize(pStmt)
return nil
}
//execute a SQLite query from a SQL String
func executeQuery(sqlStr: String, withArgs: [AnyObject]? = nil) -> (result: [SDRow], error: Int?) {
var resultSet = [SDRow]()
var sql = sqlStr
if let args = withArgs {
let result = bind(args, toSQL: sql)
if let err = result.error {
return (resultSet, err)
} else {
sql = result.string
}
}
var pStmt: COpaquePointer = nil
var status = sqlite3_prepare_v2(SQLiteDB.sharedInstance.sqliteDB, sql, -1, &pStmt, nil)
if status != SQLITE_OK {
print("SwiftData Error -> During: SQL Prepare")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
sqlite3_finalize(pStmt)
return (resultSet, Int(status))
}
var columnCount: Int32 = 0
var next = true
while next {
status = sqlite3_step(pStmt)
if status == SQLITE_ROW {
columnCount = sqlite3_column_count(pStmt)
var row = SDRow()
for i: Int32 in 0 ..< columnCount {
let columnName = String.fromCString(sqlite3_column_name(pStmt, i))!
if let columnType = String.fromCString(sqlite3_column_decltype(pStmt, i))?.uppercaseString {
if let columnValue: AnyObject = getColumnValue(pStmt, index: i, type: columnType) {
row[columnName] = SDColumn(obj: columnValue)
}
} else {
var columnType = ""
switch sqlite3_column_type(pStmt, i) {
case SQLITE_INTEGER:
columnType = "INTEGER"
case SQLITE_FLOAT:
columnType = "FLOAT"
case SQLITE_TEXT:
columnType = "TEXT"
case SQLITE3_TEXT:
columnType = "TEXT"
case SQLITE_BLOB:
columnType = "BLOB"
case SQLITE_NULL:
columnType = "NULL"
default:
columnType = "NULL"
}
if let columnValue: AnyObject = getColumnValue(pStmt, index: i, type: columnType) {
row[columnName] = SDColumn(obj: columnValue)
}
}
}
resultSet.append(row)
} else if status == SQLITE_DONE {
next = false
} else {
print("SwiftData Error -> During: SQL Step")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
sqlite3_finalize(pStmt)
return (resultSet, Int(status))
}
}
sqlite3_finalize(pStmt)
return (resultSet, nil)
}
}
// MARK: - SDRow
public struct SDRow {
var values = [String: SDColumn]()
public subscript(key: String) -> SDColumn? {
get {
return values[key]
}
set(newValue) {
values[key] = newValue
}
}
}
// MARK: - SDColumn
public struct SDColumn {
var value: AnyObject
init(obj: AnyObject) {
value = obj
}
//return value by type
/**
Return the column value as a String
- returns: An Optional String corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as a String, or the value is NULL
*/
public func asString() -> String? {
return value as? String
}
/**
Return the column value as an Int
- returns: An Optional Int corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as a Int, or the value is NULL
*/
public func asInt() -> Int? {
return value as? Int
}
/**
Return the column value as a Double
- returns: An Optional Double corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as a Double, or the value is NULL
*/
public func asDouble() -> Double? {
return value as? Double
}
/**
Return the column value as a Bool
- returns: An Optional Bool corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as a Bool, or the value is NULL
*/
public func asBool() -> Bool? {
return value as? Bool
}
/**
Return the column value as NSData
- returns: An Optional NSData object corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as NSData, or the value is NULL
*/
public func asData() -> NSData? {
return value as? NSData
}
/**
Return the column value as an NSDate
- returns: An Optional NSDate corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as an NSDate, or the value is NULL
*/
public func asDate() -> NSDate? {
return value as? NSDate
}
/**
Return the column value as an AnyObject
- returns: An Optional AnyObject corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as an AnyObject, or the value is NULL
*/
public func asAnyObject() -> AnyObject? {
return value
}
/**
Return the column value path as a UIImage
- returns: An Optional UIImage corresponding to the path of the apprioriate column value. Will be nil if: the column name does not exist, the value of the specified path cannot be cast as a UIImage, or the value is NULL
*/
public func asUIImage() -> UIImage? {
if let path = value as? String{
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
let imageDirPath = (docsPath as NSString).stringByAppendingPathComponent("SwiftDataImages")
let fullPath = (imageDirPath as NSString).stringByAppendingPathComponent(path)
if !NSFileManager.defaultManager().fileExistsAtPath(fullPath) {
print("SwiftData Error -> Invalid image ID provided")
return nil
}
if let imageAsData = NSData(contentsOfFile: fullPath) {
return UIImage(data: imageAsData)
}
}
return nil
}
}
// MARK: - Error Handling
private struct SDError {
}
}
// MARK: - Threading
extension SwiftData {
private static func putOnThread(task: ()->Void) {
if SQLiteDB.sharedInstance.inTransaction || SQLiteDB.sharedInstance.savepointsOpen > 0 || SQLiteDB.sharedInstance.openWithFlags {
task()
} else {
dispatch_sync(SQLiteDB.sharedInstance.queue) {
task()
}
}
}
}
// MARK: - Escaping And Binding Functions
extension SwiftData.SQLiteDB {
func bind(objects: [AnyObject], toSQL sql: String) -> (string: String, error: Int?) {
var newSql = ""
var bindIndex = 0
var i = false
for char in sql.characters {
if char == "?" {
if bindIndex > objects.count - 1 {
print("SwiftData Error -> During: Object Binding")
print(" -> Code: 201 - Not enough objects to bind provided")
return ("", 201)
}
var obj = ""
if i {
if let str = objects[bindIndex] as? String {
obj = escapeIdentifier(str)
} else {
print("SwiftData Error -> During: Object Binding")
print(" -> Code: 203 - Object to bind as identifier must be a String at array location: \(bindIndex)")
return ("", 203)
}
newSql = newSql.substringToIndex(newSql.endIndex.predecessor())
} else {
obj = escapeValue(objects[bindIndex])
}
newSql += obj
bindIndex += 1
} else {
newSql.append(char)
}
if char == "i" {
i = true
} else if i {
i = false
}
}
if bindIndex != objects.count {
print("SwiftData Error -> During: Object Binding")
print(" -> Code: 202 - Too many objects to bind provided")
return ("", 202)
}
return (newSql, nil)
}
//return escaped String value of AnyObject
func escapeValue(obj: AnyObject?) -> String {
if let obj: AnyObject = obj {
if obj is String {
return "'\(escapeStringValue(obj as! String))'"
}
if obj is Double || obj is Int {
return "\(obj)"
}
if obj is Bool {
if obj as! Bool {
return "1"
} else {
return "0"
}
}
if obj is NSData {
let str = "\(obj)"
var newStr = ""
for char in str.characters {
if char != "<" && char != ">" && char != " " {
newStr.append(char)
}
}
return "X'\(newStr)'"
}
if obj is NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return "\(escapeValue(dateFormatter.stringFromDate(obj as! NSDate)))"
}
if obj is UIImage {
if let imageID = SD.saveUIImage(obj as! UIImage) {
return "'\(escapeStringValue(imageID))'"
}
print("SwiftData Warning -> Cannot save image, NULL will be inserted into the database")
return "NULL"
}
print("SwiftData Warning -> Object \"\(obj)\" is not a supported type and will be inserted into the database as NULL")
return "NULL"
} else {
return "NULL"
}
}
//return escaped String identifier
func escapeIdentifier(obj: String) -> String {
return "\"\(escapeStringIdentifier(obj))\""
}
//escape string
func escapeStringValue(str: String) -> String {
var escapedStr = ""
for char in str.characters {
if char == "'" {
escapedStr += "'"
}
escapedStr.append(char)
}
return escapedStr
}
//escape string
func escapeStringIdentifier(str: String) -> String {
var escapedStr = ""
for char in str.characters {
if char == "\"" {
escapedStr += "\""
}
escapedStr.append(char)
}
return escapedStr
}
}
// MARK: - SQL Creation Functions
extension SwiftData {
/**
Column Data Types
- parameter StringVal: A column with type String, corresponds to SQLite type "TEXT"
- parameter IntVal: A column with type Int, corresponds to SQLite type "INTEGER"
- parameter DoubleVal: A column with type Double, corresponds to SQLite type "DOUBLE"
- parameter BoolVal: A column with type Bool, corresponds to SQLite type "BOOLEAN"
- parameter DataVal: A column with type NSdata, corresponds to SQLite type "BLOB"
- parameter DateVal: A column with type NSDate, corresponds to SQLite type "DATE"
- parameter UIImageVal: A column with type String (the path value of saved UIImage), corresponds to SQLite type "TEXT"
*/
public enum DataType {
case StringVal
case IntVal
case DoubleVal
case BoolVal
case DataVal
case DateVal
case UIImageVal
private func toSQL() -> String {
switch self {
case .StringVal, .UIImageVal:
return "TEXT"
case .IntVal:
return "INTEGER"
case .DoubleVal:
return "DOUBLE"
case .BoolVal:
return "BOOLEAN"
case .DataVal:
return "BLOB"
case .DateVal:
return "DATE"
}
}
}
/**
Flags for custom connection to the SQLite database
- parameter ReadOnly: Opens the SQLite database with the flag "SQLITE_OPEN_READONLY"
- parameter ReadWrite: Opens the SQLite database with the flag "SQLITE_OPEN_READWRITE"
- parameter ReadWriteCreate: Opens the SQLite database with the flag "SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE"
*/
public enum Flags {
case ReadOnly
case ReadWrite
case ReadWriteCreate
private func toSQL() -> Int32 {
switch self {
case .ReadOnly:
return SQLITE_OPEN_READONLY
case .ReadWrite:
return SQLITE_OPEN_READWRITE
case .ReadWriteCreate:
return SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
}
}
}
}
extension SwiftData.SQLiteDB {
//create a table
func createSQLTable(table: String, withColumnsAndTypes values: [String: SwiftData.DataType]) -> Int? {
var sqlStr = "CREATE TABLE \(table) (ID INTEGER PRIMARY KEY AUTOINCREMENT, "
var firstRun = true
for value in values {
if firstRun {
sqlStr += "\(escapeIdentifier(value.0)) \(value.1.toSQL())"
firstRun = false
} else {
sqlStr += ", \(escapeIdentifier(value.0)) \(value.1.toSQL())"
}
}
sqlStr += ")"
return executeChange(sqlStr)
}
//delete a table
func deleteSQLTable(table: String) -> Int? {
let sqlStr = "DROP TABLE \(table)"
return executeChange(sqlStr)
}
//alter a table
func addColumns(table: String, columnsAndTypes values: [String: SwiftData.DataType]) -> Int? {
var result: Int?
for colDef in values {
let sqlStr = "ALTER TABLE \(table) ADD COLUMN \(escapeIdentifier(colDef.0)) \(colDef.1.toSQL())"
result = executeChange(sqlStr)
if result != nil {
return result
}
}
return result
}
//get existing table names
func existingTables() -> (result: [String], error: Int?) {
let sqlStr = "SELECT name FROM sqlite_master WHERE type = 'table'"
var tableArr = [String]()
let results = executeQuery(sqlStr)
if let err = results.error {
return (tableArr, err)
}
for row in results.result {
if let table = row["name"]?.asString() {
tableArr.append(table)
} else {
print("SwiftData Error -> During: Finding Existing Tables")
print(" -> Code: 403 - Error extracting table names from sqlite_master")
return (tableArr, 403)
}
}
return (tableArr, nil)
}
//create an index
func createIndex(name: String, columns: [String], table: String, unique: Bool) -> Int? {
if columns.count < 1 {
print("SwiftData Error -> During: Creating Index")
print(" -> Code: 401 - At least one column name must be provided")
return 401
}
var sqlStr = ""
if unique {
sqlStr = "CREATE UNIQUE INDEX \(name) ON \(table) ("
} else {
sqlStr = "CREATE INDEX \(name) ON \(table) ("
}
var firstRun = true
for column in columns {
if firstRun {
sqlStr += column
firstRun = false
} else {
sqlStr += ", \(column)"
}
}
sqlStr += ")"
return executeChange(sqlStr)
}
//remove an index
func removeIndex(name: String) -> Int? {
let sqlStr = "DROP INDEX \(name)"
return executeChange(sqlStr)
}
//obtain list of existing indexes
func existingIndexes() -> (result: [String], error: Int?) {
let sqlStr = "SELECT name FROM sqlite_master WHERE type = 'index'"
var indexArr = [String]()
let results = executeQuery(sqlStr)
if let err = results.error {
return (indexArr, err)
}
for res in results.result {
if let index = res["name"]?.asString() {
indexArr.append(index)
} else {
print("SwiftData Error -> During: Finding Existing Indexes")
print(" -> Code: 402 - Error extracting index names from sqlite_master")
print("Error finding existing indexes -> Error extracting index names from sqlite_master")
return (indexArr, 402)
}
}
return (indexArr, nil)
}
//obtain list of existing indexes for a specific table
func existingIndexesForTable(table: String) -> (result: [String], error: Int?) {
let sqlStr = "SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = '\(table)'"
var indexArr = [String]()
let results = executeQuery(sqlStr)
if let err = results.error {
return (indexArr, err)
}
for res in results.result {
if let index = res["name"]?.asString() {
indexArr.append(index)
} else {
print("SwiftData Error -> During: Finding Existing Indexes for a Table")
print(" -> Code: 402 - Error extracting index names from sqlite_master")
return (indexArr, 402)
}
}
return (indexArr, nil)
}
}
// MARK: - SDError Functions
extension SwiftData.SDError {
//get the error message from the error code
private static func errorMessageFromCode(errorCode: Int) -> String {
switch errorCode {
//no error
case -1:
return "No error"
//SQLite error codes and descriptions as per: http://www.sqlite.org/c3ref/c_abort.html
case 0:
return "Successful result"
case 1:
return "SQL error or missing database"
case 2:
return "Internal logic error in SQLite"
case 3:
return "Access permission denied"
case 4:
return "Callback routine requested an abort"
case 5:
return "The database file is locked"
case 6:
return "A table in the database is locked"
case 7:
return "A malloc() failed"
case 8:
return "Attempt to write a readonly database"
case 9:
return "Operation terminated by sqlite3_interrupt()"
case 10:
return "Some kind of disk I/O error occurred"
case 11:
return "The database disk image is malformed"
case 12:
return "Unknown opcode in sqlite3_file_control()"
case 13:
return "Insertion failed because database is full"
case 14:
return "Unable to open the database file"
case 15:
return "Database lock protocol error"
case 16:
return "Database is empty"
case 17:
return "The database schema changed"
case 18:
return "String or BLOB exceeds size limit"
case 19:
return "Abort due to constraint violation"
case 20:
return "Data type mismatch"
case 21:
return "Library used incorrectly"
case 22:
return "Uses OS features not supported on host"
case 23:
return "Authorization denied"
case 24:
return "Auxiliary database format error"
case 25:
return "2nd parameter to sqlite3_bind out of range"
case 26:
return "File opened that is not a database file"
case 27:
return "Notifications from sqlite3_log()"
case 28:
return "Warnings from sqlite3_log()"
case 100:
return "sqlite3_step() has another row ready"
case 101:
return "sqlite3_step() has finished executing"
//custom SwiftData errors
//->binding errors
case 201:
return "Not enough objects to bind provided"
case 202:
return "Too many objects to bind provided"
case 203:
return "Object to bind as identifier must be a String"
//->custom connection errors
case 301:
return "A custom connection is already open"
case 302:
return "Cannot open a custom connection inside a transaction"
case 303:
return "Cannot open a custom connection inside a savepoint"
case 304:
return "A custom connection is not currently open"
case 305:
return "Cannot close a custom connection inside a transaction"
case 306:
return "Cannot close a custom connection inside a savepoint"
//->index and table errors
case 401:
return "At least one column name must be provided"
case 402:
return "Error extracting index names from sqlite_master"
case 403:
return "Error extracting table names from sqlite_master"
//->transaction and savepoint errors
case 501:
return "Cannot begin a transaction within a savepoint"
case 502:
return "Cannot begin a transaction within another transaction"
//unknown error
default:
//what the fuck happened?!?
return "Unknown error"
}
}
}
public typealias SD = SwiftData
|
mit
|
096079a85caf91aeb12e195de15cd010
| 35.132955 | 277 | 0.548598 | 5.161769 | false | false | false | false |
ibari/StationToStation
|
StationToStation/StationCommentsViewController.swift
|
1
|
2989
|
//
// StationCommentsViewController.swift
// StationToStation
//
// Created by Ian on 6/22/15.
// Copyright (c) 2015 Ian Bari. All rights reserved.
//
import UIKit
class StationCommentsViewController: UIViewController {
@IBOutlet weak var headerView: StationHeaderView!
@IBOutlet weak var containerView: UIView!
var station: Station!
var comments: [Comment]?
var commentsViewController: CommentsViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Comments"
configureHeader()
loadComments()
}
func loadComments() {
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
DataStoreClient.sharedInstance.getStationComments(station.objectId!) { (comments, error) -> Void in
if let error = error {
NSLog("Error while fetching comments: \(error)")
return
}
if let comments = comments {
self.comments = comments
self.addCommentsView()
} else {
NSLog("Unexpected nil returned for comments")
return
}
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
func addCommentsView() {
var storyboard = UIStoryboard(name: "Comments", bundle: nil)
commentsViewController = storyboard.instantiateViewControllerWithIdentifier("CommentsViewController") as! CommentsViewController
commentsViewController.comments = self.comments
addChildViewController(commentsViewController)
commentsViewController.view.frame = self.containerView.bounds
self.containerView.addSubview(commentsViewController.view)
commentsViewController.didMoveToParentViewController(self)
}
// MARK: - Actions
func didTapCollaborators() {
var storyboard = UIStoryboard(name: "Collaborators", bundle: nil)
var collaboratorsVC = storyboard.instantiateViewControllerWithIdentifier("CollaboratorsViewController") as! CollaboratorsViewController
collaboratorsVC.station = self.station!
self.navigationController!.pushViewController(collaboratorsVC, animated: true)
}
// MARK: - Configuration
func configureHeader() {
headerView.contentView.imageView.setImageWithURL(NSURL(string: station!.imageUrl))
headerView.contentView.name = station!.name
headerView.contentView.trackCount = station!.playlist!.tracks.count
headerView.contentView.collaboratorCount = station!.collaborators!.count
headerView.contentView.commentCount = station!.comments!.count
headerView.contentView.collaboratorsButton.addTarget(self, action: "didTapCollaborators", forControlEvents: UIControlEvents.TouchUpInside)
headerView.contentView.commentsButton.enabled = false
}
}
|
gpl-2.0
|
59a322d342b9b65121ab0833df0afe33
| 34.583333 | 146 | 0.66544 | 5.671727 | false | false | false | false |
cocoaheadsru/server
|
Tests/AppTests/Controllers/Event/EventControllerTests.swift
|
1
|
9344
|
import XCTest
import Testing
@testable import Vapor
@testable import App
//swiftlint:disable superfluous_disable_command
//swiftlint:disable force_try
class EventControllerTests: TestCase {
let eventContoller = EventController()
override func setUp() {
super.setUp()
do {
try drop.truncateTables()
} catch {
XCTFail("Droplet set raise exception: \(error.localizedDescription)")
return
}
}
func testThatEventHasPlaceRelation() throws {
let eventId = try! storeEvent()
let event = try! findEvent(by: eventId)
let place = try! event?.place()
XCTAssertNotNil(place)
}
func testThatPlaceOfEventHasCityRelation() throws {
let eventId = try! storeEvent()
let event = try! findEvent(by: eventId)
let place = try! event?.place()
let city = try! place?.city()
XCTAssertNotNil(city)
}
func testThatIndexEventsReturnsOkStatusForBeforeQueryKey() throws {
let query = "before=\(Date.randomValue.mysqlString)"
let request = Request.makeTest(method: .get, query: query)
let res = try! eventContoller.index(request).makeResponse()
XCTAssertEqual(res.status, .ok)
}
func testThatIndexEventsReturnsOkStatusForAfterQueryKey() throws {
let query = "after=\(Date.randomValue.mysqlString)"
let request = Request.makeTest(method: .get, query: query)
let res = try! eventContoller.index(request).makeResponse()
XCTAssertEqual(res.status, .ok)
}
func testThatIndexEventsReturnsJSONArray() throws {
let resAfter = try! fetchPastEvents()
let resBefore = try! fetchComingEvents()
XCTAssertNotNil(resAfter.json?.array)
XCTAssertNotNil(resBefore.json?.array)
}
func testThatIndexEventsReturnsJSONArrayEventsHasAllRequiredFields() throws {
try storeComingEvent()
try storePastEvent()
let resAfter = try! fetchComingEvents()
let resBefore = try! fetchPastEvents()
let eventJSON1 = resAfter.json?.array?.first
let eventJSON2 = resBefore.json?.array?.first
assertEventHasRequiredFields(json: eventJSON1)
assertEventHasRequiredFields(json: eventJSON2)
}
func testThatIndexEventsReturnsJSONArrayEventsHasAllExpectedFields() throws {
let eventId1 = try! storeComingEvent()
let eventId2 = try! storePastEvent()
guard
let event1 = try! findEvent(by: eventId1),
let event2 = try! findEvent(by: eventId2)
else {
XCTFail("Can't get event")
return
}
let resAfter = try! fetchComingEvents()
let resBefore = try! fetchPastEvents()
let eventJSON1 = resAfter.json?.array?.first
let eventJSON2 = resBefore.json?.array?.first
try! assertEventHasExpectedFields(json: eventJSON1, event: event1)
try! assertEventHasExpectedFields(json: eventJSON2, event: event2)
}
func testThatIndexEventsReturnsCorrectNumberOfPastEvents() throws {
let expectedEventsCount = Int.random(min: 1, max: 20)
try storePastEvents(count: expectedEventsCount)
let res = try fetchPastEvents()
let actualEventsCount = res.json?.array?.count
XCTAssertEqual(actualEventsCount, expectedEventsCount)
}
func testThatIndexEventsReturnsCorrectNumberOfComingEvents() throws {
let expectedEventsCount = Int.random(min: 1, max: 20)
try storeComingEvents(count: expectedEventsCount)
let res = try fetchComingEvents()
let actualEventsCount = res.json?.array?.count
XCTAssertEqual(actualEventsCount, expectedEventsCount)
}
func testThatIndexEventsReturnsCorrectNumberOfPastAndComingEvents() throws {
let expectedPastEventsCount = Int.random(min: 1, max: 20)
let expectedComingEventsCount = Int.random(min: 1, max: 20)
try! storePastEvents(count: expectedPastEventsCount)
try! storeComingEvents(count: expectedComingEventsCount)
let resBefore = try! fetchPastEvents()
let resAfter = try! fetchComingEvents()
let actualPastEventsCount = resBefore.json?.array?.count
let actualComingEventsCount = resAfter.json?.array?.count
XCTAssertEqual(actualPastEventsCount, expectedPastEventsCount)
XCTAssertEqual(actualComingEventsCount, expectedComingEventsCount)
}
// MARK: Endpoint tests
func testThatGetEventsBeforeTimestampRouteReturnsOkStatus() throws {
try drop
.clientAuthorizedTestResponse(to: .get, at: "api/event", query: "before=\(Date.randomValue.mysqlString)")
.assertStatus(is: .ok)
}
func testThatGetEventsAfterTimestampRouteReturnsOkStatus() throws {
try drop
.clientAuthorizedTestResponse(to: .get, at: "api/event", query: "after=\(Date.randomValue.mysqlString)")
.assertStatus(is: .ok)
}
func testThatGetEventsRouteFailsForEmptyQueryParameters() throws {
try drop
.clientAuthorizedTestResponse(to: .get, at: "api/event")
.assertStatus(is: .badRequest)
}
func testThatGetEventsRouteFailsWithWrongQueryParameterKey() throws {
let query = "\(EventHelper.invalidQueryKeyParameter)=\(Date.randomValue.mysqlString)"
try drop
.clientAuthorizedTestResponse(to: .get, at: "api/event", query: query)
.assertStatus(is: .badRequest)
}
func testThatGetEventsRouteFailsWithWrongQueryParameterValue() throws {
let validKey = Bool.randomValue ? "after" : "before"
let query = "\(validKey)=\(EventHelper.invalidQueryValueParameter)"
try drop
.clientAuthorizedTestResponse(to: .get, at: "api/event", query: query)
.assertStatus(is: .badRequest)
}
}
fileprivate extension EventControllerTests {
func assertEventHasRequiredFields(json: JSON?) {
XCTAssertNotNil(json)
XCTAssertNotNil(json?["id"])
XCTAssertNotNil(json?["title"])
XCTAssertNotNil(json?["description"])
XCTAssertNotNil(json?["photo_url"])
XCTAssertNotNil(json?["is_registration_open"])
XCTAssertNotNil(json?["start_date"])
XCTAssertNotNil(json?["end_date"])
XCTAssertNotNil(json?["hide"])
XCTAssertNotNil(json?["place"])
XCTAssertNotNil(json?["status"])
XCTAssertNotNil(json?["speakers_photos"])
let placeJSON = json?["place"]?.makeJSON()
XCTAssertNotNil(placeJSON?["id"])
XCTAssertNotNil(placeJSON?["latitude"])
XCTAssertNotNil(placeJSON?["longitude"])
XCTAssertNotNil(placeJSON?["title"])
XCTAssertNotNil(placeJSON?["description"])
XCTAssertNotNil(placeJSON?["address"])
XCTAssertNotNil(placeJSON?["city"])
let cityJSON = placeJSON?["city"]?.makeJSON()
XCTAssertNotNil(cityJSON?["id"])
XCTAssertNotNil(cityJSON?["city_name"])
}
func assertEventHasExpectedFields(json: JSON?, event: App.Event) throws {
guard let place = try! event.place() else {
XCTFail("Can't get place")
return
}
guard let city = try! place.city() else {
XCTFail("Can't get city")
return
}
XCTAssertEqual(json?["id"]?.int, event.id?.int)
XCTAssertEqual(json?["title"]?.string, event.title)
XCTAssertEqual(json?["description"]?.string, event.description)
XCTAssertEqual(json?["photo_url"]?.string, event.photoURL()!)
XCTAssertEqual(json?["is_registration_open"]?.bool, event.isRegistrationOpen)
XCTAssertEqual(json?["start_date"]?.string, event.startDate.mysqlString)
XCTAssertEqual(json?["end_date"]?.string, event.endDate.mysqlString)
XCTAssertEqual(json?["hide"]?.bool, event.hide)
XCTAssertEqual(json?["speakers_photos"]?.array?.count, try event.speakersPhotos().count)
XCTAssertEqual(json?["speakers_photos"]?.array?.first?.string, try event.speakersPhotos().first)
let placeJSON = json?["place"]?.makeJSON()
XCTAssertEqual(placeJSON?["id"]?.int, place.id?.int)
XCTAssertEqual(placeJSON?["latitude"]?.double, place.latitude)
XCTAssertEqual(placeJSON?["longitude"]?.double, place.longitude)
XCTAssertEqual(placeJSON?["title"]?.string, place.title)
XCTAssertEqual(placeJSON?["description"]?.string, place.description)
XCTAssertEqual(placeJSON?["address"]?.string, place.address)
let cityJSON = placeJSON?["city"]?.makeJSON()
XCTAssertEqual(cityJSON?["id"]?.int, city.id?.int)
XCTAssertEqual(cityJSON?["city_name"]?.string, city.cityName)
}
func fetchPastEvents() throws -> Response {
let query = "before=\(Date().mysqlString)"
let request = Request.makeTest(method: .get, query: query)
let result = try eventContoller.index(request).makeResponse()
return result
}
func fetchComingEvents() throws -> Response {
let query = "after=\(Date().mysqlString)"
let request = Request.makeTest(method: .get, query: query)
let result = try eventContoller.index(request).makeResponse()
return result
}
func storeEvent() throws -> Identifier? {
return try EventHelper.storeEvent()
}
@discardableResult
func storeComingEvent() throws -> Identifier? {
return try EventHelper.storeComingEvent()
}
func storeComingEvents(count: Int) throws {
for _ in 0..<count {
try storeComingEvent()
}
}
@discardableResult
func storePastEvent() throws -> Identifier? {
return try EventHelper.storePastEvent()
}
func storePastEvents(count: Int) throws {
for _ in 0..<count {
try storePastEvent()
}
}
func findEvent(by id: Identifier?) throws -> App.Event? {
return try EventHelper.findEvent(by: id)
}
}
|
mit
|
beec6e318293c43086af8db292b1f55c
| 33.479705 | 111 | 0.705372 | 4.264719 | false | true | false | false |
Keanyuan/SwiftContact
|
SwiftContent/SwiftContent/Classes/PhotoBrower/LLPhotoBrowser/LLBrowserZoomScrollView.swift
|
1
|
3116
|
//
// LLBrowserZoomScrollView.swift
// LLPhotoBrowser
//
// Created by LvJianfeng on 2017/4/14.
// Copyright © 2017年 LvJianfeng. All rights reserved.
//
import UIKit
typealias ZoomScrollViewTapClosure = () -> Void
class LLBrowserZoomScrollView: UIScrollView, UIScrollViewDelegate {
/// ImageView
public var zoomImageView: UIImageView? = nil
/// SingleTap
public var isSingleTap: Bool = false
public var zoomScrollViewTapClosure: ZoomScrollViewTapClosure?
/// Init
override init(frame: CGRect) {
super.init(frame: frame)
createZoomScrollView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Create
func createZoomScrollView() {
isSingleTap = false
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
delegate = self
minimumZoomScale = 1.0
maximumZoomScale = 3.0
zoomImageView = UIImageView.init()
zoomImageView?.isUserInteractionEnabled = true
self.addSubview(zoomImageView!)
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return zoomImageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
// Center
var rect = zoomImageView?.frame
rect?.origin.x = 0
rect?.origin.y = 0
if (rect?.size.width)! < ll_w {
rect?.origin.x = CGFloat(floorf(Float((ll_w - (rect?.size.width)!) * 0.5)))
}
if (rect?.size.height)! < ll_h {
rect?.origin.y = CGFloat(floorf(Float((ll_h - (rect?.size.height)!) * 0.5)))
}
zoomImageView?.frame = rect!
}
/// Click
func tapClick(tapAction: ZoomScrollViewTapClosure? = nil) {
zoomScrollViewTapClosure = tapAction
}
/// Touch
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = (touches as NSSet).anyObject() as! UITouch
if touch.tapCount == 1 {
self.perform(#selector(singleTapClick), with: nil, afterDelay: 0.3)
}else{
NSObject.cancelPreviousPerformRequests(withTarget: self)
if !isSingleTap {
let touchPoint = touch.location(in: zoomImageView)
zoomDoubleTapWithPoint(touchPoint: touchPoint)
}
}
}
/// Single Click
func singleTapClick() {
isSingleTap = true
if let closure = zoomScrollViewTapClosure {
closure()
}
}
/// Zoom
func zoomDoubleTapWithPoint(touchPoint: CGPoint) {
if zoomScale > minimumZoomScale {
self.setZoomScale(minimumZoomScale, animated: true)
}else{
let width = self.bounds.size.width / maximumZoomScale
let height = self.bounds.size.height / maximumZoomScale
self.zoom(to: CGRect.init(x: touchPoint.x - width * 0.5, y: touchPoint.y - height * 0.5, width: width, height: height), animated: true)
}
}
}
|
mit
|
3038f4fea0488fa93297b8cc07c284bc
| 28.932692 | 147 | 0.601028 | 4.639344 | false | false | false | false |
PhamBaTho/BTNavigationDropdownMenu
|
Source/Internal/BTConfiguration.swift
|
1
|
3411
|
//
// BTConfiguration.swift
//
// Copyright (c) 2017 PHAM BA THO ([email protected]). All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
final class BTConfiguration {
var menuTitleColor: UIColor?
var cellHeight: CGFloat!
var cellBackgroundColor: UIColor?
var cellSeparatorColor: UIColor?
var cellTextLabelColor: UIColor?
var selectedCellTextLabelColor: UIColor?
var cellTextLabelFont: UIFont!
var navigationBarTitleFont: UIFont
var cellTextLabelAlignment: NSTextAlignment!
var cellSelectionColor: UIColor?
var checkMarkImage: UIImage!
var shouldKeepSelectedCellColor: Bool!
var arrowTintColor: UIColor?
var arrowImage: UIImage!
var arrowPadding: CGFloat!
var animationDuration: TimeInterval!
var maskBackgroundColor: UIColor!
var maskBackgroundOpacity: CGFloat!
var shouldChangeTitleText: Bool!
init() {
// Path for image
let bundle = Bundle(for: BTConfiguration.self)
let url = bundle.url(forResource: "BTNavigationDropdownMenu", withExtension: "bundle")
let imageBundle = Bundle(url: url!)
let checkMarkImagePath = imageBundle?.path(forResource: "checkmark_icon", ofType: "png")
let arrowImagePath = imageBundle?.path(forResource: "arrow_down_icon", ofType: "png")
// Set default values
self.menuTitleColor = UIColor.darkGray
self.cellHeight = 50
self.cellBackgroundColor = UIColor.white
self.arrowTintColor = UIColor.white
self.cellSeparatorColor = UIColor.darkGray
self.cellTextLabelColor = UIColor.darkGray
self.selectedCellTextLabelColor = UIColor.darkGray
self.cellTextLabelFont = UIFont.systemFont(ofSize: 17, weight: .bold)
self.navigationBarTitleFont = UIFont.systemFont(ofSize: 17, weight: .bold)
self.cellTextLabelAlignment = NSTextAlignment.left
self.cellSelectionColor = UIColor.lightGray
self.checkMarkImage = UIImage(contentsOfFile: checkMarkImagePath!)
self.shouldKeepSelectedCellColor = false
self.animationDuration = 0.5
self.arrowImage = UIImage(contentsOfFile: arrowImagePath!)
self.arrowPadding = 15
self.maskBackgroundColor = UIColor.black
self.maskBackgroundOpacity = 0.3
self.shouldChangeTitleText = true
}
}
|
mit
|
bfc1113290ba00771646396e013b1d5a
| 43.881579 | 96 | 0.725887 | 4.914986 | false | false | false | false |
seanoshea/computer-science-in-swift
|
computer-science-in-swiftTests/MultiplicationTest.swift
|
1
|
4380
|
// Copyright (c) 2015-2016 Sean O'Shea. All rights reserved.
// 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 XCTest
class MultiplicationTest : XCTestCase {
func testRegularMultiplication() {
do {
let result = try Multiplication.regularMultiplication([5, 6, 7, 8], bottom: [1, 2, 3, 4])
XCTAssertTrue(result == 7006652, "Result should be 7006652")
} catch _ {
}
}
func testBackwardsMultiplication() {
do {
let result = try Multiplication.regularMultiplication([1, 2, 3, 4], bottom: [5, 6, 7, 8])
XCTAssertTrue(result == 7006652, "Result should be 7006652")
} catch _ {
}
}
func testSimpleMultiplication() {
do {
let result1 = try Multiplication.regularMultiplication([1], bottom: [1])
XCTAssertTrue(result1 == 1, "1 x 1 == 1")
let result2 = try Multiplication.regularMultiplication([2], bottom: [1])
XCTAssertTrue(result2 == 2, "2 x 1 == 2")
let result3 = try Multiplication.regularMultiplication([1], bottom: [0])
XCTAssertTrue(result3 == 0, "1 x 0 == 0")
let result4 = try Multiplication.regularMultiplication([0], bottom: [0])
XCTAssertTrue(result4 == 0, "0 x 0 == 0")
} catch _ {
}
}
func testNegatives() {
do {
let result1 = try Multiplication.regularMultiplication([-1], bottom: [1])
XCTAssertTrue(result1 == -1, "-1 x 1 == -1")
let result2 = try Multiplication.regularMultiplication([1], bottom: [-1])
XCTAssertTrue(result2 == -1, "1 x -1 == -1")
let result3 = try Multiplication.regularMultiplication([-1], bottom: [-1])
XCTAssertTrue(result3 == 1, "-1 x -1 == 1")
} catch _ {
}
}
func testDifferentSizes() {
do {
let result1 = try Multiplication.regularMultiplication([5, 6, 7], bottom: [1, 2, 3, 4])
XCTAssertTrue(result1 == 699678, "Result should be 699678")
let result2 = try Multiplication.regularMultiplication([1, 2, 3, 4], bottom: [1, 2])
XCTAssertTrue(result2 == 14808, "Result should be 699678")
} catch _ {
}
}
func testTens() {
do {
let result1 = try Multiplication.regularMultiplication([1, 0], bottom: [1, 0])
XCTAssertTrue(result1 == 100, "Result should be 100")
let result2 = try Multiplication.regularMultiplication([1, 0], bottom: [1])
XCTAssertTrue(result2 == 10, "Result should be 10")
let result3 = try Multiplication.regularMultiplication([1, 0], bottom: [-1])
XCTAssertTrue(result3 == -10, "Result should be -10")
let result4 = try Multiplication.regularMultiplication([1, 0], bottom: [-1, 0])
XCTAssertTrue(result4 == -100, "Result should be -100")
} catch _ {
}
}
func testInvalidInput() {
do {
try _ = Multiplication.regularMultiplication([10, 0], bottom: [1, 0])
XCTAssertTrue(1 == 0)
} catch let error {
XCTAssertTrue((error as? MultiplicationError) != nil)
}
}
}
|
mit
|
1c67b120ec8b10eeaa9d79c4e73dda28
| 40.320755 | 101 | 0.60137 | 4.415323 | false | true | false | false |
shlyren/ONE-Swift
|
ONE_Swift/AppDelegate.swift
|
1
|
1844
|
//
// AppDelegate.swift
// ONE_Swift
//
// Created by 任玉祥 on 16/4/27.
// Copyright © 2016年 任玉祥. All rights reserved.
//
import UIKit
import SDWebImage
import SVProgressHUD
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private var timer: Timer?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = JENTabBarController()
window?.backgroundColor = UIColor.whiteColor()
window?.makeKeyAndVisible()
SVProgressHUD.setMinimumDismissTimeInterval(1.0)
window?.addSubview(JENFPSLabel(frame: CGRectMake(15, JENScreenHeight - 50, 0, 0)))
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
stopTimer()
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
startTimer()
}
func applicationWillTerminate(application: UIApplication) {
}
func applicationDidReceiveMemoryWarning(application: UIApplication) {
clearMemory()
}
}
private extension AppDelegate {
func startTimer() {
timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: #selector(clearMemory), userInfo: nil, repeats: true)
}
func stopTimer() {
if let timer = timer {
timer.invalidate()
}
timer = nil
}
@objc func clearMemory() {
SDImageCache.sharedImageCache().clearMemory()
}
}
|
mit
|
3d8b44b3ace4000dac6bfe0febc6ec11
| 23.716216 | 137 | 0.662657 | 5.225714 | false | false | false | false |
goRestart/restart-backend-app
|
Sources/Domain/Model/Location/Location.swift
|
1
|
594
|
import Foundation
public typealias Coordinate = (latitude: Double, longitude: Double)
public struct Location {
public let coordinate: Coordinate?
public let city: String?
public let country: String?
public let zip: String?
public let ip: String?
public init(coordinate: Coordinate?,
city: String?,
country: String?,
zip: String?,
ip: String?)
{
self.coordinate = coordinate
self.city = city
self.country = country
self.zip = zip
self.ip = ip
}
}
|
gpl-3.0
|
72c4e802975635425957dbd2c5d99b52
| 22.76 | 67 | 0.56734 | 4.829268 | false | false | false | false |
practicalswift/swift
|
test/IRGen/sanitize_coverage.swift
|
4
|
2286
|
// RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=func %s | %FileCheck %s -check-prefix=SANCOV
// RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=bb %s | %FileCheck %s -check-prefix=SANCOV
// RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=edge %s | %FileCheck %s -check-prefix=SANCOV
// RUN: %target-swift-frontend -emit-ir -sanitize=fuzzer %s | %FileCheck %s -check-prefix=SANCOV
// RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=edge,trace-cmp %s | %FileCheck %s -check-prefix=SANCOV -check-prefix=SANCOV_TRACE_CMP
// RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=edge,trace-bb %s | %FileCheck %s -check-prefix=SANCOV -check-prefix=SANCOV_TRACE_BB
// RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=edge,indirect-calls %s | %FileCheck %s -check-prefix=SANCOV -check-prefix=SANCOV_INDIRECT_CALLS
// RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-coverage=edge,8bit-counters %s | %FileCheck %s -check-prefix=SANCOV -check-prefix=SANCOV_8BIT_COUNTERS
// RUN: %target-swift-frontend -emit-ir -sanitize=fuzzer %s | %FileCheck %s -check-prefix=SANCOV -check-prefix=SANCOV_TRACE_CMP
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku)
import Glibc
#elseif os(Windows)
import MSVCRT
#else
#error("Unsupported platform")
#endif
// FIXME: We should have a reliable way of triggering an indirect call in the
// LLVM IR generated from this code.
func test() {
// Use random numbers so the compiler can't constant fold
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
let x = arc4random()
let y = arc4random()
#else
let x = rand()
let y = rand()
#endif
// Comparison is to trigger insertion of __sanitizer_cov_trace_cmp
let z = x == y
print("\(z)")
}
test()
// FIXME: We need a way to distinguish the different types of coverage instrumentation
// that isn't really fragile. For now just check there's at least one call to the function
// used to increment coverage count at a particular PC.
// SANCOV: call void @__sanitizer_cov
// SANCOV_TRACE_CMP: call void @__sanitizer_cov_trace_cmp
|
apache-2.0
|
3dec021d0250e1835d73dbb8b92e772e
| 50.954545 | 172 | 0.722222 | 3.144429 | false | false | false | false |
NOTIFIT/notifit-ios-swift-sdk
|
Pod/Classes/NTFConstants.swift
|
1
|
1387
|
//
// NTFConstants.swift
// Pods
//
// Created by Tomas Sykora, jr. on 17/03/16.
//
//
import UIKit
import Foundation
struct NTFConstants {
struct api {
struct router {
static let baseURL = "http://notifit.io/api/"
static let register = NTFConstants.api.router.baseURL + "DeviceApple"
static let logState = NTFConstants.api.router.baseURL + "ApplicationState"
static let keyValue = NTFConstants.api.router.baseURL + "KeyValues"
}
static let applicationState = "state"
}
struct value {
static let communicationToken = "Communication-Token"
static let projectToken = "ProjectToken"
static let applicationToken = "ApplicationToken"
}
struct state {
static let launch = "Launch"
static let resignActive = "ResignActive"
static let enterBackground = "EnterBackground"
static let enterForeground = "EnterForeground"
static let becomeActive = "BecomeActive"
static let terminate = "Terminate"
}
}
enum NTFMethod: String {
case POST = "POST"
case PUT = "PUT"
}
enum NTFAppState: String {
case LAUNCH = "Launch"
case RESIGNACTIVE = "ResignActive"
case ENTERBACKGROUND = "EnterBackground"
case ENTERFOREGROUND = "EnterForeground"
case BECOMEACTIVE = "BecomeActive"
case TERMINATE = "Terminate"
}
|
mit
|
c346a8ff889f39c09a491c3366a19fd0
| 26.215686 | 86 | 0.653929 | 3.842105 | false | false | false | false |
Carthage/PrettyColors
|
Source/StyleParameter.swift
|
1
|
1990
|
/// Based on: ECMA-048 — 8.3.117
public enum StyleParameter: UInt8, Parameter {
// Reference: Terminal Support Table: https://github.com/jdhealy/PrettyColors/wiki/Terminal-Support
case Bold = 01 // bold or increased intensity
case Faint = 02 // faint, decreased intensity or second colour
case Italic = 03 // italicized
case Underlined = 04 // singly underlined
case BlinkSlow = 05 // slowly blinking (less then 150 per minute)
case Blink = 06 // rapidly blinking (150 per minute or more)
case Negative = 07 // negative image — a.k.a. Inverse
case Concealed = 08 // concealed characters
case CrossedOut = 09 // (characters still legible but marked as to be deleted)
case Font1 = 11
case Font2 = 12
case Font3 = 13
case Font4 = 14
case Font5 = 15
case Font6 = 16
case Font7 = 17
case Font8 = 18
case Font9 = 19
case Fraktur = 20 // Gothic
case UnderlinedDouble = 21 // doubly underlined
case Normal = 22 // normal colour or normal intensity (neither bold nor faint)
case Positive = 27 // positive image
case Revealed = 28 // revealed characters
case Framed = 51
case Encircled = 52
case Overlined = 53
public struct Reset {
/// Some parameters have corresponding resets,
/// but all parameters are reset by `defaultRendition`
public static let dictionary: [UInt8: UInt8] = [
03: 23, 04: 24, 05: 25, 06: 25, 11: 10,
12: 10, 13: 10, 14: 10, 15: 10, 16: 10,
17: 10, 18: 10, 19: 10, 20: 23, 51: 54,
52: 54, 53: 55
]
/// “cancels the effect of any preceding occurrence of SGR in the data stream”
public static let defaultRendition: UInt8 = 0
}
public var code: (enable: [UInt8], disable: UInt8?) {
return ( [self.rawValue], Reset.dictionary[self.rawValue] )
}
}
|
mit
|
3ac6ad4fd0832dcbfa59e203cae8159c
| 40.291667 | 100 | 0.601413 | 3.571171 | false | false | false | false |
paul8263/ImageBoardBrowser
|
ImageBoardBrowser/ImageInfo.swift
|
1
|
8691
|
//
// ImageInfo.swift
// ImageBoardBrowser
//
// Created by Paul Zhang on 4/12/2016.
// Copyright © 2016 Paul Zhang. All rights reserved.
//
import Foundation
class ImageInfo: NSObject, NSCoding {
var id: Int = 0
var tags: String = ""
var createdAt: Int = 0
var creatorId: Int?
var author: String = ""
var change: Int = 0
var source: String = ""
var score: Int = 0
var md5: String = ""
var fileSize: Int = 0
var fileUrl: String = ""
var isShownInIndex: Bool = false
var previewUrl: String = ""
var previewWidth: Int = 0
var previewHeight: Int = 0
var actualPreviewWidth: Int = 0
var actualPreviewHeight: Int = 0
var sampleUrl: String = ""
var sampleWidth: Int = 0
var sampleHeight: Int = 0
var sampleFileSize: Int = 0
var jpegUrl: String = ""
var jpegWidth: Int = 0
var jpegHeight: Int = 0
var jpegFileSize: Int = 0
var rating: String = ""
var hasChildren: Bool = false
var parentId: Int?
var status: String = ""
var width: Int = 0
var height: Int = 0
var isHeld: Bool = false
var flagDetail: String?
init(fromDict: [String: Any]) {
self.id = fromDict["id"] as! Int
self.tags = fromDict["tags"] as! String
self.createdAt = fromDict["created_at"] as! Int
self.creatorId = fromDict["creator_id"] as? Int
self.author = fromDict["author"] as! String
self.change = fromDict["change"] as! Int
self.source = fromDict["source"] as! String
self.score = fromDict["score"] as! Int
self.md5 = fromDict["md5"] as! String
self.fileSize = fromDict["file_size"] as! Int
self.fileUrl = fromDict["file_url"] as! String
self.isShownInIndex = fromDict["is_shown_in_index"] as! Bool
self.previewUrl = fromDict["preview_url"] as! String
self.previewWidth = fromDict["preview_width"] as! Int
self.previewHeight = fromDict["preview_height"] as! Int
self.actualPreviewWidth = fromDict["actual_preview_width"] as! Int
self.actualPreviewHeight = fromDict["actual_preview_height"] as! Int
self.sampleUrl = fromDict["sample_url"] as! String
self.sampleWidth = fromDict["sample_width"] as! Int
self.sampleHeight = fromDict["sample_height"] as! Int
self.sampleFileSize = fromDict["sample_file_size"] as! Int
self.jpegUrl = fromDict["jpeg_url"] as! String
self.jpegWidth = fromDict["jpeg_width"] as! Int
self.jpegHeight = fromDict["jpeg_height"] as! Int
self.jpegFileSize = fromDict["jpeg_file_size"] as! Int
self.rating = fromDict["rating"] as! String
self.hasChildren = fromDict["has_children"] as! Bool
self.parentId = fromDict["parent_id"] as? Int
self.status = fromDict["status"] as! String
self.width = fromDict["width"] as! Int
self.height = fromDict["height"] as! Int
self.isHeld = fromDict["is_held"] as! Bool
self.flagDetail = fromDict["flag_detail"] as? String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.id, forKey: "id")
aCoder.encode(self.tags, forKey: "tags")
aCoder.encode(self.createdAt, forKey: "createdAt")
aCoder.encode(self.creatorId, forKey: "creatorId")
aCoder.encode(self.author, forKey: "author")
aCoder.encode(self.change, forKey: "change")
aCoder.encode(self.source, forKey: "source")
aCoder.encode(self.score, forKey: "score")
aCoder.encode(self.md5, forKey: "md5")
aCoder.encode(self.fileSize, forKey: "fileSize")
aCoder.encode(self.fileUrl, forKey: "fileUrl")
aCoder.encode(self.isShownInIndex, forKey: "isShownInIndex")
aCoder.encode(self.previewUrl, forKey: "previewUrl")
aCoder.encode(self.previewWidth, forKey: "previewWidth")
aCoder.encode(self.previewHeight, forKey: "previewHeight")
aCoder.encode(self.actualPreviewWidth, forKey: "actualPreviewWidth")
aCoder.encode(self.actualPreviewHeight, forKey: "actualPreviewHeight")
aCoder.encode(self.sampleUrl, forKey: "sampleUrl")
aCoder.encode(self.sampleWidth, forKey: "sampleWidth")
aCoder.encode(self.sampleHeight, forKey: "sampleHeight")
aCoder.encode(self.sampleFileSize, forKey: "sampleFileSize")
aCoder.encode(self.jpegUrl, forKey: "jpegUrl")
aCoder.encode(self.jpegWidth, forKey: "jpegWidth")
aCoder.encode(self.jpegHeight, forKey: "jpegHeight")
aCoder.encode(self.jpegFileSize, forKey: "jpegFileSize")
aCoder.encode(self.rating, forKey: "rating")
aCoder.encode(self.hasChildren, forKey: "hasChildren")
aCoder.encode(self.parentId, forKey: "parentId")
aCoder.encode(self.status, forKey: "status")
aCoder.encode(self.width, forKey: "width")
aCoder.encode(self.height, forKey: "height")
aCoder.encode(self.isHeld, forKey: "isHeld")
aCoder.encode(self.flagDetail, forKey: "flagDetail")
}
required init?(coder aDecoder: NSCoder) {
self.id = aDecoder.decodeInteger(forKey: "id")
self.tags = aDecoder.decodeObject(forKey: "tags") as! String
self.createdAt = aDecoder.decodeInteger(forKey: "createdAt")
if aDecoder.containsValue(forKey: "creatorId") {
self.creatorId = aDecoder.decodeObject(forKey: "creatorId") as? Int
}
self.author = aDecoder.decodeObject(forKey: "author") as! String
self.change = aDecoder.decodeInteger(forKey: "change")
self.source = aDecoder.decodeObject(forKey: "source") as! String
self.score = aDecoder.decodeInteger(forKey: "score")
self.md5 = aDecoder.decodeObject(forKey: "md5") as! String
self.fileSize = aDecoder.decodeInteger(forKey: "fileSize")
self.fileUrl = aDecoder.decodeObject(forKey: "fileUrl") as! String
self.isShownInIndex = aDecoder.decodeBool(forKey: "isShownInIndex")
self.previewUrl = aDecoder.decodeObject(forKey: "previewUrl") as! String
self.previewWidth = aDecoder.decodeInteger(forKey: "previewWidth")
self.previewHeight = aDecoder.decodeInteger(forKey: "previewHeight")
self.actualPreviewWidth = aDecoder.decodeInteger(forKey: "actualPreviewWidth")
self.actualPreviewHeight = aDecoder.decodeInteger(forKey: "actualPreviewHeight")
self.sampleUrl = aDecoder.decodeObject(forKey: "sampleUrl") as! String
self.sampleWidth = aDecoder.decodeInteger(forKey: "sampleWidth")
self.sampleHeight = aDecoder.decodeInteger(forKey: "sampleHeight")
self.sampleFileSize = aDecoder.decodeInteger(forKey: "sampleFileSize")
self.jpegUrl = aDecoder.decodeObject(forKey: "jpegUrl") as! String
self.jpegWidth = aDecoder.decodeInteger(forKey: "jpegWidth")
self.jpegHeight = aDecoder.decodeInteger(forKey: "jpegHeight")
self.jpegFileSize = aDecoder.decodeInteger(forKey: "jpegFileSize")
self.rating = aDecoder.decodeObject(forKey: "rating") as! String
self.hasChildren = aDecoder.decodeBool(forKey: "hasChildren")
if aDecoder.containsValue(forKey: "parentId") {
self.parentId = aDecoder.decodeObject(forKey: "parentId") as? Int
}
self.status = aDecoder.decodeObject(forKey: "status") as! String
self.width = aDecoder.decodeInteger(forKey: "width")
self.height = aDecoder.decodeInteger(forKey: "height")
self.isHeld = aDecoder.decodeBool(forKey: "isHeld")
if aDecoder.containsValue(forKey: "flagDetail") {
self.flagDetail = aDecoder.decodeObject(forKey: "flagDetail") as? String
}
}
func getPreviewURL() -> URL {
var urlComponent = URLComponents(string: previewUrl)!
if urlComponent.scheme == nil {
urlComponent.scheme = "https"
}
return urlComponent.url(relativeTo: nil)!
}
func getSampleURL() -> URL {
var urlComponent = URLComponents(string: sampleUrl)!
if urlComponent.scheme == nil {
urlComponent.scheme = "https"
}
return urlComponent.url(relativeTo: nil)!
}
func getJpegURL() -> URL {
var urlComponent = URLComponents(string: jpegUrl)!
if urlComponent.scheme == nil {
urlComponent.scheme = "https"
}
return urlComponent.url(relativeTo: nil)!
}
func getFileURL() -> URL {
var urlComponent = URLComponents(string: fileUrl)!
if urlComponent.scheme == nil {
urlComponent.scheme = "https"
}
return urlComponent.url(relativeTo: nil)!
}
}
|
mit
|
2880eb3bd12b13ddc4b056a5a0b7097d
| 44.260417 | 88 | 0.648792 | 4.132192 | false | false | false | false |
nixzhu/Coolie
|
Sources/Coolie+Extensions.swift
|
1
|
16355
|
//
// Coolie+Extensions.swift
// Coolie
//
// Created by NIX on 16/11/3.
// Copyright © 2016年 nixWork. All rights reserved.
//
import Foundation
extension Coolie.Value {
var type: String {
switch self {
case .bool:
return "Bool"
case .number(let number):
switch number {
case .int:
return "Int"
case .double:
return "Double"
}
case .string:
return "String"
case .url:
return "URL"
case .date:
return "Date"
case .null(let value):
if let value = value {
return "\(value.type)?"
} else {
return "UnknownType?"
}
case .array(_, let values):
if let unionValue = unionValues(values) {
return "[\(unionValue.type)]"
} else {
return "UnknownType"
}
default:
fatalError("No type for: \(self)")
}
}
}
extension Coolie.Value {
func indent(with level: Int, into string: inout String) {
for _ in 0..<level {
string += "\t"
}
}
enum OrdinaryPropertyType {
case normal
case optional
case normalInArray
case optionalInArray
}
func generateOrdinaryProperty(of _type: OrdinaryPropertyType, with key: String, level: Int, into string: inout String) {
func normal(value: Coolie.Value) {
if value.isHyperString {
indent(with: level, into: &string)
string += "let \(key.coolie_lowerCamelCase)String = \(Coolie.Config.parameterName)[\"\(key)\"] as? String\n"
indent(with: level, into: &string)
switch value {
case .url:
string += "let \(key.coolie_lowerCamelCase) = \(key.coolie_lowerCamelCase)String.flatMap({ URL(string: $0) })\n"
case .date(let type):
switch type {
case .iso8601:
string += "let \(key.coolie_lowerCamelCase) = \(key.coolie_lowerCamelCase)String.flatMap({ \(Coolie.Config.DateFormatterName.iso8601).date(from: $0) })\n"
case .dateOnly:
string += "let \(key.coolie_lowerCamelCase) = \(key.coolie_lowerCamelCase)String.flatMap({ \(Coolie.Config.DateFormatterName.dateOnly).date(from: $0) })\n"
}
default:
fatalError("Unknown hyper string")
}
} else {
indent(with: level, into: &string)
let type = "\(value.type)"
string += "let \(key.coolie_lowerCamelCase) = \(Coolie.Config.parameterName)[\"\(key)\"] as? \(type)\n"
}
}
switch _type {
case .normal:
if case .null(let optionalValue) = self {
if let value = optionalValue {
normal(value: value)
} else {
indent(with: level, into: &string)
let type = "UnknownType"
string += "let \(key.coolie_lowerCamelCase) = \(Coolie.Config.parameterName)[\"\(key)\"] as? \(type)\n"
}
} else {
if isHyperString {
indent(with: level, into: &string)
string += "guard let \(key.coolie_lowerCamelCase)String = \(Coolie.Config.parameterName)[\"\(key)\"] as? String else { "
if Coolie.Config.throwsEnabled {
string += "throw ParseError.notFound(key: \"\(key)\") }\n"
} else {
string += Coolie.Config.debug ? "print(\"Not found url key: \(key)\"); return nil }\n" : "return nil }\n"
}
indent(with: level, into: &string)
switch self {
case .url:
string += "guard let \(key.coolie_lowerCamelCase) = URL(string: \(key.coolie_lowerCamelCase)String) else { "
if Coolie.Config.throwsEnabled {
string += "throw ParseError.failedToGenerate(property: \"\(key.coolie_lowerCamelCase)\") }\n"
} else {
string += Coolie.Config.debug ? "print(\"Not generate url key: \(key)\"); return nil }\n" : "return nil }\n"
}
case .date(let type):
switch type {
case .iso8601:
string += "guard let \(key.coolie_lowerCamelCase) = \(Coolie.Config.DateFormatterName.iso8601).date(from: \(key.coolie_lowerCamelCase)String) else { "
if Coolie.Config.throwsEnabled {
string += "throw ParseError.failedToGenerate(property: \"\(key.coolie_lowerCamelCase)\") }\n"
} else {
string += Coolie.Config.debug ? "print(\"Not generate date key: \(key)\"); return nil }\n" : "return nil }\n"
}
case .dateOnly:
string += "guard let \(key.coolie_lowerCamelCase) = \(Coolie.Config.DateFormatterName.dateOnly).date(from: \(key.coolie_lowerCamelCase)String) else { "
if Coolie.Config.throwsEnabled {
string += "throw ParseError.failedToGenerate(property: \"\(key.coolie_lowerCamelCase)\") }\n"
} else {
string += Coolie.Config.debug ? "print(\"Not generate date key: \(key)\"); return nil }\n" : "return nil }\n"
}
}
default:
fatalError("Unknown hyper string")
}
} else {
indent(with: level, into: &string)
string += "guard let \(key.coolie_lowerCamelCase) = \(Coolie.Config.parameterName)[\"\(key)\"] as? \(type) else { "
if Coolie.Config.throwsEnabled {
string += "throw ParseError.notFound(key: \"\(key)\") }\n"
} else {
string += Coolie.Config.debug ? "print(\"Not found key: \(key)\"); return nil }\n" : "return nil }\n"
}
}
}
case .optional:
normal(value: self)
case .normalInArray:
if isHyperString {
indent(with: level, into: &string)
string += "guard let \(key.coolie_lowerCamelCase)Strings = \(Coolie.Config.parameterName)[\"\(key)\"] as? [String] else { "
if Coolie.Config.throwsEnabled {
string += "throw ParseError.notFound(key: \"\(key)\") }\n"
} else {
string += Coolie.Config.debug ? "print(\"Not found url key: \(key)\"); return nil }\n" : "return nil }\n"
}
indent(with: level, into: &string)
switch self {
case .url:
string += "let \(key.coolie_lowerCamelCase) = \(key.coolie_lowerCamelCase)Strings.map({ URL(string: $0) }).flatMap({ $0 })\n"
case .date(let type):
switch type {
case .iso8601:
string += "let \(key.coolie_lowerCamelCase) = \(key.coolie_lowerCamelCase)Strings.map({ \(Coolie.Config.DateFormatterName.iso8601).date(from: $0) }).flatMap({ $0 })\n"
case .dateOnly:
string += "let \(key.coolie_lowerCamelCase) = \(key.coolie_lowerCamelCase)Strings.map({ \(Coolie.Config.DateFormatterName.dateOnly).date(from: $0) }).flatMap({ $0 })\n"
}
default:
fatalError("Unknown hyper string")
}
} else {
indent(with: level, into: &string)
string += "guard let \(key.coolie_lowerCamelCase) = \(Coolie.Config.parameterName)[\"\(key)\"] as? [\(type)] else { "
if Coolie.Config.throwsEnabled {
string += "throw ParseError.notFound(key: \"\(key)\") }\n"
} else {
string += Coolie.Config.debug ? "print(\"Not found key: \(key)\"); return nil }\n" : "return nil }\n"
}
}
case .optionalInArray:
if isHyperString {
indent(with: level, into: &string)
string += "guard let \(key.coolie_lowerCamelCase)Strings = \(Coolie.Config.parameterName)[\"\(key)\"] as? [String?] else { "
if Coolie.Config.throwsEnabled {
string += "throw ParseError.notFound(key: \"\(key)\") }\n"
} else {
string += Coolie.Config.debug ? "print(\"Not found url key: \(key)\"); return nil }\n" : "return nil }\n"
}
indent(with: level, into: &string)
switch self {
case .url:
string += "let \(key.coolie_lowerCamelCase) = \(key.coolie_lowerCamelCase)Strings.map({ $0.flatMap({ URL(string: $0) }) })\n"
case .date(let type):
switch type {
case .iso8601:
string += "let \(key.coolie_lowerCamelCase) = \(key.coolie_lowerCamelCase)Strings.map({ $0.flatMap({ \(Coolie.Config.DateFormatterName.iso8601).date(from: $0) }) })\n"
case .dateOnly:
string += "let \(key.coolie_lowerCamelCase) = \(key.coolie_lowerCamelCase)Strings.map({ $0.flatMap({ \(Coolie.Config.DateFormatterName.dateOnly).date(from: $0) }) })\n"
}
default:
fatalError("Unknown hyper string")
}
} else {
indent(with: level, into: &string)
string += "guard let \(key.coolie_lowerCamelCase) = \(Coolie.Config.parameterName)[\"\(key)\"] as? [\(type)?] else { "
if Coolie.Config.throwsEnabled {
string += "throw ParseError.failedToGenerate(property: \"\(key.coolie_lowerCamelCase)\") }\n"
} else {
string += Coolie.Config.debug ? "print(\"Not generate array key: \(key)\"); return nil }\n" : "return nil }\n"
}
}
}
}
}
extension Coolie.Value {
var isDictionaryOrArray: Bool {
switch self {
case .dictionary:
return true
case .array:
return true
default:
return false
}
}
var isDictionary: Bool {
switch self {
case .dictionary:
return true
default:
return false
}
}
var isArray: Bool {
switch self {
case .array:
return true
default:
return false
}
}
var isHyperString: Bool {
switch self {
case .url:
return true
case .date:
return true
default:
return false
}
}
var isNull: Bool {
switch self {
case .null:
return true
default:
return false
}
}
}
extension String {
var dateType: Coolie.Value.DateType? {
if Coolie.Config.iso8601DateFormatter.date(from: self) != nil {
return .iso8601
}
if Coolie.Config.dateOnlyDateFormatter.date(from: self) != nil {
return .dateOnly
}
return nil
}
}
extension Coolie.Value {
var upgraded: Coolie.Value {
switch self {
case .bool, .number, .url, .date, .null:
return self
case .string(let string):
if let url = URL(string: string), url.host != nil {
return .url(url)
}
if let dateType = string.dateType {
return .date(dateType)
}
return self
case .dictionary(let info):
var newInfo: [String: Coolie.Value] = [:]
for key in info.keys {
let value = info[key]!
newInfo[key] = value.upgraded
}
return .dictionary(newInfo)
case .array(let name, let values):
let newValues = values.map({ $0.upgraded })
return .array(name: name, values: newValues)
}
}
}
extension Coolie.Value {
private func union(_ otherValue: Coolie.Value) -> Coolie.Value {
switch (self, otherValue) {
case (.null(let aOptionalValue), .null(let bOptionalValue)):
switch (aOptionalValue, bOptionalValue) {
case (.some(let a), .some(let b)):
return .null(a.union(b))
case (.some(let a), .none):
return .null(a)
case (.none, .some(let b)):
return .null(b)
case (.none, .none):
return .null(nil)
}
case (.null(let value), let bValue):
if let aValue = value {
return .null(.some(aValue.union(bValue)))
} else {
return .null(.some(bValue))
}
case (let aValue, .null(let value)):
if let bValue = value {
return .null(.some(bValue.union(aValue)))
} else {
return .null(.some(aValue))
}
case (.bool, .bool):
return .bool(true)
case (.number(let aNumber), .number(let bNumber)):
switch (aNumber, bNumber) {
case (.int, .int):
return .number(.int(1))
default:
return .number(.double(1.0))
}
case (.string(let s1), .string(let s2)):
let string = s1.isEmpty ? s2 : s1
return .string(string)
case (.url(let u1), .url(let u2)):
let url = u1.host == nil ? u2 : u1
return .url(url)
case (.date(let d1), .date):
return .date(d1)
case (.dictionary(let aInfo), .dictionary(let bInfo)):
var info = aInfo
for key in aInfo.keys {
let aValue = aInfo[key]!
if let bValue = bInfo[key] {
info[key] = aValue.union(bValue)
} else {
info[key] = .null(aValue)
}
}
for key in bInfo.keys {
let bValue = bInfo[key]!
if let aValue = aInfo[key] {
info[key] = bValue.union(aValue)
} else {
info[key] = .null(bValue)
}
}
return .dictionary(info)
case (let .array(aName, aValues), let .array(bName, bValues)):
let values = (aValues + bValues)
if let first = values.first {
let value = values.dropFirst().reduce(first, { $0.union($1) })
return .array(name: aName ?? bName, values: [value])
} else {
return .array(name: aName ?? bName, values: [])
}
default:
fatalError("Unsupported union!")
}
}
func unionValues(_ values: [Coolie.Value]) -> Coolie.Value? {
if let first = values.first {
return values.dropFirst().reduce(first, { $0.union($1) })
} else {
return .dictionary([:])
}
}
}
extension String {
var coolie_dropLastCharacter: String {
if characters.count > 0 {
return String(characters.dropLast())
}
return self
}
var coolie_lowerCamelCase: String {
var symbolSet = CharacterSet.alphanumerics
symbolSet.formUnion(CharacterSet(charactersIn: "_"))
symbolSet.invert()
let validString = self.components(separatedBy: symbolSet).joined(separator: "_")
let parts = validString.components(separatedBy: "_")
return parts.enumerated().map({ index, part in
return index == 0 ? part : part.capitalized
}).joined(separator: "")
}
}
|
mit
|
5499f7f21ca0e60086e636b0379541ad
| 38.59322 | 192 | 0.47829 | 4.448313 | false | true | false | false |
grpc/grpc-swift
|
Sources/GRPC/ReadWriteStates.swift
|
1
|
7099
|
/*
* Copyright 2019, gRPC 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 NIOCore
import SwiftProtobuf
/// Number of messages expected on a stream.
enum MessageArity {
case one
case many
}
/// Encapsulates the state required to create a new write state.
struct PendingWriteState {
/// The number of messages we expect to write to the stream.
var arity: MessageArity
/// The 'content-type' being written.
var contentType: ContentType
func makeWriteState(messageEncoding: ClientMessageEncoding) -> WriteState {
let compression: CompressionAlgorithm?
switch messageEncoding {
case let .enabled(configuration):
compression = configuration.outbound
case .disabled:
compression = nil
}
let writer = LengthPrefixedMessageWriter(compression: compression)
return .writing(self.arity, self.contentType, writer)
}
}
/// The write state of a stream.
enum WriteState {
/// Writing may be attempted using the given writer.
case writing(MessageArity, ContentType, LengthPrefixedMessageWriter)
/// Writing may not be attempted: either a write previously failed or it is not valid for any
/// more messages to be written.
case notWriting
/// Writes a message into a buffer using the `writer` and `allocator`.
///
/// - Parameter message: The `Message` to write.
/// - Parameter allocator: An allocator to provide a `ByteBuffer` into which the message will be
/// written.
mutating func write(
_ message: ByteBuffer,
compressed: Bool,
allocator: ByteBufferAllocator
) -> Result<ByteBuffer, MessageWriteError> {
switch self {
case .notWriting:
return .failure(.cardinalityViolation)
case let .writing(writeArity, contentType, writer):
let buffer: ByteBuffer
do {
buffer = try writer.write(buffer: message, allocator: allocator, compressed: compressed)
} catch {
self = .notWriting
return .failure(.serializationFailed)
}
// If we only expect to write one message then we're no longer writable.
if case .one = writeArity {
self = .notWriting
} else {
self = .writing(writeArity, contentType, writer)
}
return .success(buffer)
}
}
}
enum MessageWriteError: Error {
/// Too many messages were written.
case cardinalityViolation
/// Message serialization failed.
case serializationFailed
/// An invalid state was encountered. This is a serious implementation error.
case invalidState
}
/// Encapsulates the state required to create a new read state.
struct PendingReadState {
/// The number of messages we expect to read from the stream.
var arity: MessageArity
/// The message encoding configuration, and whether it's enabled or not.
var messageEncoding: ClientMessageEncoding
func makeReadState(compression: CompressionAlgorithm? = nil) -> ReadState {
let reader: LengthPrefixedMessageReader
switch (self.messageEncoding, compression) {
case let (.enabled(configuration), .some(compression)):
reader = LengthPrefixedMessageReader(
compression: compression,
decompressionLimit: configuration.decompressionLimit
)
case (.enabled, .none),
(.disabled, _):
reader = LengthPrefixedMessageReader()
}
return .reading(self.arity, reader)
}
}
/// The read state of a stream.
enum ReadState {
/// Reading may be attempted using the given reader.
case reading(MessageArity, LengthPrefixedMessageReader)
/// Reading may not be attempted: either a read previously failed or it is not valid for any
/// more messages to be read.
case notReading
/// Consume the given `buffer` then attempt to read length-prefixed serialized messages.
///
/// For an expected message count of `.one`, this function will produce **at most** 1 message. If
/// a message has been produced then subsequent calls will result in an error.
///
/// - Parameter buffer: The buffer to read from.
mutating func readMessages(
_ buffer: inout ByteBuffer,
maxLength: Int
) -> Result<[ByteBuffer], MessageReadError> {
switch self {
case .notReading:
return .failure(.cardinalityViolation)
case .reading(let readArity, var reader):
reader.append(buffer: &buffer)
var messages: [ByteBuffer] = []
do {
while let serializedBytes = try reader.nextMessage(maxLength: maxLength) {
messages.append(serializedBytes)
}
} catch {
self = .notReading
if let grpcError = error as? GRPCError.WithContext {
if let compressionLimit = grpcError.error as? GRPCError.DecompressionLimitExceeded {
return .failure(.decompressionLimitExceeded(compressionLimit.compressedSize))
} else if let lengthLimit = grpcError.error as? GRPCError.PayloadLengthLimitExceeded {
return .failure(.lengthExceedsLimit(lengthLimit))
}
}
return .failure(.deserializationFailed)
}
// We need to validate the number of messages we decoded. Zero is fine because the payload may
// be split across frames.
switch (readArity, messages.count) {
// Always allowed:
case (.one, 0),
(.many, 0...):
self = .reading(readArity, reader)
return .success(messages)
// Also allowed, assuming we have no leftover bytes:
case (.one, 1):
// We can't read more than one message on a unary stream.
self = .notReading
// We shouldn't have any bytes leftover after reading a single message and we also should not
// have partially read a message.
if reader.unprocessedBytes != 0 || reader.isReading {
return .failure(.leftOverBytes)
} else {
return .success(messages)
}
// Anything else must be invalid.
default:
self = .notReading
return .failure(.cardinalityViolation)
}
}
}
}
enum MessageReadError: Error, Equatable {
/// Too many messages were read.
case cardinalityViolation
/// Enough messages were read but bytes there are left-over bytes.
case leftOverBytes
/// Message deserialization failed.
case deserializationFailed
/// The limit for decompression was exceeded.
case decompressionLimitExceeded(Int)
/// The length of the message exceeded the permitted maximum length.
case lengthExceedsLimit(GRPCError.PayloadLengthLimitExceeded)
/// An invalid state was encountered. This is a serious implementation error.
case invalidState
}
|
apache-2.0
|
13667dc17ddb5075ec9a15b3d0ac9f1a
| 31.268182 | 101 | 0.690802 | 4.621745 | false | false | false | false |
austinzheng/swift
|
benchmark/single-source/StackPromo.swift
|
12
|
1410
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let StackPromo = BenchmarkInfo(
name: "StackPromo",
runFunction: run_StackPromo,
tags: [.regression])
protocol Proto {
func at() -> Int
}
@inline(never)
func testStackAllocation(_ p: Proto) -> Int {
var a = [p, p, p]
var b = 0
a.withUnsafeMutableBufferPointer {
let array = $0
for i in 0..<array.count {
b += array[i].at()
}
}
return b
}
class Foo : Proto {
init() {}
func at() -> Int{
return 1
}
}
@inline(never)
func work(_ f: Foo) -> Int {
var r = 0
for _ in 0..<100_000 {
r += testStackAllocation(f)
}
return r
}
@inline(never)
func hole(_ use: Int, _ N: Int) {
if (N == 0) {
print("use: \(use)")
}
}
public func run_StackPromo(_ N: Int) {
let foo = Foo()
var r = 0
for i in 0..<N {
if i % 2 == 0 {
r += work(foo)
} else {
r -= work(foo)
}
}
hole(r, N)
}
|
apache-2.0
|
df1a0e2c267f3f1712940f25bbc0c9c3
| 19.142857 | 80 | 0.52766 | 3.56962 | false | false | false | false |
benlangmuir/swift
|
SwiftCompilerSources/Sources/Optimizer/TestPasses/SILPrinter.swift
|
8
|
1655
|
//===--- SILPrinter.swift - Example swift function pass -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SIL
let silPrinterPass = FunctionPass(name: "sil-printer", runSILPrinter)
func runSILPrinter(function: Function, context: PassContext) {
print("run SILPrinter on function: \(function.name)")
for (bbIdx, block) in function.blocks.enumerated() {
print("bb\(bbIdx):")
print(" predecessors: \(block.predecessors)")
print(" successors: \(block.successors)")
print(" arguments:")
for arg in block.arguments {
print(" arg: \(arg)")
for use in arg.uses {
print(" user: \(use.instruction)")
}
if let blockArg = arg as? BlockArgument, blockArg.isPhiArgument {
for incoming in blockArg.incomingPhiValues {
print(" incoming: \(incoming)")
}
}
}
print(" instructions:")
for inst in block.instructions {
print(" \(inst)")
for op in inst.operands {
print(" op: \(op.value)")
}
for (resultIdx, result) in inst.results.enumerated() {
for use in result.uses {
print(" user of result \(resultIdx): \(use.instruction)")
}
}
}
print()
}
}
|
apache-2.0
|
d8fa9a9f7e4c6683daa1cae6a96207ee
| 30.226415 | 80 | 0.580665 | 4.265464 | false | false | false | false |
Vanlol/MyYDW
|
SwiftCocoa/Resource/Main/View/MainHeaderView.swift
|
1
|
2327
|
//
// MainHeaderView.swift
// SwiftCocoa
//
// Created by admin on 2017/7/7.
// Copyright © 2017年 admin. All rights reserved.
//
import UIKit
class MainHeaderView: UIView {
//MARK: 初始化方法
class func mainView() -> MainHeaderView {
let vi = UINib(nibName: "MainHeaderView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! MainHeaderView
vi.frame = CGRect(x: 0, y: 0, width: 375, height: 300)
return vi
}
//MARK: 公告父视图
@IBOutlet weak var declarationView: UIView!
//MARK: BannerView视图
lazy var bannerView:InfiniteCircularView = {
let vi = InfiniteCircularView(frame: CGRect(x: 0, y: 0, width: C.SCREEN_WIDTH, height: 200))
return vi
}()
//MARK: 公告视图
lazy var noticeView:InfiniteNoticeView = {
let vi = InfiniteNoticeView(frame: CGRect(x: 0, y: 0, width: C.SCREEN_WIDTH, height: self.declarationView.bounds.size.height))
return vi
}()
//MARK: 更多公告点击回调
var moreDeclarationClosure:(() -> Void)?
//MARK: 银行存管点击回调
var bankDepositClosure:(() -> Void)?
//MARK: 新手福利点击回调
var noviceWelfareClosure:(() -> Void)?
//MARK: 邀请有礼点击回调
var inviteGiftClosure:(() -> Void)?
//MARK: 每日签到点击回调
var signBoardClosure:(() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
initView()
}
//MARK: 初始化View
fileprivate func initView() {
addSubview(bannerView)
declarationView.addSubview(noticeView)
}
//MARK: 更多公告按钮点击事件
@IBAction func moreDeclarationBtnClick(_ sender: Any) {
moreDeclarationClosure?()
}
//MARK: 银行存管按钮点击事件
@IBAction func bankDespositBtnClick(_ sender: Any) {
bankDepositClosure?()
}
//MARK: 新手福利按钮点击事件
@IBAction func noviceWelfareBtnClick(_ sender: Any) {
noviceWelfareClosure?()
}
//MARK: 邀请有礼按钮点击事件
@IBAction func inviteGiftBtnClick(_ sender: Any) {
inviteGiftClosure?()
}
//MARK: 每日签到按钮点击事件
@IBAction func signBoardBtnClick(_ sender: Any) {
signBoardClosure?()
}
}
|
apache-2.0
|
49602a741153190d7339845700e8d2b0
| 27.08 | 134 | 0.622507 | 3.727434 | false | false | false | false |
milseman/swift
|
test/decl/protocol/special/coding/class_codable_codingkeys_typealias.swift
|
15
|
895
|
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// Simple classes with all Codable properties whose CodingKeys come from a
// typealias should get derived conformance to Codable.
class SimpleClass : Codable {
var x: Int = 1
var y: Double = .pi
static var z: String = "foo"
private typealias CodingKeys = A // expected-note {{'CodingKeys' declared here}}
private typealias A = B
private typealias B = C
private typealias C = MyRealCodingKeys
private enum MyRealCodingKeys : String, CodingKey {
case x
case y
}
}
// They should receive synthesized init(from:) and an encode(to:).
let _ = SimpleClass.init(from:)
let _ = SimpleClass.encode(to:)
// The synthesized CodingKeys type should not be accessible from outside the
// class.
let _ = SimpleClass.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
|
apache-2.0
|
bdfb64f98abe9f77d2820aeb8eeeed1b
| 32.148148 | 120 | 0.727374 | 4.241706 | false | false | false | false |
123kyky/SteamReader
|
SteamReader/SteamReader/View/AppHeaderView.swift
|
1
|
4957
|
//
// AppHeaderView.swift
// SteamReader
//
// Created by Kyle Roberts on 4/29/16.
// Copyright © 2016 Kyle Roberts. All rights reserved.
//
import UIKit
import AlamofireImage
import Async
class AppHeaderView: UIView {
@IBOutlet var view: UIView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var aboutLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var releaseLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
var app: App?
var isObserving = false
var gradientLayer = CAGradientLayer()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
importView()
}
init() {
super.init(frame: CGRectZero)
importView()
}
func importView() {
for view in subviews {
view.removeFromSuperview()
}
NSBundle.mainBundle().loadNibNamed("AppHeaderView", owner: self, options: nil)
addSubview(view)
view.snp_makeConstraints { (make) in
make.edges.equalTo(self)
}
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
gradientLayer.frame = self.imageView.bounds
gradientLayer.colors = [self.view.backgroundColor!.CGColor as CGColorRef, UIColor.clearColor().CGColor as CGColorRef]
gradientLayer.startPoint = CGPoint(x: 0, y: 1)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
imageView.layer.addSublayer(gradientLayer)
}
func configureWithApp(app: App?) {
if isObserving {
app!.removeObserver(self, forKeyPath: "details")
}
self.app = app
nameLabel.text = app?.name
app!.addObserver(self, forKeyPath: "details", options: NSKeyValueObservingOptions.New, context: nil)
isObserving = true
if app!.details != nil {
configureWithDetails(app!.details!)
}
}
func configureWithDetails(details: AppDetails) {
let currencyFormatter = CurrencyFormatter()
let score = details.metacriticScore == 0 ? "--" : details.metacriticScore!.stringValue
var htmlAttributes: NSAttributedString? {
guard
let data = details.about!.dataUsingEncoding(NSUTF8StringEncoding)
else { return nil }
do {
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
aboutLabel.text = htmlAttributes?.string ?? ""
priceLabel.text = currencyFormatter.stringFromSteamPrice(details.currentPrice!)
releaseLabel.text = details.releaseDate!
scoreLabel.text = score + "/100"
imageView.af_setImageWithURL(NSURL(string: details.headerImage!)!, placeholderImage: nil, filter: AspectScaledToFillSizeWithRoundedCornersFilter(size: imageView.frame.size, radius: 5), imageTransition: .CrossDissolve(0.2), completion: { response in
Async.main {
self.imageView.image = response.result.value
self.gradientLayer.frame = self.imageView.bounds
}
})
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "details" && app!.details != nil {
Async.main {
self.configureWithDetails(self.app!.details!)
}
}
}
deinit {
if isObserving {
app?.removeObserver(self, forKeyPath: "details")
isObserving = false
}
}
}
class AppHeaderCell: UITableViewCell {
var appView: AppHeaderView?
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
appView = AppHeaderView()
contentView.addSubview(appView!)
appView?.snp_makeConstraints(closure: { (make) in
make.edges.equalTo(self)
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
appView?.imageView.af_cancelImageRequest()
appView?.imageView.layer.removeAllAnimations()
appView?.imageView.image = nil
if appView != nil && (appView!.isObserving) {
appView!.app!.removeObserver(appView!, forKeyPath: "details")
appView!.isObserving = false
}
}
}
|
mit
|
4841eaaa7988330851a2d5c94b3e4dad
| 32.261745 | 256 | 0.618442 | 5.109278 | false | false | false | false |
toshiapp/toshi-ios-client
|
Toshi/Extensions/UIStackView+Additions.swift
|
1
|
6756
|
// Copyright (c) 2018 Token Browser, Inc
//
// 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.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import TinyConstraints
import UIKit
extension UIStackView {
/// Adds given view as an arranged subview and constrains it to either the left and right or top and bottom of the caller, based on the caller's axis.
/// A vertical stack view will cause a subview to be constrained to the left and right, since top and bottom are handled by the stack view.
/// A horizontal stack view will cause a subview to be constrained to the top and bottom, since left and right are handled by the stack view.
///
/// - Parameters:
/// - view: The view to add and constrain.
/// - margin: Any additional margin to add. Defaults to zero. Will be the same on both sides it is applied to.
func addWithDefaultConstraints(view: UIView, margin: CGFloat = 0) {
self.addArrangedSubview(view)
switch self.axis {
case .vertical:
view.left(to: self, offset: margin)
view.right(to: self, offset: -margin)
case .horizontal:
view.top(to: self, offset: margin)
view.bottom(to: self, offset: -margin)
}
}
/// Adds a border view as an arranged subview and sets up its height constraint.
///
/// - Parameter margin: The margin to use when adding the border. Defaults to zero
/// - Returns: The added border view.
@discardableResult
func addStandardBorder(margin: CGFloat = 0) -> BorderView {
let border = BorderView()
addWithDefaultConstraints(view: border, margin: margin)
border.addHeightConstraint()
return border
}
/// Adds the given view as an arranged subview, and constrains it to the center of the opposite axis of the stack view.
/// A vertical stack view will cause a subview to be constrained to the center X of the stackview.
/// A horizontal stack view will cause a subview to be constrained to the center Y of the stackview.
///
/// - Parameter view: The view to add and constrain.
func addWithCenterConstraint(view: UIView) {
self.addArrangedSubview(view)
switch self.axis {
case .vertical:
view.centerX(to: self)
case .horizontal:
view.centerY(to: self)
}
}
/// Adds a background view to force a background color to be drawn.
/// https://stackoverflow.com/a/42256646/681493
///
/// - Parameters:
/// - color: The color for the background.
/// - margin: [Optional] The margin to add around the view. Useful when there's a margin where the view is pinned which you want to make sure has the appropriate background color. When nil, edges will simply be pinned to the stack view itself.
func addBackground(with color: UIColor, margin: CGFloat? = nil) {
let background = UIView()
background.backgroundColor = color
self.addSubview(background)
if let margin = margin {
background.topToSuperview(offset: -margin)
background.leftToSuperview(offset: -margin)
background.rightToSuperview(offset: -margin)
background.bottomToSuperview(offset: margin)
} else {
background.edgesToSuperview()
}
}
private static let spacerTag = 12345
/// Backwards compatibile way to add custom spacing between views of a stack view
/// NOTE: When iOS 11 support is dropped, this should be removed and `setCustomSpacing` should be used directly.
/// ALSO NOTE: On iOS 11, this doesn't work if there's no view below the view where you've added the custom spacing. Use `addSpacerView(with:after:)` instead.
///
/// - Parameters:
/// - spacing: The amount of spacing to add.
/// - view: The view to add the spacing after (to the right for horizontal, below for vertical)
func addSpacing(_ spacing: CGFloat, after view: UIView) {
if #available(iOS 11, *) {
setCustomSpacing(spacing, after: view)
} else {
guard let indexOfViewToInsertAfter = self.arrangedSubviews.index(of: view) else {
assertionFailure("You need to insert after one of the arranged subviews of this stack view!")
return
}
addSpacerView(with: spacing, after: indexOfViewToInsertAfter)
}
}
/// Inserts or adds a spacer view of the given size. Note that this should be used for bottom spacing - adding custom spacing in iOS 11 only works if there is a view below where you've added the custom spacing.
///
/// - Parameters:
/// - spacing: The amount of spacing to add.
/// - indexOfViewToInsertAfter: [optional] The index to insert the view after, or nil to just add to the end. Defaults to nil
/// - Returns: The layout constraint setting the size of the view, so if it can be adjusted if needed
@discardableResult
func addSpacerView(with spacing: CGFloat, after indexOfViewToInsertAfter: Int? = nil) -> NSLayoutConstraint {
let spacerView = UIView()
spacerView.tag = UIStackView.spacerTag
spacerView.backgroundColor = .clear
spacerView.setContentCompressionResistancePriority(.required, for: axis)
if let index = indexOfViewToInsertAfter {
insertArrangedSubview(spacerView, at: (index + 1))
} else {
addArrangedSubview(spacerView)
}
let heightOrWidthConstraint: NSLayoutConstraint
switch axis {
case .vertical:
heightOrWidthConstraint = spacerView.height(spacing)
spacerView.left(to: self)
spacerView.right(to: self)
case .horizontal:
heightOrWidthConstraint = spacerView.width(spacing)
spacerView.top(to: self)
spacerView.bottom(to: self)
}
return heightOrWidthConstraint
}
/// Empties the Stack view of its arranged subviews.
func removeAllArrangedSubviews() {
for view in arrangedSubviews {
view.removeFromSuperview()
}
}
}
|
gpl-3.0
|
fb864f3b3c5b3d6fdce7b42575dd9787
| 43.156863 | 249 | 0.65823 | 4.681913 | false | false | false | false |
toshiapp/toshi-ios-client
|
Toshi/Controllers/Sign In/SignInExplanation.swift
|
1
|
1831
|
import Foundation
import UIKit
import TinyConstraints
final class SignInExplanationViewController: UIViewController {
private lazy var titleLabel: UILabel = {
let view = UILabel()
view.text = Localized.passphrase_sign_in_explanation_title
view.textColor = Theme.darkTextColor
view.font = Theme.preferredTitle1()
view.adjustsFontForContentSizeCategory = true
view.numberOfLines = 0
return view
}()
private lazy var textLabel: UILabel = {
let attributedText = NSMutableAttributedString(string: Localized.passphrase_sign_in_explanation_text, attributes: [.font: Theme.preferredRegularMedium(), .foregroundColor: Theme.darkTextColor])
if let firstParagraph = attributedText.string.components(separatedBy: "\n\n").first, let range = (attributedText.string as NSString?)?.range(of: firstParagraph) {
attributedText.addAttribute(.font, value: Theme.semibold(size: 16), range: range)
}
let view = UILabel()
view.numberOfLines = 0
view.attributedText = attributedText
view.adjustsFontForContentSizeCategory = true
view.accessibilityIdentifier = AccessibilityIdentifier.passphraseSignInExplanationLabel.rawValue
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Theme.viewBackgroundColor
let stackView = UIStackView()
stackView.axis = .vertical
stackView.spacing = 22
view.addSubview(stackView)
stackView.top(to: layoutGuide())
stackView.leftToSuperview(offset: .largeInterItemSpacing)
stackView.rightToSuperview(offset: .largeInterItemSpacing)
stackView.addArrangedSubview(titleLabel)
stackView.addArrangedSubview(textLabel)
}
}
|
gpl-3.0
|
9c7bbd51903e0173627d1dbf8484b2c4
| 34.901961 | 201 | 0.700164 | 5.465672 | false | false | false | false |
wyz5120/VMovie
|
VMovie/Pods/Result/Result/Result.swift
|
21
|
7485
|
// Copyright (c) 2015 Rob Rix. All rights reserved.
/// An enum representing either a failure with an explanatory error, or a success with a result value.
public enum Result<T, Error: ErrorType>: ResultType, CustomStringConvertible, CustomDebugStringConvertible {
case Success(T)
case Failure(Error)
// MARK: Constructors
/// Constructs a success wrapping a `value`.
public init(value: T) {
self = .Success(value)
}
/// Constructs a failure wrapping an `error`.
public init(error: Error) {
self = .Failure(error)
}
/// Constructs a result from an Optional, failing with `Error` if `nil`.
public init(_ value: T?, @autoclosure failWith: () -> Error) {
self = value.map(Result.Success) ?? .Failure(failWith())
}
/// Constructs a result from a function that uses `throw`, failing with `Error` if throws.
public init(@autoclosure _ f: () throws -> T) {
self.init(attempt: f)
}
/// Constructs a result from a function that uses `throw`, failing with `Error` if throws.
public init(@noescape attempt f: () throws -> T) {
do {
self = .Success(try f())
} catch {
self = .Failure(error as! Error)
}
}
// MARK: Deconstruction
/// Returns the value from `Success` Results or `throw`s the error.
public func dematerialize() throws -> T {
switch self {
case let .Success(value):
return value
case let .Failure(error):
throw error
}
}
/// Case analysis for Result.
///
/// Returns the value produced by applying `ifFailure` to `Failure` Results, or `ifSuccess` to `Success` Results.
public func analysis<Result>(@noescape ifSuccess ifSuccess: T -> Result, @noescape ifFailure: Error -> Result) -> Result {
switch self {
case let .Success(value):
return ifSuccess(value)
case let .Failure(value):
return ifFailure(value)
}
}
// MARK: Higher-order functions
/// Returns `self.value` if this result is a .Success, or the given value otherwise. Equivalent with `??`
public func recover(@autoclosure value: () -> T) -> T {
return self.value ?? value()
}
/// Returns this result if it is a .Success, or the given result otherwise. Equivalent with `??`
public func recoverWith(@autoclosure result: () -> Result<T,Error>) -> Result<T,Error> {
return analysis(
ifSuccess: { _ in self },
ifFailure: { _ in result() })
}
// MARK: Errors
/// The domain for errors constructed by Result.
public static var errorDomain: String { return "com.antitypical.Result" }
/// The userInfo key for source functions in errors constructed by Result.
public static var functionKey: String { return "\(errorDomain).function" }
/// The userInfo key for source file paths in errors constructed by Result.
public static var fileKey: String { return "\(errorDomain).file" }
/// The userInfo key for source file line numbers in errors constructed by Result.
public static var lineKey: String { return "\(errorDomain).line" }
/// Constructs an error.
public static func error(message: String? = nil, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) -> NSError {
var userInfo: [String: AnyObject] = [
functionKey: function,
fileKey: file,
lineKey: line,
]
if let message = message {
userInfo[NSLocalizedDescriptionKey] = message
}
return NSError(domain: errorDomain, code: 0, userInfo: userInfo)
}
// MARK: CustomStringConvertible
public var description: String {
return analysis(
ifSuccess: { ".Success(\($0))" },
ifFailure: { ".Failure(\($0))" })
}
// MARK: CustomDebugStringConvertible
public var debugDescription: String {
return description
}
}
/// Returns `true` if `left` and `right` are both `Success`es and their values are equal, or if `left` and `right` are both `Failure`s and their errors are equal.
public func == <T: Equatable, Error: Equatable> (left: Result<T, Error>, right: Result<T, Error>) -> Bool {
if let left = left.value, right = right.value {
return left == right
} else if let left = left.error, right = right.error {
return left == right
}
return false
}
/// Returns `true` if `left` and `right` represent different cases, or if they represent the same case but different values.
public func != <T: Equatable, Error: Equatable> (left: Result<T, Error>, right: Result<T, Error>) -> Bool {
return !(left == right)
}
/// Returns the value of `left` if it is a `Success`, or `right` otherwise. Short-circuits.
public func ?? <T, Error> (left: Result<T, Error>, @autoclosure right: () -> T) -> T {
return left.recover(right())
}
/// Returns `left` if it is a `Success`es, or `right` otherwise. Short-circuits.
public func ?? <T, Error> (left: Result<T, Error>, @autoclosure right: () -> Result<T, Error>) -> Result<T, Error> {
return left.recoverWith(right())
}
// MARK: - Derive result from failable closure
public func materialize<T>(@noescape f: () throws -> T) -> Result<T, NSError> {
return materialize(try f())
}
public func materialize<T>(@autoclosure f: () throws -> T) -> Result<T, NSError> {
do {
return .Success(try f())
} catch {
return .Failure(error as NSError)
}
}
// MARK: - Cocoa API conveniences
/// Constructs a Result with the result of calling `try` with an error pointer.
///
/// This is convenient for wrapping Cocoa API which returns an object or `nil` + an error, by reference. e.g.:
///
/// Result.try { NSData(contentsOfURL: URL, options: .DataReadingMapped, error: $0) }
public func `try`<T>(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, `try`: NSErrorPointer -> T?) -> Result<T, NSError> {
var error: NSError?
return `try`(&error).map(Result.Success) ?? .Failure(error ?? Result<T, NSError>.error(function: function, file: file, line: line))
}
/// Constructs a Result with the result of calling `try` with an error pointer.
///
/// This is convenient for wrapping Cocoa API which returns a `Bool` + an error, by reference. e.g.:
///
/// Result.try { NSFileManager.defaultManager().removeItemAtURL(URL, error: $0) }
public func `try`(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, `try`: NSErrorPointer -> Bool) -> Result<(), NSError> {
var error: NSError?
return `try`(&error) ?
.Success(())
: .Failure(error ?? Result<(), NSError>.error(function: function, file: file, line: line))
}
// MARK: - Operators
infix operator >>- {
// Left-associativity so that chaining works like you’d expect, and for consistency with Haskell, Runes, swiftz, etc.
associativity left
// Higher precedence than function application, but lower than function composition.
precedence 100
}
/// Returns the result of applying `transform` to `Success`es’ values, or re-wrapping `Failure`’s errors.
///
/// This is a synonym for `flatMap`.
public func >>- <T, U, Error> (result: Result<T, Error>, @noescape transform: T -> Result<U, Error>) -> Result<U, Error> {
return result.flatMap(transform)
}
// MARK: - ErrorTypeConvertible conformance
/// Make NSError conform to ErrorTypeConvertible
extension NSError: ErrorTypeConvertible {
public static func errorFromErrorType(error: ErrorType) -> NSError {
return error as NSError
}
}
// MARK: -
/// An “error” that is impossible to construct.
///
/// This can be used to describe `Result`s where failures will never
/// be generated. For example, `Result<Int, NoError>` describes a result that
/// contains an `Int`eger and is guaranteed never to be a `Failure`.
public enum NoError: ErrorType { }
import Foundation
|
mit
|
35f9ec625f96cefc2e464d52e39ed993
| 32.075221 | 162 | 0.683478 | 3.63747 | false | false | false | false |
XiongJoJo/OFO
|
App/OFO/OFO/TimeController.swift
|
1
|
3284
|
//
// TimeController.swift
// OFO
//
// Created by JoJo on 2017/6/11.
// Copyright © 2017年 JoJo. All rights reserved.
//
import UIKit
class TimeController: UIViewController {
@IBOutlet weak var timeLab: UILabel!
@IBOutlet weak var moneyLab: UILabel!
fileprivate var remindTimerNumber: Int = 0
fileprivate var costTip: Int = 0
var userTime = 0
override func viewDidLoad() {
super.viewDidLoad()
title = "骑行中"
self.navigationItem.hidesBackButton = true //隐藏返回按钮
// self.removeGlobalPanGes()
// self.navigationController.removeGlobalPanGes()
Timer.every(1) { (timer: Timer) in
self.userTime += 1
self.timeLab.text = TimeHelper.getFormatTimeWithTimeInterval(timeInterval: Double(self.userTime))
switch self.remindTimerNumber/3600 {
case 0:
self.costTip = 1
case 1:
self.costTip = 2
case 2:
self.costTip = 3
case 3:
self.costTip = 4
case 4:
self.costTip = 5
case 5:
self.costTip = 6
default:
self.costTip = (self.costTip > 6) ? 6 : 0
break
}
self.moneyLab.text = "当前费用\(self.costTip)元"
//
// if self.remindSeconds == 0 {
// timer.invalidate()
//
// //时间结束跳转计时页面
// self.performSegue(withIdentifier: "toTimePage", sender: self)
//
// // Sound.play(file:"骑行结束_LH.m4a")//这里我们时间现实结束之后播放
//
// }
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// 移除全局手势
func removeGlobalPanGes() {
// for ges in self.view.gestureRecognizers! where ges is UIPanGestureRecognizer {
// print(ges)
// self.view.gestureRecognizers?.remove(at: 1)
// }
for case let ges as UIPanGestureRecognizer in self.view.gestureRecognizers! {
let i = self.view.gestureRecognizers?.index(of: ges)
self.view.gestureRecognizers?.remove(at: i!)
print(ges)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//由于此页面有两个跳转,所以需要指定
if segue.identifier == "toCostPage" {
let destVC = segue.destination as! CostController
destVC.moneyValue = self.costTip //传价格值
}
}
/*
// 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
|
0cf08f003102ee146c9984c454509647
| 28.392523 | 109 | 0.543084 | 4.480057 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
WordPress/WordPressUITests/Screens/Login/Unified/PasswordScreen.swift
|
1
|
2334
|
import UITestsFoundation
import XCTest
private struct ElementStringIDs {
static let navBar = "WordPress.PasswordView"
static let passwordTextField = "Password"
static let continueButton = "Continue Button"
static let errorLabel = "Password Error"
}
class PasswordScreen: BaseScreen {
let navBar: XCUIElement
let passwordTextField: XCUIElement
let continueButton: XCUIElement
init() {
let app = XCUIApplication()
navBar = app.navigationBars[ElementStringIDs.navBar]
passwordTextField = app.secureTextFields[ElementStringIDs.passwordTextField]
continueButton = app.buttons[ElementStringIDs.continueButton]
super.init(element: passwordTextField)
}
func proceedWith(password: String) -> LoginEpilogueScreen {
_ = tryProceed(password: password)
return LoginEpilogueScreen()
}
func tryProceed(password: String) -> PasswordScreen {
// A hack to make tests pass for RtL languages.
//
// An unintended side effect of calling passwordTextField.tap() while testing a RtL language is that the
// text field's secureTextEntry property gets set to 'false'. I suspect this happens because for RtL lanugagues,
// the secure text entry toggle button is displayed in the tap area of the passwordTextField.
//
// As a result, tests fail with the following error:
//
// "No matches found for Descendants matching type SecureTextField from input"
//
// Calling passwordTextField.doubleTap() prevents tests from failing by ensuring that the text field's
// secureTextEntry property remains 'true'.
passwordTextField.doubleTap()
passwordTextField.typeText(password)
continueButton.tap()
if continueButton.exists && !continueButton.isHittable {
waitFor(element: continueButton, predicate: "isEnabled == true")
}
return self
}
func verifyLoginError() -> PasswordScreen {
let errorLabel = app.cells[ElementStringIDs.errorLabel]
_ = errorLabel.waitForExistence(timeout: 2)
XCTAssertTrue(errorLabel.exists)
return self
}
static func isLoaded() -> Bool {
return XCUIApplication().buttons[ElementStringIDs.continueButton].exists
}
}
|
gpl-2.0
|
f327660ce611ff5fd7b08677b83574db
| 34.907692 | 120 | 0.687232 | 5.209821 | false | true | false | false |
hollarab/SwiftLafCOArtApp
|
LaffArtsDemo/DataParser.swift
|
1
|
1136
|
//
// DataParser.swift
// LaffArtsDemo
//
// Created by hollarab on 11/23/14.
// Copyright (c) 2014 a. brooks hollar. All rights reserved.
//
import UIKit
class DataParser: NSObject {
class var sharedInstance :DataParser {
struct Singleton {
static let instance = DataParser()
}
return Singleton.instance
}
var artWorks:[WorkOfArt]? = nil
//MARK: Data fetching
func fetchData(completion:(worksOfArt:[WorkOfArt]?) ->() ) {
let dataURL = NSURL(string:"https://raw.githubusercontent.com/saintsjd/lafayette-co-arts/master/lafayette-co-public-art.json")
let dataOpt = NSData(contentsOfURL: dataURL!)
if let data = dataOpt {
var error:NSError? = nil
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let array = jsonObject as? NSArray {
self.artWorks = WorkOfArt.parseObjsFromJSON(array)
completion(worksOfArt:artWorks)
}
}
}
}
|
mit
|
f193335cab37c68c92711aa3b8345d2d
| 27.4 | 147 | 0.611796 | 4.319392 | false | false | false | false |
wbaumann/SmartReceiptsiOS
|
SmartReceipts/Common/UI/FeedbackComposer.swift
|
2
|
3727
|
//
// FeedbackComposer.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 31/03/2019.
// Copyright © 2019 Will Baumann. All rights reserved.
//
import Foundation
import MessageUI
class FeedbackComposer: NSObject, MFMailComposeViewControllerDelegate {
weak var presentationViewController: UIViewController?
func present(on viewController: UIViewController, subject: String, attachments: [FeedbackAttachment] = []) {
presentationViewController = viewController
if !MFMailComposeViewController.canSendMail() {
Logger.warning("Mail services are not available.")
let title = LocalizedString("generic_error_alert_title")
let message = LocalizedString("error_email_not_configured_message")
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: LocalizedString("generic_button_title_ok"), style: .cancel, handler: nil))
return
}
// Configure the fields of the interface.
var messageBody = ""
// attach device info metadata
messageBody += "\n\n\nDebug info:\n"
messageBody += UIApplication.shared.appVersionInfoString()
messageBody += "Plus: \(PurchaseService.hasValidSubscriptionValue ? "true" : "false")\n"
messageBody += "\(UIDevice.current.deviceInfoString()!)\n"
messageBody += "Locale: \(Locale.current.identifier)"
let mailViewController = MFMailComposeViewController()
// Attach log files
Logger.logFiles()
.map { ($0.fileName, try? Data(contentsOf: URL(fileURLWithPath: $0.filePath))) }
.filter { $1 != nil }
.map { FeedbackAttachment(data: $1!, mimeType: "text/plain", fileName: $0) }
.adding(attachments)
.forEach { mailViewController.addAttachment($0) }
mailViewController.mailComposeDelegate = self
mailViewController.setToRecipients([FeedbackEmailAddress])
mailViewController.setSubject(subject)
mailViewController.setMessageBody(messageBody, isHTML: false)
if #available(iOS 13.0, *) {
mailViewController.navigationBar.tintColor = AppTheme.primaryColor
mailViewController.view.tintColor = AppTheme.primaryColor
} else {
mailViewController.navigationBar.tintColor = .white
}
viewController.present(mailViewController, animated: true)
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
guard result == .failed else {
controller.dismiss(animated: true, completion: nil)
return
}
Logger.warning("MFMailComposeResultFailed: \(error!.localizedDescription)")
let title = LocalizedString("generic_error_alert_title")
let alert = UIAlertController(title: title, message: error?.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: LocalizedString("generic_button_title_ok"), style: .cancel, handler: nil))
controller.dismiss(animated: true) { [weak self] in
self?.presentationViewController?.present(alert, animated: true, completion: nil)
}
}
}
struct FeedbackAttachment {
let data: Data
let mimeType: String
let fileName: String
}
extension MFMailComposeViewController {
func addAttachment(_ attachment: FeedbackAttachment) {
addAttachmentData(attachment.data, mimeType: attachment.mimeType, fileName: attachment.fileName)
}
}
|
agpl-3.0
|
6f0fb2fe9a21ce9ea7047df1a3015576
| 40.4 | 133 | 0.663178 | 5.240506 | false | false | false | false |
jairoeli/Habit
|
Zero/Sources/Utils/String+BoundingRect.swift
|
1
|
1435
|
//
// String+BoundingRect.swift
// Zero
//
// Created by Jairo Eli de Leon on 5/8/17.
// Copyright © 2017 Jairo Eli de León. All rights reserved.
//
import UIKit
extension String {
func boundingRect(with size: CGSize, attributes: [NSAttributedStringKey: Any]) -> CGRect {
let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
let rect = self.boundingRect(with: size, options: options, attributes: attributes, context: nil)
return snap(rect)
}
func size(thatFits size: CGSize, font: UIFont, maximumNumberOfLines: Int = 0) -> CGSize {
let attributes: [NSAttributedStringKey: Any] = [.font: font]
var size = self.boundingRect(with: size, attributes: attributes).size
if maximumNumberOfLines > 0 {
size.height = min(size.height, CGFloat(maximumNumberOfLines) * font.lineHeight)
}
return size
}
func width(with font: UIFont, maximumNumberOfLines: Int = 0) -> CGFloat {
let size = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
return self.size(thatFits: size, font: font, maximumNumberOfLines: maximumNumberOfLines).width
}
func height(fits width: CGFloat, font: UIFont, maximumNumberOfLines: Int = 0) -> CGFloat {
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
return self.size(thatFits: size, font: font, maximumNumberOfLines: maximumNumberOfLines).height
}
}
|
mit
|
baa57aba2da6559005dda4a67e40cdcc
| 36.710526 | 102 | 0.72575 | 4.316265 | false | true | false | false |
gaelfoppolo/handicarparking
|
HandiParking/HandiParking/RAMAnimatedTabBarController/Animations/BounceAnimation/RAMBounceAnimation.swift
|
1
|
2880
|
// RAMBounceAnimation.swift
//
// Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class RAMBounceAnimation : RAMItemAnimation {
override func playAnimation(icon : UIImageView, textLabel : UILabel) {
playBounceAnimation(icon)
textLabel.textColor = textSelectedColor
}
override func deselectAnimation(icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor) {
textLabel.textColor = defaultTextColor
let renderImage = icon.image?.imageWithRenderingMode(.AlwaysTemplate)
icon.image = renderImage
icon.tintColor = defaultTextColor
}
override func selectedState(icon : UIImageView, textLabel : UILabel) {
textLabel.textColor = textSelectedColor
let renderImage = icon.image?.imageWithRenderingMode(.AlwaysTemplate)
icon.image = renderImage
icon.tintColor = textSelectedColor
}
override func deselectedState(icon : UIImageView, textLabel : UILabel) {
textLabel.textColor = textDeselectedColor
let renderImage = icon.image?.imageWithRenderingMode(.AlwaysTemplate)
icon.image = renderImage
icon.tintColor = textDeselectedColor
}
func playBounceAnimation(icon : UIImageView) {
let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
bounceAnimation.values = [1.0 ,1.4, 0.9, 1.15, 0.95, 1.02, 1.0]
bounceAnimation.duration = NSTimeInterval(duration)
bounceAnimation.calculationMode = kCAAnimationCubic
icon.layer.addAnimation(bounceAnimation, forKey: "bounceAnimation")
let renderImage = icon.image?.imageWithRenderingMode(.AlwaysTemplate)
icon.image = renderImage
icon.tintColor = iconSelectedColor
}
}
|
gpl-3.0
|
b78e14b03931b4eaa37ba26f4dc7a948
| 39.56338 | 106 | 0.721528 | 5.106383 | false | false | false | false |
thekemkid/chooonz-server
|
Sources/App.swift
|
1
|
6674
|
import Kitura
import KituraNet
import SwiftyJSON
/**
Sets up all the routes for the Song List application
*/
func setupRoutes(router: Router, songs: SongCollection) {
router.all("/*", middleware: BodyParser())
// router.all("/*", middleware: AllRemoteOriginMiddleware())
// redirect to /songs
router.get("/") {
request, response, next in
do {
try response.redirect(config.firstPathSegment)
} catch {
print("problem with redirection")
}
next()
}
// Get all the songs
router.get(config.firstPathSegment) {
request, response, next in
songs.getAll() {
songs in
let json = JSON(SongCollectionArray.serialize(items: songs))
do {
try response.status(.OK).send(json: json).end()
} catch {
print("Song collection could not be serialized")
}
}
}
// Get information about a Song item by ID
router.get(config.firstPathSegment + "/:id") {
request, response, next in
// A guard let is similar to an if let, but it allows you to check for
// bad conditions and return if these bad conditions are met. It allows
// for cleaner code as code doesn't need to be nested in uneccessary if
// let statements.
guard let id = request.params["id"] else {
response.status(.badRequest)
print("Request does not contain ID")
return
}
songs.get(id) {
item in
if let item = item {
let result = JSON(item.serialize())
do {
try response.status(.OK).send(json: result).end()
} catch {
print("Error sending response")
}
} else {
print("Could not find the item", id)
response.status(.notFound)
return
}
}
}
// Get a Song image by ID
router.get(config.firstPathSegment + "/:id/image") {
request, response, next in
// A guard let is similar to an if let, but it allows you to check for
// bad conditions and return if these bad conditions are met. It allows
// for cleaner code as code doesn't need to be nested in uneccessary if
// let statements.
guard let id = request.params["id"] else {
response.status(.badRequest)
print("Request does not contain ID")
return
}
songs.get(id) {
item in
if let item = item {
do {
try response.send(fileName: "Images/" + item.image).end()
} catch {
print("Error sending response")
}
} else {
print("Could not find the item", id)
response.status(.notFound)
return
}
}
}
// Handle options
router.options("/*") {
request, response, next in
// response.setHeader("Access-Control-Allow-Headers", value: "accept, content-type")
// response.setHeader("Access-Control-Allow-Methods", value: "GET,HEAD,POST,DELETE,OPTIONS,PUT,PATCH")
response.status(.OK)
next()
}
// Add a Song list item
router.post(config.firstPathSegment + "/") {
request, response, next in
guard let body = request.body else {
response.status(.badRequest)
print("No body found in request")
return
}
guard case let .json(json) = body else {
response.status(.badRequest)
print("Body is invalid JSON")
return
}
let title = json["title"].stringValue
let name = json["name"].stringValue
let bio = json["bio"].stringValue
let youtubeId = json["youtubeId"].stringValue
let image = json["image"].stringValue
print("Received \(title)")
songs.add(title: title, name: name, bio: bio, youtubeId: youtubeId, image: image) {
newItem in
let result = JSON(newItem.serialize())
do {
try response.status(.OK).send(json: result).end()
} catch {
print("Error sending response")
}
}
}
// update some song
router.post(config.firstPathSegment + "/:id") {
request, response, next in
guard let id = request.params["id"] else {
response.status(.badRequest)
print("id parameter not found in request")
return
}
guard let body = request.body else {
response.status(.badRequest)
print("No body found in request")
return
}
guard case let .json(json) = body else {
response.status(.badRequest)
print("Body is invalid JSON")
return
}
let title = json["title"].stringValue
let name = json["name"].stringValue
let bio = json["bio"].stringValue
let youtubeId = json["youtubeId"].stringValue
let image = json["image"].stringValue
songs.update(id: id, title: title, name: name, bio: bio, youtubeId: youtubeId, image: image) {
newItem in
let result = JSON(newItem!.serialize())
response.status(.OK).send(json: result)
}
}
// Patch or update an existing Song item
router.patch(config.firstPathSegment + "/:id") {
request, response, next in
guard let id = request.params["id"] else {
response.status(.badRequest)
print("id parameter not found in request")
return
}
guard let body = request.body else {
response.status(.badRequest)
print("No body found in request")
return
}
guard case let .json(json) = body else {
response.status(.badRequest)
print("Body is invalid JSON")
return
}
let title = json["title"].stringValue
let name = json["name"].stringValue
let bio = json["bio"].stringValue
let youtubeId = json["youtubeId"].stringValue
let image = json["image"].stringValue
songs.update(id: id, title: title, name: name, bio: bio, youtubeId: youtubeId, image: image) {
newItem in
if let newItem = newItem {
let result = JSON(newItem.serialize())
do {
try response.status(.OK).send(json: result).end()
} catch {
print("Error sending response")
}
}
}
}
// Delete an individual Song item
router.delete(config.firstPathSegment + "/:id") {
request, response, next in
print("Requesting a delete")
guard let id = request.params["id"] else {
print("Could not parse ID")
response.status(.badRequest)
return
}
songs.delete(id) {
do {
try response.status(.OK).end()
} catch {
print("Could not produce response")
}
}
}
// Delete all the Song items
router.delete("/") {
request, response, next in
print("Requested clearing the entire list")
songs.clear() {
do {
try response.status(.OK).end()
} catch {
print("Could not produce response")
}
}
}
} // end of SetupRoutes()
|
mit
|
6b5120602e79b5d0daff78b450c9cb80
| 23.902985 | 106 | 0.604885 | 4.158255 | false | false | false | false |
OpenStack-mobile/OAuth2-Swift
|
Sources/OAuth2/FormURLEncoded.swift
|
1
|
4588
|
//
// FormURLEncoded.swift
// OAuth2
//
// Created by Alsey Coleman Miller on 12/21/16.
// Copyright © 2016 OpenStack. All rights reserved.
//
import SwiftFoundation
/// Form URL Encoded data for sending in an HTTP body.
public struct FormURLEncoded {
// MARK: - Properties
public var parameters: [String: String]
// MARK: - Initialization
public init(parameters: [String: String]) {
self.parameters = parameters
}
}
// MARK: - Equatable
extension FormURLEncoded: Equatable {
public static func == (lhs: FormURLEncoded, rhs: FormURLEncoded) -> Bool {
return lhs.parameters == rhs.parameters
}
}
// MARK: - DataConvertible
extension FormURLEncoded: DataConvertible {
public init?(data: Data) {
guard let string = String(UTF8Data: data)
else { return nil }
let components = string.components(separatedBy: "&")
var parameters = [String: String](minimumCapacity: components.count)
for component in components {
let subcomponents = component.components(separatedBy: "=")
guard subcomponents.count == 2,
let parameter = subcomponents[0].removingPercentEncoding,
let value = subcomponents[1].removingPercentEncoding
else { return nil }
parameters[parameter] = value
}
self.parameters = parameters
}
public func toData() -> Data {
return parameters.map({ "\($0)=\(FormURLEncoded.escape($1))" }).joined(separator: "&").toUTF8Data()
}
}
// MARK: - Utility Functions
public extension FormURLEncoded {
// https://github.com/Alamofire/Alamofire/blob/master/Source/ParameterEncoding.swift
/// Returns a percent-escaped string following RFC 3986 for a query string key or value.
///
/// RFC 3986 states that the following characters are "reserved" characters.
///
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
///
/// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
/// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
/// should be percent-escaped in the query string.
///
/// - parameter string: The string to be percent-escaped.
///
/// - returns: The percent-escaped string.
///
public static func escape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
var escaped = ""
//==========================================================================================================
//
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to:
//
// - https://github.com/Alamofire/Alamofire/issues/206
//
//==========================================================================================================
if #available(iOS 8.3, *) {
escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
} else {
let batchSize = 50
var index = string.startIndex
while index != string.endIndex {
let startIndex = index
let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex
let range = startIndex..<endIndex
let substring = string.substring(with: range)
escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? substring
index = endIndex
}
}
return escaped
}
}
|
mit
|
bbe1492990307fa66e4d1a513635feef
| 34.015267 | 118 | 0.551777 | 5.460714 | false | false | false | false |
nathawes/swift
|
test/Sema/keypath_subscript_nolabel.swift
|
8
|
1342
|
// RUN: %target-swift-frontend -typecheck -verify -primary-file %s
// [SR-12745]
// rdar://problem/62957095
struct S1 {
var x : Int = 0
}
var s1 = S1()
s1[\.x] = 10 // expected-error {{missing argument label 'keyPath:' in subscript}} {{4-4=keyPath: }}
struct S2 {
var x : Int = 0
subscript(_ v: Int) -> Int { 0 }
}
var s2 = S2()
s2[\.x] = 10 // expected-error {{missing argument label 'keyPath:' in subscript}} {{4-4=keyPath: }}
struct S3 {
var x : Int = 0
subscript(v v: KeyPath<S3, Int>) -> Int { get { 0 } set(newValue) {} }
}
var s3 = S3()
// TODO(diagnostics): This should actually be a diagnostic that correctly identifies that in the presence
// of a missing label, there are two options for resolution: 'keyPath' and 'v:' and to offer the user
// a choice.
// Today, the ExprTypeChecker identifies the disjunction with two of these possibilities, but
// filters out some of the terms based on label mismatch (but not implicit keypath terms, for example).
// It should probably not do that.
s3[\.x] = 10 // expected-error {{missing argument label 'keyPath:' in subscript}} {{4-4=keyPath: }}
struct S4 {
var x : Int = 0
subscript(v: KeyPath<S4, String>) -> Int { get { 0 } set(newValue) {} }
}
var s4 = S4()
s4[\.x] = 10 // expected-error {{key path value type 'Int' cannot be converted to contextual type 'String'}}
|
apache-2.0
|
8ac18b4b72f6e62f0556e85500ca1001
| 37.342857 | 108 | 0.661699 | 3.257282 | false | false | false | false |
snakajima/remoteio
|
ios/remoteio/remoteio/ScenePicker.swift
|
1
|
3129
|
//
// ScenePicker
// ioswall
//
// Created by satoshi on 10/20/16.
// Copyright © 2016 UIEvolution Inc. All rights reserved.
//
import UIKit
class ScenePicker: UITableViewController {
var scenes = [["name":"Main", "path":"/"]] as [[String:Any]]
var room = "N/A"
var index = 0
var sceneName = "Main"
var handler:SocketHandler!
let notificationManger = SNNotificationManager()
@IBOutlet var btnNext:UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = room
notificationManger.addObserver(forName: SocketHandler.didConnectionChange, object: nil, queue: OperationQueue.main) { [unowned self] (_) in
self.tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
let scripts = handler.scripts
return scripts.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let script = handler.scripts[section]
return script["title"] as? String
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let script = handler.scripts[section]
scenes = script["scenes"] as? [[String:Any]] ?? [[String:Any]]()
return scenes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "standard", for: indexPath)
cell.textLabel?.text = scenes[indexPath.row]["name"] as? String
return cell
}
private func moveTo(index:Int) {
var scene = scenes[index]
guard let name = scene["name"] as? String else {
return
}
self.index = index
scene["index"] = index
sceneName = name
handler.switchTo(scene:scene)
btnNext.isEnabled = (index + 1 < scenes.count)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
moveTo(index: indexPath.row)
}
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
moveTo(index: indexPath.row)
performSegue(withIdentifier: "scene", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? SceneViewController {
vc.scene = sceneName
vc.handler = handler
} else if let vc = segue.destination as? ClientController {
vc.handler = handler
handler.scan()
}
}
@IBAction func next() {
if index + 1 < scenes.count {
moveTo(index: index + 1)
tableView.selectRow(at: [0, index], animated: true, scrollPosition: UITableViewScrollPosition.none)
}
}
}
|
mit
|
dbbd92882dcb5d837d38512588f1a0b2
| 32.276596 | 147 | 0.631074 | 4.797546 | false | false | false | false |
chenchangqing/travelMapMvvm
|
travelMapMvvm/travelMapMvvm/ViewModels/ForgetPwdViewModel.swift
|
1
|
8013
|
//
// ForgetPwdViewModel.swift
// travelMapMvvm
//
// Created by green on 15/9/8.
// Copyright (c) 2015年 travelMapMvvm. All rights reserved.
//
import Foundation
import ReactiveCocoa
import ReactiveViewModel
class ForgetPwdViewModel: RVMViewModel {
// MARK: - 提示信息
dynamic var failureMsg: String = "" // 操作失败提示
dynamic var successMsg: String = "" // 操作失败提示
// MARK: - 文本输入内容
dynamic var telephone : String = "" // 手机号输入框文本
dynamic var password : String = "" // 第一个密码输入框文本
dynamic var password2 : String = "" // 第二个密码输入框文本
dynamic var verifyCode : String = "" // 验证码输入框文本
// MARK: - 被UI绑定的属性
dynamic var submitBtnEnabled = false // 修改密码按钮是否可以点击
dynamic var sendVerifyCodeBtnEnabled = false // 发送验证码短信按钮是否可以点击
// buttons背景色
dynamic var submitBtnBgColor = UIButton.enabledBackgroundColor
dynamic var sendVerifyCodeBtnBgColor = UIButton.enabledBackgroundColor
// textFields背景色
dynamic var telephoneFieldBgColor = UIColor.clearColor()
dynamic var passwordFieldBgColor = UIColor.clearColor()
dynamic var password2FieldBgColor = UIColor.clearColor()
dynamic var verifyCodeFieldBgColor = UIColor.clearColor()
// MARK: - 命令
var sendVerityCodeCommand:RACCommand! // 发送验证码命令
var modifyPwdCommand: RACCommand! // 修改密码命令
var commitVerifyCodeCommand: RACCommand! // 验证验证码命令
// MARK: - 文本校验信号
var telephoneSignal: RACSignal! // 手机校验信号
var passwordSignal: RACSignal! // 第一个密码校验信号
var password2Signal: RACSignal! // 第二个密码校验信号
var verifyCodeSignal: RACSignal! // 验证码校验信号
// MARK: - 数据操作类
private let userModelDataSourceProtocol = NetworkUserModelDataSource.shareInstance()
private let smsDataSourceProtocol = SMSDataSource.shareInstance()
// MARK: - INIT
override init() {
super.init()
// 查询默认区号
let countryAndAreaCode = self.smsDataSourceProtocol.queryCountryAndAreaCode()
let zoneCode = countryAndAreaCode.areaCode.stringByReplacingOccurrencesOfString("+", withString: "")
// 初始化发送验证码命令
sendVerityCodeCommand = RACCommand(signalBlock: { (any:AnyObject!) -> RACSignal! in
return self.smsDataSourceProtocol.getVerificationCodeBySMS(self.telephone, zone: zoneCode).materialize()
})
// 初始化修改密码命令
modifyPwdCommand = RACCommand(signalBlock: { (any:AnyObject!) -> RACSignal! in
return self.userModelDataSourceProtocol.modifyPwd(self.telephone, password: self.password).materialize()
})
// 初始化验证验证码命令
commitVerifyCodeCommand = RACCommand(signalBlock: { (any:AnyObject!) -> RACSignal! in
return self.smsDataSourceProtocol.commitVerityCode(self.verifyCode).materialize()
})
// 重置提示信息
RACSignal.merge([
sendVerityCodeCommand.executionSignals,
modifyPwdCommand.executionSignals,
commitVerifyCodeCommand.executionSignals
]).subscribeNext { (any:AnyObject!) -> Void in
self.failureMsg = ""
self.successMsg = ""
}
// 初始化校验信号
setupSignal()
// 更新UI
updateUI()
}
// MARK: - 初始化文本校验信号
/**
* 初始化信号
*/
private func setupSignal() {
// 手机号正确
telephoneSignal = RACObserve(self, "telephone").ignore("").mapAs { (telephone:NSString) -> NSNumber in
return ValidHelper.isValidTelephone(telephone)
}
// 验证码正确
verifyCodeSignal = RACObserve(self, "verifyCode").ignore("").mapAs { (verifyCode:NSString) -> NSNumber in
return ValidHelper.isValidVerifyCode(verifyCode)
}
// 第一个密码信号
passwordSignal = RACObserve(self, "password").ignore("").mapAs({ (password:NSString) -> NSNumber in
return ValidHelper.isValidPassword(password)
})
// 第二个密码信号
password2Signal = RACObserve(self, "password2").ignore("").mapAs({ (password:NSString) -> NSNumber in
return ValidHelper.isValidPassword(password)
})
}
// MARK: - 更新UI
/**
* 更新UI
*/
private func updateUI() {
// 发送验证码按钮
telephoneSignal ~> RAC(self,"sendVerifyCodeBtnEnabled")
telephoneSignal.mapAs({ (isValid:NSNumber) -> UIColor in
return isValid.boolValue ? UIButton.defaultBackgroundColor : UIButton.enabledBackgroundColor
}) ~> RAC(self,"sendVerifyCodeBtnBgColor")
// 修改密码按钮是否可以点击信号
let submitBtnEnabledSignal = getSubmitBtnEnabledSignal()
submitBtnEnabledSignal ~> RAC(self,"submitBtnEnabled")
// 修改密码按钮背景色信号
let submitBtnBgColorSignal = getSubmitBtnBgColorSignal()
submitBtnBgColorSignal ~> RAC(self,"submitBtnBgColor")
// 修改textField背景色
telephoneSignal.mapAs({ (isValid:NSNumber) -> UIColor in
return isValid.boolValue ? UIColor.clearColor() : UITextField.warningBackgroundColor
}) ~> RAC(self,"telephoneFieldBgColor")
passwordSignal.mapAs({ (isValid:NSNumber) -> UIColor in
return isValid.boolValue ? UIColor.clearColor() : UITextField.warningBackgroundColor
}) ~> RAC(self,"passwordFieldBgColor")
password2Signal.mapAs({ (isValid:NSNumber) -> UIColor in
return isValid.boolValue ? UIColor.clearColor() : UITextField.warningBackgroundColor
}) ~> RAC(self,"password2FieldBgColor")
verifyCodeSignal.mapAs({ (isValid:NSNumber) -> UIColor in
return isValid.boolValue ? UIColor.clearColor() : UITextField.warningBackgroundColor
}) ~> RAC(self,"verifyCodeFieldBgColor")
}
// MARK: - 得到修改密码按钮是否可以点击信号
/**
* 修改密码按钮是否可以点击
*/
private func getSubmitBtnEnabledSignal() -> RACSignal {
/** 手机号正确 && 验证码正确 && 2个密码正确 **/
return RACSignal.combineLatest([
telephoneSignal,verifyCodeSignal,passwordSignal,password2Signal
]).mapAs({ (tuple: RACTuple) -> NSNumber in
let first = tuple.first as! Bool
let second = tuple.second as! Bool
let third = tuple.third as! Bool
let fourth = tuple.fourth as! Bool
let submitBtnEnabled = first && second && third && fourth
// 密码一致
let pwdEqual = self.password == self.password2
return submitBtnEnabled && pwdEqual
})
}
// MARK: - 得到修改密码按钮背景色信号
/**
* 修改密码按钮背景色信号
*/
private func getSubmitBtnBgColorSignal() -> RACSignal {
return getSubmitBtnEnabledSignal().mapAs({ (submitBtnEnabled:NSNumber) -> UIColor in
return submitBtnEnabled.boolValue ? UIButton.defaultBackgroundColor : UIButton.enabledBackgroundColor
})
}
}
|
apache-2.0
|
5a8927a3a5b3bf2746f095be0c297325
| 32.131818 | 116 | 0.60118 | 4.757833 | false | false | false | false |
ngageoint/mage-ios
|
Mage/NavigationControllerObserver.swift
|
1
|
5932
|
//
// NavigationControllerObserver.swift
// MAGE
//
// Created by Daniel Barela on 4/6/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
@objc public protocol NavigationControllerObserverDelegate {
/**
Callback when a `viewController` is popped from the `navigationController` stack
- parameter observer: the observer that observed the pop transition
- parameter viewController: the `UIViewController` that has been popped from the stack
*/
func navigationControllerObserver(_ observer: NavigationControllerObserver,
didObservePopTransitionFor viewController: UIViewController)
}
// We can't use Weak<T: AnyObject> here because we would have
// to declare NavigationControllerObserverDelegate as @objc
private class NavigationControllerObserverDelegateContainer {
private(set) weak var value: NavigationControllerObserverDelegate?
init(value: NavigationControllerObserverDelegate) {
self.value = value
}
}
/**
The `NavigationControllerObserver` class provides a simple API to observe the
pop transitions that occur in a `navigationController` stack.
One drawback of `UINavigationController` is that its delegate is shared among multiple
view controllers and this requires a lot of bookkeeping to register multiple delegates.
`NavigationControllerObserver` allows to register a delegate per viewController we want to observe.
What's more the class provides a `navigationControllerDelegate` property used to forward all the
`UINavigationControllerDelegate` methods to another navigationController delegate if need be.
- important: The `NavigationControllerObserver` will observe only *animated* pop transitions.
Indeed, if you call `popViewController(animated: false)` you won't be notified.
*/
@objc public class NavigationControllerObserver : NSObject, UINavigationControllerDelegate {
/**
All calls from `UINavigationControllerDelegate` methods are forwarded to this object
*/
@objc public weak var navigationControllerDelegate: UINavigationControllerDelegate? {
didSet {
// Make the navigationController reevaluate respondsToSelector
// for UINavigationControllerDelegate methods
navigationController.delegate = nil
navigationController.delegate = self
}
}
private var viewControllersToDelegates: [UIViewController: NavigationControllerObserverDelegateContainer] = [:]
private let navigationController: UINavigationController
/**
- parameter navigationController: the `UINavigationController` we want to observe
*/
@objc public init(navigationController: UINavigationController) {
self.navigationController = navigationController
super.init()
navigationController.delegate = self
}
//MARK: - NSObject
@objc override public func responds(to aSelector: Selector!) -> Bool {
if shouldForwardSelector(aSelector) {
return navigationControllerDelegate?.responds(to: aSelector) ?? false
}
return super.responds(to: aSelector)
}
@objc override public func forwardingTarget(for aSelector: Selector!) -> Any? {
if shouldForwardSelector(aSelector) {
return navigationControllerDelegate
}
return super.forwardingTarget(for: aSelector)
}
//MARK: - Public
/**
Observe a pop transition in the `navigationController` stack
- parameter viewController: the `UIViewController` instance to observe in the `navigationController` stack
- parameter delegate: The delegate that will be notified of the transition
*/
@objc public func observePopTransition(of viewController: UIViewController,
delegate: NavigationControllerObserverDelegate) {
let wrappedDelegate = NavigationControllerObserverDelegateContainer(value: delegate)
viewControllersToDelegates[viewController] = wrappedDelegate
}
//MARK: - UINavigationControllerDelegate
@objc public func navigationController(_ navigationController: UINavigationController,
didShow viewController: UIViewController,
animated: Bool) {
navigationControllerDelegate?.navigationController?(
navigationController,
didShow: viewController,
animated: animated
)
guard
let fromViewController = navigationController.transitionCoordinator?.viewController(forKey: .from),
!navigationController.viewControllers.contains(fromViewController) else {
return
}
if let wrappedDelegate = viewControllersToDelegates[fromViewController] {
let delegate = wrappedDelegate.value
delegate?.navigationControllerObserver(self, didObservePopTransitionFor: fromViewController)
viewControllersToDelegates.removeValue(forKey: fromViewController)
}
cleanOutdatedViewControllers()
}
//MARK: - Private
private func shouldForwardSelector(_ aSelector: Selector!) -> Bool {
let description = protocol_getMethodDescription(UINavigationControllerDelegate.self, aSelector, false, true)
return
description.name != nil // belongs to UINavigationControllerDelegate
&& class_getInstanceMethod(type(of: self), aSelector) == nil // self does not implement aSelector
}
private func cleanOutdatedViewControllers() {
let viewControllersToRemove = viewControllersToDelegates.keys.filter {
$0.parent != self.navigationController
}
viewControllersToRemove.forEach {
viewControllersToDelegates.removeValue(forKey: $0)
}
}
}
|
apache-2.0
|
0e404b4e7b21ac9c47fea30215fb3550
| 42.291971 | 116 | 0.70612 | 6.15249 | false | false | false | false |
soapyigu/LeetCode_Swift
|
DP/UniquePathsII.swift
|
1
|
1143
|
/**
* Question Link: https://leetcode.com/problems/unique-paths-ii/
* Primary idea: 2D Dynamic Programming, use a 2D array as a cache to store calculated data
* Time Complexity: O(mn), Space Complexity: O(mn)
*/
class UniquePathsII {
func uniquePathsWithObstacles(_ obstacleGrid: [[Int]]) -> Int {
let m = obstacleGrid.count
guard m > 0 else {
return 0
}
let n = obstacleGrid[0].count
guard n > 0 else {
return 0
}
var dp = Array(repeating: Array(repeating: -1, count: n), count: m)
return help(m - 1, n - 1, &dp, obstacleGrid)
}
fileprivate func help(_ m: Int, _ n: Int, _ dp: inout [[Int]], _ obstacleGrid: [[Int]]) -> Int {
if m < 0 || n < 0 {
return 0
}
if obstacleGrid[m][n] == 1 {
return 0
}
if m == 0 && n == 0 {
return 1
}
if dp[m][n] != -1 {
return dp[m][n]
}
dp[m][n] = help(m - 1, n, &dp, obstacleGrid) + help(m, n - 1, &dp, obstacleGrid)
return dp[m][n]
}
}
|
mit
|
752e96340c7c0e136444d692f591dff1
| 26.902439 | 100 | 0.48119 | 3.59434 | false | false | false | false |
payjp/payjp-ios
|
example-swift/example-swift/ViewController.swift
|
1
|
4153
|
//
// ViewController.swift
// Example
//
// Created by Tatsuya Kitagawa on 2017/12/07.
// Copyright © 2017年 PAY, Inc. All rights reserved.
//
import UIKit
import PAYJP
class ViewController: UITableViewController {
@IBOutlet weak var fieldCardNumber: UITextField!
@IBOutlet weak var fieldCardCvc: UITextField!
@IBOutlet weak var fieldCardMonth: UITextField!
@IBOutlet weak var fieldCardYear: UITextField!
@IBOutlet weak var filedCardName: UITextField!
@IBOutlet weak var labelTokenId: UILabel!
private let payjpClient: PAYJP.APIClient = PAYJP.APIClient.shared
enum CellSection: Int {
case CardInformation = 0
case CreateToken = 1
case TokenId = 2
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch CellSection(rawValue: indexPath.section) {
case .CreateToken?:
createToken()
tableView.deselectRow(at: indexPath, animated: true)
case .TokenId?:
getToken()
tableView.deselectRow(at: indexPath, animated: true)
default: break
}
}
private func createToken() {
print("createToken")
let number = fieldCardNumber.text ?? ""
let cvc = fieldCardCvc.text ?? ""
let month = fieldCardMonth.text ?? ""
let year = fieldCardYear.text ?? ""
let name = filedCardName.text ?? ""
print("input number=\(number), cvc=\(cvc), month=\(month), year=\(year) name=\(name)")
payjpClient.createToken(
with: number,
cvc: cvc,
expirationMonth: month,
expirationYear: year,
name: name) { [weak self] result in
switch result {
case .success(let token):
DispatchQueue.main.async {
self?.labelTokenId.text = token.identifer
self?.tableView.reloadData()
self?.showToken(token: token)
}
case .failure(let error):
if let payError = error.payError {
print("[errorResponse] \(payError.description)")
}
DispatchQueue.main.async {
self?.labelTokenId.text = ""
self?.showError(error: error)
}
}
}
}
private func getToken() {
let tokenId = labelTokenId.text ?? ""
print("getToken with \(tokenId)")
payjpClient.getToken(with: tokenId) { [weak self] result in
switch result {
case .success(let token):
DispatchQueue.main.async {
self?.labelTokenId.text = token.identifer
self?.tableView.reloadData()
self?.showToken(token: token)
}
case .failure(let error):
DispatchQueue.main.async {
self?.labelTokenId.text = ""
self?.showError(error: error)
}
}
}
}
}
extension Token {
var display: String {
return "id=\(identifer),\n"
+ "card.id=\(card.identifer),\n"
+ "card.last4=\(card.last4Number),\n"
+ "card.exp=\(card.expirationMonth)/\(card.expirationYear),\n"
+ "card.name=\(card.name ?? "nil")"
}
}
extension UIViewController {
func showToken(token: Token) {
let alert = UIAlertController(
title: "success",
message: token.display,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func showError(error: Error) {
let alert = UIAlertController(
title: "error",
message: error.localizedDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
|
mit
|
8d3275401f68af7549d76305b374af90
| 31.421875 | 94 | 0.558072 | 4.710556 | false | false | false | false |
hshidara/iOS
|
A~Maze/A~Maze/Maze.swift
|
1
|
5542
|
//
// Maze.swift
// A~Maze
//
// Created by Hidekazu Shidara on 5/24/15.
// Copyright (c) 2015 Hidekazu Shidara. All rights reserved.
//
import UIKit
import Foundation
import SpriteKit
class Maze: SKScene {
// Main Character.
let runner = SKSpriteNode(imageNamed: "Spaceship")
override func didMoveToView(view: SKView)
{
// Affects how fast the wall falls. Affects the gravity.
self.physicsWorld.gravity = CGVectorMake(0, -0.15)
self.createRunner()
self.routeA()
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
{
let touch = touches.anyObject()! as UITouch
let location = touch.locationInNode(self)
runner.position = location
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent)
{
let touch = touches.anyObject()! as UITouch
let location = touch.locationInNode(self)
runner.position = location
}
// Creates the maze runner.
func createRunner()
{
runner.setScale(0.15)
runner.position = CGPointMake(200, 200)
runner.name = "RunnerNode"
runner.physicsBody = SKPhysicsBody(circleOfRadius: runner.size.width/2)
runner.physicsBody?.usesPreciseCollisionDetection = true
runner.physicsBody?.mass = 1000.0
runner.physicsBody?.density = 100.0
runner.physicsBody?.dynamic = true // Will not change position
runner.physicsBody?.pinned = false
runner.physicsBody?.allowsRotation = false
runner.physicsBody?.affectedByGravity = false // Will not be affected by the gravitational field.
self.addChild(runner)
}
// Creates the vertical wall.
func createVerticalWall(xPlacement: CGFloat, yPlacement: CGFloat)-> SKSpriteNode // Returns the newly created vertical wall.
{
let wallSize = CGSizeMake(35,250)
let wallColor = UIColor.darkGrayColor()
let verticalWall = SKSpriteNode(color: wallColor, size: wallSize)
let verticalWallSize = CGSizeMake(35, 250) // Cuz the rectangleofsize needs a CGSize.
verticalWall.position = CGPointMake(xPlacement, yPlacement)
verticalWall.name = "verticalWall"
verticalWall.physicsBody = SKPhysicsBody(rectangleOfSize: verticalWallSize)
verticalWall.physicsBody?.mass = 100000.0 // Makes it hard to move.
verticalWall.physicsBody?.density = 100000.0
verticalWall.physicsBody?.allowsRotation = false
verticalWall.physicsBody?.usesPreciseCollisionDetection = true
self.addChild(verticalWall)
return verticalWall
}
//Creates the horizontal wall.
func createHorizontalWall(xPlacement: CGFloat, yPlacement: CGFloat)-> SKSpriteNode // Returns the newly created horizontal wall.
{
let wallSize = CGSizeMake(250,20)
let wallColor = UIColor.darkGrayColor()
let horizontalWall = SKSpriteNode(color: wallColor, size: wallSize)
let horizontalWallSize = CGSizeMake(250, 20)
horizontalWall.position = CGPointMake(xPlacement, yPlacement)
horizontalWall.name = "HorizontalWall"
horizontalWall.physicsBody = SKPhysicsBody(rectangleOfSize: horizontalWallSize)
horizontalWall.physicsBody?.density = 10000000.0
horizontalWall.physicsBody?.mass = 10000000.0
horizontalWall.physicsBody?.allowsRotation = false
horizontalWall.physicsBody?.usesPreciseCollisionDetection = true
self.addChild(horizontalWall)
return horizontalWall
}
// HorizontalWall.position = CGPointMake(self.xScale + 1, self.yScale + 1)
// Decides when game ends.
// Collision handling in the sides of the screen too.
override func update(currentTime: CFTimeInterval)// Called before each frame is rendered.
{
if(runner.position.y <= 0.0) // Prints out a label that says game over. Freezes everything.
{
println("Game over.")
}
if(runner.position.x <= 0.0 || runner.position.x >= 1000.0)
{
println("Out of bounds")
}
}
func routeA()
{
let actionSequence = SKAction.sequence([
SKAction.runBlock({(self.patternOne())}),
SKAction.waitForDuration(5.0),
SKAction.runBlock({(self.patternOne())})
])
runAction(actionSequence)
}
// Create a pattern.
func patternOne()
{
self.createHorizontalWall(512 + 125, yPlacement: self.size.height + 135 + 125)
self.createHorizontalWall(512 - 125, yPlacement: self.size.height + 135 + 125)
self.createVerticalWall(280, yPlacement: self.size.height + 125)
self.createVerticalWall(512.5, yPlacement: self.size.height + 125 - 100)
self.createVerticalWall(745, yPlacement: self.size.height + 125)
}
func patternTwo()
{
}
}
|
mit
|
8ab418e3df05f9031c7e9911bf50b2f9
| 37.755245 | 132 | 0.587153 | 4.91748 | false | false | false | false |
Marketcloud/marketcloud-swift-sdk
|
Marketcloud/Shippings.swift
|
1
|
1758
|
import Foundation
internal class Shippings {
fileprivate var headers:[String : String]
internal init(key: String) {
headers = ["accept":"application/json","content-type":"application/json","authorization":key]
}
internal init(key: String, token: String) {
headers = ["accept":"application/json","content-type":"application/json","authorization":"\(key):\(token)"]
}
internal func getShippings() -> NSDictionary {
guard Reachability.isConnectedToNetwork() == true else {
return [
"Error" : "No Connection"]
}
guard let shouldReturn:HTTPResult = Just.get("https://api.marketcloud.it/v0/shippings", headers:headers) else {
return[
"Error" : "Critical Error in HTTP request (get)"]
}
if (shouldReturn.json == nil) {
print(shouldReturn.reason)
return [
"Error" : "Returned JSON is nil"]
}
return shouldReturn.json as! NSDictionary
}
internal func getShippingById(_ id:Int) -> NSDictionary {
guard Reachability.isConnectedToNetwork() == true else {
return [
"Error" : "No Connection"]
}
guard let shouldReturn:HTTPResult = Just.get("https://api.marketcloud.it/v0/shippings/\(id)", headers:headers) else {
return[
"Error" : "Critical Error in HTTP request (get)"]
}
if (shouldReturn.json == nil) {
print(shouldReturn.reason)
return [
"Error" : "Returned JSON is nil"]
}
return shouldReturn.json as! NSDictionary
}
}
|
apache-2.0
|
fc67a0066ba0ff19301e1994aa697cb4
| 30.963636 | 125 | 0.544369 | 4.952113 | false | false | false | false |
NaughtyOttsel/swift-corelibs-foundation
|
Foundation/FoundationErrors.swift
|
3
|
8967
|
// 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
//
public struct NSCocoaError : RawRepresentable, ErrorProtocol, __BridgedNSError {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static var __NSErrorDomain: String { return NSCocoaErrorDomain }
}
/// Enumeration that describes the error codes within the Cocoa error
/// domain.
public extension NSCocoaError {
public static var FileNoSuchFileError: NSCocoaError {
return NSCocoaError(rawValue: 4)
}
public static var FileLockingError: NSCocoaError {
return NSCocoaError(rawValue: 255)
}
public static var FileReadUnknownError: NSCocoaError {
return NSCocoaError(rawValue: 256)
}
public static var FileReadNoPermissionError: NSCocoaError {
return NSCocoaError(rawValue: 257)
}
public static var FileReadInvalidFileNameError: NSCocoaError {
return NSCocoaError(rawValue: 258)
}
public static var FileReadCorruptFileError: NSCocoaError {
return NSCocoaError(rawValue: 259)
}
public static var FileReadNoSuchFileError: NSCocoaError {
return NSCocoaError(rawValue: 260)
}
public static var FileReadInapplicableStringEncodingError: NSCocoaError {
return NSCocoaError(rawValue: 261)
}
public static var FileReadUnsupportedSchemeError: NSCocoaError {
return NSCocoaError(rawValue: 262)
}
public static var FileReadTooLargeError: NSCocoaError {
return NSCocoaError(rawValue: 263)
}
public static var FileReadUnknownStringEncodingError: NSCocoaError {
return NSCocoaError(rawValue: 264)
}
public static var FileWriteUnknownError: NSCocoaError {
return NSCocoaError(rawValue: 512)
}
public static var FileWriteNoPermissionError: NSCocoaError {
return NSCocoaError(rawValue: 513)
}
public static var FileWriteInvalidFileNameError: NSCocoaError {
return NSCocoaError(rawValue: 514)
}
public static var FileWriteFileExistsError: NSCocoaError {
return NSCocoaError(rawValue: 516)
}
public static var FileWriteInapplicableStringEncodingError: NSCocoaError {
return NSCocoaError(rawValue: 517)
}
public static var FileWriteUnsupportedSchemeError: NSCocoaError {
return NSCocoaError(rawValue: 518)
}
public static var FileWriteOutOfSpaceError: NSCocoaError {
return NSCocoaError(rawValue: 640)
}
public static var FileWriteVolumeReadOnlyError: NSCocoaError {
return NSCocoaError(rawValue: 642)
}
public static var FileManagerUnmountUnknownError: NSCocoaError {
return NSCocoaError(rawValue: 768)
}
public static var FileManagerUnmountBusyError: NSCocoaError {
return NSCocoaError(rawValue: 769)
}
public static var KeyValueValidationError: NSCocoaError {
return NSCocoaError(rawValue: 1024)
}
public static var FormattingError: NSCocoaError {
return NSCocoaError(rawValue: 2048)
}
public static var UserCancelledError: NSCocoaError {
return NSCocoaError(rawValue: 3072)
}
public static var FeatureUnsupportedError: NSCocoaError {
return NSCocoaError(rawValue: 3328)
}
public static var ExecutableNotLoadableError: NSCocoaError {
return NSCocoaError(rawValue: 3584)
}
public static var ExecutableArchitectureMismatchError: NSCocoaError {
return NSCocoaError(rawValue: 3585)
}
public static var ExecutableRuntimeMismatchError: NSCocoaError {
return NSCocoaError(rawValue: 3586)
}
public static var ExecutableLoadError: NSCocoaError {
return NSCocoaError(rawValue: 3587)
}
public static var ExecutableLinkError: NSCocoaError {
return NSCocoaError(rawValue: 3588)
}
public static var PropertyListReadCorruptError: NSCocoaError {
return NSCocoaError(rawValue: 3840)
}
public static var PropertyListReadUnknownVersionError: NSCocoaError {
return NSCocoaError(rawValue: 3841)
}
public static var PropertyListReadStreamError: NSCocoaError {
return NSCocoaError(rawValue: 3842)
}
public static var PropertyListWriteStreamError: NSCocoaError {
return NSCocoaError(rawValue: 3851)
}
public static var PropertyListWriteInvalidError: NSCocoaError {
return NSCocoaError(rawValue: 3852)
}
public static var XPCConnectionInterrupted: NSCocoaError {
return NSCocoaError(rawValue: 4097)
}
public static var XPCConnectionInvalid: NSCocoaError {
return NSCocoaError(rawValue: 4099)
}
public static var XPCConnectionReplyInvalid: NSCocoaError {
return NSCocoaError(rawValue: 4101)
}
public static var UbiquitousFileUnavailableError: NSCocoaError {
return NSCocoaError(rawValue: 4353)
}
public static var UbiquitousFileNotUploadedDueToQuotaError: NSCocoaError {
return NSCocoaError(rawValue: 4354)
}
public static var UbiquitousFileUbiquityServerNotAvailable: NSCocoaError {
return NSCocoaError(rawValue: 4355)
}
public static var UserActivityHandoffFailedError: NSCocoaError {
return NSCocoaError(rawValue: 4608)
}
public static var UserActivityConnectionUnavailableError: NSCocoaError {
return NSCocoaError(rawValue: 4609)
}
public static var UserActivityRemoteApplicationTimedOutError: NSCocoaError {
return NSCocoaError(rawValue: 4610)
}
public static var UserActivityHandoffUserInfoTooLargeError: NSCocoaError {
return NSCocoaError(rawValue: 4611)
}
public static var CoderReadCorruptError: NSCocoaError {
return NSCocoaError(rawValue: 4864)
}
public static var CoderValueNotFoundError: NSCocoaError {
return NSCocoaError(rawValue: 4865)
}
public var isCoderError: Bool {
return rawValue >= 4864 && rawValue <= 4991
}
public var isExecutableError: Bool {
return rawValue >= 3584 && rawValue <= 3839
}
public var isFileError: Bool {
return rawValue >= 0 && rawValue <= 1023
}
public var isFormattingError: Bool {
return rawValue >= 2048 && rawValue <= 2559
}
public var isPropertyListError: Bool {
return rawValue >= 3840 && rawValue <= 4095
}
public var isUbiquitousFileError: Bool {
return rawValue >= 4352 && rawValue <= 4607
}
public var isUserActivityError: Bool {
return rawValue >= 4608 && rawValue <= 4863
}
public var isValidationError: Bool {
return rawValue >= 1024 && rawValue <= 2047
}
public var isXPCConnectionError: Bool {
return rawValue >= 4096 && rawValue <= 4224
}
}
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
internal func _NSErrorWithErrno(_ posixErrno : Int32, reading : Bool, path : String? = nil, url : NSURL? = nil, extraUserInfo : [String : Any]? = nil) -> NSError {
var cocoaError : NSCocoaError
if reading {
switch posixErrno {
case EFBIG: cocoaError = NSCocoaError.FileReadTooLargeError
case ENOENT: cocoaError = NSCocoaError.FileReadNoSuchFileError
case EPERM, EACCES: cocoaError = NSCocoaError.FileReadNoPermissionError
case ENAMETOOLONG: cocoaError = NSCocoaError.FileReadUnknownError
default: cocoaError = NSCocoaError.FileReadUnknownError
}
} else {
switch posixErrno {
case ENOENT: cocoaError = NSCocoaError.FileNoSuchFileError
case EPERM, EACCES: cocoaError = NSCocoaError.FileWriteNoPermissionError
case ENAMETOOLONG: cocoaError = NSCocoaError.FileWriteInvalidFileNameError
case EDQUOT, ENOSPC: cocoaError = NSCocoaError.FileWriteOutOfSpaceError
case EROFS: cocoaError = NSCocoaError.FileWriteVolumeReadOnlyError
case EEXIST: cocoaError = NSCocoaError.FileWriteFileExistsError
default: cocoaError = NSCocoaError.FileWriteUnknownError
}
}
var userInfo = extraUserInfo ?? [String : Any]()
if let path = path {
userInfo[NSFilePathErrorKey] = path._nsObject
} else if let url = url {
userInfo[NSURLErrorKey] = url
}
return NSError(domain: NSCocoaErrorDomain, code: cocoaError.rawValue, userInfo: userInfo)
}
|
apache-2.0
|
40aa3cdc777e92773d615c2da91b1a2a
| 30.797872 | 163 | 0.684064 | 5.569565 | false | false | false | false |
Mozharovsky/CVCalendar
|
CVCalendar/CVCalendarMonthView.swift
|
2
|
7122
|
//
// CVCalendarMonthView.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/26/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
public final class CVCalendarMonthView: UIView {
// MARK: - Non public properties
fileprivate var interactiveView: UIView!
public override var frame: CGRect {
didSet {
if let calendarView = calendarView {
if calendarView.calendarMode == CalendarMode.monthView {
updateInteractiveView()
}
}
}
}
fileprivate var touchController: CVCalendarTouchController {
return calendarView.touchController
}
var allowScrollToPreviousMonth = true
var allowScrollToNextMonth = true
// MARK: - Public properties
public weak var calendarView: CVCalendarView!
public var date: Foundation.Date!
public var numberOfWeeks: Int!
public var weekViews: [CVCalendarWeekView]!
public var weeksIn: [[Int : [Int]]]?
public var weeksOut: [[Int : [Int]]]?
public var currentDay: Int?
public var potentialSize: CGSize {
return CGSize(width: bounds.width,
height: CGFloat(weekViews.count) * weekViews[0].bounds.height +
calendarView.appearance.spaceBetweenWeekViews! *
CGFloat(weekViews.count))
}
// MARK: - Initialization
public init(calendarView: CVCalendarView, date: Foundation.Date) {
super.init(frame: CGRect.zero)
self.calendarView = calendarView
self.date = date
commonInit()
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func mapDayViews(_ body: (DayView) -> Void) {
for weekView in self.weekViews {
for dayView in weekView.dayViews {
body(dayView)
}
}
}
}
// MARK: - Creation and destruction
extension CVCalendarMonthView {
public func commonInit() {
let calendarManager = calendarView.manager
safeExecuteBlock({
let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current
self.numberOfWeeks = calendarManager?.monthDateRange(self.date).countOfWeeks
self.weeksIn = calendarManager?.weeksWithWeekdaysForMonthDate(self.date).weeksIn
self.weeksOut = calendarManager?.weeksWithWeekdaysForMonthDate(self.date).weeksOut
self.currentDay = Manager.dateRange(Foundation.Date(), calendar: calendar).day
}, collapsingOnNil: true, withObjects: date as AnyObject?)
}
}
// MARK: Content reload
extension CVCalendarMonthView {
public func reloadViewsWithRect(_ frame: CGRect) {
self.frame = frame
safeExecuteBlock({
for (index, weekView) in self.weekViews.enumerated() {
if let size = self.calendarView.weekViewSize {
weekView.frame = CGRect(x: 0, y: size.height * CGFloat(index),
width: size.width, height: size.height)
weekView.reloadDayViews()
}
}
}, collapsingOnNil: true, withObjects: weekViews as AnyObject?)
}
}
// MARK: - Content fill & update
extension CVCalendarMonthView {
public func updateAppearance(_ frame: CGRect) {
self.frame = frame
createWeekViews()
}
public func createWeekViews() {
weekViews = [CVCalendarWeekView]()
safeExecuteBlock({
for i in 0..<self.numberOfWeeks! {
let weekView = CVCalendarWeekView(monthView: self, index: i)
self.safeExecuteBlock({
self.weekViews!.append(weekView)
}, collapsingOnNil: true, withObjects: self.weekViews as AnyObject?)
self.addSubview(weekView)
}
}, collapsingOnNil: true, withObjects: numberOfWeeks as AnyObject?)
}
}
// MARK: - Interactive view management & update
extension CVCalendarMonthView {
public func updateInteractiveView() {
safeExecuteBlock({
let mode = self.calendarView!.calendarMode!
if mode == .monthView {
if let interactiveView = self.interactiveView {
interactiveView.frame = self.bounds
interactiveView.removeFromSuperview()
self.addSubview(interactiveView)
} else {
self.interactiveView = UIView(frame: self.bounds)
self.interactiveView.backgroundColor = .clear
let tapRecognizer = UITapGestureRecognizer(target: self,
action: #selector(CVCalendarMonthView.didTouchInteractiveView(_:)))
let pressRecognizer = UILongPressGestureRecognizer(target: self,
action: #selector(CVCalendarMonthView.didPressInteractiveView(_:)))
pressRecognizer.minimumPressDuration = 0.3
self.interactiveView.addGestureRecognizer(pressRecognizer)
self.interactiveView.addGestureRecognizer(tapRecognizer)
self.addSubview(self.interactiveView)
}
}
}, collapsingOnNil: false, withObjects: calendarView)
}
@objc public func didPressInteractiveView(_ recognizer: UILongPressGestureRecognizer) {
let location = recognizer.location(in: self.interactiveView)
let state: UIGestureRecognizer.State = recognizer.state
switch state {
case .began:
touchController.receiveTouchLocation(location, inMonthView: self,
withSelectionType: .range(.started))
case .changed:
touchController.receiveTouchLocation(location, inMonthView: self,
withSelectionType: .range(.changed))
case .ended:
touchController.receiveTouchLocation(location, inMonthView: self,
withSelectionType: .range(.ended))
default: break
}
}
@objc public func didTouchInteractiveView(_ recognizer: UITapGestureRecognizer) {
let location = recognizer.location(in: self.interactiveView)
touchController.receiveTouchLocation(location, inMonthView: self,
withSelectionType: .single)
}
}
// MARK: - Safe execution
extension CVCalendarMonthView {
public func safeExecuteBlock(_ block: () -> Void, collapsingOnNil collapsing: Bool,
withObjects objects: AnyObject?...) {
for object in objects {
if object == nil {
if collapsing {
fatalError("Object { \(String(describing: object)) } must not be nil!")
} else {
return
}
}
}
block()
}
}
|
mit
|
44f859adef8a1d1fe67e42dd05fe5c43
| 33.240385 | 94 | 0.597304 | 5.748184 | false | false | false | false |
ps2/rileylink_ios
|
OmniKit/OmnipodCommon/MessageBlocks/TempBasalExtraCommand.swift
|
1
|
3314
|
//
// TempBasalExtraCommand.swift
// OmniKit
//
// Created by Pete Schwamb on 6/6/18.
// Copyright © 2018 Pete Schwamb. All rights reserved.
//
import Foundation
public struct TempBasalExtraCommand : MessageBlock {
public let acknowledgementBeep: Bool
public let completionBeep: Bool
public let programReminderInterval: TimeInterval
public let remainingPulses: Double
public let delayUntilFirstPulse: TimeInterval
public let rateEntries: [RateEntry]
public let blockType: MessageBlockType = .tempBasalExtra
public var data: Data {
let beepOptions = (UInt8(programReminderInterval.minutes) & 0x3f) + (completionBeep ? (1<<6) : 0) + (acknowledgementBeep ? (1<<7) : 0)
var data = Data([
blockType.rawValue,
UInt8(8 + rateEntries.count * 6),
beepOptions,
0
])
data.appendBigEndian(UInt16(round(remainingPulses * 10)))
data.appendBigEndian(UInt32(delayUntilFirstPulse.hundredthsOfMilliseconds))
for entry in rateEntries {
data.append(entry.data)
}
return data
}
public init(encodedData: Data) throws {
if encodedData.count < 14 {
throw MessageBlockError.notEnoughData
}
let length = encodedData[1]
let numEntries = (length - 8) / 6
acknowledgementBeep = encodedData[2] & (1<<7) != 0
completionBeep = encodedData[2] & (1<<6) != 0
programReminderInterval = TimeInterval(minutes: Double(encodedData[2] & 0x3f))
remainingPulses = Double(encodedData[4...].toBigEndian(UInt16.self)) / 10.0
let timerCounter = encodedData[6...].toBigEndian(UInt32.self)
delayUntilFirstPulse = TimeInterval(hundredthsOfMilliseconds: Double(timerCounter))
var entries = [RateEntry]()
for entryIndex in (0..<numEntries) {
let offset = 10 + entryIndex * 6
let totalPulses = Double(encodedData[offset...].toBigEndian(UInt16.self)) / 10.0
let timerCounter = encodedData[(offset+2)...].toBigEndian(UInt32.self) & ~nearZeroBasalRateFlag
let delayBetweenPulses = TimeInterval(hundredthsOfMilliseconds: Double(timerCounter))
entries.append(RateEntry(totalPulses: totalPulses, delayBetweenPulses: delayBetweenPulses))
}
rateEntries = entries
}
public init(rate: Double, duration: TimeInterval, acknowledgementBeep: Bool = false, completionBeep: Bool = false, programReminderInterval: TimeInterval = 0) {
rateEntries = RateEntry.makeEntries(rate: rate, duration: duration)
remainingPulses = rateEntries[0].totalPulses
delayUntilFirstPulse = rateEntries[0].delayBetweenPulses
self.acknowledgementBeep = acknowledgementBeep
self.completionBeep = completionBeep
self.programReminderInterval = programReminderInterval
}
}
extension TempBasalExtraCommand: CustomDebugStringConvertible {
public var debugDescription: String {
return "TempBasalExtraCommand(completionBeep:\(completionBeep), programReminderInterval:\(programReminderInterval.stringValue) remainingPulses:\(remainingPulses), delayUntilFirstPulse:\(delayUntilFirstPulse.stringValue), rateEntries:\(rateEntries))"
}
}
|
mit
|
fbf9964786a4a4602ae88fda62d60969
| 40.936709 | 257 | 0.681558 | 4.699291 | false | false | false | false |
superk589/DereGuide
|
DereGuide/LiveSimulator/LSSkill.swift
|
2
|
6570
|
//
// LSSkill.swift
// DereGuide
//
// Created by zzk on 2017/3/31.
// Copyright © 2017 zzk. All rights reserved.
//
import Foundation
enum LSSkillType {
case comboBonus
case perfectBonus
case skillBoost
case heal
case overload
case deep
case allRound
case concentration
case `guard`
case comboContinue
case perfectLock
case encore
case lifeSparkle
case synergy
case coordination
case longAct
case flickAct
case turning
static let allPerfectBonus: [LSSkillType] = [LSSkillType.perfectBonus, .overload, .deep, .concentration, .synergy, .coordination, .flickAct, .longAct]
static let allComboBonus: [LSSkillType] = [LSSkillType.allRound, .comboBonus, .deep, .synergy, .coordination, .turning]
static let allLifeResotre: [LSSkillType] = [LSSkillType.allRound, .heal, .synergy]
init?(type: CGSSSkillTypes) {
switch type {
case CGSSSkillTypes.comboBonus:
self = .comboBonus
case CGSSSkillTypes.allRound:
self = .allRound
case CGSSSkillTypes.perfectBonus:
self = .perfectBonus
case CGSSSkillTypes.concentration:
self = .concentration
case CGSSSkillTypes.overload:
self = .overload
case CGSSSkillTypes.deep:
self = .deep
case CGSSSkillTypes.boost:
self = .skillBoost
case CGSSSkillTypes.heal:
self = .heal
case CGSSSkillTypes.comboContinue:
self = .comboContinue
case CGSSSkillTypes.perfectLock:
self = .perfectLock
case CGSSSkillTypes.guard:
self = .guard
case CGSSSkillTypes.encore:
self = .encore
case CGSSSkillTypes.lifeSparkle:
self = .lifeSparkle
case CGSSSkillTypes.synergy:
self = .synergy
case CGSSSkillTypes.coordination:
self = .coordination
case CGSSSkillTypes.tuning:
self = .turning
case CGSSSkillTypes.longAct:
self = .longAct
case CGSSSkillTypes.flickAct:
self = .flickAct
default:
return nil
}
}
}
struct LSTriggerEvaluations: OptionSet {
let rawValue: UInt
init(rawValue: UInt) { self.rawValue = rawValue }
static let perfect = LSTriggerEvaluations(rawValue: 1 << 0)
static let great = LSTriggerEvaluations(rawValue: 1 << 1)
static let nice = LSTriggerEvaluations(rawValue: 1 << 2)
static let bad = LSTriggerEvaluations(rawValue: 1 << 3)
static let miss = LSTriggerEvaluations(rawValue: 1 << 4)
static let all: LSTriggerEvaluations = [.perfect, .great, .nice, .bad, .miss]
}
struct LSSkill {
var range: LSRange<Float>
/// in percent, 117 means 17%up
var value: Int
/// heal of all round / combo bonus of deep
var value2: Int
/// heal of three color synegy
var value3: Int
var type: LSSkillType
/// 0 ~ 10000
var rate: Int
/// in percent, 30 means 0.3
var rateBonus: Int
/// in percent, 20 means 0.2
var ratePotentialBonus: Int
/// overload skills' trigger life value
var triggerLife: Int
/// 0 ~ 4, the index of the member in the unit
var position: Int
/// what kind of note evaluation can get bonus of effect 1
var triggerEvaluations1: LSTriggerEvaluations
/// what kind of note evaluation can get bonus of effect 2
var triggerEvaluations2: LSTriggerEvaluations
/// what kind of note evaluation can get bonus of effect 3
var triggerEvaluations3: LSTriggerEvaluations
var baseRarity: CGSSRarityTypes
}
extension LSSkill {
var probability: Double {
return min(1, Double((rate + ratePotentialBonus * 100) * (100 + rateBonus)) / 1000000)
}
var isConcentrated: Bool {
return type == .concentration
}
/// rate in integer, from 0 to 1000000
var rate1000000: Int {
return min(1000000, (rate + ratePotentialBonus * 100) * (100 + rateBonus))
}
}
extension LSSkill {
func perfectBonusValue(noteType: CGSSBeatmapNote.Style) -> Int {
switch (type, noteType) {
case (.longAct, .hold),
(.longAct, .wideSlide):
return value2
case (.flickAct, .flick),
(.flickAct, .wideFlick):
return value2
case (let x, _) where LSSkillType.allPerfectBonus.contains(x):
return value
default:
return 100
}
}
var comboBonusValue: Int {
if type == .deep || type == .synergy || type == .coordination {
return value2
} else if LSSkillType.allComboBonus.contains(type) {
return value
} else {
return 100
}
}
var lifeValue: Int {
if type == .allRound {
return value2
} else if type == .synergy {
return value3
} else if LSSkillType.allLifeResotre.contains(type) {
return value
} else {
return 0
}
}
}
extension CGSSSkill {
var triggerEvaluations1: LSTriggerEvaluations {
switch skillTypeId {
case 1, 14, 15, 17, 21, 22, 23, 26, 27, 28, 29:
return .perfect
case 2, 18:
return [.perfect, .great]
case 3, 19:
return [.perfect, .great, .nice]
case 13:
return [.perfect, .great, .nice, .bad, .miss]
case 5:
return .great
case 6:
return [.great, .nice]
case 7:
return [.great, .nice, .bad]
case 8:
return [.great, .nice, .bad, .miss]
case 9:
return .nice
case 10:
return [.bad, .nice]
case 31:
return [.perfect]
default:
return .all
}
}
// for the second effect of focus, all round and overload
var triggerEvaluations2: LSTriggerEvaluations {
switch skillTypeId {
case 14:
return [.nice, .bad]
case 24, 28, 29:
return .perfect
case 31:
return [.great, .nice]
default:
return .all
}
}
var triggerEvalutions3: LSTriggerEvaluations {
switch skillTypeId {
case 26:
return [.perfect]
default:
return .all
}
}
}
|
mit
|
9a0fa8bb75abefea6aeadccef00ce930
| 25.171315 | 154 | 0.56858 | 4.186743 | false | false | false | false |
AppLovin/iOS-SDK-Demo
|
Swift Demo App/iOS-SDK-Demo/ALDemoProgrammaticMRecViewController.swift
|
1
|
3496
|
//
// ALDemoProgrammaticMRecViewController.swift
// iOS-SDK-Demo-Swift
//
// Created by Thomas So on 3/6/17.
// Copyright © 2017 AppLovin. All rights reserved.
//
import UIKit
import AppLovinSDK
class ALDemoProgrammaticMRecViewController : ALDemoBaseViewController
{
private let kMRecHeight: CGFloat = 250
private let kMRecWidth: CGFloat = 300
private let adView = ALAdView(size: .mrec)
// MARK: View Lifecycle
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
// Optional: Implement the ad delegates to receive ad events.
adView.adLoadDelegate = self
adView.adDisplayDelegate = self
adView.adEventDelegate = self
adView.translatesAutoresizingMaskIntoConstraints = false
// Call loadNextAd() to start showing ads
adView.loadNextAd()
view.addSubview(adView)
view.addConstraints([
NSLayoutConstraint(item: adView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: adView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: adView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: kMRecHeight),
NSLayoutConstraint(item: adView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: kMRecWidth)
])
}
override func viewDidDisappear(_ animated: Bool)
{
super.viewDidDisappear(animated)
adView.adLoadDelegate = nil
adView.adDisplayDelegate = nil
adView.adEventDelegate = nil
}
}
extension ALDemoProgrammaticMRecViewController : ALAdLoadDelegate
{
func adService(_ adService: ALAdService, didLoad ad: ALAd)
{
log("MRec Loaded")
}
func adService(_ adService: ALAdService, didFailToLoadAdWithError code: Int32)
{
// Look at ALErrorCodes.h for list of error codes
log("MRec failed to load with error code \(code)")
}
}
extension ALDemoProgrammaticMRecViewController : ALAdDisplayDelegate
{
func ad(_ ad: ALAd, wasDisplayedIn view: UIView)
{
log("MRec Displayed")
}
func ad(_ ad: ALAd, wasHiddenIn view: UIView)
{
log("MRec Dismissed")
}
func ad(_ ad: ALAd, wasClickedIn view: UIView)
{
log("MRec Clicked")
}
}
extension ALDemoProgrammaticMRecViewController : ALAdViewEventDelegate
{
func ad(_ ad: ALAd, didPresentFullscreenFor adView: ALAdView)
{
log("MRec did present fullscreen")
}
func ad(_ ad: ALAd, willDismissFullscreenFor adView: ALAdView)
{
log("MRec will dismiss fullscreen")
}
func ad(_ ad: ALAd, didDismissFullscreenFor adView: ALAdView)
{
log("MRec did dismiss fullscreen")
}
func ad(_ ad: ALAd, willLeaveApplicationFor adView: ALAdView)
{
log("MRec will leave application")
}
func ad(_ ad: ALAd, didReturnToApplicationFor adView: ALAdView)
{
log("MRec did return to application")
}
func ad(_ ad: ALAd, didFailToDisplayIn adView: ALAdView, withError code: ALAdViewDisplayErrorCode)
{
log("MRec did fail to display with error code: \(code)")
}
}
|
mit
|
b263c5ffe63f88527b13d68ce4330c99
| 29.12931 | 165 | 0.652933 | 4.293612 | false | false | false | false |
hunj/hCrypto
|
hCrypto/EncryptViewController.swift
|
1
|
1060
|
//
// EncryptViewController.swift
// hCrypto
//
// Created by Hun Jae Lee on 6/7/16.
// Copyright © 2016 Hun Jae Lee. All rights reserved.
//
import Cocoa
class EncryptViewController: NSViewController {
@IBOutlet var inputTextField: NSTextField!
@IBOutlet var outputTextField: NSTextField!
@IBOutlet var keyField: NSTextField!
@IBOutlet var submitButton: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
@IBAction func encryptButtonPressed(sender: NSButton) {
if inputTextField.stringValue == "" {
showAlert("Please enter the message to be decrypted.")
} else {
if keyField.stringValue == "" {
let cryptor = hCryptor()
let (ciphertext, key) = cryptor.encrypt(inputTextField.stringValue)
outputTextField.stringValue = ciphertext
keyField.stringValue = key
} else {
let cryptor = hCryptor(key: keyField.stringValue)
let (ciphertext, _) = cryptor.encrypt(inputTextField.stringValue)
outputTextField.stringValue = ciphertext
}
}
}
}
|
mit
|
4e00a885650dfbc3966d65fb591c862a
| 24.829268 | 71 | 0.699717 | 4.057471 | false | false | false | false |
AgaKhanFoundation/WCF-iOS
|
Steps4Impact/NotificationsV2/NotificationsViewController.swift
|
1
|
6651
|
/**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import UIKit
import RxSwift
class NotificationsViewController: TableViewController {
override func commonInit() {
super.commonInit()
title = Strings.Notifications.title
dataSource = NotificationsDataSource()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Check the notification permission and then add or remove the persmission cell from tableView if needed.
if let dataSource = dataSource as? NotificationsDataSource {
dataSource.handleNotificationPermissionCell { [weak self] (shouldReload) in
if shouldReload {
self?.tableView.reloadOnMain()
}
}
}
}
override func reload() {
dataSource?.reload { [weak self] in
self?.tableView.reloadOnMain()
}
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
super.tableView(tableView, willDisplay: cell, forRowAt: indexPath)
if let cell = cell as? NotificationPermissionCell {
cell.delegate = self
}
}
}
class NotificationsDataSource: TableViewDataSource {
let cache = Cache.shared
var cells: [[CellContext]] = []
var disposeBag = DisposeBag()
let notificationPermissionCellContext = NotificationPermissionCellContext(title: Strings.NotificationsPermission.title,
description: Strings.NotificationsPermission.message,
disclosureText: Strings.NotificationsPermission.discloreText)
init() {
cache.participantRelay.subscribeOnNext { [weak self] (participant: Participant?) in
guard let fbId = participant?.fbid, let eventId = participant?.currentEvent?.id else { return }
AKFCausesService.getNotifications(fbId: fbId, eventId: eventId) { (result) in
self?.configure()
}
}.disposed(by: disposeBag)
}
func reload(completion: @escaping () -> Void) {
configure()
completion()
}
func handleNotificationPermissionCell(completion: ((Bool) -> Void)?) {
// Checking if notification permission cell is already included in the cells array
if let firstCell = cells.first, firstCell is [NotificationPermissionCellContext] {
// Check if user is registered for remote notifications
if UIApplication.shared.isRegisteredForRemoteNotifications {
// remove the permission cell as the user has registered for push notification
cells.remove(at: 0)
completion?(true)
}
} else if !UIApplication.shared.isRegisteredForRemoteNotifications, canShowPrompt() {
cells.insert([notificationPermissionCellContext], at: 0)
completion?(true)
}
completion?(false)
}
func canShowPrompt() -> Bool {
if let waitingDate = UserInfo.waitingDate {
let currentDate = Date()
if currentDate.compare(waitingDate) == .orderedAscending {
return false
}
}
return true
}
func configure() {
cells = [[]]
if !UIApplication.shared.isRegisteredForRemoteNotifications, canShowPrompt() {
self.cells.insert([notificationPermissionCellContext], at: 0)
}
}
private func testData() -> [NotificationCellInfo] {
[
NotificationCellInfo(title: "FirstName LastName has joined your team",
date: Date(), isRead: false, isFirst: true),
NotificationCellInfo(title: "You have been removed from [Team Name] Team.",
date: Date(timeIntervalSinceNow: -10*60), isRead: false),
NotificationCellInfo(title: "Challenge [name of challenge] has ended.",
date: Date(timeIntervalSinceNow: -1*60*60)),
NotificationCellInfo(title: "FirstName LastName has joined the team.",
date: Date(timeIntervalSinceNow: -1*24*60*60)),
NotificationCellInfo(title: "Abigal Gates is going to Nike run club with 80 others.",
date: Date(timeIntervalSinceNow: -7*24*60*60)),
NotificationCellInfo(title: "Last notification from long ago",
date: Date(timeIntervalSinceNow: -35*24*60*60)),
NotificationCellInfo(title: "Notification from so long ago",
date: Date(timeIntervalSinceNow: -100*24*60*60), isLast: true)
]
}
}
extension NotificationsViewController: NotificationPermissionCellDelegate {
func turnOnNotifictions() {
guard let url = URL(string: UIApplication.openSettingsURLString) else {
return
}
UIApplication.shared.open(url, options: [:]) { (success) in
guard !success else {
return
}
}
}
func close() {
if let firstCell = dataSource?.cells.first, firstCell is [NotificationPermissionCellContext] {
let currentDate = Date()
let calendar = Calendar.current
// add 1 day to the date:
if let newDate = calendar.date(byAdding: .day, value: 1, to: currentDate) {
UserInfo.waitingDate = newDate
}
dataSource?.cells.remove(at: 0)
tableView.reloadOnMain()
}
}
}
|
bsd-3-clause
|
5c4ccdd25e727cde1167a7ee3002ae9a
| 38.583333 | 137 | 0.676541 | 4.958986 | false | false | false | false |
yonadev/yona-app-ios
|
Yona/Yona/UIControlCell/WeekScoreControlCell.swift
|
1
|
5202
|
//
// WeekScoreControlCell.swift
// Yona
//
// Created by Anders Liebl on 30/06/2016.
// Copyright © 2016 Yona. All rights reserved.
//
import Foundation
class WeekScoreControlCell: UITableViewCell {
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var goalTypeLabel: UILabel!
@IBOutlet weak var goalMessage: UILabel!
@IBOutlet weak var gradientView: GradientSmooth!
@IBOutlet weak var day1CircelView: WeekCircleView!
@IBOutlet weak var day2CircelView: WeekCircleView!
@IBOutlet weak var day3CircelView: WeekCircleView!
@IBOutlet weak var day4CircelView: WeekCircleView!
@IBOutlet weak var day5CircelView: WeekCircleView!
@IBOutlet weak var day6CircelView: WeekCircleView!
@IBOutlet weak var day7CircelView: WeekCircleView!
@IBOutlet weak var firstLayoutConstraint: NSLayoutConstraint!
@IBOutlet weak var secondLayoutConstraint: NSLayoutConstraint!
@IBOutlet weak var fourthLayoutConstraint: NSLayoutConstraint!
@IBOutlet weak var lastLayoutConstraint: NSLayoutConstraint!
weak var aActivityGoal : WeekSingleActivityGoal!
weak var delegate : MeDashBoardMainViewController?
override func layoutSubviews() {
super.layoutSubviews()
contentView.layoutIfNeeded()
var width = frame.width
width -= day1CircelView.frame.size.width*7+(2*32)
let distanceBetweenEach = width / 7
firstLayoutConstraint.constant = distanceBetweenEach
secondLayoutConstraint.constant = distanceBetweenEach
fourthLayoutConstraint.constant = distanceBetweenEach
lastLayoutConstraint.constant = distanceBetweenEach
setupGradient()
}
func setupGradient () {
gradientView.setGradientSmooth(UIColor.yiBgGradientTwoColor(), color2: UIColor.yiBgGradientOneColor())
}
func setSingleActivity(_ theActivityGoal : WeekSingleActivityGoal, isScore :Bool = false) {
aActivityGoal = theActivityGoal
self.goalMessage.text = NSLocalizedString("meweek.message.timescompleted", comment: "")
var userCalendar = Calendar.init(identifier: .gregorian)
userCalendar.firstWeekday = 1
scoreLabel.text = "\(aActivityGoal.numberOfDaysGoalWasReached)"
if !isScore {
goalTypeLabel.text = aActivityGoal.goalName
} else {
goalTypeLabel.text = NSLocalizedString("meweek.message.score", comment: "")
}
for index in 0...6 {
var periodComponents = DateComponents()
periodComponents.weekday = index-1
let aDate = (userCalendar as NSCalendar).date(
byAdding: periodComponents,
to: aActivityGoal.date,
options: [])!
//let aDate = theActivityGoal.date.dateByAddingTimeInterval(-Double(index)*60*60*24)
let obje : WeekCircleView = self.value(forKey: "day\(index+1)CircelView") as! WeekCircleView
var tempStatus : circleViewStatus = circleViewStatus.noData
for dayActivity in aActivityGoal.activity {
if dayActivity.dayofweek.rawValue == getDayOfWeek(aDate) {
obje.activity = dayActivity
if (dayActivity.goalAccomplished) {
tempStatus = .underGoal
} else if !dayActivity.goalAccomplished {
tempStatus = .overGoal
} else {
tempStatus = .noData
}
}
}
obje.configureUI(aDate, status: tempStatus)
}
}
func getDayOfWeek(_ theDate:Date)->Int {
var myCalendar = Calendar(identifier: Calendar.Identifier.gregorian)
myCalendar.firstWeekday = 1
let myComponents = (myCalendar as NSCalendar).components(.weekday, from: theDate)
let weekDay = myComponents.weekday
return weekDay!
}
@IBAction func singeldayAction(_ sender : UIButton){
var aDate : Date?
var aActivity : SingleDayActivityGoal?
switch sender.tag {
case 1:
aDate = day1CircelView.theData as Date?
aActivity = day1CircelView.activity
case 2:
aDate = day2CircelView.theData as Date?
aActivity = day2CircelView.activity
case 3:
aDate = day3CircelView.theData as Date?
aActivity = day3CircelView.activity
case 4:
aDate = day4CircelView.theData as Date?
aActivity = day4CircelView.activity
case 5:
aDate = day5CircelView.theData as Date?
aActivity = day5CircelView.activity
case 6:
aDate = day6CircelView.theData as Date?
aActivity = day6CircelView.activity
case 7:
aDate = day7CircelView.theData as Date?
aActivity = day7CircelView.activity
default:
return
}
if aDate != nil {
if let activ = aActivity {
delegate?.didSelectDayInWeek(activ, aDate: aDate!)
}
}
}
}
|
mpl-2.0
|
da14b26385733db6a6b7a3acf3416f9a
| 35.370629 | 110 | 0.625841 | 4.860748 | false | false | false | false |
AgaKhanFoundation/WCF-iOS
|
Steps4Impact/DashboardV2/Cells/ProfileCardCell.swift
|
1
|
5011
|
/**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import UIKit
import SnapKit
import SDWebImage
protocol ProfileCardCellDelegate: AnyObject {
func profileDisclosureTapped()
}
struct ProfileCardCellContext: CellContext {
let identifier: String = ProfileCardCell.identifier
let imageURL: URL?
let name: String
let teamName: String
let eventName: String
let eventTimeline: String
let disclosureLabel: String
}
class ProfileCardCell: ConfigurableTableViewCell {
static let identifier = "ProfileCardCell"
private let cardView = CardViewV2()
private let profileImageView = WebImageView()
private let profileView = ProfileView()
private let disclosureView = CellDisclosureView()
weak var delegate: ProfileCardCellDelegate?
override func commonInit() {
super.commonInit()
disclosureView.delegate = self
profileImageView.clipsToBounds = true
contentView.addSubview(cardView) {
$0.leading.trailing.equalToSuperview().inset(Style.Padding.p24)
$0.top.bottom.equalToSuperview().inset(Style.Padding.p12)
}
cardView.addSubview(disclosureView) {
$0.leading.trailing.bottom.equalToSuperview()
}
let layoutGuide = UILayoutGuide()
cardView.addLayoutGuide(layoutGuide) {
$0.top.leading.trailing.equalToSuperview()
$0.bottom.equalTo(disclosureView.snp.top)
}
cardView.addSubview(profileImageView) {
$0.height.width.equalTo(Style.Size.s96)
$0.centerY.equalTo(layoutGuide)
$0.leading.equalToSuperview().inset(Style.Padding.p32)
}
cardView.addSubview(profileView) {
$0.top.bottom.trailing.equalTo(layoutGuide).inset(Style.Padding.p32)
$0.leading.equalTo(profileImageView.snp.trailing).offset(Style.Padding.p32)
}
}
override func layoutSubviews() {
super.layoutSubviews()
profileImageView.layer.cornerRadius = profileImageView.frame.height / 2
}
override func prepareForReuse() {
super.prepareForReuse()
profileImageView.stopLoading()
}
func configure(context: CellContext) {
guard let context = context as? ProfileCardCellContext else { return }
profileImageView.fadeInImage(imageURL: context.imageURL, placeHolderImage: Assets.placeholder.image)
profileView.configure(context: context)
disclosureView.configure(context: CellDisclosureContext(label: context.disclosureLabel))
}
}
extension ProfileCardCell: CellDisclosureViewDelegate {
func cellDisclosureTapped() {
delegate?.profileDisclosureTapped()
}
}
class ProfileView: View {
private let nameLabel = UILabel(typography: .title)
private let teamNameLabel = UILabel(typography: .smallRegular)
private let eventNameLabel = UILabel(typography: .smallBold)
private let eventTimelineLabel = UILabel(typography: .smallRegular)
override func commonInit() {
super.commonInit()
addSubview(nameLabel) {
$0.leading.trailing.top.equalToSuperview()
}
addSubview(teamNameLabel) {
$0.leading.trailing.equalToSuperview()
$0.top.equalTo(nameLabel.snp.bottom)
}
addSubview(eventNameLabel) {
$0.leading.trailing.equalToSuperview()
$0.top.equalTo(teamNameLabel.snp.bottom).offset(Style.Padding.p8)
}
addSubview(eventTimelineLabel) {
$0.leading.trailing.bottom.equalToSuperview()
$0.top.equalTo(eventNameLabel.snp.bottom)
}
}
func configure(context: ProfileCardCellContext) {
nameLabel.text = context.name
teamNameLabel.text = context.teamName
eventNameLabel.text = context.eventName
eventTimelineLabel.text = context.eventTimeline
}
}
|
bsd-3-clause
|
9d0b930755e3504addd8b95b4d512333
| 32.178808 | 104 | 0.746108 | 4.509451 | false | false | false | false |
mownier/photostream
|
Photostream/Modules/Comment Feed/Interactor/CommentFeedData.swift
|
1
|
970
|
//
// CommentFeedData.swift
// Photostream
//
// Created by Mounir Ybanez on 29/11/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
protocol CommentFeedData {
var id: String { set get }
var content: String { set get }
var timestamp: Double { set get }
var authorName: String { set get }
var authorId: String { set get }
var authorAvatar: String { set get }
}
struct CommentFeedDataItem: CommentFeedData {
var id: String = ""
var content: String = ""
var timestamp: Double = 0
var authorName: String = ""
var authorId: String = ""
var authorAvatar: String = ""
}
extension Array where Element: CommentFeedData {
func indexOf(comment id: String) -> CommentFeedData? {
let index = self.index { item -> Bool in
return item.id == id
}
guard index != nil else {
return nil
}
return self[index!]
}
}
|
mit
|
059e80e02be04487a6f93a480274d522
| 22.071429 | 58 | 0.590299 | 4.141026 | false | false | false | false |
Geor9eLau/WorkHelper
|
WorkoutHelper/GraphicDataViewController.swift
|
1
|
2509
|
//
// GraphicDataViewController.swift
// WorkoutHelper
//
// Created by George on 2017/2/15.
// Copyright © 2017年 George. All rights reserved.
//
import UIKit
class GraphicDataViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "Data"
tableView.register(UINib.init(nibName: "GraphicDataHomePageTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
}
override func viewWillAppear(_ animated: Bool) {
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let part = ALL_BODY_PART_CHOICES[indexPath.row]
let detailVc = DataDetailViewController(nibName: "DataDetailViewController", bundle: nil)
detailVc.part = part
detailVc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(detailVc, animated: true)
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ALL_BODY_PART_CHOICES.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! GraphicDataHomePageTableViewCell
let part = ALL_BODY_PART_CHOICES[indexPath.row]
cell.partNameLbl.text = part.rawValue
cell.recordMsgLbl.text = DataManager.sharedInstance.getRecordDescription(part: part)
return cell
}
/*
// 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
|
49cf2625d983f47aa91e07f1c9b047ae
| 34.8 | 128 | 0.690742 | 5.072874 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio
|
uoregon-cis-399/examples/W8Example_W17/W8ExampleTests/FruitServiceTest.swift
|
1
|
998
|
//
// W8ExampleTests.swift
// W8ExampleTests
//
// Created by Charles Augustine on 2/13/17.
// Copyright © 2017 Charles. All rights reserved.
//
import XCTest
@testable import W8Example
class FruitServiceTests : XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testSingleton() {
let singleton = FruitService.shared
XCTAssertNotNil(singleton)
}
func testFruitsDoesNotReturnNil() {
let singleton = FruitService.shared
let resultsController = singleton.fruits()
XCTAssertNotNil(resultsController)
}
func testFruitsSingleSection() {
let singleton = FruitService.shared
let resultsController = singleton.fruits()
XCTAssertEqual(resultsController.sections?.count, 1)
}
func testFruitsRowCount() {
let singleton = FruitService.shared
let resultsController = singleton.fruits()
XCTAssertGreaterThanOrEqual(resultsController.sections?[0].numberOfObjects ?? 0, 1)
}
}
|
gpl-3.0
|
6a1942155fbf2afddf48dd468ef16965
| 18.94 | 85 | 0.72317 | 4.069388 | false | true | false | false |
hakota/Sageru
|
Sageru/SageruTableCell.swift
|
1
|
4556
|
//
// SageruTableCell.swift
// Sageru
//
// Created by ArakiKenta on 2016/11/08.
// Copyright © 2016年 Araki Kenta. All rights reserved.
//
import UIKit
public enum BadgePattern {
case new
case plus
}
class SageruTableViewCell: UITableViewCell {
open var selectLine: UIView = {
let view = UIView()
view.backgroundColor = UIColor.orange
return view
}()
open var cellImage: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.backgroundColor = UIColor.clear
imageView.tintColor = UIColor.white
return imageView
}()
open var titleLabel: UILabel = {
let label = UILabel()
label.backgroundColor = UIColor.clear
label.font = UIFont(name: "HelveticaNeue-Light", size: 18)!
label.textColor = UIColor.white
label.numberOfLines = 0
return label
}()
open var bottomLine: UIView = {
let view = UIView()
view.backgroundColor = UIColor.white
return view
}()
open var badge: UILabel = {
let label = UILabel()
label.backgroundColor = UIColor.orange
label.textColor = UIColor.white
label.textAlignment = NSTextAlignment.center
label.font = UIFont(name: "HelveticaNeue-Bold", size: 12)!
label.text = ""
label.isHidden = true
label.layer.cornerRadius = 5.0
label.layer.masksToBounds = true
label.minimumScaleFactor = 0.4
label.adjustsFontSizeToFitWidth = true
return label
}()
var totalHeight: CGFloat!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.clear
selectionStyle = .none
contentView.backgroundColor = UIColor.clear
contentView.addSubview(selectLine)
contentView.addSubview(cellImage)
contentView.addSubview(titleLabel)
contentView.addSubview(bottomLine)
contentView.addSubview(badge)
}
var cureentBadgePattern: BadgePattern?
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
let maxX = self.frame.width
let maxY = self.frame.height
let margin: CGFloat = 4
selectLine.frame = CGRect(x: margin, y: margin, width: 4, height: maxY-(margin*2))
cellImage.frame = CGRect(x: selectLine.frame.maxX + margin*2,
y: margin*3,
width: maxY-(margin*6),
height: maxY-(margin*6))
titleLabel.frame = CGRect(x: cellImage.frame.maxX + (margin*3),
y: margin,
width: maxX-(cellImage.frame.maxX + (margin*3)),
height: maxY-(margin*2))
bottomLine.frame = CGRect(x: margin*6,
y: maxY-0.5,
width: maxX-(margin*12),
height: 0.5)
badge.frame = CGRect(x: titleLabel.frame.minX + (margin*3) + titleLabelToVary(label: titleLabel).width,
y: 0,
width: titleLabelToVary(label: badge).width,
height: maxY/2)
badge.center = CGPoint(x: badge.center.x, y: titleLabel.center.y)
}
func setBadgeValue(value: Int, maxValue: Int, limitOver: BadgePattern = .new) {
if value <= 0 {
badge.isHidden = true
return
}
let count: String = String(value)
if value >= maxValue {
if limitOver == .new {
badge.text = "New"
cureentBadgePattern = .new
} else if limitOver == .plus{
badge.text = String(maxValue) + " +"
cureentBadgePattern = .plus
}
badge.isHidden = false
return
}
badge.text = count
badge.isHidden = false
}
func titleLabelToVary(label: UILabel) -> CGSize {
guard label.text != nil else {
return CGSize(width: 0, height: 0)
}
let width = label.text?.size(attributes: [NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 18)!])
return width!
}
}
|
mit
|
8a62fe781b9c5123410ebe10a0d3bfbc
| 31.978261 | 119 | 0.552406 | 4.755486 | false | false | false | false |
jhurray/SQLiteModel-Example-Project
|
iOS+SQLiteModel/Blogz4Dayz/BlogListCell.swift
|
1
|
2999
|
//
// BlogListCell.swift
// Blogz4Dayz
//
// Created by Jeff Hurray on 4/9/16.
// Copyright © 2016 jhurray. All rights reserved.
//
import UIKit
import Neon
import SQLiteModel
class BlogListCell: UICollectionViewCell {
var titleLabel = UILabel()
var monthLabel = UILabel()
var dayLabel = UILabel()
var timeLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
func styleLabel( inout label: UILabel, color: UIColor, size: CGFloat, numberOfLines: Int = 1) {
label.textColor = color
label.font = UIFont.systemFontOfSize(size)
label.textAlignment = .Center
label.numberOfLines = numberOfLines
label.lineBreakMode = .ByTruncatingTail
self.contentView.addSubview(label)
}
styleLabel(&titleLabel, color: UIColor.blackColor(), size: 14.0, numberOfLines: 2)
styleLabel(&monthLabel, color: UIColor.blackColor(), size: 30.0)
styleLabel(&dayLabel, color: UIColor.grayColor(), size: 48.0)
styleLabel(&timeLabel, color: color, size: 14.0)
}
func reloadWithBlogModel(blog: BlogModel) {
titleLabel.text = blog => BlogModel.Title
guard let date = blog.localCreatedAt else{
self.dayLabel.text = "?"
self.monthLabel.text = "?"
return
}
func dayFromDate(date: NSDate) -> String {
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let components = calendar.components(.Day, fromDate: date)
let day = components.day
return String(day)
}
func monthFromDate(date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM"
return dateFormatter.stringFromDate(date)
}
func timeFromDate(date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
dateFormatter.dateStyle = .NoStyle
return dateFormatter.stringFromDate(date)
}
monthLabel.text = monthFromDate(date)
dayLabel.text = dayFromDate(date)
timeLabel.text = timeFromDate(date)
self.setNeedsLayout()
}
override func layoutSubviews() {
super.layoutSubviews()
monthLabel.anchorAndFillEdge(.Top, xPad: 16, yPad: 16, otherSize: 48)
titleLabel.anchorAndFillEdge(.Bottom, xPad: 16, yPad: 8, otherSize: 40)
timeLabel.align(.AboveCentered, relativeTo: titleLabel, padding: 8, width: monthLabel.width, height: 16)
dayLabel.alignBetweenVertical(align: .UnderCentered, primaryView: monthLabel, secondaryView: timeLabel, padding: 8, width: monthLabel.width)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
c98080d2d43230f339cdfa08e5f4b0ef
| 33.860465 | 148 | 0.620414 | 4.858995 | false | false | false | false |
leannenorthrop/markdown-swift
|
Markdown/Renderer.swift
|
1
|
2699
|
//
// Renderer.swift
// Markdown
//
// Created by Leanne Northrop on 22/06/2015.
// Copyright (c) 2015 Leanne Northrop. All rights reserved.
//
import Foundation
public class Renderer {
public init() {}
func escapeHTML(text:String) -> String {
if !text.isBlank() {
return text.replace("&", replacement: "&")
.replace("<", replacement: "<")
.replace(">", replacement: ">")
.replace("\"", replacement: """)
.replace("\'", replacement: "'")
} else {
return ""
}
}
func render_tree(jsonml:String) -> String {
return escapeHTML(jsonml)
}
func render_tree(var jsonml: [AnyObject]) -> String {
if jsonml.isEmpty { return "" }
var tag: AnyObject = jsonml.removeAtIndex(0)
if tag is [AnyObject] {
return render_tree(tag as! [AnyObject])
}
var tagName : String = tag as! String
var attributes : [String:String] = [:]
var content : [String] = []
if jsonml.count > 0 {
if jsonml[0] is Dictionary<String,String> {
attributes = jsonml.removeAtIndex(0) as! Dictionary<String,String>
}
}
while jsonml.count > 0 {
var node: AnyObject = jsonml.removeAtIndex(0)
if node is [AnyObject] {
content.append(render_tree(node as! [AnyObject]))
} else if node is String {
content.append(render_tree(node as! String))
} else if node is [String:AnyObject] {
// to do ?
} else {
println("Render warning: " + node.description)
}
}
var tag_attrs : String = ""
if attributes.indexForKey("src") != nil {
tag_attrs += " src=\"" + escapeHTML(attributes["src"]!) + "\""
attributes.removeValueForKey("src")
}
for (key,value) in attributes {
var escaped = escapeHTML(value)
if !escaped.isBlank() {
tag_attrs += " " + key + "=\"" + escaped + "\""
}
}
// be careful about adding whitespace here for inline elements
var str : String = "<"
str += tag as! String
str += tag_attrs
if (tagName == "img" || tagName == "br" || tagName == "hr") {
str += "/>"
}
else {
str += ">"
str += "".join(content)
str += "</" + tagName + ">"
}
return str
}
}
|
gpl-2.0
|
edbdb64c79497e53b7d6913d0efe3da9
| 29.337079 | 82 | 0.465728 | 4.528523 | false | false | false | false |
SwiftFS/Swift-FS-China
|
Sources/SwiftFSChina/router/Upload.swift
|
1
|
4916
|
//
// upload.swift
// PerfectChina
//
// Created by mubin on 2017/7/31.
//
//
import Foundation
import PerfectHTTP
import PerfectLib
class Upload {
static func avatar(data:[String:Any]) throws -> RequestHandler{
return {
req,res in
do{
let session_user:[String:Any]? = req.session?.data["user"] as? [String : Any]
guard let user_id = session_user?["userid"] as? Int else {
try res.setBody(json: ["success":false,"msg":"上传之前请先登录."])
res.completed()
return
}
guard let uploads = req.postFileUploads, uploads.count > 0,uploads.count == 1 else{
try res.setBody(json: ["success":false,"msg":"请选择正确的图片数量"])
res.completed()
return
}
let fileDir = Dir(Dir.workingDir.path + "webroot/avatar")
do {
try fileDir.create()
} catch {
Log.error(message: "\(error)")
}
let upload = uploads[0]
let thisFile = File(upload.tmpFileName)
let date = NSDate()
let timeInterval = date.timeIntervalSince1970
let hashName = "\(timeInterval.hashValue)"
var type:String?
let typeArray = upload.contentType.components(separatedBy: "/")
guard typeArray.count >= 2 else {
try res.setBody(json: ["success":false,"msg":"获取类型出错"])
res.completed()
return
}
type = typeArray[1]
let picName = hashName + "." + type!
let _ = try thisFile.moveTo(path: fileDir.path + picName, overWrite: true)
let judge = try UserServer.update_avatar(avatar: picName, userid: user_id)
guard judge != false else {
try res.setBody(json: ["success":false,"msg":"上传失败"])
res.completed()
return
}
try res.setBody(json: ["success":true,"originFilename":upload.tmpFileName,"filename":picName])
res.completed()
}catch{
Log.error(message: "\(error)")
}
}
}
static func file(data:[String:Any]) throws -> RequestHandler{
return {
req,res in
do{
let session_user:[String:Any]? = req.session?.data["user"] as? [String : Any]
guard let user_id = session_user?["userid"] as? Int else {
try res.setBody(json: ["success":false,"msg":"上传之前请先登录."])
res.completed()
return
}
guard let uploads = req.postFileUploads, uploads.count > 0,uploads.count == 1 else{
try res.setBody(json: ["success":false,"msg":"请选择正确的图片数量"])
res.completed()
return
}
let fileDir = Dir(Dir.workingDir.path + "webroot/avatar")
do {
try fileDir.create()
} catch {
Log.error(message: "user_id:\(user_id),\(error)")
}
let upload = uploads[0]
let thisFile = File(upload.tmpFileName)
let date = NSDate()
let timeInterval = date.timeIntervalSince1970
let hashName = "\(timeInterval.hashValue)"
var type:String?
let typeArray = upload.contentType.components(separatedBy: "/")
guard typeArray.count >= 2 else {
try res.setBody(json: ["success":false,"msg":"获取类型出错"])
res.completed()
return
}
type = typeArray[1]
let picName = hashName + "." + type!
let file = try thisFile.moveTo(path: fileDir.path + picName, overWrite: true)
let tempPicPath = "/" + picName
guard file.exists != false else {
try res.setBody(json: ["success":false,"msg":"上传错误"])
res.completed()
return
}
try res.setBody(json: ["success":true,"originFilename":tempPicPath,"filename":picName])
res.completed()
}catch{
Log.error(message: "\(error)")
}
}
}
}
|
mit
|
e0f962f7330f1bfb5e6db4510435d1bc
| 36.53125 | 110 | 0.447544 | 5.035639 | false | false | false | false |
nolol/Swift-Notes
|
Resources/GuidedTour.playground/Pages/Simple Values.xcplaygroundpage/Contents.swift
|
2
|
3673
|
//: # A Swift Tour
//:
//: Tradition suggests that the first program in a new language should print the words “Hello, world!” on the screen. In Swift, this can be done in a single line:
//:
print("Hello, world!")
//: If you have written code in C or Objective-C, this syntax looks familiar to you—in Swift, this line of code is a complete program. You don’t need to import a separate library for functionality like input/output or string handling. Code written at global scope is used as the entry point for the program, so you don’t need a `main()` function. You also don’t need to write semicolons at the end of every statement.
//:
//: This tour gives you enough information to start writing code in Swift by showing you how to accomplish a variety of programming tasks. Don’t worry if you don’t understand something—everything introduced in this tour is explained in detail in the rest of this book.
//:
//: ## Simple Values
//:
//: Use `let` to make a constant and `var` to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.
//:
var myVariable = 42
myVariable = 50
let myConstant = 42
//: A constant or variable must have the same type as the value you want to assign to it. However, you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above, the compiler infers that `myVariable` is an integer because its initial value is an integer.
//:
//: If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon.
//:
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
//: - Experiment:
//: Create a constant with an explicit type of `Float` and a value of `4`.
//:
//: Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type.
//:
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
//: - Experiment:
//: Try removing the conversion to `String` from the last line. What error do you get?
//:
//: There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash (`\`) before the parentheses. For example:
//:
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
//: - Experiment:
//: Use `\()` to include a floating-point calculation in a string and to include someone’s name in a greeting.
//:
//: Create arrays and dictionaries using brackets (`[]`), and access their elements by writing the index or key in brackets. A comma is allowed after the last element.
//:
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
//: To create an empty array or dictionary, use the initializer syntax.
//:
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
//: If type information can be inferred, you can write an empty array as `[]` and an empty dictionary as `[:]`—for example, when you set a new value for a variable or pass an argument to a function.
//:
shoppingList = []
occupations = [:]
//: See [License](License) for this sample's licensing information.
//:
//: [Next](@next)
|
mit
|
f912e6841502ccff78cb85a77fe591ac
| 48.243243 | 417 | 0.727697 | 4.088664 | false | false | false | false |
Egibide-DAM/swift
|
02_ejemplos/10_varios/01_optional_chaining/03_modelo_clases_ejemplo.playground/Contents.swift
|
1
|
898
|
class Person {
var residence: Residence?
}
class Room {
let name: String
init(name: String) { self.name = name }
}
class Address {
var buildingName: String?
var buildingNumber: String?
var street: String?
func buildingIdentifier() -> String? {
if let buildingNumber = buildingNumber, let street = street {
return "\(buildingNumber) \(street)"
} else if buildingName != nil {
return buildingName
} else {
return nil
}
}
}
class Residence {
var rooms = [Room]()
var numberOfRooms: Int {
return rooms.count
}
subscript(i: Int) -> Room {
get {
return rooms[i]
}
set {
rooms[i] = newValue
}
}
func printNumberOfRooms() {
print("The number of rooms is \(numberOfRooms)")
}
var address: Address?
}
|
apache-2.0
|
12882de6f45e8d4759b0f2303878e327
| 20.380952 | 69 | 0.545657 | 4.467662 | false | false | false | false |
JohnEstropia/CoreStore
|
Sources/Select.swift
|
1
|
26930
|
//
// Select.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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 CoreGraphics
import CoreData
// MARK: - SelectResultType
/**
The `SelectResultType` protocol is implemented by return types supported by the `Select` clause.
*/
public protocol SelectResultType {}
// MARK: - SelectAttributesResultType
/**
The `SelectAttributesResultType` protocol is implemented by return types supported by the `queryAttributes(...)` methods.
*/
public protocol SelectAttributesResultType: SelectResultType {
static func cs_fromQueryResultsNativeType(_ result: [Any]) -> [[String: Any]]
}
// MARK: - SelectTerm
/**
The `SelectTerm` is passed to the `Select` clause to indicate the attributes/aggregate keys to be queried.
*/
public enum SelectTerm<O: DynamicObject>: ExpressibleByStringLiteral, Hashable {
/**
Provides a `SelectTerm` to a `Select` clause for querying an entity attribute. A shorter way to do the same is to assign from the string keypath directly:
```
let fullName = dataStack.queryValue(
From<MyPersonEntity>(),
Select<String>(.attribute("fullName")),
Where("employeeID", isEqualTo: 1111)
)
```
is equivalent to:
```
let fullName = dataStack.queryValue(
From<MyPersonEntity>(),
Select<String>("fullName"),
Where("employeeID", isEqualTo: 1111)
)
```
- parameter keyPath: the attribute name
- returns: a `SelectTerm` to a `Select` clause for querying an entity attribute
*/
public static func attribute(_ keyPath: KeyPathString) -> SelectTerm<O> {
return ._attribute(keyPath)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the average value of an attribute.
```
let averageAge = dataStack.queryValue(
From<MyPersonEntity>(),
Select<Int>(.average("age"))
)
```
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "average(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the average value of an attribute
*/
public static func average(_ keyPath: KeyPathString, as alias: KeyPathString? = nil) -> SelectTerm<O> {
return ._aggregate(
function: "average:",
keyPath: keyPath,
alias: alias ?? "average(\(keyPath))",
nativeType: .decimalAttributeType
)
}
/**
Provides a `SelectTerm` to a `Select` clause for a count query.
```
let numberOfEmployees = dataStack.queryValue(
From<MyPersonEntity>(),
Select<Int>(.count("employeeID"))
)
```
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "count(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for a count query
*/
public static func count(_ keyPath: KeyPathString, as alias: KeyPathString? = nil) -> SelectTerm<O> {
return ._aggregate(
function: "count:",
keyPath: keyPath,
alias: alias ?? "count(\(keyPath))",
nativeType: .integer64AttributeType
)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the maximum value for an attribute.
```
let maximumAge = dataStack.queryValue(
From<MyPersonEntity>(),
Select<Int>(.maximum("age"))
)
```
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "max(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the maximum value for an attribute
*/
public static func maximum(_ keyPath: KeyPathString, as alias: KeyPathString? = nil) -> SelectTerm<O> {
return ._aggregate(
function: "max:",
keyPath: keyPath,
alias: alias ?? "max(\(keyPath))",
nativeType: .undefinedAttributeType
)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the minimum value for an attribute.
```
let minimumAge = dataStack.queryValue(
From<MyPersonEntity>(),
Select<Int>(.minimum("age"))
)
```
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "min(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the minimum value for an attribute
*/
public static func minimum(_ keyPath: KeyPathString, as alias: KeyPathString? = nil) -> SelectTerm<O> {
return ._aggregate(
function: "min:",
keyPath: keyPath,
alias: alias ?? "min(\(keyPath))",
nativeType: .undefinedAttributeType
)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the sum value for an attribute.
```
let totalAge = dataStack.queryValue(
From<MyPersonEntity>(),
Select<Int>(.sum("age"))
)
```
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "sum(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the sum value for an attribute
*/
public static func sum(_ keyPath: KeyPathString, as alias: KeyPathString? = nil) -> SelectTerm<O> {
return ._aggregate(
function: "sum:",
keyPath: keyPath,
alias: alias ?? "sum(\(keyPath))",
nativeType: .decimalAttributeType
)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the `NSManagedObjectID`.
```
let objectID = dataStack.queryValue(
From<MyPersonEntity>(),
Select<NSManagedObjectID>(),
Where("employeeID", isEqualTo: 1111)
)
```
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "objecID" is used
- returns: a `SelectTerm` to a `Select` clause for querying the sum value for an attribute
*/
public static func objectID(as alias: KeyPathString? = nil) -> SelectTerm<O> {
return ._identity(
alias: alias ?? "objectID",
nativeType: .objectIDAttributeType
)
}
// MARK: ExpressibleByStringLiteral
public init(stringLiteral value: KeyPathString) {
self = ._attribute(value)
}
public init(unicodeScalarLiteral value: KeyPathString) {
self = ._attribute(value)
}
public init(extendedGraphemeClusterLiteral value: KeyPathString) {
self = ._attribute(value)
}
// MARK: Equatable
public static func == (lhs: SelectTerm<O>, rhs: SelectTerm<O>) -> Bool {
switch (lhs, rhs) {
case (._attribute(let keyPath1), ._attribute(let keyPath2)):
return keyPath1 == keyPath2
case (._aggregate(let function1, let keyPath1, let alias1, let nativeType1),
._aggregate(let function2, let keyPath2, let alias2, let nativeType2)):
return function1 == function2
&& keyPath1 == keyPath2
&& alias1 == alias2
&& nativeType1 == nativeType2
case (._identity(let alias1, let nativeType1), ._identity(let alias2, let nativeType2)):
return alias1 == alias2 && nativeType1 == nativeType2
case (._attribute, _),
(._aggregate, _),
(._identity, _):
return false
}
}
// MARK: Hashable
public func hash(into hasher: inout Hasher) {
switch self {
case ._attribute(let keyPath):
hasher.combine(0)
hasher.combine(keyPath)
case ._aggregate(let function, let keyPath, let alias, let nativeType):
hasher.combine(1)
hasher.combine(function)
hasher.combine(keyPath)
hasher.combine(alias)
hasher.combine(nativeType)
case ._identity(let alias, let nativeType):
hasher.combine(2)
hasher.combine(alias)
hasher.combine(nativeType)
}
}
// MARK: Internal
case _attribute(KeyPathString)
case _aggregate(function: String, keyPath: KeyPathString, alias: String, nativeType: NSAttributeType)
case _identity(alias: String, nativeType: NSAttributeType)
internal var keyPathString: String {
switch self {
case ._attribute(let keyPath): return keyPath
case ._aggregate(_, _, let alias, _): return alias
case ._identity(let alias, _): return alias
}
}
// MARK: Deprecated
@available(*, deprecated, renamed: "O")
public typealias D = O
}
// MARK: - SelectTerm where O: NSManagedObject
extension SelectTerm where O: NSManagedObject {
/**
Provides a `SelectTerm` to a `Select` clause for querying an entity attribute.
- parameter keyPath: the attribute name
- returns: a `SelectTerm` to a `Select` clause for querying an entity attribute
*/
public static func attribute<V>(_ keyPath: KeyPath<O, V>) -> SelectTerm<O> {
return self.attribute(keyPath._kvcKeyPathString!)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the average value of an attribute.
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "average(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the average value of an attribute
*/
public static func average<V>(_ keyPath: KeyPath<O, V>, as alias: KeyPathString? = nil) -> SelectTerm<O> {
return self.average(keyPath._kvcKeyPathString!, as: alias)
}
/**
Provides a `SelectTerm` to a `Select` clause for a count query.
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "count(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for a count query
*/
public static func count<V>(_ keyPath: KeyPath<O, V>, as alias: KeyPathString? = nil) -> SelectTerm<O> {
return self.count(keyPath._kvcKeyPathString!, as: alias)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the maximum value for an attribute.
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "max(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the maximum value for an attribute
*/
public static func maximum<V>(_ keyPath: KeyPath<O, V>, as alias: KeyPathString? = nil) -> SelectTerm<O> {
return self.maximum(keyPath._kvcKeyPathString!, as: alias)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the minimum value for an attribute.
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "min(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the minimum value for an attribute
*/
public static func minimum<V>(_ keyPath: KeyPath<O, V>, as alias: KeyPathString? = nil) -> SelectTerm<O> {
return self.minimum(keyPath._kvcKeyPathString!, as: alias)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the sum value for an attribute.
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "sum(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the sum value for an attribute
*/
public static func sum<V>(_ keyPath: KeyPath<O, V>, as alias: KeyPathString? = nil) -> SelectTerm<O> {
return self.sum(keyPath._kvcKeyPathString!, as: alias)
}
}
// MARK: - SelectTerm where O: CoreStoreObject
extension SelectTerm where O: CoreStoreObject {
/**
Provides a `SelectTerm` to a `Select` clause for querying an entity attribute.
- parameter keyPath: the attribute name
- returns: a `SelectTerm` to a `Select` clause for querying an entity attribute
*/
public static func attribute<K: AttributeKeyPathStringConvertible>(_ keyPath: KeyPath<O, K>) -> SelectTerm<O> where K.ObjectType == O {
return self.attribute(O.meta[keyPath: keyPath].cs_keyPathString)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the average value of an attribute.
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "average(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the average value of an attribute
*/
public static func average<K: AttributeKeyPathStringConvertible>(_ keyPath: KeyPath<O, K>, as alias: KeyPathString? = nil) -> SelectTerm<O> where K.ObjectType == O{
return self.average(O.meta[keyPath: keyPath].cs_keyPathString, as: alias)
}
/**
Provides a `SelectTerm` to a `Select` clause for a count query.
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "count(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for a count query
*/
public static func count<K: AttributeKeyPathStringConvertible>(_ keyPath: KeyPath<O,
K>, as alias: KeyPathString? = nil) -> SelectTerm<O> where K.ObjectType == O {
return self.count(O.meta[keyPath: keyPath].cs_keyPathString, as: alias)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the maximum value for an attribute.
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "max(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the maximum value for an attribute
*/
public static func maximum<K: AttributeKeyPathStringConvertible>(_ keyPath: KeyPath<O,
K>, as alias: KeyPathString? = nil) -> SelectTerm<O> where K.ObjectType == O {
return self.maximum(O.meta[keyPath: keyPath].cs_keyPathString, as: alias)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the minimum value for an attribute.
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "min(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the minimum value for an attribute
*/
public static func minimum<K: AttributeKeyPathStringConvertible>(_ keyPath: KeyPath<O, K>, as alias: KeyPathString? = nil) -> SelectTerm<O> where K.ObjectType == O {
return self.minimum(O.meta[keyPath: keyPath].cs_keyPathString, as: alias)
}
/**
Provides a `SelectTerm` to a `Select` clause for querying the sum value for an attribute.
- parameter keyPath: the attribute name
- parameter alias: the dictionary key to use to access the result. Ignored when the query return value is not an `NSDictionary`. If `nil`, the default key "sum(<attributeName>)" is used
- returns: a `SelectTerm` to a `Select` clause for querying the sum value for an attribute
*/
public static func sum<K: AttributeKeyPathStringConvertible>(_ keyPath: KeyPath<O, K>, as alias: KeyPathString? = nil) -> SelectTerm<O> where K.ObjectType == O {
return self.sum(O.meta[keyPath: keyPath].cs_keyPathString, as: alias)
}
}
// MARK: - Select
/**
The `Select` clause indicates the attribute / aggregate value to be queried. The generic type is a `SelectResultType`, and will be used as the return type for the query.
You can bind the return type by specializing the initializer:
```
let maximumAge = dataStack.queryValue(
From<MyPersonEntity>(),
Select<Int>(.maximum("age"))
)
```
or by casting the type of the return value:
```
let maximumAge: Int = dataStack.queryValue(
From<MyPersonEntity>(),
Select(.maximum("age"))
)
```
Valid return types depend on the query:
- for `queryValue(...)` methods:
- all types that conform to `QueryableAttributeType` protocol
- for `queryAttributes(...)` methods:
- `NSDictionary`
- parameter sortDescriptors: a series of `NSSortDescriptor`s
*/
public struct Select<O: DynamicObject, T: SelectResultType>: SelectClause, Hashable {
/**
Initializes a `Select` clause with a list of `SelectTerm`s
- parameter selectTerm: a `SelectTerm`
- parameter selectTerms: a series of `SelectTerm`s
*/
public init(_ selectTerm: SelectTerm<O>, _ selectTerms: SelectTerm<O>...) {
self.selectTerms = [selectTerm] + selectTerms
}
/**
Initializes a `Select` clause with a list of `SelectTerm`s
- parameter selectTerms: a series of `SelectTerm`s
*/
public init(_ selectTerms: [SelectTerm<O>]) {
self.selectTerms = selectTerms
}
// MARK: Equatable
public static func == <T, U>(lhs: Select<O, T>, rhs: Select<O, U>) -> Bool {
return lhs.selectTerms == rhs.selectTerms
}
// MARK: SelectClause
public typealias ObjectType = O
public typealias ReturnType = T
public let selectTerms: [SelectTerm<O>]
// MARK: Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(self.selectTerms)
}
// MARK: Internal
internal func applyToFetchRequest(_ fetchRequest: NSFetchRequest<NSDictionary>) {
fetchRequest.includesPendingChanges = false
fetchRequest.resultType = .dictionaryResultType
func attributeDescription(for keyPath: String, in entity: NSEntityDescription) -> NSAttributeDescription? {
let components = keyPath.components(separatedBy: ".")
switch components.count {
case 0:
return nil
case 1:
return entity.attributesByName[components[0]]
default:
guard let relationship = entity.relationshipsByName[components[0]],
let destinationEntity = relationship.destinationEntity else {
return nil
}
return attributeDescription(
for: components.dropFirst().joined(separator: "."),
in: destinationEntity
)
}
}
var propertiesToFetch = [Any]()
for term in self.selectTerms {
switch term {
case ._attribute(let keyPath):
propertiesToFetch.append(keyPath)
case ._aggregate(let function, let keyPath, let alias, let nativeType):
let entityDescription = fetchRequest.entity!
if let attributeDescription = attributeDescription(for: keyPath, in: entityDescription) {
let expressionDescription = NSExpressionDescription()
expressionDescription.name = alias
if nativeType == .undefinedAttributeType {
expressionDescription.expressionResultType = attributeDescription.attributeType
}
else {
expressionDescription.expressionResultType = nativeType
}
expressionDescription.expression = NSExpression(
forFunction: function,
arguments: [NSExpression(forKeyPath: keyPath)]
)
propertiesToFetch.append(expressionDescription)
}
else {
Internals.log(
.warning,
message: "The key path \"\(keyPath)\" could not be resolved in entity \(Internals.typeName(entityDescription.managedObjectClassName)) as an attribute and will be ignored by \(Internals.typeName(self)) query clause."
)
}
case ._identity(let alias, let nativeType):
let expressionDescription = NSExpressionDescription()
expressionDescription.name = alias
if nativeType == .undefinedAttributeType {
expressionDescription.expressionResultType = .objectIDAttributeType
}
else {
expressionDescription.expressionResultType = nativeType
}
expressionDescription.expression = NSExpression.expressionForEvaluatedObject()
propertiesToFetch.append(expressionDescription)
}
}
fetchRequest.propertiesToFetch = propertiesToFetch
}
// MARK: Deprecated
@available(*, deprecated, renamed: "O")
public typealias D = O
}
extension Select where T: NSManagedObjectID {
/**
Initializes a `Select` that queries for `NSManagedObjectID` results
*/
public init() {
self.init(.objectID())
}
}
extension Select where O: NSManagedObject {
/**
Initializes a `Select` that queries the value of an attribute pertained by a keyPath
- parameter keyPath: the keyPath for the attribute
*/
public init(_ keyPath: KeyPath<O, T>) {
self.init(.attribute(keyPath))
}
}
extension Select where O: CoreStoreObject, T: ImportableAttributeType {
/**
Initializes a `Select` that queries the value of an attribute pertained by a keyPath
- parameter keyPath: the keyPath for the attribute
*/
public init(_ keyPath: KeyPath<O, ValueContainer<O>.Required<T>>) {
self.init(.attribute(keyPath))
}
/**
Initializes a `Select` that queries the value of an attribute pertained by a keyPath
- parameter keyPath: the keyPath for the attribute
*/
public init(_ keyPath: KeyPath<O, ValueContainer<O>.Optional<T>>) {
self.init(.attribute(keyPath))
}
}
extension Select where O: CoreStoreObject, T: ImportableAttributeType & NSCoding & NSCopying {
/**
Initializes a `Select` that queries the value of an attribute pertained by a keyPath
- parameter keyPath: the keyPath for the attribute
*/
public init(_ keyPath: KeyPath<O, TransformableContainer<O>.Required<T>>) {
self.init(.attribute(keyPath))
}
/**
Initializes a `Select` that queries the value of an attribute pertained by a keyPath
- parameter keyPath: the keyPath for the attribute
*/
public init(_ keyPath: KeyPath<O, TransformableContainer<O>.Optional<T>>) {
self.init(.attribute(keyPath))
}
}
// MARK: - SelectClause
/**
Abstracts the `Select` clause for protocol utilities.
*/
public protocol SelectClause {
/**
The `DynamicObject` type associated with the clause
*/
associatedtype ObjectType: DynamicObject
/**
The `SelectResultType` type associated with the clause
*/
associatedtype ReturnType: SelectResultType
/**
The `SelectTerm`s for the query
*/
var selectTerms: [SelectTerm<ObjectType>] { get }
}
// MARK: - NSDictionary: SelectAttributesResultType
extension NSDictionary: SelectAttributesResultType {
// MARK: SelectAttributesResultType
public static func cs_fromQueryResultsNativeType(_ result: [Any]) -> [[String : Any]] {
return result as! [[String: Any]]
}
}
|
mit
|
67379ee035f66af5ef7567191eece1c1
| 36.297784 | 239 | 0.624346 | 4.870501 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.