repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Hunter-Li-EF/HLAlbumPickerController
refs/heads/master
HLAlbumPickerController/Classes/HLAlbumGroupCell.swift
mit
1
// // HLAlbumGroupCell.swift // Pods // // Created by Hunter Li on 1/9/2016. // // import UIKit import Photos internal class HLAlbumGroupCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .default layoutMargins = UIEdgeInsets.zero setupIcon() setupNameLabel() setupCountLabel() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate var icon: UIImageView? fileprivate func setupIcon(){ let icon = UIImageView() icon.translatesAutoresizingMaskIntoConstraints = false icon.contentMode = .scaleAspectFit contentView.addSubview(icon) self.icon = icon contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-8-[icon(==44)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["icon":icon])) contentView.addConstraint(NSLayoutConstraint(item: icon, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1.0, constant: 8)) contentView.addConstraint(NSLayoutConstraint(item: icon, attribute: .width, relatedBy: .equal, toItem: icon, attribute: .height, multiplier: 1.0, constant: 0)) } var nameLable: UILabel? fileprivate func setupNameLabel(){ let nameLable = UILabel() nameLable.translatesAutoresizingMaskIntoConstraints = false nameLable.font = UIFont.systemFont(ofSize: 18) nameLable.textColor = UIColor.darkText contentView.addSubview(nameLable) self.nameLable = nameLable contentView.addConstraint(NSLayoutConstraint(item: nameLable, attribute: .left, relatedBy: .equal, toItem: icon, attribute: .right, multiplier: 1.0, constant: 8)) contentView.addConstraint(NSLayoutConstraint(item: nameLable, attribute: .top, relatedBy: .equal, toItem: icon, attribute: .top, multiplier: 1.0, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: nameLable, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1.0, constant: 0)) } var countLable: UILabel? fileprivate func setupCountLabel(){ let countLable = UILabel() countLable.translatesAutoresizingMaskIntoConstraints = false countLable.font = UIFont.systemFont(ofSize: 15) countLable.textColor = UIColor.darkText contentView.addSubview(countLable) self.countLable = countLable contentView.addConstraint(NSLayoutConstraint(item: countLable, attribute: .left, relatedBy: .equal, toItem: nameLable, attribute: .left, multiplier: 1.0, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: countLable, attribute: .bottom, relatedBy: .equal, toItem: icon, attribute: .bottom, multiplier: 1.0, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: countLable, attribute: .right, relatedBy: .equal, toItem: nameLable, attribute: .right, multiplier: 1.0, constant: 0)) } func refreshView(_ assetGroup: PHAssetCollection?) { guard let group = assetGroup else{ return } nameLable?.text = assetGroup?.localizedTitle let results = PHAsset.fetchAssets(in: group, options: nil) if let asset = results.firstObject { let options = PHImageRequestOptions() options.version = .current options.deliveryMode = .highQualityFormat options.resizeMode = .exact options.isSynchronous = true PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: 44 * UIScreen.main.scale, height: 44 * UIScreen.main.scale), contentMode: .aspectFill, options: options) { (image, mdeia) in self.icon?.image = image self.countLable?.text = String(results.count) } } } }
e558c07a78788cf8b5f45280c36de5a2
45.146067
212
0.673971
false
false
false
false
apple/swift-llbuild
refs/heads/main
products/llbuildSwift/BuildValue.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for Swift project authors // This file contains Swift bindings for the llbuild C API. #if canImport(Darwin) import Darwin.C #elseif os(Windows) import ucrt import WinSDK #elseif canImport(Glibc) import Glibc #else #error("Missing libc or equivalent") #endif import struct Foundation.Date // We don't need this import if we're building // this file as part of the llbuild framework. #if !LLBUILD_FRAMEWORK import llbuild #endif extension BuildValueKind: CustomStringConvertible { public var description: String { switch self { case .invalid: return "invalid" case .virtualInput: return "virtualInput" case .existingInput: return "existingInput" case .missingInput: return "missingInput" case .directoryContents: return "directoryContents" case .directoryTreeSignature: return "directoryTreeSignature" case .directoryTreeStructureSignature: return "directoryTreeStructureSignature" case .staleFileRemoval: return "staleFileRemoval" case .missingOutput: return "missingOutput" case .failedInput: return "failedInput" case .successfulCommand: return "successfulCommand" case .failedCommand: return "failedCommand" case .propagatedFailureCommand: return "propagatedFailureCommand" case .cancelledCommand: return "cancelledCommand" case .skippedCommand: return "skippedCommand" case .target: return "target" case .filteredDirectoryContents: return "filteredDirectoryContents" case .successfulCommandWithOutputSignature: return "successfulCommandWithOutputSignature" @unknown default: return "unknown" } } } extension BuildValueFileInfo: Equatable { public static func == (lhs: BuildValueFileInfo, rhs: BuildValueFileInfo) -> Bool { return lhs.device == rhs.device && lhs.inode == rhs.inode && lhs.mode == rhs.mode && lhs.size == rhs.size && lhs.modTime == rhs.modTime } } extension BuildValueFileInfo: CustomStringConvertible { public var description: String { return "<FileInfo device=\(device) inode=\(inode) mode=\(mode) size=\(size) modTime=\(modTime)>" } } extension BuildValueFileTimestamp: Equatable { public static func == (lhs: llb_build_value_file_timestamp_t_, rhs: BuildValueFileTimestamp) -> Bool { return lhs.seconds == rhs.seconds && lhs.nanoseconds == rhs.nanoseconds } } extension BuildValueFileTimestamp: Comparable { public static func < (lhs: BuildValueFileTimestamp, rhs: BuildValueFileTimestamp) -> Bool { if lhs.seconds != rhs.seconds { return lhs.seconds < rhs.seconds } return lhs.nanoseconds < rhs.nanoseconds } } extension BuildValueFileTimestamp: CustomStringConvertible { public var description: String { return "<FileTimestamp seconds=\(seconds) nanoseconds=\(nanoseconds)>" } } public extension Date { init(_ ft: BuildValueFileTimestamp) { // Using reference date, instead of 1970, which offers a bit more nanosecond precision since it is a lower absolute number. self.init(timeIntervalSinceReferenceDate: Double(ft.seconds) - Date.timeIntervalBetween1970AndReferenceDate + (1.0e-9 * Double(ft.nanoseconds))) } } /// Abstract class of a build value, use subclasses public class BuildValue: CustomStringConvertible, Equatable, Hashable { /// Build values can be of different kind - each has its own subclass public typealias Kind = BuildValueKind /// Describes information about a file or directory public typealias FileInfo = BuildValueFileInfo /// Is part of the file info by providing a timestamp for the modifiation time public typealias FileTimestamp = BuildValueFileTimestamp /// Is a calculated signature of general purpose used by some of the subclasses public typealias CommandSignature = BuildValueCommandSignature /// The opaque pointer to the internal C++ class fileprivate let internalBuildValue: OpaquePointer fileprivate var owned: Bool = true fileprivate init(_ internalBuildValue: OpaquePointer) { self.internalBuildValue = internalBuildValue } /// Tries to construct a BuildValue from the given data /// /// NOTE: If the data is malformed this code might assert. public static func construct(from value: Value) -> BuildValue? { var llbData = copiedDataFromBytes(value.data) defer { llb_data_destroy(&llbData) } return construct(from: llb_build_value_make(&llbData)) } public static func construct(from buildValue: OpaquePointer) -> BuildValue? { let kind = llb_build_value_get_kind(buildValue) switch kind { case .invalid: return Invalid(buildValue) case .virtualInput: return VirtualInput(buildValue) case .existingInput: return ExistingInput(buildValue) case .missingInput: return MissingInput(buildValue) case .directoryContents: return DirectoryContents(buildValue) case .directoryTreeSignature: return DirectoryTreeSignature(buildValue) case .directoryTreeStructureSignature: return DirectoryTreeStructureSignature(buildValue) case .staleFileRemoval: return StaleFileRemoval(buildValue) case .missingOutput: return MissingOutput(buildValue) case .failedInput: return FailedInput(buildValue) case .successfulCommand: return SuccessfulCommand(buildValue) case .failedCommand: return FailedCommand(buildValue) case .propagatedFailureCommand: return PropagatedFailureCommand(buildValue) case .cancelledCommand: return CancelledCommand(buildValue) case .skippedCommand: return SkippedCommand(buildValue) case .target: return Target(buildValue) case .filteredDirectoryContents: return FilteredDirectoryContents(buildValue) case .successfulCommandWithOutputSignature: return SuccessfulCommandWithOutputSignature(buildValue) @unknown default: return nil } } deinit { // As implemented below, ownership of the internal build value may be // moved, thus we should only destroy it if we actually own it. if owned { llb_build_value_destroy(internalBuildValue) } } /// Moves ownership of the internal build value object /// This attempts to provide move semantics for uniquely owned instances to /// prevent copy overhead. If that cannot be guaranteed, it will clone the /// build value to ensure that the internal object remains valid for other /// references. static func move(_ value: inout BuildValue) -> OpaquePointer { if isKnownUniquelyReferenced(&value) { value.owned = false return value.internalBuildValue } return llb_build_value_clone(value.internalBuildValue) } /// The kind of the build value. /// The kind also defines the subclass, so kind == .invalid means the instance should be of type Invalid public var kind: Kind { return llb_build_value_get_kind(internalBuildValue) } /// The raw value data public var valueData: ValueType { var result = ValueType() withUnsafeMutablePointer(to: &result) { ptr in llb_build_value_get_value_data(internalBuildValue, ptr) { context, data in context?.assumingMemoryBound(to: ValueType.self).pointee.append(data) } } return result } public var description: String { return "<BuildValue.\(type(of: self))>" } public static func ==(lhs: BuildValue, rhs: BuildValue) -> Bool { return lhs.equal(to: rhs) } public func hash(into hasher: inout Hasher) { hasher.combine(valueData) } /// This needs to be overriden in subclass if properties need to be checked fileprivate func equal(to other: BuildValue) -> Bool { return type(of: self) == type(of: other) } /// An invalid value, for sentinel purposes. public final class Invalid: BuildValue { public convenience init() { self.init(llb_build_value_make_invalid()) } } /// A value produced by a virtual input. public final class VirtualInput: BuildValue { public convenience init() { self.init(llb_build_value_make_virtual_input()) } } /// A value produced by an existing input file. public final class ExistingInput: BuildValue { public convenience init(fileInfo: BuildValueFileInfo) { self.init(llb_build_value_make_existing_input(fileInfo)) } /// Information about the existing input file public var fileInfo: FileInfo { return llb_build_value_get_output_info(internalBuildValue) } override func equal(to other: BuildValue) -> Bool { return (other as? ExistingInput)?.fileInfo == fileInfo } public override var description: String { return "<BuildValue.\(type(of: self)) fileInfo=\(fileInfo)>" } } /// A value produced by a missing input file. public final class MissingInput: BuildValue { public convenience init() { self.init(llb_build_value_make_missing_input()) } } /// The contents of a directory. public final class DirectoryContents: BuildValue { public convenience init(directoryInfo: FileInfo, contents: [String]) { let ptr = contents.withCArrayOfStrings { ptr in llb_build_value_make_directory_contents(directoryInfo, ptr, Int32(contents.count)) } self.init(ptr) } /// The information about the directory public var fileInfo: FileInfo { return llb_build_value_get_output_info(internalBuildValue) } /// The contents of the directory public var contents: [String] { var result: [String] = [] withUnsafeMutablePointer(to: &result) { ptr in llb_build_value_get_directory_contents(internalBuildValue, ptr) { ctx, data in ctx!.assumingMemoryBound(to: [String].self).pointee.append(stringFromData(data)) } } return result } override func equal(to other: BuildValue) -> Bool { guard let other = other as? DirectoryContents else { return false } return fileInfo == other.fileInfo && contents == other.contents } public override var description: String { return "<BuildValue.\(type(of: self)) fileInfo=\(fileInfo) contents=[\(contents.joined(separator: ", "))]>" } } /// The signature of a directories contents. public final class DirectoryTreeSignature: BuildValue { public convenience init(signature: CommandSignature) { self.init(llb_build_value_make_directory_tree_signature(signature)) } /// The signature of the directory tree public var signature: CommandSignature { return llb_build_value_get_directory_tree_signature(internalBuildValue) } override func equal(to other: BuildValue) -> Bool { guard let other = other as? DirectoryTreeSignature else { return false } return signature == other.signature } public override var description: String { return "<BuildValue.\(type(of: self)) signature=\(signature)>" } } /// The signature of a directories structure. public final class DirectoryTreeStructureSignature: BuildValue { public convenience init(signature: CommandSignature) { self.init(llb_build_value_make_directory_tree_structure_signature(signature)) } /// The signature of the directory's tree structure public var signature: CommandSignature { return llb_build_value_get_directory_tree_structure_signature(internalBuildValue) } override func equal(to other: BuildValue) -> Bool { guard let other = other as? DirectoryTreeStructureSignature else { return false } return signature == other.signature } public override var description: String { return "<BuildValue.\(type(of: self)) signature=\(signature)>" } } /// A value produced by a command which succeeded, but whose output was /// missing. public final class MissingOutput: BuildValue { public convenience init() { self.init(llb_build_value_make_missing_output()) } } /// A value for a produced output whose command failed or was cancelled. public final class FailedInput: BuildValue { public convenience init() { self.init(llb_build_value_make_failed_input()) } } /// A value produced by a successful command. public final class SuccessfulCommand: BuildValue { public convenience init(outputInfos: [FileInfo]) { self.init(llb_build_value_make_successful_command(outputInfos, Int32(outputInfos.count))) } /// Information about the outputs of the command public var outputInfos: [FileInfo] { var result: [FileInfo] = [] withUnsafeMutablePointer(to: &result) { ptr in llb_build_value_get_file_infos(internalBuildValue, ptr) { ctx, fileInfo in ctx!.assumingMemoryBound(to: [FileInfo].self).pointee.append(fileInfo) } } return result } override func equal(to other: BuildValue) -> Bool { guard let other = other as? SuccessfulCommand else { return false } return outputInfos == other.outputInfos } public override var description: String { return "<BuildValue.\(type(of: self)) outputInfos=[\(outputInfos.map { $0.description }.joined(separator: ", "))]>" } } /// A value produced by a failing command. public final class FailedCommand: BuildValue { public convenience init() { self.init(llb_build_value_make_failed_command()) } } /// A value produced by a command which was skipped because one of its /// dependencies failed. public final class PropagatedFailureCommand: BuildValue { public convenience init() { self.init(llb_build_value_make_propagated_failure_command()) } } /// A value produced by a command which was cancelled. public final class CancelledCommand: BuildValue { public convenience init() { self.init(llb_build_value_make_cancelled_command()) } } /// A value produced by a command which was skipped. public final class SkippedCommand: BuildValue { public convenience init() { self.init(llb_build_value_make_skipped_command()) } } /// Sentinel value representing the result of "building" a top-level target. public final class Target: BuildValue { public convenience init() { self.init(llb_build_value_make_target()) } } /// A value produced by stale file removal. public final class StaleFileRemoval: BuildValue { public convenience init(fileList: [String]) { let ptr = fileList.withCArrayOfStrings { ptr in llb_build_value_make_stale_file_removal(ptr, Int32(fileList.count)) } self.init(ptr) } /// A list of the files that got removed public var fileList: [String] { var result: [String] = [] withUnsafeMutablePointer(to: &result) { ptr in llb_build_value_get_stale_file_list(internalBuildValue, ptr) { ctx, data in ctx!.assumingMemoryBound(to: [String].self).pointee.append(stringFromData(data)) } } return result } override func equal(to other: BuildValue) -> Bool { guard let other = other as? StaleFileRemoval else { return false } return fileList == other.fileList } public override var description: String { return "<BuildValue.\(type(of: self)) fileList=[\(fileList.joined(separator: ", "))]>" } } /// The filtered contents of a directory. public final class FilteredDirectoryContents: BuildValue { public convenience init(contents: [String]) { let ptr = contents.withCArrayOfStrings { ptr in llb_build_value_make_filtered_directory_contents(ptr, Int32(contents.count)) } self.init(ptr) } /// The contents of the directory with the filter applied public var contents: [String] { var result: [String] = [] withUnsafeMutablePointer(to: &result) { ptr in llb_build_value_get_directory_contents(internalBuildValue, ptr) { ctx, data in ctx!.assumingMemoryBound(to: [String].self).pointee.append(stringFromData(data)) } } return result } override func equal(to other: BuildValue) -> Bool { guard let other = other as? FilteredDirectoryContents else { return false } return contents == other.contents } public override var description: String { return "<BuildValue.\(type(of: self)) contents=[\(contents.joined(separator: ", "))]>" } } /// A value produced by a successful command with an output signature. public final class SuccessfulCommandWithOutputSignature: BuildValue { public convenience init(outputInfos: [FileInfo], signature: CommandSignature) { self.init(llb_build_value_make_successful_command_with_output_signature(outputInfos, Int32(outputInfos.count), signature)) } /// Information about the outputs of the command public var outputInfos: [FileInfo] { var result: [FileInfo] = [] withUnsafeMutablePointer(to: &result) { ptr in llb_build_value_get_file_infos(internalBuildValue, ptr) { ctx, fileInfo in ctx!.assumingMemoryBound(to: [FileInfo].self).pointee.append(fileInfo) } } return result } /// The output signature of the command public var signature: CommandSignature { return llb_build_value_get_output_signature(internalBuildValue) } override func equal(to other: BuildValue) -> Bool { guard let other = other as? SuccessfulCommandWithOutputSignature else { return false } return outputInfos == other.outputInfos && signature == other.signature } public override var description: String { return "<BuildValue.\(type(of: self)) outputInfos=[\(outputInfos.map { $0.description }.joined(separator: ", "))] signature=\(signature)>" } } }
7189a0d2e8337d0fbe2c3a1975f5b752
38.577778
152
0.642387
false
false
false
false
wangkai678/WKDouYuZB
refs/heads/master
WKDouYuZB/WKDouYuZB/Classes/Main/View/CollectionBaseCell.swift
mit
1
// // CollectionBaseCell.swift // WKDouYuZB // // Created by 王凯 on 17/5/22. // Copyright © 2017年 wk. All rights reserved. // import UIKit import Kingfisher class CollectionBaseCell: UICollectionViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var nickNameLabel: UILabel! @IBOutlet weak var onlineBtn: UIButton! //MARK: - 定义模型属性 var anchor : AnchorModel?{ didSet{ //校验模型是否有值 guard let anchor = anchor else {return} //显示在线人数 var onlineStr : String = ""; if anchor.online >= 10000 { onlineStr = "\(Int(anchor.online / 10000))万在线"; }else{ onlineStr = "\(anchor.online)在线"; } onlineBtn.setTitle(onlineStr, for: .normal); //昵称 nickNameLabel.text = anchor.nickname; //设置封面图片 guard let iconURL = URL(string: anchor.vertical_src) else {return} iconImageView.kf.setImage(with: ImageResource(downloadURL: iconURL)); iconImageView.kf.setImage(with: ImageResource(downloadURL: iconURL), placeholder: UIImage(named:"live_cell_default_phone"), options: nil, progressBlock: nil, completionHandler: nil) } } }
931c83d9fa1a3a8dfbcb4b31ada7f041
29.093023
193
0.59119
false
false
false
false
objecthub/swift-lispkit
refs/heads/master
Sources/LispKit/Primitives/HashTableLibrary.swift
apache-2.0
1
// // HashTableLibrary.swift // LispKit // // Created by Matthias Zenger on 18/07/2016. // Copyright © 2016 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import NumberKit /// /// Hashtable library: based on R6RS spec. /// public final class HashTableLibrary: NativeLibrary { private static let equalHashProc = Procedure("equal-hash", HashTableLibrary.equalHashVal) private static let eqvHashProc = Procedure("eqv-hash", HashTableLibrary.eqvHashVal) private static let eqHashProc = Procedure("eq-hash", HashTableLibrary.eqHashVal) private static let defaultCapacity = 127 private var bucketsProc: Procedure! = nil private var bucketAddProc: Procedure! = nil private var bucketDelProc: Procedure! = nil private var equalProc: Procedure! = nil private var eqvProc: Procedure! = nil private var eqProc: Procedure! = nil private var hashtableUnionLoc = 0 private var hashtableIntersectionLoc = 0 private var hashtableDifferenceLoc = 0 /// Name of the library. public override class var name: [String] { return ["lispkit", "hashtable"] } /// Dependencies of the library. public override func dependencies() { self.`import`(from: ["lispkit", "core"], "define", "lambda", "equal?", "eqv?", "eq?", "not", "call-with-values") self.`import`(from: ["lispkit", "control"], "let", "let*", "letrec", "if", "do") self.`import`(from: ["lispkit", "list"], "cons", "car", "cdr", "pair?", "for-each", "value", "null?") self.`import`(from: ["lispkit", "math"], ">", "+", "*") self.`import`(from: ["lispkit", "vector"], "vector-for-each") } /// Access to imported native procedures. public override func initializations() { self.equalProc = self.procedure(self.imported("equal?")) self.eqvProc = self.procedure(self.imported("eqv?")) self.eqProc = self.procedure(self.imported("eq?")) } /// Declarations of the library. public override func declarations() { self.bucketsProc = Procedure("_buckets", self.hBuckets) self.bucketAddProc = Procedure("_bucket-add!", self.hBucketAdd) self.bucketDelProc = Procedure("_bucket-repl!", self.hBucketRepl) self.define(HashTableLibrary.equalHashProc) self.define(HashTableLibrary.eqvHashProc) self.define(HashTableLibrary.eqHashProc) self.define(Procedure("_make-hashtable", makeHashTable)) self.define(Procedure("make-eq-hashtable", makeEqHashTable)) self.define(Procedure("make-eqv-hashtable", makeEqvHashTable)) self.define(Procedure("make-equal-hashtable", makeEqualHashTable)) self.define("make-hashtable", via: "(define (make-hashtable hash eql . size)", " (letrec ((k (if (pair? size) (car size) \(HashTableLibrary.defaultCapacity)))", " (find (lambda (key bs)", " (if (pair? bs)", " (if (eql (car (car bs)) key) (car bs) (find key (cdr bs)))", " #f)))", " (drop (lambda (key bs)", // TODO: Use a built-in filter function for this " (if (pair? bs)", " (if (eql (car (car bs)) key)", " bs", " (let ((res (drop key (cdr bs))))", " (cons (car res) (cons (car bs) (cdr res)))))", " (cons #f bs)))))", " (_make-hashtable k eql hash", " (lambda (ht buckets key)", " (find key (buckets ht (hash key))))", " (lambda (ht buckets add key value)", " (add ht (hash key) key value)", " (if (> (hashtable-load ht) 0.75)", " (let ((ms (buckets ht)))", " (hashtable-clear! ht (+ (* (hashtable-size ht) 3) 1))", " (for-each (lambda (m) (add ht (hash (car m)) (car m) (cdr m))) ms))))", " (lambda (ht buckets replace key)", " (let* ((h (hash key))", " (res (drop key (buckets ht h))))", " (replace ht h (cdr res)) (car res))))))") self.define(Procedure("hashtable?", isHashTable)) self.define(Procedure("eq-hashtable?", isEqHashTable)) self.define(Procedure("eqv-hashtable?", isEqvHashTable)) self.define(Procedure("equal-hashtable?", isEqualHashTable)) self.define(Procedure("hashtable-mutable?", isHashTableMutable)) self.define(Procedure("hashtable-size", hashTableSize)) self.define(Procedure("hashtable-load", hashTableLoad)) self.define(Procedure("hashtable-get", hashTableGet)) self.define(Procedure("hashtable-add!", hashTableAdd)) self.define(Procedure("hashtable-remove!", hashTableRemove)) self.define("hashtable-contains?", via: "(define (hashtable-contains? map key) (pair? (hashtable-get map key)))") self.define("hashtable-ref", via: "(define (hashtable-ref map key default) (value (hashtable-get map key) default))") self.define("hashtable-set!", via: "(define (hashtable-set! map key value)", " (hashtable-remove! map key)(hashtable-add! map key value))") self.define("hashtable-update!", via: "(define (hashtable-update! map key proc default)" + " (hashtable-add! map key (proc (value (hashtable-remove! map key) default))))") self.define("hashtable-delete!", via: "(define (hashtable-delete! map key)", " (if (hashtable-remove! map key) (hashtable-delete! map key)))") self.define(Procedure("hashtable-clear!", hashTableClear)) self.hashtableUnionLoc = self.define("_hashtable-union!", via: "(define (_hashtable-union! ht1 ht2)", " (do ((ks (hashtable->alist ht2) (cdr ks)))", " ((null? ks))", " (if (not (hashtable-contains? ht1 (car (car ks))))", " (hashtable-add! ht1 (car (car ks)) (cdr (car ks))))))") self.hashtableIntersectionLoc = self.define("_hashtable-intersection!", via: "(define (_hashtable-intersection! ht1 ht2)", " (do ((ks (hashtable->alist ht1) (cdr ks)))", " ((null? ks))", " (if (not (hashtable-contains? ht2 (car (car ks))))", " (hashtable-delete! ht1 (car (car ks))))))") self.hashtableDifferenceLoc = self.define("_hashtable-difference!", via: "(define (_hashtable-difference! ht1 ht2)", " (do ((ks (hashtable->alist ht1) (cdr ks)))", " ((null? ks))", " (if (hashtable-contains? ht2 (car (car ks)))", " (hashtable-delete! ht1 (car (car ks))))))") self.define(Procedure("hashtable-union!", hashTableUnion)) self.define(Procedure("hashtable-intersection!", hashTableIntersection)) self.define(Procedure("hashtable-difference!", hashTableDifference)) self.define(Procedure("hashtable-copy", hashTableCopy)) self.define(Procedure("hashtable-keys", hashTableKeys)) self.define(Procedure("hashtable-values", hashTableValues)) self.define(Procedure("hashtable-entries", hashTableEntries)) self.define(Procedure("hashtable-key-list", hashTableKeyList)) self.define(Procedure("hashtable-value-list", hashTableValueList)) self.define("hashtable-for-each", via: "(define (hashtable-for-each proc ht)", " (call-with-values", " (lambda () (hashtable-entries ht))", " (lambda (keys vals) (vector-for-each proc keys vals))))") self.define("hashtable-map!", via: "(define (hashtable-map! proc ht)", " (call-with-values", " (lambda () (let ((res (hashtable-entries ht))) (hashtable-clear! ht) res))", " (lambda (keys vals)", " (vector-for-each (lambda (key value) (hashtable-add! ht key (proc key value)))", " keys vals))))") self.define(Procedure("hashtable->alist", hashTableToAlist)) self.define("alist->hashtable!", via: "(define (alist->hashtable! hm alist)", " (for-each (lambda (m) (hashtable-add! hm (car m) (cdr m))) alist))") self.define(Procedure("alist->eq-hashtable", alistToEqHashTable)) self.define(Procedure("alist->eqv-hashtable", alistToEqvHashTable)) self.define(Procedure("alist->equal-hashtable", alistToEqualHashTable)) self.define(Procedure("hashtable-equivalence-function", hashTableEquivalenceFunction)) self.define(Procedure("hashtable-hash-function", hashTableHashFunction)) self.define(Procedure("boolean-hash", booleanHashVal)) self.define(Procedure("char-hash", charHashVal)) self.define(Procedure("char-ci-hash", charCiHashVal)) self.define(Procedure("string-hash", stringHashVal)) self.define(Procedure("string-ci-hash", stringCiHashVal)) self.define(Procedure("symbol-hash", symbolHashVal)) self.define(Procedure("number-hash", numberHashVal)) self.define(Procedure("combine-hash", combineHash)) self.define("hashtable-empty-copy", via: "(define (hashtable-empty-copy ht)", " (make-hashtable (hashtable-hash-function ht #t) (hashtable-equivalence-function ht)))") } func makeHashTable(_ capacity: Expr, _ eql: Expr, _ hsh: Expr, _ args: Arguments) throws -> Expr { guard args.count == 3 else { throw RuntimeError.argumentCount( of: "make-hashtable", min: 6, max: 6, args: .pair(capacity, .pair(eql, .pair(hsh, .makeList(args))))) } let numBuckets = try capacity.asInt() let eqlProc = try eql.asProcedure() let hshProc = try hsh.asProcedure() if eqlProc == self.equalProc && hshProc == HashTableLibrary.equalHashProc { return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .equal)) } else if eqlProc == self.eqvProc && hshProc == HashTableLibrary.eqvHashProc { return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .eqv)) } else if eqlProc == self.eqProc && hshProc == HashTableLibrary.eqHashProc { return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .eq)) } else { let procs = HashTable.CustomProcedures(eql: eqlProc, hsh: hshProc, get: try args[args.startIndex].asProcedure(), add: try args[args.startIndex + 1].asProcedure(), del: try args[args.startIndex + 2].asProcedure()) return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .custom(procs))) } } func makeEqHashTable(_ capacity: Expr?) throws -> Expr { let numBuckets = try capacity?.asInt() ?? HashTableLibrary.defaultCapacity return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .eq)) } func makeEqvHashTable(_ capacity: Expr?) throws -> Expr { let numBuckets = try capacity?.asInt() ?? HashTableLibrary.defaultCapacity return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .eqv)) } func makeEqualHashTable(_ capacity: Expr?) throws -> Expr { let numBuckets = try capacity?.asInt() ?? HashTableLibrary.defaultCapacity return .table(HashTable(capacity: numBuckets, mutable: true, equiv: .equal)) } func isHashTable(_ expr: Expr) -> Expr { guard case .table(_) = expr else { return .false } return .true } func isEqHashTable(_ expr: Expr) -> Expr { guard case .table(let table) = expr, case .eq = table.equiv else { return .false } return .true } func isEqvHashTable(_ expr: Expr) -> Expr { guard case .table(let table) = expr, case .eqv = table.equiv else { return .false } return .true } func isEqualHashTable(_ expr: Expr) -> Expr { guard case .table(let table) = expr, case .equal = table.equiv else { return .false } return .true } func isHashTableMutable(_ expr: Expr) -> Expr { guard case .table(let table) = expr else { return .false } return .makeBoolean(table.mutable) } func hashTableSize(_ expr: Expr) throws -> Expr { return .fixnum(Int64(try expr.asHashTable().count)) } func hashTableLoad(_ expr: Expr) throws -> Expr { let map = try expr.asHashTable() return .makeNumber(Double(map.count) / Double(map.bucketCount)) } func hashTableGet(_ args: Arguments) throws -> (Procedure, Exprs) { try EvalError.assert(args, count: 2) let map = try args[args.startIndex].asHashTable() let key = args[args.startIndex + 1] guard case .custom(let procs) = map.equiv else { return (CoreLibrary.idProc, [map.get(key) ?? .false]) } return (procs.get, [.table(map), .procedure(self.bucketsProc), key]) } func hashTableAdd(_ args: Arguments) throws -> (Procedure, Exprs) { try EvalError.assert(args, count: 3) let map = try args.first!.asHashTable() let key = args[args.startIndex + 1] let value = args[args.startIndex + 2] guard map.mutable else { throw RuntimeError.eval(.attemptToModifyImmutableData, .table(map)) } guard case .custom(let procs) = map.equiv else { guard map.add(key: key, mapsTo: value) else { preconditionFailure("trying to set mapping in immutable hash map") } return (CoreLibrary.idProc, [.void]) } return (procs.add, [.table(map), .procedure(self.bucketsProc), .procedure(self.bucketAddProc), key, value]) } func hashTableRemove(_ args: Arguments) throws -> (Procedure, Exprs) { try EvalError.assert(args, count: 2) let map = try args.first!.asHashTable() let key = args[args.startIndex + 1] guard map.mutable else { throw RuntimeError.eval(.attemptToModifyImmutableData, .table(map)) } guard case .custom(let procs) = map.equiv else { guard let res = map.remove(key: key) else { preconditionFailure("trying to delete mapping in immutable hash map") } return (CoreLibrary.idProc, [res]) } return (procs.del, [.table(map), .procedure(self.bucketsProc), .procedure(self.bucketDelProc), key]) } func hashTableCopy(_ expr: Expr, mutable: Expr?) throws -> Expr { let map = try expr.asHashTable() return .table(HashTable(copy: map, mutable: mutable == .true)) } func hashTableClear(_ expr: Expr, k: Expr?) throws -> Expr { let map = try expr.asHashTable() guard map.mutable else { throw RuntimeError.eval(.attemptToModifyImmutableData, .table(map)) } guard try map.clear(k?.asInt()) else { preconditionFailure("trying to clear immutable hash map") } return .void } func hashTableUnion(_ args: Arguments) throws -> (Procedure, Exprs) { try EvalError.assert(args, count: 2) let map1 = try args.first!.asHashTable() let map2 = try args[args.startIndex + 1].asHashTable() guard map1.mutable else { throw RuntimeError.eval(.attemptToModifyImmutableData, .table(map1)) } guard case .custom(_) = map1.equiv else { guard map1.union(map2) else { preconditionFailure("trying to union mapping with immutable hash map") } return (CoreLibrary.voidProc, []) } return (self.procedure(self.hashtableUnionLoc), [.table(map1), .table(map2)]) } func hashTableIntersection(_ args: Arguments) throws -> (Procedure, Exprs) { try EvalError.assert(args, count: 2) let map1 = try args.first!.asHashTable() let map2 = try args[args.startIndex + 1].asHashTable() guard map1.mutable else { throw RuntimeError.eval(.attemptToModifyImmutableData, .table(map1)) } guard case .custom(_) = map1.equiv else { guard map1.difference(map2, intersect: true) else { preconditionFailure("trying to intersect mapping with immutable hash map") } return (CoreLibrary.voidProc, []) } return (self.procedure(self.hashtableIntersectionLoc), [.table(map1), .table(map2)]) } func hashTableDifference(_ args: Arguments) throws -> (Procedure, Exprs) { try EvalError.assert(args, count: 2) let map1 = try args.first!.asHashTable() let map2 = try args[args.startIndex + 1].asHashTable() guard map1.mutable else { throw RuntimeError.eval(.attemptToModifyImmutableData, .table(map1)) } guard case .custom(_) = map1.equiv else { guard map1.difference(map2, intersect: false) else { preconditionFailure("trying to compute difference with immutable hash map") } return (CoreLibrary.voidProc, []) } return (self.procedure(self.hashtableDifferenceLoc), [.table(map1), .table(map2)]) } func hashTableKeys(_ expr: Expr) throws -> Expr { return .vector(Collection(kind: .immutableVector, exprs: try expr.asHashTable().keys)) } func hashTableValues(_ expr: Expr) throws -> Expr { return .vector(Collection(kind: .immutableVector, exprs: try expr.asHashTable().values)) } func hashTableEntries(_ expr: Expr) throws -> Expr { return .values( .pair(.vector(Collection(kind: .immutableVector, exprs: try expr.asHashTable().keys)), .pair(.vector(Collection(kind: .immutableVector, exprs: try expr.asHashTable().values)), .null))) } func hashTableKeyList(_ expr: Expr) throws -> Expr { return try expr.asHashTable().keyList() } func hashTableValueList(_ expr: Expr) throws -> Expr { return try expr.asHashTable().valueList() } func hashTableToAlist(_ expr: Expr) throws -> Expr { return try expr.asHashTable().entryList() } private func newHashTable(_ equiv: HashTable.Equivalence, capacity: Int?) -> HashTable { let numBuckets = capacity ?? HashTableLibrary.defaultCapacity return HashTable(capacity: numBuckets, mutable: true, equiv: equiv) } private func enterAlist(_ expr: Expr, into map: HashTable) throws { var list = expr while case .pair(.pair(let key, let value), let cdr) = list { map.add(key: key, mapsTo: value) list = cdr } guard list.isNull else { throw RuntimeError.type(expr, expected: [.assocListType]) } } func alistToEqHashTable(_ expr: Expr, capacity: Expr?) throws -> Expr { let table = self.newHashTable(.eq, capacity: try capacity?.asInt()) try self.enterAlist(expr, into: table) return .table(table) } func alistToEqvHashTable(_ expr: Expr, capacity: Expr?) throws -> Expr { let table = self.newHashTable(.eqv, capacity: try capacity?.asInt()) try self.enterAlist(expr, into: table) return .table(table) } func alistToEqualHashTable(_ expr: Expr, capacity: Expr?) throws -> Expr { let table = self.newHashTable(.equal, capacity: try capacity?.asInt()) try self.enterAlist(expr, into: table) return .table(table) } func hashTableEquivalenceFunction(_ expr: Expr) throws -> Expr { switch try expr.asHashTable().equiv { case .eq: return .procedure(self.eqProc) case .eqv: return .procedure(self.eqvProc) case .equal: return .procedure(self.equalProc) case .custom(let procs): return .procedure(procs.eql) } } func hashTableHashFunction(_ expr: Expr, _ force: Expr?) throws -> Expr { switch try expr.asHashTable().equiv { case .eq: return (force?.isTrue ?? false) ? .procedure(HashTableLibrary.eqHashProc) : .false case .eqv: return (force?.isTrue ?? false) ? .procedure(HashTableLibrary.eqvHashProc) : .false case .equal: return .procedure(HashTableLibrary.equalHashProc) case .custom(let procs): return .procedure(procs.hsh) } } private static func eqHashVal(_ expr: Expr) -> Expr { return .fixnum(Int64(eqHash(expr))) } private static func eqvHashVal(_ expr: Expr) -> Expr { return .fixnum(Int64(eqvHash(expr))) } private static func equalHashVal(_ expr: Expr) -> Expr { return .fixnum(Int64(equalHash(expr))) } private func booleanHashVal(_ expr: Expr) -> Expr { return .fixnum(Int64(expr.isTrue.hashValue)) } private func numberHashVal(_ expr: Expr) throws -> Expr { switch expr { case .fixnum(let num): return .fixnum(Int64(num.hashValue)) case .bignum(let num): return .fixnum(Int64(num.hashValue)) case .rational(let n, let d): var hasher = Hasher() hasher.combine(n) hasher.combine(d) return .fixnum(Int64(hasher.finalize())) case .flonum(let num): return .fixnum(Int64(num.hashValue)) case .complex(let num): return .fixnum(Int64(num.hashValue)) default: throw RuntimeError.type(expr, expected: [.numberType]) } } private func charHashVal(_ expr: Expr) throws -> Expr { guard case .char(_) = expr else { throw RuntimeError.type(expr, expected: [.charType]) } return .fixnum(Int64(expr.hashValue)) } private func charCiHashVal(_ expr: Expr) throws -> Expr { return .fixnum(Int64(try expr.charAsString().lowercased().hashValue)) } private func stringHashVal(_ expr: Expr) throws -> Expr { guard case .string(_) = expr else { throw RuntimeError.type(expr, expected: [.strType]) } return .fixnum(Int64(expr.hashValue)) } private func stringCiHashVal(_ expr: Expr) throws -> Expr { guard case .string(let str) = expr else { throw RuntimeError.type(expr, expected: [.strType]) } return .fixnum(Int64(str.lowercased.hashValue)) } private func symbolHashVal(_ expr: Expr) throws -> Expr { guard case .symbol(_) = expr else { throw RuntimeError.type(expr, expected: [.symbolType]) } return .fixnum(Int64(expr.hashValue)) } private func combineHash(_ args: Arguments) throws -> Expr { var hasher = Hasher() for arg in args { hasher.combine(try arg.asInt64()) } return .fixnum(Int64(hasher.finalize())) } private func bucket(_ hval: Expr, _ numBuckets: Int) throws -> Int { switch hval { case .fixnum(let num): return Int(num %% Int64(numBuckets)) case .bignum(let num): let n = BigInt(numBuckets) let rem = num % n return Int(rem.isNegative ? (rem + n).intValue! : rem.intValue!) default: throw RuntimeError.type(hval, expected: [.exactIntegerType]) } } private func hBuckets(_ expr: Expr, hval: Expr?) throws -> Expr { let map = try expr.asHashTable() if let hashValue = hval { return map.bucketList(try self.bucket(hashValue, map.bucketCount)) } else { return map.bucketList() } } private func hBucketAdd(_ expr: Expr, hval: Expr, key: Expr, value: Expr) throws -> Expr { guard case .table(let map) = expr else { throw RuntimeError.type(expr, expected: [.tableType]) } if !key.isAtom || !value.isAtom { self.context.objects.manage(map) } map.add(try self.bucket(hval, map.bucketCount), key, value) return .void } private func hBucketRepl(_ expr: Expr, hval: Expr, bucket: Expr) throws -> Expr { guard case .table(let map) = expr else { throw RuntimeError.type(expr, expected: [.tableType]) } map.replace(try self.bucket(hval, map.bucketCount), bucket) return .void } public override func release() { super.release() self.bucketsProc = nil self.bucketAddProc = nil self.bucketDelProc = nil self.equalProc = nil self.eqvProc = nil self.eqProc = nil } }
7332c3dd0291237e116f63450e2b7067
38.542484
100
0.626736
false
false
false
false
mdab121/swift-fcm
refs/heads/master
Sources/FCM/Firebase.swift
mit
1
// (c) 2017 Kajetan Michal Dabrowski // This code is licensed under MIT license (see LICENSE for details) import Foundation /// This is the main class that you should be using to send notifications public class Firebase { /// Set this to true if you want your requests to be performed in the background. /// Defaults to false, since I don't think it's been tested enough /// Please do not change this after pushing notifications internal var backgroundMode: Bool = false /// The server key internal let serverKey: ServerKey private let serializer: MessageSerializer = MessageSerializer() private let pushUrl: URL = URL(string: "https://fcm.googleapis.com/fcm/send")! private let requestAdapter: RequestAdapting = RequestAdapterCurl() private lazy var backgroundQueue = OperationQueue() private var requestQueue: OperationQueue { return backgroundMode ? backgroundQueue : (OperationQueue.current ?? OperationQueue.main) } /// Convenience initializer taking a path to a file where the key is stored. /// /// - Parameter keyPath: Path to the Firebase Server Key /// - Throws: Throws an error if file doesn't exist public convenience init(keyPath: String) throws { let fileManager = FileManager() guard let keyData = fileManager.contents(atPath: keyPath), let keyString = String(data: keyData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) else { throw FirebaseError.invalidServerKey } self.init(serverKey: ServerKey(rawValue: keyString)) } /// Initializes FCM with the key as the parameter. Please note that you should NOT store your server key in the source code and in your repository. /// Instead, fetch your key from some configuration files, that are not stored in your repository. /// /// - Parameter serverKey: server key public init(serverKey: ServerKey) { self.serverKey = serverKey } /// Sends a single message to a single device. After sending it calls the completion closure on the queue that it was called from. /// /// - Parameters: /// - message: The message that you want to send /// - deviceToken: Firebase Device Token that you want to send your message to /// - completion: completion closure /// - Throws: Serialization error when the message could not be serialized public func send(message: Message, to deviceToken: DeviceToken, completion: @escaping (FirebaseResponse) -> Void) throws { let requestBytes: [UInt8] = try serializer.serialize(message: message, device: deviceToken) let requestData = Data(requestBytes) let requestHeaders = generateHeaders() let url = pushUrl let completionQueue = OperationQueue.current ?? OperationQueue.main let requestAdapter = self.requestAdapter requestQueue.addOperation { do { try requestAdapter.send(data: requestData, headers: requestHeaders, url: url) { (data, statusCode, error) in let response = FirebaseResponse(data: data, statusCode: statusCode, error: error) completionQueue.addOperation { completion(response) } } } catch { let response = FirebaseResponse(data: nil, statusCode: nil, error: error) completionQueue.addOperation { completion(response) } } } } // MARK: Private methods private func generateHeaders() -> [String: String] { return [ "Content-Type": "application/json", "Authorization": "key=\(serverKey.rawValue)" ] } }
0961ccebadc9e961c7bc4abd71b71430
38.482353
148
0.739869
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
refs/heads/master
Parse Dashboard for iOS/ViewControllers/Core/Object/ObjectBuilderViewController.swift
mit
1
// // ObjectBuilderViewController.swift // Parse Dashboard for iOS // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 12/17/17. // import UIKit import AlertHUDKit import Former import SwiftyJSON class ObjectBuilderViewController: FormViewController { // MARK: - Properties override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } private var body = JSON() private let schema: PFSchema private lazy var formerInputAccessoryView = FormerInputAccessoryView(former: self.former) lazy var moreSection: SectionFormer = { let addFieldRow = LabelRowFormer<FormLabelCell>() { $0.titleLabel.font = .boldSystemFont(ofSize: 15) $0.titleLabel.textColor = .logoTint }.configure { $0.text = "Add Field" }.onSelected { [weak self] _ in self?.former.deselect(animated: true) self?.addField() } return SectionFormer(rowFormer: addFieldRow) }() // MARK: - Initialization init(for schema: PFSchema) { self.schema = schema super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() setupTableView() setupNavigationBar() buildForm() } // MARK: - View Setup private func setupTableView() { tableView.contentInset.top = 10 tableView.contentInset.bottom = 80 } private func setupNavigationBar() { title = "New \(schema.name) Object" navigationController?.navigationBar.barTintColor = .darkPurpleBackground navigationController?.navigationBar.tintColor = .white navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 15), NSAttributedStringKey.foregroundColor : UIColor.white ] navigationItem.backBarButtonItem = UIBarButtonItem(title: Localizable.cancel.localized, style: .plain, target: nil, action: nil) navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelCreation)) navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "Save"), style: .plain, target: self, action: #selector(saveNewObject)) } private func buildForm() { let currentFields = schema.editableFields().map { return createRow(for: $0) } let bodySection = SectionFormer(rowFormers: currentFields) former .append(sectionFormer: bodySection, moreSection) .onCellSelected { [weak self] _ in self?.formerInputAccessoryView.update() } } private func addField() { let types: [String] = ["Select One", .string, .boolean, .number, .date, .pointer, .array, .file] let fieldNameRow = TextFieldRowFormer<FormerFieldCell>(instantiateType: .Nib(nibName: "FormerFieldCell")) { [weak self] in $0.titleLabel.text = "Field Name" $0.textField.textAlignment = .right $0.textField.inputAccessoryView = self?.formerInputAccessoryView }.configure { $0.placeholder = "ex. Foo" } let pointerClassRow = TextFieldRowFormer<FormerFieldCell>(instantiateType: .Nib(nibName: "FormerFieldCell")) { [weak self] in $0.titleLabel.text = "Target Class" $0.textField.textAlignment = .right $0.textField.inputAccessoryView = self?.formerInputAccessoryView }.configure { $0.placeholder = "ex. _User" } let dataTypePickerRow = InlinePickerRowFormer<FormInlinePickerCell, Any>() { $0.titleLabel.text = "Data Type" $0.titleLabel.font = .boldSystemFont(ofSize: 15) $0.displayLabel.textColor = .darkGray }.configure { $0.pickerItems = types.map { return InlinePickerItem(title: $0) } }.onValueChanged { [weak self] item in if item.title == .pointer { self?.former.insertUpdate(rowFormer: pointerClassRow, below: fieldNameRow, rowAnimation: .fade) } else { self?.former.removeUpdate(rowFormer: pointerClassRow, rowAnimation: .fade) } } let addRow = LabelRowFormer<FormLabelCell>() { $0.titleLabel.font = .boldSystemFont(ofSize: 15) $0.titleLabel.textAlignment = .center $0.titleLabel.textColor = .logoTint }.configure { $0.text = "Add" }.onSelected { [weak self] _ in self?.former.deselect(animated: true) guard let className = self?.schema.name else { return } guard let fieldName = fieldNameRow.text, !fieldName.isEmpty else { self?.handleError("Empty Field Name") return } guard dataTypePickerRow.selectedRow > 0 else { self?.handleError("Please Select a Data Type") return } let dataType = types[dataTypePickerRow.selectedRow] var newField = JSON() newField.dictionaryObject?["className"] = className if dataType == .pointer { guard let targetClass = pointerClassRow.text else { self?.handleError("Empty Target Class") return } newField.dictionaryObject?["fields"] = [ fieldName : ["type":dataType, "targetClass":targetClass] ] } else { newField.dictionaryObject?["fields"] = [fieldName : ["type":dataType]] } do { let data = try newField.rawData() ParseLite.shared.put("/schemas/" + className, data: data, completion: { (result, json) in guard result.success, let json = json else { self?.handleError(result.error) return } let updatedSchema = PFSchema(json) let index = (self?.schema.editableFields().count ?? 0) > 0 ? 1 : 0 self?.schema.fields?[fieldName] = updatedSchema.fields?[fieldName] self?.handleSuccess("Class Updated") if let newRow = self?.createRow(for: fieldName), let sectionToDelete = self?.former.sectionFormers[index] { let numberOfRows = self?.former.sectionFormers.first?.numberOfRows ?? 0 let row = index == 1 ? numberOfRows : 0 // Accounts for there being no initial fields let indexPath = IndexPath(row: row, section: 0) self?.former .removeUpdate(sectionFormer: sectionToDelete, rowAnimation: .fade) .insertUpdate(rowFormer: newRow, toIndexPath: indexPath, rowAnimation: .fade) .insertUpdate(sectionFormer: self!.moreSection, toSection: 1, rowAnimation: .fade) } else { self?.handleError(nil) } }) } catch let error { self?.handleError(error.localizedDescription) } } let section = SectionFormer(rowFormer: fieldNameRow, dataTypePickerRow, addRow) let index = schema.editableFields().count > 0 ? 1 : 0 // Accounts for there being no initial fields former .removeUpdate(sectionFormer: moreSection, rowAnimation: .fade) .insertUpdate(sectionFormer: section, toSection: index, rowAnimation: .fade) .onCellSelected { [weak self] _ in self?.formerInputAccessoryView.update() } } private func createRow(for field: String) -> RowFormer { let type = schema.typeForField(field) ?? String.string switch type { case .string: return TextFieldRowFormer<FormerFieldCell>(instantiateType: .Nib(nibName: "FormerFieldCell")) { [weak self] in $0.titleLabel.text = field $0.textField.textAlignment = .right $0.textField.inputAccessoryView = self?.formerInputAccessoryView }.configure { $0.placeholder = type }.onTextChanged { [weak self] newValue in // Update self?.body.dictionaryObject?[field] = newValue } case .file: return LabelRowFormer<FormLabelCell>() { $0.titleLabel.font = .boldSystemFont(ofSize: 15) $0.accessoryType = .disclosureIndicator }.configure { $0.text = field $0.subText = type }.onSelected { [weak self] _ in self?.former.deselect(animated: true) self?.handleError("Sorry, files can only be uploaded after objects creation.") } case .boolean: return SwitchRowFormer<FormSwitchCell>() { $0.titleLabel.text = field $0.titleLabel.font = .boldSystemFont(ofSize: 15) $0.switchButton.onTintColor = .logoTint }.configure { $0.switched = false }.onSwitchChanged { [weak self] newValue in // Update self?.body.dictionaryObject?[field] = newValue } case .number: return TextFieldRowFormer<FormerFieldCell>(instantiateType: .Nib(nibName: "FormerFieldCell")) { [weak self] in $0.titleLabel.text = field $0.textField.keyboardType = .numbersAndPunctuation $0.textField.textAlignment = .right $0.textField.inputAccessoryView = self?.formerInputAccessoryView }.configure { $0.placeholder = type }.onTextChanged { [weak self] newValue in // Update let numberValue = Double(newValue) self?.body.dictionaryObject?[field] = numberValue } case .date: return InlineDatePickerRowFormer<FormInlineDatePickerCell>() { $0.titleLabel.text = field $0.titleLabel.font = .boldSystemFont(ofSize: 15) $0.displayLabel.textColor = .darkGray $0.displayLabel.font = .systemFont(ofSize: 15) }.inlineCellSetup { $0.detailTextLabel?.text = type $0.datePicker.datePickerMode = .dateAndTime }.onDateChanged { [weak self] newValue in // Update self?.body.dictionaryObject?[field] = [ "__type" : "Date", "iso" : newValue.stringify() ] }.displayTextFromDate { date in return date.string(dateStyle: .medium, timeStyle: .short) } case .pointer: let targetClass = (schema.fields?[field] as? [String:AnyObject])?["targetClass"] as? String return LabelRowFormer<FormLabelCell>() { $0.titleLabel.font = .boldSystemFont(ofSize: 15) $0.accessoryType = .disclosureIndicator }.configure { $0.text = field $0.subText = targetClass }.onUpdate { [weak self] in let pointer = self?.body.dictionaryObject?[field] as? [String:AnyObject] $0.subText = pointer?[.objectId] as? String ?? targetClass }.onSelected { [weak self] _ in self?.former.deselect(animated: true) guard let targetClass = targetClass else { return } ParseLite.shared.get("/schemas/" + targetClass, completion: { [weak self] (result, json) in guard result.success, let schemaJSON = json else { self?.handleError(result.error) return } let schema = PFSchema(schemaJSON) let selectionController = ObjectSelectorViewController(selecting: field, in: schema) selectionController.delegate = self self?.navigationController?.pushViewController(selectionController, animated: true) }) } case .object, .array: return TextViewRowFormer<FormTextViewCell> { [weak self] in $0.titleLabel.text = field $0.titleLabel.font = .boldSystemFont(ofSize: 15) $0.textView.inputAccessoryView = self?.formerInputAccessoryView }.configure { $0.placeholder = type }.onTextChanged { [weak self] newValue in // Update let arrayValue = JSON(arrayLiteral: newValue) self?.body.dictionaryObject?[field] = arrayValue } case .relation: return LabelRowFormer<FormLabelCell>() { $0.titleLabel.font = .boldSystemFont(ofSize: 15) $0.accessoryType = .disclosureIndicator }.configure { $0.text = field $0.subText = type }.onSelected { [weak self] _ in self?.former.deselect(animated: true) self?.handleError("Sorry, relations cannot be added via Parse Server's REST API") } default: return TextFieldRowFormer<FormerFieldCell>(instantiateType: .Nib(nibName: "FormerFieldCell")) { [weak self] in $0.titleLabel.text = field $0.textField.textAlignment = .right $0.textField.inputAccessoryView = self?.formerInputAccessoryView }.configure { $0.placeholder = type }.onTextChanged { [weak self] newValue in // Update self?.body.dictionaryObject?[field] = newValue } } } // MARK: - Error Handling func handleError(_ error: String?) { let error = error ?? Localizable.unknownError.localized Ping(text: error, style: .danger).show() } func handleSuccess(_ message: String?) { let message = message?.capitalized ?? Localizable.success.localized Ping(text: message, style: .success).show() } // MARK: - User Actions @objc func cancelCreation() { dismiss(animated: true, completion: nil) } @objc func saveNewObject() { do { let data = try body.rawData() ParseLite.shared.post("/classes/" + schema.name, data: data, completion: { [weak self] (result, json) in guard result.success, let json = json else { self?.handleError(result.error) return } let newObject = ParseLiteObject(json) self?.handleSuccess("Object \(newObject.id) Created") self?.dismiss(animated: true, completion: nil) }) } catch let error { Ping(text: error.localizedDescription, style: .danger).show() } } } extension ObjectBuilderViewController: ObjectSelectorViewControllerDelegate { func objectSelector(_ viewController: ObjectSelectorViewController, didSelect object: ParseLiteObject, for key: String) { guard let type = schema.typeForField(key) else { handleError("Unknown type for selected field") return } switch type { case .pointer: body.dictionaryObject?[key] = [ "__type" : "Pointer", "objectId" : object.id, "className" : object.schema?.name ] guard let index = schema.editableFields().index(of: key) else { return } former.reload(indexPaths: [IndexPath(row: index, section: 0)]) viewController.navigationController?.popViewController(animated: true) default: handleError("Type `Pointer` cannot be assigned to field `\(key)`") } } }
51dbf6d06fe5d5aa3507d078624cfc84
43.421801
136
0.537981
false
false
false
false
tavon321/FoodApp
refs/heads/master
FoodApp/FoodApp/Menu.swift
mit
1
// // Menu.swift // TODO // // Created by Luis F Ruiz Arroyave on 10/23/16. // Copyright © 2016 UdeM. All rights reserved. // import Foundation class Menu: NSObject, NSCoding { //MARK: - Properties var _id: String var restaurant: String var name: String var price: String var image: String //MARK: - Init //Designated Initializer init(_id: String, restaurant:String, name:String, price:String,image:String) { self._id = _id self.restaurant = restaurant self.name = name self.price = price self.image = price super.init() } required convenience init(coder aDecoder: NSCoder) { let _id = aDecoder.decodeObjectForKey("_id") as! String let restaurant = aDecoder.decodeObjectForKey("restaurant") as! String let name = aDecoder.decodeObjectForKey("name") as! String let price = aDecoder.decodeObjectForKey("price") as! String let image = aDecoder.decodeObjectForKey("image") as! String self.init(_id: _id, restaurant:restaurant, name:name, price:price,image: image) } //Convenience Initializer convenience override init() { self.init(_id: "", restaurant:"" ,name:"", price:"",image:"") } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(_id, forKey: "_id") aCoder.encodeObject(name, forKey: "restaurant") aCoder.encodeObject(name, forKey: "name") aCoder.encodeObject(price, forKey: "price") aCoder.encodeObject(price, forKey: "image") } // static func save(tasks:[Task]) { // let data = NSKeyedArchiver.archivedDataWithRootObject(tasks) // NSUserDefaults.standardUserDefaults().setObject(data, forKey: "Tasks") // } class func menus() -> [Menu] { var menus = [Menu]() if let data = NSUserDefaults.standardUserDefaults().objectForKey("Menus") as? NSData { if let objectTasks = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Menu] { menus = objectTasks } } return menus } static func menus(completionHandler: CompletionHandler){ Services.menus { (success, response) in if success { var menus = [Menu]() for(_, value) in response { // response = [String: AnyObject] let array = value as! NSArray for itemMenu in array { let menu = Menu() let dictMenu = itemMenu as! NSDictionary // itemTask representa una tarea for(keyMenu, valueMenu) in dictMenu{ if menu.respondsToSelector(NSSelectorFromString(keyMenu as! String)) { menu.setValue(valueMenu, forKey: keyMenu as! String) //KVC key value Coding Key-value coding is a mechanism for accessing an object’s properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables. } } menus.append(menu) } } completionHandler(success:success, response: ["menus":menus]) }else { completionHandler(success: success, response: response) } } } }
210116f4b21445c836ab80c399e53d50
33.346154
334
0.566349
false
false
false
false
zuoya0820/DouYuZB
refs/heads/master
DouYuZB/DouYuZB/Classes/Main/View/CollectionBaseCell.swift
mit
1
// // CollectionBaseCell.swift // DouYuZB // // Created by zuoya on 2017/10/22. // Copyright © 2017年 zuoya. All rights reserved. // import UIKit import Kingfisher class CollectionBaseCell: UICollectionViewCell { @IBOutlet weak var nicknameLabel: UILabel! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var onlineBtn: UIButton! var anchor : AnchorModel? { didSet { // 0.校验模型是否有值 guard let anchor = anchor else { return } // 1.取出在线人数显示的文字 var onlineStr : String = "" if anchor.online >= 10000 { onlineStr = "\(Int(anchor.online / 10000))万在线" } else { onlineStr = "\(Int(anchor.online))在线" } onlineBtn.setTitle(onlineStr, for: .normal) // 2.昵称的显示 nicknameLabel.text = anchor.nickname // 3.设置封面图片 guard let iconURL : URL = URL(string : anchor.vertical_src) else { return } iconImageView.kf.setImage(with: ImageResource.init(downloadURL: iconURL)) } } }
50cd338a69c4e784cdce60dea5a2c849
26.022727
87
0.535744
false
false
false
false
gouyz/GYZBaking
refs/heads/master
baking/Classes/Tool/comView/GYZLoadingView.swift
mit
1
// // GYZLoadingView.swift // LazyHuiSellers // 加载动画loading // Created by gouyz on 2016/12/22. // Copyright © 2016年 gouyz. All rights reserved. // import UIKit class GYZLoadingView: UIView { // MARK: 生命周期方法 override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func setupUI(){ addSubview(desLab) addSubview(loadView) loadView.snp.makeConstraints { (make) in make.center.equalTo(self) make.size.equalTo(CGSize.init(width: 40, height: 40)) } desLab.snp.makeConstraints { (make) in make.left.equalTo(loadView.snp.right) make.centerY.equalTo(self) make.height.equalTo(loadView) make.width.equalTo(100) } } /// 描述 lazy var desLab : UILabel = { let lab = UILabel() lab.font = k14Font lab.textColor = kHeightGaryFontColor lab.text = "正在加载..." return lab }() /// 菊花动画 lazy var loadView : UIActivityIndicatorView = { let indView = UIActivityIndicatorView.init(activityIndicatorStyle: .gray) return indView }() /// 开始动画 func startAnimating(){ loadView.startAnimating() } }
7775900b25d4576cc743fd843c24a524
22.932203
81
0.573654
false
false
false
false
atsumo/swift-tutorial
refs/heads/master
StopWatch/StopWatch/ViewController.swift
mit
1
// // ViewController.swift // StopWatch // // Created by atsumo on 9/25/15. // Copyright © 2015 atsumo. All rights reserved. // import UIKit class ViewController: UIViewController { var _count = 0 var _isRunning = false var _timer = NSTimer() @IBOutlet weak var label: UILabel! @IBAction func start(sender: UIButton) { if _isRunning == true { return } _timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("update"), userInfo: nil, repeats: true) _isRunning = true } @IBAction func stop(sender: UIButton) { if _isRunning == false { return } _timer.invalidate() _isRunning = false } @IBAction func reset(sender: UIButton) { _count = 0 label.text = "\(format(0))" } func update() { _count++ label.text = "\(format(_count))" } func format(count:Int) -> String { let ms = count % 100 let s = (count - ms) / 100 % 60 let m = (count - s - ms) / 6000 % 3600 return String(format: "%02d:%02d:%02d", m, s, ms) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
d16d4ea284a2df6fb079ae396602f2ef
21.61194
135
0.550495
false
false
false
false
qingtianbuyu/Mono
refs/heads/master
Moon/Classes/Main/Other/MNBackNavgationController.swift
mit
1
// // MNBackNavgationController.swift // Moon // // Created by YKing on 16/6/24. // Copyright © 2016年 YKing. All rights reserved. // import UIKit class MNBackNavgationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() interactivePopGestureRecognizer?.delegate = nil } override func pushViewController(_ viewController: UIViewController, animated: Bool) { viewController.navigationItem.hidesBackButton = true if childViewControllers.count > 0 { viewController.hidesBottomBarWhenPushed = true let button = UIButton(type:UIButtonType.custom); button.setBackgroundImage(UIImage(named: "icon-update-arrow-left-black"), for: UIControlState.normal) button.setBackgroundImage(UIImage(named: "icon-update-arrow-left-black"), for: UIControlState.highlighted) button.frame = CGRect(x:0, y:0, width:button.currentBackgroundImage!.size.width, height:button.currentBackgroundImage!.size.height) button.addTarget(self, action: #selector(MNBackNavgationController.back), for: UIControlEvents.touchUpInside) viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button) } super.pushViewController(viewController, animated: animated) } func back() { self.popViewController(animated: true) } }
ee989862371e21d2974cb27f51424606
33.461538
137
0.747024
false
false
false
false
jdspoone/Recipinator
refs/heads/master
RecipeBook/IngredientAmountToIngredientAmountPolicy.swift
mit
1
/* Written by Jeff Spooner Custom migration policy for IngredientAmount instances */ import CoreData class IngredientAmountToIngredientAmountPolicy: NSEntityMigrationPolicy { override func createRelationships(forDestination destinationInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws { // Get the user info dictionary let userInfo = mapping.userInfo! // Get the source version let sourceVersion = userInfo["sourceVersion"] as? String // If a source version was specified if let sourceVersion = sourceVersion { // Get the source note let sourceIngredientAmount = manager.sourceInstances(forEntityMappingName: mapping.name, destinationInstances: [destinationInstance]).first! // Get the source note's relationship keys and values let sourceRelationshipKeys = Array(sourceIngredientAmount.entity.relationshipsByName.keys) let sourceRelationshipValues = sourceIngredientAmount.dictionaryWithValues(forKeys: sourceRelationshipKeys) // Switch on the source version switch sourceVersion { // Migrating from v1.2 to v1.3 case "v1.2": // Get the source instance's incorrectly named recipesUsedIn relationship let sourceRecipe = sourceRelationshipValues["recipesUsedIn"] as! NSManagedObject // Get the corresponding destination recipe let destinationRecipe = manager.destinationInstances(forEntityMappingName: "RecipeToRecipe", sourceInstances: [sourceRecipe]).first! // Set the destination instance's recipeUsedIn relationship destinationInstance.setValue(destinationRecipe, forKey: "recipeUsedIn") default: break } } } }
45330a9b49619b9465cdd93c0270330e
32.981818
155
0.691279
false
false
false
false
qvacua/vimr
refs/heads/master
VimR/VimR/KeysPref.swift
mit
1
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import PureLayout import RxSwift final class KeysPref: PrefPane, UiComponent, NSTextFieldDelegate { typealias StateType = AppState enum Action { case isLeftOptionMeta(Bool) case isRightOptionMeta(Bool) } override var displayName: String { "Keys" } override var pinToContainer: Bool { true } required init(source: Observable<StateType>, emitter: ActionEmitter, state: StateType) { self.emit = emitter.typedEmit() self.isLeftOptionMeta = state.mainWindowTemplate.isLeftOptionMeta self.isRightOptionMeta = state.mainWindowTemplate.isRightOptionMeta super.init(frame: .zero) self.addViews() self.updateViews() source .observe(on: MainScheduler.instance) .subscribe(onNext: { state in if self.isLeftOptionMeta != state.mainWindowTemplate.isLeftOptionMeta || self.isRightOptionMeta != state.mainWindowTemplate.isRightOptionMeta { self.isLeftOptionMeta = state.mainWindowTemplate.isLeftOptionMeta self.isRightOptionMeta = state.mainWindowTemplate.isRightOptionMeta self.updateViews() } }) .disposed(by: self.disposeBag) } private let emit: (Action) -> Void private let disposeBag = DisposeBag() private var isLeftOptionMeta: Bool private var isRightOptionMeta: Bool private let isLeftOptionMetaCheckbox = NSButton(forAutoLayout: ()) private let isRightOptionMetaCheckbox = NSButton(forAutoLayout: ()) @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } private func updateViews() { self.isLeftOptionMetaCheckbox.boolState = self.isLeftOptionMeta self.isRightOptionMetaCheckbox.boolState = self.isRightOptionMeta } private func addViews() { let paneTitle = self.paneTitleTextField(title: "Keys") let isLeftOptionMeta = self.isLeftOptionMetaCheckbox self.configureCheckbox( button: isLeftOptionMeta, title: "Use Left Option as Meta", action: #selector(KeysPref.isLeftOptionMetaAction(_:)) ) let isRightOptionMeta = self.isRightOptionMetaCheckbox self.configureCheckbox( button: isRightOptionMeta, title: "Use Right Option as Meta", action: #selector(KeysPref.isRightOptionMetaAction(_:)) ) let metaInfo = self.infoTextField(markdown: #""" When an Option key is set to Meta, then every input containing the corresponding Option key will\ be passed through to Neovim. This means that you can use mappings like `<M-1>` in Neovim, but\ cannot use the corresponding Option key for keyboard shortcuts containing `Option` or to enter\ special characters like `µ` which is entered by `Option-M` (on the ABC keyboard layout). """#) self.addSubview(paneTitle) self.addSubview(isLeftOptionMeta) self.addSubview(isRightOptionMeta) self.addSubview(metaInfo) paneTitle.autoPinEdge(toSuperviewEdge: .top, withInset: 18) paneTitle.autoPinEdge(toSuperviewEdge: .left, withInset: 18) paneTitle.autoPinEdge(toSuperviewEdge: .right, withInset: 18, relation: .greaterThanOrEqual) isLeftOptionMeta.autoPinEdge(.top, to: .bottom, of: paneTitle, withOffset: 18) isLeftOptionMeta.autoPinEdge(toSuperviewEdge: .left, withInset: 18) isRightOptionMeta.autoPinEdge(.top, to: .bottom, of: isLeftOptionMeta, withOffset: 5) isRightOptionMeta.autoPinEdge(toSuperviewEdge: .left, withInset: 18) metaInfo.autoPinEdge(.top, to: .bottom, of: isRightOptionMeta, withOffset: 5) metaInfo.autoPinEdge(toSuperviewEdge: .left, withInset: 18) } } // MARK: - Actions extension KeysPref { @objc func isLeftOptionMetaAction(_ sender: NSButton) { self.emit(.isLeftOptionMeta(sender.boolState)) } @objc func isRightOptionMetaAction(_ sender: NSButton) { self.emit(.isRightOptionMeta(sender.boolState)) } }
5224435e03105571dbe402f9379fc5d1
30.47619
101
0.725164
false
false
false
false
jovito-royeca/Decktracker
refs/heads/master
osx/DataSource/DataSource/Ruling.swift
apache-2.0
1
// // Ruling.swift // DataSource // // Created by Jovit Royeca on 29/06/2016. // Copyright © 2016 Jovito Royeca. All rights reserved. // import Foundation import CoreData class Ruling: NSManagedObject { struct Keys { static let Text = "text" static let Date = "date" } override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } init(dictionary: [String : AnyObject], context: NSManagedObjectContext) { let entity = NSEntityDescription.entityForName("Ruling", inManagedObjectContext: context)! super.init(entity: entity,insertIntoManagedObjectContext: context) update(dictionary) } func update(dictionary: [String : AnyObject]) { text = dictionary[Keys.Text] as? String if let d = dictionary[Keys.Date] as? String { let formatter = NSDateFormatter() formatter.dateFormat = "YYYY-MM-dd" date = formatter.dateFromString(d) } } var yearKeyPath: String? { if let date = date { let formatter = NSDateFormatter() formatter.dateFormat = "YYYY" return formatter.stringFromDate(date) } return nil } }
4304f841e1a92dede874ee40a1d6a067
26.156863
113
0.620217
false
false
false
false
mattermost/mattermost-mobile
refs/heads/main
ios/Gekidou/Sources/Gekidou/Networking/ShareExtension.swift
apache-2.0
1
// // File.swift // // // Created by Elias Nahum on 26-06-22. // import Foundation import os.log struct UploadSessionData { var serverUrl: String? var channelId: String? var files: [String] = [] var fileIds: [String] = [] var message: String = "" var totalFiles: Int = 0 func toDictionary() -> NSDictionary { let data: NSDictionary = [ "serverUrl": serverUrl as Any, "channelId": channelId as Any, "files": files, "fileIds": fileIds, "message": message, "totalFiles": totalFiles ] return data } func fromDictionary(dict: NSDictionary) -> UploadSessionData { let serverUrl = dict["serverUrl"] as! String let channelId = dict["channelId"] as! String let files = dict["files"] as! [String] let fileIds = dict["fileIds"] as! [String] let message = dict["message"] as! String let totalFiles = dict["totalFiles"] as! Int return UploadSessionData( serverUrl: serverUrl, channelId: channelId, files: files, fileIds: fileIds, message: message, totalFiles: totalFiles ) } } public class ShareExtension: NSObject { public var backgroundSession: URLSession? private var cacheURL: URL? private let fileMgr = FileManager.default private let preferences = Preferences.default public var completionHandler: (() -> Void)? public override init() { super.init() if let groupId = appGroupId, let containerUrl = fileMgr.containerURL(forSecurityApplicationGroupIdentifier: groupId), let url = containerUrl.appendingPathComponent("Library", isDirectory: true) as URL?, let cache = url.appendingPathComponent("Cache", isDirectory: true) as URL? { self.cacheURL = cache self.createCacheDirectoryIfNeeded() } } private func createCacheDirectoryIfNeeded() { var isDirectory = ObjCBool(false) if let cachePath = cacheURL?.path { let exists = FileManager.default.fileExists(atPath: cachePath, isDirectory: &isDirectory) if !exists && !isDirectory.boolValue { try? FileManager.default.createDirectory(atPath: cachePath, withIntermediateDirectories: true, attributes: nil) } } } func saveUploadSessionData(id: String, data: UploadSessionData) { preferences.set(data.toDictionary(), forKey: id) os_log( OSLogType.default, "Mattermost BackgroundSession: saveUploadSessionData for identifier=%{public}@", id ) } func createUploadSessionData(id: String, serverUrl: String, channelId: String, message: String, files: [String]) { let data = UploadSessionData( serverUrl: serverUrl, channelId: channelId, files: files, message: message, totalFiles: files.count ) saveUploadSessionData(id: id, data: data) } func getUploadSessionData(id: String) -> UploadSessionData? { if let data = preferences.object(forKey: id) as? NSDictionary { return UploadSessionData().fromDictionary(dict: data) } return nil } func removeUploadSessionData(id: String) { preferences.removeObject(forKey: id) os_log( OSLogType.default, "Mattermost BackgroundSession: removeUploadSessionData for identifier=%{public}@", id ) } func appendCompletedUploadToSession(id: String, fileId: String) { if let data = getUploadSessionData(id: id) { var fileIds = data.fileIds fileIds.append(fileId) let newData = UploadSessionData( serverUrl: data.serverUrl, channelId: data.channelId, files: data.files, fileIds: fileIds, message: data.message, totalFiles: data.totalFiles ) saveUploadSessionData(id: id, data: newData) } } func deleteUploadedFiles(files: [String]) { for file in files { do { try fileMgr.removeItem(atPath: file) } catch { os_log( OSLogType.default, "Mattermost BackgroundSession: deleteUploadedFiles filed to delete=%{public}@", file ) } } } }
1fbec4cea192696b4e9721152678b143
30.378378
121
0.576012
false
false
false
false
Why51982/SLDouYu
refs/heads/master
SLDouYu/SLDouYu/Classes/Home/Controller/SLRecommendViewController.swift
mit
1
// // SLRecommendViewController.swift // SLDouYu // // Created by CHEUNGYuk Hang Raymond on 2016/10/26. // Copyright © 2016年 CHEUNGYuk Hang Raymond. All rights reserved. // import UIKit //MARK: - 定义常量 private let kItemMargin: CGFloat = 10 private let kItemW: CGFloat = (kScreenW - 3 * kItemMargin) / 2 private let kNormalItemH: CGFloat = kItemW * 3 / 4 private let kPrettyItemH: CGFloat = kItemW * 4 / 3 private let kHeaderViewH: CGFloat = 50 private let kCycleViewH: CGFloat = kScreenW * 3 / 8 private let kGameViewH: CGFloat = 90 private let kNormalCellReuseIdentifier = "kNormalCellReuseIdentifier" private let kPrettyCellReuseIdentifier = "kPrettyCellReuseIdentifier" private let kHeaderViewReuseIdentifier = "kHeaderViewReuseIdentifier" class SLRecommendViewController: SLBaseAnchorViewController { //MARK: - 懒加载 /// 网络请求的VM fileprivate lazy var recommendVM: SLRecommendViewModel = SLRecommendViewModel() /// 创建cycleView fileprivate lazy var cycleView: SLRecommendCycleView = { let cycleView = SLRecommendCycleView.recommendCycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH) return cycleView }() /// 创建推荐游戏界面 fileprivate lazy var gameView: SLRecommendGameView = { let gameView = SLRecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() } //MARK: - 设置UI界面内容 extension SLRecommendViewController { //设置UI界面 override func setupUI() { super.setupUI() //将cycleView添加到collectionView上 //注意要清空cycle的autoresizingMask,防止其随着父控件的拉升而拉升,造成看不见 collectionView.addSubview(cycleView) //添加gameView collectionView.addSubview(gameView) //调整collectionView的内边距,使cycleView显示出来 collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0) } } //MARK: - 请求网络数据 extension SLRecommendViewController { //请求推荐网络数据 override func loadData() { //给父类的ViewModel赋值 baseVM = recommendVM //发送轮播的网络请求 loadCycleData() recommendVM.requestData { //刷新表格 self.collectionView.reloadData() //取出数据 var groups = self.recommendVM.anchorGroups //去除前两组数据 groups.remove(at: 0) groups.remove(at: 0) //拼接更多一组 let moreGroup = SLAnchorGroup() moreGroup.tag_name = "更多" groups.append(moreGroup) //给GameView赋值 self.gameView.groups = groups //停止动画,并显示collectionView self.loadDataFinished() } } //请求轮播图的网络数据 fileprivate func loadCycleData() { recommendVM.requestCycleData { self.cycleView.cycleModels = self.recommendVM.cycleModels } } } //MARK: - UICollectionViewDataSource extension SLRecommendViewController: UICollectionViewDelegateFlowLayout { //UICollectionViewDelegateFlowLayout - 定义item的大小 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { //如果为颜值组(第一组),修改尺寸 if indexPath.section == 1 { return CGSize(width: kItemW, height: kPrettyItemH) } return CGSize(width: kItemW, height: kNormalItemH) } }
4a1e22641947584cdf5e135f60bc2e99
28.601626
160
0.642955
false
false
false
false
Pacific3/PFoundation
refs/heads/master
PFoundation/Error.swift
mit
1
public let ErrorDomain = "net.Pacific3.ErrorDomainSpecification" public protocol ErrorConvertible { associatedtype Code associatedtype Description associatedtype Domain var code: Code { get } var errorDescription: Description { get } var domain: Domain { get } } public enum Error: ErrorConvertible { case Error(Int, String) case None public var code: Int { return getCode() } public var errorDescription: String { return getErrorDescription() } public var domain: String { return ErrorDomain } func getCode() -> Int { switch self { case let .Error(c, _): return c case .None: return -1001 } } func getErrorDescription() -> String { switch self { case let .Error(_, d): return d case .None: return "Malformed error." } } } public struct ErrorSpecification<CodeType, DescriptionType, DomainType>: ErrorConvertible { var _code: CodeType var _desc: DescriptionType var _domain: DomainType public var code: CodeType { return _code } public var errorDescription: DescriptionType { return _desc } public var domain: DomainType { return _domain } public init<E: ErrorConvertible where E.Code == CodeType, E.Description == DescriptionType, E.Domain == DomainType>(ec: E) { _code = ec.code _desc = ec.errorDescription _domain = ec.domain } }
e887fc9495c9581f167adfcd0595792d
21.388889
128
0.578784
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/WordPressTest/Classes/Stores/ActivityStoreTests.swift
gpl-2.0
1
import WordPressFlux import XCTest @testable import WordPress @testable import WordPressKit class ActivityStoreTests: XCTestCase { private var dispatcher: ActionDispatcher! private var store: ActivityStore! private var activityServiceMock: ActivityServiceRemoteMock! private var backupServiceMock: JetpackBackupServiceMock! override func setUp() { super.setUp() dispatcher = ActionDispatcher() activityServiceMock = ActivityServiceRemoteMock() backupServiceMock = JetpackBackupServiceMock() store = ActivityStore(dispatcher: dispatcher, activityServiceRemote: activityServiceMock, backupService: backupServiceMock) } override func tearDown() { dispatcher = nil store = nil super.tearDown() } // Check if refreshActivities call the service with the correct after and before date // func testRefreshActivities() { let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo") let afterDate = Date() let beforeDate = Date(timeIntervalSinceNow: 86400) let group = ["post"] dispatch(.refreshActivities(site: jetpackSiteRef, quantity: 10, afterDate: afterDate, beforeDate: beforeDate, group: group)) XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithAfterDate, afterDate) XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithBeforeDate, beforeDate) XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithGroup, group) } // Check if loadMoreActivities call the service with the correct params // func testLoadMoreActivities() { let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo") let afterDate = Date() let beforeDate = Date(timeIntervalSinceNow: 86400) let group = ["post", "user"] dispatch(.loadMoreActivities(site: jetpackSiteRef, quantity: 10, offset: 20, afterDate: afterDate, beforeDate: beforeDate, group: group)) XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithSiteID, 9) XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithCount, 10) XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithOffset, 20) XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithAfterDate, afterDate) XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithBeforeDate, beforeDate) XCTAssertEqual(activityServiceMock.getActivityForSiteCalledWithGroup, group) } // Check if loadMoreActivities keep the activies and add the new retrieved ones // func testLoadMoreActivitiesKeepTheExistent() { let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo") store.state.activities[jetpackSiteRef] = [Activity.mock()] activityServiceMock.activitiesToReturn = [Activity.mock(), Activity.mock()] activityServiceMock.hasMore = true dispatch(.loadMoreActivities(site: jetpackSiteRef, quantity: 10, offset: 20, afterDate: nil, beforeDate: nil, group: [])) XCTAssertEqual(store.state.activities[jetpackSiteRef]?.count, 3) XCTAssertTrue(store.state.hasMore) } // resetActivities remove all activities // func testResetActivities() { let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo") store.state.activities[jetpackSiteRef] = [Activity.mock()] activityServiceMock.activitiesToReturn = [Activity.mock(), Activity.mock()] activityServiceMock.hasMore = true dispatch(.resetActivities(site: jetpackSiteRef)) XCTAssertTrue(store.state.activities[jetpackSiteRef]!.isEmpty) XCTAssertFalse(store.state.fetchingActivities[jetpackSiteRef]!) XCTAssertFalse(store.state.hasMore) } // Check if loadMoreActivities keep the activies and add the new retrieved ones // func testReturnOnlyRewindableActivities() { let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo") store.state.activities[jetpackSiteRef] = [Activity.mock()] activityServiceMock.activitiesToReturn = [Activity.mock(isRewindable: true), Activity.mock()] activityServiceMock.hasMore = true store.onlyRestorableItems = true dispatch(.loadMoreActivities(site: jetpackSiteRef, quantity: 10, offset: 20, afterDate: nil, beforeDate: nil, group: [])) XCTAssertEqual(store.state.activities[jetpackSiteRef]?.filter { $0.isRewindable }.count, 1) } // refreshGroups call the service with the correct params // func testRefreshGroups() { let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo") let afterDate = Date() let beforeDate = Date(timeIntervalSinceNow: 86400) dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: afterDate, beforeDate: beforeDate)) XCTAssertEqual(activityServiceMock.getActivityGroupsForSiteCalledWithSiteID, 9) XCTAssertEqual(activityServiceMock.getActivityGroupsForSiteCalledWithAfterDate, afterDate) XCTAssertEqual(activityServiceMock.getActivityGroupsForSiteCalledWithBeforeDate, beforeDate) } // refreshGroups stores the returned groups // func testRefreshGroupsStoreGroups() { let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo") activityServiceMock.groupsToReturn = [try! ActivityGroup("post", dictionary: ["name": "Posts and Pages", "count": 5] as [String: AnyObject])] dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: nil, beforeDate: nil)) XCTAssertEqual(store.state.groups[jetpackSiteRef]?.count, 1) XCTAssertTrue(store.state.groups[jetpackSiteRef]!.contains(where: { $0.key == "post" && $0.name == "Posts and Pages" && $0.count == 5})) } // refreshGroups does not produce multiple requests // func testRefreshGroupsDoesNotProduceMultipleRequests() { let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo") dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: nil, beforeDate: nil)) dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: nil, beforeDate: nil)) XCTAssertEqual(activityServiceMock.getActivityGroupsForSiteCalledTimes, 1) } // When a previous request for Activity types has suceeded, return the cached groups // func testRefreshGroupsUseCache() { let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo") activityServiceMock.groupsToReturn = [try! ActivityGroup("post", dictionary: ["name": "Posts and Pages", "count": 5] as [String: AnyObject])] dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: nil, beforeDate: nil)) dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: nil, beforeDate: nil)) XCTAssertEqual(activityServiceMock.getActivityGroupsForSiteCalledTimes, 1) XCTAssertTrue(store.state.groups[jetpackSiteRef]!.contains(where: { $0.key == "post" && $0.name == "Posts and Pages" && $0.count == 5})) } // Request groups endpoint again if the cache expired // func testRefreshGroupsRequestsAgainIfTheFirstSucceeds() { let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo") activityServiceMock.groupsToReturn = [try! ActivityGroup("post", dictionary: ["name": "Posts and Pages", "count": 5] as [String: AnyObject])] dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: nil, beforeDate: nil)) dispatch(.resetGroups(site: jetpackSiteRef)) dispatch(.refreshGroups(site: jetpackSiteRef, afterDate: Date(), beforeDate: nil)) XCTAssertEqual(activityServiceMock.getActivityGroupsForSiteCalledTimes, 2) } // MARK: - Backup Status // Query for backup status call the service // func testBackupStatusQueryCallsService() { let jetpackSiteRef = JetpackSiteRef.mock(siteID: 9, username: "foo") _ = store.query(.backupStatus(site: jetpackSiteRef)) store.processQueries() XCTAssertEqual(backupServiceMock.didCallGetAllBackupStatusWithSite, jetpackSiteRef) } // MARK: - Helpers private func dispatch(_ action: ActivityAction) { dispatcher.dispatch(action) } } class ActivityServiceRemoteMock: ActivityServiceRemote { var getActivityForSiteCalledWithSiteID: Int? var getActivityForSiteCalledWithOffset: Int? var getActivityForSiteCalledWithCount: Int? var getActivityForSiteCalledWithAfterDate: Date? var getActivityForSiteCalledWithBeforeDate: Date? var getActivityForSiteCalledWithGroup: [String]? var getActivityGroupsForSiteCalledWithSiteID: Int? var getActivityGroupsForSiteCalledWithAfterDate: Date? var getActivityGroupsForSiteCalledWithBeforeDate: Date? var getActivityGroupsForSiteCalledTimes = 0 var activitiesToReturn: [Activity]? var hasMore = false var groupsToReturn: [ActivityGroup]? override func getActivityForSite(_ siteID: Int, offset: Int = 0, count: Int, after: Date? = nil, before: Date? = nil, group: [String] = [], success: @escaping (_ activities: [Activity], _ hasMore: Bool) -> Void, failure: @escaping (Error) -> Void) { getActivityForSiteCalledWithSiteID = siteID getActivityForSiteCalledWithCount = count getActivityForSiteCalledWithOffset = offset getActivityForSiteCalledWithAfterDate = after getActivityForSiteCalledWithBeforeDate = before getActivityForSiteCalledWithGroup = group if let activitiesToReturn = activitiesToReturn { success(activitiesToReturn, hasMore) } } override func getActivityGroupsForSite(_ siteID: Int, after: Date? = nil, before: Date? = nil, success: @escaping ([ActivityGroup]) -> Void, failure: @escaping (Error) -> Void) { getActivityGroupsForSiteCalledWithSiteID = siteID getActivityGroupsForSiteCalledWithAfterDate = after getActivityGroupsForSiteCalledWithBeforeDate = before getActivityGroupsForSiteCalledTimes += 1 if let groupsToReturn = groupsToReturn { success(groupsToReturn) } } override func getRewindStatus(_ siteID: Int, success: @escaping (RewindStatus) -> Void, failure: @escaping (Error) -> Void) { } } extension ActivityGroup { class func mock() -> ActivityGroup { try! ActivityGroup("post", dictionary: ["name": "Posts and Pages", "count": 5] as [String: AnyObject]) } } class JetpackBackupServiceMock: JetpackBackupService { var didCallGetAllBackupStatusWithSite: JetpackSiteRef? init() { super.init(managedObjectContext: TestContextManager.sharedInstance().mainContext) } override func getAllBackupStatus(for site: JetpackSiteRef, success: @escaping ([JetpackBackup]) -> Void, failure: @escaping (Error) -> Void) { didCallGetAllBackupStatusWithSite = site let jetpackBackup = JetpackBackup(backupPoint: Date(), downloadID: 100, rewindID: "", startedAt: Date(), progress: 10, downloadCount: 0, url: "", validUntil: nil) success([jetpackBackup]) } }
50bbe66991527ddd8533e00996162851
42.636015
182
0.703222
false
true
false
false
geekaurora/ReactiveListViewKit
refs/heads/master
Example/ReactiveListViewKitDemo/UI Layer/FeedList/HotUsers/HotUserCellCardView.swift
mit
1
// // HotUserCellView.swift // ReactiveListViewKit // // Created by Cheng Zhang on 3/4/17. // Copyright © 2017 Cheng Zhang. All rights reserved. // import CZUtils import ReactiveListViewKit class HotUserCellCardView: CZNibLoadableView, CZFeedCellViewSizeCalculatable { @IBOutlet var frameView: UIView? @IBOutlet var contentView: UIView? @IBOutlet var stackView: UIStackView? @IBOutlet var portaitView: UIImageView? @IBOutlet var nameLabel: UILabel? @IBOutlet var detailsLabel: UILabel? @IBOutlet var followButton: UIButton? @IBOutlet var closeButton: UIButton? private var viewModel: HotUserCellViewModel var diffId: String {return viewModel.diffId} var onAction: OnAction? required init(viewModel: CZFeedViewModelable?, onAction: OnAction?) { guard let viewModel = viewModel as? HotUserCellViewModel else { fatalError("Incorrect ViewModel type.") } self.viewModel = viewModel self.onAction = onAction super.init(frame: .zero) backgroundColor = .white config(with: viewModel) } required init?(coder aDecoder: NSCoder) { fatalError("Must call designated initializer `init(viewModel:onAction:)`") } func config(with viewModel: CZFeedViewModelable?) { guard let viewModel = viewModel as? HotUserCellViewModel else { fatalError("Incorrect ViewModel type.") } if let portraitUrl = viewModel.portraitUrl { portaitView?.cz_setImage(with: portraitUrl) portaitView?.roundToCircle() } detailsLabel?.text = viewModel.fullName nameLabel?.text = "" followButton?.roundCorner(2) closeButton?.roundCorner(2) frameView?.roundCorner(2) } func config(with viewModel: CZFeedViewModelable?, prevViewModel: CZFeedViewModelable?) {} static func sizeThatFits(_ containerSize: CGSize, viewModel: CZFeedViewModelable) -> CGSize { return CZFacadeViewHelper.sizeThatFits(containerSize, viewModel: viewModel, viewClass: HotUserCellCardView.self, isHorizontal: true) } @IBAction func tappedFollow(_ sender: UIButton) { onAction?(SuggestedUserAction.follow(user: viewModel.user)) } @IBAction func tappedClose(_ sender: UIButton) { onAction?(SuggestedUserAction.ignore(user: viewModel.user)) } }
6c1d562c6a77af33cdb15d8cecbb7ed4
33.386667
97
0.639395
false
false
false
false
qualaroo/QualarooSDKiOS
refs/heads/master
QualarooTests/Network/SimpleRequestSchedulerSpec.swift
mit
1
// // SimpleRequestSchedulerSpec.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation import Quick import Nimble @testable import Qualaroo class SimpleRequestSchedulerSpec: QuickSpec { override func spec() { super.spec() describe("SimpleRequestScheduler") { var scheduler: SimpleRequestScheduler! beforeEach { scheduler = SimpleRequestScheduler(reachability: nil, storage: PersistentMemory()) scheduler.removeObservers() } context("SimpleRequestProtocol") { it("schedule request when asked") { scheduler.privateQueue.isSuspended = true scheduler.scheduleRequest(URL(string: "https://qualaroo.com")!) let operations = scheduler.privateQueue.operations.filter { $0.isCancelled == false } expect(operations).to(haveCount(1)) } it("schedule two request when asked") { scheduler.privateQueue.isSuspended = true scheduler.scheduleRequest(URL(string: "https://qualaroo.com")!) scheduler.scheduleRequest(URL(string: "https://qualaroo.com")!) let operations = scheduler.privateQueue.operations.filter { $0.isCancelled == false } expect(operations).to(haveCount(2)) } } } } }
1bc5a634099d6ffc6bf443e3dd867518
32.627907
95
0.670816
false
false
false
false
apple/swift-driver
refs/heads/main
Sources/SwiftDriver/Execution/ProcessProtocol.swift
apache-2.0
1
//===--------------- ProessProtocol.swift - Swift Subprocesses ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 class TSCBasic.Process import struct TSCBasic.ProcessResult import class Foundation.FileHandle import struct Foundation.Data /// Abstraction for functionality that allows working with subprocesses. public protocol ProcessProtocol { /// The PID of the process. /// /// Clients that don't really launch a process can return /// a negative number to represent a "quasi-pid". /// /// - SeeAlso: https://github.com/apple/swift/blob/main/docs/DriverParseableOutput.rst#quasi-pids var processID: TSCBasic.Process.ProcessID { get } /// Wait for the process to finish execution. @discardableResult func waitUntilExit() throws -> ProcessResult static func launchProcess( arguments: [String], env: [String: String] ) throws -> Self static func launchProcessAndWriteInput( arguments: [String], env: [String: String], inputFileHandle: FileHandle ) throws -> Self } extension TSCBasic.Process: ProcessProtocol { public static func launchProcess( arguments: [String], env: [String: String] ) throws -> TSCBasic.Process { let process = Process(arguments: arguments, environment: env) try process.launch() return process } public static func launchProcessAndWriteInput( arguments: [String], env: [String: String], inputFileHandle: FileHandle ) throws -> TSCBasic.Process { let process = Process(arguments: arguments, environment: env) let processInputStream = try process.launch() var input: Data // Write out the contents of the input handle and close the input stream repeat { input = inputFileHandle.availableData processInputStream.write(input) } while (input.count > 0) processInputStream.flush() try processInputStream.close() return process } }
f52ca5e6918affafcd5f6b3b61e6dcad
31.069444
99
0.686444
false
false
false
false
CodaFi/swift
refs/heads/master
test/IDE/complete_property_delegate_attribute.swift
apache-2.0
2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AFTER_PAREN | %FileCheck %s -check-prefix=AFTER_PAREN // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_MyEnum_NODOT | %FileCheck %s -check-prefix=ARG_MyEnum_NODOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_MyEnum_DOT | %FileCheck %s -check-prefix=ARG_MyEnum_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_MyEnum_NOBINDING | %FileCheck %s -check-prefix=ARG_MyEnum_NOBINDING enum MyEnum { case east, west } @propertyWrapper struct MyStruct { var value: MyEnum init(initialValue: MyEnum) {} init(arg1: MyEnum, arg2: Int) {} } var globalInt: Int = 1 var globalMyEnum: MyEnum = .east struct TestStruct { @MyStruct(#^AFTER_PAREN^# var test1 // AFTER_PAREN: Begin completions, 2 items // AFTER_PAREN-DAG: Decl[Constructor]/CurrNominal: ['(']{#initialValue: MyEnum#}[')'][#MyStruct#]; name=initialValue: MyEnum // AFTER_PAREN-DAG: Decl[Constructor]/CurrNominal: ['(']{#arg1: MyEnum#}, {#arg2: Int#}[')'][#MyStruct#]; name=arg1: MyEnum, arg2: Int // AFTER_PAREN: End completions @MyStruct(arg1: #^ARG_MyEnum_NODOT^# var test2 // ARG_MyEnum_NODOT: Begin completions // ARG_MyEnum_NODOT-DAG: Decl[Struct]/CurrModule: TestStruct[#TestStruct#]; name=TestStruct // ARG_MyEnum_NODOT-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Identical]: globalMyEnum[#MyEnum#]; name=globalMyEnum // ARG_MyEnum_NODOT: End completions @MyStruct(arg1: .#^ARG_MyEnum_DOT^# var test3 // ARG_MyEnum_DOT: Begin completions, 3 items // ARG_MyEnum_DOT-DAG: Decl[EnumElement]/CurrNominal/TypeRelation[Identical]: east[#MyEnum#]; name=east // ARG_MyEnum_DOT-DAG: Decl[EnumElement]/CurrNominal/TypeRelation[Identical]: west[#MyEnum#]; name=west // ARG_MyEnum_DOT-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): MyEnum#})[#(into: inout Hasher) -> Void#]; // ARG_MyEnum_DOT: End completions @MyStruct(arg1: MyEnum.#^ARG_MyEnum_NOBINDING^#) // ARG_MyEnum_NOBINDING: Begin completions // ARG_MyEnum_NOBINDING-DAG: Decl[EnumElement]/CurrNominal: east[#MyEnum#]; // ARG_MyEnum_NOBINDING-DAG: Decl[EnumElement]/CurrNominal: west[#MyEnum#]; // ARG_MyEnum_NOBINDING: End completions }
c76805c8e4c9a4c001c48495b1517fc9
48.208333
162
0.723539
false
true
false
false
malt03/Balblair
refs/heads/master
Example/Balblair/QiitaRequest.swift
mit
1
// // QiitaRequest.swift // ApiClient // // Created by Koji Murata on 2016/08/04. // Copyright © 2016年 CocoaPods. All rights reserved. // import Foundation import Balblair struct QiitaRequest: MyApiRequest { typealias ResultType = [QiitaResult] var encodeType: EncodeType { return .json } let method = Balblair.Method.get let path = "api/v2/items" let parameters = QiitaParameters() } struct QiitaResult: Decodable { let title: String } struct QiitaParameters: Encodable { let page = 1 let per_page = 21 } protocol MyApiRequest: ApiRequest {} extension MyApiRequest { func didFailure(error: ErrorModel<MyErrorResultType>) {} func didSuccess(result: Self.ResultType) {} func willBeginRequest(parameters: Self.ParametersType) {} } struct MyErrorResultType: Decodable { }
019dd8b6c0a52e988c8a30742b825ae3
18.780488
59
0.727497
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Comments/EditCommentMultiLineCell.swift
gpl-2.0
1
import Foundation protocol EditCommentMultiLineCellDelegate: AnyObject { func textViewHeightUpdated() func textUpdated(_ updatedText: String?) } class EditCommentMultiLineCell: UITableViewCell, NibReusable { // MARK: - Properties @IBOutlet weak var textView: UITextView! @IBOutlet weak var textViewMinHeightConstraint: NSLayoutConstraint! weak var delegate: EditCommentMultiLineCellDelegate? // MARK: - View override func awakeFromNib() { super.awakeFromNib() configureCell() } func configure(text: String? = nil) { textView.text = text adjustHeight() } } // MARK: - UITextViewDelegate extension EditCommentMultiLineCell: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { delegate?.textUpdated(textView.text) adjustHeight() } } // MARK: - Private Extension private extension EditCommentMultiLineCell { func configureCell() { textView.font = .preferredFont(forTextStyle: .body) textView.textColor = .text textView.backgroundColor = .clear } func adjustHeight() { let originalHeight = textView.frame.size.height textView.sizeToFit() let textViewHeight = ceilf(Float(max(textView.frame.size.height, textViewMinHeightConstraint.constant))) textView.frame.size.height = CGFloat(textViewHeight) if textViewHeight != Float(originalHeight) { delegate?.textViewHeightUpdated() } } }
e700004c6a4af1a8f188e7a042c8dbc2
23.387097
112
0.686508
false
false
false
false
yoha/Ventori
refs/heads/master
Ventori/AddViewController.swift
mit
1
// // AddViewController.swift // Ventori // // Created by Yohannes Wijaya on 6/8/17. // Copyright © 2017 Corruption of Conformity. All rights reserved. // import UIKit protocol AddViewControllerDelegate { func getInventory(_ inventory: Inventory) } class AddViewController: UIViewController { // MARK: - Stored Properties var inventory: Inventory! var counter = 0 { willSet { self.counterLabel.text = String(describing: newValue) } } var delegate: AddViewControllerDelegate? enum Icon: String { case box, decrement, increment func getName() -> String { switch self { case .box: return "box100" case .decrement: return "Minus100" case .increment: return "Plus100" } } } // MARK: - IBOutlet Properties @IBOutlet weak var inventoryImageView: UIImageView! @IBOutlet weak var inventoryNameTextField: UITextField! @IBOutlet weak var counterLabel: UILabel! @IBOutlet weak var decrementButton: UIButton! @IBOutlet weak var incrementButton: UIButton! // MARK: - IBAction Methods @IBAction func cancelBarButtonItemDidTouch(_ sender: UIBarButtonItem) { self.dismissAddViewController() } @IBAction func saveBarButtonItemDidTouch(_ sender: UIBarButtonItem) { guard let validInventoryName = self.inventoryNameTextField.text, let validCounter = self.counterLabel.text else { return } self.inventory = Inventory(name: validInventoryName, count: validCounter, image: self.inventoryImageView.image, modifiedDate: self.getCurrentDateAndTime()) self.delegate?.getInventory(self.inventory) self.dismissAddViewController() } @IBAction func decrementButtonDidTouch(_ sender: UIButton) { guard self.counter != 0 else { return } self.counter -= 1 } @IBAction func incrementButtonDidTouch(_ sender: UIButton) { self.counter += 1 } // MARK: - UIViewController Methods override func viewDidLoad() { super.viewDidLoad() self.navigationItem.hidesBackButton = true self.decrementButton.setTitle(String(), for: .normal) self.decrementButton.setImage(UIImage(named: Icon.decrement.getName()), for: .normal) self.incrementButton.setTitle("", for: .normal) self.incrementButton.setImage(UIImage(named: Icon.increment.getName()), for: .normal) self.inventoryNameTextField.returnKeyType = .done self.inventoryNameTextField.delegate = self self.addGesturesToControlsWithin(self) if self.presentingViewController is UINavigationController { self.load(Inventory(name: "Inventory Name", count: "0", image: UIImage(named: Icon.box.getName()), modifiedDate: self.getCurrentDateAndTime())) } else { self.load(self.inventory) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.isToolbarHidden = true } // MARK: - Helper Methods func addGesturesToControlsWithin(_ viewController: AddViewController) { let dismissKeyboardGesture = UITapGestureRecognizer(target: viewController, action: #selector(AddViewController.dismissKeyboardIfPresent)) viewController.view.addGestureRecognizer(dismissKeyboardGesture) // ----- let tapImageViewToPresentImagePickerActionSheet = UITapGestureRecognizer(target: viewController, action: #selector(AddViewController.presentImagePickerActionSheet)) viewController.inventoryImageView.isUserInteractionEnabled = true viewController.inventoryImageView.addGestureRecognizer(tapImageViewToPresentImagePickerActionSheet) } func dismissKeyboardIfPresent() { self.inventoryNameTextField.resignFirstResponder() } func dismissAddViewController() { if self.presentingViewController is UINavigationController { self.dismiss(animated: true, completion: nil) } else { self.navigationController?.popViewController(animated: true) } } func load(_ inventory: Inventory) { self.inventoryNameTextField.text = inventory.name self.inventoryImageView.image = inventory.image self.counterLabel.text = inventory.count self.counter = Int(inventory.count)! } func initAndPresentCameraWith(_ imagePickerController: UIImagePickerController) { guard UIImagePickerController.isSourceTypeAvailable(.camera) == true else { let noCameraAlertController = UIAlertController(title: "Error: Missing Camera", message: "The built-in camera may be malfunctioning", preferredStyle: .alert) let okAlertAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) noCameraAlertController.addAction(okAlertAction) self.present(noCameraAlertController, animated: true, completion: nil) return } imagePickerController.sourceType = .camera self.present(imagePickerController, animated: true, completion: nil) } func initAndPresentPhotoLibraryWith(_ imagePickerController: UIImagePickerController) { imagePickerController.sourceType = .photoLibrary self.present(imagePickerController, animated: true, completion: nil) } func presentImagePickerActionSheet() { let imagePickerController = UIImagePickerController() imagePickerController.allowsEditing = true imagePickerController.delegate = self let imagePickerAlertController = UIAlertController(title: "Choose Image From", message: nil, preferredStyle: .actionSheet) let cameraAlertAction = UIAlertAction(title: "Camera", style: .default) { [weak self] (_) in guard let weakSelf = self else { return } weakSelf.initAndPresentCameraWith(imagePickerController) } let photoLibraryAlertAction = UIAlertAction(title: "Photo Library", style: .default) { [weak self] (_) in guard let weakSelf = self else { return } weakSelf.initAndPresentPhotoLibraryWith(imagePickerController) } let cancelAlertAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) let _ = [cameraAlertAction, photoLibraryAlertAction, cancelAlertAction].map { (alertAction: UIAlertAction) -> Void in imagePickerAlertController.addAction(alertAction) } self.present(imagePickerAlertController, animated: true, completion: nil) } func setupInventoryRelatedControls() { self.inventoryImageView.contentMode = .scaleAspectFill self.inventoryImageView.clipsToBounds = true self.inventoryImageView.layer.borderWidth = 0.5 self.inventoryImageView.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.50).cgColor self.inventoryImageView.layer.cornerRadius = 5 self.decrementButton.setTitle("", for: .normal) self.decrementButton.setBackgroundImage(UIImage(named: Icon.decrement.getName()), for: .normal) self.incrementButton.setTitle("", for: .normal) self.incrementButton.setBackgroundImage(UIImage(named: Icon.increment.getName()), for: .normal) } } extension AddViewController: CurrentAndDateTimeProtocol {} extension AddViewController: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { guard let selectedImage = info[UIImagePickerControllerEditedImage] as? UIImage else { return } self.inventoryImageView.image = selectedImage picker.dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } } extension AddViewController: UINavigationControllerDelegate {} extension AddViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
3dd829b8f98f3e8df63a98c1556e323c
40.191781
172
0.636958
false
false
false
false
Vienta/kuafu
refs/heads/master
kuafu/kuafu/src/Controller/KFVersionsViewController.swift
mit
1
// // KFVersionsViewController.swift // kuafu // // Created by Vienta on 15/7/20. // Copyright (c) 2015年 www.vienta.me. All rights reserved. // import UIKit class KFVersionsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var tbvVersions: UITableView! var versions: Array<Dictionary<String,String>>! // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "KF_SETTINGS_HISTORY_VERSION".localized self.versions = [["versionTitle":APP_DISPLAY_NAME + __KUAFU_1_0 + "KF_UPDATE_DESC".localized,"publishtime":"2015年8月8日","version":__KUAFU_1_0]] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - IBActions // MARK: - Private Methods // MARK: - Public Methods // MARK: - UITableViewDelegate && UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.versions.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "versionsCellIdentifier" var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell if (cell == nil) { cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellIdentifier) cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator } var rowVersionInfo: Dictionary = self.versions[indexPath.row] cell.textLabel?.text = rowVersionInfo["versionTitle"] cell.detailTextLabel?.text = rowVersionInfo["publishtime"] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) var rowVersionInfo: Dictionary = self.versions[indexPath.row] var version: String? = rowVersionInfo["version"] var versionTitle: String? = rowVersionInfo["versionTitle"] let versionDetailViewController: KFVersionDetailViewController = KFVersionDetailViewController(nibName: "KFVersionDetailViewController", bundle: nil) versionDetailViewController.version = version versionDetailViewController.title = versionTitle self.navigationController?.pushViewController(versionDetailViewController, animated: true) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 66 } }
dc51a7d95c33f180075ea6ea56cb7688
38.928571
157
0.704472
false
false
false
false
koalaylj/code-labs
refs/heads/master
swift/apple/main.swift
mit
2
// // main.swift // apple // // Created by koala on 11/23/15. // Copyright © 2015 koala. All rights reserved. // import Foundation print("Hello, World!") //1. let声明常量,var声明变量 // 各种进制的字面量表示 let decimalInteger = 17 let binaryInteger = 0b10001 // 17 in binary notation let octalInteger = 0o21 // 17 in octal notation let hexadecimalInteger = 0x11 // 17 in hexadecimal notation // 更易于阅读的写法 let paddedDouble = 000123.456 let oneMillion = 1_000_000 let justOverOneMillion = 1_000_000.000_000_1 //2. 定义类型别名 typealias typealias AudioSample = UInt16 // decompose一个tuple时,对于不想使用的元素用’_’接收 let http404Error = (404, "Not Found") let (justTheStatusCode, _) = http404Error print("The status code is \(justTheStatusCode)") // prints "The status code is 404 let possibleNumber = "123" let convertedNumber = Int(possibleNumber) //3. array var arr = ["hello", "world"] var brr = arr brr[0] = "haw" print(brr) // ["haw", "world"] print(arr ) // ["hello", "world"] brr.insert("aaaaaa", atIndex: 0) print(brr) print(arr) var threeDoubles = Double[](count: 3, repeatedValue: 0.0) // threeDoubles is of type Double[], and equals [0.0, 0.0, 0.0] var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5) // anotherThreeDoubles is inferred as Double[], and equals [2.5, 2.5, 2.5]
af29cd2e5e303dc0d012a20c77033b03
21.894737
74
0.65859
false
false
false
false
JuweTakeheshi/ajuda
refs/heads/master
Ajuda/VC/JUWShelterViewController.swift
mit
1
// // JUWShelterViewController.swift // Ajuda // // Created by Juwe Takeheshi on 9/21/17. // Copyright © 2017 Juwe Takeheshi. All rights reserved. // typealias OnResultsFound = (_ result: [JUWCollectionCenter], _ product: String)->() import UIKit class JUWShelterViewController: UIViewController { @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var searchController: UISearchController! var productSearch: String? var onResultsFound: OnResultsFound? override func viewDidLoad() { super.viewDidLoad() customizeUserInterface() customizeNavigationBarColors() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) searchBar.becomeFirstResponder() } func customizeUserInterface() { searchBar.autocapitalizationType = .none title = "Quiero ayudar con..." let dismissButton = UIButton() dismissButton.setImage(UIImage(named: "closeButtonOrange"), for: .normal) dismissButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30) dismissButton.addTarget(self, action: #selector(JUWShelterViewController.cancel(_:)), for: .touchUpInside) let dismissBarButton = UIBarButtonItem(customView: dismissButton) navigationItem.rightBarButtonItem = dismissBarButton } @IBAction func cancel(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } } extension JUWShelterViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText != "" { productSearch = searchText } else{ productSearch = nil } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { guard let product = productSearch else { return } activityIndicator.startAnimating() activityIndicator.isHidden = false searchBar.resignFirstResponder() JUWCollectionCenterManager().collectionCenters(whichNeed: product) { collectionCenters in self.onResultsFound?(collectionCenters, product) self.dismiss(animated: true, completion: nil) } } }
3ad2f98c68deda903d518e54a6886527
31.253521
114
0.679039
false
false
false
false
abertelrud/swift-package-manager
refs/heads/main
Sources/Basics/ImportScanning.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Dispatch import class Foundation.JSONDecoder import struct TSCBasic.AbsolutePath import class TSCBasic.Process private let defaultImports = ["Swift", "SwiftOnoneSupport", "_Concurrency", "_StringProcessing"] private struct Imports: Decodable { let imports: [String] } public protocol ImportScanner { func scanImports(_ filePathToScan: AbsolutePath, callbackQueue: DispatchQueue, completion: @escaping (Result<[String], Error>) -> Void) } public struct SwiftcImportScanner: ImportScanner { private let swiftCompilerEnvironment: EnvironmentVariables private let swiftCompilerFlags: [String] private let swiftCompilerPath: AbsolutePath public init(swiftCompilerEnvironment: EnvironmentVariables, swiftCompilerFlags: [String], swiftCompilerPath: AbsolutePath) { self.swiftCompilerEnvironment = swiftCompilerEnvironment self.swiftCompilerFlags = swiftCompilerFlags self.swiftCompilerPath = swiftCompilerPath } public func scanImports(_ filePathToScan: AbsolutePath, callbackQueue: DispatchQueue, completion: @escaping (Result<[String], Error>) -> Void) { let cmd = [swiftCompilerPath.pathString, filePathToScan.pathString, "-scan-dependencies", "-Xfrontend", "-import-prescan"] + self.swiftCompilerFlags TSCBasic.Process.popen(arguments: cmd, environment: self.swiftCompilerEnvironment, queue: callbackQueue) { result in dispatchPrecondition(condition: .onQueue(callbackQueue)) do { let stdout = try result.get().utf8Output() let imports = try JSONDecoder.makeWithDefaults().decode(Imports.self, from: stdout).imports .filter { !defaultImports.contains($0) } callbackQueue.async { completion(.success(imports)) } } catch { callbackQueue.async { completion(.failure(error)) } } } } }
d22e61c91d448ff3cebf3e2d37ee36fd
39.184615
139
0.619449
false
false
false
false
Ceroce/SwiftRay
refs/heads/master
SwiftRay/SwiftRay/Hitable.swift
mit
1
// // Hitable.swift // SwiftRay // // Created by Renaud Pradenc on 23/11/2016. // Copyright © 2016 Céroce. All rights reserved. // struct HitIntersection { let distance: Float // Distance from the origin of the ray let position: Vec3 let normal: Vec3 let material: Material } protocol Hitable { func hit(ray: Ray, distMin: Float, distMax: Float) -> HitIntersection? func boundingBox(startTime: Float, endTime: Float) -> BoundingBox } func closestHit(ray: Ray, hitables: [Hitable]) -> HitIntersection? { var closerIntersection: HitIntersection? = nil var closestSoFar: Float = Float.infinity for hitable in hitables { if let intersection = hitable.hit(ray: ray, distMin: 0.001, distMax: closestSoFar) { if intersection.distance < closestSoFar { closestSoFar = intersection.distance closerIntersection = intersection } } } return closerIntersection } /*func closestHit(ray: Ray, hitables: [Hitable]) -> HitIntersection? { for hitable in hitables { // There is only one return hitable.hit(ray: ray, distMin: 0.001, distMax: Float.infinity) } return nil }*/
df7796f5090971f038a21b15024d9136
27.761905
92
0.654801
false
false
false
false
volodg/iAsync.social
refs/heads/master
Pods/ReactiveKit/ReactiveKit/Disposables/BlockDisposable.swift
mit
1
// // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // 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. // /// A disposable that executes the given block upon disposing. public final class BlockDisposable: DisposableType { public var isDisposed: Bool { return handler == nil } private var handler: (() -> ())? private let lock = RecursiveLock(name: "com.ReactiveKit.ReactiveKit.BlockDisposable") public init(_ handler: () -> ()) { self.handler = handler } public func dispose() { lock.lock() handler?() handler = nil lock.unlock() } } public class DeinitDisposable: DisposableType { public var otherDisposable: DisposableType? = nil public var isDisposed: Bool { return otherDisposable == nil } public init(disposable: DisposableType) { otherDisposable = disposable } public func dispose() { otherDisposable?.dispose() } deinit { otherDisposable?.dispose() } }
7527e8140e0a3aef1e7985a972985ebc
29.328358
87
0.708169
false
false
false
false
che1404/RGViperChat
refs/heads/master
RGViperChat/CreateChat/DataManager/API/CreateChatAPIDataManager.swift
mit
1
// // Created by Roberto Garrido // Copyright (c) 2017 Roberto Garrido. All rights reserved. // import Foundation import FirebaseDatabase import FirebaseAuth class CreateChatAPIDataManager: CreateChatAPIDataManagerInputProtocol { let root = Database.database().reference() init() {} func fetchUsers(completion: @escaping (Result<[User]>) -> Void) { guard let currentUser = Auth.auth().currentUser else { completion(.failure(NSError(domain: "createChat", code: -1, userInfo: [NSLocalizedDescriptionKey: "User not logged in"]))) return } root.child("User").observeSingleEvent(of: .value, with: { snapshot in if let userDictionaries = snapshot.value as? [String: Any] { var users: [User] = [] for userDictionaryWithKey in userDictionaries where currentUser.uid != userDictionaryWithKey.key { if let userDictionary = userDictionaryWithKey.value as? [String: Any] { if let username = userDictionary["name"] as? String { let user = User(username: username, userID: userDictionaryWithKey.key) users.append(user) } } } completion(.success(users)) } else { completion(.failure(NSError(domain: "fetchUsers", code: -1, userInfo: [NSLocalizedDescriptionKey: "Couldn't fetch users"]))) } }) } func createChat(withUser user: User, completion: @escaping (Result<Chat>) -> Void) { guard let currentUser = Auth.auth().currentUser else { completion(.failure(NSError(domain: "createChat", code: -1, userInfo: [NSLocalizedDescriptionKey: "User not logged in"]))) return } // Get current user display name root.child("User/\(currentUser.uid)/name").observeSingleEvent(of: .value, with: { snapshot in if let currentUsername = snapshot.value as? String { // Create chat, and add users to the chat let chatDictionary = [ "users": [ currentUser.uid: currentUsername, user.userID: user.username ] ] let chatID = self.root.child("Chat").childByAutoId().key self.root.child("Chat/\(chatID)").setValue(chatDictionary, withCompletionBlock: { error, reference in if error == nil { // Add chat to current user let chatJoinTimestamp = Date().timeIntervalSince1970 self.root.child("User/\(currentUser.uid)/chats/\(chatID)").setValue(chatJoinTimestamp, withCompletionBlock: { error, reference in if error != nil { completion(.failure(NSError(domain: "createChat", code: -1, userInfo: [NSLocalizedDescriptionKey: error!.localizedDescription]))) } else { // Add chat to the other participant user self.root.child("User/\(user.userID)/chats/\(chatID)").setValue(chatJoinTimestamp, withCompletionBlock: { error, reference in if error != nil { completion(.failure(NSError(domain: "createChat", code: -1, userInfo: [NSLocalizedDescriptionKey: error!.localizedDescription]))) } else { completion(.success(Chat(chatID: reference.key, displayName: user.username, senderID: currentUser.uid, senderDisplayName: currentUsername, receiverID: user.userID, lastMessage: ""))) } }) } }) } else { completion(.failure(NSError(domain: "createChat", code: -1, userInfo: [NSLocalizedDescriptionKey: "Error creating chat"]))) } }) } }) } }
0f08e3f5029dd7a6d4dece592bafacf9
49.409639
222
0.536807
false
false
false
false
szukuro/spacecat-swift
refs/heads/master
Space Cat/HudNode.swift
mit
1
// // HudNode.swift // Space Cat // // Created by László Györi on 28/07/14. // Copyright (c) 2014 László Györi. All rights reserved. // import UIKit import SpriteKit class HudNode: SKNode { var lives : NSInteger = MaxLives var score : NSInteger = 0 } extension HudNode { class func hudAtPosition(position:CGPoint, frame:CGRect) -> HudNode { let hud = self.node() as HudNode hud.position = position hud.zPosition = 10 hud.name = "HUD" let catHead = SKSpriteNode(imageNamed: "HUD_cat_1") catHead.position = CGPointMake(30, -10) hud.addChild(catHead) var lastLifeBar : SKSpriteNode? for var i = 0; i < hud.lives; ++i { let lifeBar = SKSpriteNode(imageNamed: "HUD_life_1") lifeBar.name = "Life\(i + 1)" hud.addChild(lifeBar) if (lastLifeBar) { lifeBar.position = CGPointMake(lastLifeBar!.position.x + 10, lastLifeBar!.position.y) } else { lifeBar.position = CGPointMake(catHead.position.x + 30, catHead.position.y) } lastLifeBar = lifeBar } let scoreLabel = SKLabelNode(fontNamed: "Futura-CondensedExtraBold") scoreLabel.name = "Score" scoreLabel.text = "\(hud.score)" scoreLabel.fontSize = 20 scoreLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Right scoreLabel.position = CGPointMake(frame.size.width - 20, -10) hud.addChild(scoreLabel) return hud } func addPoints(points:Int) { self.score += points let scoreLabel = self.childNodeWithName("Score") as SKLabelNode scoreLabel.text = "\(self.score)" } func loseLife() -> Bool { if (self.lives > 0) { let lifeNodeName = "Life\(self.lives)" let lifeToRemove = self.childNodeWithName(lifeNodeName) lifeToRemove.removeFromParent() self.lives-- } return self.lives == 0 } }
15fc084627137d067ba92aefea521d5e
27
101
0.556574
false
false
false
false
darina/omim
refs/heads/master
iphone/Maps/UI/Search/Tabs/CategoriesTab/SearchCategoryCell.swift
apache-2.0
5
final class SearchCategoryCell: MWMTableViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! private var category: String = "" func update(with category: String) { self.category = category iconImageView.mwm_name = String(format: "ic_%@", category) titleLabel.text = L(category) } override func applyTheme() { super.applyTheme() iconImageView.mwm_name = String(format: "ic_%@", category) } }
872ce035bd491d56f537b644fffef5fc
28.5
62
0.701271
false
false
false
false
Onix-Systems/ios-mazazine-reader
refs/heads/master
MazazineReader/MasterViewController.swift
apache-2.0
1
// Copyright 2017 Onix-Systems // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem } override func viewWillAppear(_ animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed super.viewWillAppear(animated) } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] as! Date let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object as AnyObject? controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let object = objects[indexPath.row] as! Date cell.textLabel!.text = object.description return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { objects.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
746f7b77f3be7eec288a9c8b29121b6c
36.658537
136
0.689443
false
false
false
false
JV17/MyCal-iWatch
refs/heads/master
MyCal-Calculator/MyCalViewController.swift
mit
1
// // MyCalViewController.swift // MyCal-Calculator // // Created by Jorge Valbuena on 2015-04-17. // Copyright (c) 2015 Jorge Valbuena. All rights reserved. // import UIKit import QuartzCore import MessageUI import WatchConnectivity //MARK: Structs /// Holds all the screen sizes within a struct struct ScreenSize { static let SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width static let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) } /// The device types iPhone 4, iPhone5, iPhone6 & iPhone6+ struct DeviceType { static let IS_IPHONE_4_OR_LESS = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0 static let IS_IPHONE_5 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0 static let IS_IPHONE_6 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0 static let IS_IPHONE_6P = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0 } /// Controllers identifiers struct identifiers { static let backgroundColor: String = "backgroundColor" static let numberColor: String = "numberColor" static let operationColor: String = "operationColor" static let resetColors: String = "reset" } /// Table view constants values struct TableViewConstants { static let numRows: Int = 1 static let numSections: Int = 5 } //MARK: //MARK: Implementation @available(iOS 9.0, *) class MyCalViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MFMailComposeViewControllerDelegate, WCSessionDelegate { //MARK: Lazy Initialization private lazy var tableView: UITableView = { let tableView = UITableView(frame: CGRectZero, style: .Plain) tableView.backgroundColor = .clearColor() tableView.separatorStyle = .None tableView.separatorColor = .grayColor() tableView.bounces = true tableView.scrollEnabled = true tableView.delegate = self tableView.dataSource = self tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "tableViewCell") tableView.translatesAutoresizingMaskIntoConstraints = false tableView.showsVerticalScrollIndicator = false tableView.showsHorizontalScrollIndicator = false return tableView }() private lazy var imagesArray: Array<UIImage> = { let array = Array<UIImage>() return array }() private lazy var selectedRowView: UIView = { let view = UIView() view.backgroundColor = UIColor.jv_colorWithHexString("#DBDDDE").colorWithAlphaComponent(0.7) return view }() private lazy var imageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "appIconBig")) return imageView }() private lazy var appHelper: MyCalHelper = { let appHelper = MyCalHelper() return appHelper }() private lazy var bgColorController: MyCalColorPickerViewController = { let bgColorController = MyCalColorPickerViewController(title: "Choose a background color", identifier: identifiers.backgroundColor) return bgColorController }() private lazy var numbersColorController: MyCalColorPickerViewController = { let numbersColorController = MyCalColorPickerViewController(title: "Choose the numbers color", identifier: identifiers.numberColor) return numbersColorController }() private lazy var operationsColorController: MyCalColorPickerViewController = { let operationsColorController = MyCalColorPickerViewController(title: "Choose the operations color", identifier: identifiers.operationColor) return operationsColorController }() private lazy var transitionManager: TransitionManager = { let transitionManager = TransitionManager() return transitionManager }() private let session : WCSession? = WCSession.isSupported() ? WCSession.defaultSession() : nil private var titleLabel: UILabel? private var versionLabel: UILabel? //MARK: Constants let rowHeight: CGFloat = 50.0 let heightHeader: CGFloat = 15.0 let heightFooter: CGFloat = 0.0 //MARK: //MARK: Initializers required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.configureWCSession() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.configureWCSession() } override func viewDidLoad() { super.viewDidLoad() // setting view controller self.commonInit() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if(tableView.respondsToSelector(Selector("separatorInset"))) { tableView.separatorInset = UIEdgeInsetsZero } if(tableView.respondsToSelector(Selector("layoutMargins"))) { tableView.layoutMargins = UIEdgeInsetsZero } } private func commonInit() { // setting gradient background let colors: [AnyObject] = [UIColor.jv_colorWithHexString("#FF5E3A").CGColor, UIColor.jv_colorWithHexString("#FF2A68").CGColor] self.appHelper.applyGradientFromColors(colors, view: view) self.imagesArray = [UIImage(named: "background_color-50")!, UIImage(named: "brush-50")!, UIImage(named: "roller_brush-50")!, UIImage(named: "message_group-50")!] self.selectedRowView.frame = CGRectMake(0, 0, view.frame.size.width, rowHeight) self.view.addSubview(tableView) self.applyTableViewAutoLayout() } private func labelWithFrmae(frame: CGRect, text: String) -> UILabel { let label = UILabel(frame: frame) label.backgroundColor = .clearColor() label.font = UIFont(name: "Lato-Light", size: 20) label.textColor = .blackColor() label.textAlignment = .Center label.numberOfLines = 1 label.text = text return label } private func configureWCSession() { session?.delegate = self; session?.activateSession() } private func applyTableViewAutoLayout() { let leadingConstraint = NSLayoutConstraint(item: tableView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 20) let trailingConstraint = NSLayoutConstraint(item: tableView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: -20) let topConstraint = NSLayoutConstraint(item: tableView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 16) let bottomConstraint = NSLayoutConstraint(item: tableView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: -10) view.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint]) } //MARK: //MARK: TableView delegate and datasource func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("tableViewCell")! if(cell.respondsToSelector(Selector("separatorInset"))) { cell.separatorInset = UIEdgeInsetsZero } if(cell.respondsToSelector(Selector("preservesSuperviewLayoutMargins"))) { cell.preservesSuperviewLayoutMargins = false } if(cell.respondsToSelector(Selector("layoutMargins"))) { cell.layoutMargins = UIEdgeInsetsZero } // setting up cell cell.layer.cornerRadius = 10.0 cell.layer.masksToBounds = true cell.selectedBackgroundView = selectedRowView cell.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5) cell.textLabel?.font = UIFont(name: "Lato-Light", size: 22) cell.textLabel?.textColor = .whiteColor() //colorWithHexString("#DBDDDE") cell.accessoryType = .DisclosureIndicator if(indexPath.section == 0) { cell.layer.cornerRadius = 0.0 cell.layer.masksToBounds = false cell.selectedBackgroundView = nil cell.backgroundColor = UIColor.clearColor() cell.accessoryType = .None cell.selectionStyle = .None let imgFrame: CGSize = self.imageView.frame.size self.imageView.frame = CGRectMake(tableView.frame.width/2-imgFrame.width/2, 5, imgFrame.width, imgFrame.height) self.imageView.layer.cornerRadius = 10.0 self.imageView.clipsToBounds = true cell.addSubview(imageView) titleLabel = labelWithFrmae(CGRectMake(0, CGRectGetMaxY(imageView.frame), tableView.frame.size.width, 30), text: "Version 1.0") cell.addSubview(titleLabel!) versionLabel = labelWithFrmae(CGRectMake(0, CGRectGetMaxY(titleLabel!.frame), tableView.frame.size.width, 30), text: "MyCal Calculator Settings") cell.addSubview(versionLabel!) } else if(indexPath.section == 1) { cell.textLabel?.text = "Numbers color"//"Background color" cell.textLabel?.alpha = 0.9 cell.imageView?.image = imagesArray[0] cell.imageView?.alpha = 0.9 } else if(indexPath.section == 2) { cell.textLabel?.text = "Operations color" cell.textLabel?.alpha = 0.9 cell.imageView?.image = imagesArray[1] cell.imageView?.alpha = 0.9 } else if(indexPath.section == 3) { cell.textLabel?.text = "Reset colors" cell.textLabel?.alpha = 0.9 cell.imageView?.image = imagesArray[2] cell.imageView?.alpha = 0.9 } else if(indexPath.section == 4) { cell.textLabel?.text = "Contact Support" cell.textLabel?.alpha = 0.9 cell.imageView?.image = imagesArray[3] cell.imageView?.alpha = 0.9 } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // selected row code tableView.deselectRowAtIndexPath(indexPath, animated: true) if(indexPath.section == 1) { self.numbersColorController.transitioningDelegate = self.transitionManager self.numbersColorController.title = identifiers.numberColor self.presentViewController(numbersColorController, animated: true, completion: nil) } else if(indexPath.section == 2) { self.operationsColorController.transitioningDelegate = self.transitionManager self.operationsColorController.title = identifiers.operationColor self.presentViewController(operationsColorController, animated: true, completion: nil) } else if(indexPath.section == 3) { // passing notification to app watch self.sendMessageWithData(NSKeyedArchiver.archivedDataWithRootObject(UIColor.clearColor()), identifier: identifiers.resetColors) } else if(indexPath.section == 4) { // open mail composer self.sendEmailButtonTapped() } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // number of rows return TableViewConstants.numRows } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if(indexPath.section == 0) { return 260; } return rowHeight } func numberOfSectionsInTableView(tableView: UITableView) -> Int { // number of sections return TableViewConstants.numSections } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // header for tableview return UIView.init(); } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // height for header return heightHeader } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { // footer for tableview return UIView.init() } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { // height for footer return heightFooter } //MARK: //MARK: Helper functions private func sendEmailButtonTapped() { let mailComposeViewController = configuredMailComposeViewController() if MFMailComposeViewController.canSendMail() { self.presentViewController(mailComposeViewController, animated: true, completion: nil) } else { self.showSendMailErrorAlert() } } private func configuredMailComposeViewController() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self mailComposerVC.setToRecipients(["[email protected]"]) mailComposerVC.setSubject("MyCal - Apple Watch Support") //mailComposerVC.setMessageBody("Sending e-mail in-app!", isHTML: false) return mailComposerVC } private func showSendMailErrorAlert() { let alertController = UIAlertController.init(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", preferredStyle: .Alert) let defaultAction = UIAlertAction.init(title: "OK", style: .Default, handler: nil) alertController.addAction(defaultAction) self.presentViewController(alertController, animated: true, completion: nil) } func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) } private func infoButtonPressed(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "http://www.jorgedeveloper.com")!) } private func sendMessageWithData(data: NSData, identifier: String) { let applicationData = ["color" : data, "identifier" : identifier] if let session = session where session.reachable { session.sendMessage(applicationData, replyHandler: { replyData in print(replyData) }, errorHandler: { error in print(error) let alertController = UIAlertController.init(title: "Fail Color Transfer", message: "Sorry, we couldn't update the color in your watch because of an error. " + "Error: " + error.description, preferredStyle: .Alert) let defaultAction = UIAlertAction.init(title: "OK", style: .Default, handler: nil) alertController.addAction(defaultAction) self.presentViewController(alertController, animated: true, completion: nil) }) } } }
f8d24bb843bcf1f40f0bb7d7e64746e6
35.949772
234
0.647986
false
false
false
false
onmyway133/Github.swift
refs/heads/master
Carthage/Checkouts/Sugar/Source/Shared/GrandCentralDispatch.swift
mit
1
import Foundation public enum DispatchQueue { case Main, Interactive, Initiated, Utility, Background, Custom(dispatch_queue_t) } private func getQueue(queue queueType: DispatchQueue = .Main) -> dispatch_queue_t { let queue: dispatch_queue_t switch queueType { case .Main: queue = dispatch_get_main_queue() case .Interactive: queue = dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0) case .Initiated: queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0) case .Utility: queue = dispatch_get_global_queue(QOS_CLASS_UTILITY, 0) case .Background: queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) case .Custom(let userQueue): queue = userQueue } return queue } public func delay(delay:Double, queue queueType: DispatchQueue = .Main, closure: () -> Void) { dispatch_after( dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), getQueue(queue: queueType), closure ) } public func dispatch(queue queueType: DispatchQueue = .Main, closure: () -> Void) { dispatch_async(getQueue(queue: queueType), { closure() }) }
66afccf02e880091fea15e6d9db2e0b6
27.1
94
0.704626
false
false
false
false
vector-im/vector-ios
refs/heads/master
Riot/Modules/CreateRoom/EnterNewRoomDetails/Cells/ChooseAvatarTableViewCell.swift
apache-2.0
1
// // Copyright 2020 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Reusable protocol ChooseAvatarTableViewCellDelegate: AnyObject { func chooseAvatarTableViewCellDidTapChooseAvatar(_ cell: ChooseAvatarTableViewCell, sourceView: UIView) func chooseAvatarTableViewCellDidTapRemoveAvatar(_ cell: ChooseAvatarTableViewCell) } class ChooseAvatarTableViewCell: UITableViewCell { @IBOutlet private weak var avatarImageView: UIImageView! { didSet { avatarImageView.layer.cornerRadius = avatarImageView.frame.width/2 } } @IBOutlet private weak var chooseAvatarButton: UIButton! @IBOutlet private weak var removeAvatarButton: UIButton! { didSet { removeAvatarButton.imageView?.contentMode = .scaleAspectFit } } weak var delegate: ChooseAvatarTableViewCellDelegate? @IBAction private func chooseAvatarButtonTapped(_ sender: UIButton) { delegate?.chooseAvatarTableViewCellDidTapChooseAvatar(self, sourceView: sender) } @IBAction private func removeAvatarButtonTapped(_ sender: UIButton) { delegate?.chooseAvatarTableViewCellDidTapRemoveAvatar(self) } func configure(withViewModel viewModel: ChooseAvatarTableViewCellVM) { if let image = viewModel.avatarImage { avatarImageView.image = image removeAvatarButton.isHidden = false } else { avatarImageView.image = Asset.Images.captureAvatar.image removeAvatarButton.isHidden = true } } } extension ChooseAvatarTableViewCell: NibReusable {} extension ChooseAvatarTableViewCell: Themable { func update(theme: Theme) { backgroundView = UIView() backgroundView?.backgroundColor = theme.backgroundColor } }
41ba4e2e718fd9951454f49019756ba0
32.485714
107
0.72099
false
false
false
false
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART
refs/heads/master
bluefruitconnect/Common/UartManager.swift
mit
1
// // UartManager.swift // Bluefruit Connect // // Created by Antonio García on 06/02/16. // Copyright © 2016 Adafruit. All rights reserved. // import Foundation class UartManager: NSObject { enum UartNotifications : String { case DidSendData = "didSendData" case DidReceiveData = "didReceiveData" case DidBecomeReady = "didBecomeReady" } // Constants private static let UartServiceUUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e" // UART service UUID static let RxCharacteristicUUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e" private static let TxCharacteristicUUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e" private static let TxMaxCharacters = 20 // Manager static let sharedInstance = UartManager() // Bluetooth Uart private var uartService: CBService? private var rxCharacteristic: CBCharacteristic? private var txCharacteristic: CBCharacteristic? private var txWriteType = CBCharacteristicWriteType.WithResponse var blePeripheral: BlePeripheral? { didSet { if blePeripheral?.peripheral.identifier != oldValue?.peripheral.identifier { // Discover UART resetService() if let blePeripheral = blePeripheral { DLog("Uart: discover services") blePeripheral.peripheral.discoverServices([CBUUID(string: UartManager.UartServiceUUID)]) } } } } // Data var dataBuffer = [UartDataChunk]() var dataBufferEnabled = Config.uartShowAllUartCommunication override init() { super.init() let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: #selector(didDisconnectFromPeripheral(_:)), name: BleManager.BleNotifications.DidDisconnectFromPeripheral.rawValue, object: nil) } deinit { let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver(self, name: BleManager.BleNotifications.DidDisconnectFromPeripheral.rawValue, object: nil) } func didDisconnectFromPeripheral(notification : NSNotification) { blePeripheral = nil resetService() } private func resetService() { uartService = nil rxCharacteristic = nil txCharacteristic = nil } func sendDataWithCrc(data : NSData) { let len = data.length var dataBytes = [UInt8](count: len, repeatedValue: 0) var crc: UInt8 = 0 data.getBytes(&dataBytes, length: len) for i in dataBytes { //add all bytes crc = crc &+ i } crc = ~crc //invert let dataWithChecksum = NSMutableData(data: data) dataWithChecksum.appendBytes(&crc, length: 1) sendData(dataWithChecksum) } func sendData(data: NSData) { let dataChunk = UartDataChunk(timestamp: CFAbsoluteTimeGetCurrent(), mode: .TX, data: data) sendChunk(dataChunk) } func sendChunk(dataChunk: UartDataChunk) { if let txCharacteristic = txCharacteristic, blePeripheral = blePeripheral { let data = dataChunk.data if dataBufferEnabled { blePeripheral.uartData.sentBytes += data.length dataBuffer.append(dataChunk) } // Split data in txmaxcharacters bytes packets var offset = 0 repeat { let chunkSize = min(data.length-offset, UartManager.TxMaxCharacters) let chunk = NSData(bytesNoCopy: UnsafeMutablePointer<UInt8>(data.bytes)+offset, length: chunkSize, freeWhenDone:false) if Config.uartLogSend { DLog("send: \(hexString(chunk))") } blePeripheral.peripheral.writeValue(chunk, forCharacteristic: txCharacteristic, type: txWriteType) offset+=chunkSize }while(offset<data.length) NSNotificationCenter.defaultCenter().postNotificationName(UartNotifications.DidSendData.rawValue, object: nil, userInfo:["dataChunk" : dataChunk]); } else { DLog("Error: sendChunk with uart not ready") } } private func receivedData(data: NSData) { let dataChunk = UartDataChunk(timestamp: CFAbsoluteTimeGetCurrent(), mode: .RX, data: data) receivedChunk(dataChunk) } private func receivedChunk(dataChunk: UartDataChunk) { if Config.uartLogReceive { DLog("received: \(hexString(dataChunk.data))") } if dataBufferEnabled { blePeripheral?.uartData.receivedBytes += dataChunk.data.length dataBuffer.append(dataChunk) } NSNotificationCenter.defaultCenter().postNotificationName(UartNotifications.DidReceiveData.rawValue, object: nil, userInfo:["dataChunk" : dataChunk]); } func isReady() -> Bool { return txCharacteristic != nil && rxCharacteristic != nil// && rxCharacteristic!.isNotifying } func clearData() { dataBuffer.removeAll() blePeripheral?.uartData.receivedBytes = 0 blePeripheral?.uartData.sentBytes = 0 } } // MARK: - CBPeripheralDelegate extension UartManager: CBPeripheralDelegate { func peripheral(peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) { DLog("UartManager: resetService because didModifyServices") resetService() } func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) { guard blePeripheral != nil else { return } if uartService == nil { if let services = peripheral.services { var found = false var i = 0 while (!found && i < services.count) { let service = services[i] if (service.UUID.UUIDString .caseInsensitiveCompare(UartManager.UartServiceUUID) == .OrderedSame) { found = true uartService = service peripheral.discoverCharacteristics([CBUUID(string: UartManager.RxCharacteristicUUID), CBUUID(string: UartManager.TxCharacteristicUUID)], forService: service) } i += 1 } } } } func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) { guard blePeripheral != nil else { return } //DLog("uart didDiscoverCharacteristicsForService") if let uartService = uartService where rxCharacteristic == nil || txCharacteristic == nil { if rxCharacteristic == nil || txCharacteristic == nil { if let characteristics = uartService.characteristics { var found = false var i = 0 while !found && i < characteristics.count { let characteristic = characteristics[i] if characteristic.UUID.UUIDString .caseInsensitiveCompare(UartManager.RxCharacteristicUUID) == .OrderedSame { rxCharacteristic = characteristic } else if characteristic.UUID.UUIDString .caseInsensitiveCompare(UartManager.TxCharacteristicUUID) == .OrderedSame { txCharacteristic = characteristic txWriteType = characteristic.properties.contains(.WriteWithoutResponse) ? .WithoutResponse:.WithResponse DLog("Uart: detected txWriteType: \(txWriteType.rawValue)") } found = rxCharacteristic != nil && txCharacteristic != nil i += 1 } } } // Check if characteristics are ready if (rxCharacteristic != nil && txCharacteristic != nil) { // Set rx enabled peripheral.setNotifyValue(true, forCharacteristic: rxCharacteristic!) // Send notification that uart is ready NSNotificationCenter.defaultCenter().postNotificationName(UartNotifications.DidBecomeReady.rawValue, object: nil, userInfo:nil) DLog("Uart: did become ready") } } } func peripheral(peripheral: CBPeripheral, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic, error: NSError?) { guard blePeripheral != nil else { return } DLog("didUpdateNotificationStateForCharacteristic") /* if characteristic == rxCharacteristic { if error != nil { DLog("Uart RX isNotifying error: \(error)") } else { if characteristic.isNotifying { DLog("Uart RX isNotifying: true") // Send notification that uart is ready NSNotificationCenter.defaultCenter().postNotificationName(UartNotifications.DidBecomeReady.rawValue, object: nil, userInfo:nil) } else { DLog("Uart RX isNotifying: false") } } } */ } func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) { guard blePeripheral != nil else { return } if characteristic == rxCharacteristic && characteristic.service == uartService { if let characteristicDataValue = characteristic.value { receivedData(characteristicDataValue) } } } }
a2dd9f83e003240b4e434986a8793024
36.032847
183
0.589691
false
false
false
false
robertoseidenberg/MixerBox
refs/heads/master
SampleApp/SampleApp/ViewController+Layout.swift
mit
1
import MixerBox extension ViewController { func updateColorPreview() { zoom.backgroundColor = UIColor(hsb: hsbMixer.hsb) } func updateHSBSliders(hsb: HSB, labelsOnly: Bool = false) { if labelsOnly == false { hueSlider.value = 360 * hsb.hue saturationSlider.value = 100 * hsb.saturation brightnessSlider.value = 100 * hsb.brightness } hueLabel.text = String(Int(hueSlider.value)) saturationLabel.text = String(Int(saturationSlider.value)) brightnessLabel.text = String(Int(brightnessSlider.value)) } func updateRGBSliders(rgb: RGB, labelsOnly: Bool = false) { if labelsOnly == false { redSlider.value = 255 * rgb.red greenSlider.value = 255 * rgb.green blueSlider.value = 255 * rgb.blue } redLabel.text = String(Int(redSlider.value)) greenLabel.text = String(Int(greenSlider.value)) blueLabel.text = String(Int(blueSlider.value)) } }
681c1d2e8d5dab9da1239417b8aae908
27.088235
62
0.66911
false
false
false
false
sarahspins/Loop
refs/heads/master
Loop/Models/MLabService.swift
apache-2.0
2
// // mLabService.swift // Loop // // Created by Nate Racklyeft on 7/3/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation private let mLabAPIHost = NSURL(string: "https://api.mongolab.com/api/1/databases")! struct MLabService: ServiceAuthentication { var credentials: [ServiceCredential] let title: String = NSLocalizedString("mLab", comment: "The title of the mLab service") init(databaseName: String?, APIKey: String?) { credentials = [ ServiceCredential( title: NSLocalizedString("Database", comment: "The title of the mLab database name credential"), placeholder: "nightscoutdb", isSecret: false, keyboardType: .ASCIICapable, value: databaseName ), ServiceCredential( title: NSLocalizedString("API Key", comment: "The title of the mLab API Key credential"), placeholder: nil, isSecret: false, keyboardType: .ASCIICapable, value: APIKey ) ] if databaseName != nil && APIKey != nil { isAuthorized = true } } var databaseName: String? { return credentials[0].value } var APIKey: String? { return credentials[1].value } private(set) var isAuthorized: Bool = false mutating func verify(completion: (success: Bool, error: ErrorType?) -> Void) { guard let APIURL = APIURLForCollection("") else { completion(success: false, error: nil) return } NSURLSession.sharedSession().dataTaskWithURL(APIURL) { (_, response, error) in var error: ErrorType? = error if error == nil, let response = response as? NSHTTPURLResponse where response.statusCode >= 300 { error = LoopError.ConnectionError } self.isAuthorized = error == nil completion(success: self.isAuthorized, error: error) }.resume() } mutating func reset() { credentials[0].value = nil credentials[1].value = nil isAuthorized = false } private func APIURLForCollection(collection: String) -> NSURL? { guard let databaseName = databaseName, APIKey = APIKey else { return nil } let APIURL = mLabAPIHost.URLByAppendingPathComponent("\(databaseName)/collections").URLByAppendingPathComponent(collection) let components = NSURLComponents(URL: APIURL, resolvingAgainstBaseURL: true)! var items = components.queryItems ?? [] items.append(NSURLQueryItem(name: "apiKey", value: APIKey)) components.queryItems = items return components.URL } func uploadTaskWithData(data: NSData, inCollection collection: String) -> NSURLSessionTask? { guard let URL = APIURLForCollection(collection) else { return nil } let request = NSMutableURLRequest(URL: URL) request.HTTPMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") return NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: data) } } extension KeychainManager { func setMLabDatabaseName(databaseName: String?, APIKey: String?) throws { let credentials: InternetCredentials? if let username = databaseName, password = APIKey { credentials = InternetCredentials(username: username, password: password, URL: mLabAPIHost) } else { credentials = nil } try replaceInternetCredentials(credentials, forURL: mLabAPIHost) } func getMLabCredentials() -> (databaseName: String, APIKey: String)? { do { let credentials = try getInternetCredentials(URL: mLabAPIHost) return (databaseName: credentials.username, APIKey: credentials.password) } catch { return nil } } }
213a1492f23614bc2769fa5f41da760f
30.46875
131
0.618669
false
false
false
false
cdtschange/SwiftMKit
refs/heads/master
SwiftMKit/UI/View/RangeSlider/RangeSliderThumbLayer.swift
mit
1
// // RangeSliderThumbLayer.swift // CustomControl // // Created by chenyh on 16/7/4. // Copyright © 2016年 chenyh. All rights reserved. // import UIKit import QuartzCore /// Range slider track layer. Responsible for drawing the horizontal track public class RangeSliderTrackLayer: CALayer { /// owner slider weak var rangeSlider: RangeSlider? /// draw the track between 2 thumbs /// /// - Parameter ctx: current graphics context override public func draw(in ctx: CGContext) { if let slider = rangeSlider { // Clip var orgRect = bounds if slider.trackHeight > 0 { orgRect.y = orgRect.y + (orgRect.h - slider.trackHeight)/2 orgRect.h = slider.trackHeight } let cornerRadius = orgRect.height * slider.curvaceousness / 2.0 let path = UIBezierPath(roundedRect: orgRect, cornerRadius: cornerRadius) ctx.addPath(path.cgPath) // Fill the track ctx.setFillColor(slider.trackTintColor.cgColor) ctx.addPath(path.cgPath) ctx.fillPath() let lowerValuePosition = CGFloat(slider.positionForValue(value: slider.lowerValue)) let upperValuePosition = CGFloat(slider.positionForValue(value: slider.upperValue)) // Fill the lower track range ctx.setFillColor(slider.lowerTrackHighlightTintColor.cgColor) let lowerRect = CGRect(x: 0.0 , y: orgRect.y, width: lowerValuePosition - 0, height: orgRect.height) let lowerPath = UIBezierPath(roundedRect: lowerRect, cornerRadius: cornerRadius) ctx.addPath(lowerPath.cgPath) ctx.fillPath() // Fill the upper track range ctx.setFillColor(slider.upperTrackHighlightTintColor.cgColor) let upperRect = CGRect(x: upperValuePosition, y: orgRect.y, width: orgRect.width - upperValuePosition, height: orgRect.height) let upperPath = UIBezierPath(roundedRect: upperRect, cornerRadius: cornerRadius) ctx.addPath(upperPath.cgPath) ctx.fillPath() // Fill the highlighted range ctx.setFillColor(slider.trackHighlightTintColor.cgColor) let rect = CGRect(x: lowerValuePosition, y: orgRect.y, width: upperValuePosition - lowerValuePosition, height: orgRect.height) ctx.fill(rect) } } } public class RangeSliderThumbLayer: CALayer { /// owner slider weak var rangeSlider: RangeSlider? /// whether this thumb is currently highlighted i.e. touched by user public var highlighted: Bool = false { didSet { setNeedsDisplay() } } /// stroke color public var strokeColor: UIColor = UIColor.gray { didSet { setNeedsDisplay() } } /// highlightedColor color public var highlightedColor: UIColor = UIColor(white: 0.0, alpha: 0.1) { didSet { setNeedsDisplay() } } /// line width public var lineWidth: CGFloat = 0.5 { didSet { setNeedsDisplay() } } /// image public var image: UIImage?{ didSet { setNeedsDisplay() } } override public func draw(in ctx: CGContext) { // Clip if let slider = rangeSlider { // clip let thumbFrame = bounds.insetBy(dx: 0.0, dy: 0.0) let cornerRadius = thumbFrame.height * slider.curvaceousness / 2.0 let thumbPath = UIBezierPath(roundedRect: thumbFrame, cornerRadius: cornerRadius) // Image if image != nil { ctx.saveGState() ctx.translateBy(x: 0, y: image!.size.height) ctx.scaleBy(x: 1.0, y: -1.0) ctx.draw(image!.cgImage!, in: CGRect(x: (bounds.w - image!.size.width)/2, y: -(bounds.h - image!.size.height)/2, w: image!.size.width, h: image!.size.height)) ctx.restoreGState() }else{ // Fill ctx.setFillColor(slider.thumbTintColor.cgColor) ctx.addPath(thumbPath.cgPath) ctx.fillPath() // Outline ctx.setStrokeColor(strokeColor.cgColor) ctx.setLineWidth(lineWidth) ctx.addPath(thumbPath.cgPath) ctx.strokePath() } if highlighted { ctx.setFillColor(highlightedColor.cgColor) ctx.addPath(thumbPath.cgPath) ctx.fillPath() } } } }
f96c112942bfd9bbbca1760aea0cf22e
33.273381
174
0.570109
false
false
false
false
zhenghuadong11/firstGitHub
refs/heads/master
旅游app_useSwift/旅游app_useSwift/MYHeaderForBuyView.swift
apache-2.0
1
// // MYHeaderForBuyView.swift // 旅游app_useSwift // // Created by zhenghuadong on 16/4/18. // Copyright © 2016年 zhenghuadong. All rights reserved. // import Foundation import UIKit class MYHeaderForBuyView:UIView { var _moneyLabel:UILabel = UILabel() var _buyButton:UIButton = UIButton() var _viewController:UIViewController? override func layoutSubviews() { _moneyLabel.snp_makeConstraints { (make) in make.top.bottom.equalTo(self) make.left.equalTo(self).offset(10) make.width.equalTo(self).multipliedBy(0.3) } _buyButton.snp_makeConstraints { (make) in make.top.right.equalTo(self).offset(10) make.bottom.equalTo(self).offset(-10) make.width.equalTo(self).multipliedBy(0.35) } } func buyButtonClick() -> Void { if MYMineModel._shareMineModel.name == nil { _loginClick(_viewController!) } if MYMineModel._shareMineModel.name == nil { return } MYZhifuModel.shareZhifuModel().user = MYMineModel._shareMineModel.name let zhifuDataViewController = MYZhifuDataSelectViewController() zhifuDataViewController.presentViewController = _viewController _viewController?.presentViewController(zhifuDataViewController, animated: true, completion: nil) } override func didMoveToSuperview() { self.addSubview(_moneyLabel) self.addSubview(_buyButton) _buyButton.addTarget(self, action: #selector(buyButtonClick), forControlEvents: UIControlEvents.TouchUpInside) _buyButton.backgroundColor = UIColor.orangeColor() _buyButton.setTitle("购买", forState: UIControlState.Normal) } }
d14ebb06a2ab50df87b06b50d143dcae
31.818182
118
0.643767
false
false
false
false
yageek/LazyBug
refs/heads/develop
LazyBug/LazyServerClient.swift
mit
1
// // LazyServerClient.swift // LazyBug // // Created by Yannick Heinrich on 10.05.17. // // import Foundation import ProcedureKit import ProcedureKitNetwork import Compression import SwiftProtobuf enum NetworkError: Error { case compression case apiError } final class ConvertFeedbackProcedure: Procedure, OutputProcedure { let formatter: DateFormatter = { let dateFormatter = DateFormatter() let enUSPosixLocale = Locale(identifier: "en_US_POSIX") dateFormatter.locale = enUSPosixLocale dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return dateFormatter }() let feedback: Feedback var output: Pending<ProcedureResult<Data>> = .pending init(feedback: Feedback) { self.feedback = feedback super.init() name = "net.yageek.lazybug.convertFeedback.\(feedback.identifier ?? "Unknown")" } override func execute() { guard !isCancelled else { self.finish(); return } do { var request = Lazybug_Feedback() request.identifier = feedback.identifier! request.creationDate = formatter.string(from: feedback.createdDate! as Date) request.content = feedback.content! if let meta = feedback.meta { request.meta = meta as Data } request.snapshot = feedback.snapshot! as Data let data = try request.serializedData() self.finish(withResult: .success(data)) } catch let error { Log.error("Error during marshalling: \(error)") self.finish(withError: error) } } } final class CompressDataProcedure: Procedure, InputProcedure, OutputProcedure { private var compressBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 4096) var input: Pending<Data> = .pending var output: Pending<ProcedureResult<Data>> = .pending override func execute() { guard !isCancelled else { self.finish(); return } guard let data = input.value else { self.finish(withError: ProcedureKitError.dependenciesFailed()) return } var result: Int = 0 data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in result = compression_encode_buffer(compressBuffer, 4096, bytes, data.count, nil, COMPRESSION_LZFSE) } if result == 0 { self.finish(withError: NetworkError.compression) } else { let data = Data(bytes: compressBuffer, count: result) self.finish(withResult: .success(data)) } } } final class ValidAPICode: Procedure, InputProcedure { var input: Pending<HTTPPayloadResponse<Data>> = .pending override func execute() { guard !isCancelled else { self.finish(); return } guard let result = input.value else { self.finish(withError: ProcedureKitError.requirementNotSatisfied()) return } switch result.response.statusCode { case 200..<300: self.finish() default: self.finish(withError: NetworkError.apiError) } } } final class LazyServerClient: FeedbackServerClient { let queue: ProcedureQueue = { let queue = ProcedureQueue() queue.qualityOfService = .background queue.name = "net.yageek.lazybug.lazyserverclient" return queue }() let url: URL init(url: URL) { self.url = url } func sendFeedback(feedback: Feedback, completion: @escaping (Error?) -> Void) { var httpRequest = URLRequest(url: url.appendingPathComponent("/feedbacks")) httpRequest.httpMethod = "PUT" let convert = ConvertFeedbackProcedure(feedback: feedback) let transform = TransformProcedure { return HTTPPayloadRequest(payload: $0, request: httpRequest) }.injectResult(from: convert) let network = NetworkUploadProcedure(session: URLSession.shared).injectResult(from: transform) let valid = ValidAPICode().injectResult(from: network) valid.addDidFinishBlockObserver { (_, errors) in completion(errors.first) } queue.add(operations: convert, transform, network, valid) } }
388e85114cd84f36d0b62fe0fc4603d5
28.631944
135
0.637919
false
false
false
false
marklin2012/iOS_Animation
refs/heads/master
Section4/Chapter21/O2Cook_challenge/O2Cook/ViewController.swift
mit
2
// // ViewController.swift // O2Cook // // Created by O2.LinYi on 16/3/21. // Copyright © 2016年 jd.com. All rights reserved. // import UIKit let herbs = HerbModel.all() class ViewController: UIViewController { @IBOutlet var listView: UIScrollView! @IBOutlet var bgImage: UIImageView! var selectedImage: UIImageView? let transition = PopAnimator() // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() if listView.subviews.count < herbs.count { listView.viewWithTag(0)?.tag = 1000 // prevent confusion when looking up images setupList() } transition.dismissCompletion = { self.selectedImage!.hidden = false } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } // MARK: - view setup // add all images to the list func setupList() { for var i=0; i < herbs.count; i++ { // create image view let imageView = UIImageView(image: UIImage(named: herbs[i].image)) imageView.tag = i + 100 imageView.contentMode = .ScaleAspectFill imageView.userInteractionEnabled = true imageView.layer.cornerRadius = 20 imageView.layer.masksToBounds = true listView.addSubview(imageView) // attach tap detector imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "didTapImageView:")) } listView.backgroundColor = UIColor.clearColor() positionListItems() } // position all images inside the list func positionListItems() { let itemHeight: CGFloat = listView.frame.height * 1.33 let aspectRatio = UIScreen.mainScreen().bounds.height / UIScreen.mainScreen().bounds.width let itemWidth: CGFloat = itemHeight / aspectRatio print("width: \(itemWidth)") let horizontalPadding: CGFloat = 10.0 for var i = 0; i < herbs.count; i++ { let imageView = listView.viewWithTag(i+100) as! UIImageView imageView.frame = CGRect(x: CGFloat(i+1) * horizontalPadding + CGFloat(i) * itemWidth, y: 0, width: itemWidth, height: itemHeight) print("frame: \(imageView.frame)") } listView.contentSize = CGSize(width: CGFloat(herbs.count) * (itemWidth+horizontalPadding) + horizontalPadding, height: 0) } func didTapImageView(tap: UITapGestureRecognizer) { selectedImage = tap.view as? UIImageView let index = tap.view!.tag - 100 let selectedHerb = herbs[index] //present details view controller let herbDetails = storyboard!.instantiateViewControllerWithIdentifier("HerbDetailsViewController") as! HerbDetailsViewController herbDetails.herb = selectedHerb herbDetails.transitioningDelegate = self presentViewController(herbDetails, animated: true, completion: nil) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition({ (context) -> Void in self.bgImage.alpha = (size.width > size.height) ? 0.25 : 0.55 self.positionListItems() }, completion: nil) } } extension ViewController: UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.originFrame = selectedImage!.superview!.convertRect(selectedImage!.frame, toView: nil) transition.presenting = true selectedImage!.hidden = true return transition } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.presenting = false return transition } }
b7e5d2a47b20006a5a4b640e1a8f066b
33.780488
217
0.650771
false
false
false
false
macemmi/HBCI4Swift
refs/heads/master
HBCI4Swift/HBCI4Swift/Source/Orders/HBCICamtStatementsOrder.swift
gpl-2.0
1
// // HBCICamtStatementsOrder.swift // HBCI4Swift // // Created by Frank Emminghaus on 01.07.20. // Copyright © 2020 Frank Emminghaus. All rights reserved. // import Foundation open class HBCICamtStatementsOrder: HBCIOrder { public let account:HBCIAccount; open var statements:Array<HBCIStatement> open var dateFrom:Date? open var dateTo:Date? var offset:String? var camtFormat:String? var bookedPart:Data? var isPartial = false; var partNumber = 1; public init?(message: HBCICustomMessage, account:HBCIAccount) { self.account = account; self.statements = Array<HBCIStatement>(); super.init(name: "CamtStatements", message: message); if self.segment == nil { return nil; } } open func enqueue() ->Bool { // check if order is supported if !user.parameters.isOrderSupportedForAccount(self, number: account.number, subNumber: account.subNumber) { logInfo(self.name + " is not supported for account " + account.number); return false; } var values = Dictionary<String,Any>(); // check if SEPA version is supported (only globally for bank - // later we check if account supports this as well if account.iban == nil || account.bic == nil { logInfo("Account has no IBAN or BIC information"); return false; } values = ["KTV.bic":account.bic!, "KTV.iban":account.iban!, "KTV.number":account.number, "KTV.KIK.country":"280", "KTV.KIK.blz":account.bankCode, "allaccounts":false]; if var date = dateFrom { if let maxdays = user.parameters.maxStatementDays() { let currentDate = Date(); let minDate = currentDate.addingTimeInterval((Double)((maxdays-1) * 24 * 3600 * -1)); if minDate > date { date = minDate; } } values["startdate"] = date; } if let date = dateTo { values["enddate"] = date; } if let ofs = offset { values["offset"] = ofs; } let formats = user.parameters.camtFormats(); guard formats.count > 0 else { logInfo("No supported camt formats"); return false; } for format in formats { if format.hasSuffix("052.001.02") || format.hasSuffix("052.001.08") { camtFormat = format; //break; } else { logDebug("Camt format "+format+" is not supported"); } } guard let format = camtFormat else { logInfo("No supported Camt formats found"); return false; } values["format"] = format; if !segment.setElementValues(values) { logInfo("CamtStatements Order values could not be set"); return false; } // add to message return msg.addOrder(self); } func getOutstandingPart(_ offset:String) ->Data? { do { if let msg = HBCICustomMessage.newInstance(msg.dialog) { if let order = HBCICamtStatementsOrder(message: msg, account: self.account) { order.dateFrom = self.dateFrom; order.dateTo = self.dateTo; order.offset = offset; order.isPartial = true; order.partNumber = self.partNumber + 1; if !order.enqueue() { return nil; } _ = try msg.send(); return order.bookedPart; } } } catch { // we don't do anything in case of errors } return nil; } override open func updateResult(_ result: HBCIResultMessage) { var parser:HBCICamtParser! super.updateResult(result); // check whether result is incomplete self.offset = nil; for response in result.segmentResponses { if response.code == "3040" && response.parameters.count > 0 { self.offset = response.parameters[0]; } } if camtFormat!.hasSuffix("052.001.02") { parser = HBCICamtParser_052_001_02(); } else { parser = HBCICamtParser_052_001_08(); } // now parse statements self.statements.removeAll(); for seg in resultSegments { if let booked_list = seg.elementValuesForPath("booked.statement") as? [Data] { for var booked in booked_list { // check whether result is incomplete if let offset = self.offset { if partNumber >= 100 { // we stop here - too many statement parts logInfo("Too many statement parts but we still get response 3040 - we stop here") } else { if let part2 = getOutstandingPart(offset) { booked.append(part2); } } } // check if we are a part or the original order if isPartial { self.bookedPart = booked; } else { if let statements = parser.parse(account, data: booked, isPreliminary: false) { self.statements.append(contentsOf: statements); } } } } if let notbooked = seg.elementValueForPath("notbooked") as? Data { if let statements = parser.parse(account, data: notbooked, isPreliminary: true) { self.statements.append(contentsOf: statements); } } } } }
f27f04e4efe19877a5ee815b07208e7d
33.891429
175
0.504586
false
false
false
false
soso1617/iCalendar
refs/heads/master
Calendar/Utility/DateConversion.swift
mit
1
// // DateConversion.swift // Calendar // // Created by Zhang, Eric X. on 5/6/17. // Copyright © 2017 ShangHe. All rights reserved. // import Foundation class DateConversion { // // lazy init // static var calender: Calendar = { return Calendar.init(identifier: .gregorian) }() // // lazy init // static var timeZoneDateFormatter: DateFormatter = { let retDateFormatter = DateFormatter.init() // // init dateformatter for global // retDateFormatter.timeStyle = .long retDateFormatter.dateStyle = .short // // use current timezone for display // retDateFormatter.timeZone = TimeZone.current return retDateFormatter }() // // lazy init // static var ISO8601DateFormatter: DateFormatter = { let retDateFormatter = DateFormatter.init() retDateFormatter.locale = Locale.init(identifier: "en_US_POSIX") retDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ" return retDateFormatter }() // // lazy init // static var HHMMDateFormatter: DateFormatter = { let retDateFormatter = DateFormatter.init() retDateFormatter.locale = Locale.current retDateFormatter.timeZone = TimeZone.current retDateFormatter.dateFormat = "HH:mm" return retDateFormatter }() // // lazy init // static var LongDateFormatter: DateFormatter = { let retDateFormatter = DateFormatter.init() retDateFormatter.locale = Locale.current retDateFormatter.timeZone = TimeZone.current retDateFormatter.timeStyle = .none retDateFormatter.dateStyle = .long return retDateFormatter }() // // convert kind formatter of "2016-11-30T09:20:30+08:00" to date // class func dateFromISO8601String(_ dateString: String) -> Date? { return ISO8601DateFormatter.date(from: dateString) } // // convert timestamp to date string // class func dateStringWithSystemSpecifiedTimeZoneFromTimeStamp(_ timeStamp: Double) -> String { return timeZoneDateFormatter.string(from: Date.init(timeIntervalSince1970: timeStamp)) } // // convert date to date string // class func dateStringWithSystemSpecifiedTimeZoneFromDate(_ date: Date) -> String { return timeZoneDateFormatter.string(from: date) } // // convert date to "HH:MM" // class func date2MMSSFromDate(_ date: Date) -> String { return HHMMDateFormatter.string(from: date) } // // convert date to long date string // class func date2LongStringFromDate(_ date: Date) -> String { return LongDateFormatter.string(from: date) } // // check to date is in same day // class func compare2DateIsSame(_ date: Date, comparedDate: Date) -> Bool { let component1 = self.calender.dateComponents([.year, .month, .day], from: date) let component2 = self.calender.dateComponents([.year, .month, .day], from: comparedDate) return ((component1.day! == component2.day!) && (component1.month! == component2.month!) && (component1.year! == component2.year!)) } }
292ea761db1c4442b196171501461184
25.867188
139
0.59843
false
false
false
false
EdwaRen/Recycle_Can_iOS
refs/heads/master
Recycle_Can/Recycle Can/ViewControllerAbout.swift
mit
1
// // ViewControllerAbout.swift // Recycle Can // // Created by - on 2017/06/13. // Copyright © 2017 Recycle Canada. All rights reserved. // import UIKit import MessageUI import Foundation import Social class ViewControllerAbout: UIViewController, MFMailComposeViewControllerDelegate { @IBOutlet weak var logoImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() let screenSize: CGRect = UIScreen.main.bounds let screenWidth = screenSize.width let screenHeight = screenSize.height if (screenHeight <= 480) { print(screenHeight) print(screenWidth) print("Success!") logoImage.alpha = 0 } else { print("Not an iPhone 4s... or this does not work :(") } } @IBAction func RateBtn(_ sender: Any) { let alert = UIAlertController(title: "Rate This App", message: "This will open up the App Store", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Go", style: UIAlertActionStyle.default) { _ in // Open App in AppStore let iLink = "https://itunes.apple.com/us/app/recycle-can/id1248915926?ls=1&mt=8" UIApplication.shared.openURL(NSURL(string: iLink)! as URL) } ) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } @IBAction func WebBtn(_ sender: Any) { let iLink = "http://www.recyclecan.ca" UIApplication.shared.openURL(NSURL(string: iLink)! as URL) } @IBAction func FacebookBtn(_ sender: Any) { // Check if Facebook is available if (SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook)) { // Create the post let post = SLComposeViewController(forServiceType: (SLServiceTypeFacebook)) post?.setInitialText("\n\nhttps://itunes.apple.com/us/app/recycle-can/id1248915926?ls=1&mt=8") post?.add(UIImage(named: "Screenshot_5")) self.present(post!, animated: true, completion: nil) } else { // Facebook not available. Show a warning let alert = UIAlertController(title: "Facebook", message: "Facebook not available", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } @IBAction func MailBtn(_ sender: Any) { // Check if Mail is available let mailComposeViewController = configuredMailComposeViewController() if MFMailComposeViewController.canSendMail() { self.present(mailComposeViewController, animated: true, completion: nil) } else { self.showSendMailErrorAlert() } } func configuredMailComposeViewController() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property // mailComposerVC.setToRecipients(["[email protected]"]) mailComposerVC.setSubject("Check Out This Recycling App!") mailComposerVC.setMessageBody("\n\n\nhttps://itunes.apple.com/us/app/recycle-can/id1248915926?ls=1&mt=8", isHTML: false) let imageData = UIImagePNGRepresentation(UIImage(named: "Screenshot_5")!) mailComposerVC.addAttachmentData(imageData!, mimeType: "image/png", fileName: "Image") return mailComposerVC } func showSendMailErrorAlert() { let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK") sendMailErrorAlert.show() } // MARK: MFMailComposeViewControllerDelegate Method func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } }
8ff0d31348fefdbcb6096fa846c94460
41.359223
213
0.659638
false
false
false
false
JaSpa/swift
refs/heads/master
test/SILGen/builtins.swift
apache-2.0
3
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen -parse-stdlib %s -disable-objc-attr-requires-foundation-module | %FileCheck %s // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-sil -Onone -parse-stdlib %s -disable-objc-attr-requires-foundation-module | %FileCheck -check-prefix=CANONICAL %s import Swift protocol ClassProto : class { } struct Pointer { var value: Builtin.RawPointer } // CHECK-LABEL: sil hidden @_T08builtins3foo{{[_0-9a-zA-Z]*}}F func foo(_ x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 { // CHECK: builtin "cmp_eq_Int1" return Builtin.cmp_eq_Int1(x, y) } // CHECK-LABEL: sil hidden @_T08builtins8load_pod{{[_0-9a-zA-Z]*}}F func load_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @_T08builtins8load_obj{{[_0-9a-zA-Z]*}}F func load_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @_T08builtins12load_raw_pod{{[_0-9a-zA-Z]*}}F func load_raw_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadRaw(x) } // CHECK-LABEL: sil hidden @_T08builtins12load_raw_obj{{[_0-9a-zA-Z]*}}F func load_raw_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadRaw(x) } // CHECK-LABEL: sil hidden @_T08builtins8load_gen{{[_0-9a-zA-Z]*}}F func load_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [[ADDR]] to [initialization] {{%.*}} return Builtin.load(x) } // CHECK-LABEL: sil hidden @_T08builtins8move_pod{{[_0-9a-zA-Z]*}}F func move_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @_T08builtins8move_obj{{[_0-9a-zA-Z]*}}F func move_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [take] [[ADDR]] // CHECK-NOT: copy_value [[VAL]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @_T08builtins8move_gen{{[_0-9a-zA-Z]*}}F func move_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [take] [[ADDR]] to [initialization] {{%.*}} return Builtin.take(x) } // CHECK-LABEL: sil hidden @_T08builtins11destroy_pod{{[_0-9a-zA-Z]*}}F func destroy_pod(_ x: Builtin.RawPointer) { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box // CHECK-NOT: pointer_to_address // CHECK-NOT: destroy_addr // CHECK-NOT: destroy_value // CHECK: destroy_value [[XBOX]] : ${{.*}}{ // CHECK-NOT: destroy_value return Builtin.destroy(Builtin.Int64, x) // CHECK: return } // CHECK-LABEL: sil hidden @_T08builtins11destroy_obj{{[_0-9a-zA-Z]*}}F func destroy_obj(_ x: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(Builtin.NativeObject, x) } // CHECK-LABEL: sil hidden @_T08builtins11destroy_gen{{[_0-9a-zA-Z]*}}F func destroy_gen<T>(_ x: Builtin.RawPointer, _: T) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(T.self, x) } // CHECK-LABEL: sil hidden @_T08builtins10assign_pod{{[_0-9a-zA-Z]*}}F func assign_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { var x = x var y = y // CHECK: alloc_box // CHECK: alloc_box // CHECK-NOT: alloc_box // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: assign {{%.*}} to [[ADDR]] // CHECK: destroy_value // CHECK: destroy_value // CHECK-NOT: destroy_value Builtin.assign(x, y) // CHECK: return } // CHECK-LABEL: sil hidden @_T08builtins10assign_obj{{[_0-9a-zA-Z]*}}F func assign_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: assign {{%.*}} to [[ADDR]] // CHECK: destroy_value Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_T08builtins12assign_tuple{{[_0-9a-zA-Z]*}}F func assign_tuple(_ x: (Builtin.Int64, Builtin.NativeObject), y: Builtin.RawPointer) { var x = x var y = y // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*(Builtin.Int64, Builtin.NativeObject) // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: destroy_value Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_T08builtins10assign_gen{{[_0-9a-zA-Z]*}}F func assign_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [take] {{%.*}} to [[ADDR]] : Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_T08builtins8init_pod{{[_0-9a-zA-Z]*}}F func init_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: store {{%.*}} to [trivial] [[ADDR]] // CHECK-NOT: destroy_value [[ADDR]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @_T08builtins8init_obj{{[_0-9a-zA-Z]*}}F func init_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK-NOT: load [[ADDR]] // CHECK: store [[SRC:%.*]] to [init] [[ADDR]] // CHECK-NOT: destroy_value [[SRC]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @_T08builtins8init_gen{{[_0-9a-zA-Z]*}}F func init_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [[OTHER_LOC:%.*]] to [initialization] [[ADDR]] // CHECK: destroy_addr [[OTHER_LOC]] Builtin.initialize(x, y) } class C {} class D {} // CHECK-LABEL: sil hidden @_T08builtins22class_to_native_object{{[_0-9a-zA-Z]*}}F func class_to_native_object(_ c:C) -> Builtin.NativeObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToNativeObject(c) } // CHECK-LABEL: sil hidden @_T08builtins23class_to_unknown_object{{[_0-9a-zA-Z]*}}F func class_to_unknown_object(_ c:C) -> Builtin.UnknownObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToUnknownObject(c) } // CHECK-LABEL: sil hidden @_T08builtins32class_archetype_to_native_object{{[_0-9a-zA-Z]*}}F func class_archetype_to_native_object<T : C>(_ t: T) -> Builtin.NativeObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToNativeObject(t) } // CHECK-LABEL: sil hidden @_T08builtins33class_archetype_to_unknown_object{{[_0-9a-zA-Z]*}}F func class_archetype_to_unknown_object<T : C>(_ t: T) -> Builtin.UnknownObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToUnknownObject(t) } // CHECK-LABEL: sil hidden @_T08builtins34class_existential_to_native_object{{[_0-9a-zA-Z]*}}F func class_existential_to_native_object(_ t:ClassProto) -> Builtin.NativeObject { // CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto // CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.NativeObject return Builtin.castToNativeObject(t) } // CHECK-LABEL: sil hidden @_T08builtins35class_existential_to_unknown_object{{[_0-9a-zA-Z]*}}F func class_existential_to_unknown_object(_ t:ClassProto) -> Builtin.UnknownObject { // CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto // CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.UnknownObject return Builtin.castToUnknownObject(t) } // CHECK-LABEL: sil hidden @_T08builtins24class_from_native_object{{[_0-9a-zA-Z]*}}F func class_from_native_object(_ p: Builtin.NativeObject) -> C { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_T08builtins25class_from_unknown_object{{[_0-9a-zA-Z]*}}F func class_from_unknown_object(_ p: Builtin.UnknownObject) -> C { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_T08builtins34class_archetype_from_native_object{{[_0-9a-zA-Z]*}}F func class_archetype_from_native_object<T : C>(_ p: Builtin.NativeObject) -> T { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $T // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_T08builtins35class_archetype_from_unknown_object{{[_0-9a-zA-Z]*}}F func class_archetype_from_unknown_object<T : C>(_ p: Builtin.UnknownObject) -> T { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $T // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_T08builtins41objc_class_existential_from_native_object{{[_0-9a-zA-Z]*}}F func objc_class_existential_from_native_object(_ p: Builtin.NativeObject) -> AnyObject { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $AnyObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_T08builtins42objc_class_existential_from_unknown_object{{[_0-9a-zA-Z]*}}F func objc_class_existential_from_unknown_object(_ p: Builtin.UnknownObject) -> AnyObject { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $AnyObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_T08builtins20class_to_raw_pointer{{[_0-9a-zA-Z]*}}F func class_to_raw_pointer(_ c: C) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } func class_archetype_to_raw_pointer<T : C>(_ t: T) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(t) } protocol CP: class {} func existential_to_raw_pointer(_ p: CP) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(p) } // CHECK-LABEL: sil hidden @_T08builtins18obj_to_raw_pointer{{[_0-9a-zA-Z]*}}F func obj_to_raw_pointer(_ c: Builtin.NativeObject) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } // CHECK-LABEL: sil hidden @_T08builtins22class_from_raw_pointer{{[_0-9a-zA-Z]*}}F func class_from_raw_pointer(_ p: Builtin.RawPointer) -> C { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $C // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } func class_archetype_from_raw_pointer<T : C>(_ p: Builtin.RawPointer) -> T { return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_T08builtins20obj_from_raw_pointer{{[_0-9a-zA-Z]*}}F func obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.NativeObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_T08builtins28unknown_obj_from_raw_pointer{{[_0-9a-zA-Z]*}}F func unknown_obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.UnknownObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.UnknownObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_T08builtins28existential_from_raw_pointer{{[_0-9a-zA-Z]*}}F func existential_from_raw_pointer(_ p: Builtin.RawPointer) -> AnyObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $AnyObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_T08builtins9gep_raw64{{[_0-9a-zA-Z]*}}F func gep_raw64(_ p: Builtin.RawPointer, i: Builtin.Int64) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gepRaw_Int64(p, i) } // CHECK-LABEL: sil hidden @_T08builtins9gep_raw32{{[_0-9a-zA-Z]*}}F func gep_raw32(_ p: Builtin.RawPointer, i: Builtin.Int32) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gepRaw_Int32(p, i) } // CHECK-LABEL: sil hidden @_T08builtins3gep{{[_0-9a-zA-Z]*}}F func gep<Elem>(_ p: Builtin.RawPointer, i: Builtin.Word, e: Elem.Type) -> Builtin.RawPointer { // CHECK: [[P2A:%.*]] = pointer_to_address %0 // CHECK: [[GEP:%.*]] = index_addr [[P2A]] : $*Elem, %1 : $Builtin.Word // CHECK: [[A2P:%.*]] = address_to_pointer [[GEP]] // CHECK: return [[A2P]] return Builtin.gep_Word(p, i, e) } public final class Header { } // CHECK-LABEL: sil hidden @_T08builtins20allocWithTailElems_1{{[_0-9a-zA-Z]*}}F func allocWithTailElems_1<T>(n: Builtin.Word, ty: T.Type) -> Header { // CHECK: [[M:%.*]] = metatype $@thick Header.Type // CHECK: [[A:%.*]] = alloc_ref [tail_elems $T * %0 : $Builtin.Word] $Header // CHECK: return [[A]] return Builtin.allocWithTailElems_1(Header.self, n, ty) } // CHECK-LABEL: sil hidden @_T08builtins20allocWithTailElems_3{{[_0-9a-zA-Z]*}}F func allocWithTailElems_3<T1, T2, T3>(n1: Builtin.Word, ty1: T1.Type, n2: Builtin.Word, ty2: T2.Type, n3: Builtin.Word, ty3: T3.Type) -> Header { // CHECK: [[M:%.*]] = metatype $@thick Header.Type // CHECK: [[A:%.*]] = alloc_ref [tail_elems $T1 * %0 : $Builtin.Word] [tail_elems $T2 * %2 : $Builtin.Word] [tail_elems $T3 * %4 : $Builtin.Word] $Header // CHECK: return [[A]] return Builtin.allocWithTailElems_3(Header.self, n1, ty1, n2, ty2, n3, ty3) } // CHECK-LABEL: sil hidden @_T08builtins16projectTailElems{{[_0-9a-zA-Z]*}}F func projectTailElems<T>(h: Header, ty: T.Type) -> Builtin.RawPointer { // CHECK: bb0([[ARG1:%.*]] : $Header // CHECK: [[ARG1_COPY:%.*]] = copy_value [[ARG1]] // CHECK: [[TA:%.*]] = ref_tail_addr [[ARG1_COPY]] : $Header // CHECK: [[A2P:%.*]] = address_to_pointer [[TA]] // CHECK: destroy_value [[ARG1_COPY]] // CHECK: destroy_value [[ARG1]] // CHECK: return [[A2P]] return Builtin.projectTailElems(h, ty) } // CHECK: } // end sil function '_T08builtins16projectTailElemsBpAA6HeaderC1h_xm2tytlF' // CHECK-LABEL: sil hidden @_T08builtins11getTailAddr{{[_0-9a-zA-Z]*}}F func getTailAddr<T1, T2>(start: Builtin.RawPointer, i: Builtin.Word, ty1: T1.Type, ty2: T2.Type) -> Builtin.RawPointer { // CHECK: [[P2A:%.*]] = pointer_to_address %0 // CHECK: [[TA:%.*]] = tail_addr [[P2A]] : $*T1, %1 : $Builtin.Word, $T2 // CHECK: [[A2P:%.*]] = address_to_pointer [[TA]] // CHECK: return [[A2P]] return Builtin.getTailAddr_Word(start, i, ty1, ty2) } // CHECK-LABEL: sil hidden @_T08builtins8condfail{{[_0-9a-zA-Z]*}}F func condfail(_ i: Builtin.Int1) { Builtin.condfail(i) // CHECK: cond_fail {{%.*}} : $Builtin.Int1 } struct S {} @objc class O {} @objc protocol OP1 {} @objc protocol OP2 {} protocol P {} // CHECK-LABEL: sil hidden @_T08builtins10canBeClass{{[_0-9a-zA-Z]*}}F func canBeClass<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(O.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(OP1.self) // -- FIXME: 'OP1 & OP2' doesn't parse as a value typealias ObjCCompo = OP1 & OP2 // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(ObjCCompo.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(S.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(C.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(P.self) typealias MixedCompo = OP1 & P // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompo.self) // CHECK: builtin "canBeClass"<T> Builtin.canBeClass(T.self) } // FIXME: "T.Type.self" does not parse as an expression // CHECK-LABEL: sil hidden @_T08builtins18canBeClassMetatype{{[_0-9a-zA-Z]*}}F func canBeClassMetatype<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 0 typealias OT = O.Type Builtin.canBeClass(OT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias OP1T = OP1.Type Builtin.canBeClass(OP1T.self) // -- FIXME: 'OP1 & OP2' doesn't parse as a value typealias ObjCCompoT = (OP1 & OP2).Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(ObjCCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias ST = S.Type Builtin.canBeClass(ST.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias CT = C.Type Builtin.canBeClass(CT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias PT = P.Type Builtin.canBeClass(PT.self) typealias MixedCompoT = (OP1 & P).Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias TT = T.Type Builtin.canBeClass(TT.self) } // CHECK-LABEL: sil hidden @_T08builtins11fixLifetimeyAA1CCF : $@convention(thin) (@owned C) -> () { func fixLifetime(_ c: C) { // CHECK: bb0([[ARG:%.*]] : $C): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: fix_lifetime [[ARG_COPY]] : $C // CHECK: destroy_value [[ARG_COPY]] // CHECK: destroy_value [[ARG]] Builtin.fixLifetime(c) } // CHECK: } // end sil function '_T08builtins11fixLifetimeyAA1CCF' // CHECK-LABEL: sil hidden @_T08builtins20assert_configuration{{[_0-9a-zA-Z]*}}F func assert_configuration() -> Builtin.Int32 { return Builtin.assert_configuration() // CHECK: [[APPLY:%.*]] = builtin "assert_configuration"() : $Builtin.Int32 // CHECK: return [[APPLY]] : $Builtin.Int32 } // CHECK-LABEL: sil hidden @_T08builtins17assumeNonNegativeBwBwF func assumeNonNegative(_ x: Builtin.Word) -> Builtin.Word { return Builtin.assumeNonNegative_Word(x) // CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word // CHECK: return [[APPLY]] : $Builtin.Word } // CHECK-LABEL: sil hidden @_T08builtins11autoreleaseyAA1OCF : $@convention(thin) (@owned O) -> () { // ==> SEMANTIC ARC TODO: This will be unbalanced... should we allow it? // CHECK: bb0([[ARG:%.*]] : $O): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: autorelease_value [[ARG_COPY]] // CHECK: destroy_value [[ARG_COPY]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T08builtins11autoreleaseyAA1OCF' func autorelease(_ o: O) { Builtin.autorelease(o) } // The 'unreachable' builtin is emitted verbatim by SILGen and eliminated during // diagnostics. // CHECK-LABEL: sil hidden @_T08builtins11unreachable{{[_0-9a-zA-Z]*}}F // CHECK: builtin "unreachable"() // CHECK: return // CANONICAL-LABEL: sil hidden @_T08builtins11unreachableyyF : $@convention(thin) () -> () { func unreachable() { Builtin.unreachable() } // CHECK-LABEL: sil hidden @_T08builtins15reinterpretCastBw_AA1DCAA1CCSgAFtAF_Bw1xtF : $@convention(thin) (@owned C, Builtin.Word) -> (Builtin.Word, @owned D, @owned Optional<C>, @owned C) // CHECK: bb0([[ARG1:%.*]] : $C, [[ARG2:%.*]] : $Builtin.Word): // CHECK-NEXT: debug_value // CHECK-NEXT: debug_value // CHECK-NEXT: [[ARG1_COPY1:%.*]] = copy_value [[ARG1]] : $C // CHECK-NEXT: [[ARG1_TRIVIAL:%.*]] = unchecked_trivial_bit_cast [[ARG1_COPY1]] : $C to $Builtin.Word // CHECK-NEXT: [[ARG1_COPY2:%.*]] = copy_value [[ARG1]] : $C // CHECK-NEXT: [[ARG1_COPY2_CASTED:%.*]] = unchecked_ref_cast [[ARG1_COPY2]] : $C to $D // CHECK-NEXT: [[ARG1_COPY3:%.*]] = copy_value [[ARG1]] // CHECK-NEXT: [[ARG1_COPY3_CAST:%.*]] = unchecked_ref_cast [[ARG1_COPY3]] : $C to $Optional<C> // CHECK-NEXT: [[ARG2_OBJ_CASTED:%.*]] = unchecked_bitwise_cast [[ARG2]] : $Builtin.Word to $C // CHECK-NEXT: [[ARG2_OBJ_CASTED_COPIED:%.*]] = copy_value [[ARG2_OBJ_CASTED]] : $C // CHECK-NEXT: destroy_value [[ARG1_COPY1]] // CHECK-NEXT: destroy_value [[ARG1]] // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ARG1_TRIVIAL]] : $Builtin.Word, [[ARG1_COPY2_CASTED]] : $D, [[ARG1_COPY3_CAST]] : $Optional<C>, [[ARG2_OBJ_CASTED_COPIED:%.*]] : $C) // CHECK: return [[RESULT]] func reinterpretCast(_ c: C, x: Builtin.Word) -> (Builtin.Word, D, C?, C) { return (Builtin.reinterpretCast(c) as Builtin.Word, Builtin.reinterpretCast(c) as D, Builtin.reinterpretCast(c) as C?, Builtin.reinterpretCast(x) as C) } // CHECK-LABEL: sil hidden @_T08builtins19reinterpretAddrOnly{{[_0-9a-zA-Z]*}}F func reinterpretAddrOnly<T, U>(_ t: T) -> U { // CHECK: unchecked_addr_cast {{%.*}} : $*T to $*U return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @_T08builtins28reinterpretAddrOnlyToTrivial{{[_0-9a-zA-Z]*}}F func reinterpretAddrOnlyToTrivial<T>(_ t: T) -> Int { // CHECK: [[ADDR:%.*]] = unchecked_addr_cast [[INPUT:%.*]] : $*T to $*Int // CHECK: [[VALUE:%.*]] = load [trivial] [[ADDR]] // CHECK: destroy_addr [[INPUT]] return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @_T08builtins27reinterpretAddrOnlyLoadable{{[_0-9a-zA-Z]*}}F func reinterpretAddrOnlyLoadable<T>(_ a: Int, _ b: T) -> (T, Int) { // CHECK: [[BUF:%.*]] = alloc_stack $Int // CHECK: store {{%.*}} to [trivial] [[BUF]] // CHECK: [[RES1:%.*]] = unchecked_addr_cast [[BUF]] : $*Int to $*T // CHECK: copy_addr [[RES1]] to [initialization] return (Builtin.reinterpretCast(a) as T, // CHECK: [[RES:%.*]] = unchecked_addr_cast {{%.*}} : $*T to $*Int // CHECK: load [trivial] [[RES]] Builtin.reinterpretCast(b) as Int) } // CHECK-LABEL: sil hidden @_T08builtins18castToBridgeObject{{[_0-9a-zA-Z]*}}F // CHECK: [[BO:%.*]] = ref_to_bridge_object {{%.*}} : $C, {{%.*}} : $Builtin.Word // CHECK: return [[BO]] func castToBridgeObject(_ c: C, _ w: Builtin.Word) -> Builtin.BridgeObject { return Builtin.castToBridgeObject(c, w) } // CHECK-LABEL: sil hidden @_T08builtins23castRefFromBridgeObject{{[_0-9a-zA-Z]*}}F // CHECK: bridge_object_to_ref [[BO:%.*]] : $Builtin.BridgeObject to $C func castRefFromBridgeObject(_ bo: Builtin.BridgeObject) -> C { return Builtin.castReferenceFromBridgeObject(bo) } // CHECK-LABEL: sil hidden @_T08builtins30castBitPatternFromBridgeObject{{[_0-9a-zA-Z]*}}F // CHECK: bridge_object_to_word [[BO:%.*]] : $Builtin.BridgeObject to $Builtin.Word // CHECK: destroy_value [[BO]] func castBitPatternFromBridgeObject(_ bo: Builtin.BridgeObject) -> Builtin.Word { return Builtin.castBitPatternFromBridgeObject(bo) } // CHECK-LABEL: sil hidden @_T08builtins8pinUnpin{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : $Builtin.NativeObject): // CHECK-NEXT: debug_value func pinUnpin(_ object : Builtin.NativeObject) { // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] : $Builtin.NativeObject // CHECK-NEXT: [[HANDLE:%.*]] = strong_pin [[ARG_COPY]] : $Builtin.NativeObject // CHECK-NEXT: debug_value // CHECK-NEXT: destroy_value [[ARG_COPY]] : $Builtin.NativeObject let handle : Builtin.NativeObject? = Builtin.tryPin(object) // CHECK-NEXT: [[HANDLE_COPY:%.*]] = copy_value [[HANDLE]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: strong_unpin [[HANDLE_COPY]] : $Optional<Builtin.NativeObject> // ==> SEMANTIC ARC TODO: This looks like a mispairing or a weird pairing. Builtin.unpin(handle) // CHECK-NEXT: tuple () // CHECK-NEXT: destroy_value [[HANDLE]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: destroy_value [[ARG]] : $Builtin.NativeObject // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] : $() } // ---------------------------------------------------------------------------- // isUnique variants // ---------------------------------------------------------------------------- // NativeObject // CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Optional<Builtin.NativeObject> // CHECK: return func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // NativeObject nonNull // CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Builtin.NativeObject): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Builtin.NativeObject // CHECK: return func isUnique(_ ref: inout Builtin.NativeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // NativeObject pinned // CHECK-LABEL: sil hidden @_T08builtins16isUniqueOrPinned{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>): // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Optional<Builtin.NativeObject> // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.NativeObject?) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // NativeObject pinned nonNull // CHECK-LABEL: sil hidden @_T08builtins16isUniqueOrPinned{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Builtin.NativeObject): // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Builtin.NativeObject // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.NativeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // UnknownObject (ObjC) // CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Optional<Builtin.UnknownObject>): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Optional<Builtin.UnknownObject> // CHECK: return func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) nonNull // CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Builtin.UnknownObject): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Builtin.UnknownObject // CHECK: return func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) pinned nonNull // CHECK-LABEL: sil hidden @_T08builtins16isUniqueOrPinned{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Builtin.UnknownObject): // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Builtin.UnknownObject // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.UnknownObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // BridgeObject nonNull // CHECK-LABEL: sil hidden @_T08builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Builtin.BridgeObject // CHECK: return func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // BridgeObject pinned nonNull // CHECK-LABEL: sil hidden @_T08builtins16isUniqueOrPinned{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Builtin.BridgeObject // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // BridgeObject nonNull native // CHECK-LABEL: sil hidden @_T08builtins15isUnique_native{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK: [[CAST:%.*]] = unchecked_addr_cast %0 : $*Builtin.BridgeObject to $*Builtin.NativeObject // CHECK: return func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique_native(&ref)) } // BridgeObject pinned nonNull native // CHECK-LABEL: sil hidden @_T08builtins23isUniqueOrPinned_native{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK: [[CAST:%.*]] = unchecked_addr_cast %0 : $*Builtin.BridgeObject to $*Builtin.NativeObject // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[CAST]] : $*Builtin.NativeObject // CHECK: return func isUniqueOrPinned_native(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned_native(&ref)) } // ---------------------------------------------------------------------------- // Builtin.castReference // ---------------------------------------------------------------------------- class A {} protocol PUnknown {} protocol PClass : class {} // CHECK-LABEL: sil hidden @_T08builtins19refcast_generic_any{{[_0-9a-zA-Z]*}}F // CHECK: unchecked_ref_cast_addr T in %{{.*}} : $*T to AnyObject in %{{.*}} : $*AnyObject func refcast_generic_any<T>(_ o: T) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_T08builtins17refcast_class_anys9AnyObject_pAA1ACF : // CHECK: bb0([[ARG:%.*]] : $A): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_CASTED:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $A to $AnyObject // CHECK: destroy_value [[ARG]] // CHECK: return [[ARG_COPY_CASTED]] // CHECK: } // end sil function '_T08builtins17refcast_class_anys9AnyObject_pAA1ACF' func refcast_class_any(_ o: A) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_T08builtins20refcast_punknown_any{{[_0-9a-zA-Z]*}}F // CHECK: unchecked_ref_cast_addr PUnknown in %{{.*}} : $*PUnknown to AnyObject in %{{.*}} : $*AnyObject func refcast_punknown_any(_ o: PUnknown) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_T08builtins18refcast_pclass_anys9AnyObject_pAA6PClass_pF : // CHECK: bb0([[ARG:%.*]] : $PClass): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_CAST:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $PClass to $AnyObject // CHECK: destroy_value [[ARG]] // CHECK: return [[ARG_COPY_CAST]] // CHECK: } // end sil function '_T08builtins18refcast_pclass_anys9AnyObject_pAA6PClass_pF' func refcast_pclass_any(_ o: PClass) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_T08builtins20refcast_any_punknown{{[_0-9a-zA-Z]*}}F // CHECK: unchecked_ref_cast_addr AnyObject in %{{.*}} : $*AnyObject to PUnknown in %{{.*}} : $*PUnknown func refcast_any_punknown(_ o: AnyObject) -> PUnknown { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_T08builtins22unsafeGuaranteed_class{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : $A): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<A>([[P_COPY]] : $A) // CHECK: [[R:%.*]] = tuple_extract [[T]] : $(A, Builtin.Int8), 0 // CHECK: [[K:%.*]] = tuple_extract [[T]] : $(A, Builtin.Int8), 1 // CHECK: destroy_value [[R]] : $A // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: destroy_value [[P]] // CHECK: return [[P_COPY]] : $A // CHECK: } func unsafeGuaranteed_class(_ a: A) -> A { Builtin.unsafeGuaranteed(a) return a } // CHECK-LABEL: _T08builtins24unsafeGuaranteed_generic{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : $T): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T) // CHECK: [[R:%.*]] = tuple_extract [[T]] : $(T, Builtin.Int8), 0 // CHECK: [[K:%.*]] = tuple_extract [[T]] : $(T, Builtin.Int8), 1 // CHECK: destroy_value [[R]] : $T // CHECK: [[P_RETURN:%.*]] = copy_value [[P]] // CHECK: destroy_value [[P]] // CHECK: return [[P_RETURN]] : $T // CHECK: } func unsafeGuaranteed_generic<T: AnyObject> (_ a: T) -> T { Builtin.unsafeGuaranteed(a) return a } // CHECK_LABEL: sil hidden @_T08builtins31unsafeGuaranteed_generic_return{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : $T): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T) // CHECK: [[R]] = tuple_extract [[T]] : $(T, Builtin.Int8), 0 // CHECK: [[K]] = tuple_extract [[T]] : $(T, Builtin.Int8), 1 // CHECK: destroy_value [[P]] // CHECK: [[S:%.*]] = tuple ([[R]] : $T, [[K]] : $Builtin.Int8) // CHECK: return [[S]] : $(T, Builtin.Int8) // CHECK: } func unsafeGuaranteed_generic_return<T: AnyObject> (_ a: T) -> (T, Builtin.Int8) { return Builtin.unsafeGuaranteed(a) } // CHECK-LABEL: sil hidden @_T08builtins19unsafeGuaranteedEnd{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : $Builtin.Int8): // CHECK: builtin "unsafeGuaranteedEnd"([[P]] : $Builtin.Int8) // CHECK: [[S:%.*]] = tuple () // CHECK: return [[S]] : $() // CHECK: } func unsafeGuaranteedEnd(_ t: Builtin.Int8) { Builtin.unsafeGuaranteedEnd(t) } // CHECK-LABEL: sil hidden @_T08builtins10bindMemory{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : $Builtin.RawPointer, [[I:%.*]] : $Builtin.Word, [[T:%.*]] : $@thick T.Type): // CHECK: bind_memory [[P]] : $Builtin.RawPointer, [[I]] : $Builtin.Word to $*T // CHECK: return {{%.*}} : $() // CHECK: } func bindMemory<T>(ptr: Builtin.RawPointer, idx: Builtin.Word, _: T.Type) { Builtin.bindMemory(ptr, idx, T.self) }
a687fd4a4e90aea40615008828fd5678
40.426859
188
0.634182
false
false
false
false
pnhechim/Fiestapp-iOS
refs/heads/master
Fiestapp/Fiestapp/ViewControllers/Matches/MatchesTableViewController.swift
mit
1
// // MatchesTableViewController.swift // Fiestapp // // Created by Nicolás Hechim on 2/7/17. // Copyright © 2017 Mint. All rights reserved. // import UIKit class MatchesTableViewController: UITableViewController { let cellHeight: CGFloat = 84 let cellIdentifier = "MatchCell" var idFiesta = String() var idUsuarioMatch = String() var invitados = [UsuarioModel]() override func viewDidLoad() { super.viewDidLoad() ProgressOverlayView.shared.showProgressView(view) MeGustasService.shared.obtenerMatches(idFiesta: "-KkrLG86TLQ4HcURJynY") { idUsuariosMatch in if idUsuariosMatch.count == 0 { ProgressOverlayView.shared.hideProgressView() self.performSegue(withIdentifier: "segueSinMatches", sender: self) } self.invitados = Common.shared.initUsuariosConListaIds(ids: idUsuariosMatch) FacebookService.shared.completarDatosInvitadosFacebook(invitados: self.invitados) { success in self.tableView.reloadData() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return invitados.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MatchTableViewCell else { fatalError("The dequeued cell is not an instance of MatchTableViewCell.") } initPrototypeCell(cell: cell, invitado: invitados[indexPath.row]) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return cellHeight } // MARK: - Navigation // method to run when table view cell is tapped override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.idUsuarioMatch = self.invitados[indexPath.row].Id let fotoPerfilInvitadoMatch = UIImageView(frame: CGRect(x: 10, y: 70, width: 250, height: 172)) fotoPerfilInvitadoMatch.image = invitados[indexPath.row].FotoPerfil.image fotoPerfilInvitadoMatch.contentMode = .scaleAspectFit let tap = UITapGestureRecognizer(target: self, action: #selector(self.abrirPerfil(_:))) fotoPerfilInvitadoMatch.addGestureRecognizer(tap) fotoPerfilInvitadoMatch.isUserInteractionEnabled = true let spacer = "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" let alertController = UIAlertController(title: "¡Da el próximo paso!" , message: invitados[indexPath.row].Nombre + spacer, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Ver perfil", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in FacebookService.shared.abrirPerfil(idUsuario: self.invitados[indexPath.row].Id) }) alertController.addAction(UIAlertAction(title: "Cerrar", style: UIAlertActionStyle.cancel) { (result : UIAlertAction) -> Void in }) alertController.view.addSubview(fotoPerfilInvitadoMatch) self.present(alertController, animated: true, completion: nil) } func initPrototypeCell(cell: MatchTableViewCell, invitado: UsuarioModel) { cell.iconCircle.image = invitado.FotoPerfil.image cell.iconCircle.layer.cornerRadius = cell.iconCircle.frame.height/2 cell.iconCircle.layer.masksToBounds = false cell.iconCircle.clipsToBounds = true cell.name.text = invitado.Nombre cell.cardMask.layer.cornerRadius = 4 cell.contentViewCell.backgroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1) cell.cardMask.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor cell.cardMask.layer.masksToBounds = false cell.cardMask.layer.shadowOpacity = 0.8 cell.cardMask.layer.shadowOffset = CGSize(width: 0, height: 0) } func setIdFiesta(idFiesta: String) { self.idFiesta = idFiesta } func abrirPerfil(_ sender: UITapGestureRecognizer) { FacebookService.shared.abrirPerfil(idUsuario: idUsuarioMatch) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "segueSinMatches" { let meGustasSinResultadosViewController = segue.destination as! MeGustasSinResultadosViewController meGustasSinResultadosViewController.setTitulo(titulo: MeGustasService.MIS_MATCHES) meGustasSinResultadosViewController.setMensaje(mensaje: MeGustasService.SIN_MATCHES) } } }
40ae232dd9679b692bd4b1749fdee667
40.503876
176
0.654277
false
false
false
false
JGiola/swift
refs/heads/main
benchmark/single-source/ObserverUnappliedMethod.swift
apache-2.0
10
//===----------------------------------------------------------------------===// // // 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 TestsUtils public let benchmarks = BenchmarkInfo( name: "ObserverUnappliedMethod", runFunction: run_ObserverUnappliedMethod, tags: [.validation], legacyFactor: 10) class Observer { @inline(never) func receive(_ value: Int) { } } protocol Sink { func receive(_ value: Int) } struct Forwarder<Object>: Sink { let object: Object let method: (Object) -> (Int) -> () func receive(_ value: Int) { method(object)(value) } } class Signal { var observers: [Sink] = [] func subscribe(_ sink: Sink) { observers.append(sink) } func send(_ value: Int) { for observer in observers { observer.receive(value) } } } public func run_ObserverUnappliedMethod(_ iterations: Int) { let signal = Signal() let observer = Observer() for _ in 0 ..< 1_000 * iterations { let forwarder = Forwarder(object: observer, method: Observer.receive) signal.subscribe(forwarder) } signal.send(1) }
30925bf12bbad4ea0ee1b853622a7c0a
22.507937
80
0.602971
false
false
false
false
objecthub/swift-lispkit
refs/heads/master
Sources/LispKit/Graphics/DrawingDocument.swift
apache-2.0
1
// // DrawingDocument.swift // LispKit // // Created by Matthias Zenger on 01/07/2018. // Copyright © 2018 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import CoreGraphics #if os(iOS) || os(watchOS) || os(tvOS) import UIKit #elseif os(macOS) import AppKit #endif /// /// A `DrawingDocument` object represents a document whose pages consist of drawings. /// For now, the main purpose of creating a `DrawingDocument` object is to save it into /// a PDF document. /// public final class DrawingDocument { /// The title of the collection. public var title: String? /// The author of the collection. public var author: String? /// The creator of the collection. public var creator: String? /// The subject of the collection. public var subject: String? /// Keywords describing the collection public var keywords: String? /// The owner's password public var ownerPassword: String? /// A user password public var userPassword: String? /// Can this collection be printed? public var allowsPrinting: Bool = true /// Can this collection be copied (copy/pasted)? public var allowsCopying: Bool = true /// Internal representation of the various pages of the drawing collection. public private(set) var pages: [Page] /// Initializer public init (title: String? = nil, author: String? = nil, creator: String? = nil, subject: String? = nil, keywords: String? = nil) { self.pages = [] self.title = title self.author = author self.creator = creator self.subject = subject self.keywords = keywords } /// Append a new drawing to the collection. public func append(_ drawing: Drawing, flipped: Bool = false, width: Int, height: Int) { self.pages.append(Page(drawing: drawing, flipped: flipped, width: width, height: height)) } /// Save the collection as a PDF file to URL `url`. public func saveAsPDF(url: URL) -> Bool { // First check if we can write to the URL var dir: ObjCBool = false let parent = url.deletingLastPathComponent().path guard FileManager.default.fileExists(atPath: parent, isDirectory: &dir) && dir.boolValue else { return false } guard FileManager.default.isWritableFile(atPath: parent) else { return false } // Define PDF document information let pdfInfo: NSMutableDictionary = [ kCGPDFContextAllowsPrinting: (self.allowsPrinting ? kCFBooleanTrue : kCFBooleanFalse) as Any, kCGPDFContextAllowsCopying : (self.allowsCopying ? kCFBooleanTrue : kCFBooleanFalse) as Any ] if let title = self.title { pdfInfo[kCGPDFContextTitle] = title } if let author = self.author { pdfInfo[kCGPDFContextAuthor] = author } if let creator = self.creator { pdfInfo[kCGPDFContextCreator] = creator } if let subject = self.subject { pdfInfo[kCGPDFContextSubject] = subject } if let keywords = self.keywords { pdfInfo[kCGPDFContextKeywords] = keywords } if let password = self.ownerPassword { pdfInfo[kCGPDFContextOwnerPassword] = password } if let password = self.userPassword { pdfInfo[kCGPDFContextUserPassword] = password } // Default media box (will be overwritten on a page by page basis) var mediaBox = CGRect(x: 0, y: 0, width: Double(200), height: Double(200)) // Create a core graphics context suitable for creating PDF files guard let cgc = CGContext(url as CFURL, mediaBox: &mediaBox, pdfInfo as CFDictionary) else { return false } #if os(macOS) let previous = NSGraphicsContext.current defer { NSGraphicsContext.current = previous } #endif for page in self.pages { page.createPDFPage(in: cgc) } cgc.closePDF() return true } /// Representation of a page. public struct Page { public let drawing: Drawing public let flipped: Bool public let width: Int public let height: Int fileprivate func createPDFPage(in cgc: CGContext) { var mediaBox = CGRect(x: 0, y: 0, width: Double(self.width), height: Double(self.height)) let pageInfo: NSDictionary = [ kCGPDFContextMediaBox : NSData(bytes: &mediaBox, length: MemoryLayout.size(ofValue: mediaBox)) ] // Create a graphics context for drawing into the PDF page #if os(iOS) || os(watchOS) || os(tvOS) UIGraphicsPushContext(cgc) defer { UIGraphicsPopContext() } #elseif os(macOS) NSGraphicsContext.current = NSGraphicsContext(cgContext: cgc, flipped: self.flipped) #endif // Create a new PDF page cgc.beginPDFPage(pageInfo as CFDictionary) cgc.saveGState() // Flip graphics if required if self.flipped { cgc.translateBy(x: 0.0, y: CGFloat(self.height)) cgc.scaleBy(x: 1.0, y: -1.0) } // Draw the image self.drawing.draw() cgc.restoreGState() // Close PDF page and document cgc.endPDFPage() } } }
456e9e9dc072438b2c40dd98d4f74d72
30.662983
99
0.65486
false
false
false
false
robconrad/fledger-ios
refs/heads/master
fledger-ios/ui/AppUITableViewCell.swift
mit
1
// // AppUITableViewCell.swift // fledger-ios // // Created by Robert Conrad on 4/14/15. // Copyright (c) 2015 TwoSpec Inc. All rights reserved. // import UIKit class AppUITableViewCell: UITableViewCell { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = AppColors.bgMain() textLabel?.textColor = AppColors.text() let selectedBgView = UIView() selectedBgView.backgroundColor = AppColors.bgSelected() selectedBackgroundView = selectedBgView } }
8e1292cb49851c72da6ff76782d5b769
21.92
63
0.65096
false
false
false
false
mixersoft/cordova-plugin-camera-roll-location
refs/heads/master
src/ios/CameraRollLocation.swift
apache-2.0
1
/* * Copyright (c) 2016 by Snaphappi, Inc. All rights reserved. * * @SNAPHAPPI_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apache License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://opensource.org/licenses/Apache-2.0/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @SNAPHAPPI_LICENSE_HEADER_END@ */ // import PhotoWithLocationService; @objc(CameraRollLocation) class CameraRollLocation : CDVPlugin { // deprecate @objc(getByMoments:) func getByMoments(command: CDVInvokedUrlCommand) { return self.getCameraRoll(command: command); } @objc(getCameraRoll:) func getCameraRoll(command: CDVInvokedUrlCommand) { let dateFmt = DateFormatter() dateFmt.dateFormat = "yyyy-MM-dd" var pluginResult = CDVPluginResult( status: CDVCommandStatus_ERROR ) // let options = command.arguments[0] as? String ?? "" let options : [String:Any] = command.arguments[0] as! [String:Any]; // prepare params var fromDate : Date? = nil; var toDate : Date? = nil; if let from = options["from"] as! NSString? { fromDate = dateFmt.date(from: from.substring(to: 10)) print("FROM: \( from.substring(to: 10) ) => \(fromDate)") } if let to = options["to"] as! NSString? { toDate = dateFmt.date(from: to.substring(to: 10)) print("TO: \( to.substring(to: 10) ) => \(toDate)") } // get result from CameraRoll let cameraRoll = PhotoWithLocationService() var data : [NSData] = [] // runInBackground self.commandDelegate!.run(inBackground: { let result = cameraRoll.getByMoments(from:fromDate, to:toDate); if result.count > 0 { // toJSON() var asJson = "" for o in result { if !asJson.isEmpty { asJson += ", " } asJson += "\(o.toJson())" // data.append( NSKeyedArchiver.archivedDataWithRootObject(o) ) } asJson = "[\(asJson)]" pluginResult = CDVPluginResult( status: CDVCommandStatus_OK, messageAs: asJson ) } else if result.count == 0 { pluginResult = CDVPluginResult( status: CDVCommandStatus_OK, messageAs: "[]" ) } // let aDict = [result[0].uuid:result[0]] // pluginResult = CDVPluginResult( // status: CDVCommandStatus_OK //// , messageAsArray: result // <NSInvalidArgumentException> Invalid type in JSON write (mappi1.CameraRollPhoto) //// , messageAsArray: data // <NSInvalidArgumentException> Invalid type in JSON write (NSConcreteMutableData) //// , messageAsDictionary: aDict // Invalid type in JSON write (mappi1.CameraRollPhoto) //// , messageAsMultipart: data // returns ArrayBuffer to JS - then what? // ) // send result in Background self.commandDelegate!.send( pluginResult, callbackId: command.callbackId ) }) } // experimental @objc(getImage:) func getImage(command: CDVInvokedUrlCommand) { let uuids : [String] = command.arguments[0] as! [String]; let options : [String:Any] = command.arguments[1] as! [String:Any]; var pluginResult = CDVPluginResult( status: CDVCommandStatus_ERROR ) let cameraRoll = PhotoWithLocationService() // runInBackground self.commandDelegate!.run(inBackground: { let result = cameraRoll.getImage(localIds:uuids, options:options) // var resultStr: String // do { // let jsonData = try JSONSerialization.data(withJSONObject: result) // resultStr = String(data: jsonData, encoding: .utf8)! // } catch { // resultStr = "error:JSONSerialization()" // } pluginResult = CDVPluginResult( status: CDVCommandStatus_OK, messageAs: result ) self.commandDelegate!.send( pluginResult, callbackId: command.callbackId ) }) } }
51b90e6df34e3ee0e060141e24717f0a
33.057143
128
0.618289
false
false
false
false
debugsquad/metalic
refs/heads/master
metalic/Model/Main/MMain.swift
mit
1
import Foundation class MMain { let items:[MMainItem] var state:MMainState weak var current:MMainItem! weak var itemHome:MMainItemHome! init() { state = MMainStateOptions() var items:[MMainItem] = [] let itemHome:MMainItemHome = MMainItemHome(index:items.count) current = itemHome self.itemHome = itemHome items.append(itemHome) let itemStore:MMainItemStore = MMainItemStore(index:items.count) items.append(itemStore) self.items = items } //MARK: public func pushed() { state = MMainStatePushed() } func poped() { state = MMainStateOptions() } }
c5e0dc95ee2d1fe5f4e55bad602d2d76
18.945946
72
0.571816
false
false
false
false
ashfurrow/RxSwift
refs/heads/master
Rx.playground/Pages/Combining_Observables.xcplaygroundpage/Contents.swift
mit
2
//: [<< Previous](@previous) - [Index](Index) import RxSwift /*: ## Combination operators Operators that work with multiple source Observables to create a single Observable. */ /*: ### `startWith` emit a specified sequence of items before beginning to emit the items from the source Observable ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/startwith.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/startwith.html ) */ example("startWith") { let subscription = sequenceOf(4, 5, 6, 7, 8, 9) .startWith(3) .startWith(2) .startWith(1) .startWith(0) .subscribe { print($0) } } /*: ### `combineLatest` when an item is emitted by either of two Observables, combine the latest item emitted by each Observable via a specified function and emit items based on the results of this function ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/combinelatest.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/combinelatest.html ) */ example("combineLatest 1") { let intOb1 = PublishSubject<String>() let intOb2 = PublishSubject<Int>() _ = combineLatest(intOb1, intOb2) { "\($0) \($1)" } .subscribe { print($0) } intOb1.on(.Next("A")) intOb2.on(.Next(1)) intOb1.on(.Next("B")) intOb2.on(.Next(2)) } //: To produce output, at least one element has to be received from each sequence in arguements. example("combineLatest 2") { let intOb1 = just(2) let intOb2 = sequenceOf(0, 1, 2, 3, 4) _ = combineLatest(intOb1, intOb2) { $0 * $1 } .subscribe { print($0) } } //: Combine latest has versions with more than 2 arguments. example("combineLatest 3") { let intOb1 = just(2) let intOb2 = sequenceOf(0, 1, 2, 3) let intOb3 = sequenceOf(0, 1, 2, 3, 4) _ = combineLatest(intOb1, intOb2, intOb3) { ($0 + $1) * $2 } .subscribe { print($0) } } //: Combinelatest version that allows combining sequences with different types. example("combineLatest 4") { let intOb = just(2) let stringOb = just("a") _ = combineLatest(intOb, stringOb) { "\($0) " + $1 } .subscribe { print($0) } } //: `combineLatest` extension method for Array of `ObservableType` conformable types //: The array must be formed by `Observables` of the same type. example("combineLatest 5") { let intOb1 = just(2) let intOb2 = sequenceOf(0, 1, 2, 3) let intOb3 = sequenceOf(0, 1, 2, 3, 4) _ = [intOb1, intOb2, intOb3].combineLatest { intArray -> Int in Int((intArray[0] + intArray[1]) * intArray[2]) } .subscribe { (event: Event<Int>) -> Void in print(event) } } /*: ### `zip` combine the emissions of multiple Observables together via a specified function and emit single items for each combination based on the results of this function ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/zip.png) [More info in reactive.io website](http://reactivex.io/documentation/operators/zip.html) */ example("zip 1") { let intOb1 = PublishSubject<String>() let intOb2 = PublishSubject<Int>() _ = zip(intOb1, intOb2) { "\($0) \($1)" } .subscribe { print($0) } intOb1.on(.Next("A")) intOb2.on(.Next(1)) intOb1.on(.Next("B")) intOb1.on(.Next("C")) intOb2.on(.Next(2)) } example("zip 2") { let intOb1 = just(2) let intOb2 = sequenceOf(0, 1, 2, 3, 4) _ = zip(intOb1, intOb2) { $0 * $1 } .subscribe { print($0) } } example("zip 3") { let intOb1 = sequenceOf(0, 1) let intOb2 = sequenceOf(0, 1, 2, 3) let intOb3 = sequenceOf(0, 1, 2, 3, 4) _ = zip(intOb1, intOb2, intOb3) { ($0 + $1) * $2 } .subscribe { print($0) } } /*: ### `merge` combine multiple Observables into one by merging their emissions ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/merge.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/merge.html ) */ example("merge 1") { let subject1 = PublishSubject<Int>() let subject2 = PublishSubject<Int>() _ = sequenceOf(subject1, subject2) .merge() .subscribeNext { int in print(int) } subject1.on(.Next(20)) subject1.on(.Next(40)) subject1.on(.Next(60)) subject2.on(.Next(1)) subject1.on(.Next(80)) subject1.on(.Next(100)) subject2.on(.Next(1)) } example("merge 2") { let subject1 = PublishSubject<Int>() let subject2 = PublishSubject<Int>() _ = sequenceOf(subject1, subject2) .merge(maxConcurrent: 2) .subscribe { print($0) } subject1.on(.Next(20)) subject1.on(.Next(40)) subject1.on(.Next(60)) subject2.on(.Next(1)) subject1.on(.Next(80)) subject1.on(.Next(100)) subject2.on(.Next(1)) } /*: ### `switchLatest` convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently-emitted of those Observables ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/switch.png) [More info in reactive.io website]( http://reactivex.io/documentation/operators/switch.html ) */ example("switchLatest") { let var1 = Variable(0) let var2 = Variable(200) // var3 is like an Observable<Observable<Int>> let var3 = Variable(var1) let d = var3 .switchLatest() .subscribe { print($0) } var1.value = 1 var1.value = 2 var1.value = 3 var1.value = 4 var3.value = var2 var2.value = 201 var1.value = 5 var1.value = 6 var1.value = 7 } //: [Index](Index) - [Next >>](@next)
44f4ad4e674e05fd7dfbdbb09c2ec4bf
20.910714
182
0.601304
false
true
false
false
maranathApp/GojiiFramework
refs/heads/master
GojiiFrameWork/UIImageViewExtensions.swift
mit
1
// // CGFloatExtensions.swift // GojiiFrameWork // // Created by Stency Mboumba on 01/06/2017. // Copyright © 2017 Stency Mboumba. All rights reserved. // import UIKit // MARK: - Extension UIImageView BSFramework public extension UIImageView { /* --------------------------------------------------------------------------- */ // MARK: - Initilizers ( init ) /* --------------------------------------------------------------------------- */ /** Initialize with internal image ( with image or not if imageName = nil ) - parameter frame: CGRect - parameter imageName: String? / Name of image in Asset - parameter contentMode: UIViewContentMode ( default = ScaleAspectFit ) - returns: UIImageView */ public convenience init (frame: CGRect, imageName: String?, contentMode:UIViewContentMode = .scaleAspectFit) { guard let hasImgName = imageName, let hasImage = UIImage (named: hasImgName) else { self.init (frame: frame) self.contentMode = contentMode return } self.init (frame: frame,image: hasImage, contentMode: contentMode) } /** Initialize with internal image - parameter frame: CGRect - parameter image: String / Name of image in Asset - parameter contentMode: UIViewContentMode ( default = ScaleAspectFit ) - returns: UIImageView */ public convenience init (frame: CGRect, image: UIImage, contentMode:UIViewContentMode = .scaleAspectFit) { self.init (frame: frame) self.image = image self.contentMode = contentMode } /** Initialize, Download a image on a server Can set a default image When is finished download a callBack (succesDownload or errorDownload) is call, for assign the image with an animation - parameter frame: CGRect - parameter nsurl: NSURL - parameter defaultImage: String? / default image (default = nil) - parameter contentMode: UIViewContentMode (default = .ScaleAspectFit) - parameter succesDownload: ()->()? - parameter errorDownload: (UIImageBSError)->()? - returns: UIImageView */ public convenience init ( frame: CGRect, nsurl:NSURL, defaultImage:NSData? = nil, contentMode:UIViewContentMode = .scaleAspectFit, succesDownload:(()->())? = nil, errorDownload:((_ error:UIImageViewBSError)->())? = nil) { if let hasImageString = defaultImage, let hasImage = UIImage(data: hasImageString as Data) { self.init(frame: frame, image: hasImage, contentMode: contentMode) } else { self.init(frame: frame) self.contentMode = contentMode } self.imageWithUrl(url: nsurl,succesDownload: succesDownload,errorDownload: errorDownload) } /** Initialize, Download a image on a server Can set a default image When is finished download a callBack (succesDownload or errorDownload) is call, for assign the image with an animation - parameter frame: CGRect - parameter nsurl: NSURL - parameter defaultImage: String? / default image (default = nil) - parameter contentMode: UIViewContentMode (default = .ScaleAspectFit) - parameter succesDownload: ()->()? - parameter errorDownload: (UIImageBSError)->()? - returns: UIImageView */ public convenience init ( frame: CGRect, nsurl:NSURL, defaultImage:String? = nil, contentMode:UIViewContentMode = .scaleAspectFit, succesDownload:(()->())? = nil, errorDownload:((_ error:UIImageViewBSError)->())? = nil) { self.init(frame: frame, imageName: defaultImage, contentMode: contentMode) self.imageWithUrl(url: nsurl,succesDownload: succesDownload,errorDownload: errorDownload) } /** Initialize, Download a image on a server Can set a default image When is finished download a callBack (succesDownload or errorDownload) is call, for assign the image with an animation - parameter frame: CGRect - parameter url: String Url - parameter defaultImage: String? / default image (default = nil) - parameter contentMode: UIViewContentMode (default = .ScaleAspectFit) - parameter succesDownload: ()->()? - parameter errorDownload: (UIImageBSError)->()? - returns: UIImageView */ public convenience init ( frame: CGRect, url:String, defaultImage:String? = nil, contentMode:UIViewContentMode = .scaleAspectFit, succesDownload:(()->())? = nil, errorDownload:((_ error:UIImageViewBSError)->())? = nil ) { self.init(frame: frame, imageName: defaultImage, contentMode: contentMode) guard let nsurl = NSURL (string: url) else { errorDownload?(UIImageViewBSError.Nil(errorIs: "URLString is nil")) return } self.imageWithUrl(url: nsurl,succesDownload: succesDownload,errorDownload: errorDownload) } /* --------------------------------------------------------------------------- */ // MARK: - Download image for server /* --------------------------------------------------------------------------- */ /** Download image for server When is finished download a callBack (succesDownload or errorDownload) is call, for assign the image with an animation Or directly if succesDownload = nil succesDownload (imageView = self / UIImageView , donwloadedImage = UIImage / image downloaded) - parameter url: NSURL - parameter succesDownload: (imageView = self / UIImageView , donwloadedImage = UIImage / image downloaded)->() - parameter errorDownload: ()->() / Call when error */ public func imageWithUrl( url:NSURL, succesDownload:(()->())? = nil, errorDownload:((_ error:UIImageViewBSError)->())? = nil ) { NSData.getDataFromNSURL(urL: url as URL) { (data, error) in DispatchQueue.main.sync(execute: { guard error == nil, let hasData = data, let hasImage = UIImage(data: hasData) else { if error != nil { errorDownload?(UIImageViewBSError.NSURL(errorIs: error.debugDescription) ) } else { errorDownload?(UIImageViewBSError.NSData(errorIs:"NSData Error : data not have image") ) } return } succesDownload?() self.image = hasImage // Update the UI on the main thread. }) } } /* --------------------------------------------------------------------------- */ // MARK: - UIImageView → TintColor /* --------------------------------------------------------------------------- */ /** Tint picto with color - parameter color: UIColor */ public func tintPicto(color:UIColor) { if let imageToChange = self.image?.withRenderingMode(.alwaysTemplate) { self.image = imageToChange self.tintColor = color } } /** Tint Photo with Color<br><br> This is similar to Photoshop's "Color" layer blend mode<br><br> This is perfect for non-greyscale source images, and images that have both highlights and shadows that should be preserved<br><br> white will stay white and black will stay black as the lightness of the image is preserved<br><br> - parameter color: UIColor */ public func tintPhoto(color:UIColor) { if let imageToChange = self.image?.tintPhoto(tintColor: color) { self.image = imageToChange } } } /* --------------------------------------------------------------------------- */ // MARK: - UIImageViewBSError UIImageView Extensions /* --------------------------------------------------------------------------- */ /** Enum for Debug BSError - Error: Error of any kind - Nil: Error Nil Object - NSData: Error NSData - NSURL: Error NSUrl - JSON: Error JSon */ public enum UIImageViewBSError: Error, CustomStringConvertible { case Error(whereIs:String,funcIs:String, errorIs:String) case Nil(errorIs:String) case NSData(errorIs:String) case NSURL(errorIs:String) /// A textual representation / Mark CustomStringConvertible public var description: String { switch self { case .Error(let whereIs,let funcIs, let errorString) : return "[\(whereIs)][\(funcIs)] \(errorString)" case .Nil(let errorString) : return "\(errorString)" case .NSData(let errorString) : return "\(errorString)" case .NSURL(let errorString) : return "\(errorString)" } } /** Print Error */ // func print() { printObject("[BSFramework][UIImageView extension] \(self.description)") } }
f2c06b1be08d3547cf2564cd7d86d1d9
35.900763
135
0.54096
false
false
false
false
leytzher/LemonadeStand_v2
refs/heads/master
LemonadeStandv2/Balance.swift
gpl-2.0
1
// // Balance.swift // LemonadeStandv2 // // Created by Leytzher on 1/24/15. // Copyright (c) 2015 Leytzher. All rights reserved. // import Foundation import UIKit class Balance{ var money = 0.0 var lemons = 0 var iceCubes = 0 var lemonsUsed = 0 var iceCubesUsed = 0 var lemonsInCart = 0 var iceCubesInCart = 0 var inStock = 0 }
532bae38886e9ee503672053ca123003
14.636364
53
0.686047
false
false
false
false
madoffox/Stretching
refs/heads/master
Stretching/Stretching/CalendarActivation.swift
mit
1
// // CalendarVC.swift // Stretching // // Created by Admin on 31.01.17. // Copyright © 2017 Admin. All rights reserved. // import UIKit import EventKit var savedEventId : String = "" func createEvent(eventStore: EKEventStore, title: String, startDate: NSDate, endDate: NSDate) { let event = EKEvent(eventStore: eventStore) event.title = title event.startDate = startDate as Date event.endDate = endDate as Date event.calendar = eventStore.defaultCalendarForNewEvents event.calendar.title = "Sport" do { try eventStore.save(event, span: .thisEvent) savedEventId = event.eventIdentifier } catch { print("Bad things happened") } } func addEvent(title: String,startDate: NSDate,endDate: NSDate) { let eventStore = EKEventStore() if (EKEventStore.authorizationStatus(for: .event) != EKAuthorizationStatus.authorized) { eventStore.requestAccess(to: .event, completion: { granted, error in createEvent(eventStore: eventStore, title: title, startDate: startDate, endDate: endDate) }) } else { createEvent(eventStore: eventStore, title: title, startDate: startDate, endDate: endDate) } } func retrieveEventDates()->[Date]{ let eventStore = EKEventStore() var eventsDates = [Date]() let calendars = eventStore.calendars(for: .event) for calendar in calendars{ if(calendar.title == "Sport"){ let ThreeMonthAgo = NSDate(timeIntervalSinceNow: -3*30*24*3600) let predicate = eventStore.predicateForEvents(withStart: ThreeMonthAgo as Date, end: Date(), calendars: [calendar]) let events = eventStore.events(matching: predicate) for event in events { eventsDates.append(event.endDate) print(event.title) } break } } return eventsDates }
5ec2bcef18cf8bf0c99c98166cb6450c
24.365854
127
0.599038
false
false
false
false
Hidebush/McBlog
refs/heads/master
McBlog/McBlog/Classes/Module/Home/Refresh/YHRefreshConrol.swift
mit
1
// // YHRefreshConrol.swift // McBlog // // Created by admin on 16/5/6. // Copyright © 2016年 郭月辉. All rights reserved. // import UIKit private let refreshViewOffset: CGFloat = -60 class YHRefreshConrol: UIRefreshControl { override init() { super.init() setUpUI() addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil) } override func endRefreshing() { super.endRefreshing() refreshView.stopLoading() } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if frame.origin.y > 0 { return } if refreshing { refreshView.startLoading() } if frame.origin.y < refreshViewOffset && !refreshView.rotateFlag { refreshView.rotateFlag = true } else if frame.origin.y > refreshViewOffset && refreshView.rotateFlag { refreshView.rotateFlag = false } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { removeObserver(self, forKeyPath: "frame") } private func setUpUI() { tintColor = UIColor.clearColor() addSubview(refreshView) refreshView.frame = CGRectMake((UIScreen.mainScreen().bounds.size.width - 160.0) * 0.5-15, 0, 160, 60) } private lazy var refreshView: YHRefreshView = YHRefreshView.refreshView() } class YHRefreshView: UIView { private var rotateFlag: Bool = false { didSet { rotateIconAnim() } } @IBOutlet weak var rotateIcon: UIImageView! @IBOutlet weak var tipView: UIView! @IBOutlet weak var loadingIcon: UIImageView! class func refreshView() -> YHRefreshView { return NSBundle.mainBundle().loadNibNamed("YHRefreshView", owner: nil, options: nil).last as! YHRefreshView } private func rotateIconAnim() { let angel = rotateFlag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01) UIView.animateWithDuration(0.25) { self.rotateIcon.transform = CGAffineTransformRotate(self.rotateIcon.transform, angel) } } private func startLoading() { tipView.hidden = true if layer.animationForKey("loadingAnim") != nil { return } let anim = CABasicAnimation(keyPath: "transform.rotation") anim.toValue = 2*M_PI anim.repeatCount = MAXFLOAT anim.removedOnCompletion = false anim.duration = 1 loadingIcon.layer.addAnimation(anim, forKey: "loadingAnim") } private func stopLoading() { tipView.hidden = false loadingIcon.layer.removeAllAnimations() } }
bde9925e189c0eed5b914b8b79f9902b
28.161616
157
0.617464
false
false
false
false
kaltura/playkit-ios
refs/heads/develop
Classes/Events/EventsPayloads/PKAdInfo.swift
agpl-3.0
1
// =================================================================================================== // Copyright (C) 2017 Kaltura Inc. // // Licensed under the AGPLv3 license, unless a different license for a // particular library is specified in the applicable library path. // // You may obtain a copy of the License at // https://www.gnu.org/licenses/agpl-3.0.html // =================================================================================================== import Foundation /// The position type of the ad according to the content timeline. @objc public enum AdPositionType: Int, CustomStringConvertible { case preRoll case midRoll case postRoll public var description: String { switch self { case .preRoll: return "preRoll" case .midRoll: return "midRoll" case .postRoll: return "postRoll" } } } /// `PKAdInfo` represents ad information. @objc public class PKAdInfo: NSObject { @objc public var duration: TimeInterval @objc public var title: String /// The position of the pod in the content in seconds. Pre-roll returns 0, /// post-roll returns -1 and mid-rolls return the scheduled time of the pod. @objc public var timeOffset: TimeInterval @objc public var adDescription: String @objc public var isSkippable: Bool @objc public var contentType: String @objc public var adId: String /// The source ad server information included in the ad response. @objc public var adSystem: String @objc public var height: Int @objc public var width: Int /// Total number of ads in the pod this ad belongs to. Will be 1 for standalone ads. @objc public var totalAds: Int /// The position of this ad within an ad pod. Will be 1 for standalone ads. @objc public var adPosition: Int @objc public var isBumper: Bool // The index of the pod, where pre-roll pod is 0, mid-roll pods are 1 .. N // and the post-roll is -1. @objc public var podIndex: Int // The bitrate of the selected creative. @objc public var mediaBitrate: Int // The CreativeId for the ad. @objc public var creativeId: String // The Advertiser Name for the ad. @objc public var advertiserName: String @objc public var adPlayHead: TimeInterval @objc public var skipTimeOffset: TimeInterval @objc public var creativeAdId: String? @objc public var dealId: String? @objc public var surveyUrl: String? @objc public var traffickingParams: String? @objc public var adIndexInPod: Int @objc public var podCount: Int @objc public var adPodTimeOffset: TimeInterval /// returns the position type of the ad (pre, mid, post) @objc public var positionType: AdPositionType { if timeOffset > 0 { return .midRoll } else if timeOffset < 0 { return .postRoll } else { return .preRoll } } @objc public init(adDescription: String, adDuration: TimeInterval, title: String, isSkippable: Bool, contentType: String, adId: String, adSystem: String, height: Int, width: Int, totalAds: Int, adPosition: Int, timeOffset: TimeInterval, isBumper: Bool, podIndex: Int, mediaBitrate: Int, creativeId: String, advertiserName: String, adPlayHead: TimeInterval, skipTimeOffset: TimeInterval, creativeAdId: String?, dealId: String?, surveyUrl: String?, traffickingParams: String?, adIndexInPod: Int, podCount: Int, adPodTimeOffset: TimeInterval) { self.adDescription = adDescription self.duration = adDuration self.title = title self.isSkippable = isSkippable self.contentType = contentType self.adId = adId self.adSystem = adSystem self.height = height self.width = width self.totalAds = totalAds self.adPosition = adPosition self.timeOffset = timeOffset self.isBumper = isBumper self.podIndex = podIndex self.mediaBitrate = mediaBitrate self.creativeId = creativeId self.advertiserName = advertiserName self.adPlayHead = adPlayHead self.skipTimeOffset = skipTimeOffset self.creativeAdId = creativeAdId self.dealId = dealId self.surveyUrl = surveyUrl self.traffickingParams = traffickingParams self.adIndexInPod = adIndexInPod self.podCount = podCount self.adPodTimeOffset = adPodTimeOffset } public override var description: String { let info = "adDescription: \(adDescription)\n" + "duration: \(duration)\n" + "title: \(title)\n" + "isSkippable: \(isSkippable)\n" + "contentType: \(contentType)\n" + "adId: \(adId)\n" + "adSystem: \(adSystem)\n" + "height: \(height)\n" + "width: \(width)\n" + "totalAds: \(totalAds)\n" + "adPosition: \(adPosition)\n" + "timeOffset: \(timeOffset)\n" + "isBumper: \(isBumper)\n" + "podIndex: \(podIndex)\n" + "mediaBitrate: \(mediaBitrate)\n" + "positionType: \(positionType)\n" + "creativeId: \(creativeId)\n" + "advertiserName: \(advertiserName)\n" + "adPlayHead: \(adPlayHead)\n" + "skipTimeOffset: \(skipTimeOffset)\n" + "creativeAdId: \(creativeAdId ?? "")\n" + "dealId: \(dealId ?? "")\n" + "surveyUrl: \(surveyUrl ?? "")\n" + "traffickingParams: \(traffickingParams ?? "")\n" + "adIndexInPod: \(adIndexInPod)\n" + "podCount: \(podCount)\n" + "adPodTimeOffset: \(adPodTimeOffset)\n" return info } }
cda8285924ea08e2f9fa2adf785abe5d
34.4
102
0.581921
false
false
false
false
lojals/DoorsConcept
refs/heads/master
DoorConcept/Controllers/Buildings/BuildingsInteractor.swift
mit
1
// // BuildingsInteractor.swift // DoorConcept // // Created by Jorge Raul Ovalle Zuleta on 3/21/16. // Copyright © 2016 jorgeovalle. All rights reserved. // import UIKit import CoreData typealias FetchCompletionHandler = ((data:[AnyObject]?,error:String?)->Void)? class BuildingsInteractor { private let managedObjectContext:NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext init(){} /** Retrieve all the buildings created. TODO: Retrieve just the permited by the current user. - parameter completion: completion description (data = [Building], error = error description) */ func getBuildings(completion:FetchCompletionHandler){ let fetchRequest = NSFetchRequest(entityName: "Building") do{ let fetchResults = try managedObjectContext.executeRequest(fetchRequest) as! NSAsynchronousFetchResult let fetchBuilding = fetchResults.finalResult as! [Building] completion!(data:fetchBuilding, error: nil) }catch{ completion!(data:nil,error: "CoreData error!") } } /** Add a new Building - parameter user: user adding the Building - parameter name: Building name - parameter avatar: Avatar image name index (0-4) (building_[index].png) */ func saveBuilding(user:User, name:String, avatar:String){ let build1 = NSEntityDescription.insertNewObjectForEntityForName("Building", inManagedObjectContext: managedObjectContext) as! Building build1.owner = user build1.buildingName = name build1.buildingAvatar = avatar build1.buildingCreatedAt = NSDate() do{ try managedObjectContext.save() }catch{ print("Some error inserting Building") } } /** Delete building from the db - parameter building: valid building */ func deleteBuilding(building:Building){ if UserService.sharedInstance.currentUser! == building.owner!{ managedObjectContext.deleteObject(building) do{ try managedObjectContext.save() }catch{ print("Some error deleting Door") } }else{ //Not yet implemented un UI print("That's not your building") } } }
0f9fd349f3c1b7a8bf245f8e3dcccbc4
32.081081
157
0.63031
false
false
false
false
vector-im/vector-ios
refs/heads/master
RiotSwiftUI/Modules/Common/Util/ClearViewModifier.swift
apache-2.0
1
// // Copyright 2021 New Vector Ltd // // 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 SwiftUI @available(iOS 14.0, *) extension ThemableTextField { func showClearButton(text: Binding<String>, alignement: VerticalAlignment = .center) -> some View { return modifier(ClearViewModifier(alignment: alignement, text: text)) } } @available(iOS 14.0, *) extension ThemableTextEditor { func showClearButton(text: Binding<String>, alignement: VerticalAlignment = .top) -> some View { return modifier(ClearViewModifier(alignment: alignement, text: text)) } } /// `ClearViewModifier` aims to add a clear button (e.g. `x` button) on the right side of any text editing view @available(iOS 14.0, *) struct ClearViewModifier: ViewModifier { // MARK: - Properties let alignment: VerticalAlignment // MARK: - Bindings @Binding var text: String // MARK: - Private @Environment(\.theme) private var theme: ThemeSwiftUI // MARK: - Public public func body(content: Content) -> some View { HStack(alignment: alignment) { content if !text.isEmpty { Button(action: { self.text = "" }) { Image(systemName: "xmark.circle.fill") .renderingMode(.template) .foregroundColor(theme.colors.quarterlyContent) } .padding(EdgeInsets(top: alignment == .top ? 8 : 0, leading: 0, bottom: alignment == .bottom ? 8 : 0, trailing: 8)) } } } }
0a1a481ea6be59cc7eec3f42b0364642
30.746269
131
0.630465
false
false
false
false
CoderLiLe/Swift
refs/heads/master
扩展/main.swift
mit
1
// // main.swift // 扩展 // // Created by LiLe on 2017/9/28. // Copyright © 2017年 itcast. All rights reserved. // import Foundation /* 扩展: 就是给一个现存类, 结构体, 枚举或者协议添加新的属性或着方法的语法, 无需目标源码, 就可以把想要的代码加到目标上面 但有一些限制条件需要说明: 1.不能添加一个已经存在的方法或者属性; 2.添加的属性不能是存储属性, 只能是计算属性; 格式: extension 某个先有类型 { // 增加新的功能 } */ // 1.扩展计算属性 class Transport { var scope: String init(scope: String) { self.scope = scope } } extension Transport { var extProperty: String { get { return scope } } } var myTran = Transport(scope: "✈️") print(myTran.extProperty) // 2.扩展构造器 class ChinaTransport { var price = 30 var scope: String init(scope: String) { self.scope = scope } } extension ChinaTransport { convenience init(price: Int, scope: String) { self.init(scope: scope) self.price = price } } var myTran1 = ChinaTransport(scope: "歼9") var myTran2 = ChinaTransport(price: 5000000, scope: "歼10") // 3.扩展方法 // 扩展整数类型 extension Int { func calculateDouble() -> Int { return self * 2 } } var i = 3 print(i.calculateDouble()) // 扩展下标 // 我们还可以通过扩展下标的方法来增强类的功能,比如扩展整数类型,使整数类型可以通过下标返回整数的倍数 extension Int { subscript(num: Int) -> Int { return self * num; } } print(10[3])
e70f25e21978303d88da0b89a7d15627
15.481013
64
0.613671
false
false
false
false
imfree-jdcastro/Evrythng-iOS-SDK
refs/heads/master
Evrythng-iOS/Credentials.swift
apache-2.0
1
// // Credentials.swift // EvrythngiOS // // Created by JD Castro on 26/05/2017. // Copyright © 2017 ImFree. All rights reserved. // import UIKit import Moya_SwiftyJSONMapper import SwiftyJSON public final class Credentials: ALSwiftyJSONAble { public var jsonData: JSON? public var evrythngUser: String? public var evrythngApiKey: String? public var activationCode: String? public var email: String? public var password: String? public var status: CredentialStatus? public init?(jsonData: JSON) { self.jsonData = jsonData self.evrythngUser = jsonData["evrythngUser"].string self.evrythngApiKey = jsonData["evrythngApiKey"].string self.activationCode = jsonData["activationCode"].string self.email = jsonData["email"].string self.password = jsonData["password"].string self.status = CredentialStatus(rawValue: jsonData["status"].stringValue) } public init(email: String, password: String) { self.email = email self.password = password } } public enum CredentialStatus: String{ case Active = "active" case Inactive = "inactive" case Anonymous = "anonymous" }
f50601cc7aa0a7eab4ed6837088f1d0d
26.044444
80
0.675431
false
false
false
false
swift8/anim-app
refs/heads/master
KLAnimDemo/KLAnimDemo/Classes/Extension/StringExtension.swift
apache-2.0
1
// // StringUtils.swift // KLAnimDemo 字符串工具类 // // Created by 浩 胡 on 15/6/22. // Copyright (c) 2015年 siyan. All rights reserved. // import Foundation extension String { // 分割字符 func split(s:String)->[String] { if s.isEmpty { var x = [String]() for y in self { x.append(String(y)) } return x } return self.componentsSeparatedByString(s) } // 去掉左右空格 func trim()->String { return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } // 是否包含字符串 func has(s:String)->Bool { if (self.rangeOfString(s) != nil) { return true } else { return false } } // 重复字符串 func repeat(times: Int) -> String{ var result = "" for i in 0...times { result += self } return result } // 反转 func reverse()-> String { var s = self.split("").reverse() var x = "" for y in s{ x += y } return x } }
2807e186ec575814075e72e3b7cc4121
17.45
92
0.482821
false
false
false
false
weikz/Mr-Ride-iOS
refs/heads/master
Mr-Ride-iOS/HistoryViewController.swift
mit
1
// // HistoryViewController.swift // Mr-Ride-iOS // // Created by 張瑋康 on 2016/6/8. // Copyright © 2016年 Appworks School Weikz. All rights reserved. // import UIKit import CoreData import Charts class HistoryViewController: UIViewController { @IBOutlet weak var lineChartView: LineChartView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var sideMenuButton: UIBarButtonItem! private let runDataModel = RunDataModel() private var runDataStructArray: [RunDataModel.runDataStruct] = [] private var runDataSortedByTime: [String: [RunDataModel.runDataStruct]] = [:] private var headers: [String] = [] enum CellStatus { case recordCell case gap } var cellStatus: CellStatus = .gap } // MARK: - View LifeCycle extension HistoryViewController { override func viewDidLoad() { super.viewDidLoad() setupTableView() setupSideMenu() setupBackground() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) clearData() prepareTableViewData() setupChart() } } // MARK: - Setup extension HistoryViewController { func setupBackground() { let gradientLayer = CAGradientLayer() gradientLayer.colors = [UIColor.MRLightblueColor().CGColor, UIColor.pineGreen50Color().CGColor] gradientLayer.locations = [0.5, 1] gradientLayer.frame = view.frame self.view.layer.insertSublayer(gradientLayer, atIndex: 1) } func setupSideMenu() { if self.revealViewController() != nil { sideMenuButton.target = self.revealViewController() sideMenuButton.action = "revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } } } // MARK: - TableViewDataSource and Delegate extension HistoryViewController: UITableViewDelegate, UITableViewDataSource { private func setupTableView() { tableView.dataSource = self tableView.delegate = self tableView.backgroundColor = .clearColor() let cellNib = UINib(nibName: "RunDataTableViewCell", bundle: nil) tableView.registerNib(cellNib, forCellReuseIdentifier: "RunDataTableViewCell") let gapCellNib = UINib(nibName: "RunDataTableViewGapCell", bundle: nil) tableView.registerNib(gapCellNib, forCellReuseIdentifier: "RunDataTableViewGapCell") } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { for header in headers { // first and last return gap cell if indexPath.row == 0 || indexPath.row == runDataSortedByTime[header]!.count + 1 { cellStatus = .gap let cell = tableView.dequeueReusableCellWithIdentifier("RunDataTableViewGapCell", forIndexPath: indexPath) as! RunDataTableViewGapCell return cell } else { cellStatus = .recordCell let cell = tableView.dequeueReusableCellWithIdentifier("RunDataTableViewCell", forIndexPath: indexPath) as! RunDataTableViewCell cell.runDataStruct = runDataSortedByTime[header]![indexPath.row - 1] cell.setup() return cell } } return UITableViewCell() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { // the number of sections return headers.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // the number of rows return runDataSortedByTime[headers[section]]!.count + 2 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { // the height if cellStatus == .recordCell { return 59 } else if cellStatus == .gap { return 10 } else { print("Something Wrong in HistoryView Cell's Height") return 59 } } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 24 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return headers[section] } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let statisticViewController = self.storyboard?.instantiateViewControllerWithIdentifier("StatisticViewController") as! StatisticViewController for header in headers { statisticViewController.runDataStruct = runDataSortedByTime[header]![indexPath.row - 1] } navigationController?.pushViewController(statisticViewController, animated: true) } } // MARK: - Data extension HistoryViewController { private func prepareTableViewData() { runDataStructArray = runDataModel.getData() let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MMMM, YYYY" for runDataStruct in runDataStructArray { let header = dateFormatter.stringFromDate(runDataStruct.date!) if runDataSortedByTime.keys.contains(header) { runDataSortedByTime[header]?.append(runDataStruct) } else { runDataSortedByTime[header] = [] runDataSortedByTime[header]?.append(runDataStruct) } if !headers.contains(header) { headers.append(header) } } dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } private func clearData() { runDataStructArray = [] runDataSortedByTime = [:] headers = [] } } // MARK: - Chart extension HistoryViewController { private func setupChart() { var distanceArray: [Double] = [] var dateArray: [String] = [] let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM/dd" for runDataStruct in runDataStructArray { distanceArray.append(runDataStruct.distance!) dateArray.append(dateFormatter.stringFromDate(runDataStruct.date!)) } var dataEntries:[ChartDataEntry] = [] for i in 0..<distanceArray.count { let dataEntry = ChartDataEntry(value: distanceArray[i], xIndex: i) dataEntries.append(dataEntry) } let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "") lineChartDataSet.fillColor = UIColor.blueColor() lineChartDataSet.drawFilledEnabled = true lineChartDataSet.drawCirclesEnabled = false lineChartDataSet.drawValuesEnabled = false lineChartDataSet.drawCubicEnabled = true lineChartDataSet.lineWidth = 0.0 //Gradient Fill let gradientColors = [UIColor.MRLightblueColor().CGColor, UIColor.MRTurquoiseBlue().CGColor] let colorLocations:[CGFloat] = [0.0, 0.05] let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), gradientColors, colorLocations) lineChartDataSet.fill = ChartFill.fillWithLinearGradient(gradient!, angle: 90.0) lineChartDataSet.drawFilledEnabled = true let lineChartData = LineChartData(xVals: dateArray, dataSet: lineChartDataSet) lineChartView.data = lineChartData lineChartData.setDrawValues(false) lineChartView.backgroundColor = UIColor.clearColor() lineChartView.drawGridBackgroundEnabled = false lineChartView.rightAxis.labelTextColor = .clearColor() lineChartView.rightAxis.gridColor = .whiteColor() lineChartView.leftAxis.enabled = false lineChartView.xAxis.gridColor = .clearColor() lineChartView.xAxis.labelTextColor = .whiteColor() lineChartView.xAxis.labelPosition = .Bottom lineChartView.xAxis.axisLineColor = .whiteColor() lineChartView.legend.enabled = false lineChartView.descriptionText = "" lineChartView.userInteractionEnabled = false lineChartView.leftAxis.drawAxisLineEnabled = false lineChartView.rightAxis.drawAxisLineEnabled = false lineChartView.leftAxis.drawLabelsEnabled = false lineChartView.rightAxis.drawLabelsEnabled = false lineChartView.rightAxis.drawGridLinesEnabled = false lineChartView.leftAxis.gridColor = UIColor.whiteColor() } }
a68f19ea1e3bf2232c570dcedbdd72a7
32.522901
150
0.644313
false
false
false
false
WangCrystal/actor-platform
refs/heads/master
actor-apps/app-ios/ActorCore/Config.swift
mit
1
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class Config { var endpoints = [String]() var mixpanel: String? = nil var hockeyapp: String? = nil var mint: String? = nil var enableCommunity: Bool = false var pushId: Int? = nil init() { let path = NSBundle.mainBundle().pathForResource("app", ofType: "json") let text: String let parsedObject: AnyObject? do { text = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) parsedObject = try NSJSONSerialization.JSONObjectWithData(text.asNS.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.AllowFragments) } catch _ { fatalError("Unable to load config") } if let configData = parsedObject as? NSDictionary { if let endpoints = configData["endpoints"] as? NSArray { for endpoint in endpoints { self.endpoints.append(endpoint as! String) } } if let mixpanel = configData["mixpanel"] as? String { self.mixpanel = mixpanel } if let hockeyapp = configData["hockeyapp"] as? String { self.hockeyapp = hockeyapp } if let mint = configData["mint"] as? String { self.mint = mint } if let enableCommunity = configData["community"] as? Bool { self.enableCommunity = enableCommunity } if let pushId = configData["push_id"] as? Int { self.pushId = pushId } } } }
cc979ec2ffc9e9bdcb80ac8bfd622690
32.392157
121
0.552291
false
true
false
false
tlax/GaussSquad
refs/heads/master
GaussSquad/Model/LinearEquations/Landing/MLinearEquations.swift
mit
1
import Foundation class MLinearEquations { private(set) var items:[MLinearEquationsItem] private weak var controller:CLinearEquations? init(controller:CLinearEquations) { self.controller = controller items = [] DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.loadFromDb() } } //MARK: private private func loadFromDb() { DManager.sharedInstance?.fetchData( entityName:DProject.entityName) { [weak self] (fetched) in if let fetched:[DProject] = fetched as? [DProject] { var items:[MLinearEquationsItem] = [] for project:DProject in fetched { let item:MLinearEquationsItem = MLinearEquationsItem( project:project) items.append(item) } self?.items = items self?.sortItems() } else { self?.items = [] } self?.finishLoading() } } private func sortItems() { items.sort { (itemA:MLinearEquationsItem, itemB:MLinearEquationsItem) -> Bool in let before:Bool = itemA.project.created > itemB.project.created return before } } private func finishLoading() { DispatchQueue.main.async { [weak self] in self?.controller?.modelLoaded() } } }
6763be1cb8c11a10e7bfc488a9e230a7
23.328571
77
0.479154
false
false
false
false
jdspoone/Recipinator
refs/heads/master
RecipeBook/AppDelegate.swift
mit
1
/* Written by Jeff Spooner */ import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Instantiate the main window window = UIWindow(frame: UIScreen.main.bounds) // Create a CoreDataController and get the managed object context let coreDataController = CoreDataController() let managedObjectContext = coreDataController.getManagedObjectContext() // Embed the recipe table view controller in a navigation view controller, and set that as the root view controller let navigationViewController = UINavigationController(rootViewController: SearchViewController(context: managedObjectContext)) navigationViewController.navigationBar.isTranslucent = false self.window!.rootViewController = navigationViewController // Make the window key and visible window!.makeKeyAndVisible() return true } }
884b8ccf52e72fda4060cd73e8f3accd
28.947368
142
0.733743
false
false
false
false
terietor/GTForms
refs/heads/master
Source/Forms/FormSegmentedPicker.swift
mit
1
// Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import SnapKit import GTSegmentedControl private class SegmentedControlLabelView<L: UILabel>: ControlLabelView<L> { let segmentedControl = SegmentedControl() override init() { super.init() self.control = self.segmentedControl configureView() { (label, control) in label.snp.makeConstraints() { make in make.left.equalTo(self) make.width.equalTo(self).multipliedBy(0.4) make.top.equalTo(self) make.bottom.equalTo(self) } // end label control.snp.makeConstraints() { make in make.centerY.equalTo(label.snp.centerY).priority(UILayoutPriorityDefaultLow) make.right.equalTo(self) make.left.equalTo(label.snp.right).offset(10) make.height.lessThanOrEqualTo(self) } // end control } // end configureView } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public class FormSegmentedPicker: BaseResultForm<String> { private let segmentedControlView = SegmentedControlLabelView() public var segmentedControl: SegmentedControl { return self.segmentedControlView.segmentedControl } public init(text: String, items: [String], itemsPerRow: Int = 3) { super.init() self.text = text self.segmentedControlView.segmentedControl.items = items self.segmentedControlView.segmentedControl.itemsPerRow = itemsPerRow self.segmentedControlView.controlLabel.text = self.text self.segmentedControlView.segmentedControl.valueDidChange = { result in self.updateResult(result) } } public override func formView() -> UIView { return self.segmentedControlView } }
3c4a4df98df28aafc5ec27bd2add8a1c
34.681818
92
0.666561
false
false
false
false
esttorhe/SlackTeamExplorer
refs/heads/master
SlackTeamExplorer/SlackTeamCoreDataProxy/Models/Member.swift
mit
1
// Native Frameworks import CoreData import Foundation /// Member `NSManagedObject` model. @objc(Member) public class Member : NSManagedObject { // Basic properties @NSManaged public var membersIdentifier: String? @NSManaged public var realName: String? @NSManaged public var color: String? @NSManaged public var name: String // Timezones @NSManaged public var tzLabel: String @NSManaged public var tz: String @NSManaged public var tzOffset: Int32 // Customization Flags @NSManaged public var isUltraRestricted: Bool @NSManaged public var isOwner: Bool @NSManaged public var isPrimaryOwner: Bool @NSManaged public var isRestricted: Bool @NSManaged public var has2FA: Bool @NSManaged public var hasFiles: Bool @NSManaged public var devared: Bool @NSManaged public var isNot: Bool @NSManaged public var isAdmin: Bool // Relations @NSManaged public var profile: Profile? /** Inserts a new `Member` entity to the `context` provided initialized with the `json`. - :param: context The `NSManagedObjectContext` where the new `Member` entity will be inserted. - :param: json A `[NSObject:AnyObject?]` dictionary with the `JSON` schema used to seed the `Member` instance - :returns: A fully initialized `Member` instance with the values read from the `json` provided. */ public static func memberInContext(context: NSManagedObjectContext, json:[NSObject:AnyObject?]) -> Member? { if let member = NSEntityDescription.insertNewObjectForEntityForName("Member", inManagedObjectContext: context) as? Member { if let id = json["id"] as? String { member.membersIdentifier = id } if let isUltraRestricted = json["is_ultra_restricted"] as? Bool { member.isUltraRestricted = isUltraRestricted } if let realName = json["real_name"] as? String { member.realName = realName } if let isOwner = json["is_owner"] as? Bool { member.isOwner = isOwner } if let tzLabel = json["tz_label"] as? String { member.tzLabel = tzLabel } if let tz = json["tz"] as? String { member.tz = tz } if let isRestricted = json["is_restricted"] as? Bool { member.isRestricted = isRestricted } if let has2FA = json["has2fa"] as? Bool { member.has2FA = has2FA } if let hasFiles = json["has_files"] as? Bool { member.hasFiles = hasFiles } if let color = json["color"] as? String { member.color = color } if let devared = json["devared"] as? Bool { member.devared = devared } if let tzOffset = json["tz_offset"] as? Int32 { member.tzOffset = tzOffset } if let isNot = json["is_not"] as? Bool { member.isNot = isNot } if let isAdmin = json["is_admin"] as? Bool { member.isAdmin = isAdmin } if let name = json["name"] as? String { member.name = name } if let jsonProfile = json["profile"] as? Dictionary<NSObject, AnyObject> { member.profile = Profile.profileInContext(context, json: jsonProfile) } return member } return nil } }
afb3ee3507b297dad3aee576bd511f5f
32.587719
131
0.543103
false
false
false
false
dulingkang/Socket
refs/heads/master
SocketSwift/SocketDemo/PacketManager.swift
mit
1
// // PacketManager.swift // SocketDemo // // Created by dulingkang on 16/1/6. // Copyright © 2016年 dulingkang. All rights reserved. // import UIKit enum PacketType: Int { case SPT_NONE = 0, SPT_STATUS, SPT_CMD, SPT_LOG, SPT_FILE_START, SPT_FILE_SENDING } enum PacketJson: String { case fileLen, fileName } protocol PacketManagerDelegate { func updateImage(image: UIImage) } class PacketManager: NSObject { static let sharedInstance = PacketManager() var delegate: PacketManagerDelegate? var bufferData = NSMutableData() var fileLen: Int = 0 var fileOnceLen: Int = 0 var fileName: String = "" var needSave = false var fileData = NSMutableData() override init() {} func handleBufferData(data: NSData) { if data.length != 0 { bufferData.appendData(data) } let headerData = bufferData.subdataWithRange(NSMakeRange(0, headerLength)) if headerData.length == 0 { return } let payloadLength = parseHeader(headerData).payloadLength if bufferData.length == payloadLength + headerLength { self.processCompletePacket(bufferData) bufferData = NSMutableData() } else if bufferData.length > payloadLength + headerLength { let contentData = bufferData.subdataWithRange(NSMakeRange(headerLength, payloadLength)) self.processCompletePacket(contentData) let leftData = bufferData.subdataWithRange(NSMakeRange(payloadLength + headerLength, bufferData.length - payloadLength - headerLength)) bufferData = NSMutableData() bufferData.appendData(leftData) self.handleBufferData(NSData()) } } func parseHeader(headerData: NSData) -> (spt: Int, payloadLength: Int) { let stream: NSInputStream = NSInputStream(data: headerData) stream.open() var buffer = [UInt8](count: 4, repeatedValue: 0) var index: Int = 0 var spt: Int = 0 var payloadLength: Int = 0 while stream.hasBytesAvailable { stream.read(&buffer, maxLength: buffer.count) let sum: Int = Int(buffer[0]) + Int(buffer[1]) + Int(buffer[2]) + Int(buffer[3]) if index == 0 { if sum != 276 { return (0,0) } } if index == 1 { spt = sum } if index == 2 { payloadLength = sum } index++ print("buffer:", buffer) } return (spt, payloadLength) } func parseJsonBody(bodyData: NSData) -> NSDictionary? { do { let parsedObject = try NSJSONSerialization.JSONObjectWithData(bodyData, options: NSJSONReadingOptions.AllowFragments) print("parsedObject:", parsedObject) return parsedObject as? NSDictionary } catch { print("parse error") } return nil } func processCompletePacket(data: NSData) { let headerData = data.subdataWithRange(NSMakeRange(0, headerLength)) let spt = parseHeader(headerData).spt let payloadLength = parseHeader(headerData).payloadLength let leftData = data.subdataWithRange(NSMakeRange(headerLength, payloadLength)) let type: PacketType = PacketType(rawValue: spt)! switch type { case .SPT_NONE: break case .SPT_STATUS: break case .SPT_CMD: break case .SPT_LOG: break case .SPT_FILE_START: let dict: NSDictionary = self.parseJsonBody(leftData)! fileLen = dict.valueForKey(PacketJson.fileLen.rawValue) as! Int fileName = dict.valueForKey(PacketJson.fileName.rawValue) as! String if fileName.suffix() != "jpg" { needSave = true } case .SPT_FILE_SENDING: fileOnceLen = fileOnceLen + payloadLength if !needSave { fileData.appendData(leftData) if fileOnceLen == fileLen { self.delegate?.updateImage(UIImage.init(data: fileData)!) } } } } }
9d6d0c0226ee628de31d7ba34606aa7d
30.637681
147
0.573883
false
false
false
false
appcompany/SwiftSky
refs/heads/master
Sources/SwiftSky/Storm.swift
mit
1
// // Storm.swift // SwiftSky // // Created by Luca Silverentand on 11/04/2017. // Copyright © 2017 App Company.io. All rights reserved. // import Foundation import CoreLocation extension CLLocation { func destinationBy(_ distance: CLLocationDistance, direction: CLLocationDirection) -> CLLocation { let earthRadius = 6372.7976 let angularDistance = (distance / 1000) / earthRadius let originLatRad = self.coordinate.latitude * (.pi / 180) let originLngRad = self.coordinate.longitude * (.pi / 180) let directionRad = direction * (.pi / 180) let destinationLatRad = asin( sin(originLatRad) * cos(angularDistance) + cos(originLatRad) * sin(angularDistance) * cos(directionRad)) let destinationLngRad = originLngRad + atan2( sin(directionRad) * sin(angularDistance) * cos(originLatRad), cos(angularDistance) - sin(originLatRad) * sin(destinationLatRad)) let destinationLat: CLLocationDegrees = destinationLatRad * (180 / .pi) let destinationLng: CLLocationDegrees = destinationLngRad * (180 / .pi) return CLLocation(latitude: destinationLat, longitude: destinationLng) } } /// Contains a `Bearing` and `Distance` describing the location of a storm public struct Storm { /// `Bearing` from requested location where a storm can be found public let bearing : Bearing? /// `Distance` from requested location where a storm can be found public let distance : Distance? /// `` public let location : CLLocation? var hasData : Bool { if bearing != nil { return true } if distance != nil { return true } return false } init(bearing: Bearing?, distance: Distance?, origin: CLLocation?) { self.bearing = bearing self.distance = distance if bearing == nil || distance == nil || origin == nil { self.location = nil } else { self.location = origin?.destinationBy(Double(distance!.value(as: .meter)), direction: Double(bearing!.degrees)) } } }
d4042f307afc95d13aced5e4ca76e8fd
33.3125
123
0.621129
false
false
false
false
megavolt605/CNLUIKitTools
refs/heads/master
CNLUIKitTools/CNLUIT+UIColor.swift
mit
1
// // CNLUIT+UIColor.swift // CNLUIKitTools // // Created by Igor Smirnov on 11/11/2016. // Copyright © 2016 Complex Numbers. All rights reserved. // import UIKit import CNLFoundationTools public extension UIColor { public class func colorWithInt(red: UInt, green: UInt, blue: UInt, alpha: UInt) -> UIColor { let r = CGFloat(red) / 255.0 let g = CGFloat(green) / 255.0 let b = CGFloat(blue) / 255.0 let a = CGFloat(alpha) / 255.0 return UIColor(red: r, green: g, blue: b, alpha: a) } public class func colorWith(hex: UInt) -> UIColor { let red = hex % 0x100 let green = (hex >> 8) % 0x100 let blue = (hex >> 16) % 0x100 let alpha = (hex >> 24) % 0x100 return UIColor.colorWithInt(red: red, green: green, blue: blue, alpha: alpha) } public class func colorWith(string: String?, reverse: Bool = false) -> UIColor? { if let stringColor = string, let reversedColor = UInt(stringColor, radix: 16) { if reverse { let color1 = (reversedColor & 0x000000FF) << 16 let color2 = (reversedColor & 0x00FF0000) >> 16 let color3 = reversedColor & 0xFF00FF00 return UIColor.colorWith(hex: color1 | color2 | color3) } else { return UIColor.colorWith(hex: reversedColor) } } return nil } public func hexIntVaue(reversed: Bool = false) -> UInt { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 0.0 if getRed(&red, green: &green, blue: &blue, alpha: &alpha) { let hexRed = UInt(255.0 * red) let hexGreen = UInt(255.0 * green) << 8 let hexBlue = UInt(255.0 * blue) << 16 let hexAlpha = UInt(255.0 * alpha) << 24 let color = hexRed | hexGreen | hexBlue | hexAlpha if reversed { let reversedColor1 = (color & 0x000000FF) << 16 let reversedColor2 = (color & 0x00FF0000) >> 16 let reversedColor3 = color & 0xFF00FF00 return reversedColor1 | reversedColor2 | reversedColor3 } else { return color } } // opaque black by default return 0xFF000000 } public func hexValue(reversed: Bool = false) -> String { let value = hexIntVaue(reversed: reversed) return String(format: "%08x", value) } } /* extension UIColor: CNLDictionaryDecodable { public static func decodeValue(_ any: Any) -> Self? { if let value = any as? UInt { return self.colorWith(hex: value) } return nil } public func encodeValue() -> Any? { return hexValue() } } */
86a35e243bbff28fdfbb6ec2912a0e7f
31.862069
96
0.552641
false
false
false
false
tectijuana/patrones
refs/heads/master
Bloque1SwiftArchivado/PracticasSwift/SandovalChristopher/programa1.swift
gpl-3.0
1
/* Nombre del programa: Suma de dos n numeros nombre: Sandoval Lizarraga Chritopher */ //Importación de librerías import Foundation //declaración de constantes let val1 = 5 let val2 = -5 //variable donde se guarda la suma de los 2 valores var suma = 0 //suma de los 2 valores suma = val1 + val2 print("Suma de 2 valores") print("\n\(val1)\(val2) = \(suma)") //Bloque de control para indicar si la suma es positiva, negativa o 0 if suma < 0 {print("La suma es negativa")} else if suma == 0 {print("La suma es igual a 0")} else {print("La suma es positiva")}
d9a3b3c2a93d4993170efd894ed606d1
19.344828
70
0.672326
false
false
false
false
andrelind/Breeze
refs/heads/master
Breeze/BreezeStore+Saving.swift
mit
1
// // BreezeStore+Saving.swift // Breeze // // Created by André Lind on 2014-08-11. // Copyright (c) 2014 André Lind. All rights reserved. // import Foundation public typealias BreezeSaveBlock = (BreezeContextType) -> Void public typealias BreezeErrorBlock = (NSError?) -> Void extension BreezeStore { // MARK: Save in Main public class func saveInMain(changes: BreezeSaveBlock) { let moc = BreezeStore.contextForType(.Main) moc.performBlock { changes(.Main) var error: NSError? moc.save(&error) if error != nil { println("Breeze - Error saving main context: \(error!)") } } } public class func saveInMainWaiting(changes: BreezeSaveBlock) { let moc = BreezeStore.contextForType(.Main) moc.performBlockAndWait { () -> Void in changes(.Main) var error: NSError? moc.save(&error) if error != nil { println("Breeze - Error saving main context: \(error!)") } } } // MARK: Save in Background public class func saveInBackground(changes: BreezeSaveBlock) { saveInBackground(changes, completion: nil) } public class func saveInBackground(changes: BreezeSaveBlock, completion: BreezeErrorBlock?) { let moc = BreezeStore.contextForType(.Background) moc.performBlock { () -> Void in changes(.Background) var error: NSError? moc.save(&error) if error != nil { println("Breeze - Error saving background context: \(error!)") } if completion != nil { dispatch_async(dispatch_get_main_queue()) { completion!(error) } } } } }
0a9b50515f4e7ae781a40c2f3f5b531f
25.253521
97
0.559013
false
false
false
false
fromkk/SlackFeedback
refs/heads/master
FeedbackSlack/FeedbackSlack.swift
mit
1
// // FeedbackSlack.swift // SlackTest // // Created by Ueoka Kazuya on 2016/08/21. // Copyright © 2016年 fromKK. All rights reserved. // import Foundation @objc open class FeedbackSlack: NSObject { @objc public let slackToken: String @objc public let slackChannel: String @objc open var enabled: Bool = true @objc open var options: String? @objc var subjects: [String]? private init(slackToken: String, slackChannel: String, subjects: [String]? = nil) { self.slackToken = slackToken self.slackChannel = slackChannel self.subjects = subjects super.init() NotificationCenter.default.addObserver(self, selector: #selector(FeedbackSlack.screenshotNotification(_:)), name: UIApplication.userDidTakeScreenshotNotification, object: nil) } @objc public static var shared: FeedbackSlack? private lazy var sharedWindow: UIWindow = { let result: UIWindow = UIWindow(frame: UIApplication.shared.keyWindow?.bounds ?? UIScreen.main.bounds) return result }() @objc public static func setup(_ slackToken: String, slackChannel: String, subjects: [String]? = nil) -> FeedbackSlack? { if let feedback: FeedbackSlack = shared { return feedback } shared = FeedbackSlack(slackToken: slackToken, slackChannel: slackChannel, subjects: subjects) return shared } private var feedbacking: Bool = false @objc func screenshotNotification(_ notification: Notification) { guard let window: UIWindow = UIApplication.shared.delegate?.window!, !self.feedbacking, self.enabled else { return } self.feedbacking = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) { [unowned self] in UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, 0.0) window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() let viewController: FeedbackSlackViewController = FeedbackSlackViewController.instantitate() viewController.image = image self.sharedWindow.isHidden = false self.sharedWindow.rootViewController = viewController self.sharedWindow.alpha = 0.0 self.sharedWindow.makeKeyAndVisible() UIView.animate(withDuration: 0.33, animations: { [unowned self] in self.sharedWindow.alpha = 10.0 }) } } func close() { DispatchQueue.main.async { [unowned self] in self.sharedWindow.alpha = 1.0 UIView.animate(withDuration: 0.33, animations: { [unowned self] in self.sharedWindow.alpha = 0.0 }) { [unowned self] (finished: Bool) in self.sharedWindow.isHidden = true self.feedbacking = false UIApplication.shared.delegate?.window??.makeKeyAndVisible() } } } }
61ab95def4e213c4718a28c2252db959
38.269231
183
0.651322
false
false
false
false
lee5783/TLMonthYearPicker
refs/heads/master
Classes/TLMonthYearPickerView.swift
mit
1
// // TLMonthYearPickerView.swift // TLMonthYearPicker // // Created by lee5783 on 12/22/16. // Copyright © 2016 lee5783. All rights reserved. // import UIKit /// enum MonthYearPickerMode /// /// - monthAndYear: Show month and year components /// - year: Show year only public enum MonthYearPickerMode: Int { case monthAndYear = 0 case year = 1 } /// Maximum year constant fileprivate let kMaximumYears = 5000 /// Minimum year constant fileprivate let kMinimumYears = 1 public protocol TLMonthYearPickerDelegate: NSObjectProtocol { /// Delegate: notify picker date changed /// /// - Parameters: /// - picker: return picker instant /// - date: return picker date value func monthYearPickerView(picker: TLMonthYearPickerView, didSelectDate date: Date) } public class TLMonthYearPickerView: UIControl, UIPickerViewDataSource, UIPickerViewDelegate { /// Set picker mode: monthAndYear or year only fileprivate var _mode: MonthYearPickerMode = .monthAndYear public var monthYearPickerMode: MonthYearPickerMode { get { return self._mode } set(value) { self._mode = value self._picker?.reloadAllComponents() self.setDate(date: self.date, animated: false) } } /// Locale value, default is device locale fileprivate var _locale: Locale? var locale: Locale! { get { if self._locale != nil { return self._locale! } else { return Locale.current } } set(value) { self._locale = value self.calendar.locale = value } } /// Calendar value, default is device calendar fileprivate var _calendar: Calendar! public var calendar: Calendar! { get { if self._calendar != nil { return self._calendar } else { var calendar = Calendar.current calendar.locale = self.locale return calendar } } set(value) { self._calendar = value self._locale = value.locale self.initPickerData() } } /// Picker text color, default is black color public var textColor: UIColor = UIColor.black { didSet(value) { self._picker?.reloadAllComponents() } } /// Picker font, default is system font with size 16 public var font: UIFont = UIFont.systemFont(ofSize: 16) { didSet(value) { self._picker?.reloadAllComponents() } } /// Get/Set Picker background color public override var backgroundColor: UIColor? { get { return super.backgroundColor } set(value) { super.backgroundColor = value self._picker?.backgroundColor = value } } /// Current picker value public var date: Date! /// Delegate public weak var delegate: TLMonthYearPickerDelegate? /// Maximum date fileprivate var _minimumDate: Date? public var minimumDate: Date? { get { return self._minimumDate } set(value) { self._minimumDate = value if let date = value { let components = self.calendar.dateComponents([.year, .month], from: date) _minimumYear = components.year! _minimumMonth = components.month! } else { _minimumYear = -1 _minimumMonth = -1 } self._picker?.reloadAllComponents() } } /// Mimimum date fileprivate var _maximumDate: Date? public var maximumDate: Date? { get { return self._maximumDate } set(value) { self._maximumDate = value if let date = value { let components = self.calendar.dateComponents([.year, .month], from: date) _maximumYear = components.year! _maximumMonth = components.month! } else { _maximumYear = -1 _maximumMonth = -1 } self._picker?.reloadAllComponents() } } //MARK: - Internal variables /// UIPicker var _picker: UIPickerView! /// month year array values fileprivate var _months: [String] = [] fileprivate var _years: [String] = [] /// Store caculated value of minimum year-month and maximum year-month fileprivate var _minimumYear = -1 fileprivate var _maximumYear = -1 fileprivate var _minimumMonth = -1 fileprivate var _maximumMonth = -1 override init(frame: CGRect) { super.init(frame: frame) self.initView() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initView() } /// Initial view /// Setup Picker and Picker data internal func initView() { self._picker = UIPickerView(frame: self.bounds) self._picker.showsSelectionIndicator = true self._picker.delegate = self self._picker.dataSource = self self._picker.autoresizingMask = [.flexibleWidth, .flexibleHeight] self._picker.translatesAutoresizingMaskIntoConstraints = true self.addSubview(self._picker) self.clipsToBounds = true self.initPickerData() self.date = Date() self._picker.reloadAllComponents() } /// Setup picker data internal func initPickerData() { //list of month let dateFormatter = DateFormatter() dateFormatter.locale = self.locale self._months = dateFormatter.monthSymbols dateFormatter.dateFormat = "yyyy" var components = DateComponents() self._years.removeAll() for year in kMinimumYears...kMaximumYears { components.year = year if let date = self.calendar.date(from: components) { self._years.append(dateFormatter.string(from: date)) } } } /// Set picker date to UI override public func didMoveToSuperview() { super.didMoveToSuperview() self.setDate(date: self.date, animated: false) } override public func layoutSubviews() { super.layoutSubviews() self._picker?.frame = self.bounds } //MARK: - Public function /// Set date to picker /// /// - Parameters: /// - date: the date user choose /// - animated: display UI animate or not func setDate(date: Date, animated: Bool) { // Extract the month and year from the current date value let components = self.calendar.dateComponents([.year, .month], from: date) let month = components.month! let year = components.year! self.date = date if self.monthYearPickerMode == .year { self._picker.selectRow(year - kMinimumYears, inComponent: 0, animated: animated) } else { self._picker.selectRow(year - kMinimumYears, inComponent: 1, animated: animated) self._picker.selectRow(month - 1, inComponent: 0, animated: animated) } } //MARK: - Implement UIPickerViewDataSource, UIPickerViewDelegate /// - Parameters: /// - Parameter pickerView /// - Returns: return 2 if pickerMode is monthAndYear, otherwise return 1 public func numberOfComponents(in pickerView: UIPickerView) -> Int { return self.monthYearPickerMode == .year ? 1 : 2 } /// - Parameters: /// - pickerView /// - component /// - Returns: return number of row public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if self.monthYearPickerMode == .year { return self._years.count } else { if component == 0 { return self._months.count } else { return self._years.count } } } /// - Parameters: /// - pickerView /// - row /// - component /// - Returns: display string of specific row in specific component public func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let isSelectYear = self.monthYearPickerMode == .year || component == 1 var shouldDisable = false if isSelectYear { let year = row + kMinimumYears if (self._maximumDate != nil && year > _maximumYear) || (self._minimumDate != nil && year < _minimumYear) { shouldDisable = true } } else { let month = row + 1 let components = self.calendar.dateComponents([.year], from: self.date) let year = components.year! if (self._maximumDate != nil && year > _maximumYear) || (year == _maximumYear && month > _maximumMonth) || (self._minimumDate != nil && year < _minimumYear) || (year == _minimumYear && month < _minimumMonth) { shouldDisable = true } } var text = "" if self.monthYearPickerMode == .year { text = self._years[row] } else { if component == 0 { text = self._months[row] } else { text = self._years[row] } } var color = self.textColor if shouldDisable { color = color.withAlphaComponent(0.5) } return NSAttributedString(string: text, attributes: [ .font: self.font, .foregroundColor: color ]) } /// - Parameters: /// - pickerView /// - row /// - component public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if let date = self.dateFromSelection() { var targetDate = date if let minimumDate = self._minimumDate { if minimumDate.compare(date) == .orderedDescending { targetDate = minimumDate } } if let maximumDate = self._maximumDate { if maximumDate.compare(date) == .orderedAscending { targetDate = maximumDate } } self.setDate(date: targetDate, animated: true) self.delegate?.monthYearPickerView(picker: self, didSelectDate: targetDate) if self.monthYearPickerMode == .monthAndYear { self._picker.reloadComponent(0) } } } /// Compare only month and year value /// /// - Parameters: /// - date1: first date you want to compare /// - date2: second date you want to compare /// - Returns: ComparisonResult fileprivate func compareMonthAndYear(date1: Date, date2: Date) -> ComparisonResult { let components1 = self.calendar.dateComponents([.year, .month], from: date1) let components2 = self.calendar.dateComponents([.year, .month], from: date2) if let date1Compare = self.calendar.date(from: components1), let date2Compare = self.calendar.date(from: components2) { return date1Compare.compare(date2Compare) } else { return date1.compare(date2) } } /// Caculate date of current picker /// /// - Returns: Date fileprivate func dateFromSelection() -> Date? { var month = 1 var year = 1 if self.monthYearPickerMode == .year { year = self._picker.selectedRow(inComponent: 0) + kMinimumYears } else { month = self._picker.selectedRow(inComponent: 0) + 1 year = self._picker.selectedRow(inComponent: 1) + kMinimumYears } var components = DateComponents() components.month = month components.year = year components.day = 1 components.timeZone = TimeZone(secondsFromGMT: 0) return self.calendar.date(from: components) } }
36a2fd89d6627024cd44484530dbbb9f
30.034739
140
0.556888
false
false
false
false
NordicSemiconductor/IOS-nRF-Toolbox
refs/heads/master
nRF Toolbox/CommonViews/NordicButton.swift
bsd-3-clause
1
/* * Copyright (c) 2020, Nordic Semiconductor * 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. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS 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 struct NordicButtonConfigurator { var isHidden: Bool = false var normalTitle: String var style: NordicButton.Style = .default } class NordicButton: UIButton { struct Style: RawRepresentable, Equatable { let rawValue: Int static let `default` = Style(rawValue: 1) static let mainAction = Style(rawValue: 2) static let destructive = Style(rawValue: 3) var tintColor: UIColor { switch self { case .mainAction: return .white case .destructive: return .nordicRed case .default: return .nordicLake default: return UIColor.Text.systemText } } var bgColor: UIColor { switch self { case .default, .destructive: return .clear case .mainAction: return .nordicLake default: return .clear } } var borderColor: UIColor { switch self { case .destructive: return .nordicRed case .mainAction, .default: return .nordicLake default: return .clear } } } override var isEnabled: Bool { didSet { setupBrandView() } } var style: Style = .default { didSet { tintColor = style.tintColor borderColor = style.borderColor self.setupBrandView() } } var normalTitle: String? { get { title(for: .normal) } set { setTitle(newValue, for: .normal) } } override init(frame: CGRect) { super.init(frame: frame) setupBrandView() } required init?(coder: NSCoder) { super.init(coder: coder) setupBrandView() } override func awakeFromNib() { super.awakeFromNib() style = .default } private func setupBrandView() { cornerRadius = 4 borderWidth = 1 guard isEnabled else { setTitleColor(UIColor.Text.inactive, for: .normal) borderColor = UIColor.Text.inactive backgroundColor = .clear return } borderColor = style.borderColor setTitleColor(style.tintColor, for: .normal) backgroundColor = style.bgColor } override func draw(_ rect: CGRect) { super.draw(rect) cornerRadius = 4 layer.masksToBounds = true } func apply(configurator: NordicButtonConfigurator) { isHidden = configurator.isHidden setTitle(configurator.normalTitle, for: .normal) style = configurator.style } }
b6775c336851e01afd8ab88cc625d34d
30.167883
84
0.633958
false
false
false
false
miktap/pepe-p06
refs/heads/master
PePeP06/PePeP06Tests/TasoClientTests.swift
mit
1
// // TasoClientTests.swift // PePeP06Tests // // Created by Mikko Tapaninen on 24/12/2017. // import Quick import Nimble import ObjectMapper import SwiftyBeaver @testable import PePeP06 class TasoClientTests: QuickSpec { override func spec() { describe("Taso") { var tasoClient: TasoClient! beforeEach { tasoClient = TasoClient() tasoClient.initialize() sleep(1) } describe("getTeam") { it("gets PePe team") { var teamListing: TasoTeamListing? tasoClient.getTeam(team_id: "141460", competition_id: "lsfs1718", category_id: "FP12")! .then { response -> Void in let message = String(data: response.data!, encoding: .utf8) log.debug(message!) teamListing = TasoTeamListing(JSONString: message!) } expect(teamListing?.team.team_name).toEventually(equal("PePe"), timeout: 3) } } describe("getCompetitions") { it("gets lsfs1718 competition") { var competitionListing: TasoCompetitionListing? tasoClient.getCompetitions()! .then { response -> Void in let message = String(data: response.data!, encoding: .utf8) log.debug(message!) competitionListing = TasoCompetitionListing(JSONString: message!) } expect(competitionListing?.competitions!).toEventually(containElementSatisfying({$0.competition_id == "lsfs1718"}), timeout: 3) } } describe("getCategories") { it("gets category FP12") { var categoryListing: TasoCategoryListing? tasoClient.getCategories(competition_id: "lsfs1718")! .then { response -> Void in let message = String(data: response.data!, encoding: .utf8) log.debug(message!) categoryListing = TasoCategoryListing(JSONString: message!) } expect(categoryListing?.categories).toEventually(containElementSatisfying({$0.category_id == "FP12"}), timeout: 3) } } describe("getClub") { it("gets club 3077") { var clubListing: TasoClubListing? tasoClient.getClub()! .then { response -> Void in let message = String(data: response.data!, encoding: .utf8) log.debug(message!) clubListing = TasoClubListing(JSONString: message!) } expect(clubListing?.club?.club_id).toEventually(equal("3077"), timeout: 3) } } describe("getPlayer") { it("gets player Jimi") { var playerListing: TasoPlayerListing? tasoClient.getPlayer(player_id: "290384")! .then { response -> Void in let message = String(data: response.data!, encoding: .utf8) log.debug(message!) playerListing = TasoPlayerListing(JSONString: message!) } expect(playerListing?.player?.first_name).toEventually(equal("Jimi"), timeout: 3) } } describe("getGroup") { it("gets group with team standings") { var groupListing: TasoGroupListing? tasoClient.getGroup(competition_id: "lsfs1718", category_id: "FP12", group_id: "1")! .then { response -> Void in let message = String(data: response.data!, encoding: .utf8) log.debug(message!) groupListing = TasoGroupListing(JSONString: message!) } expect(groupListing?.group?.teams).toNotEventually(beNil(), timeout: 3) } } } } }
aa14940fef9b79b6284085f411332f38
40.927273
147
0.460104
false
false
false
false
GoogleCloudPlatform/ios-docs-samples
refs/heads/master
screensaver/GCPLife/GCPLifeView.swift
apache-2.0
1
// Copyright 2016 Google Inc. 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 Cocoa import ScreenSaver let stepDuration = 1.0 let fadeDuration = 0.5 let cellSize:CGFloat = 128.0 let host = "storage.googleapis.com" let bucket = "gcp-screensaver.appspot.com" class GCPLifeView: ScreenSaverView { var gridViews:[[NSImageView]]! var grid:[[Int]]! var newgrid:[[Int]]! var imageNames:[String]! var timer:Timer! var history:[String: Int]! override init?(frame: NSRect, isPreview: Bool) { super.init(frame: frame, isPreview: isPreview) startRunning() } required init?(coder: NSCoder) { super.init(coder:coder) startRunning() } override func resizeSubviews(withOldSize oldSize: NSSize) { buildGrid() randomizeGrid() renderGrid() } override func draw(_ dirtyRect: NSRect) { NSColor(white: 0.2, alpha: 1).set() NSRectFill(bounds) } func startRunning() { animationTimeInterval = 1/30.0 // Prepare the display in case there is no network connection. buildGrid() renderGrid() // Fetch the icon list and start animating. fetchIconList { self.buildGrid() self.renderGrid() self.timer = Timer.scheduledTimer(timeInterval: stepDuration, target: self, selector: #selector(self.tick), userInfo: nil, repeats: true) } } func buildGrid() { let bundle = Bundle(for: type(of: self)) history = [String: Int]() if gridViews != nil { for views in gridViews { for view in views { view.removeFromSuperview() } } } let cellWidth = cellSize * sqrt(3) / 2 let centerX = (bounds.size.width - cellSize) * 0.5 let centerY = (bounds.size.height - cellSize) * 0.5 let rows:Int = Int(bounds.size.height/cellSize * 0.5 + 0.5) let cols:Int = Int(bounds.size.width/cellWidth * 0.5 + 0.5) var i:Int = 0 grid = [] newgrid = [] gridViews = [] for r in -rows...rows { grid.append([]) newgrid.append([]) gridViews.append([]) for c in -cols...cols { let cellX:CGFloat = centerX + CGFloat(c) * cellSize * sqrt(3) / 2 var cellY:CGFloat = centerY + CGFloat(r) * cellSize let odd:Bool = abs(c) % 2 == 1 if odd { cellY -= 0.5 * cellSize } let imageFrame = NSRect(x : cellX, y : cellY, width: cellSize, height: cellSize) let view = NSImageView.init(frame: imageFrame) addSubview(view) if r == 0 && c == 0 { let imageName = "Logo_Cloud_512px_Retina.png" let imagePath = bundle.pathForImageResource(imageName)! let image = NSImage.init(contentsOfFile: imagePath) view.image = image grid[r+rows].append(1) newgrid[r+rows].append(1) // Expand the logo image slightly to match the product icon sizes. let ds = -0.05*cellSize view.frame = view.frame.insetBy(dx: ds, dy: ds) } else { if let imageNames = imageNames { let imageName = imageNames[i % imageNames.count] i = i + 1 fetchImage(view, name:imageName) } grid[r+rows].append(0) newgrid[r+rows].append(0) } gridViews[r+rows].append(view) } } } func renderGrid() { let rows = grid.count let cols = grid[0].count for r in 0..<rows { for c in 0..<cols { let gridView = gridViews[r][c] if grid[r][c] == 0 { if newgrid[r][c] == 0 { gridView.alphaValue = 0 gridView.isHidden = true } else { gridView.alphaValue = 0 gridView.isHidden = false NSAnimationContext.runAnimationGroup({ (context) in context.duration = fadeDuration gridView.animator().alphaValue = 1 }, completionHandler: { }) } } else { if newgrid[r][c] == 0 { gridView.alphaValue = 1 NSAnimationContext.runAnimationGroup({ (context) in context.duration = fadeDuration gridView.animator().alphaValue = 0 }, completionHandler: { gridView.isHidden = true }) } else { gridView.isHidden = false gridView.alphaValue = 1 } } } } } func tick() { updateGrid() renderGrid() } func randomizeGrid() { history = [String: Int]() let rows = grid.count let cols = grid[0].count for r in 0..<rows { for c in 0..<cols { let diceRoll = Int(arc4random_uniform(6) + 1) if diceRoll > 5 { newgrid[r][c] = 1 } else { newgrid[r][c] = 0 } grid[r][c] = 0 } } // The center cell should always be alive. newgrid[rows/2][cols/2] = 1 grid[rows/2][cols/2] = 1 } // Compute a signature for the current grid. // This will allow us to detect repeats (and cycles). func signature() -> String { let data = NSMutableData() var i = 0 var v:UInt64 = 0 let rows = grid.count let cols = grid[0].count for r in 0..<rows { for c in 0..<cols { if grid[r][c] != 0 { v = v | UInt64(UInt64(1) << UInt64(i)) } i = i + 1 if i == 64 { data.append(&v, length: MemoryLayout.size(ofValue: v)) i = 0 v = 0 } } } if i > 0 { data.append(&v, length: MemoryLayout.size(ofValue: v)) } return data.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue:0)) } func updateGrid() { // First check for repetitions. let s = signature() if let x = history[s] { if (x == 3) { randomizeGrid() return } history[s] = x + 1 } else { history[s] = 1 } // Compute new grid state. let rows = grid.count let cols = grid[0].count grid = newgrid newgrid = [] for r in 0..<rows { newgrid.append([]) for c in 0..<cols { // Count the neighbors of cell (r,c). var alive = grid[r][c] var count = 0 for rr in -1...1 { for cc in -1...1 { if rr == 0 && cc == 0 { // Don't count the center cell. } else { // Wrap coordinates around the grid edges. var rrr = (r + rr) if rrr >= rows { rrr = rrr - rows } else if rrr < 0 { rrr = rrr + rows } var ccc = (c + cc) if ccc >= cols { ccc = ccc - cols } else if ccc < 0 { ccc = ccc + cols } count += grid[rrr][ccc] } } } // Compute the new cell liveness following // https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life if (alive == 0) { if (count == 3) { // Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. alive = 1 } else { alive = 0 } } else { if (count == 2) || (count == 3) { // Any live cell with two or three live neighbours lives on to the next generation. alive = 1 } else { // Any live cell with fewer than two live neighbours dies, as if caused by under-population. // Any live cell with more than three live neighbours dies, as if by over-population. alive = 0 } } // Arbitrarily keep the center cell alive always. if r == rows/2 && c == cols/2 { alive = 1 } newgrid[r].append(alive) } } } func fetchIconList(_ continuation:@escaping ()->()) { var urlComponents = URLComponents() urlComponents.scheme = "https"; urlComponents.host = host urlComponents.path = "/" + bucket + "/icons.txt" if let url = urlComponents.url { let request = URLRequest(url:url) let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { (data, response, error) in if let error = error { NSLog("error \(error)") } else if let data = data { DispatchQueue.main.async { if let content = String.init(data: data, encoding: String.Encoding.utf8) { self.imageNames = content.components(separatedBy: CharacterSet.whitespacesAndNewlines) self.imageNames.removeLast() continuation() } } } else { DispatchQueue.main.async { self.imageNames = [] continuation() } } }) task.resume() } } func fetchImage(_ imageView:NSImageView, name:String) { var urlComponents = URLComponents() urlComponents.scheme = "https"; urlComponents.host = host urlComponents.path = "/" + bucket + "/" + name if let url = urlComponents.url { let request = URLRequest(url:url) let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { (data, response, error) in if let error = error { NSLog("error \(error)") } else if let data = data { DispatchQueue.main.async { imageView.image = NSImage(data: data) } } else { NSLog("failed to load \(name)") DispatchQueue.main.async { imageView.image = nil; } } }) task.resume() } } }
fdd7c75a186c468750de2c6c9f091861
27.669444
105
0.536963
false
false
false
false
DroidsOnRoids/PhotosHelper
refs/heads/master
Example/PhotosHelper/ViewController.swift
mit
1
// // ViewController.swift // PhotosHelper // // Created by Andrzej Filipowicz on 12/03/2015. // Copyright (c) 2015 Andrzej Filipowicz. All rights reserved. // import UIKit import AVFoundation import PhotosHelper let padding: CGFloat = 10.0 class ViewController: UIViewController { var captureSession: AVCaptureSession? var captureLayer: AVCaptureVideoPreviewLayer? let output = AVCaptureStillImageOutput() override func viewDidLoad() { super.viewDidLoad() setupCamera() setupUI() } func setupUI() { view.clipsToBounds = true let captureButton = UIButton() captureButton.setTitle("take a picture", forState: .Normal) captureButton.sizeToFit() captureButton.addTarget(self, action: #selector(ViewController.takePicture(_:)), forControlEvents: .TouchUpInside) captureButton.center = CGPoint(x: view.frame.midX, y: view.frame.height - captureButton.frame.midY - padding) view.addSubview(captureButton) } func setupCamera() { captureSession = AVCaptureSession() guard let captureSession = captureSession else { return } captureSession.beginConfiguration() setDeviceInput() if captureSession.canSetSessionPreset(AVCaptureSessionPresetHigh) { captureSession.sessionPreset = AVCaptureSessionPresetHigh } if captureSession.canAddOutput(output) { captureSession.addOutput(output) } captureLayer = AVCaptureVideoPreviewLayer(session: captureSession) captureLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill captureLayer?.frame = view.bounds guard let captureLayer = captureLayer else { return } view.layer.addSublayer(captureLayer) captureSession.commitConfiguration() captureSession.startRunning() } private func setDeviceInput(back: Bool = true) { guard let captureSession = captureSession else { return } if let input = captureSession.inputs.first as? AVCaptureInput { captureSession.removeInput(input) } let device = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) .filter {$0.position == (back ? .Back : .Front)} .first as? AVCaptureDevice ?? AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) guard let input = try? AVCaptureDeviceInput(device: device) else { return } if captureSession.canAddInput(input) { captureSession.addInput(input) } } func takePicture(sender: AnyObject) { let connection = output.connectionWithMediaType(AVMediaTypeVideo) output.captureStillImageAsynchronouslyFromConnection(connection) { [weak self] buffer, error in guard let `self` = self where error == nil else { return } let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) guard let image = UIImage(data: imageData) else { return } PhotosHelper.saveImage(image, toAlbum: "Example Album") { success, _ in guard success else { return } dispatch_async(dispatch_get_main_queue(), { let alert = UIAlertController(title: "Photo taken", message: "Open Photos.app to see that an album with your photo was created.", preferredStyle: .Alert) let action = UIAlertAction(title: "Ok", style: .Default, handler: nil) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) }) } } } }
7a0a0cdf53112e68b4afc2ddf43966be
35.028302
173
0.637601
false
false
false
false
CodePath2017Group4/travel-app
refs/heads/master
RoadTripPlanner/AlbumCell.swift
mit
1
// // AlbumCell.swift // RoadTripPlanner // // Created by Nanxi Kang on 10/14/17. // Copyright © 2017 Deepthy. All rights reserved. // import UIKit import Parse class AlbumCell: UITableViewCell { @IBOutlet weak var albumImage: UIImageView! @IBOutlet weak var albumLabel: UILabel! @IBOutlet weak var tripLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var createdByLabel: UILabel! @IBOutlet weak var deleteViewTrailing: NSLayoutConstraint! @IBOutlet weak var deleteView: UIView! var delegate: DeleteAlbumDelegate? var albumIndex: IndexPath? var album: Album? var panRecognizer: UIPanGestureRecognizer? func displayAlbum(album: Album) { hideDelete() if (self.album == nil) { self.album = Album() } self.album!.updated(copyFrom: album) albumImage.image = UIImage(named: "album-default") albumImage.contentMode = .scaleAspectFit if (album.photos.count > 0) { album.photos[0].getDataInBackground(block: { (data, error) -> Void in if (error == nil) { if let data = data { DispatchQueue.main.async { self.albumImage.image = UIImage(data: data) self.albumImage.contentMode = .scaleAspectFill } } } }) } albumLabel.text = album.albumName print("set owner") if let owner = album.owner { owner.fetchInBackground(block: { (object, error) in if error == nil { DispatchQueue.main.async { let realOwner = object as! PFUser self.createdByLabel.text = realOwner.username } } else { log.error("Error fetching album owner: \(error!)") } }) } print("set trip") if let trip = album.trip { trip.fetchInBackground(block: { (object, error) in if error == nil { DispatchQueue.main.async { let realTrip = object as! Trip if let date = realTrip.date { self.dateLabel.text = Utils.formatDate(date: date) } else { self.dateLabel.text = "unknown" } self.tripLabel.text = realTrip.name } } else { log.error("Error fetching trip: \(error!)") } }) } } func hideDelete() { deleteViewTrailing.constant = -deleteView.frame.width } func showDelete() { deleteViewTrailing.constant = 0 } override func awakeFromNib() { super.awakeFromNib() self.panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panThisCell)) self.panRecognizer!.delegate = self self.contentView.addGestureRecognizer(self.panRecognizer!) } override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } @IBAction func panThisCell(_ sender: UIPanGestureRecognizer) { // Absolute (x,y) coordinates in parent view (parentView should be // the parent view of the tray) let point = sender.location(in: self) if sender.state == .began { print("Gesture began at: \(point)") } else if sender.state == .changed { let velocity = sender.velocity(in: self) if (velocity.x < 0) { // LEFT UIView.animate(withDuration: 0.5, animations: self.showDelete) } else if (velocity.x > 0){ // RIGHT UIView.animate(withDuration: 0.5, animations: self.hideDelete) } } else if sender.state == .ended { print("Gesture ended at: \(point)") } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } @IBAction func deleteAlbumTapped(_ sender: Any) { guard self.delegate != nil && self.album != nil && self.albumIndex != nil else { return } self.delegate!.deleteAlbum(album: self.album!, indexPath: self.albumIndex!) } }
6f3816805e2aac5a0938e2ba0c035ecd
32.811594
166
0.534076
false
false
false
false
ibm-bluemix-mobile-services/bluemix-pushnotifications-swift-sdk
refs/heads/master
Sources/PushNotifications.swift
apache-2.0
2
/* *     Copyright 2016 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ import Foundation import SimpleHttpClient /** The type of callback to send with PushNotifications requests. */ public typealias PushNotificationsCompletionHandler = (_ data: Data?,_ status: Int?,_ error: PushNotificationsError?) -> Void /** Used to send Push notifications via a IBM Cloud Push Notifications service. */ public class PushNotifications { /// The IBM Cloud region where the Push Notifications service is hosted. public struct Region { public static let US_SOUTH = "us-south" public static let UK = "eu-gb" public static let SYDNEY = "au-syd" public static let FRANKFURT = "eu-de" public static let US_EAST = "us-east" public static let JP_TOK = "jp-tok" } internal var headers = [String: String]() private var httpResource = HttpResource(schema: "", host: "") private var httpBulkResource = HttpResource(schema: "", host: "") private var pushApiKey = "" private var pushAppRegion = "" // used to test in test zone and dev zone public static var overrideServerHost = ""; /** Initialize PushNotifications by supplying the information needed to connect to the IBM Cloud Push Notifications service. - parameter pushRegion: The IBM Cloud region where the Push Notifications service is hosted. - parameter pushAppGuid: The app GUID for the IBM Cloud application that the Push Notifications service is bound to. - parameter pushAppSecret: The appSecret credential required for Push Notifications service authorization. */ public init(pushRegion: String, pushAppGuid: String, pushAppSecret: String) { headers = ["appSecret": pushAppSecret, "Content-Type": "application/json"] if(PushNotifications.overrideServerHost.isEmpty){ var pushHost = pushRegion+".imfpush.cloud.ibm.com" httpResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/imfpush/v1/apps/\(pushAppGuid)/messages") httpBulkResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/imfpush/v1/apps/\(pushAppGuid)/messages/bulk") }else{ let url = URL(string: PushNotifications.overrideServerHost) httpResource = HttpResource(schema: (url?.scheme)!, host: (url?.host)!, path: "/imfpush/v1/apps/\(pushAppGuid)/messages") httpBulkResource = HttpResource(schema: (url?.scheme)!, host: (url?.host)!, path: "/imfpush/v1/apps/\(pushAppGuid)/messages/bulk") } } /** Initialize PushNotifications by supplying the information needed to connect to the IBM Cloud Push Notifications service. - parameter pushRegion: The IBM Cloud region where the Push Notifications service is hosted. - parameter pushAppGuid: The app GUID for the IBM Cloud application that the Push Notifications service is bound to. - parameter pushApiKey: The ApiKey credential required for Push Notifications service authorization. */ public init(pushApiKey:String, pushAppGuid: String, pushRegion: String) { self.pushApiKey = pushApiKey self.pushAppRegion = pushRegion if(PushNotifications.overrideServerHost.isEmpty) { let pushHost = pushRegion+".imfpush.cloud.ibm.com" httpResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/imfpush/v1/apps/\(pushAppGuid)/messages") httpBulkResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/imfpush/v1/apps/\(pushAppGuid)/messages/bulk") } else { let url = URL(string: PushNotifications.overrideServerHost) httpResource = HttpResource(schema: (url?.scheme)!, host: (url?.host)!, path: "/imfpush/v1/apps/\(pushAppGuid)/messages") httpBulkResource = HttpResource(schema: (url?.scheme)!, host: (url?.host)!, path: "/imfpush/v1/apps/\(pushAppGuid)/messages/bulk") } } /** This method will get an iam auth token from the server and add it to the request header. Get Auth token before calling any send methods. - parameter completionHandler: Returns true if there is token with token string */ public func getAuthToken(completionHandler: @escaping (_ hasToken:Bool?, _ tokenValue: String) -> Void) { if (pushApiKey != "" && pushAppRegion != "") { var regionString = pushAppRegion; var pushHost = "iam." if (!PushNotifications.overrideServerHost.isEmpty) { let url = URL(string: PushNotifications.overrideServerHost) let domain = url?.host if let splitStringArray = domain?.split(separator: ".", maxSplits: 1, omittingEmptySubsequences: true) { regionString = String(splitStringArray[1]) } pushHost = pushHost + regionString } else{ pushHost = pushHost + "cloud.ibm.com" } let iamHttpResource = HttpResource(schema: "https", host: pushHost, port: "443", path: "/identity/token") var data:Data? let dataString = "grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey=\(pushApiKey)" data = dataString.data(using: .ascii, allowLossyConversion: true) let iamHeaders = ["Content-Type":"application/x-www-form-urlencoded","Accept":"application/json"] HttpClient.post(resource: iamHttpResource, headers: iamHeaders, data: data) { (error, status, headers, data) in //completionHandler?(data,status,PushNotificationsError.from(httpError: error)) if(status == 200) { let dataJson = try! JSONSerialization.jsonObject(with: data!, options:JSONSerialization.ReadingOptions.allowFragments) as! [String:Any] let tokenString = dataJson["access_token"] as? String if !(tokenString?.isEmpty)! { self.headers = ["Authorization": "Bearer " + tokenString!, "Content-Type": "application/json"] } completionHandler(true, tokenString!) } else { print("Error While getting the token", error ?? "") completionHandler(false, "") } } } else { print("Error : Pass valid Apikey and app region") completionHandler(false, "") } } /** Send the Push notification. - parameter notificiation: The push notification to send. - paramter completionHandler: The callback to be executed when the send request completes. */ public func send(notification: Notification, completionHandler: PushNotificationsCompletionHandler?) { guard let requestBody = notification.jsonFormat else { completionHandler?(nil,500,PushNotificationsError.InvalidNotification) return } guard let data = try? JSONSerialization.data(withJSONObject: requestBody, options: .prettyPrinted) else{ completionHandler?(nil,500,PushNotificationsError.InvalidNotification) return } HttpClient.post(resource: httpResource, headers: headers, data: data) { (error, status, headers, data) in completionHandler?(data,status,PushNotificationsError.from(httpError: error)) } } /** Send Bulk Push notification. - parameter notificiation: Array of push notification payload to send. - paramter completionHandler: The callback to be executed when the send request completes. */ public func sendBulk(notification: [Notification], completionHandler: PushNotificationsCompletionHandler?) { var dataArray = [[String:Any]]() for notif in notification { guard let requestBody = notif.jsonFormat else { completionHandler?(nil,500,PushNotificationsError.InvalidNotification) return } dataArray.append(requestBody) } guard let data = try? JSONSerialization.data(withJSONObject: dataArray, options: .prettyPrinted) else{ completionHandler?(nil,500,PushNotificationsError.InvalidNotification) return } HttpClient.post(resource: httpBulkResource, headers: headers, data: data) { (error, status, headers, data) in completionHandler?(data,status,PushNotificationsError.from(httpError: error)) } } }
85c0c6cd7a171d3805b6472aee9268d0
45.86
155
0.636897
false
false
false
false
crossroadlabs/reSwiftInception
refs/heads/master
reSwift/Controllers/TrendingListVC.swift
bsd-3-clause
1
// // TrendingListVC.swift // reSwift // // Created by Roman Stolyarchuk on 10/16/17. // Copyright © 2017 Crossroad Labs s.r.o. All rights reserved. // import UIKit class TrendingListVC: UIViewController { @IBOutlet weak var languagesBtn: UIButton! @IBOutlet weak var segmentFilter: UISegmentedControl! @IBOutlet weak var trendingTV: UITableView! override func viewDidLoad() { super.viewDidLoad() trendingTV.delegate = self trendingTV.dataSource = self trendingTV.register(UINib(nibName: "SearchCell", bundle: nil), forCellReuseIdentifier: "SearchCell") segmentFilter.sendActions(for: .valueChanged) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } @IBAction func segmentedControlAction(sender: UISegmentedControl) { if(sender.selectedSegmentIndex == 0) { print("DAILY") } else if(sender.selectedSegmentIndex == 1) { print("WEEKLY") } else if(sender.selectedSegmentIndex == 2) { print("MONTHLY") } } @IBAction func languageBtnAction(sender: UIButton) { print("Language button pressed") } } extension TrendingListVC: UITableViewDelegate,UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "SearchCell") as? SearchCell { return cell } return UITableViewCell() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let repoVC = UIStoryboard(name: "Repositories", bundle: nil).instantiateViewController(withIdentifier: "RepositoriesController") as? RepositoriesController { self.navigationController?.pushViewController(repoVC, animated: true) } } }
847bd6c81f808ba04eccccc2ddf4885b
29.277778
168
0.654128
false
false
false
false
Pacific3/P3UIKit
refs/heads/master
Sources/Extensions/UIImage.swift
mit
1
// // UIImage.swift // P3UIKit // // Created by Oscar Swanros on 6/17/16. // Copyright © 2016 Pacific3. All rights reserved. // #if os(iOS) || os(tvOS) public typealias P3Image = UIImage #else public typealias P3Image = NSImage #endif public extension P3Image { class func p3_fromImageNameConvertible<I: ImageNameConvertible>(imageNameConvertible: I) -> P3Image? { #if os(iOS) || os(tvOS) return P3Image( named: imageNameConvertible.imageName, in: imageNameConvertible.bundle, compatibleWith: nil ) #else guard let imagePath = imageNameConvertible.bundle.pathForImageResource(imageNameConvertible.imageName) else { return nil } return P3Image(contentsOfFile: imagePath) #endif } } #if os(iOS) || os(tvOS) public extension P3Image { class func p3_imageWithColor(color: P3Color) -> P3Image? { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } class func p3_imageWithColor<C: ColorConvertible>(color: C) -> P3Image? { return p3_imageWithColor(color: color.color()) } class func p3_roundedImageWithColor(color: P3Color, size: CGSize) -> P3Image? { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) let circleBezierPath = UIBezierPath(rect: rect) UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) circleBezierPath.fill() let bezierImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return bezierImage } class func p3_roundedImageWithColor<C: ColorConvertible>(color: C, size: CGSize) -> P3Image? { return p3_roundedImageWithColor(color: color.color(), size: size) } class func p3_roundedImageWithColor(color: P3Color) -> P3Image? { return p3_roundedImageWithColor(color: color, size: CGSize(width: 1, height: 1)) } class func p3_roundedImageWithColor<C: ColorConvertible>(color: C) -> P3Image? { return p3_roundedImageWithColor(color: color, size: CGSize(width: 1, height: 1)) } } #endif
58c689b834c7cacf639404311c8f38ed
33.580247
121
0.592288
false
false
false
false
IvanVorobei/RateApp
refs/heads/master
SPRateApp - project/SPRateApp/sparrow/ui/controls/buttons/SPLinesCircleButtonsView.swift
mit
2
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public class SPLinesCircleButtonsView: UIView { fileprivate var minSpace: CGFloat = 15 var items = [UIButton]() init(frame: CGRect = CGRect.zero, buttons: [UIButton]) { super.init(frame: frame) commonInit() self.addButtons(buttons) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.backgroundColor = UIColor.clear } func addButtons(_ buttons: [UIButton]) { for button in buttons { self.items.append(button) self.addSubview(button) } } fileprivate func commonInit() { self.backgroundColor = UIColor.clear } override public func layoutSubviews() { super.layoutSubviews() let counts: CGFloat = CGFloat(self.items.count) var sideSize = self.frame.height var space = (self.frame.width - (sideSize * counts)) / (counts - 1) if (space < self.minSpace) { sideSize = (self.frame.width - (self.minSpace * (counts - 1))) / counts space = self.minSpace } var xItemPosition: CGFloat = 0 let yItemPosition: CGFloat = (self.frame.height / 2) - (sideSize / 2) for view in self.subviews { view.frame = CGRect.init( x: xItemPosition, y: yItemPosition, width: sideSize, height: sideSize ) xItemPosition = xItemPosition + sideSize + space } } }
8386e832b8206074392efa68e037bb79
35.675676
83
0.646279
false
false
false
false
tscholze/nomster-ios
refs/heads/master
Nomster/RESTLoader.swift
mit
1
// // RESTLoader.swift // Nomster // // Created by Klaus Meyer on 06.03.15. // Copyright (c) 2015 Tobias Scholze. All rights reserved. // import Foundation class RESTLoader { let ApiBase = "http://localhost:3000" func get(ressource: NSString) -> NSArray { let url: NSURL! = NSURL(string: "\(ApiBase)/\(ressource)") let data: NSData? = NSData(contentsOfURL: url) var results: NSArray = NSArray() if (data != nil) { results = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray } return results } }
adcb4e04a3c20fe1ecbdf37d96fff00d
22.142857
140
0.632716
false
false
false
false
pedrovsn/2reads
refs/heads/master
reads2/reads2/BuscarTableViewController.swift
mit
1
// // BuscarTableViewController.swift // reads2 // // Created by Student on 11/29/16. // Copyright © 2016 Student. All rights reserved. // import UIKit class BuscarTableViewController: UITableViewController { @IBOutlet var tableViewSearch: UITableView! @IBOutlet weak var searchBar: UISearchBar! let searchController = UISearchController(searchResultsController: nil) var filteredLivros = [Livro]() var livros:[Livro] = [Livro]() var searchActive : Bool = false override func viewDidLoad() { super.viewDidLoad() searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false definesPresentationContext = true tableView.tableHeaderView = searchController.searchBar self.livros = Livro.getList() } func filterContentForSearchText(searchText: String, scope: String = "All") { filteredLivros = livros.filter { livro in return livro.titulo!.lowercaseString.containsString(searchText.lowercaseString) } tableView.reloadData() } func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchActive = true; } func searchBarTextDidEndEditing(searchBar: UISearchBar) { searchActive = false; } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchActive = false; } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchActive = false; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.active && searchController.searchBar.text != "" { return filteredLivros.count } return self.livros.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BuscarTableViewCell let livro: Livro if searchController.active && searchController.searchBar.text != "" { livro = filteredLivros[indexPath.row] } else { livro = livros[indexPath.row] } cell.titulo.text = livro.titulo cell.autor.text = livro.autor cell.foto.image = UIImage(named: livro.imagem!) return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension BuscarTableViewController: UISearchResultsUpdating { func updateSearchResultsForSearchController(searchController: UISearchController) { filterContentForSearchText(searchController.searchBar.text!) } }
b01d27c135886266e92fa2e07fcb9d5c
31.986486
158
0.668101
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Analytics/Sources/AnalyticsKit/Providers/Nabu/Model/Context/Screen.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation #if canImport(UIKit) import UIKit struct Screen: Encodable { let width = Double(UIScreen.main.bounds.width) let height = Double(UIScreen.main.bounds.height) let density = Double(UIScreen.main.scale) } #endif #if canImport(AppKit) import AppKit struct Screen: Encodable { let width = Double(NSScreen.main!.frame.width) let height = Double(NSScreen.main!.frame.height) let density = Double(1) } #endif
d79851545d368188e9fef6685eb57639
21.173913
62
0.729412
false
false
false
false
ArnavChawla/InteliChat
refs/heads/master
Carthage/Checkouts/swift-sdk/Source/AssistantV1/Models/Workspace.swift
mit
2
/** * Copyright IBM Corporation 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /** Workspace. */ public struct Workspace: Decodable { /// The name of the workspace. public var name: String /// The language of the workspace. public var language: String /// The timestamp for creation of the workspace. public var created: String? /// The timestamp for the last update to the workspace. public var updated: String? /// The workspace ID. public var workspaceID: String /// The description of the workspace. public var description: String? /// Any metadata related to the workspace. public var metadata: [String: JSON]? /// Whether training data from the workspace (including artifacts such as intents and entities) can be used by IBM for general service improvements. `true` indicates that workspace training data is not to be used. public var learningOptOut: Bool? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case name = "name" case language = "language" case created = "created" case updated = "updated" case workspaceID = "workspace_id" case description = "description" case metadata = "metadata" case learningOptOut = "learning_opt_out" } }
353ef5bca1baeefe05488dc915fdca16
31.931034
217
0.695812
false
false
false
false
kazuhiro4949/EditDistance
refs/heads/master
iOS Example/iOS Example/CollectionViewController.swift
mit
1
// // CollectionViewController.swift // // Copyright © 2017年 Kazuhiro Hayashi. All rights reserved. // import UIKit import EditDistance private let reuseIdentifier = "Cell" class CollectionViewController: UICollectionViewController { var source = [0, 1, 2, 3, 4, 5] override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return source.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) return cell } @IBAction func rightBarButtonItemDidTap(_ sender: UIBarButtonItem) { let newSource = Array(0..<Int(arc4random() % 50)).shuffled() let container = source.diff.compare(to: newSource) source = Array(newSource) collectionView?.diff.performBatchUpdates(with: container, completion: nil) } }
14aa929ad4abfffb8b18c14b95819b03
28.043478
130
0.701347
false
false
false
false
1amageek/Toolbar
refs/heads/master
Example/AnimationViewController.swift
mit
1
// // AnimationViewController.swift // Example // // Created by 1amageek on 2018/01/18. // Copyright © 2018年 Stamp Inc. All rights reserved. // import UIKit class AnimationViewController: UIViewController { var item0: ToolbarItem? var item1: ToolbarItem? var toolbar: Toolbar? override func viewDidLoad() { super.viewDidLoad() let button: UIButton = UIButton(type: .system) button.setTitle("Animation Button", for: UIControl.State.normal) self.view.addSubview(button) button.sizeToFit() button.center = self.view.center button.addTarget(self, action: #selector(hide0), for: UIControl.Event.touchUpInside) let toolbar: Toolbar = Toolbar() self.view.addSubview(toolbar) if #available(iOS 11.0, *) { toolbar.layoutMargins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) toolbar.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 100).isActive = true } else { toolbar.topAnchor.constraint(equalTo: self.view.layoutMarginsGuide.topAnchor, constant: 100).isActive = true } self.item0 = ToolbarItem(title: "Button", target: nil, action: nil) self.item1 = ToolbarItem(image: #imageLiteral(resourceName: "instagram"), target: nil, action: nil) self.item1?.contentSize = CGSize(width: 50, height: 100) toolbar.setItems([self.item0!, self.item1!], animated: false) } @objc func hide0() { self.item0?.setHidden(!self.item0!.isHidden, animated: true) } @objc func hide1() { self.item0?.setHidden(!self.item1!.isHidden, animated: true) } }
cee307d5d0a0e80d3bc354c709a16fb2
33.489796
121
0.656805
false
false
false
false
IngmarStein/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01922-getselftypeforcontainer.swift
apache-2.0
11
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse let x { var b = 1][Any) -> Self { f(")) { let i(x) { } let v: A, self.A> Any) -> { func c] = [unowned self] { return { self.f == A<B : Any) -> : AnyObject, 3] == { var d { } } } } return z: NSObject { func x: B, range.<T, U) -> () { }) } } protocol b { func a typealias d: a {
1e6f387403e75c7ef369a6a7006622ec
22.068966
78
0.641256
false
false
false
false
GYLibrary/GPRS
refs/heads/master
OznerGPRS/View/WaterPurifierHeadCircleView.swift
mit
1
// // WaterPurifierHeadCircleView.swift // OzneriFamily // // Created by 赵兵 on 2016/10/15. // Copyright © 2016年 net.ozner. All rights reserved. // import UIKit class WaterPurifierHeadCircleView: UIView { // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. private var lastAngle:[CGFloat]=[0,0]//lastAngle=0需要动画,否则不需要动画 private var currentAngle:[CGFloat]=[0,0] private var currentLayer:[CAGradientLayer]=[] override func draw(_ rect: CGRect) { super.draw(rect) for layer in currentLayer { layer.removeFromSuperlayer() } currentLayer=[] //第1条背景线 let context=UIGraphicsGetCurrentContext() context!.setAllowsAntialiasing(true); context!.setLineWidth(2); context!.setStrokeColor(UIColor.lightGray.cgColor); context?.addArc(center: CGPoint(x: rect.size.width/2, y: rect.size.width/2), radius: rect.size.width/2-5, startAngle: -CGFloat(M_PI), endAngle: 0, clockwise: false)//clockwise顺时针 context!.strokePath() if currentAngle[0] != 0 { //第2条背景线 context!.setAllowsAntialiasing(true); context!.setLineWidth(2); context!.setStrokeColor(UIColor(white: 1, alpha: 0.8).cgColor); context?.addArc(center: CGPoint(x: rect.size.width/2, y: rect.size.width/2), radius: rect.size.width/2-20, startAngle: -CGFloat(M_PI), endAngle: 0, clockwise: false)//clockwise顺时针 context!.strokePath() } //TDS线 for i in 0...1 { let shapeLayer=CAShapeLayer() shapeLayer.path=UIBezierPath(arcCenter: CGPoint(x: rect.size.width/2, y: rect.size.width/2), radius: rect.size.width/2-5-CGFloat(i*15), startAngle: -CGFloat(M_PI), endAngle: -CGFloat(M_PI)+CGFloat(M_PI)*currentAngle[i], clockwise: true).cgPath shapeLayer.lineCap="round"//圆角 shapeLayer.lineWidth=10 shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = UIColor.purple.cgColor if lastAngle[i] == 0 { let drawAnimation = CABasicAnimation(keyPath: "strokeEnd") drawAnimation.duration = 5.0; drawAnimation.repeatCount = 0; drawAnimation.isRemovedOnCompletion = false; drawAnimation.fromValue = 0; drawAnimation.toValue = 10; drawAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) shapeLayer.add(drawAnimation, forKey: "drawCircleAnimation") } let gradientLayer = CAGradientLayer() gradientLayer.frame = self.bounds gradientLayer.colors = [ UIColor(colorLiteralRed: 9.0/255, green: 142.0/255, blue: 254.0/255, alpha: 1.0).cgColor, UIColor(colorLiteralRed: 134.0/255, green: 102.0/255, blue: 255.0/255, alpha: 1.0).cgColor, UIColor(colorLiteralRed: 215.0/255, green: 67.0/255, blue: 113.0/255, alpha: 1.0).cgColor ]; gradientLayer.startPoint = CGPoint(x: 0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1, y: 0.5) gradientLayer.mask=shapeLayer currentLayer.append(gradientLayer) self.layer.addSublayer(gradientLayer) } lastAngle=currentAngle } func updateCircleView(angleBefore:CGFloat,angleAfter:CGFloat){ currentAngle=[angleBefore,angleAfter] if currentAngle != lastAngle { self.setNeedsDisplay() } } }
0681666fcfb9a023100d1f56b3d18092
40.988764
255
0.610918
false
false
false
false
darthpelo/DARCartList
refs/heads/master
DARCartList/ViewController.swift
mit
1
// // ViewController.swift // DARCartList // // Created by Alessio Roberto on 19/02/15. // Copyright (c) 2015 Alessio Roberto. All rights reserved. // import UIKit class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { private let reuseIdentifier = "ProductCell" private var listResult = [Product]() private var selectedProduct: Product? func productForIndexPath(indexPath: NSIndexPath) -> Product { return listResult[indexPath.row] } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. title = "Cart" requestCartList() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func showAlert() { let alertController = UIAlertController(title: "Attention", message: "Connection error occurred", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in println(action) } alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: { () -> Void in }) } private func requestCartList() { DARCartListAPI.sharedInstance.requestCartItems().continueWithExecutor(BFExecutor.mainThreadExecutor(), withBlock: { (task) -> AnyObject! in if (task.error() != nil) { self.showAlert() } else { self.listResult = task.result() as! [(Product)] self.collectionView?.reloadData() } return nil }) } @IBAction func refreshList(sender: UIBarButtonItem) { // TODO: add pull to refresh function to the CollectionView requestCartList() } // MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ProductDetailSegue" { let detail = segue.destinationViewController as! DARProductDetailViewController detail.product = selectedProduct } } // MARK: UICollectionView override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return listResult.count } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var cellSize: CGSize; let collectionViewWidth = collectionView.frame.size.width; let newCellWidth = collectionViewWidth / 2 cellSize = CGSizeMake(newCellWidth - 1.0, newCellWidth - 1.0); return cellSize; } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // TODO: improve CollectionViewCell cache managment let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ProductCell let product = productForIndexPath(indexPath) cell.activityIndicator.stopAnimating() cell.productNameLabel.text = product.name let price = product.price / 100 cell.productPriceLabel.text = "\(price)€" if product.image != nil { cell.productImage.image = product.image return cell } cell.activityIndicator.startAnimating() product.loadImage { (productPhoto, error) -> Void in cell.activityIndicator.stopAnimating() if error != nil { return } if productPhoto.image == nil { return } if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? ProductCell { cell.productImage.image = product.image } } return cell } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { selectedProduct = self.productForIndexPath(indexPath) self.performSegueWithIdentifier("ProductDetailSegue", sender: self) } }
8872fee8b32f29f295608afbea3fe5ca
31.9375
139
0.616066
false
false
false
false
regexident/Gestalt
refs/heads/master
GestaltDemo/Views/StageDesignView.swift
mpl-2.0
1
// // StageDesignView.swift // GestaltDemo // // Created by Vincent Esche on 5/15/18. // Copyright © 2018 Vincent Esche. All rights reserved. // import UIKit import Gestalt @IBDesignable class StageDesignView: UIView { @IBOutlet private var lightView: UIImageView? @IBOutlet private var fixtureView: UIImageView? @IBOutlet private var shadowView: UIImageView? override func awakeFromNib() { super.awakeFromNib() self.observe(theme: \ApplicationTheme.custom.stageDesign) } } extension StageDesignView: Themeable { typealias Theme = StageDesignViewTheme func apply(theme: Theme) { UIView.performWithoutAnimation { self.backgroundColor = theme.backgroundColor self.shadowView?.layer.opacity = theme.shadowOpacity } UIView.animate(withDuration: 5.0, animations: { self.lightView?.layer.opacity = theme.lightOpacity }) self.lightView?.image = theme.lightImage self.fixtureView?.image = theme.fixtureImage self.shadowView?.image = theme.shadowImage } }
59fe3bf0ba49c696f1d423bb156a2182
24.767442
65
0.6787
false
false
false
false
Hearsayer/YLCycleScrollView
refs/heads/master
Source/YLCycleScrollView.swift
mit
1
// // YLCycleScrollView.swift // YLCycleScrollView // // Created by he on 2017/4/7. // Copyright © 2017年 he. All rights reserved. // import UIKit import Kingfisher @objc public protocol CycleScrollViewDelegate { func cycleScrollView(_ cycleScrollView: YLCycleScrollView, didTap index: Int, data: YLCycleModel) } public enum IndicatiorPositionType { case right case middle case left } let margin: CGFloat = 10 let indicatorWidth: CGFloat = 120 let indicatorHeight: CGFloat = 30 public class YLCycleScrollView: UIView { /// 代理 public weak var delegate: CycleScrollViewDelegate? /// 图片内容模式 public var imageContentMode: UIViewContentMode = .scaleToFill { didSet { for imageView in imageViews { imageView.contentMode = imageContentMode } } } /// 占位图片(用来当iamgeView还没将图片显示出来时,显示的图片) public var placeholderImage: UIImage? { didSet { resetImageViewSource() } } /// 数据源,URL字符串 public var dataSource : [YLCycleModel]? { didSet { guard let dataSource = dataSource, dataSource.count > 0 else { return } resetImageViewSource() //设置页控制器 configurePageController() } } /// 滚动间隔时间,默认3秒 public var intervalTime: TimeInterval = 3 { didSet { invalidate() configureAutoScrollTimer(intervalTime) } } /// 分页控件位置 public var indicatiorPosition: IndicatiorPositionType = .middle { didSet { for imageView in scrollerView.subviews as! [YLCycleImageView] { switch indicatiorPosition { case .left: imageView.textLabelPosition = .right case .middle: imageView.textLabelPosition = .none case .right: imageView.textLabelPosition = .left } } switch indicatiorPosition { case .left: pageControl.frame = CGRect(x: margin, y: scrollerViewHeight - indicatorHeight, width: indicatorWidth, height: indicatorHeight) case .right: pageControl.frame = CGRect(x: scrollerViewWidth - indicatorWidth - margin, y: scrollerViewHeight - indicatorHeight, width: indicatorWidth, height: indicatorHeight) case .middle: pageControl.frame = CGRect(x: (scrollerViewWidth - indicatorWidth) * 0.5, y: scrollerViewHeight - indicatorHeight, width: indicatorWidth, height: indicatorHeight) } } } /// 分页控件圆点颜色 public var pageIndicatorTintColor: UIColor? { didSet { pageControl.pageIndicatorTintColor = pageIndicatorTintColor } } /// 分页控件当前圆点颜色 public var currentPageIndicatorTintColor: UIColor? { didSet { pageControl.currentPageIndicatorTintColor = currentPageIndicatorTintColor } } /// 是否显示底部阴影栏 public var isShowDimBar: Bool = false { didSet { for view in scrollerView.subviews as! [YLCycleImageView] { view.isShowDimBar = isShowDimBar } } } /// 当前展示的图片索引 fileprivate var currentIndex : Int = 0 /// 图片辅助属性,把传进来的URL字符串转成URL对象 // fileprivate lazy var imagesURL = [URL]() /// 用于轮播的左中右三个image(不管几张图片都是这三个imageView交替使用) fileprivate lazy var leftImageView: YLCycleImageView = YLCycleImageView() fileprivate lazy var middleImageView: YLCycleImageView = YLCycleImageView() fileprivate lazy var rightImageView: YLCycleImageView = YLCycleImageView() fileprivate var imageViews: [YLCycleImageView] { return [leftImageView, middleImageView, rightImageView] } /// 放置imageView的滚动视图 private lazy var scrollerView = UIScrollView() /// scrollView的宽 fileprivate var scrollerViewWidth: CGFloat = 0 /// scrollView的高 fileprivate var scrollerViewHeight: CGFloat = 0 /// 页控制器(小圆点) fileprivate lazy var pageControl = UIPageControl() /// 自动滚动计时器 fileprivate var autoScrollTimer: Timer? public init(frame: CGRect, placeholder: UIImage? = nil) { super.init(frame: frame) scrollerViewWidth = frame.size.width scrollerViewHeight = frame.size.height //设置scrollerView configureScrollerView() //设置加载指示图片 // configurePlaceholder(placeholder) //设置imageView configureImageView() //设置自动滚动计时器 configureAutoScrollTimer() backgroundColor = UIColor.black } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 设置scrollerView private func configureScrollerView(){ scrollerView.frame = CGRect(x: 0,y: 0, width: scrollerViewWidth, height: scrollerViewHeight) // scrollerView.backgroundColor = UIColor.red scrollerView.delegate = self scrollerView.contentSize = CGSize(width: scrollerViewWidth * 3, height: 0) //滚动视图内容区域向左偏移一个view的宽度 scrollerView.contentOffset = CGPoint(x: scrollerViewWidth, y: 0) scrollerView.showsVerticalScrollIndicator = false scrollerView.showsHorizontalScrollIndicator = false scrollerView.isPagingEnabled = true scrollerView.bounces = false addSubview(scrollerView) } /// 设置占位图片图片 // private func configurePlaceholder(_ placeholder: UIImage?){ // //这里使用ImageHelper将文字转换成图片,作为加载指示符 // if placeholder == nil { // // let font = UIFont.systemFont(ofSize: 17.0, weight: UIFontWeightMedium) // let size = CGSize(width: scrollerViewWidth, height: scrollerViewHeight) // placeholderImage = UIImage(text: "图片加载中...", font:font, color:UIColor.white, size:size)! // } else { // placeholderImage = placeholder // } // } /// 设置imageView func configureImageView(){ for (i, imageView) in imageViews.enumerated() { imageView.frame = CGRect(x: CGFloat(i) * scrollerViewWidth, y: 0, width: scrollerViewWidth, height: scrollerViewHeight) imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTap(tap:)))) scrollerView.addSubview(imageView) } // leftImageView.frame = CGRect(x: 0, y: 0, width: scrollerViewWidth, height: scrollerViewHeight) // middleImageView.frame = CGRect(x: scrollerViewWidth, y: 0, width: scrollerViewWidth, height: scrollerViewHeight) // rightImageView.frame = CGRect(x: 2 * scrollerViewWidth, y: 0, width: scrollerViewWidth, height: scrollerViewHeight) // //设置初始时左中右三个imageView的图片(分别时数据源中最后一张,第一张,第二张图片) resetImageViewSource() // scrollerView.addSubview(leftImageView) // scrollerView.addSubview(middleImageView) // scrollerView.addSubview(rightImageView) // leftImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTap(tap:)))) // middleImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTap(tap:)))) // rightImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTap(tap:)))) } @objc private func imageTap(tap: UITapGestureRecognizer) { if dataSource != nil && dataSource!.count > 0 && currentIndex < dataSource!.count { delegate?.cycleScrollView(self, didTap: currentIndex, data: dataSource![currentIndex]) } } /// 设置页控制器 private func configurePageController() { pageControl.frame = CGRect(x: (scrollerViewWidth - indicatorWidth) * 0.5, y: scrollerViewHeight - indicatorHeight, width: indicatorWidth, height: indicatorHeight) pageControl.numberOfPages = dataSource?.count ?? 0 pageControl.isUserInteractionEnabled = false addSubview(pageControl) } /// 设置自动滚动计时器 fileprivate func configureAutoScrollTimer(_ time: TimeInterval = 3) { autoScrollTimer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(letItScroll), userInfo: nil, repeats: true) } fileprivate func invalidate() { autoScrollTimer?.invalidate() autoScrollTimer = nil } /// 计时器时间一到,滚动一张图片 @objc fileprivate func letItScroll(){ let offset = CGPoint(x: 2 * scrollerViewWidth, y: 0) scrollerView.setContentOffset(offset, animated: true) } /// 每当滚动后重新设置各个imageView的图片 fileprivate func resetImageViewSource() { guard let dataSource = dataSource, dataSource.count > 0 else { return } let first = dataSource.first let last = dataSource.last //当前显示的是第一张图片 if currentIndex == 0 { setupImageView(leftImageView, image: last?.url, text: last?.text) setupImageView(middleImageView, image: first?.url, text: first?.text) let rightImageIndex = (dataSource.count) > 1 ? 1 : 0 //保护 setupImageView(rightImageView, image: dataSource[rightImageIndex].url, text: dataSource[rightImageIndex].text) } //当前显示的是最好一张图片 else if currentIndex == dataSource.count - 1 { setupImageView(leftImageView, image: dataSource[currentIndex - 1].url, text: dataSource[currentIndex - 1].text) setupImageView(middleImageView, image: last?.url, text: last?.text) setupImageView(rightImageView, image: first?.url, text: first?.text) } //其他情况 else{ setupImageView(leftImageView, image: dataSource[currentIndex-1].url, text: dataSource[currentIndex-1].text) setupImageView(middleImageView, image: dataSource[currentIndex].url, text: dataSource[currentIndex].text) setupImageView(rightImageView, image: dataSource[currentIndex+1].url, text: dataSource[currentIndex+1].text) } } private func setupImageView(_ imageView: YLCycleImageView, image: URL?, text: String?) { imageView.kf.setImage(with: image, placeholder: placeholderImage, options: [.transition(.fade(1))]) imageView.text = text } } // MARK: - UIScrollViewDelegate extension YLCycleScrollView: UIScrollViewDelegate { // 自动滚动 public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { guard let dataSource = dataSource, dataSource.count > 0 else { return } //获取当前偏移量 let offset = scrollView.contentOffset.x //如果向左滑动(显示下一张) if (offset >= scrollerViewWidth * 2) { //还原偏移量 scrollView.contentOffset = CGPoint(x: scrollerViewWidth, y: 0) //视图索引+1 currentIndex = currentIndex + 1 if currentIndex == dataSource.count { currentIndex = 0 } } //如果向右滑动(显示上一张) if offset <= 0 { //还原偏移量 scrollView.contentOffset = CGPoint(x: scrollerViewWidth, y: 0) //视图索引-1 currentIndex = currentIndex - 1 if currentIndex == -1 { currentIndex = dataSource.count - 1 } } //重新设置各个imageView的图片 resetImageViewSource() //设置页控制器当前页码 pageControl.currentPage = currentIndex } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollViewWillBeginDecelerating(scrollView) } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { scrollViewWillBeginDecelerating(scrollView) } //手动拖拽滚动开始 public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { scrollViewWillBeginDecelerating(scrollView) //使自动滚动计时器失效(防止用户手动移动图片的时候这边也在自动滚动) invalidate() } //手动拖拽滚动结束 public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { //重新启动自动滚动计时器 configureAutoScrollTimer() scrollViewWillBeginDecelerating(scrollView) } }
d60e39de7d1730d9c777f0310ad494c3
33.911357
179
0.619773
false
false
false
false
HTWDD/HTWDresden-iOS
refs/heads/develop
HTWDD/Core/Base Classes/DataSource/ErrorViews.swift
gpl-2.0
2
// // ErrorCell.swift // HTWDD // // Created by Benjamin Herzog on 04/03/2017. // Copyright © 2017 HTW Dresden. All rights reserved. // import UIKit /// Use to display an error in the collection view. class ErrorCollectionCell: CollectionViewCell { /// Setting the error String will replace the labels string with the given one. var error: String? { get { return label.text } set { label.text = newValue } } private let label = UILabel() override func initialSetup() { self.contentView.backgroundColor = .red self.label.frame = self.contentView.bounds self.label.textColor = .white self.label.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.label.numberOfLines = 0 self.label.font = UIFont.systemFont(ofSize: 10) self.contentView.add(self.label) } } class ErrorSupplementaryView: CollectionReusableView { /// Setting the error String will replace the labels string with the given one. var error: String? { get { return label.text } set { label.text = newValue } } private let label = UILabel() override func initialSetup() { self.backgroundColor = .red self.label.frame = self.bounds self.label.textColor = .white self.label.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.label.numberOfLines = 0 self.label.font = UIFont.systemFont(ofSize: 10) self.add(self.label) } } class ErrorTableCell: TableViewCell { /// Setting the error String will replace the labels string with the given one. var error: String? { get { return label.text } set { label.text = newValue } } private let label = UILabel() override func initialSetup() { self.contentView.backgroundColor = .red self.label.frame = self.contentView.bounds self.label.textColor = .white self.label.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.label.numberOfLines = 0 self.label.font = UIFont.systemFont(ofSize: 10) self.contentView.add(self.label) } }
93210be0314e114c6561dee55923d59a
25.337209
83
0.618543
false
false
false
false