repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cfilipov/MuscleBook
|
MuscleBook/ExerciseInstructionsViewController.swift
|
1
|
3491
|
/*
Muscle Book
Copyright (C) 2016 Cristian Filipov
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
import Eureka
import Kingfisher
import SafariServices
class ExerciseInstructionsViewController : FormViewController {
let exercise: Exercise
lazy var imageView: AnimatedImageView = {
let view = AnimatedImageView()
view.frame = CGRect(x: 0, y: 15, width: 120, height: 120)
view.contentMode = .ScaleAspectFit
view.autoresizingMask = .FlexibleWidth
return view
}()
lazy var imageViewContainer: UIView = {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 130))
view.autoresizingMask = .FlexibleWidth
view.addSubview(self.imageView)
return view
}()
init(exercise: Exercise) {
self.exercise = exercise
super.init(style: .Grouped)
hidesBottomBarWhenPushed = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Instructions"
tableView?.contentInset = UIEdgeInsetsMake(-36, 0, 0, 0)
form
+++ Section() {
$0.footer = HeaderFooterView<UIView>(HeaderFooterProvider.Callback({ () -> UIView in
return self.imageViewContainer
}))
}
<<< LabelRow() {
$0.title = "Name"
$0.value = exercise.name
}
+++ Section()
if let instructions = exercise.instructions {
for i in instructions {
form.last! <<< TextAreaRow() {
$0.value = i
$0.textAreaHeight = .Dynamic(initialTextViewHeight: 20)
$0.disabled = true
}
}
}
if let link = exercise.link {
form +++ Section() <<< PushViewControllerRow() {
$0.title = "More Details"
$0.controller = { SFSafariViewController(URL: NSURL(string: link)!) }
}
}
if let gif = exercise.gif, url = NSURL(string: gif) {
imageView.kf_setImageWithURL(url)
}
}
private func load(URL: NSURL, callback: NSData -> Void) {
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request) { data, response, error in
if let error = error {
Alert(message: error.localizedDescription)
return
}
guard let data = data else { return }
callback(data)
}
task.resume()
}
}
|
gpl-3.0
|
7e490750d1f3bcf47c6b5638fdfa6083
| 29.356522 | 99 | 0.603552 | 4.930791 | false | false | false | false |
faimin/ZDOpenSourceDemo
|
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/NodeRenderSystem/Nodes/Text/TextAnimatorNode.swift
|
1
|
7266
|
//
// TextAnimatorNode.swift
// lottie-ios-iOS
//
// Created by Brandon Withrow on 2/19/19.
//
import Foundation
import CoreGraphics
import QuartzCore
final class TextAnimatorNodeProperties: NodePropertyMap, KeypathSearchable {
let keypathName: String
init(textAnimator: TextAnimator) {
self.keypathName = textAnimator.name
var properties = [String : AnyNodeProperty]()
if let keyframeGroup = textAnimator.anchor {
self.anchor = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Anchor"] = self.anchor
} else {
self.anchor = nil
}
if let keyframeGroup = textAnimator.position {
self.position = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Position"] = self.position
} else {
self.position = nil
}
if let keyframeGroup = textAnimator.scale {
self.scale = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Scale"] = self.scale
} else {
self.scale = nil
}
if let keyframeGroup = textAnimator.skew {
self.skew = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Skew"] = self.skew
} else {
self.skew = nil
}
if let keyframeGroup = textAnimator.skewAxis {
self.skewAxis = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Skew Axis"] = self.skewAxis
} else {
self.skewAxis = nil
}
if let keyframeGroup = textAnimator.rotation {
self.rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Rotation"] = self.rotation
} else {
self.rotation = nil
}
if let keyframeGroup = textAnimator.opacity {
self.opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Opacity"] = self.opacity
} else {
self.opacity = nil
}
if let keyframeGroup = textAnimator.strokeColor {
self.strokeColor = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Stroke Color"] = self.strokeColor
} else {
self.strokeColor = nil
}
if let keyframeGroup = textAnimator.fillColor {
self.fillColor = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Fill Color"] = self.fillColor
} else {
self.fillColor = nil
}
if let keyframeGroup = textAnimator.strokeWidth {
self.strokeWidth = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Stroke Width"] = self.strokeWidth
} else {
self.strokeWidth = nil
}
if let keyframeGroup = textAnimator.tracking {
self.tracking = NodeProperty(provider: KeyframeInterpolator(keyframes: keyframeGroup.keyframes))
properties["Tracking"] = self.tracking
} else {
self.tracking = nil
}
self.keypathProperties = properties
self.properties = Array(keypathProperties.values)
}
let anchor: NodeProperty<Vector3D>?
let position: NodeProperty<Vector3D>?
let scale: NodeProperty<Vector3D>?
let skew: NodeProperty<Vector1D>?
let skewAxis: NodeProperty<Vector1D>?
let rotation: NodeProperty<Vector1D>?
let opacity: NodeProperty<Vector1D>?
let strokeColor: NodeProperty<Color>?
let fillColor: NodeProperty<Color>?
let strokeWidth: NodeProperty<Vector1D>?
let tracking: NodeProperty<Vector1D>?
let keypathProperties: [String : AnyNodeProperty]
let properties: [AnyNodeProperty]
var caTransform: CATransform3D {
return CATransform3D.makeTransform(anchor: anchor?.value.pointValue ?? .zero,
position: position?.value.pointValue ?? .zero,
scale: scale?.value.sizeValue ?? CGSize(width: 100, height: 100),
rotation: rotation?.value.cgFloatValue ?? 0,
skew: skew?.value.cgFloatValue,
skewAxis: skewAxis?.value.cgFloatValue)
}
}
final class TextOutputNode: NodeOutput {
var parent: NodeOutput? {
return parentTextNode
}
var parentTextNode: TextOutputNode?
var isEnabled: Bool = true
init(parent: TextOutputNode?) {
self.parentTextNode = parent
}
fileprivate var _xform: CATransform3D?
fileprivate var _opacity: CGFloat?
fileprivate var _strokeColor: CGColor?
fileprivate var _fillColor: CGColor?
fileprivate var _tracking: CGFloat?
fileprivate var _strokeWidth: CGFloat?
var xform: CATransform3D {
get {
return _xform ?? parentTextNode?.xform ?? CATransform3DIdentity
}
set {
_xform = newValue
}
}
var opacity: CGFloat {
get {
return _opacity ?? parentTextNode?.opacity ?? 1
}
set {
_opacity = newValue
}
}
var strokeColor: CGColor? {
get {
return _strokeColor ?? parentTextNode?.strokeColor
}
set {
_strokeColor = newValue
}
}
var fillColor: CGColor? {
get {
return _fillColor ?? parentTextNode?.fillColor
}
set {
_fillColor = newValue
}
}
var tracking: CGFloat {
get {
return _tracking ?? parentTextNode?.tracking ?? 0
}
set {
_tracking = newValue
}
}
var strokeWidth: CGFloat {
get {
return _strokeWidth ?? parentTextNode?.strokeWidth ?? 0
}
set {
_strokeWidth = newValue
}
}
func hasOutputUpdates(_ forFrame: CGFloat) -> Bool {
// TODO Fix This
return true
}
var outputPath: CGPath?
}
class TextAnimatorNode: AnimatorNode {
let textOutputNode: TextOutputNode
var outputNode: NodeOutput {
return textOutputNode
}
let textAnimatorProperties: TextAnimatorNodeProperties
init(parentNode: TextAnimatorNode?, textAnimator: TextAnimator) {
self.textOutputNode = TextOutputNode(parent: parentNode?.textOutputNode)
self.textAnimatorProperties = TextAnimatorNodeProperties(textAnimator: textAnimator)
self.parentNode = parentNode
}
// MARK: Animator Node Protocol
var propertyMap: NodePropertyMap & KeypathSearchable {
return textAnimatorProperties
}
let parentNode: AnimatorNode?
var hasLocalUpdates: Bool = false
var hasUpstreamUpdates: Bool = false
var lastUpdateFrame: CGFloat? = nil
var isEnabled: Bool = true
func localUpdatesPermeateDownstream() -> Bool {
return true
}
func rebuildOutputs(frame: CGFloat) {
textOutputNode.xform = textAnimatorProperties.caTransform
textOutputNode.opacity = (textAnimatorProperties.opacity?.value.cgFloatValue ?? 100) * 0.01
textOutputNode.strokeColor = textAnimatorProperties.strokeColor?.value.cgColorValue
textOutputNode.fillColor = textAnimatorProperties.fillColor?.value.cgColorValue
textOutputNode.tracking = textAnimatorProperties.tracking?.value.cgFloatValue ?? 1
textOutputNode.strokeWidth = textAnimatorProperties.strokeWidth?.value.cgFloatValue ?? 0
}
}
|
mit
|
ccdf4737c07490217af677f9e0ef8e26
| 27.948207 | 105 | 0.676576 | 4.730469 | false | false | false | false |
Jnosh/swift
|
test/IRGen/objc_ns_enum.swift
|
5
|
5663
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
import gizmo
// CHECK: @_T0SC16NSRuncingOptionsOWV = linkonce_odr hidden constant
// CHECK: @_T0SC16NSRuncingOptionsOMn = linkonce_odr hidden constant
// CHECK: @_T0SC16NSRuncingOptionsON = linkonce_odr hidden global
// CHECK: @_T0SC28NeverActuallyMentionedByNameOs9Equatable5gizmoWP = linkonce_odr hidden constant
// CHECK-LABEL: define{{( protected)?}} i32 @main
// CHECK: call %swift.type* @_T0SC16NSRuncingOptionsOMa()
// CHECK: define hidden swiftcc i16 @_T012objc_ns_enum09imported_C9_inject_aSC16NSRuncingOptionsOyF()
// CHECK: ret i16 123
func imported_enum_inject_a() -> NSRuncingOptions {
return .mince
}
// CHECK: define hidden swiftcc i16 @_T012objc_ns_enum09imported_C9_inject_bSC16NSRuncingOptionsOyF()
// CHECK: ret i16 4567
func imported_enum_inject_b() -> NSRuncingOptions {
return .quinceSliced
}
// CHECK: define hidden swiftcc i16 @_T012objc_ns_enum09imported_C9_inject_cSC16NSRuncingOptionsOyF()
// CHECK: ret i16 5678
func imported_enum_inject_c() -> NSRuncingOptions {
return .quinceJulienned
}
// CHECK: define hidden swiftcc i16 @_T012objc_ns_enum09imported_C9_inject_dSC16NSRuncingOptionsOyF()
// CHECK: ret i16 6789
func imported_enum_inject_d() -> NSRuncingOptions {
return .quinceDiced
}
// CHECK: define hidden swiftcc i32 @_T012objc_ns_enum09imported_C17_inject_radixed_aSC16NSRadixedOptionsOyF() {{.*}} {
// -- octal 0755
// CHECK: ret i32 493
func imported_enum_inject_radixed_a() -> NSRadixedOptions {
return .octal
}
// CHECK: define hidden swiftcc i32 @_T012objc_ns_enum09imported_C17_inject_radixed_bSC16NSRadixedOptionsOyF() {{.*}} {
// -- hex 0xFFFF
// CHECK: ret i32 65535
func imported_enum_inject_radixed_b() -> NSRadixedOptions {
return .hex
}
// CHECK: define hidden swiftcc i32 @_T012objc_ns_enum09imported_C18_inject_negative_aSC17NSNegativeOptionsOyF() {{.*}} {
// CHECK: ret i32 -1
func imported_enum_inject_negative_a() -> NSNegativeOptions {
return .foo
}
// CHECK: define hidden swiftcc i32 @_T012objc_ns_enum09imported_C18_inject_negative_bSC17NSNegativeOptionsOyF() {{.*}} {
// CHECK: ret i32 -2147483648
func imported_enum_inject_negative_b() -> NSNegativeOptions {
return .bar
}
// CHECK: define hidden swiftcc i32 @_T012objc_ns_enum09imported_C27_inject_negative_unsigned_aSC25NSNegativeUnsignedOptionsOyF() {{.*}} {
// CHECK: ret i32 -1
func imported_enum_inject_negative_unsigned_a() -> NSNegativeUnsignedOptions {
return .foo
}
// CHECK: define hidden swiftcc i32 @_T012objc_ns_enum09imported_C27_inject_negative_unsigned_bSC25NSNegativeUnsignedOptionsOyF() {{.*}} {
// CHECK: ret i32 -2147483648
func imported_enum_inject_negative_unsigned_b() -> NSNegativeUnsignedOptions {
return .bar
}
func test_enum_without_name_Equatable(_ obj: TestThatEnumType) -> Bool {
return obj.getValue() != .ValueOfThatEnumType
}
func use_metadata<T>(_ t:T){}
use_metadata(NSRuncingOptions.mince)
// CHECK-LABEL: define linkonce_odr hidden %swift.type* @_T0SC16NSRuncingOptionsOMa()
// CHECK: call %swift.type* @swift_getForeignTypeMetadata({{.*}} @_T0SC16NSRuncingOptionsON {{.*}}) [[NOUNWIND_READNONE:#[0-9]+]]
@objc enum ExportedToObjC: Int {
case Foo = -1, Bar, Bas
}
// CHECK-LABEL: define hidden swiftcc i64 @_T012objc_ns_enum0a1_C7_injectAA14ExportedToObjCOyF()
// CHECK: ret i64 -1
func objc_enum_inject() -> ExportedToObjC {
return .Foo
}
// CHECK-LABEL: define hidden swiftcc i64 @_T012objc_ns_enum0a1_C7_switchSiAA14ExportedToObjCOF(i64)
// CHECK: switch i64 %0, label {{%.*}} [
// CHECK: i64 -1, label {{%.*}}
// CHECK: i64 0, label {{%.*}}
// CHECK: i64 1, label {{%.*}}
func objc_enum_switch(_ x: ExportedToObjC) -> Int {
switch x {
case .Foo:
return 0
case .Bar:
return 1
case .Bas:
return 2
}
}
@objc class ObjCEnumMethods : NSObject {
// CHECK: define internal void @_T012objc_ns_enum15ObjCEnumMethodsC0C2InyAA010ExportedToD1COFTo([[OBJC_ENUM_METHODS:.*]]*, i8*, i64)
dynamic func enumIn(_ x: ExportedToObjC) {}
// CHECK: define internal i64 @_T012objc_ns_enum15ObjCEnumMethodsC0C3OutAA010ExportedToD1COyFTo([[OBJC_ENUM_METHODS]]*, i8*)
dynamic func enumOut() -> ExportedToObjC { return .Foo }
// CHECK: define internal i64 @_T012objc_ns_enum15ObjCEnumMethodsC4propAA010ExportedToD1COfgTo([[OBJC_ENUM_METHODS]]*, i8*)
// CHECK: define internal void @_T012objc_ns_enum15ObjCEnumMethodsC4propAA010ExportedToD1COfsTo([[OBJC_ENUM_METHODS]]*, i8*, i64)
dynamic var prop: ExportedToObjC = .Foo
}
// CHECK-LABEL: define hidden swiftcc void @_T012objc_ns_enum0a1_C13_method_callsyAA15ObjCEnumMethodsCF(%T12objc_ns_enum15ObjCEnumMethodsC*)
func objc_enum_method_calls(_ x: ObjCEnumMethods) {
// CHECK: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OBJC_ENUM_METHODS]]*, i8*)*)
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJC_ENUM_METHODS]]*, i8*, i64)*)
x.enumIn(x.enumOut())
// CHECK: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OBJC_ENUM_METHODS]]*, i8*)*)
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJC_ENUM_METHODS]]*, i8*, i64)*)
x.enumIn(x.prop)
// CHECK: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OBJC_ENUM_METHODS]]*, i8*)*)
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJC_ENUM_METHODS]]*, i8*, i64)*)
x.prop = x.enumOut()
}
// CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind readnone }
|
apache-2.0
|
35a1756a8f1d36cfbb80e6446b6a2b35
| 38.601399 | 140 | 0.707575 | 3.190423 | false | false | false | false |
wikimedia/apps-ios-wikipedia
|
Wikipedia/Code/ReadMoreAboutRevertedEditViewController.swift
|
1
|
6061
|
import UIKit
import WMF
@objc protocol ReadMoreAboutRevertedEditViewControllerDelegate: class {
func readMoreAboutRevertedEditViewControllerDidPressGoToArticleButton(_ articleURL: URL)
}
class ReadMoreAboutRevertedEditViewController: WMFScrollViewController {
private var theme = Theme.standard
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!
@IBOutlet weak var contentTextView: UITextView!
@IBOutlet weak var contentTextViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var button: UIButton!
@objc public var articleURL: URL?
@objc public weak var delegate: ReadMoreAboutRevertedEditViewControllerDelegate?
override public func viewDidLoad() {
super.viewDidLoad()
contentTextView.delegate = self
title = CommonStrings.revertedEditTitle
titleLabel.text = WMFLocalizedString("reverted-edit-thanks-for-editing-title", value: "Thanks for editing Wikipedia!", comment: "Title thanking the user for contributing to Wikipedia")
subtitleLabel.text = WMFLocalizedString("reverted-edit-possible-reasons-subtitle", value: "We know that you tried your best, but one of the reviewers had a concern.\n\nPossible reasons your edit was reverted include:", comment: "Subtitle leading to an explanation why an edit was reverted.")
button.setTitle(WMFLocalizedString("reverted-edit-back-to-article-button-title", value: "Back to article", comment: "Title for button that allows the user to go back to the article they edited"), for: .normal)
button.layer.cornerRadius = 8
button.contentEdgeInsets = UIEdgeInsets(top: 12, left: 24, bottom: 12, right: 24)
button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
view.wmf_configureSubviewsForDynamicType()
apply(theme: theme)
}
@objc private func close() {
dismiss(animated: true)
}
@objc private func buttonPressed() {
close()
guard let articleURL = articleURL else {
assertionFailure("articleURL should be set by now")
return
}
guard let delegate = delegate else {
assertionFailure("delegate should be set by now")
return
}
delegate.readMoreAboutRevertedEditViewControllerDidPressGoToArticleButton(articleURL)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let closeButton = UIBarButtonItem.wmf_buttonType(WMFButtonType.X, target: self, action: #selector(close))
navigationItem.leftBarButtonItem = closeButton
}
let editingGuidelines = (text: WMFLocalizedString("reverted-edit-view-guidelines-text", value: "View guidelines", comment: "Text for link for viewing editing guidelines"),
urlString: "https://www.wikidata.org/wiki/Help:FAQ#Editing")
private var contentTextViewText: NSAttributedString? {
let formatString = WMFLocalizedString("reverted-edit-possible-reasons", value: "- Your contribution didn’t follow one of the guidelines. %1$@ \n\n - Your contribution looked like an experiment or vandalism", comment: "List of possible reasons describing why an edit might have been reverted. %1$@ is replaced with a link to view editing guidelines")
let baseAttributes: [NSAttributedString.Key: Any] = [.font: UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection), .foregroundColor: theme.colors.primaryText];
let linkAttributes: [NSAttributedString.Key: Any] = [.foregroundColor: theme.colors.link,
.font: UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection)]
guard let attributedString = formatString.attributedString(attributes: baseAttributes, substitutionStrings: [editingGuidelines.text], substitutionAttributes: [linkAttributes]) else {
return nil
}
let mutableAttributedString = NSMutableAttributedString(attributedString: attributedString)
let range = mutableAttributedString.mutableString.range(of: editingGuidelines.text)
mutableAttributedString.addAttribute(NSAttributedString.Key.link, value: editingGuidelines.urlString, range: range)
return mutableAttributedString
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
titleLabel.font = UIFont.wmf_font(.semiboldSubheadline, compatibleWithTraitCollection: traitCollection)
subtitleLabel.font = UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection)
contentTextView.attributedText = contentTextViewText
button.titleLabel?.font = UIFont.wmf_font(.semiboldSubheadline, compatibleWithTraitCollection: traitCollection)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
contentTextViewHeightConstraint.constant = contentTextView.sizeThatFits(contentTextView.frame.size).height
}
}
extension ReadMoreAboutRevertedEditViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
contentView.backgroundColor = theme.colors.paperBackground
contentTextView.backgroundColor = view.backgroundColor
titleLabel.textColor = theme.colors.secondaryText
subtitleLabel.textColor = theme.colors.primaryText
button.setTitleColor(theme.colors.link, for: .normal)
button.backgroundColor = theme.colors.cardButtonBackground
}
}
extension ReadMoreAboutRevertedEditViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
guard URL.absoluteString == editingGuidelines.urlString else {
return false
}
return true
}
}
|
mit
|
98d7fb8598bc722d50a63a542ffc1387
| 50.347458 | 357 | 0.73527 | 5.319579 | false | false | false | false |
martinLilili/JSONModelWithMirror
|
JSONModel/JSONModel.swift
|
1
|
9396
|
//
// JSONModel.swift
// JSONModel
//
// Created by UBT on 2016/12/5.
// Copyright © 2016年 martin. All rights reserved.
//
import UIKit
//MARK: - MirrorResult,使用mirror遍历所有的属性和值,通过action传出做相应的处理
public protocol MirrorResult {
/// 使用mirror遍历所有的属性和值
///
/// - Parameters:
/// - mir: mirror
/// - action: 要对属性和值做什么处理
func getResultFromMirror(mir : Mirror, action: (_ label: String?, _ value : Any) -> Void)
}
public extension MirrorResult {
public func getResultFromMirror(mir : Mirror, action: (_ label: String?, _ value : Any) -> Void) {
if let superMirror = mir.superclassMirror { //便利父类所有属性
getResultFromMirror(mir: superMirror, action: action)
}
if (mir.children.count) > 0 {
for case let (label?, value) in (mir.children) {
action(label, value)
}
}
}
}
//MARK: - JSON协议
//自定义一个JSON协议
public protocol JSON: MirrorResult {
/// 如果是对象实现了JSON协议,这个方法返回对象属性及其value的dic,注意如果某个value不是基础数据类型,会一直向下解析直到基础数据类型为止,另外可选类型和数组需要单独处理
/// 如果是基础数据类型实现了JSON协议,只返回他们自己
/// - Returns: 对于对象返回dic,对于基础数据类型,返回他们自己
func toJSONModel() -> AnyObject?
/// 生成JSON字符串
///
/// - Returns: 字符串
func toJSONString() -> String
}
//扩展协议方法
public extension JSON {
/// 使用mirror遍历所有的属性,并保存与dic中,如果属性的value不是基础类型,则一直向下解析直到基础类型,另外可选类型和数组需要单独处理
///
/// - Parameter mir: mirror
/// - Returns: dic
// func getResultFromMirror(mir : Mirror) -> [String:AnyObject] {
// var result: [String:AnyObject] = [:]
// if let superMirror = mir.superclassMirror { //便利父类所有属性
// result = getResultFromMirror(mir: superMirror)
// }
// if (mir.children.count) > 0 {
// for case let (label?, value) in (mir.children) {
// //属性:label 值:value
// if let jsonValue = value as? JSON { //如果value实现了JSON,继续向下解析
// result[label] = jsonValue.toJSONModel()
// }
// }
// }
// return result
// }
/// 将数据转成可用的JSON模型
public func toJSONModel() -> AnyObject? {
let mirror = Mirror(reflecting: self)
if mirror.children.count > 0 {
// let result = getResultFromMirror(mir: mirror)
var result: [String:AnyObject] = [:]
getResultFromMirror(mir: mirror, action: { (label, value) in
//属性:label 值:value
if let jsonValue = value as? JSON , label != nil { //如果value实现了JSON,继续向下解析
result[label!] = jsonValue.toJSONModel()
}
})
return result as AnyObject? //有属性的对象,返回result是一个dic
}
return self as AnyObject? //基础数据类型,返回自己
}
//将数据转成JSON字符串
public func toJSONString() -> String {
let jsonModel = self.toJSONModel()
//利用OC的json库转换成OC的Data,
let data : Data! = try? JSONSerialization.data(withJSONObject: jsonModel ?? [:] , options: .prettyPrinted)
//data转换成String打印输出
if let str = String(data: data, encoding: String.Encoding.utf8) {
return str
} else {
return ""
}
}
}
//扩展可选类型,使其遵循JSON协议
extension Optional: JSON {
//可选类型重写toJSONModel()方法
public func toJSONModel() -> AnyObject? {
if let x = self {
if let value = x as? JSON {
return value.toJSONModel()
}
}
return nil
}
}
//扩展Swift的基本数据类型,使其遵循JSON协议
extension String: JSON { }
extension Int: JSON { }
extension Bool: JSON { }
extension Dictionary: JSON { }
extension Array: JSON {
public func toJSONModel() -> AnyObject? {
let mirror = Mirror(reflecting: self)
if mirror.children.count > 0 {
var arr:[Any] = []
for childer in Mirror(reflecting: self).children {
if let jsonValue = childer.value as? JSON {
if let jsonModel = jsonValue.toJSONModel() {
arr.append(jsonModel)
}
}
}
return arr as AnyObject?
}
return self as AnyObject?
}
}
//得到所有的属性即value
public protocol PropertieValues: MirrorResult {
/// 得到所有的属性及其对应的value组成dic,注意value不一定全是基础数据类型,可能是其他自定义对象。同时,dic中存储的都是有值的属性,那些没有赋值的属性不会出现在dic中
///
/// - Returns: dic
func codablePropertieValues() -> [String:AnyObject]
//遍历所有的属性列表,将所有的属性存储到数组中
func allProperties() -> [String]
}
//MARK: - PropertieValues协议
public extension PropertieValues {
// func getPropertieValuesWithMirror(mir : Mirror) -> [String:AnyObject] {
// var result: [String:AnyObject] = [:]
// if let superMirror = mir.superclassMirror {
// result = getPropertieValuesWithMirror(mir: superMirror)
// }
// for case let (label?, value) in (mir.children) {
// result[label] = unwrap(any: value) as AnyObject?
// }
// return result
// }
//
/// 得到所有的属性及其对应的value组成dic,注意value不一定全是基础数据类型,可能是其他自定义对象。同时,dic中存储的都是有值的属性,那些没有赋值的属性不会出现在dic中
///
/// - Returns: dic
public func codablePropertieValues() -> [String:AnyObject] {
var codableProperties = [String:AnyObject]()
let mirror = Mirror(reflecting: self)
// codableProperties = getPropertieValuesWithMirror(mir: mirror)
getResultFromMirror(mir: mirror, action: { (label, value) in
if label != nil {
codableProperties[label!] = unwrap(any: value) as AnyObject?
}
})
return codableProperties
}
// //遍历所有的属性列表,将所有的属性存储到数组中
// func getPropertiesWithMirror(mir : Mirror) -> [String] {
// var result: [String] = []
// if let superMirror = mir.superclassMirror {
// result = getPropertiesWithMirror(mir: superMirror)
// }
// for case let (label?, _) in (mir.children) {
// result.append(label)
// }
// return result
// }
//遍历所有的属性列表,将所有的属性存储到数组中
public func allProperties() -> [String] {
var allProperties = [String]()
let mirror = Mirror(reflecting: self)
// codableProperties = getPropertiesWithMirror(mir: mirror)
getResultFromMirror(mir: mirror, action: { (label, value) in
if label != nil {
allProperties.append(label!)
}
})
return allProperties
}
/// 将一个any类型的对象转化为可选类型
///
/// - Parameter any: any 类型对象
/// - Returns: 可选值
public func unwrap(any: Any) -> Any? {
let mirror = Mirror(reflecting: any)
if mirror.displayStyle != .optional {
return any
}
if mirror.children.count == 0 { return nil } // Optional.None
for case let (_?, value) in (mirror.children) {
return value
}
return nil
}
}
//MARK: - JSONModel
@objcMembers open class JSONModel: NSObject, JSON, NSCoding, PropertieValues {
override public init() {
}
override open var description: String {
return toJSONString()
}
public func encode(with aCoder: NSCoder) {
let dic = codablePropertieValues()
for (key, value) in dic {
switch value {
case let property as AnyObject:
aCoder.encode(property, forKey: key)
case let property as Int:
aCoder.encodeCInt(Int32(property), forKey: key)
case let property as Bool:
aCoder.encode(property, forKey: key)
default:
print("Nil value for \(key)")
}
}
}
public required init?(coder aDecoder: NSCoder) {
super.init()
let arr = allProperties()
for key in arr {
let object = aDecoder.decodeObject(forKey: key)
self.setValue(object, forKey: key)
}
}
}
|
mit
|
0beb5011e37373a83d5aff211265d7ff
| 29.852273 | 114 | 0.555187 | 3.992647 | false | false | false | false |
leznupar999/SSYoutubeParser
|
SSYoutubeParser/AVPlayerView.swift
|
1
|
764
|
//
// AVPlayerView.swift
// Movin_ios
//
// Created by leznupar999 on 2015/06/03.
// Copyright (c) 2015 leznupar999. All rights reserved.
//
import UIKit
import AVFoundation
class AVPlayerView: UIView {
var player: AVPlayer! {
get {
let layer: AVPlayerLayer = self.layer as! AVPlayerLayer
return layer.player
}
set(newValue) {
let layer: AVPlayerLayer = self.layer as! AVPlayerLayer
layer.player = newValue
}
}
override class func layerClass() -> AnyClass {
return AVPlayerLayer.self
}
func setVideoFillMode(mode: String) {
let layer: AVPlayerLayer = self.layer as! AVPlayerLayer
layer.videoGravity = mode
}
}
|
mit
|
6698ad54dcacbeffb390fae8e7efeace
| 21.470588 | 67 | 0.602094 | 4.316384 | false | false | false | false |
chrisjmendez/swift-exercises
|
Transitions/DynamicViewControllers/DynamicViewControllers/ViewController.swift
|
1
|
2760
|
//
// ViewController.swift
// DynamicViewControllers
//
// Created by Chris on 1/18/16.
// Copyright © 2016 Chris Mendez. All rights reserved.
//
// Note:
// This example shows two things:
// 1. How to create view controllers dynamically
// 2. How to override the basic animation and create a custom fade in animator
import UIKit
class ViewController: UIViewController {
let STORYBOARD = "Main"
let VIEW_CONTROLLER_IDENTIFIER = "viewController"
@IBAction func onButton(sender: AnyObject) {
let recursiveCount = navigationController?.viewControllers.count
let nextViewController = UIStoryboard(name: STORYBOARD, bundle: nil).instantiateViewControllerWithIdentifier(VIEW_CONTROLLER_IDENTIFIER) as! ViewController
nextViewController.title = "View # \(recursiveCount!)"
navigationController?.pushViewController(nextViewController, animated: true)
}
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.
}
}
class FadeInAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.35
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView()
//Animations
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
//
containerView?.addSubview((toVC?.view)!)
//Initial state of alpha is 0
toVC?.view.alpha = 0.0
let duration = transitionDuration(transitionContext)
UIView.animateWithDuration(duration, animations: { () -> Void in
toVC?.view.alpha = 1.0
}) { (finished) -> Void in
let cancelled = transitionContext.transitionWasCancelled()
transitionContext.completeTransition(!cancelled)
}
}
}
class NavigationControllerDelegate:NSObject, UINavigationControllerDelegate {
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return FadeInAnimator()
}
}
|
mit
|
be2d3d6fde8f7701abc8401c9aaa19a5
| 34.371795 | 281 | 0.708953 | 6.103982 | false | false | false | false |
webim/webim-client-sdk-ios
|
WebimClientLibrary/Backend/DeltaRequestLoop.swift
|
1
|
17805
|
//
// DeltaRequestLoop.swift
// WebimClientLibrary
//
// Created by Nikita Lazarev-Zubov on 16.08.17.
// Copyright © 2017 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/**
Class that handles HTTP-requests sending by SDK with internal requested actions (initialization and chat updates).
- seealso:
`DeltaCallback`
`DeltaResponse`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
class DeltaRequestLoop: AbstractRequestLoop {
// MARK: - Properties
private static var providedAuthenticationTokenErrorCount = 0
private let appVersion: String?
private let baseURL: String
private let deltaCallback: DeltaCallback
private let deviceID: String
private let title: String
@WMSynchronized var authorizationData: AuthorizationData?
@WMSynchronized private var providedAuthenticationToken: String?
@WMSynchronized var queue: DispatchQueue?
@WMSynchronized var since: Int64 = 0
@WMSynchronized private var deviceToken: String?
@WMSynchronized private var remoteNotificationSystem: Webim.RemoteNotificationSystem?
@WMSynchronized private var location: String
@WMSynchronized private var sessionID: String?
@WMSynchronized private var visitorFieldsJSONString: String?
@WMSynchronized private var visitorJSONString: String?
@WMSynchronized private var prechat: String?
private let sessionParametersListener: SessionParametersListener? // а не должен ли он быть weak ?
private weak var providedAuthenticationTokenStateListener: ProvidedAuthorizationTokenStateListener?
// MARK: - Initialization
init(deltaCallback: DeltaCallback,
completionHandlerExecutor: ExecIfNotDestroyedHandlerExecutor,
sessionParametersListener: SessionParametersListener?,
internalErrorListener: InternalErrorListener,
baseURL: String,
title: String,
location: String,
appVersion: String?,
visitorFieldsJSONString: String?,
providedAuthenticationTokenStateListener: ProvidedAuthorizationTokenStateListener?,
providedAuthenticationToken: String?,
deviceID: String,
deviceToken: String?,
remoteNotificationSystem: Webim.RemoteNotificationSystem?,
visitorJSONString: String?,
sessionID: String?,
prechat:String?,
authorizationData: AuthorizationData?) {
self.deltaCallback = deltaCallback
self.sessionParametersListener = sessionParametersListener
self.baseURL = baseURL
self.title = title
self.location = location
self.appVersion = appVersion
self.visitorFieldsJSONString = visitorFieldsJSONString
self.deviceID = deviceID
self.deviceToken = deviceToken
self.remoteNotificationSystem = remoteNotificationSystem
self.visitorJSONString = visitorJSONString
self.sessionID = sessionID
self.authorizationData = authorizationData
self.providedAuthenticationTokenStateListener = providedAuthenticationTokenStateListener
self.providedAuthenticationToken = providedAuthenticationToken
self.prechat = prechat
super.init(completionHandlerExecutor: completionHandlerExecutor, internalErrorListener: internalErrorListener)
}
// MARK: - Methods
override func start() {
guard queue == nil else {
return
}
queue = DispatchQueue(label: "ru.webim.DeltaDispatchQueue")
guard let queue = queue else {
WebimInternalLogger.shared.log(entry: "DispatchQueue initialisation failure in DeltaRequestLoop.\(#function)")
return
}
queue.async {
self.run()
}
}
override func stop() {
super.stop()
queue = nil
}
func set(deviceToken: String) {
self.deviceToken = deviceToken
}
func change(location: String) throws {
self.location = location
authorizationData = nil
since = 0
requestInitialization()
}
func getAuthorizationData() -> AuthorizationData? {
return authorizationData
}
func run() {
while isRunning() {
if authorizationData != nil && since != 0 {
requestDelta()
} else {
requestInitialization()
}
}
}
func parseRequestInitialization(data: Data) {
if let dataJSON = try? (JSONSerialization.jsonObject(with: data) as? [String: Any]) {
if let error = dataJSON[AbstractRequestLoop.ResponseFields.error.rawValue] as? String {
handleInitialization(error: error)
} else {
DeltaRequestLoop.providedAuthenticationTokenErrorCount = 0
let deltaResponse = DeltaResponse(jsonDictionary: dataJSON)
if let deltaList = deltaResponse.getDeltaList() {
if deltaList.count > 0 {
handleIncorrectServerAnswer()
return
}
}
guard let fullUpdate = deltaResponse.getFullUpdate() else {
handleIncorrectServerAnswer()
return
}
if let since = deltaResponse.getRevision() {
self.since = since
}
process(fullUpdate: fullUpdate)
}
} else {
WebimInternalLogger.shared.log(entry: "Error de-serializing server response: \(String(data: data, encoding: .utf8) ?? "unreadable data").",
verbosityLevel: .warning)
}
}
func requestInitialization() {
let url = URL(string: getDeltaServerURLString() + "?" + getInitializationParameterString())
var request = URLRequest(url: url!)
request.setValue("3.37.4", forHTTPHeaderField: Parameter.webimSDKVersion.rawValue)
request.httpMethod = AbstractRequestLoop.HTTPMethods.get.rawValue
do {
let data = try perform(request: request)
self.parseRequestInitialization(data: data)
} catch let unknownError as UnknownError {
self.completionHandlerExecutor?.execute(task: DispatchWorkItem {
self.handleRequestLoop(error: unknownError)
})
} catch {
WebimInternalLogger.shared.log(entry: "Request failed with unknown error: \(error.localizedDescription)",
verbosityLevel: .warning)
}
}
private func parseDelta(data: Data) {
if let dataJSON = try? (JSONSerialization.jsonObject(with: data) as? [String: Any]) {
if let error = dataJSON[AbstractRequestLoop.ResponseFields.error.rawValue] as? String {
handleDeltaRequest(error: error)
} else {
let deltaResponse = DeltaResponse(jsonDictionary: dataJSON)
guard let revision = deltaResponse.getRevision() else {
// Delta timeout.
return
}
since = revision
if let fullUpdate = deltaResponse.getFullUpdate() {
completionHandlerExecutor?.execute(task: DispatchWorkItem {
self.process(fullUpdate: fullUpdate)
})
} else if let deltaList = deltaResponse.getDeltaList() {
if deltaList.count > 0 {
completionHandlerExecutor?.execute(task: DispatchWorkItem {
self.deltaCallback.process(deltaList: deltaList)
})
}
}
}
} else {
WebimInternalLogger.shared.log(entry: "Error de-serializing server response: \(String(data: data, encoding: .utf8) ?? "unreadable data").",
verbosityLevel: .warning)
}
}
func requestDelta() {
guard let url = URL(string: getDeltaServerURLString() + "?" + getDeltaParameterString()) else {
WebimInternalLogger.shared.log(entry: "Initialize URL failure in DeltaRequestLoop.\(#function)")
return
}
var request = URLRequest(url: url)
request.httpMethod = AbstractRequestLoop.HTTPMethods.get.rawValue
do {
let data = try perform(request: request)
self.parseDelta(data: data)
} catch let unknownError as UnknownError {
handleRequestLoop(error: unknownError)
} catch {
WebimInternalLogger.shared.log(entry: "Request failed with unknown error: \(error.localizedDescription).",
verbosityLevel: .warning)
}
}
// MARK: Private methods
private func getDeltaServerURLString() -> String {
return (baseURL + ServerPathSuffix.getDelta.rawValue)
}
private func getInitializationParameterString() -> String {
var parameterDictionary = [Parameter.deviceID.rawValue: deviceID,
Parameter.event.rawValue: Event.initialization.rawValue,
Parameter.location.rawValue: location,
Parameter.platform.rawValue: Platform.ios.rawValue,
Parameter.respondImmediately.rawValue: true,
Parameter.since.rawValue: 0,
Parameter.title.rawValue: title] as [String: Any]
if let appVersion = appVersion {
parameterDictionary[Parameter.applicationVersion.rawValue] = appVersion
}
if let deviceToken = deviceToken {
parameterDictionary[Parameter.deviceToken.rawValue] = deviceToken
switch remoteNotificationSystem {
case .apns:
parameterDictionary[Parameter.pushService.rawValue] = "apns"
case .fcm:
parameterDictionary[Parameter.pushService.rawValue] = "fcm"
default:
break
}
}
if let sessionID = sessionID {
parameterDictionary[Parameter.visitSessionID.rawValue] = sessionID
}
if let visitorJSONString = visitorJSONString {
parameterDictionary[Parameter.visitor.rawValue] = visitorJSONString
}
if let visitorFieldsJSONString = visitorFieldsJSONString {
parameterDictionary[Parameter.visitorExt.rawValue] = visitorFieldsJSONString
}
if let providedAuthenticationToken = providedAuthenticationToken {
parameterDictionary[Parameter.providedAuthenticationToken.rawValue] = providedAuthenticationToken
}
if let prechat = prechat {
parameterDictionary[Parameter.prechat.rawValue] = prechat
}
return parameterDictionary.stringFromHTTPParameters()
}
private func getDeltaParameterString() -> String {
let currentTimestamp = Int64(CFAbsoluteTimeGetCurrent() * 1000)
var parameterDictionary = [Parameter.since.rawValue: String(since),
Parameter.timestamp.rawValue: currentTimestamp] as [String: Any]
if let authorizationData = authorizationData {
parameterDictionary[Parameter.pageID.rawValue] = authorizationData.getPageID()
parameterDictionary[Parameter.authorizationToken.rawValue] = authorizationData.getAuthorizationToken()
}
return parameterDictionary.stringFromHTTPParameters()
}
private func sleepBetweenInitializationAttempts() {
authorizationData = nil
since = 0
usleep(1_000_000) // 1s
}
private func handleIncorrectServerAnswer() {
WebimInternalLogger.shared.log(entry: "Incorrect server answer while requesting initialization.",
verbosityLevel: .debug)
usleep(1_000_000) // 1s
}
private func handleInitialization(error: String) {
switch error {
case WebimInternalError.reinitializationRequired.rawValue:
handleReinitializationRequiredError()
break
case WebimInternalError.providedAuthenticationTokenNotFound.rawValue:
handleProvidedAuthenticationTokenNotFoundError()
break
default:
running = false
completionHandlerExecutor?.execute(task: DispatchWorkItem {
self.internalErrorListener?.on(error: error)
})
break
}
}
private func handleDeltaRequest(error: String) {
if error == WebimInternalError.reinitializationRequired.rawValue {
handleReinitializationRequiredError()
} else {
completionHandlerExecutor?.execute(task: DispatchWorkItem {
self.internalErrorListener?.on(error: error)
})
}
}
private func handleReinitializationRequiredError() {
authorizationData = nil
since = 0
}
private func handleProvidedAuthenticationTokenNotFoundError() {
DeltaRequestLoop.providedAuthenticationTokenErrorCount += 1
if DeltaRequestLoop.providedAuthenticationTokenErrorCount < 5 {
sleepBetweenInitializationAttempts()
} else {
guard let token = providedAuthenticationToken else {
WebimInternalLogger.shared.log(entry: "Provided Authentication Token is nil in DeltaRequestLoop.\(#function)")
return
}
providedAuthenticationTokenStateListener?.update(providedAuthorizationToken: token)
DeltaRequestLoop.providedAuthenticationTokenErrorCount = 0
sleepBetweenInitializationAttempts()
}
}
private func process(fullUpdate: FullUpdate) {
let visitorJSONString = fullUpdate.getVisitorJSONString()
let sessionID = fullUpdate.getSessionID()
let authorizationData = AuthorizationData(pageID: fullUpdate.getPageID(),
authorizationToken: fullUpdate.getAuthorizationToken())
let isNecessaryToUpdateVisitorFieldJSONString = (self.visitorFieldsJSONString == nil)
|| (self.visitorFieldsJSONString != visitorFieldsJSONString)
let isNecessaryToUpdateSessionID = (self.sessionID == nil)
|| (self.sessionID != sessionID)
let isNecessaryToUpdateAuthorizationData = (self.authorizationData == nil)
|| ((self.authorizationData?.getPageID() != fullUpdate.getPageID())
|| (self.authorizationData?.getAuthorizationToken() != fullUpdate.getAuthorizationToken()))
if (isNecessaryToUpdateVisitorFieldJSONString
|| isNecessaryToUpdateSessionID)
|| isNecessaryToUpdateAuthorizationData {
self.visitorJSONString = visitorJSONString
self.sessionID = sessionID
self.authorizationData = authorizationData
DispatchQueue.global(qos: .background).async { [weak self] in
guard let `self` = self,
let visitorJSONString = self.visitorJSONString,
let sessionID = self.sessionID,
let authorizationData = self.authorizationData else {
WebimInternalLogger.shared.log(entry: "Changing parameters failure while unwrpping in DeltaRequestLoop.\(#function)")
return
}
self.completionHandlerExecutor?.execute(task: DispatchWorkItem {
self.sessionParametersListener?.onSessionParametersChanged(visitorFieldsJSONString: visitorJSONString,
sessionID: sessionID,
authorizationData: authorizationData)
})
}
}
completionHandlerExecutor?.execute(task: DispatchWorkItem {
self.completionHandlerExecutor?.execute(task: DispatchWorkItem {
self.deltaCallback.process(fullUpdate: fullUpdate)
})
})
}
}
|
mit
|
332a20e551915f052cb6aca4cdd67666
| 40.558411 | 151 | 0.615843 | 5.700962 | false | false | false | false |
335g/TwitterAPIKit
|
Sources/Models/UsersList.swift
|
1
|
1299
|
//
// UsersList.swift
// TwitterAPIKit
//
// Created by Yoshiki Kudo on 2015/07/06.
// Copyright © 2015年 Yoshiki Kudo. All rights reserved.
//
import Foundation
public struct UsersList {
public let users: [Users]
public let nextCursor: Int
public let nextCursorStr: String
public let previousCursor: Int
public let previousCursorStr: String
public init?(dictionary: [String: AnyObject]){
guard let
_users = dictionary["users"] as? Array<[String: AnyObject]>,
nextCursor = dictionary["next_cursor"] as? Int,
nextCursorStr = dictionary["next_cursor_str"] as? String,
previousCursor = dictionary["previous_cursor"] as? Int,
previousCursorStr = dictionary["previous_cursor_str"] as? String else {
return nil
}
var users: [Users] = []
for _user in _users {
guard let user = Users(dictionary: _user) else {
return nil
}
users.append(user)
}
self.users = users
self.nextCursor = nextCursor
self.nextCursorStr = nextCursorStr
self.previousCursor = previousCursor
self.previousCursorStr = previousCursorStr
}
}
|
mit
|
825b8527587a450b311652dc21adbe0d
| 28.477273 | 83 | 0.585648 | 4.645161 | false | false | false | false |
NocturneZX/TTT-Pre-Internship-Exercises
|
Swift/Class2Playground.playground/section-1.swift
|
1
|
2130
|
// Playground - noun: a place where people can play
import UIKit
var str = "This is a test"
let newstr : String = str.stringByReplacingOccurrencesOfString("te", withString:
"gho", options: NSStringCompareOptions.LiteralSearch, range: nil)
println(newstr)
func isStringEqual(firstString: String, secondString: String) -> Bool{
return (firstString == secondString) ? true: false
}
let first = "This is the first."
let second = "This is the second."
let copyfirst = "This is the first."
isStringEqual(first, second)
isStringEqual(first, copyfirst)
var num = 0
do{
println(num++)
}while(num <= 100)
println("REAL QUICK!")
class Car {
var name: String = ""
var odometer: Double = 0
var driverName = "John Smith"
func drive(){
println("This car is a \(self.name) and it's going vroom")
odometer += 1000
}
func checkOdometer(){
println("This car has this much mileage: \(self.name)")
}
}
class Tesla: Car{
var charge: Int = 100
init(aName: String){
super.init()
self.driverName = aName
}
func setName(aTeslaName: String){ // Superclass
self.name = aTeslaName
}
func setCharge(aCharge: Int){
self.charge = aCharge
}
override func drive() {
println("This car is a \(self.name) and it's doesn't go vroom. It purrs.")
odometer += 1000
charge -= 10
}
func checkCharge(){
if self.charge < 50 && self.charge > 30{
println("This car has \(self.charge)% charge!")
}else if self.charge <= 30{
println("Holy shit. \(self.charge)% CHARGE! Hurry up and refuel.")
}else{
println("Charge is \(self.charge)% charge. All systems nominal.")
}
}
}
var someCar: Car = Car()
someCar.name = "Old car"
someCar.drive()
var someTesla: Tesla = Tesla(aName: "Julio");
someTesla.setName("Tesla Model Z")
someTesla.drive()
someTesla.drive()
someTesla.checkCharge()
someTesla.drive()
someTesla.checkCharge()
someTesla.drive()
someTesla.drive()
someTesla.drive()
someTesla.drive()
someTesla.checkCharge()
|
gpl-2.0
|
8bc16d48a031f586a1fef1f96b141132
| 22.406593 | 82 | 0.632864 | 3.641026 | false | false | false | false |
Alexiuce/Tip-for-day
|
iFeiBo/iFeiBo/WebLoginController/WebLoginViewController.swift
|
1
|
2565
|
//
// WebLoginViewController.swift
// iFeiBo
//
// Created by Alexcai on 2017/9/17.
// Copyright © 2017年 Alexcai. All rights reserved.
//
import Cocoa
import WebKit
import Alamofire
class WebLoginViewController: NSViewController {
@IBOutlet weak var webView: WebView!
lazy var session = URLSession(configuration: URLSessionConfiguration.default)
var dataTask : URLSessionDataTask!
var codeForToken = "" {
didSet{
if codeForToken == oldValue {return}
let url = URL(string: WBTokenURL)!
let paraDict = ["client_id":WBAppID,"client_secret":WBAppSecretKey,"grant_type":"authorization_code",
"code":codeForToken,"redirect_uri":WBAppReDirectURL]
Alamofire.request(url, method: .post, parameters: paraDict).responseJSON { (response) in
guard let data = try? JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.mutableLeaves) as? [String : Any] else {
return
}
let account = UserAccount(dict: data)
_ = UAToolManager.defaultManager.saveUserAccount(account)
let storyboard = NSStoryboard(name: "Main", bundle: nil)
let homeWindowController = storyboard.instantiateController(withIdentifier: kFBHomeControllerID) as! HomeWindowController
homeWindowController.showWindow(nil)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
let requestURL = URL(string:WBOAuth2URL)
let request = URLRequest(url: requestURL!)
webView.mainFrame.load(request)
}
}
extension WebLoginViewController : WebPolicyDelegate{
func webView(_ webView: WebView!, decidePolicyForNavigationAction actionInformation: [AnyHashable : Any]!, request: URLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) {
print(request.url?.host ?? "")
if request.url?.host == "alexiuce.github.io" {
guard let host = request.url?.absoluteString else { return }
let hostString = host as NSString
let range = hostString.range(of: "code=")
codeForToken = hostString.substring(from: range.location + range.length)
listener.ignore()
}
listener.use()
}
}
|
mit
|
7afd24aaeb024c527f7f63ab98b16c45
| 34.09589 | 207 | 0.607338 | 5.103586 | false | false | false | false |
guipanizzon/ioscreator
|
SpriteKitSwiftFollowPathTutorial/SpriteKitSwiftFollowPathTutorial/GameViewController.swift
|
36
|
2177
|
//
// GameViewController.swift
// SpriteKitSwiftFollowPathTutorial
//
// Created by Arthur Knopper on 09/02/15.
// Copyright (c) 2015 Arthur Knopper. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : String) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
mit
|
3258dcbe58833fadf43afae00b2178f3
| 30.550725 | 104 | 0.628847 | 5.610825 | false | false | false | false |
quintonwall/leads-sdk
|
Pod/Classes/Leads.swift
|
1
|
570
|
//
// Constants.swift
// Pods
//
// Created by Quinton Wall on 1/28/16.
//
//
import Foundation
open class Leads {
public struct StandardFields {
public static let ORGID = "oid"
public static let FIRST_NAME = "first_name"
public static let LAST_NAME = "last_name"
public static let EMAIL = "email"
public static let COMPANY = "company"
public static let CITY = "city"
public static let STATE = "state"
}
public enum LeadError: Error {
case noOrgId
case commsFailure
}
}
|
mit
|
4811b445a0517052caa93b9234a2717d
| 19.357143 | 51 | 0.598246 | 3.825503 | false | false | false | false |
sonnygauran/trailer
|
PocketTrailer/PickerViewController.swift
|
1
|
1779
|
import UIKit
protocol PickerViewControllerDelegate: class {
func pickerViewController(picker: PickerViewController, didSelectIndexPath: NSIndexPath)
}
final class PickerViewController: UITableViewController {
var values: [String]!
weak var delegate: PickerViewControllerDelegate!
var previousValue: Int?
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = values[indexPath.row]
cell.accessoryType = indexPath.row == previousValue ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
view.userInteractionEnabled = false
previousValue = indexPath.row
tableView.reloadData()
atNextEvent { [weak self] in
self!.navigationController?.popViewControllerAnimated(true)
self!.delegate.pickerViewController(self!, didSelectIndexPath: indexPath)
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Please select an option"
}
private var layoutDone: Bool = false
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if !layoutDone {
if let p = previousValue {
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: p, inSection:0), atScrollPosition: UITableViewScrollPosition.Middle, animated: false)
}
layoutDone = true
}
}
}
|
mit
|
6b70161dd2cce1fe748f068dc5c0fc53
| 31.345455 | 142 | 0.787521 | 4.782258 | false | false | false | false |
instacrate/Subber-api
|
Sources/App/Stripe/Models/FileUpload.swift
|
2
|
2817
|
//
// FileUpload.swift
// subber-api
//
// Created by Hakon Hanesand on 1/19/17.
//
//
import Foundation
import Node
public enum UploadReason: String, NodeConvertible {
case business_logo
case dispute_evidence
case identity_document
case incorporation_article
case incorporation_document
case invoice_statement
case payment_provider_transfer
case product_feed
var maxSize: Int {
switch self {
case .identity_document: fallthrough
case .business_logo: fallthrough
case .incorporation_article: fallthrough
case .incorporation_document: fallthrough
case .invoice_statement: fallthrough
case .invoice_statement: fallthrough
case .payment_provider_transfer: fallthrough
case .product_feed:
return 8 * 1000000
case .dispute_evidence:
return 4 * 1000000
}
}
var allowedMimeTypes: [String] {
switch self {
case .identity_document: fallthrough
case .business_logo: fallthrough
case .incorporation_article: fallthrough
case .incorporation_document: fallthrough
case .invoice_statement: fallthrough
case .invoice_statement: fallthrough
case .payment_provider_transfer: fallthrough
case .product_feed:
return ["image/jpeg", "image/png"]
case .dispute_evidence:
return ["image/jpeg", "image/png", "application/pdf"]
}
}
}
public enum FileType: String, NodeConvertible {
case pdf
case xml
case jpg
case png
case csv
case tsv
}
public final class FileUpload: NodeConvertible {
static let type = "file_upload"
public let id: String
public let created: Date
public let purpose: UploadReason
public let size: Int
public let type: FileType
public let url: String?
public init(node: Node, in context: Context = EmptyNode) throws {
guard try node.extract("object") == FileUpload.type else {
throw NodeError.unableToConvert(node: node, expected: FileUpload.type)
}
id = try node.extract("id")
created = try node.extract("created")
purpose = try node.extract("purpose")
size = try node.extract("size")
type = try node.extract("type")
url = try node.extract("url")
}
public func makeNode(context: Context = EmptyNode) throws -> Node {
return try Node(node: [
"id" : .string(id),
"created" : try created.makeNode(),
"purpose" : try purpose.makeNode(),
"size" : .number(.int(size)),
"type" : try type.makeNode()
]).add(objects: [
"url" : url
])
}
}
|
mit
|
8aaf7c13cea71ac765392bcf5c23d5fe
| 26.349515 | 82 | 0.601349 | 4.528939 | false | false | false | false |
bananafish911/SmartReceiptsiOS
|
SmartReceipts/Backup/DataExport.swift
|
1
|
2989
|
//
// DataExport.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 11/06/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import objective_zip
class DataExport: NSObject {
var workDirectory: String!
init(workDirectory: String) {
super.init()
self.workDirectory = workDirectory
}
func execute() -> String {
let zipPath = (workDirectory as NSString).appendingPathComponent(SmartReceiptsExportName)
Logger.debug("Execute at path: \(zipPath)")
let zipFile = OZZipFile(fileName: zipPath, mode: .create)
Logger.debug("zipFile legacy32BitMode: \(zipFile.legacy32BitMode ? "YES" : "NO")")
appendFile(named: SmartReceiptsDatabaseName, inDirectory: workDirectory,
archiveName: SmartReceiptsDatabaseExportName, toZip: zipFile)
appendAllTrips(toZip: zipFile)
let preferences = WBPreferences.xmlString().data(using: .utf8)
append(data: preferences!, zipName: SmartReceiptsPreferencesExportName, toFile: zipFile)
zipFile.close()
return zipPath
}
func appendFile(named fileName: String, inDirectory: String, archiveName: String, toZip: OZZipFile) {
let filePath = (inDirectory as NSString).appendingPathComponent(fileName)
let fileData = NSData(contentsOfFile: filePath)
append(data: fileData! as Data, zipName: archiveName, toFile: toZip)
}
func append(data: Data, zipName: String, toFile: OZZipFile) {
Logger.debug("Append Data: size \(data.count) zipName: \(zipName), toFile: \(toFile.description)")
let stream = toFile.writeInZip(withName: zipName, compressionLevel: .default)
stream.write(data)
stream.finishedWriting()
}
func appendAllTrips(toZip file: OZZipFile) {
let tripsFolder = (workDirectory as NSString).appendingPathComponent(SmartReceiptsTripsDirectoryName)
var trips = [String]()
do {
trips = try FileManager.default.contentsOfDirectory(atPath: tripsFolder)
} catch {
Logger.error("appendAllTripFilesToZip error: \(error.localizedDescription)")
}
for trip in trips {
appendFilesFor(trip: trip, to: file)
}
}
func appendFilesFor(trip: String, to zip: OZZipFile) {
let tripFolder = ((workDirectory as NSString).appendingPathComponent(SmartReceiptsTripsDirectoryName)
as NSString).appendingPathComponent(trip)
var files = [String]()
do {
files = try FileManager.default.contentsOfDirectory(atPath: tripFolder)
} catch {
Logger.error("appFilesForTrip error: \(error.localizedDescription)")
}
for file in files {
let zipName = (trip as NSString).appendingPathComponent(file)
appendFile(named: file, inDirectory: tripFolder, archiveName: zipName, toZip: zip)
}
}
}
|
agpl-3.0
|
d2aa1b9cc245734ef0eb63e683209fab
| 37.307692 | 109 | 0.65261 | 4.506787 | false | false | false | false |
EmilioPelaez/CGMath
|
CGMath/Sources/CGGeometry.swift
|
1
|
1422
|
//
// CGGeometry.swift
// CGMath
//
// Created by Emilio Peláez on 26/6/18.
//
import CoreGraphics
extension CGPoint: CGFloatListRepresentable {
public init(floatList: [CGFloat]) {
let floatList = floatList + [0, 0]
self.init(x: floatList[0], y: floatList[1])
}
public var floatList: [CGFloat] {
get {
[x, y]
}
set {
x = newValue[0]
y = newValue[1]
}
}
}
extension CGSize: CGFloatListRepresentable {
public init(floatList: [CGFloat]) {
let floatList = floatList + [0, 0]
self.init(width: floatList[0], height: floatList[1])
}
public var floatList: [CGFloat] {
get {
[width, height]
}
set {
width = newValue[0]
height = newValue[1]
}
}
}
extension CGRect: CGFloatListRepresentable {
public init(floatList: [CGFloat]) {
let floatList = floatList + [0, 0, 0, 0]
self.init(x: floatList[0], y: floatList[1], width: floatList[2], height: floatList[3])
}
public var floatList: [CGFloat] {
get { origin.floatList + size.floatList }
set {
origin = CGPoint(floatList: newValue)
size = CGSize(width: newValue[2], height: newValue[3])
}
}
}
extension CGVector: CGFloatListRepresentable {
public init(floatList: [CGFloat]) {
let floatList = floatList + [0, 0]
self.init(dx: floatList[0], dy: floatList[1])
}
public var floatList: [CGFloat] {
get {
[dx, dy]
}
set {
dx = CGFloat(newValue[0])
dy = CGFloat(newValue[1])
}
}
}
|
mit
|
e85183156e5e6955b2c286343b014e1e
| 18.202703 | 88 | 0.63969 | 2.780822 | false | false | false | false |
EgeTart/MedicineDMW
|
DWM/EnterpriseListData.swift
|
1
|
1182
|
//
// EnterpriseListData.swift
// DWM
//
// Created by 高永效 on 15/10/23.
// Copyright © 2015年 EgeTart. All rights reserved.
//
import Foundation
import Alamofire
class EnterpriseListData {
var enterprises = [Dictionary<String, AnyObject>]()
var enterpriseType: String!
init (enterpriseType: String) {
self.enterpriseType = enterpriseType
//getEnterprises()
}
func getEnterprises(completion completion: () -> Void) {
let currentPage = enterprises.count / 15 + 1
let params = ["currentPage": "\(currentPage)", "size": "15", "type": "\(enterpriseType)", "Cookie":"JSESSIONID=\(session)"]
Alamofire.request(.POST, "http://112.74.131.194:8080/MedicineProject/App/user/getEnterprise", parameters: params, encoding: ParameterEncoding.URL, headers: nil).responseJSON { (_, _, result) -> Void in
let enterprisesResult = result.value!["Enterprises"]! as! [Dictionary<String, AnyObject>]
for enterprise in enterprisesResult {
self.enterprises.append(enterprise)
}
completion()
}
}
}
|
mit
|
a026df9432976da0ae2c875450569c10
| 29.868421 | 209 | 0.611253 | 4.234657 | false | false | false | false |
taotao361/swift
|
FirstSwiftDemo/others/YTTestView.swift
|
1
|
1633
|
//
// YTTestView.swift
// FirstSwiftDemo
//
// Created by yangxutao on 2017/5/16.
// Copyright © 2017年 yangxutao. All rights reserved.
//
import UIKit
let identifier = "YTFirstCell"
extension YTTestView {
}
class YTTestView: UIView,UITableViewDelegate,UITableViewDataSource {
var tableView : UITableView
// let model : YTTestModel = YTTestModel.init(name: "pppp", detail: "haha")
override init(frame: CGRect) {
self.tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: 320, height: 568-20), style: UITableViewStyle.plain)
super.init(frame: frame)
self.initUI()
}
required init?(coder aDecoder: NSCoder) {
self.tableView = UITableView.init()
super.init(coder: aDecoder)
}
func initUI () {
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.register(YTFirstCell.self, forCellReuseIdentifier: identifier)
self.addSubview(self.tableView)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? YTFirstCell
cell?.labe1.text = "haha"
cell?.label2.text = "ppp"
return (cell)!
}
}
|
mit
|
36c3733fd94b3dcaa1936b73e3b88572
| 20.733333 | 132 | 0.615337 | 4.578652 | false | true | false | false |
wokalski/Diff.swift
|
Sources/ExtendedPatch+Apply.swift
|
8
|
2180
|
// TODO: Fix ugly copy paste :/
public extension RangeReplaceableCollection where Self.Iterator.Element: Equatable {
public func apply(_ patch: [ExtendedPatch<Generator.Element>]) -> Self {
var mutableSelf = self
for change in patch {
switch change {
case let .insertion(i, element):
let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(i)))
mutableSelf.insert(element, at: target)
case let .deletion(i):
let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(i)))
mutableSelf.remove(at: target)
case let .move(from, to):
let fromIndex = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(from)))
let toIndex = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(to)))
let element = mutableSelf.remove(at: fromIndex)
mutableSelf.insert(element, at: toIndex)
}
}
return mutableSelf
}
}
public extension String {
public func apply(_ patch: [ExtendedPatch<String.CharacterView.Iterator.Element>]) -> String {
var mutableSelf = self
for change in patch {
switch change {
case let .insertion(i, element):
let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(i)))
mutableSelf.insert(element, at: target)
case let .deletion(i):
let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(i)))
mutableSelf.remove(at: target)
case let .move(from, to):
let fromIndex = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(from)))
let toIndex = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(to)))
let element = mutableSelf.remove(at: fromIndex)
mutableSelf.insert(element, at: toIndex)
}
}
return mutableSelf
}
}
|
mit
|
6270abe8eb145da306f786a761c40939
| 40.923077 | 112 | 0.616972 | 5.034642 | false | false | false | false |
davejlin/treehouse
|
swift/swift2/selfie-photo/SelfiePhoto/SortItemSelector.swift
|
1
|
2062
|
//
// SortItemSelector.swift
// SelfiePhoto
//
// Created by Lin David, US-205 on 11/15/16.
// Copyright © 2016 Lin David. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class SortItemSelector<SortType: NSManagedObject>: NSObject, UITableViewDelegate {
private let sortItems: [SortType]
var checkedItems: Set<SortType> = []
init(sortItems: [SortType]) {
self.sortItems = sortItems
super.init()
}
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.section {
case 0:
guard let cell = tableView.cellForRowAtIndexPath(indexPath) else { return }
if cell.accessoryType == .None {
cell.accessoryType = .Checkmark
let nextSection = indexPath.section.advancedBy(1)
let numberOfRowsInSubsequentSection = tableView.numberOfRowsInSection(nextSection)
for row in 0..<numberOfRowsInSubsequentSection {
let indexPath = NSIndexPath(forRow: row, inSection: nextSection)
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.accessoryType = .None
}
checkedItems = []
}
case 1:
let allItemsIndexPath = NSIndexPath(forRow: 0, inSection: 0)
let allItemsCell = tableView.cellForRowAtIndexPath(allItemsIndexPath)
allItemsCell?.accessoryType = .None
guard let cell = tableView.cellForRowAtIndexPath(indexPath) else { return }
let item = sortItems[indexPath.row]
if cell.accessoryType == .None {
cell.accessoryType = .Checkmark
checkedItems.insert(item)
} else if cell.accessoryType == .Checkmark {
cell.accessoryType = .None
checkedItems.remove(item)
}
default: break
}
}
}
|
unlicense
|
a449d50cf4e45565865cf862600399bc
| 34.551724 | 98 | 0.597283 | 5.298201 | false | false | false | false |
drmohundro/Nimble
|
Nimble/Matchers/EndWith.swift
|
1
|
2042
|
import Foundation
public func endWith<S: SequenceType, T: Equatable where S.Generator.Element == T>(endingElement: T) -> MatcherFunc<S> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "end with <\(endingElement)>"
var actualGenerator = actualExpression.evaluate().generate()
var lastItem: T?
var item: T?
do {
lastItem = item
item = actualGenerator.next()
} while(item.hasValue)
return lastItem == endingElement
}
}
public func endWith(endingElement: AnyObject) -> MatcherFunc<NMBOrderedCollection?> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "end with <\(endingElement)>"
let collection = actualExpression.evaluate()
return collection.hasValue && collection!.indexOfObject(endingElement) == collection!.count - 1
}
}
public func endWith(endingSubstring: String) -> MatcherFunc<String> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "end with <\(endingSubstring)>"
let collection = actualExpression.evaluate()
let range = collection.rangeOfString(endingSubstring)
return range.hasValue && range!.endIndex == collection.endIndex
}
}
extension NMBObjCMatcher {
public class func endWithMatcher(expected: AnyObject) -> NMBObjCMatcher {
return NMBObjCMatcher { actualBlock, failureMessage, location in
let actual = actualBlock()
if let actualString = actual as? String {
let expr = Expression(expression: ({ actualString }), location: location)
return endWith(expected as NSString).matches(expr, failureMessage: failureMessage)
} else {
let expr = Expression(expression: ({ actual as? NMBOrderedCollection }), location: location)
return endWith(expected).matches(expr, failureMessage: failureMessage)
}
}
}
}
|
apache-2.0
|
6abb899ec6d737d84e258f0ecdac76e5
| 40.673469 | 119 | 0.670421 | 5.34555 | false | false | false | false |
softmaxsg/trakt.tv-searcher
|
TraktSearchAPIIntegrationTests/TraktSearchAPITests.swift
|
1
|
10508
|
//
// TraktSearchAPITests.swift
// TraktSearchAPIIntegrationTests
//
// Copyright © 2016 Vitaly Chupryk. All rights reserved.
//
import XCTest
import ObjectMapper
import OHHTTPStubs
@testable import TraktSearchAPI
class TraktSearchAPITests: XCTestCase
{
private static let popularMoviesUrlPath = "/movies/popular"
private static let searchMoviesUrlPath = "/search"
private static let fileResponseNormalPopularMovies = "PopularMovies.normal.json"
private static let fileResponseNormalSearchMovies = "SearchMovies.normal.json"
private static let fileResponseInvalidPopularMovies = "PopularMovies.invalid.json"
private static let fileResponseInvalidSearchMovies = "SearchMovies.invalid.json"
private static let fileHeadersNormal = "Headers.normal.json"
private static let fileHeadersInvalid = "Headers.invalid.json"
let applicationKey = NSUUID().UUIDString
let queue: NSOperationQueue = NSOperationQueue()
var searchAPI: TraktSearchAPI?
override func setUp()
{
super.setUp()
self.searchAPI = TraktSearchAPI(queue: self.queue, applicationKey: self.applicationKey)
}
override func tearDown()
{
self.searchAPI = nil
OHHTTPStubs.removeAllStubs()
super.tearDown()
}
func normalResponseHeaders() -> [String: String]
{
return self.JSONObjectWithFileName(self.dynamicType.fileHeadersNormal) as? [String: String] ?? [:]
}
func invalidResponseHeaders() -> [String: String]
{
return self.JSONObjectWithFileName(self.dynamicType.fileHeadersInvalid) as? [String: String] ?? [:]
}
func stubRequestsWithResponses(responses: [String: (fileName: String, statusCode: Int32, headers: [String: String]?)])
{
stub({ request in
return responses[request.URL?.path ?? ""] != nil
}, response: { request in
guard let response = responses[request.URL?.path ?? ""] else {
return OHHTTPStubsResponse()
}
guard let fileUrl = self.URLForFileName(response.fileName) else {
return OHHTTPStubsResponse()
}
return OHHTTPStubsResponse(fileURL: fileUrl, statusCode: response.statusCode, headers: response.headers)
})
}
func stubRequestsWithNormalResponse()
{
self.stubRequestsWithResponses([
self.dynamicType.popularMoviesUrlPath: (
fileName: self.dynamicType.fileResponseNormalPopularMovies,
statusCode: 200,
headers: self.normalResponseHeaders()
),
self.dynamicType.searchMoviesUrlPath: (
fileName: self.dynamicType.fileResponseNormalSearchMovies,
statusCode: 200,
headers: self.normalResponseHeaders()
),
])
}
func stubRequestsWithEmptyResponse()
{
self.stubRequestsWithResponses([
self.dynamicType.popularMoviesUrlPath: (
fileName: "",
statusCode: 200,
headers: nil
),
self.dynamicType.searchMoviesUrlPath: (
fileName: "",
statusCode: 200,
headers: nil
),
])
}
func stubRequestsWithInvalidResponse()
{
self.stubRequestsWithResponses([
self.dynamicType.popularMoviesUrlPath: (
fileName: self.dynamicType.fileResponseInvalidPopularMovies,
statusCode: 200,
headers: self.normalResponseHeaders()
),
self.dynamicType.searchMoviesUrlPath: (
fileName: self.dynamicType.fileResponseInvalidSearchMovies,
statusCode: 200,
headers: self.normalResponseHeaders()
),
])
}
func stubRequestsWithInvalidHeadersResponse()
{
self.stubRequestsWithResponses([
self.dynamicType.popularMoviesUrlPath: (
fileName: self.dynamicType.fileResponseNormalPopularMovies,
statusCode: 200,
headers: self.invalidResponseHeaders()
),
self.dynamicType.searchMoviesUrlPath: (
fileName: self.dynamicType.fileResponseNormalSearchMovies,
statusCode: 200,
headers: self.invalidResponseHeaders()
),
])
}
func validateMoviesResponse(moviesResponse: MoviesResponse?, movies originalMovies: [Movie], paginationInfo originalPaginationInfo: PaginationInfo)
{
guard let response = moviesResponse else {
XCTAssertTrue(false)
return
}
switch response {
case .Success(let movies, let paginationInfo):
XCTAssertEqual(movies, originalMovies)
XCTAssertEqual(paginationInfo, originalPaginationInfo)
default: XCTAssertTrue(false)
}
}
func validateErrorResponse(moviesResponse: MoviesResponse?)
{
guard let response = moviesResponse else {
XCTAssertTrue(false)
return
}
switch response {
case .Error: XCTAssertTrue(true)
default: XCTAssertTrue(false)
}
}
func testLoadPopularMoviesNormal()
{
self.stubRequestsWithNormalResponse()
var moviesResponse: MoviesResponse?
let expectation = self.expectationWithDescription("Performing loadPopularMovies request to Search API")
self.searchAPI!.loadPopularMovies(pageNumber:1, pageSize: 20) { response in
moviesResponse = response
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5, handler: nil)
guard let movies = Mapper<Movie>().mapArray(self.JSONObjectWithFileName(self.dynamicType.fileResponseNormalPopularMovies)) else {
XCTAssertTrue(false)
return
}
guard let paginationInfo = Mapper<PaginationInfo>().map(self.normalResponseHeaders()) else {
XCTAssertTrue(false)
return
}
self.validateMoviesResponse(moviesResponse, movies: movies, paginationInfo: paginationInfo)
}
func testSearchMoviesNormal()
{
self.stubRequestsWithNormalResponse()
var moviesResponse: MoviesResponse?
let expectation = self.expectationWithDescription("Performing searchMovies request to Search API")
self.searchAPI!.searchMovies("batman", pageNumber:1, pageSize: 20) { response in
moviesResponse = response
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5, handler: nil)
guard let searchItems = Mapper<SearchResultItem>().mapArray(self.JSONObjectWithFileName(self.dynamicType.fileResponseNormalSearchMovies)) else {
XCTAssertTrue(false)
return
}
guard let paginationInfo = Mapper<PaginationInfo>().map(self.normalResponseHeaders()) else {
XCTAssertTrue(false)
return
}
let movies = searchItems.map { $0.item as? Movie ?? Movie(JSON: [:])! }.filter { $0.isValid() }
self.validateMoviesResponse(moviesResponse, movies: movies, paginationInfo: paginationInfo)
}
func testLoadPopularMoviesEmpty()
{
self.stubRequestsWithEmptyResponse()
var moviesResponse: MoviesResponse?
let expectation = self.expectationWithDescription("Performing loadPopularMovies request to Search API")
self.searchAPI!.loadPopularMovies(pageNumber:1, pageSize: 20) { response in
moviesResponse = response
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5, handler: nil)
self.validateErrorResponse(moviesResponse)
}
func testSearchMoviesEmpty()
{
self.stubRequestsWithEmptyResponse()
var moviesResponse: MoviesResponse?
let expectation = self.expectationWithDescription("Performing searchMovies request to Search API")
self.searchAPI!.searchMovies("batman", pageNumber:1, pageSize: 20) { response in
moviesResponse = response
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5, handler: nil)
self.validateErrorResponse(moviesResponse)
}
func testLoadPopularMoviesInvalid()
{
self.stubRequestsWithInvalidResponse()
var moviesResponse: MoviesResponse?
let expectation = self.expectationWithDescription("Performing loadPopularMovies request to Search API")
self.searchAPI!.loadPopularMovies(pageNumber:1, pageSize: 20) { response in
moviesResponse = response
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5, handler: nil)
self.validateErrorResponse(moviesResponse)
}
func testSearchMoviesInvalid()
{
self.stubRequestsWithInvalidResponse()
var moviesResponse: MoviesResponse?
let expectation = self.expectationWithDescription("Performing searchMovies request to Search API")
self.searchAPI!.searchMovies("batman", pageNumber:1, pageSize: 20) { response in
moviesResponse = response
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5, handler: nil)
self.validateErrorResponse(moviesResponse)
}
func testLoadPopularMoviesInvalidHeaders()
{
self.stubRequestsWithInvalidHeadersResponse()
var moviesResponse: MoviesResponse?
let expectation = self.expectationWithDescription("Performing loadPopularMovies request to Search API")
self.searchAPI!.loadPopularMovies(pageNumber:1, pageSize: 20) { response in
moviesResponse = response
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5, handler: nil)
self.validateErrorResponse(moviesResponse)
}
func testSearchMoviesInvalidHeaders()
{
self.stubRequestsWithInvalidHeadersResponse()
var moviesResponse: MoviesResponse?
let expectation = self.expectationWithDescription("Performing searchMovies request to Search API")
self.searchAPI!.searchMovies("batman", pageNumber:1, pageSize: 20) { response in
moviesResponse = response
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(5, handler: nil)
self.validateErrorResponse(moviesResponse)
}
}
|
mit
|
05f7f6e1ab8593f0bf01e0cb302c5bd2
| 31.529412 | 152 | 0.652993 | 5.35525 | false | false | false | false |
ycfreeman/ReSwift
|
ReSwift/CoreTypes/StoreType.swift
|
2
|
5637
|
//
// StoreType.swift
// ReSwift
//
// Created by Benjamin Encz on 11/28/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import Foundation
/**
Defines the interface of Stores in ReSwift. `Store` is the default implementation of this
interface. Applications have a single store that stores the entire application state.
Stores receive actions and use reducers combined with these actions, to calculate state changes.
Upon every state update a store informs all of its subscribers.
*/
public protocol StoreType {
associatedtype State: StateType
/// Initializes the store with a reducer and an intial state.
init(reducer: @escaping Reducer<State>, state: State?)
/// Initializes the store with a reducer, an initial state and a list of middleware.
/// Middleware is applied in the order in which it is passed into this constructor.
init(reducer: @escaping Reducer<State>, state: State?, middleware: [Middleware])
/// The current state stored in the store.
var state: State! { get }
/**
The main dispatch function that is used by all convenience `dispatch` methods.
This dispatch function can be extended by providing middlewares.
*/
var dispatchFunction: DispatchFunction! { get }
/**
Subscribes the provided subscriber to this store.
Subscribers will receive a call to `newState` whenever the
state in this store changes.
- parameter subscriber: Subscriber that will receive store updates
*/
func subscribe<S: StoreSubscriber>(_ subscriber: S) where S.StoreSubscriberStateType == State
/**
Unsubscribes the provided subscriber. The subscriber will no longer
receive state updates from this store.
- parameter subscriber: Subscriber that will be unsubscribed
*/
func unsubscribe(_ subscriber: AnyStoreSubscriber)
/**
Dispatches an action. This is the simplest way to modify the stores state.
Example of dispatching an action:
```
store.dispatch( CounterAction.IncreaseCounter )
```
- parameter action: The action that is being dispatched to the store
- returns: By default returns the dispatched action, but middlewares can change the
return type, e.g. to return promises
*/
func dispatch(_ action: Action) -> Any
/**
Dispatches an action creator to the store. Action creators are functions that generate
actions. They are called by the store and receive the current state of the application
and a reference to the store as their input.
Based on that input the action creator can either return an action or not. Alternatively
the action creator can also perform an asynchronous operation and dispatch a new action
at the end of it.
Example of an action creator:
```
func deleteNote(noteID: Int) -> ActionCreator {
return { state, store in
// only delete note if editing is enabled
if (state.editingEnabled == true) {
return NoteDataAction.DeleteNote(noteID)
} else {
return nil
}
}
}
```
This action creator can then be dispatched as following:
```
store.dispatch( noteActionCreatore.deleteNote(3) )
```
- returns: By default returns the dispatched action, but middlewares can change the
return type, e.g. to return promises
*/
func dispatch(_ actionCreator: ActionCreator) -> Any
/**
Dispatches an async action creator to the store. An async action creator generates an
action creator asynchronously.
*/
func dispatch(_ asyncActionCreator: AsyncActionCreator)
/**
Dispatches an async action creator to the store. An async action creator generates an
action creator asynchronously. Use this method if you want to wait for the state change
triggered by the asynchronously generated action creator.
This overloaded version of `dispatch` calls the provided `callback` as soon as the
asynchronoously dispatched action has caused a new state calculation.
- Note: If the ActionCreator does not dispatch an action, the callback block will never
be called
*/
func dispatch(_ asyncActionCreator: AsyncActionCreator, callback: DispatchCallback?)
/**
An optional callback that can be passed to the `dispatch` method.
This callback will be called when the dispatched action triggers a new state calculation.
This is useful when you need to wait on a state change, triggered by an action (e.g. wait on
a successful login). However, you should try to use this callback very seldom as it
deviates slighlty from the unidirectional data flow principal.
*/
associatedtype DispatchCallback = (State) -> Void
/**
An ActionCreator is a function that, based on the received state argument, might or might not
create an action.
Example:
```
func deleteNote(noteID: Int) -> ActionCreator {
return { state, store in
// only delete note if editing is enabled
if (state.editingEnabled == true) {
return NoteDataAction.DeleteNote(noteID)
} else {
return nil
}
}
}
```
*/
associatedtype ActionCreator = (_ state: State, _ store: StoreType) -> Action?
/// AsyncActionCreators allow the developer to wait for the completion of an async action.
associatedtype AsyncActionCreator =
(_ state: State, _ store: StoreType,
_ actionCreatorCallback: (ActionCreator) -> Void) -> Void
}
|
mit
|
59a636c9c41f14e11a9acd15ae03e46d
| 34.670886 | 98 | 0.684173 | 5.086643 | false | false | false | false |
belatrix/iOSAllStarsRemake
|
AllStars/AllStars/iPhone/Classes/Event/EventTableViewCell.swift
|
1
|
1877
|
//
// EventTableViewCell.swift
// AllStars
//
// Created by Flavio Franco Tunqui on 7/6/16.
// Copyright © 2016 Belatrix SF. All rights reserved.
//
import UIKit
class EventTableViewCell: UITableViewCell {
@IBOutlet weak var lblTitle : UILabel!
@IBOutlet weak var lblDate : UILabel!
@IBOutlet weak var lblLocation : UILabel!
@IBOutlet weak var lblDescription : UILabel!
@IBOutlet weak var imgEvent : UIImageView!
@IBOutlet weak var containerView : UIView!
var objEvent = Event()
func updateData() -> Void {
self.lblTitle.text = self.objEvent.event_title!
if let datetime = self.objEvent.event_datetime {
self.lblDate.text = OSPDateManager.convertirFecha(datetime, alFormato: "dd MMM yyyy HH:mm", locale: "en_US")
} else {
self.lblDate.text = "No date"
}
if let location = self.objEvent.event_location where location != "" {
self.lblLocation.text = location
} else {
self.lblLocation.text = "---"
}
if let desc = self.objEvent.event_location where desc != "" {
self.lblDescription.text = desc
} else {
self.lblDescription.text = "---"
}
if (self.objEvent.event_image! != "") {
OSPImageDownloaded.descargarImagenEnURL(self.objEvent.event_image!, paraImageView: self.imgEvent, conPlaceHolder: nil) { (correct : Bool, nameImage : String!, image : UIImage!) in
if nameImage == self.objEvent.event_image! {
self.imgEvent.image = image
}
}
} else {
self.imgEvent.image = UIImage(named: "placeholder_general.png")
}
}
}
|
mit
|
e69648c3128a6c56552eb7f2d91987ae
| 30.813559 | 191 | 0.553305 | 4.37296 | false | false | false | false |
TabletopAssistant/DiceKit
|
DiceKit/Dictionary+Functions.swift
|
1
|
3492
|
//
// Dictionary+Functions.swift
// DiceKit
//
// Created by Brentley Jones on 7/19/15.
// Copyright © 2015 Brentley Jones. All rights reserved.
//
import Foundation
extension Dictionary {
func mapValues(@noescape transform: (Key, Value) -> Value) -> [Key:Value] {
var newDictionary: [Key:Value] = [:]
for (key, value) in self {
newDictionary[key] = transform(key, value)
}
return newDictionary
}
/// - Warning: If two keys are mapped to the same key, the last one evaluated will be used. Use conflictTransform variant to provide a different behavior.
func mapKeys(@noescape transform: (Key, Value) -> Key) -> [Key:Value] {
var newDictionary: [Key:Value] = [:]
for (key, value) in self {
let newKey = transform(key, value)
newDictionary[newKey] = value
}
return newDictionary
}
func mapKeys(@noescape conflictTransform: (Key, Value, Value) -> Value, @noescape transform: (Key, Value) -> Key) -> [Key:Value] {
var newDictionary: [Key:Value] = [:]
for (key, var value) in self {
let newKey = transform(key, value)
if let existingValue = newDictionary[newKey] {
value = conflictTransform(newKey, existingValue, value)
}
newDictionary[newKey] = value
}
return newDictionary
}
/// - Warning: If two keys are mapped to the same key, the last one evaluated will be used. Use conflictTransform variant to provide a different behavior.
func map(@noescape transform: (Key, Value) -> (Key, Value)) -> [Key:Value] {
var newDictionary: [Key:Value] = [:]
for (key, value) in self {
let (newKey, newValue) = transform(key, value)
newDictionary[newKey] = newValue
}
return newDictionary
}
func map(@noescape conflictTransform: (Key, Value, Value) -> Value, @noescape transform: (Key, Value) -> (Key, Value)) -> [Key:Value] {
var newDictionary: [Key:Value] = [:]
for (key, value) in self {
var (newKey, newValue) = transform(key, value)
if let existingValue = newDictionary[newKey] {
newValue = conflictTransform(newKey, existingValue, newValue)
}
newDictionary[newKey] = newValue
}
return newDictionary
}
func filterValues(@noescape includeElement: Value -> Bool) -> [Key: Value] {
var newDictionary: [Key: Value] = [:]
for (key, value) in self {
if includeElement(value) {
newDictionary[key] = value
}
}
return newDictionary
}
func filterKeys(@noescape includeElement: Key -> Bool) -> [Key: Value] {
var newDictionary: [Key: Value] = [:]
for (key, value) in self {
if includeElement(key) {
newDictionary[key] = value
}
}
return newDictionary
}
func filter(@noescape includeElement: (Key, Value) -> Bool) -> [Key: Value] {
var newDictionary: [Key: Value] = [:]
for (key, value) in self {
if includeElement(key, value) {
newDictionary[key] = value
}
}
return newDictionary
}
}
|
apache-2.0
|
aca6f1537af3fd2d39bb7ee55e366f63
| 30.45045 | 158 | 0.544257 | 4.667112 | false | false | false | false |
BaiduCloudTeam/PaperInSwift
|
PaperInSwift/CHPaperCollectionViewController.swift
|
1
|
3778
|
//
// CHPaperCollectionViewController.swift
// PaperInSwift
//
// Created by Peter Frank on 15/10/12.
// Copyright © 2015年 Team_ChineseHamburger. All rights reserved.
// Uptown Funk
import UIKit
class CHPaperCollectionViewController:UICollectionViewController {
var count = 0
var header:CHSectionHeader?
func nextViewControllerAtPoint(point:CGPoint) ->UICollectionViewController {
return self
}
//MARK View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.registerClass(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier:"CELL_ID")
self.collectionView?.backgroundColor = UIColor.clearColor()
self.collectionView?.registerNib(UINib(nibName:"CHSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
self.collectionView?.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
self.automaticallyAdjustsScrollViewInsets = false
self.collectionView?.delaysContentTouches = false
self.count = 20
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.collectionView?.decelerationRate = self.classForCoder != CHPaperCollectionViewController.classForCoder() ? UIScrollViewDecelerationRateNormal:UIScrollViewDecelerationRateFast
}
override func prefersStatusBarHidden() -> Bool {
self.navigationController?.setNavigationBarHidden(true, animated: true)
return true
}
//MARK Delegate
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell:UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL_ID", forIndexPath: indexPath)
cell.backgroundColor = UIColor.whiteColor()
cell.layer.cornerRadius = 4
cell.clipsToBounds = true
let backgroundView:UIImageView = UIImageView(image: UIImage(named:"fake-cell"))
cell.backgroundView = backgroundView
return cell
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.count
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout {
let transitionLayout:CHTransitionLayout = CHTransitionLayout(currentLayout: fromLayout, nextLayout:toLayout)
return transitionLayout
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
guard let _ = self.header else {
self.header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header", forIndexPath: indexPath) as? CHSectionHeader
let callback:(NSInteger) -> Void = {
[unowned self]
(arg) -> Void in
self.count = Int(arc4random_uniform(20))+3;
self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forRow:0, inSection:0), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
self.collectionView?.reloadSections(NSIndexSet(index: 0))
}
self.header?.didPageControllerChanged = callback
return self.header!
}
return self.header!
}
}
|
mit
|
9f807fad6c037f05022ea89a90620dc9
| 44.493976 | 213 | 0.717616 | 6.05939 | false | false | false | false |
koehlermichael/focus
|
Blockzilla/Toast.swift
|
1
|
1659
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
class Toast {
private let text: String
init(text: String) {
self.text = text
}
func show() {
guard let window = UIApplication.shared.windows.first else {
return
}
let toast = UIView()
toast.alpha = 0
toast.backgroundColor = UIConstants.colors.toastBackground
toast.layer.cornerRadius = 18
window.addSubview(toast)
let label = UILabel()
label.text = text
label.textColor = UIConstants.colors.toastText
label.font = UIConstants.fonts.toast
label.numberOfLines = 0
toast.addSubview(label)
toast.snp.makeConstraints { make in
make.bottom.equalTo(window).offset(-30)
make.centerX.equalTo(window)
make.leading.greaterThanOrEqualTo(window)
make.trailing.lessThanOrEqualTo(window)
}
label.snp.makeConstraints { make in
make.leading.trailing.equalTo(toast).inset(20)
make.top.bottom.equalTo(toast).inset(10)
}
toast.animateHidden(false, duration: UIConstants.layout.toastAnimationDuration) {
DispatchQueue.main.asyncAfter(deadline: .now() + UIConstants.layout.toastDuration) {
toast.animateHidden(true, duration: UIConstants.layout.toastAnimationDuration) {
toast.removeFromSuperview()
}
}
}
}
}
|
mpl-2.0
|
91013bdb317507f96545899f596294b7
| 30.903846 | 96 | 0.617842 | 4.608333 | false | false | false | false |
azadibogolubov/InterestDestroyer
|
iOS Version/Interest Destroyer/Charts/Classes/Charts/ScatterChartView.swift
|
99
|
2247
|
//
// ScatterChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
/// The ScatterChart. Draws dots, triangles, squares and custom shapes into the chartview.
public class ScatterChartView: BarLineChartViewBase, ScatterChartRendererDelegate
{
public override func initialize()
{
super.initialize()
renderer = ScatterChartRenderer(delegate: self, animator: _animator, viewPortHandler: _viewPortHandler)
_chartXMin = -0.5
}
public override func calcMinMax()
{
super.calcMinMax()
if (_deltaX == 0.0 && _data.yValCount > 0)
{
_deltaX = 1.0
}
_chartXMax += 0.5
_deltaX = CGFloat(abs(_chartXMax - _chartXMin))
}
// MARK: - ScatterChartRendererDelegate
public func scatterChartRendererData(renderer: ScatterChartRenderer) -> ScatterChartData!
{
return _data as! ScatterChartData!
}
public func scatterChartRenderer(renderer: ScatterChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!
{
return getTransformer(which)
}
public func scatterChartDefaultRendererValueFormatter(renderer: ScatterChartRenderer) -> NSNumberFormatter!
{
return self._defaultValueFormatter
}
public func scatterChartRendererChartYMax(renderer: ScatterChartRenderer) -> Double
{
return self.chartYMax
}
public func scatterChartRendererChartYMin(renderer: ScatterChartRenderer) -> Double
{
return self.chartYMin
}
public func scatterChartRendererChartXMax(renderer: ScatterChartRenderer) -> Double
{
return self.chartXMax
}
public func scatterChartRendererChartXMin(renderer: ScatterChartRenderer) -> Double
{
return self.chartXMin
}
public func scatterChartRendererMaxVisibleValueCount(renderer: ScatterChartRenderer) -> Int
{
return self.maxVisibleValueCount
}
}
|
apache-2.0
|
9edbb8f41f228b7d933a0c4465cf5e40
| 26.414634 | 142 | 0.676012 | 5.440678 | false | false | false | false |
ta2yak/loqui
|
loqui/ViewControllers/ChatViewController.swift
|
1
|
10058
|
//
// ChatViewController.swift
// loqui
//
// Created by Kawasaki Tatsuya on 2017/08/13.
// Copyright © 2017年 Kawasaki Tatsuya. All rights reserved.
//
import UIKit
import MaterialComponents
import Cartography
import RxSwift
import RxCocoa
import JSQMessagesViewController
import Hokusai
import FCAlertView
class ChatViewController: JSQMessagesViewController {
let vm = ChatViewModel()
let disposeBag = DisposeBag()
let activityIndicator = MDCActivityIndicator()
override func viewDidLoad() {
super.viewDidLoad()
self.senderId = vm.currentUser.value.uid
self.senderDisplayName = vm.currentUser.value.name
self.inputToolbar.contentView.leftBarButtonItem = nil
self.topContentAdditionalInset = 60
setupNavigationBar()
// Loading
activityIndicator.radius = 40
view.addSubview(activityIndicator)
constrain(view, activityIndicator) { view, activityIndicator in
activityIndicator.width == view.width / 3
activityIndicator.height == view.width / 3
activityIndicator.center == view.center
}
vm.isLoading.asObservable().subscribe(onNext: { (isLoading) in
isLoading ? self.activityIndicator.startAnimating() : self.activityIndicator.stopAnimating()
}, onError: nil, onCompleted: nil, onDisposed: nil)
.addDisposableTo(disposeBag)
vm.successMessage.asObservable().subscribe(onNext: { (message) in
if (!message.isEmpty) {
let alert = FCAlertView()
alert.delegate = self
alert.blurBackground = true
alert.makeAlertTypeSuccess()
alert.showAlert(inView: self,
withTitle:message.title,
withSubtitle:message.message,
withCustomImage:nil,
withDoneButtonTitle:"OK",
andButtons:[])
}
}, onError: nil, onCompleted: nil, onDisposed: nil)
.addDisposableTo(disposeBag)
vm.errorMessage.asObservable().subscribe(onNext: { (message) in
if (!message.isEmpty) {
let alert = FCAlertView()
alert.delegate = self
alert.blurBackground = true
alert.makeAlertTypeCaution()
alert.showAlert(inView: self,
withTitle:message.title,
withSubtitle:message.message,
withCustomImage:nil,
withDoneButtonTitle:"OK",
andButtons:[])
}
}, onError: nil, onCompleted: nil, onDisposed: nil)
.addDisposableTo(disposeBag)
vm.messages.asObservable().bind { (messages) in
// メッセージ一覧に変更があれば画面を更新
self.collectionView.reloadData()
}
vm.setup()
}
func setupNavigationBar() {
// ナビゲーションバーの制御
let navigationbar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 60))
self.view.addSubview(navigationbar)
navigationbar.setBackgroundImage(UIImage.colorImage(color: UIColor.white,
size: CGSize(width: UIScreen.main.bounds.size.width,
height: 60 )),
for: UIBarPosition.any,
barMetrics: UIBarMetrics.default)
navigationbar.shadowImage = UIImage()
let titleAttributes = [NSForegroundColorAttributeName: UIColor.mainTextColor()] as Dictionary!
navigationbar.titleTextAttributes = titleAttributes
let navigationItem = UINavigationItem(title: "質問しましょう")
let leftBarButton = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(back))
let leftBarButtonAttributes = [NSFontAttributeName: UIFont.icon(from: .FontAwesome, ofSize: 22.0),
NSForegroundColorAttributeName: UIColor.mainTextColor()] as Dictionary!
leftBarButton.setTitleTextAttributes(leftBarButtonAttributes, for: UIControlState())
leftBarButton.title = String.fontAwesomeIcon("close")
navigationItem.leftBarButtonItem = leftBarButton
let rightBarButton = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(actions))
let rightBarButtonAttributes = [NSFontAttributeName: UIFont.icon(from: .FontAwesome, ofSize: 22.0),
NSForegroundColorAttributeName: UIColor.mainTextColor()] as Dictionary!
rightBarButton.setTitleTextAttributes(rightBarButtonAttributes, for: UIControlState())
rightBarButton.title = String.fontAwesomeIcon("cog")
navigationItem.rightBarButtonItem = rightBarButton
navigationbar.setItems([navigationItem], animated: true)
}
}
extension ChatViewController {
func back(){
self.dismiss(animated: true, completion: nil)
}
func actions(){
let hokusai = Hokusai()
hokusai.addButton("ブロックする", target: self, selector: #selector(blockUser))
hokusai.addButton("通報する", target: self, selector: #selector(alertUser))
hokusai.cancelButtonTitle = "キャンセル"
hokusai.colorScheme = HOKColorScheme.tsubaki
hokusai.show()
}
func blockUser(){
vm.block().always {
self.vm.successMessage.value = AlertMessage(title:"ブロックしました", message: "相手にブロックを通知しました")
self.dismiss(animated: true, completion: nil)
}
}
func alertUser(){
vm.alert().always {
self.vm.successMessage.value = AlertMessage(title:"通報しました", message: "管理者が調査させていただきます")
}
}
}
extension ChatViewController {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell
if let textView = cell.textView {
textView.textColor = UIColor.mainTextColor()
}
return cell
}
//送信ボタンが押された時の挙動
override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
let message = JSQMessage(senderId: senderId, displayName: senderDisplayName, text: text)
vm.postMessage(message: message!)
finishSendingMessage()
}
//添付ファイルボタンが押された時の挙動
override func didPressAccessoryButton(_ sender: UIButton!) {
}
//各送信者の表示について
override func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath!) -> NSAttributedString! {
let messages = vm.messages.value
let authorId = messages[indexPath.row].senderId
var senderUsername = "System"
vm.usersInRoom.value.forEach { (profile) in
if (profile.uid == authorId) {
senderUsername = profile.name
}
}
return NSAttributedString(string: senderUsername)
}
//各メッセージの高さ
override func collectionView(_ collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAt indexPath: IndexPath!) -> CGFloat {
return 15
}
//各送信者の表示に画像を使うか
override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
let message = vm.messages.value[indexPath.row]
return JSQMessagesAvatarImageFactory.avatarImage(with: vm.userAvatarsInRoom.value[message.senderId],
diameter: 60)
}
//各メッセージの背景を設定
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! {
let bubbleFactory = JSQMessagesBubbleImageFactory()
let messages = vm.messages.value
let message = messages[indexPath.row]
if vm.currentUser.value.uid == message.senderId {
return bubbleFactory?.outgoingMessagesBubbleImage(with: UIColor.outgoingChatColor())
} else {
return bubbleFactory?.incomingMessagesBubbleImage(with: UIColor.incomingChatColor())
}
}
// メッセージの総数を取得
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return vm.messages.value.count
}
// メッセージの内容参照場所の設定
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
let messages = vm.messages.value
let message = messages[indexPath.row]
return message
}
}
extension ChatViewController: FCAlertViewDelegate {
func fcAlertViewDismissed(_ alertView: FCAlertView!) {
self.vm.successMessage.value = AlertMessage.emptyObject()
self.vm.errorMessage.value = AlertMessage.emptyObject()
}
}
|
mit
|
981924adcdc884b57a426b5c5ae028f1
| 36.714844 | 214 | 0.622683 | 5.507701 | false | false | false | false |
rsaenzi/MyCurrencyConverterApp
|
MyCurrencyConverterApp/MyCurrencyConverterApp/App/DataModels/ApiContainer/Response/ResponseGetExchangeRates.swift
|
1
|
514
|
//
// ResponseGetExchangeRates.swift
// MyCurrencyConverterApp
//
// Created by Rigoberto Sáenz Imbacuán on 8/7/16.
// Copyright © 2016 Rigoberto Sáenz Imbacuán [https://www.linkedin.com/in/rsaenzi]. All rights reserved.
//
struct ResponseGetExchangeRates {
// Main response
var responseCode = eResponseCodeGetExchangeRates.UnknownError_AP1
var responseMessage = String()
// Content
var base = String()
var date = String()
var rates = [eCurrencyCode: Float]()
}
|
mit
|
9daba1c42d581b8e30f0c91577cf6cba
| 25.842105 | 105 | 0.691552 | 4.138211 | false | false | false | false |
mshhmzh/firefox-ios
|
SyncTests/MockSyncServerTests.swift
|
5
|
9210
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import Storage
@testable import Sync
import UIKit
import XCTest
private class MockBackoffStorage: BackoffStorage {
var serverBackoffUntilLocalTimestamp: Timestamp?
func clearServerBackoff() {
serverBackoffUntilLocalTimestamp = nil
}
func isInBackoff(now: Timestamp) -> Timestamp? {
return nil
}
}
class MockSyncServerTests: XCTestCase {
var server: MockSyncServer!
var client: Sync15StorageClient!
override func setUp() {
server = MockSyncServer(username: "1234567")
server.start()
client = getClient(server)
}
private func getClient(server: MockSyncServer) -> Sync15StorageClient? {
guard let url = server.baseURL.asURL else {
XCTFail("Couldn't get URL.")
return nil
}
let authorizer: Authorizer = identity
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
print("URL: \(url)")
return Sync15StorageClient(serverURI: url, authorizer: authorizer, workQueue: queue, resultQueue: queue, backoff: MockBackoffStorage())
}
func testDeleteSpec() {
// Deletion of a collection path itself, versus trailing slash, sets the right flags.
let all = SyncDeleteRequestSpec.fromPath("/1.5/123456/storage/bookmarks", withQuery: [:])!
XCTAssertTrue(all.wholeCollection)
XCTAssertNil(all.ids)
let some = SyncDeleteRequestSpec.fromPath("/1.5/123456/storage/bookmarks", withQuery: ["ids": "123456,abcdef"])!
XCTAssertFalse(some.wholeCollection)
XCTAssertEqual(["123456", "abcdef"], some.ids!)
let one = SyncDeleteRequestSpec.fromPath("/1.5/123456/storage/bookmarks/123456", withQuery: [:])!
XCTAssertFalse(one.wholeCollection)
XCTAssertNil(one.ids)
}
func testInfoCollections() {
server.storeRecords([MockSyncServer.makeValidEnvelope(Bytes.generateGUID(), modified: 0)], inCollection: "bookmarks", now: 1326251111000)
server.storeRecords([], inCollection: "tabs", now: 1326252222500)
server.storeRecords([MockSyncServer.makeValidEnvelope(Bytes.generateGUID(), modified: 0)], inCollection: "bookmarks", now: 1326252222000)
server.storeRecords([MockSyncServer.makeValidEnvelope(Bytes.generateGUID(), modified: 0)], inCollection: "clients", now: 1326253333000)
let expectation = self.expectationWithDescription("Waiting for result.")
let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
client.getInfoCollections().upon { result in
XCTAssertNotNil(result.successValue)
guard let response = result.successValue else {
expectation.fulfill()
return
}
let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
// JSON contents.
XCTAssertEqual(response.value.collectionNames().sort(), ["bookmarks", "clients", "tabs"])
XCTAssertEqual(response.value.modified("bookmarks"), 1326252222000)
XCTAssertEqual(response.value.modified("clients"), 1326253333000)
// X-Weave-Timestamp.
XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds)
XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after)
// X-Weave-Records.
XCTAssertEqual(response.metadata.records, 3) // bookmarks, clients, tabs.
// X-Last-Modified, max of all collection modified timestamps.
XCTAssertEqual(response.metadata.lastModifiedMilliseconds, 1326253333000)
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
}
func testGet() {
server.storeRecords([MockSyncServer.makeValidEnvelope("guid", modified: 0)], inCollection: "bookmarks", now: 1326251111000)
let collectionClient = client.clientForCollection("bookmarks", encrypter: getEncrypter())
let expectation = self.expectationWithDescription("Waiting for result.")
let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
collectionClient.get("guid").upon { result in
XCTAssertNotNil(result.successValue)
guard let response = result.successValue else {
expectation.fulfill()
return
}
let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
// JSON contents.
XCTAssertEqual(response.value.id, "guid")
XCTAssertEqual(response.value.modified, 1326251111000)
// X-Weave-Timestamp.
XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds)
XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after)
// X-Weave-Records.
XCTAssertNil(response.metadata.records)
// X-Last-Modified.
XCTAssertEqual(response.metadata.lastModifiedMilliseconds, 1326251111000)
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
// And now a missing record, which should produce a 404.
collectionClient.get("missing").upon { result in
XCTAssertNotNil(result.failureValue)
guard let response = result.failureValue else {
expectation.fulfill()
return
}
XCTAssertNotNil(response as? NotFound<NSHTTPURLResponse>)
}
}
func testWipeStorage() {
server.storeRecords([MockSyncServer.makeValidEnvelope("a", modified: 0)], inCollection: "bookmarks", now: 1326251111000)
server.storeRecords([MockSyncServer.makeValidEnvelope("b", modified: 0)], inCollection: "bookmarks", now: 1326252222000)
server.storeRecords([MockSyncServer.makeValidEnvelope("c", modified: 0)], inCollection: "clients", now: 1326253333000)
server.storeRecords([], inCollection: "tabs")
// For now, only testing wiping the storage root, which is the only thing we use in practice.
let expectation = self.expectationWithDescription("Waiting for result.")
let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
client.wipeStorage().upon { result in
XCTAssertNotNil(result.successValue)
guard let response = result.successValue else {
expectation.fulfill()
return
}
let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
// JSON contents: should be the empty object.
XCTAssertEqual(response.value.toString(), "{}")
// X-Weave-Timestamp.
XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds)
XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after)
// X-Weave-Records.
XCTAssertNil(response.metadata.records)
// X-Last-Modified.
XCTAssertNil(response.metadata.lastModifiedMilliseconds)
// And we really wiped the data.
XCTAssertTrue(self.server.collections.isEmpty)
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
}
func testPut() {
// For now, only test uploading crypto/keys. There's nothing special about this PUT, however.
let expectation = self.expectationWithDescription("Waiting for result.")
let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
client.uploadCryptoKeys(Keys.random(), withSyncKeyBundle: KeyBundle.random(), ifUnmodifiedSince: nil).upon { result in
XCTAssertNotNil(result.successValue)
guard let response = result.successValue else {
expectation.fulfill()
return
}
let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(NSDate.now()))!
// Contents: should be just the record timestamp.
XCTAssertLessThanOrEqual(before, response.value)
XCTAssertLessThanOrEqual(response.value, after)
// X-Weave-Timestamp.
XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds)
XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after)
// X-Weave-Records.
XCTAssertNil(response.metadata.records)
// X-Last-Modified.
XCTAssertNil(response.metadata.lastModifiedMilliseconds)
// And we really uploaded the record.
XCTAssertNotNil(self.server.collections["crypto"])
XCTAssertNotNil(self.server.collections["crypto"]?.records["keys"])
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
}
}
|
mpl-2.0
|
1bc4094c4eb0e87e0fc631310d86e584
| 43.926829 | 145 | 0.668295 | 5.575061 | false | true | false | false |
karstengresch/rw_studies
|
Countidon/Countidon/PushButtonView.swift
|
1
|
1531
|
//
// PushButtonView.swift
// Countidon
//
// Created by Karsten Gresch on 18.09.15.
// Copyright © 2015 Closure One. All rights reserved.
//
import UIKit
@IBDesignable
class PushButtonView: UIButton {
@IBInspectable var fillColor: UIColor = UIColor.red
@IBInspectable var isAddButton: Bool = true
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override func draw(_ rect: CGRect) {
let path = UIBezierPath(ovalIn: rect)
fillColor.setFill()
path.fill()
// line thickness
let plusHeight: CGFloat = 0.7
// line length
let plusWidth: CGFloat = min(bounds.width, bounds.height) * 0.74
let plusPath = UIBezierPath()
plusPath.lineWidth = plusHeight
plusPath.move(to: CGPoint(x: bounds.width/2 - plusWidth/2 + 0.5, y: bounds.height/2 + 0.5))
plusPath.addLine(to: CGPoint(x: bounds.width/2 + plusWidth/2 + 0.5, y: bounds.height/2 + 0.5))
if isAddButton {
//move to the start of the vertical stroke
plusPath.move(to: CGPoint(
x:bounds.width/2 + 0.5,
y:bounds.height/2 - plusWidth/2 + 0.5))
//add the end point to the vertical stroke
plusPath.addLine(to: CGPoint(
x:bounds.width/2 + 0.5,
y:bounds.height/2 + plusWidth/2 + 0.5))
}
UIColor.white.setStroke()
plusPath.stroke()
}
}
|
unlicense
|
d5aa9db78ceb1948fa8ab1c47b642e04
| 24.081967 | 98 | 0.630065 | 3.75 | false | false | false | false |
mnvr/Soundtrack
|
Soundtrack/AACShoutcastStreamPlayer.swift
|
1
|
4973
|
//
// Copyright (c) 2017 Manav Rathi
//
// Apache License, v2.0
//
import Foundation
import AVFoundation
import AudioToolbox
/// Play an AAC SHOUTcast stream.
///
/// An AAC stream has the MIME type "audio/aac", and the data consists
/// of ADTS (Audio Data Transport Stream) frames.
class AACShoutcastStreamPlayer: StreamPlayer, ShoutcastStreamDelegate, ADTSParserDelegate {
let url: URL
let delegateQueue: DispatchQueue
weak var delegate: StreamPlayerDelegate?
private let engine = AVAudioEngine()
private let playerNode = AVAudioPlayerNode()
private var stream: ShoutcastStream?
private var adtsParser: ADTSParser?
private var activeVolumeRamp: VolumeRamp?
/// - Parameter url: The URL of the SHOUTcast stream server that
/// emits an AAC audio stream.
///
/// - Parameter delegateQueue: A serial queue on which the delegate
/// methods will be invoked.
init(url: URL, delegateQueue: DispatchQueue) {
self.url = url
self.delegateQueue = delegateQueue
engine.attach(playerNode)
engine.connect(playerNode, to: engine.mainMixerNode, format: nil)
engine.prepare()
}
func play() {
connect()
}
func pause() {
fadeOut { [weak self] in
self?.pauseImmediately()
}
}
private func pauseImmediately() {
stopPlayback()
disconnect()
}
private func connect() {
adtsParser = ADTSParser(pcmFormat: playerNode.outputFormat(forBus: 0))
adtsParser?.delegate = self
stream = ShoutcastStream(url: url, mimeType: "audio/aac", delegate: self, delegateQueue: delegateQueue)
}
private func disconnect() {
stream = nil
adtsParser = nil
}
private func startPlayback() throws {
try engine.start()
playerNode.volume = 0
playerNode.play()
fadeIn()
delegate?.streamPlayerDidStartPlayback(self)
}
private func stopPlayback() {
playerNode.stop()
engine.stop()
delegate?.streamPlayerDidStopPlayback(self)
}
func shoutcastStreamDidConnect(_ stream: ShoutcastStream) {
do {
try startPlayback()
} catch {
disconnect()
return log.warning("Could not start audio playback: \(error)")
}
}
func shoutcastStreamDidDisconnect(_ stream: ShoutcastStream) {
pause()
}
func shoutcastStream(_ stream: ShoutcastStream, gotNewTitle title: String) {
delegate?.streamPlayer(self, didChangeSong: title)
}
func shoutcastStream(_ stream: ShoutcastStream, gotData data: Data) {
adtsParser!.parse(data)
}
func adtsParserDidEncounterError(_ adtsParser: ADTSParser) {
pauseImmediately()
}
func adtsParser(_ adtsParser: ADTSParser, didParsePCMBuffer buffer: AVAudioPCMBuffer) {
playerNode.scheduleBuffer(buffer)
}
private func fadeIn() {
ramp(toVolume: 1, duration: 1)
}
private func fadeOut(completionHandler: @escaping () -> Void) {
ramp(toVolume: 0, duration: 0.25, completionHandler: completionHandler)
}
private func ramp(toVolume: Double, duration: Double, completionHandler: (() -> Void)? = nil) {
activeVolumeRamp = VolumeRamp(playerNode: playerNode, toVolume: toVolume, duration: duration, queue: delegateQueue) { [weak self] in
self?.activeVolumeRamp = nil
if let handler = completionHandler {
handler()
}
}
}
}
private class VolumeRamp {
let playerNode: AVAudioPlayerNode
var pendingSteps = 10
let duration: Double
let timeDelta: Double
let volumeDelta: Double
let queue: DispatchQueue
let completionHandler: () -> Void
init(playerNode: AVAudioPlayerNode, toVolume: Double, duration: Double, queue: DispatchQueue, completionHandler: @escaping () -> Void) {
self.playerNode = playerNode
self.duration = duration
timeDelta = duration / Double(pendingSteps)
volumeDelta = (toVolume - Double(playerNode.volume)) / Double(pendingSteps)
self.queue = queue
self.completionHandler = completionHandler
ramp()
}
private func ramp() {
if pendingSteps > 0 {
let nextVolume = Double(playerNode.volume) + volumeDelta
playerNode.volume = Float(clamp(nextVolume, between: 0, and: 1))
pendingSteps -= 1
queue.asyncAfter(deadline: DispatchTime.now() + timeDelta) { [weak self] in
self?.ramp()
}
} else {
completionHandler()
}
}
private func clamp(_ x: Double, between a: Double, and b: Double) -> Double {
let min_x = min(a, b)
let max_x = max(a, b)
if x < min_x {
return min_x
}
if x > max_x {
return max_x
}
return x
}
}
|
apache-2.0
|
964e770f92559b05737e253682f4f5ea
| 26.174863 | 140 | 0.620752 | 4.456093 | false | false | false | false |
tripleCC/GanHuoCode
|
GanHuo/Util/TPCUMManager.swift
|
1
|
1769
|
//
// TPCUMManager.swift
// WKCC
//
// Created by tripleCC on 15/12/2.
// Copyright © 2015年 tripleCC. All rights reserved.
//
import Foundation
let UMAPPKEY = "565c060c67e58e9a00003d3c"
enum TPCUMEvent: String {
case TechinicalNoMoreData = "techinical_nomoredata"
case TechnicalSet = "technical_set"
case AboutMeJianShu = "aboutme_jianshu"
case LoadDataCountCount = "loaddatacount_count"
case ShowCategoryCategory = "showcategory_category"
case ContentRuleRule = "contentrule_rule"
case ShareCountCount = "sharecount_count"
case ImageAlphaAlpha = "imagealpha_alpha"
}
class TPCUMManager {
class func start() {
var v = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
#if (arch(i386) || arch(x86_64)) && os(iOS)
v += "_sim"
#else
#if GanHuoDev
v += "_dev"
#endif
#endif
MobClick.setAppVersion(v)
MobClick.setLogEnabled(true)
MobClick.startWithAppkey(UMAPPKEY, reportPolicy: BATCH, channelId: nil)
}
class func beginLogPageView(name: String) {
MobClick.beginLogPageView(name)
}
class func endLogPageView(name: String) {
MobClick.endLogPageView(name)
}
class func event(event: TPCUMEvent, attributes: [String : String]? = nil, counter: Int? = nil) {
if counter == nil && attributes != nil {
MobClick.event(event.rawValue, attributes: attributes)
} else if counter == nil && attributes == nil {
MobClick.event(event.rawValue)
} else if counter != nil && attributes != nil {
MobClick.event(event.rawValue, attributes: attributes!, counter: Int32(counter!))
}
}
}
|
mit
|
d3b2f0721bb2a6e20a071ce8f372df6e
| 30.553571 | 100 | 0.633635 | 3.822511 | false | false | false | false |
natecook1000/swift
|
stdlib/public/core/Reverse.swift
|
2
|
9984
|
//===--- Reverse.swift - Sequence and collection reversal -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension MutableCollection where Self: BidirectionalCollection {
/// Reverses the elements of the collection in place.
///
/// The following example reverses the elements of an array of characters:
///
/// var characters: [Character] = ["C", "a", "f", "é"]
/// characters.reverse()
/// print(characters)
/// // Prints "["é", "f", "a", "C"]
///
/// - Complexity: O(*n*), where *n* is the number of elements in the
/// collection.
@inlinable // protocol-only
public mutating func reverse() {
if isEmpty { return }
var f = startIndex
var l = index(before: endIndex)
while f < l {
swapAt(f, l)
formIndex(after: &f)
formIndex(before: &l)
}
}
}
/// A collection that presents the elements of its base collection
/// in reverse order.
///
/// - Note: This type is the result of `x.reversed()` where `x` is a
/// collection having bidirectional indices.
///
/// The `reversed()` method is always lazy when applied to a collection
/// with bidirectional indices, but does not implicitly confer
/// laziness on algorithms applied to its result. In other words, for
/// ordinary collections `c` having bidirectional indices:
///
/// * `c.reversed()` does not create new storage
/// * `c.reversed().map(f)` maps eagerly and returns a new array
/// * `c.lazy.reversed().map(f)` maps lazily and returns a `LazyMapCollection`
@_fixed_layout
public struct ReversedCollection<Base: BidirectionalCollection> {
public let _base: Base
/// Creates an instance that presents the elements of `base` in
/// reverse order.
///
/// - Complexity: O(1)
@inlinable
internal init(_base: Base) {
self._base = _base
}
}
extension ReversedCollection {
// An iterator that can be much faster than the iterator of a reversed slice.
@_fixed_layout
public struct Iterator {
@usableFromInline
internal let _base: Base
@usableFromInline
internal var _position: Base.Index
@inlinable
@inline(__always)
/// Creates an iterator over the given collection.
public /// @testable
init(_base: Base) {
self._base = _base
self._position = _base.endIndex
}
}
}
extension ReversedCollection.Iterator: IteratorProtocol, Sequence {
public typealias Element = Base.Element
@inlinable
@inline(__always)
public mutating func next() -> Element? {
guard _fastPath(_position != _base.startIndex) else { return nil }
_base.formIndex(before: &_position)
return _base[_position]
}
}
extension ReversedCollection: Sequence {
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Element = Base.Element
@inlinable
@inline(__always)
public func makeIterator() -> Iterator {
return Iterator(_base: _base)
}
}
extension ReversedCollection {
/// An index that traverses the same positions as an underlying index,
/// with inverted traversal direction.
@_fixed_layout
public struct Index {
/// The position after this position in the underlying collection.
///
/// To find the position that corresponds with this index in the original,
/// underlying collection, use that collection's `index(before:)` method
/// with the `base` property.
///
/// The following example declares a function that returns the index of the
/// last even number in the passed array, if one is found. First, the
/// function finds the position of the last even number as a `ReversedIndex`
/// in a reversed view of the array of numbers. Next, the function calls the
/// array's `index(before:)` method to return the correct position in the
/// passed array.
///
/// func indexOfLastEven(_ numbers: [Int]) -> Int? {
/// let reversedNumbers = numbers.reversed()
/// guard let i = reversedNumbers.firstIndex(where: { $0 % 2 == 0 })
/// else { return nil }
///
/// return numbers.index(before: i.base)
/// }
///
/// let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51]
/// if let lastEven = indexOfLastEven(numbers) {
/// print("Last even number: \(numbers[lastEven])")
/// }
/// // Prints "Last even number: 40"
public let base: Base.Index
/// Creates a new index into a reversed collection for the position before
/// the specified index.
///
/// When you create an index into a reversed collection using `base`, an
/// index from the underlying collection, the resulting index is the
/// position of the element *before* the element referenced by `base`. The
/// following example creates a new `ReversedIndex` from the index of the
/// `"a"` character in a string's character view.
///
/// let name = "Horatio"
/// let aIndex = name.firstIndex(of: "a")!
/// // name[aIndex] == "a"
///
/// let reversedName = name.reversed()
/// let i = ReversedIndex<String>(aIndex)
/// // reversedName[i] == "r"
///
/// The element at the position created using `ReversedIndex<...>(aIndex)` is
/// `"r"`, the character before `"a"` in the `name` string.
///
/// - Parameter base: The position after the element to create an index for.
@inlinable
public init(_ base: Base.Index) {
self.base = base
}
}
}
extension ReversedCollection.Index: Comparable {
@inlinable
public static func == (
lhs: ReversedCollection<Base>.Index,
rhs: ReversedCollection<Base>.Index
) -> Bool {
// Note ReversedIndex has inverted logic compared to base Base.Index
return lhs.base == rhs.base
}
@inlinable
public static func < (
lhs: ReversedCollection<Base>.Index,
rhs: ReversedCollection<Base>.Index
) -> Bool {
// Note ReversedIndex has inverted logic compared to base Base.Index
return lhs.base > rhs.base
}
}
extension ReversedCollection.Index: Hashable where Base.Index: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(base)
}
}
extension ReversedCollection: BidirectionalCollection {
@inlinable
public var startIndex: Index {
return Index(_base.endIndex)
}
@inlinable
public var endIndex: Index {
return Index(_base.startIndex)
}
@inlinable
public func index(after i: Index) -> Index {
return Index(_base.index(before: i.base))
}
@inlinable
public func index(before i: Index) -> Index {
return Index(_base.index(after: i.base))
}
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
return Index(_base.index(i.base, offsetBy: -n))
}
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: `-n` can trap on Int.min.
return _base.index(i.base, offsetBy: -n, limitedBy: limit.base)
.map(Index.init)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return _base.distance(from: end.base, to: start.base)
}
@inlinable
public subscript(position: Index) -> Element {
return _base[_base.index(before: position.base)]
}
}
extension ReversedCollection: RandomAccessCollection where Base: RandomAccessCollection { }
extension ReversedCollection {
/// Reversing a reversed collection returns the original collection.
///
/// - Complexity: O(1)
@inlinable
@available(swift, introduced: 4.2)
public func reversed() -> Base {
return _base
}
}
extension BidirectionalCollection {
/// Returns a view presenting the elements of the collection in reverse
/// order.
///
/// You can reverse a collection without allocating new space for its
/// elements by calling this `reversed()` method. A `ReversedCollection`
/// instance wraps an underlying collection and provides access to its
/// elements in reverse order. This example prints the characters of a
/// string in reverse order:
///
/// let word = "Backwards"
/// for char in word.reversed() {
/// print(char, terminator: "")
/// }
/// // Prints "sdrawkcaB"
///
/// If you need a reversed collection of the same type, you may be able to
/// use the collection's sequence-based or collection-based initializer. For
/// example, to get the reversed version of a string, reverse its
/// characters and initialize a new `String` instance from the result.
///
/// let reversedWord = String(word.reversed())
/// print(reversedWord)
/// // Prints "sdrawkcaB"
///
/// - Complexity: O(1)
@inlinable
public func reversed() -> ReversedCollection<Self> {
return ReversedCollection(_base: self)
}
}
extension LazyCollectionProtocol
where
Self: BidirectionalCollection,
Elements: BidirectionalCollection {
/// Returns the elements of the collection in reverse order.
///
/// - Complexity: O(1)
@inlinable
public func reversed() -> LazyCollection<ReversedCollection<Elements>> {
return ReversedCollection(_base: elements).lazy
}
}
|
apache-2.0
|
94b5d2c978f007b9a787ae9080c6efcd
| 31.304207 | 91 | 0.649269 | 4.273116 | false | false | false | false |
mpangburn/RayTracer
|
RayTracer/View Controllers/SettingsTableViewController.swift
|
1
|
19899
|
//
// SettingsTableViewController.swift
// RayTracer
//
// Created by Michael Pangburn on 7/9/17.
// Copyright © 2017 Michael Pangburn. All rights reserved.
//
import UIKit
import CoreData
final class SettingsTableViewController: ExpandableCellTableViewController {
let tracer = RayTracer.shared
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("Settings", comment: "The title text for the settings screen")
tableView.register(EyePointTableViewCell.nib(), forCellReuseIdentifier: EyePointTableViewCell.className)
tableView.register(PointTableViewCell.nib(), forCellReuseIdentifier: PointTableViewCell.className)
tableView.register(ColorTableViewCell.nib(), forCellReuseIdentifier: ColorTableViewCell.className)
tableView.register(SegmentedControlTableViewCell.nib(), forCellReuseIdentifier: SegmentedControlTableViewCell.className)
tableView.register(FrameViewTableViewCell.nib(), forCellReuseIdentifier: FrameViewTableViewCell.className)
tableView.register(FrameSizeTableViewCell.nib(), forCellReuseIdentifier: FrameSizeTableViewCell.className)
tableView.register(SingleButtonTableViewCell.nib(), forCellReuseIdentifier: SingleButtonTableViewCell.className)
tableView.estimatedRowHeight = 144
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UserDefaults.standard.rayTracerSettings = tracer.settings
}
fileprivate enum Section: Int {
case eyePoint
case light
case ambience
case background
case frame
case resetSettings
case resetSpheres
static let count = 7
}
private enum LightRow: Int {
case position
case color
case intensity
static let count = 3
}
fileprivate enum FrameRow: Int {
case aspectRatio
case view
case size
static let count = 3
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return Section.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch Section(rawValue: section)! {
case .eyePoint:
return NSLocalizedString("EYE POINT", comment: "The title of the section for the scene's viewpoint setting")
case .light:
return NSLocalizedString("LIGHT", comment: "The title of the section for the scene's light setting")
case .ambience:
return NSLocalizedString("AMBIENCE", comment: "The title of the section for the scene's ambient color setting")
case .background:
return NSLocalizedString("BACKGROUND", comment: "The title of the section for the scene's background color setting")
case .frame:
return NSLocalizedString("FRAME", comment: "The title of the section for the scene's frame setting")
case .resetSettings, .resetSpheres:
return nil
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .light:
return LightRow.count
case .frame:
return FrameRow.count
default:
return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch Section(rawValue: indexPath.section)! {
case .eyePoint:
let cell = tableView.dequeueReusableCell(withIdentifier: EyePointTableViewCell.className, for: indexPath) as! EyePointTableViewCell
cell.zCoordinate = tracer.settings.eyePoint.z
cell.delegate = self
return cell
case .light:
switch LightRow(rawValue: indexPath.row)! {
case .position:
let cell = tableView.dequeueReusableCell(withIdentifier: PointTableViewCell.className, for: indexPath) as! PointTableViewCell
cell.point = tracer.settings.light.position
cell.delegate = self
return cell
case .color:
let cell = tableView.dequeueReusableCell(withIdentifier: ColorTableViewCell.className, for: indexPath) as! ColorTableViewCell
cell.color = tracer.settings.light.color
cell.delegate = self
return cell
case .intensity:
let cell = tableView.dequeueReusableCell(withIdentifier: SegmentedControlTableViewCell.className, for: indexPath) as! SegmentedControlTableViewCell
cell.valueType = .intensity
cell.intensity = tracer.settings.light.intensity
cell.delegate = self
return cell
}
case .ambience:
let cell = tableView.dequeueReusableCell(withIdentifier: ColorTableViewCell.className, for: indexPath) as! ColorTableViewCell
cell.color = tracer.settings.ambience
cell.delegate = self
return cell
case .background:
let cell = tableView.dequeueReusableCell(withIdentifier: ColorTableViewCell.className, for: indexPath) as! ColorTableViewCell
cell.color = tracer.settings.backgroundColor
cell.delegate = self
return cell
case .frame:
switch FrameRow(rawValue: indexPath.row)! {
case .aspectRatio:
let cell = tableView.dequeueReusableCell(withIdentifier: SegmentedControlTableViewCell.className, for: indexPath) as! SegmentedControlTableViewCell
cell.valueType = .aspectRatio
cell.aspectRatio = tracer.settings.sceneFrame.aspectRatio
cell.delegate = self
return cell
case .view:
let cell = tableView.dequeueReusableCell(withIdentifier: FrameViewTableViewCell.className, for: indexPath) as! FrameViewTableViewCell
let frame = tracer.settings.sceneFrame
cell.minX = frame.minX
cell.maxX = frame.maxX
cell.minY = frame.minY
cell.maxY = frame.maxY
cell.zPlane = frame.zPlane
cell.delegate = self
return cell
case .size:
let cell = tableView.dequeueReusableCell(withIdentifier: FrameSizeTableViewCell.className, for: indexPath) as! FrameSizeTableViewCell
cell.width = tracer.settings.sceneFrame.width
cell.height = tracer.settings.sceneFrame.height
cell.delegate = self
return cell
}
case .resetSettings:
let cell = tableView.dequeueReusableCell(withIdentifier: SingleButtonTableViewCell.className, for: indexPath) as! SingleButtonTableViewCell
cell.button.setTitle(NSLocalizedString("Reset Settings", comment: "The title text for the reset settings button"), for: .normal)
cell.button.setTitleColor(.red, for: .normal)
cell.button.addTarget(self, action: #selector(resetSettingsButtonPressed(_:)), for: .touchUpInside)
return cell
case .resetSpheres:
let cell = tableView.dequeueReusableCell(withIdentifier: SingleButtonTableViewCell.className, for: indexPath) as! SingleButtonTableViewCell
cell.button.setTitle(NSLocalizedString("Reset Spheres", comment: "The title text for the reset spheres button"), for: .normal)
cell.button.setTitleColor(.red, for: .normal)
cell.button.addTarget(self, action: #selector(resetSpheresButtonPressed(_:)), for: .touchUpInside)
return cell
}
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch Section(rawValue: section)! {
case .background:
return NSLocalizedString("The background color is used for space where no spheres appear in the scene. Shadows are not cast on the background.", comment: "The description for the scene's background color")
case .frame:
return NSLocalizedString("The minimum and maximum x and y values specify the bounds of the view rectangle rendered in the z-plane. The width and height specify the dimensions of the rendered image.", comment: "The description for the scene frame")
default:
return nil
}
}
// MARK: - Actions
@objc private func resetSettingsButtonPressed(_ button: UIButton) {
let alertController = UIAlertController(title: NSLocalizedString("Reset Settings", comment: "The title text for the reset settings alert"),
message: NSLocalizedString("Are you sure you want to reset ray tracing settings? This will not affect sphere data.", comment: "The subtitle text for the reset alert"),
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("Reset", comment: "The text for the reset button within the reset settings alert"), style: .destructive) { _ in
self.tracer.settings = RayTracerSettings()
self.tableView.reloadData()
})
alertController.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "The text for the cancel button within the reset settings alert"), style: .cancel, handler: nil))
self.present(alertController, animated: true)
}
@objc private func resetSpheresButtonPressed(_ button: UIButton) {
let alertController = UIAlertController(title: NSLocalizedString("Reset Spheres", comment: "The title text for the reset spheres alert"),
message: NSLocalizedString("Are you sure you want to reset sphere data?", comment: "The subtitle text for the reset spheres alert"),
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("Reset", comment: "The text for the reset button within the reset spheres alert"), style: .destructive) { _ in
let context = PersistenceManager.shared.persistentContainer.viewContext
let deleteRequest = NSBatchDeleteRequest(fetchRequest: Sphere.fetchRequest())
let _ = try? context.execute(deleteRequest)
let tracer = RayTracer.shared
tracer.spheres.removeAll()
tracer.spheres.append(Sphere(string: "1.0 1.0 0.0 2.0 1.0 0.0 1.0 0.2 0.4 0.5 0.05", context: context)!)
tracer.spheres.append(Sphere(string: "8.0 -10.0 100.0 90.0 0.2 0.2 0.6 0.4 0.8 0.0 0.05", context: context)!)
NotificationCenter.default.post(name: .SphereDataDidReset, object: nil)
PersistenceManager.shared.saveContext()
})
alertController.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "The text for the cancel button within the reset spheres alert"), style: .cancel, handler: nil))
self.present(alertController, animated: true)
}
}
extension SettingsTableViewController: EyePointTableViewCellDelegate {
func eyePointTableViewCellEyePointDidChange(_ cell: EyePointTableViewCell) {
tracer.settings.eyePoint = Point(x: 0, y: 0, z: cell.zCoordinate)
}
}
extension SettingsTableViewController: PointTableViewCellDelegate {
func pointTableViewCellPointDidChange(_ cell: PointTableViewCell) {
let indexPath = tableView.indexPath(for: cell)!
switch Section(rawValue: indexPath.section)! {
case .light:
tracer.settings.light.position = cell.point
default:
break
}
}
}
extension SettingsTableViewController: ColorTableViewCellDelegate {
func colorTableViewCellColorDidChange(_ cell: ColorTableViewCell) {
let indexPath = tableView.indexPath(for: cell)!
switch Section(rawValue: indexPath.section)! {
case .light:
tracer.settings.light.color = cell.color
case .ambience:
tracer.settings.ambience = cell.color
case .background:
tracer.settings.backgroundColor = cell.color
default:
break
}
}
}
extension SettingsTableViewController: SegmentedControlTableViewCellDelegate {
func segmentedControlTableViewCellSegmentedControlValueDidChange(_ cell: SegmentedControlTableViewCell) {
switch cell.valueType {
case .intensity:
tracer.settings.light.intensity = cell.intensity!
case .aspectRatio:
tracer.settings.sceneFrame.aspectRatio = cell.aspectRatio!
let frameViewCell = tableView.cellForRow(at: IndexPath(row: FrameRow.view.rawValue, section: Section.frame.rawValue)) as! FrameViewTableViewCell
let maxMinYSliderValue = Double(frameViewCell.minYSlider.maximumValue)
if frameViewCell.minY == maxMinYSliderValue || tracer.settings.sceneFrame.minY > maxMinYSliderValue {
tracer.settings.sceneFrame.minY = maxMinYSliderValue
}
frameViewCell.minX = tracer.settings.sceneFrame.minX
frameViewCell.maxX = tracer.settings.sceneFrame.maxX
frameViewCell.minY = tracer.settings.sceneFrame.minY
frameViewCell.maxY = tracer.settings.sceneFrame.maxY
let frameSizeCell = tableView.cellForRow(at: IndexPath(row: FrameRow.size.rawValue, section: Section.frame.rawValue)) as! FrameSizeTableViewCell
let minHeightSliderValue = Int(frameSizeCell.heightSlider.minimumValue)
if frameSizeCell.height == minHeightSliderValue || tracer.settings.sceneFrame.height < minHeightSliderValue {
tracer.settings.sceneFrame.height = minHeightSliderValue
}
frameSizeCell.width = tracer.settings.sceneFrame.width
frameSizeCell.height = tracer.settings.sceneFrame.height
}
}
}
extension SettingsTableViewController: FrameViewTableViewCellDelegate {
func frameViewTableViewCellMinXDidChange(_ cell: FrameViewTableViewCell) {
guard tracer.settings.sceneFrame.aspectRatio != .freeform else {
tracer.settings.sceneFrame.minX = cell.minX
return
}
let maxMinYSliderValue = Double(cell.minYSlider.maximumValue)
let minYIsAtMaxAndMinXIsIncreasing = cell.minY == maxMinYSliderValue && cell.minX > tracer.settings.sceneFrame.minX
let minXSliderValueWasIncreasedQuickly = tracer.settings.sceneFrame.minY > maxMinYSliderValue && cell.minX == Double(cell.minXSlider.maximumValue)
if minYIsAtMaxAndMinXIsIncreasing || minXSliderValueWasIncreasedQuickly {
tracer.settings.sceneFrame.minY = maxMinYSliderValue
} else {
tracer.settings.sceneFrame.minX = cell.minX
cell.minY = tracer.settings.sceneFrame.minY
cell.maxY = tracer.settings.sceneFrame.maxY
}
cell.minX = tracer.settings.sceneFrame.minX
cell.maxX = tracer.settings.sceneFrame.maxX
}
func frameViewTableViewCellMaxXDidChange(_ cell: FrameViewTableViewCell) {
guard tracer.settings.sceneFrame.aspectRatio != .freeform else {
tracer.settings.sceneFrame.maxX = cell.maxX
return
}
let maxMinYSliderValue = Double(cell.minYSlider.maximumValue)
let minYIsAtMaxAndMaxXIsDecreasing = cell.minY == maxMinYSliderValue && cell.maxX < tracer.settings.sceneFrame.maxX
let maxXSliderValueWasDecreasedQuickly = tracer.settings.sceneFrame.minY > maxMinYSliderValue && cell.maxX == Double(cell.maxXSlider.minimumValue)
if minYIsAtMaxAndMaxXIsDecreasing || maxXSliderValueWasDecreasedQuickly {
tracer.settings.sceneFrame.minY = maxMinYSliderValue
} else {
tracer.settings.sceneFrame.maxX = cell.maxX
cell.minY = tracer.settings.sceneFrame.minY
cell.maxY = tracer.settings.sceneFrame.maxY
}
cell.minX = tracer.settings.sceneFrame.minX
cell.maxX = tracer.settings.sceneFrame.maxX
}
func frameViewTableViewCellMinYDidChange(_ cell: FrameViewTableViewCell) {
guard tracer.settings.sceneFrame.aspectRatio != .freeform else {
tracer.settings.sceneFrame.minY = cell.minY
return
}
let minMinXSliderValue = Double(cell.minXSlider.minimumValue)
let minXIsAtMinAndMinYIsDecreasing = cell.minX == minMinXSliderValue && cell.minY < tracer.settings.sceneFrame.minY
if minXIsAtMinAndMinYIsDecreasing {
tracer.settings.sceneFrame.minX = minMinXSliderValue
} else {
tracer.settings.sceneFrame.minY = cell.minY
cell.minX = tracer.settings.sceneFrame.minX
cell.maxX = tracer.settings.sceneFrame.maxX
}
cell.minY = tracer.settings.sceneFrame.minY
cell.maxY = tracer.settings.sceneFrame.maxY
}
func frameViewTableViewCellMaxYDidChange(_ cell: FrameViewTableViewCell) {
guard tracer.settings.sceneFrame.aspectRatio != .freeform else {
tracer.settings.sceneFrame.maxY = cell.maxY
return
}
let minMinXSliderValue = Double(cell.minXSlider.minimumValue)
let minXIsAtMinAndMaxYIsIncreasing = cell.minX == minMinXSliderValue && cell.maxY > tracer.settings.sceneFrame.maxY
if minXIsAtMinAndMaxYIsIncreasing {
tracer.settings.sceneFrame.minX = minMinXSliderValue
} else {
tracer.settings.sceneFrame.maxY = cell.maxY
cell.minX = tracer.settings.sceneFrame.minX
cell.maxX = tracer.settings.sceneFrame.maxX
}
cell.minY = tracer.settings.sceneFrame.minY
cell.maxY = tracer.settings.sceneFrame.maxY
}
func frameViewTableViewCellZPlaneDidChange(_ cell: FrameViewTableViewCell) {
tracer.settings.sceneFrame.zPlane = cell.zPlane
}
}
extension SettingsTableViewController: FrameSizeTableViewCellDelegate {
func frameSizeTableViewCellWidthDidChange(_ cell: FrameSizeTableViewCell) {
guard tracer.settings.sceneFrame.aspectRatio != .freeform else {
tracer.settings.sceneFrame.width = cell.width
return
}
let minHeightSliderValue = Int(cell.heightSlider.minimumValue)
let heightIsAtMinAndWidthIsDecreasing = cell.height == minHeightSliderValue && cell.width < tracer.settings.sceneFrame.width
let widthSliderValueWasDecreasedQuickly = tracer.settings.sceneFrame.height < minHeightSliderValue && cell.width == Int(cell.widthSlider.minimumValue)
if heightIsAtMinAndWidthIsDecreasing || widthSliderValueWasDecreasedQuickly {
tracer.settings.sceneFrame.height = minHeightSliderValue
} else {
tracer.settings.sceneFrame.width = cell.width
cell.height = tracer.settings.sceneFrame.height
}
cell.width = tracer.settings.sceneFrame.width
}
func frameSizeTableViewCellHeightDidChange(_ cell: FrameSizeTableViewCell) {
guard tracer.settings.sceneFrame.aspectRatio != .freeform else {
tracer.settings.sceneFrame.height = cell.height
return
}
let maxWidthSliderValue = Int(cell.widthSlider.maximumValue)
let widthIsAtMaxAndHeightIsIncreasing = cell.width == maxWidthSliderValue && cell.height > tracer.settings.sceneFrame.height
if widthIsAtMaxAndHeightIsIncreasing {
tracer.settings.sceneFrame.width = maxWidthSliderValue
} else {
tracer.settings.sceneFrame.height = cell.height
cell.width = tracer.settings.sceneFrame.width
}
cell.height = tracer.settings.sceneFrame.height
}
}
|
mit
|
56a3b267dbee13c73afea2df7a0e2d87
| 47.531707 | 259 | 0.67645 | 5.089003 | false | false | false | false |
redbooth/RealmResultsController
|
Example/RealmResultsController/ViewModels.swift
|
2
|
1920
|
//
// testmodels.swift
// RealmResultsController
//
// Created by Isaac Roldan on 6/8/15.
// Copyright © 2015 Redbooth.
//
import Foundation
import RealmSwift
class TaskObject: RealmSwift.Object {
dynamic var id = 0
dynamic var name = ""
dynamic var resolved = false
dynamic var projectID = 0
dynamic var user: UserObject?
override static func primaryKey() -> String? {
return "id"
}
lazy var something: Bool = {
true
}()
static func map(_ model: TaskModelObject) -> TaskObject {
let task = TaskObject()
task.id = model.id
task.name = model.name
task.resolved = model.resolved
task.projectID = model.projectID
return task
}
static func mapTask(_ taskModel: TaskObject) -> TaskModelObject {
let task = TaskModelObject()
task.id = taskModel.id
task.name = taskModel.name
task.resolved = taskModel.resolved
task.projectID = taskModel.projectID
return task
}
}
class TaskModelObject: RealmSwift.Object {
dynamic var id = 0
dynamic var name = ""
dynamic var resolved = false
dynamic var projectID = 0
dynamic var user: UserObject?
override static func primaryKey() -> String? {
return "id"
}
lazy var something: Bool = {
true
}()
}
class UserObject: RealmSwift.Object {
dynamic var id = 0
dynamic var name = ""
dynamic var avatarURL = ""
override static func primaryKey() -> String? {
return "id"
}
}
class ProjectObject: RealmSwift.Object {
dynamic var id = 0
dynamic var name = ""
dynamic var projectDrescription = ""
override static func primaryKey() -> String? {
return "id"
}
}
class DummyObject: RealmSwift.Object {
dynamic var id: Int = 0
dynamic var optionalNilValue: ProjectObject?
}
|
mit
|
b0353694897afb02f6e582b0b24cc15e
| 21.313953 | 69 | 0.611777 | 4.371298 | false | false | false | false |
proxpero/Matasano
|
Matasano/Conversions.swift
|
1
|
10755
|
//
// Conversions.swift
// Cryptopals
//
// Created by Todd Olsen on 2/13/16.
// Copyright © 2016 Todd Olsen. All rights reserved.
//
import Foundation
private let base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".characters.map { String($0) }
extension String {
/// returns an Unicode code point
public var unicodeScalarCodePoint: UInt32 {
let scalars = self.unicodeScalars
return scalars[scalars.startIndex].value
}
/// converts a string of ascii text and
/// returns an array of bytes
/// - precondition: `self` is ascii text (0..<128)
public var asciiToBytes: [UInt8] {
return unicodeScalars.map { UInt8(ascii: $0) }
}
/// returns an array of bytes
/// - precondition: `self` is hexadecimal text
public var hexToBytes: [UInt8] {
var items = lowercaseString.characters.map { String($0) }
var bytes = [UInt8]()
for i in items.startIndex.stride(to: items.endIndex, by: 2) {
guard let byte = UInt8(items[i] + (i+1==items.endIndex ? "" : items[i+1]), radix: 16) else { fatalError() }
bytes.append(byte)
}
return bytes
}
/// returns an array of bytes
/// - precondition: `self` is base-64 text
public var base64ToBytes: [UInt8] {
return characters.map { String($0) }.filter { $0 != "=" }.map { UInt8(base64Chars.indexOf($0)!) }.sextetArrayToBytes
}
public var asciiToBase64: String {
return self.asciiToBytes.base64Representation
}
public var base64ToAscii: String {
return self.base64ToBytes.asciiRepresentation
}
public var hexToBase64: String {
return self.hexToBytes.base64Representation
}
public var base64ToHex: String {
return self.hexToBytes.hexRepresentation
}
}
extension CollectionType where Generator.Element == UInt8, Index == Int {
/// return the ascii representation of `self`
/// complexity: O(N)
public var asciiRepresentation: String {
if let result = String(bytes: self, encoding: NSUTF8StringEncoding) {
return result
}
return String(bytes: self, encoding: NSUnicodeStringEncoding)!
}
/// returns the hexidecimal representation of `self`
/// complexity: O(N)
public var hexRepresentation: String
{
var output = ""
for byte in self {
output += String(byte, radix: 16)
}
return output
}
/// returns the base64 representation of `self`
/// complexity: O(N)
public var base64Representation: String
{
var output = ""
for sixbitInt in (self.bytesToSextetArray.map { Int($0) }) {
output += base64Chars[sixbitInt]
}
while output.characters.count % 4 != 0 { output += "=" }
return output
}
///
private var bytesToSextetArray: [UInt8] {
var sixes = [UInt8]()
for i in startIndex.stride(to: endIndex, by: 3) {
sixes.append(self[i] >> 2)
// if there are two missing characters, pad the result with '=='
guard i+1 < endIndex else {
sixes.appendContentsOf([(self[i] << 6) >> 2])
return sixes
}
sixes.append((self[i] << 6) >> 2 | self[i+1] >> 4)
// if there is one missing character, pad the result with '='
guard i+2 < endIndex else {
sixes.append((self[i+1] << 4) >> 2)
return sixes
}
sixes.append((self[i+1] << 4) >> 2 | self[i+2] >> 6)
sixes.append((self[i+2] << 2) >> 2)
}
return sixes
}
private var sextetArrayToBytes: [UInt8] {
var bytes: [UInt8] = []
for i in startIndex.stride(to: endIndex, by: 4) {
bytes.append(self[i+0]<<2 | self[i+1]>>4)
guard i+2 < endIndex else { return bytes }
bytes.append(self[i+1]<<4 | self[i+2]>>2)
guard i+3 < endIndex else { return bytes }
bytes.append(self[i+2]<<6 | self[i+3]>>0)
}
return bytes
}
}
// MARK: TESTS
func testConversions() {
let hobbes = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure."
func testUnicodeScalarCodePoint()
{
assert(" ".unicodeScalarCodePoint == UInt32(32)) // lower bound
assert("0".unicodeScalarCodePoint == UInt32(48))
assert("C".unicodeScalarCodePoint == UInt32(67))
assert("a".unicodeScalarCodePoint == UInt32(97))
assert("t".unicodeScalarCodePoint == UInt32(116))
assert("~".unicodeScalarCodePoint == UInt32(126)) // upper bound
print("\(#function) passed.")
}
func testAsciiConversions()
{
let bytes = [UInt8(77), UInt8(97), UInt8(110)]
let text = "Man"
assert(text.asciiToBytes == bytes)
assert(bytes.asciiRepresentation == text)
assert(hobbes.asciiToBytes.asciiRepresentation == hobbes)
print("\(#function) passed.")
}
func testHexConversions()
{
let text = "deadbeef"
assert(text.hexToBytes.hexRepresentation == text)
let t1 = "f79"
assert(t1.hexToBytes.hexRepresentation == t1)
print("\(#function) passed.")
}
func testBase64Conversions()
{
let sixes: [UInt8] = [19, 22, 5, 46]
let eights: [UInt8] = [77, 97, 110]
assert(sixes.sextetArrayToBytes == eights)
assert(eights.bytesToSextetArray == sixes)
let t1 = "Man"
let e1 = "TWFu"
assert(t1.asciiToBytes.base64Representation == e1)
assert(e1.base64ToBytes.asciiRepresentation == t1)
assert(t1.asciiToBase64 == e1)
assert(e1.base64ToAscii == t1)
assert(t1.asciiToBytes == e1.base64ToBytes)
let t2 = "any carnal pleasure."
let e2 = "YW55IGNhcm5hbCBwbGVhc3VyZS4="
assert(t2.asciiToBytes.base64Representation == e2)
assert(e2.base64ToBytes.asciiRepresentation == t2)
assert(t2.asciiToBase64 == e2)
assert(e2.base64ToAscii == t2)
assert(t2.asciiToBytes == e2.base64ToBytes)
let t3 = "any carnal pleasure"
let e3 = "YW55IGNhcm5hbCBwbGVhc3VyZQ=="
assert(t3.asciiToBytes.base64Representation == e3)
assert(e3.base64ToBytes.asciiRepresentation == t3)
assert(t3.asciiToBase64 == e3)
assert(e3.base64ToAscii == t3)
assert(t3.asciiToBytes == e3.base64ToBytes)
let t4 = "any carnal pleasur"
let e4 = "YW55IGNhcm5hbCBwbGVhc3Vy"
assert(t4.asciiToBytes.base64Representation == e4)
assert(e4.base64ToBytes.asciiRepresentation == t4)
assert(t4.asciiToBase64 == e4)
assert(e4.base64ToAscii == t4)
assert(t4.asciiToBytes == e4.base64ToBytes)
let t5 = "any carnal pleasu"
let e5 = "YW55IGNhcm5hbCBwbGVhc3U="
assert(t5.asciiToBytes.base64Representation == e5)
assert(e5.base64ToBytes.asciiRepresentation == t5)
assert(t5.asciiToBase64 == e5)
assert(e5.base64ToAscii == t5)
assert(t5.asciiToBytes == e5.base64ToBytes)
let t6 = "any carnal pleas"
let e6 = "YW55IGNhcm5hbCBwbGVhcw=="
assert(t6.asciiToBytes.base64Representation == e6)
assert(e6.base64ToBytes.asciiRepresentation == t6)
assert(t6.asciiToBase64 == e6)
assert(e6.base64ToAscii == t6)
assert(t6.asciiToBytes == e6.base64ToBytes)
let t7 = "pleasure."
let e7 = "cGxlYXN1cmUu"
assert(t7.asciiToBytes.base64Representation == e7)
assert(e7.base64ToBytes.asciiRepresentation == t7)
assert(t7.asciiToBase64 == e7)
assert(e7.base64ToAscii == t7)
assert(t7.asciiToBytes == e7.base64ToBytes)
let t8 = "leasure."
let e8 = "bGVhc3VyZS4="
assert(t8.asciiToBytes.base64Representation == e8)
assert(e8.base64ToBytes.asciiRepresentation == t8)
assert(t8.asciiToBase64 == e8)
assert(e8.base64ToAscii == t8)
assert(t8.asciiToBytes == e8.base64ToBytes)
let t9 = "easure."
let e9 = "ZWFzdXJlLg=="
assert(t9.asciiToBytes.base64Representation == e9)
assert(e9.base64ToBytes.asciiRepresentation == t9)
assert(t9.asciiToBase64 == e9)
assert(e9.base64ToAscii == t9)
assert(t9.asciiToBytes == e9.base64ToBytes)
let t10 = "asure."
let e10 = "YXN1cmUu"
assert(t10.asciiToBytes.base64Representation == e10)
assert(e10.base64ToBytes.asciiRepresentation == t10)
assert(t10.asciiToBase64 == e10)
assert(e10.base64ToAscii == t10)
assert(t10.asciiToBytes == e10.base64ToBytes)
let t11 = "sure."
let e11 = "c3VyZS4="
assert(t11.asciiToBytes.base64Representation == e11)
assert(e11.base64ToBytes.asciiRepresentation == t11)
assert(t11.asciiToBase64 == e11)
assert(e11.base64ToAscii == t11)
assert(t11.asciiToBytes == e11.base64ToBytes)
let encoded = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="
assert(hobbes.asciiToBytes.base64Representation == encoded)
assert(hobbes.asciiToBase64 == encoded)
let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
let output = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"
assert(input.hexToBytes.base64Representation == output)
assert(input.hexToBase64 == output)
print("\(#function) passed.")
}
testUnicodeScalarCodePoint()
testAsciiConversions()
testHexConversions()
testBase64Conversions()
print("\(#function) passed.")
}
|
mit
|
27a0b92a3470e762f630332b4755f677
| 32.501558 | 384 | 0.60173 | 3.664055 | false | false | false | false |
jpush/jchat-swift
|
JChat/Src/ChatModule/Chat/ViewController/JCRemindListViewController.swift
|
1
|
6542
|
//
// JCRemindListViewController.swift
// JChat
//
// Created by JIGUANG on 2017/6/26.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
class JCRemindListViewController: UIViewController {
typealias handleFinish = (_ user: JMSGUser?, _ isAtll: Bool, _ length: Int) -> ()
var finish: handleFinish!
var group: JMSGGroup!
override func viewDidLoad() {
super.viewDidLoad()
_init()
}
private lazy var cancel = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 36))
fileprivate lazy var tableView: UITableView = {
var tableView = UITableView(frame: .zero, style: .grouped)
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.keyboardDismissMode = .onDrag
tableView.sectionIndexColor = UIColor(netHex: 0x2dd0cf)
tableView.sectionIndexBackgroundColor = .clear
tableView.register(JCContacterCell.self, forCellReuseIdentifier: "JCContacterCell")
tableView.frame = CGRect(x: 0, y: 0, width: self.view.width, height: self.view.height)
return tableView
}()
fileprivate lazy var searchView: UISearchBar = {
let searchView = UISearchBar.default
searchView.frame = CGRect(x: 0, y: 0, width: self.view.width, height: 31)
searchView.delegate = self
return searchView
}()
fileprivate lazy var tagArray = ["所有成员"]
fileprivate lazy var users: [JMSGUser] = []
fileprivate lazy var keys: [String] = []
fileprivate lazy var data: Dictionary<String, [JMSGUser]> = Dictionary()
fileprivate lazy var defaultGroupIcon = UIImage.loadImage("com_icon_group_36")
fileprivate var isSearching = false
private func _init() {
self.title = "选择提醒的人"
view.backgroundColor = .white
_setupNavigation()
tableView.tableHeaderView = searchView
users = group.memberArray()
_classify(users)
view.addSubview(tableView)
}
private func _setupNavigation() {
cancel.addTarget(self, action: #selector(_clickNavRightButton), for: .touchUpInside)
cancel.setTitle("取消", for: .normal)
cancel.titleLabel?.font = UIFont.systemFont(ofSize: 15)
let item = UIBarButtonItem(customView: cancel)
navigationItem.leftBarButtonItem = item
}
@objc func _clickNavRightButton() {
dismiss(animated: true, completion: nil)
}
func _classify(_ users: [JMSGUser]) {
keys.removeAll()
data.removeAll()
for item in users {
if item.username == JMSGUser.myInfo().username {
continue
}
var key = item.displayName().firstCharacter()
if !key.isLetterOrNum() {
key = "#"
}
var array = data[key]
if array == nil {
array = [item]
} else {
array?.append(item)
}
if !keys.contains(key) {
keys.append(key)
}
data[key] = array
}
keys = keys.sortedKeys()
}
fileprivate func filter(_ searchString: String) {
if searchString.isEmpty || searchString == "" {
isSearching = false
_classify(users)
tableView.reloadData()
return
}
isSearching = true
let filteredUsersArray = _JCFilterUsers(users: users, string: searchString)
_classify(filteredUsersArray)
tableView.reloadData()
}
}
//Mark: -
extension JCRemindListViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
if isSearching {
return keys.count
}
if users.count > 0 {
return keys.count + 1
}
return 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 && !isSearching {
return tagArray.count
}
return isSearching ? data[keys[section]]!.count : data[keys[section - 1]]!.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if isSearching {
return keys[section]
}
if section == 0 {
return ""
}
return keys[section - 1]
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return keys
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 55
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 25
}
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "JCContacterCell", for: indexPath)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let cell = cell as? JCContacterCell else {
return
}
if indexPath.section == 0 && !isSearching {
switch indexPath.row {
case 0:
cell.title = tagArray[indexPath.row]
cell.icon = defaultGroupIcon
default:
break
}
return
}
let user = isSearching ? data[keys[indexPath.section]]?[indexPath.row] : data[keys[indexPath.section - 1]]?[indexPath.row]
cell.bindDate(user!)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 0 && !isSearching {
finish(nil, true, 4)
dismiss(animated: true, completion: nil)
return
}
if let user = isSearching ? data[keys[indexPath.section]]?[indexPath.row] : data[keys[indexPath.section - 1]]?[indexPath.row] {
finish(user, false, user.displayName().length)
}
dismiss(animated: true, completion: nil)
}
}
extension JCRemindListViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filter(searchText)
}
}
|
mit
|
764f88bca31fbfe622445b6d1bbba7b6
| 31.738693 | 136 | 0.596163 | 4.797496 | false | false | false | false |
peaks-cc/iOS11_samplecode
|
chapter_12/HomeKitSample/App/Code/Controller/TimerTriggerViewController.swift
|
1
|
2476
|
//
// TimerTriggerViewController.swift
//
// Created by ToKoRo on 2017-09-03.
//
import UIKit
import HomeKit
class TimerTriggerViewController: TriggerViewController {
@IBOutlet weak var fireDateLabel: UILabel?
@IBOutlet weak var timeZoneLabel: UILabel?
@IBOutlet weak var recurrenceLabel: UILabel?
@IBOutlet weak var recurrenceCalendarLabel: UILabel?
var timerTrigger: HMTimerTrigger { return (trigger as? HMTimerTrigger)! }
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "DatePicker"?:
sendContext(timerTrigger.fireDate, to: segue.destination)
bindCallback(type: Date.self, to: segue.destination) { [weak self] date in
self?.handleNewFireDate(date)
}
default:
super.prepare(for: segue, sender: sender)
}
}
override func refresh() {
super.refresh()
fireDateLabel?.text = DateFormatter.localizedString(from: timerTrigger.fireDate, dateStyle: .short, timeStyle: .short)
timeZoneLabel?.text = {
guard let timeZone = timerTrigger.timeZone else {
return nil
}
return String(describing: timeZone)
}()
recurrenceLabel?.text = {
guard let components = timerTrigger.recurrence else {
return nil
}
return String(describing: components)
}()
recurrenceCalendarLabel?.text = {
guard let calendar = timerTrigger.recurrenceCalendar else {
return nil
}
return String(describing: calendar)
}()
}
private func displayFireDateAlert() {
performSegue(withIdentifier: "DatePicker", sender: nil)
}
private func handleNewFireDate(_ date: Date) {
timerTrigger.updateFireDate(date) { [weak self] error in
if let error = error {
print("# error: \(error)")
}
self?.refresh()
}
}
}
// MARK: - UITableViewDelegate
extension TimerTriggerViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
super.tableView(tableView, didSelectRowAt: indexPath)
switch (indexPath.section, indexPath.row) {
case (1, 0):
// fireDate
displayFireDateAlert()
default:
break
}
}
}
|
mit
|
4755d323e1076d9f3469fa8b9a206327
| 27.790698 | 126 | 0.605008 | 4.912698 | false | false | false | false |
breadwallet/breadwallet-ios
|
breadwallet/src/ViewControllers/EnterPhraseCollectionViewController.swift
|
1
|
6294
|
//
// EnterPhraseCollectionViewController.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-02-23.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import UIKit
private let itemHeight: CGFloat = 32
class EnterPhraseCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
// MARK: - Public
var didFinishPhraseEntry: ((String) -> Void)?
var height: CGFloat {
return (itemHeight * 4.0) + (2 * sectionInsets) + (3 * interItemSpacing)
}
init(keyMaster: KeyMaster) {
self.keyMaster = keyMaster
super.init(collectionViewLayout: UICollectionViewFlowLayout())
}
private let cellHeight: CGFloat = 32
var interItemSpacing: CGFloat {
return E.isSmallScreen ? 6 : C.padding[1]
}
var sectionInsets: CGFloat {
return E.isSmallScreen ? 0 : C.padding[2]
}
private lazy var cellSize: CGSize = {
let margins = sectionInsets * 2 // left and right section insets
let spacing = interItemSpacing * 2
let widthAvailableForCells = collectionView.frame.width - margins - spacing
let cellsPerRow: CGFloat = 3
return CGSize(width: widthAvailableForCells / cellsPerRow, height: cellHeight)
}()
// MARK: - Private
private let cellIdentifier = "CellIdentifier"
private let keyMaster: KeyMaster
private var phrase: String {
return (0...11).map { index in
guard let phraseCell = collectionView?.cellForItem(at: IndexPath(item: index, section: 0)) as? EnterPhraseCell else { return ""}
return phraseCell.textField.text?.lowercased() ?? ""
}.joined(separator: " ")
}
override func viewDidLoad() {
collectionView = NonScrollingCollectionView(frame: view.bounds, collectionViewLayout: collectionViewLayout)
collectionView.backgroundColor = Theme.primaryBackground
collectionView?.register(EnterPhraseCell.self, forCellWithReuseIdentifier: cellIdentifier)
collectionView?.delegate = self
collectionView?.dataSource = self
// Omit the rounded border on small screens due to space constraints.
if !E.isSmallScreen {
collectionView.layer.cornerRadius = 8.0
collectionView.layer.borderColor = Theme.secondaryBackground.cgColor
collectionView.layer.borderWidth = 2.0
}
collectionView?.isScrollEnabled = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
becomeFirstResponder(atIndex: 0)
}
// MARK: - UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 12
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return cellSize
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
guard let enterPhraseCell = item as? EnterPhraseCell else { return item }
enterPhraseCell.index = indexPath.row
enterPhraseCell.didTapNext = { [weak self] in
self?.becomeFirstResponder(atIndex: indexPath.row + 1)
}
enterPhraseCell.didTapPrevious = { [weak self] in
self?.becomeFirstResponder(atIndex: indexPath.row - 1)
}
enterPhraseCell.didTapDone = { [weak self] in
guard let phrase = self?.phrase else { return }
self?.didFinishPhraseEntry?(phrase)
}
enterPhraseCell.isWordValid = { [weak self] word in
guard let myself = self else { return false }
return myself.keyMaster.isSeedWordValid(word.lowercased())
}
enterPhraseCell.didEnterSpace = {
enterPhraseCell.didTapNext?()
}
enterPhraseCell.didPasteWords = { [weak self] words in
guard E.isDebug || E.isTestFlight else { return false }
guard enterPhraseCell.index == 0, words.count <= 12, let `self` = self else { return false }
for (index, word) in words.enumerated() {
self.setText(word, atIndex: index)
}
return true
}
if indexPath.item == 0 {
enterPhraseCell.disablePreviousButton()
} else if indexPath.item == 11 {
enterPhraseCell.disableNextButton()
}
return item
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
let insets = sectionInsets
return UIEdgeInsets(top: insets, left: insets, bottom: insets, right: insets)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return interItemSpacing
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return interItemSpacing
}
// MARK: - Extras
private func becomeFirstResponder(atIndex: Int) {
guard let phraseCell = collectionView?.cellForItem(at: IndexPath(item: atIndex, section: 0)) as? EnterPhraseCell else { return }
phraseCell.textField.becomeFirstResponder()
}
private func setText(_ text: String, atIndex: Int) {
guard let phraseCell = collectionView?.cellForItem(at: IndexPath(item: atIndex, section: 0)) as? EnterPhraseCell else { return }
phraseCell.textField.text = text
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
e4af43ceb83f452c59b8920e8d7adebe
| 38.578616 | 144 | 0.647068 | 5.374039 | false | false | false | false |
NilStack/NilThemeKit
|
NilThemeKit/ViewController.swift
|
2
|
2637
|
//
// ViewController.swift
// NilThemeKit
//
// Created by Peng on 9/26/14.
// Copyright (c) 2014 peng. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UISearchBarDelegate
{
let searchBar: UISearchBar = UISearchBar()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
title = "Main View"
let toolBar: UIToolbar = UIToolbar(frame: CGRectMake(0.0, 0.0, CGRectGetWidth(view.frame), 35.0))
let flexibleItem: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let dismissButton: UIBarButtonItem = UIBarButtonItem(title: "Dismiss", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("dismiss") )
toolBar.items = [flexibleItem, dismissButton]
searchBar.frame = CGRectMake(0.0, 0.0, CGRectGetWidth(view.frame), 50.0)
searchBar.showsCancelButton = true
searchBar.inputAccessoryView = toolBar
searchBar.delegate = self
view.addSubview(searchBar)
let demoSwitch = UISwitch(frame: CGRectMake(20.0, 60.0, 100.0, 50.0))
view.addSubview(demoSwitch)
let demoButton: UIButton = UIButton(frame: CGRectMake(20.0, 100.0, 100.0, 50.0))
demoButton.setTitle("UIButton", forState: UIControlState.Normal)
demoButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
view.addSubview(demoButton)
let aiView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
aiView.frame = CGRectMake(120.0, 100.0, 50.0, 50.0)
view.addSubview(aiView)
aiView.startAnimating()
let segmentedControl: UISegmentedControl = UISegmentedControl(items: ["One", "Two"])
segmentedControl.frame = CGRectMake(20.0, 160.0, 200.0, 40.0)
segmentedControl.selectedSegmentIndex = 0
view.addSubview(segmentedControl)
let slider: UISlider = UISlider(frame: CGRectMake(20.0, 210.0, 200.0, 40.0))
slider.minimumValue = 0
slider.maximumValue = 100
slider.value = 50
view.addSubview(slider)
let pageControl: UIPageControl = UIPageControl(frame: CGRectMake(0, CGRectGetHeight(view.frame) - 150, CGRectGetWidth(self.view.frame), 50) )
pageControl.numberOfPages = 3
view.addSubview(pageControl)
}
func dismiss()
{
searchBar.resignFirstResponder()
}
}
|
mit
|
89d35bce03b912218d59251fe1cb143b
| 38.358209 | 157 | 0.672734 | 4.708929 | false | false | false | false |
qingtianbuyu/Mono
|
Moon/Classes/Main/Model/MNBannerEntity.swift
|
1
|
799
|
//
// MNBannerEntity.swift
// Moon
//
// Created by YKing on 16/6/4.
// Copyright © 2016年 YKing. All rights reserved.
//
import UIKit
class MNBannerEntity: NSObject {
var start: Int = 0
var type: String?
var id: Int = 0
var name: String?
var entity_list: [MNBanner]?
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
if key == "entity_list" {
guard let array = (value as?[[String : AnyObject]]) else {
return
}
var bannerArray = [MNBanner]()
for dict in array {
bannerArray.append(MNBanner(dict:dict))
}
entity_list = bannerArray
return
}
super.setValue(value, forKey: key)
}
}
|
mit
|
c1b8cd99645c45334c18bf65400ec9dd
| 17.511628 | 66 | 0.581658 | 3.668203 | false | false | false | false |
epv44/TwitchAPIWrapper
|
Sources/TwitchAPIWrapper/Requests/VideoRequest.swift
|
1
|
1566
|
//
// VideoRequest.swift
// TwitchAPIWrapper iOS
//
// Created by Eric Vennaro on 4/3/18.
//
import Foundation
///Get videos request see https://dev.twitch.tv/docs/api/reference/#get-videos for details
public struct VideoRequest: JSONConstructableRequest {
///URL for the request
public let url: URL?
///Initialize a `VideoRequest` with the included parameters
/// - throws `RequestValidationError`.
public init(
id: [String]?,
userID: String?,
gameID: String?,
after: String? = nil,
before: String? = nil,
first: String? = nil,
language: [String]? = nil,
period: String? = nil,
sort: String? = nil,
type: String? = nil
) throws {
if id == nil && userID == nil && gameID == nil {
throw RequestValidationError.invalidInput(
"id, gameID, and userID cannot all be null, at least one is required")
}
let queryParams = ["id":id as Any,
"user_id":userID as Any,
"game_id":gameID as Any,
"after":after as Any,
"before":before as Any,
"first":first as Any,
"language":language as Any,
"period":period as Any,
"sort":sort as Any,
"type":type as Any].buildQueryItems()
self.url = TwitchEndpoints.videos.construct()?.appending(queryItems: queryParams)
}
}
|
mit
|
d334ae41c1a22891f30be78d75c26b69
| 33.8 | 90 | 0.52235 | 4.552326 | false | false | false | false |
CD1212/Doughnut
|
Pods/GRDB.swift/GRDB/QueryInterface/SQLCollatedExpression.swift
|
1
|
2312
|
/// SQLCollatedExpression taints an expression so that every derived expression
/// is eventually evaluated using an SQLite collation.
///
/// You create one by calling the SQLSpecificExpressible.collating() method.
///
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
///
/// // SELECT * FROM players WHERE email = '[email protected]' COLLATE NOCASE
/// Players.filter(email == "[email protected]")
public struct SQLCollatedExpression {
/// The tainted expression
public let expression: SQLExpression
/// The name of the collation
public let collationName: Database.CollationName
/// Returns an ordering suitable for QueryInterfaceRequest.order()
///
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
///
/// // SELECT * FROM players ORDER BY email COLLATE NOCASE ASC
/// Players.order(email.asc)
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var asc: SQLOrderingTerm {
return SQLOrdering.asc(sqlExpression)
}
/// Returns an ordering suitable for QueryInterfaceRequest.order()
///
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
///
/// // SELECT * FROM players ORDER BY email COLLATE NOCASE DESC
/// Players.order(email.desc)
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
public var desc: SQLOrderingTerm {
return SQLOrdering.desc(sqlExpression)
}
init(_ expression: SQLExpression, collationName: Database.CollationName) {
self.expression = expression
self.collationName = collationName
}
var sqlExpression: SQLExpression {
return SQLExpressionCollate(expression, collationName: collationName)
}
}
extension SQLCollatedExpression : SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var reversed: SQLOrderingTerm {
return desc
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
return sqlExpression.orderingTermSQL(&arguments)
}
}
|
gpl-3.0
|
18bc956b448cb30df6cc0da808eb9c1b
| 36.290323 | 93 | 0.676471 | 4.56917 | false | false | false | false |
R3dTeam/SwiftLint
|
Source/SwiftLintFramework/Rules/NestingRule.swift
|
5
|
3886
|
//
// NestingRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SourceKittenFramework
import SwiftXPC
public struct NestingRule: ASTRule {
public init() {}
public let identifier = "nesting"
public func validateFile(file: File) -> [StyleViolation] {
return validateFile(file, dictionary: file.structure.dictionary)
}
public func validateFile(file: File, dictionary: XPCDictionary) -> [StyleViolation] {
return (dictionary["key.substructure"] as? XPCArray ?? []).flatMap { subItem in
var violations = [StyleViolation]()
if let subDict = subItem as? XPCDictionary,
let kindString = subDict["key.kind"] as? String,
let kind = flatMap(kindString, { SwiftDeclarationKind(rawValue: $0) }) {
violations.extend(validateFile(file, dictionary: subDict))
violations.extend(validateFile(file, kind: kind, dictionary: subDict))
}
return violations
}
}
public func validateFile(file: File,
kind: SwiftDeclarationKind,
dictionary: XPCDictionary) -> [StyleViolation] {
return self.validateFile(file, kind: kind, dictionary: dictionary, level: 0)
}
func validateFile(file: File,
kind: SwiftDeclarationKind,
dictionary: XPCDictionary,
level: Int) -> [StyleViolation] {
var violations = [StyleViolation]()
let typeKinds: [SwiftDeclarationKind] = [
.Class,
.Struct,
.Typealias,
.Enum,
.Enumelement
]
if let offset = flatMap(dictionary["key.offset"] as? Int64, { Int($0) }) {
if level > 1 && contains(typeKinds, kind) {
violations.append(StyleViolation(type: .Nesting,
location: Location(file: file, offset: offset),
reason: "Types should be nested at most 1 level deep"))
} else if level > 5 {
violations.append(StyleViolation(type: .Nesting,
location: Location(file: file, offset: offset),
reason: "Statements should be nested at most 5 levels deep"))
}
}
let substructure = dictionary["key.substructure"] as? XPCArray ?? []
violations.extend(compact(substructure.map { subItem in
let subDict = subItem as? XPCDictionary
let kindString = subDict?["key.kind"] as? String
let kind = flatMap(kindString) { kindString in
return SwiftDeclarationKind(rawValue: kindString)
}
if let kind = kind, subDict = subDict {
return (kind, subDict)
}
return nil
} as [(SwiftDeclarationKind, XPCDictionary)?]).flatMap { (kind, dict) in
return validateFile(file, kind: kind, dictionary: dict, level: level + 1)
})
return violations
}
public let example = RuleExample(
ruleName: "Nesting Rule",
ruleDescription: "Types should be nested at most 1 level deep, " +
"and statements should be nested at most 5 levels deep.",
nonTriggeringExamples: ["class", "struct", "enum"].flatMap { kind in
["\(kind) Class0 { \(kind) Class1 {} }\n",
"func func0() {\nfunc func1() {\nfunc func2() {\nfunc func3() {\nfunc func4() { " +
"func func5() {\n}\n}\n}\n}\n}\n}\n"]
},
triggeringExamples: ["class", "struct", "enum"].map { kind in
"\(kind) Class0 { \(kind) Class1 { \(kind) Class2 {} } }\n"
} + [
"func func0() {\nfunc func1() {\nfunc func2() {\nfunc func3() {\nfunc func4() { " +
"func func5() {\nfunc func6() {\n}\n}\n}\n}\n}\n}\n}\n"
]
)
}
|
mit
|
d2c0b7cb1e8d7684f7ba4dd07b338d4f
| 39.479167 | 99 | 0.56665 | 4.476959 | false | false | false | false |
adis300/Swift-Learn
|
SwiftLearn/Source/Arithmetic/MaxMin.swift
|
1
|
2531
|
//
// Max.swift
// Swift-Learn
//
// Created by Disi A on 11/24/16.
// Copyright © 2016 Votebin. All rights reserved.
//
import Foundation
import Accelerate
// MARK: Maximum
public func max(_ x: [Float]) -> Float {
var result: Float = 0
vDSP_maxv(x, 1, &result, vDSP_Length(x.count))
return result
}
public func max(_ x: [Double]) -> Double {
var result: Double = 0
vDSP_maxvD(x, 1, &result, vDSP_Length(x.count))
return result
}
public func max(_ x: Vector<Float>) -> Float {
var result: Float = 0
vDSP_maxv(x.vector, 1, &result, vDSP_Length(x.length))
return result
}
public func max(_ x: Vector<Double>) -> Double {
var result: Double = 0
vDSP_maxvD(x.vector, 1, &result, vDSP_Length(x.length))
return result
}
// Max with index
public func max(_ x: [Float]) -> (Float, Int){
var index: UInt = 0
var value: Float = 0
vDSP_maxvi(x, 1, &value, &index, vDSP_Length(x.count))
return (value, Int(index))
}
public func max(_ x: [Double]) -> (Double, Int){
var index: UInt = 0
var value: Double = 0
vDSP_maxviD(x, 1, &value, &index, vDSP_Length(x.count))
return (value, Int(index))
}
public func max(_ x: Vector<Float>) -> (Float, Int){
return max(x.vector)
}
public func max(_ x: Vector<Double>) -> (Double, Int){
return max(x.vector)
}
// MARK: Minimum
public func min(_ x: [Float]) -> Float {
var result: Float = 0.0
vDSP_minv(x, 1, &result, vDSP_Length(x.count))
return result
}
public func min(_ x: [Double]) -> Double {
var result: Double = 0.0
vDSP_minvD(x, 1, &result, vDSP_Length(x.count))
return result
}
public func min(_ x: Vector<Float>) -> Float {
var result: Float = 0.0
vDSP_minv(x.vector, 1, &result, vDSP_Length(x.length))
return result
}
public func min(_ x: Vector<Double>) -> Double {
var result: Double = 0.0
vDSP_minvD(x.vector, 1, &result, vDSP_Length(x.length))
return result
}
// Minimum index
public func min(_ x: [Float]) -> (Float, Int){
var index: UInt = 0
var value: Float = 0
vDSP_minvi(x, 1, &value, &index, vDSP_Length(x.count))
return (value, Int(index))
}
public func min(_ x: [Double]) -> (Double, Int){
var index: UInt = 0
var value: Double = 0
vDSP_minviD(x, 1, &value, &index, vDSP_Length(x.count))
return (value, Int(index))
}
public func min(_ x: Vector<Float>) -> (Float, Int){
return min(x.vector)
}
public func min(_ x: Vector<Double>) -> (Double, Int){
return min(x.vector)
}
|
apache-2.0
|
c806eb764badd7addf3f74d364484885
| 21.389381 | 59 | 0.6083 | 2.983491 | false | false | false | false |
hooman/swift
|
test/DebugInfo/doubleinlines.swift
|
3
|
956
|
// RUN: %target-swift-frontend -primary-file %s -emit-ir -g -parse-stdlib \
// RUN: -debug-info-format=codeview -O -parse-as-library \
// RUN: -module-name DoubleInlines -o - | %FileCheck %s
func condFail(arg: Builtin.Int1, msg: Builtin.RawPointer) {
Builtin.condfail_message(arg, msg)
}
func callCondFail(arg: Builtin.Int1, msg: Builtin.RawPointer) {
condFail(arg: arg, msg: msg)
}
// CHECK: define hidden swiftcc void @"$s13DoubleInlines12callCondFail3arg3msgyBi1__BptF"{{.*}} !dbg ![[FUNCSCOPE:.*]] {
// CHECK: tail call void asm sideeffect "", "n"(i32 0) #3, !dbg ![[SCOPEONE:.*]]
// CHECK: ![[FUNCSCOPEOTHER:.*]] = distinct !DISubprogram(name: "condFail",{{.*}}
// CHECK: ![[SCOPEONE]] = !DILocation(line: 0, scope: ![[SCOPETWO:.*]], inlinedAt: ![[SCOPETHREE:.*]])
// CHECK: ![[SCOPETHREE]] = !DILocation(line: 6, scope: ![[SCOPEFOUR:.*]])
// CHECK: ![[SCOPEFOUR]] = distinct !DILexicalBlock(scope: ![[FUNCSCOPE]], file: !{{.*}}, line: 10)
|
apache-2.0
|
c9cce4c902cd4fb31fbdd748195c7feb
| 52.111111 | 120 | 0.650628 | 3.093851 | false | false | false | false |
padawan/smartphone-app
|
MT_iOS/MT_iOS/Classes/ViewController/ImageSelectorTableViewController.swift
|
1
|
4969
|
//
// ImageSelectorTableViewController.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/06/11.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
class ImageSelectorTableViewController: AddAssetTableViewController, AssetSelectorDelegate {
var object: EntryImageItem!
var entry: BaseEntry!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.title = NSLocalizedString("Photos", comment: "Photos")
}
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 Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
*/
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
let user = (UIApplication.sharedApplication().delegate as! AppDelegate).currentUser!
switch indexPath.section {
case Section.Buttons.rawValue:
if let cameraButton = cell.viewWithTag(1) as? UIButton {
cameraButton.enabled = self.blog.canUpload(user: user)
}
if let libraryButton = cell.viewWithTag(2) as? UIButton {
libraryButton.enabled = self.blog.canUpload(user: user)
}
if let assetListButton = cell.viewWithTag(3) as? UIButton {
if self.entry is Entry {
assetListButton.enabled = self.blog.canListAssetForEntry(user: user)
} else {
assetListButton.enabled = self.blog.canListAssetForPage(user: user)
}
}
return cell
case Section.Items.rawValue:
return cell
default:
break
}
// Configure the cell...
return UITableViewCell()
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@IBAction override func assetListButtonPushed(sender: UIButton) {
let vc = AssetSelectorTableViewController()
let nav = UINavigationController(rootViewController: vc)
vc.blog = self.blog
vc.delegate = self
self.presentViewController(nav, animated: true, completion: nil)
}
func AssetSelectorDone(controller: AssetSelectorTableViewController, asset: Asset) {
self.delegate?.AddAssetDone(self, asset: asset)
}
}
|
mit
|
df5130ada7a64a3fb8ccc20e10ebb05b
| 34.992754 | 157 | 0.6515 | 5.387202 | false | false | false | false |
joeytat/Eww
|
Eww/Classes/Extensions/ImagePicker+Extension.swift
|
1
|
2638
|
//
// ImagePicker+Extension.swift
// Tea
//
// Created by Joey on 21/04/2017.
// Copyright © 2017 Miaomi. All rights reserved.
//
import Foundation
import Photos
import BSImagePicker
import RxSwift
public extension UIViewController {
public func displayImagePicker(maxSelections: Int, takePhotos: Bool = false) -> Observable<[PHAsset]> {
return Observable<[PHAsset]>.create {[weak self] observable in
let vc = BSImagePickerViewController()
vc.maxNumberOfSelections = maxSelections
vc.takePhotos = takePhotos
if let color = self?.navigationController?.navigationBar.tintColor {
vc.cancelButton.setTitleTextAttributes([NSForegroundColorAttributeName : color], for: UIControlState.normal)
vc.cancelButton.setTitleTextAttributes([NSForegroundColorAttributeName : color], for: UIControlState.highlighted)
vc.doneButton.setTitleTextAttributes([NSForegroundColorAttributeName : color], for: UIControlState.normal)
vc.doneButton.setTitleTextAttributes([NSForegroundColorAttributeName : color], for: UIControlState.highlighted)
} else {
vc.cancelButton.tintColor = self?.navigationController?.navigationBar.tintColor
vc.doneButton.tintColor = self?.navigationController?.navigationBar.tintColor
}
self?.bs_presentImagePickerController(
vc,
animated: true,
select: { (asset: PHAsset) -> Void in
},
deselect: { (asset: PHAsset) -> Void in
},
cancel: { (assets: [PHAsset]) -> Void in
observable.onNext([])
observable.onCompleted()
},
finish: { (assets: [PHAsset]) -> Void in
observable.onNext(assets)
observable.onCompleted()
},
completion: nil)
return Disposables.create()
}
}
}
public extension PHAsset {
public func reqeustImageData(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?) -> Observable<UIImage?> {
return Observable<UIImage?>.create {[weak self] observable in
PHImageManager()
.requestImage(for: self!, targetSize: targetSize, contentMode: contentMode, options: options) { (image, _) in
observable.onNext(image)
observable.onCompleted()
}
return Disposables.create()
}
}
}
|
mit
|
9b2b808a4fa22eda03ddde5fad852cef
| 40.203125 | 144 | 0.60182 | 5.873051 | false | false | false | false |
nazarcybulskij/scituner
|
SciTuner/Tuner.swift
|
3
|
10978
|
//
// Tuner.swift
// SciTuner
//
// Created by Denis Kreshikhin on 28.02.15.
// Copyright (c) 2015 Denis Kreshikhin. All rights reserved.
//
import Foundation
class Tuner {
let defaults = NSUserDefaults.standardUserDefaults()
class var sharedInstance: Tuner {
struct Static {
static var instance: Tuner?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = Tuner()
}
return Static.instance!
}
var bindings: [String:[()->Void]] = [:]
func on(name: String, _ callback: ()->Void){
if bindings[name] != nil {
bindings[name]! += [callback]
} else {
bindings[name] = [callback]
}
}
func call(name: String) {
var callbacks = bindings[name]
if callbacks == nil {
return
}
for callback in callbacks! {
callback()
}
}
var instrument: String = "guitar"
var tunings: [String] = []
var tuningStrings: [[String]] = []
var tuningIndex: Int = 0
var strings: [String] = []
var sortedStrings: [String] = []
var stringIndex: Int = 0
var string: String = "e2"
var notes: [String] = []
var frequency: Double = 440
var baseFrequency: Double = 440
var baseNote: String = "a4"
var fret: Int = 0
var isPaused = false;
let pitchs: [String] = ["Default A4=440Hz", "Scientific C4=256Hz"]
let pitchValues: [String] = ["default", "scientific"]
var pitchIndex: Int = 0
var pitch: String = "default"
var instruments: [String: [(title: String, strings: [String])]] = [:]
var filter: String = "on"
func setInstrument(value: String){
if instruments[value] == nil {
return
}
instrument = value
defaults.setValue(instrument, forKey: "instrument")
tunings = []
tuningStrings = []
for tuning in instruments[instrument]! {
tunings.append(tuning.title)
tuningStrings.append(tuning.strings)
}
var defaultTuning: Int? = defaults.integerForKey(instrument)
if defaultTuning != nil {
setTuningIndex(defaultTuning!)
}else{
setTuningIndex(0)
}
call("instrumentChange")
}
func setTuningIndex(value: Int) {
defaults.setInteger(value, forKey: instrument)
tuningIndex = value
strings = tuningStrings[tuningIndex]
sortedStrings = sorted(strings) {self.noteFrequency($0) < self.noteFrequency($1)}
setStringIndex(stringIndex)
call("tuningChange")
}
func setStringIndex(value: Int) {
if value < 0 {
stringIndex = 0
} else if value >= strings.count {
stringIndex = strings.count - 1
} else {
stringIndex = value
}
defaults.setInteger(stringIndex, forKey: "stringIndex")
string = strings[stringIndex]
var n = Double(noteNumber(string))
notes = [noteString(n-1.0), noteString(n), noteString(n+1.0)]
call("stringChange")
}
func setPitchIndex(value: Int) {
defaults.setInteger(value, forKey: "pitchIndex")
pitchIndex = value
pitch = pitchValues[pitchIndex]
if pitch == "scientific" {
baseFrequency = 256.0
baseNote = "c4"
return
}
baseFrequency = 440.0
baseNote = "a4"
call("pitchChange")
}
func setFrequency(value: Double){
frequency = value / fretScale()
call("frequencyChange")
}
func setFret(value: Int) {
fret = value
defaults.setInteger(fret, forKey: "fret")
call("fretChange")
call("")
}
func setFilter(value: String) {
filter = value
defaults.setObject(filter, forKey: "filter")
call("filterChange")
}
var status = "active"
func setStatus(value: String){
status = value
call("statusChange")
}
init(){
addInstrument("guitar", [
("Standard", "e2 a2 d3 g3 b3 e4"),
("New Standard", "c2 g2 d3 a3 e4 g4"),
("Russian", "d2 g2 b2 d3 g3 b3 d4"),
("Drop D", "d2 a2 d3 g3 b3 e4"),
("Drop C", "c2 g2 c3 f3 a3 d4"),
("Drop G", "g2 d2 g3 c4 e4 a4"),
("Open D", "d2 a2 d3 f#3 a3 d4"),
("Open C", "c2 g2 c3 g3 c4 e4"),
("Open G", "g2 g3 d3 g3 b3 d4"),
("Lute", "e2 a2 d3 f#3 b3 e4"),
("Irish", "d2 a2 d3 g3 a3 d4")
])
addInstrument("cello", [
("Standard", "c2 g2 d3 a3"),
("Alternative", "c2 g2 d3 g3")
])
addInstrument("violin", [
("Standard", "g3 d4 a4 e5"),
("Tenor", "g2 d3 a3 e4"),
("Tenor alter.", "f2 c3 g3 d4")
])
addInstrument("banjo", [
("Standard", "g4 d3 g3 b3 d4")
])
addInstrument("balalaika", [
("Standard/Prima", "e4 e4 a4"),
("Bass", "e2 a2 d3"),
("Tenor", "a2 a2 e3"),
("Alto", "e3 e3 a3"),
("Secunda", "a3 a3 d4"),
("Piccolo", "b4 e5 a5")
])
addInstrument("ukulele", [
("Standard", "g4 c4 e4 a4"),
("D-tuning", "a4 d4 f#4 b4")
])
//addInstrument("free mode", [
// ("Octaves", "c2 c3 c4 c5 c6"),
// ("C-major", "c3 d3 e3 f3 g3 a3 b3"),
// ("C-minor", "c3 d3 e3 f3 g3 a3 b3")
//])
if defaults.stringForKey("instrument") != nil {
var value: String? = defaults.stringForKey("instrument")
setInstrument(value!)
} else {
setInstrument("guitar")
}
if defaults.stringForKey("filter") != nil {
var value: String? = defaults.stringForKey("filter")
setFilter(value!)
} else {
setFilter("on")
}
setTuningIndex(defaults.integerForKey(instrument))
setStringIndex(defaults.integerForKey("stringIndex"))
setPitchIndex(defaults.integerForKey("pitchIndex"))
setFret(defaults.integerForKey("fret"))
}
func addInstrument(name: String, _ tunings: [(String, String)]){
var result: [(title: String, strings: [String])] = []
for (title, strings) in tunings {
var splitStrings: [String] = split(strings) {$0 == " "}
var titleStrings: String = join(" ", splitStrings.map({(note: String) -> String in
return note.stringByReplacingOccurrencesOfString("#", withString: "♯", options: NSStringCompareOptions.LiteralSearch, range: nil).uppercaseString
}))
result += [(title: title + " (" + titleStrings + ")", strings: splitStrings)]
}
instruments[name] = result
}
func noteNumber(noteString: String) -> Int {
var note = noteString.lowercaseString
var number = 0
var octave = 0
if note.hasPrefix("c") { number = 0; }
if note.hasPrefix("c#") { number = 1; }
if note.hasPrefix("d") { number = 2; }
if note.hasPrefix("d#") { number = 3; }
if note.hasPrefix("e") { number = 4; }
if note.hasPrefix("f") { number = 5; }
if note.hasPrefix("f#") { number = 6; }
if note.hasPrefix("g") { number = 7; }
if note.hasPrefix("g#") { number = 8; }
if note.hasPrefix("a") { number = 9; }
if note.hasPrefix("a#") { number = 10; }
if note.hasPrefix("b") { number = 11; }
if note.hasSuffix("0") { octave = 0; }
if note.hasSuffix("1") { octave = 1; }
if note.hasSuffix("2") { octave = 2; }
if note.hasSuffix("3") { octave = 3; }
if note.hasSuffix("4") { octave = 4; }
if note.hasPrefix("5") { octave = 5; }
if note.hasPrefix("6") { octave = 6; }
if note.hasPrefix("7") { octave = 7; }
if note.hasPrefix("8") { octave = 8; }
return 12 * octave + number
}
func noteString(num: Double) -> String {
var noteOctave: Int = Int(num / 12)
var noteShift: Int = Int(num % 12)
var result = ""
switch noteShift {
case 0: result += "c"
case 1: result += "c#"
case 2: result += "d"
case 3: result += "d#"
case 4: result += "e"
case 5: result += "f"
case 6: result += "f#"
case 7: result += "g"
case 8: result += "g#"
case 9: result += "a"
case 10: result += "a#"
case 11: result += "b"
default: result += ""
}
return result + String(noteOctave)
}
func noteFrequency(noteString: String) -> Double {
var n = noteNumber(noteString)
var b = noteNumber(baseNote)
return baseFrequency * pow(2.0, Double(n - b) / 12.0);
}
func frequencyNumber(f: Double) -> Double {
var b = noteNumber(baseNote);
return 12.0 * log(f / baseFrequency) / log(2) + Double(b);
}
func frequencyDistanceNumber(f0: Double, _ f1: Double) -> Double {
var n0 = frequencyNumber(f0)
var n1 = frequencyNumber(f1)
return n1 - n0;
}
func targetFrequency() -> Double {
return noteFrequency(string) * fretScale()
}
func actualFrequency() -> Double {
return frequency * fretScale()
}
func frequencyDeviation() -> Double {
return 100.0 * frequencyDistanceNumber(noteFrequency(string), frequency)
}
func stringPosition() -> Double {
var pos: Double = soretedStringPosition()
var index: Int = Int(pos + 0.5)
if index < 0 || index >= sortedStrings.count {
return pos
}
var name = sortedStrings[index]
var realIndex: Int? = find(strings, name)
if realIndex == nil{
return pos
}
return pos + Double(realIndex! - index)
}
func soretedStringPosition() -> Double {
var frst = noteFrequency(sortedStrings.first!)
var lst = noteFrequency(sortedStrings.last!)
if frequency > frst {
var f0 = 0.0
var pos: Double = -1.0
for str in sortedStrings {
var f1 = noteFrequency(str)
if frequency < f1 {
return pos + (frequency - f0) / (f1 - f0)
}
f0 = f1
pos++
}
}
return Double(strings.count - 1) * (frequency - frst) / (lst - frst)
}
func nextString() {
setStringIndex(stringIndex+1)
}
func prevString() {
setStringIndex(stringIndex-1)
}
func fretScale() -> Double {
return pow(2.0, Double(fret) / 12.0)
}
}
|
mit
|
6e73d6964dedbf1dbcb65921eba952eb
| 27.071611 | 161 | 0.517037 | 3.86615 | false | false | false | false |
swiftde/Live-Sessions
|
#3 - OOP - Thomas/Xcode Projekte/OOPDemo/OOPDemo/Component.swift
|
1
|
410
|
class Component {
let manufacturer: Company
let name: String
let price: Double?
init(manufacturer: Company, name: String, price: Double) {
self.manufacturer = manufacturer
self.name = name
self.price = price
}
init(manufacturer: Company, name: String) {
self.manufacturer = manufacturer
self.name = name
self.price = nil
}
}
|
apache-2.0
|
30e97747904652463f7eb4e41ea81f2a
| 23.176471 | 62 | 0.6 | 4.606742 | false | false | false | false |
IngmarStein/swift
|
test/SILGen/guaranteed_closure_context.swift
|
3
|
3018
|
// RUN: %target-swift-frontend -parse-as-library -emit-silgen -enable-guaranteed-closure-contexts %s | %FileCheck %s
func use<T>(_: T) {}
func escape(_ f: () -> ()) {}
protocol P {}
class C: P {}
struct S {}
// CHECK-LABEL: sil hidden @_TF26guaranteed_closure_context19guaranteed_capturesFT_T_
func guaranteed_captures() {
// CHECK: [[MUTABLE_TRIVIAL_BOX:%.*]] = alloc_box $S
var mutableTrivial = S()
// CHECK: [[MUTABLE_RETAINABLE_BOX:%.*]] = alloc_box $C
var mutableRetainable = C()
// CHECK: [[MUTABLE_ADDRESS_ONLY_BOX:%.*]] = alloc_box $P
var mutableAddressOnly: P = C()
// CHECK: [[IMMUTABLE_TRIVIAL:%.*]] = apply {{.*}} -> S
let immutableTrivial = S()
// CHECK: [[IMMUTABLE_RETAINABLE:%.*]] = apply {{.*}} -> @owned C
let immutableRetainable = C()
// CHECK: [[IMMUTABLE_ADDRESS_ONLY:%.*]] = alloc_stack $P
let immutableAddressOnly: P = C()
func captureEverything() {
use((mutableTrivial, mutableRetainable, mutableAddressOnly,
immutableTrivial, immutableRetainable, immutableAddressOnly))
}
// CHECK-NOT: strong_retain [[MUTABLE_TRIVIAL_BOX]]
// CHECK-NOT: strong_retain [[MUTABLE_RETAINABLE_BOX]]
// CHECK-NOT: strong_retain [[MUTABLE_ADDRESS_ONLY_BOX]]
// CHECK-NOT: strong_retain [[IMMUTABLE_RETAINABLE]]
// CHECK: [[IMMUTABLE_AO_BOX:%.*]] = alloc_box $P
// CHECK: [[FN:%.*]] = function_ref [[FN_NAME:@_TFF26guaranteed_closure_context19guaranteed_capturesFT_T_L_17captureEverythingfT_T_]]
// CHECK: apply [[FN]]([[MUTABLE_TRIVIAL_BOX]], [[MUTABLE_RETAINABLE_BOX]], [[MUTABLE_ADDRESS_ONLY_BOX]], [[IMMUTABLE_TRIVIAL]], [[IMMUTABLE_RETAINABLE]], [[IMMUTABLE_AO_BOX]])
captureEverything()
// CHECK: strong_release [[IMMUTABLE_AO_BOX]]
// CHECK-NOT: strong_retain [[MUTABLE_TRIVIAL_BOX]]
// CHECK-NOT: strong_retain [[MUTABLE_RETAINABLE_BOX]]
// CHECK-NOT: strong_retain [[MUTABLE_ADDRESS_ONLY_BOX]]
// CHECK-NOT: strong_retain [[IMMUTABLE_RETAINABLE]]
// -- partial_apply still takes ownership of its arguments.
// CHECK: [[FN:%.*]] = function_ref [[FN_NAME]]
// CHECK: strong_retain [[MUTABLE_TRIVIAL_BOX]]
// CHECK: strong_retain [[MUTABLE_RETAINABLE_BOX]]
// CHECK: strong_retain [[MUTABLE_ADDRESS_ONLY_BOX]]
// CHECK: strong_retain [[IMMUTABLE_RETAINABLE]]
// CHECK: [[IMMUTABLE_AO_BOX:%.*]] = alloc_box $P
// CHECK: [[CLOSURE:%.*]] = partial_apply {{.*}}([[MUTABLE_TRIVIAL_BOX]], [[MUTABLE_RETAINABLE_BOX]], [[MUTABLE_ADDRESS_ONLY_BOX]], [[IMMUTABLE_TRIVIAL]], [[IMMUTABLE_RETAINABLE]], [[IMMUTABLE_AO_BOX]])
// CHECK: apply {{.*}}[[CLOSURE]]
// CHECK-NOT: strong_retain [[MUTABLE_TRIVIAL_BOX]]
// CHECK-NOT: strong_retain [[MUTABLE_RETAINABLE_BOX]]
// CHECK-NOT: strong_retain [[MUTABLE_ADDRESS_ONLY_BOX]]
// CHECK-NOT: strong_retain [[IMMUTABLE_RETAINABLE]]
// CHECK-NOT: strong_release [[IMMUTABLE_AO_BOX]]
escape(captureEverything)
}
// CHECK: sil shared [[FN_NAME]] : $@convention(thin) (@guaranteed @box S, @guaranteed @box C, @guaranteed @box P, S, @guaranteed C, @guaranteed @box P)
|
apache-2.0
|
3424b1edada32e90f9f0e067d0846bb5
| 42.73913 | 204 | 0.661034 | 3.623049 | false | false | false | false |
crazypoo/PTools
|
PooToolsSource/PhoneInfo/PTPhoneNetWorkInfo.swift
|
1
|
2975
|
//
// PTPhoneNetWorkInfo.swift
// PooTools_Example
//
// Created by 邓杰豪 on 18/11/22.
// Copyright © 2022 crazypoo. All rights reserved.
//
import UIKit
/*
#define IOS_CELLULAR @"pdp_ip0"
#define IOS_WIFI @"en0"
#define IOS_VPN @"utun0"
#define IP_ADDR_IPv4 @"ipv4"
#define IP_ADDR_IPv6 @"ipv6"
*/
@objcMembers
public class PTPhoneNetWorkInfo:NSObject {
public struct NetworkInterfaceInfo
{
let name: String
let ip: String
let netmask: String
}
class open func ipv4String()->String
{
for info in PTPhoneNetWorkInfo.enumerate()
{
if info.name == "en0"
{
return info.ip
}
}
return "0.0.0.0"
}
public static func enumerate() -> [NetworkInterfaceInfo]
{
var interfaces = [NetworkInterfaceInfo]()
//MARK: Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&ifaddr) == 0
{
//MARK: For each interface ...
var ptr = ifaddr
while( ptr != nil) {
let flags = Int32(ptr!.pointee.ifa_flags)
var addr = ptr!.pointee.ifa_addr.pointee
//MARK: Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
var mask = ptr!.pointee.ifa_netmask.pointee
//MARK: Convert interface address to a human readable string:
let zero = CChar(0)
var hostname = [CChar](repeating: zero, count: Int(NI_MAXHOST))
var netmask = [CChar](repeating: zero, count: Int(NI_MAXHOST))
if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST) == 0) {
let address = String(cString: hostname)
let name = ptr!.pointee.ifa_name!
let ifname = String(cString: name)
if (getnameinfo(&mask, socklen_t(mask.sa_len), &netmask, socklen_t(netmask.count),nil, socklen_t(0), NI_NUMERICHOST) == 0)
{
let netmaskIP = String(cString: netmask)
let info = NetworkInterfaceInfo(name: ifname,ip: address,netmask: netmaskIP)
interfaces.append(info)
}
}
}
}
ptr = ptr!.pointee.ifa_next
}
freeifaddrs(ifaddr)
}
return interfaces
}
}
|
mit
|
c446def6a5aa47ff46adcefceaaa43e8
| 32.727273 | 150 | 0.497305 | 4.233951 | false | false | false | false |
fxdemolisher/newscats
|
ios/NewsCats/NavigationBridge.swift
|
1
|
1297
|
import React
import UIKit
/**
* A RN->Native bridge supporting various navigation features that cannot be done in RN.
*/
class NavigationBridge : NSObject, RCTBridgeModule {
/**
* Returns the name that the module is exposed under in RN.
*/
static func moduleName() -> String! {
return "nav"
}
/**
* Returns a list of methods to expose to RN.
*/
func methodsToExport() -> [RCTBridgeMethod]! {
return [
BridgeMethodWrapper(name: "restart", .oneWay(restart)),
]
}
/**
* Restarts the RN bridge, effectively restarting the UI portion of the app.
*/
func restart(_ bridge: RCTBridge, _ arguments: [Any]) throws -> Void {
let currentDispatchQueueLabel = String(validatingUTF8: __dispatch_queue_get_label(nil))!
let isOnMainDispatchQueue = currentDispatchQueueLabel == DispatchQueue.main.label
let restartOperation = {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.reset()
bridge.reload()
}
guard !isOnMainDispatchQueue else {
restartOperation()
return
}
return DispatchQueue.main.sync(execute: restartOperation)
}
}
|
apache-2.0
|
01ca4c558c0a77070aa82cdb5566e76a
| 28.477273 | 96 | 0.606014 | 4.969349 | false | false | false | false |
collegboi/MBaaSKit
|
MBaaSKit/Classes/Protocols/CellViewLoad.swift
|
1
|
3493
|
//
// CellViewLoad.swift
// DIT-Timetable-V2
//
// Created by Timothy Barnard on 11/02/2017.
// Copyright © 2017 Timothy Barnard. All rights reserved.
//
import UIKit
public protocol CellViewLoad { }
public extension CellViewLoad where Self: UITableViewCell {
public func setupCellView( className: UIViewController, name:String = "" ) {
self.setup(className: String(describing: type(of: className)), tagValue: name )
}
public func setupCellView( className: UIView, name:String = "") {
self.setup(className: String(describing: type(of: className)), tagValue: name)
}
private func setup( className: String, tagValue : String ) {
var viewName = tagValue
if tagValue.isEmpty {
viewName = String(self.tag)
}
let dict = RCConfigManager.getObjectProperties(className: className, objectName: viewName)
var fontName: String = ""
var size : CGFloat = 0.0
for (key, value) in dict {
switch key {
case "textLabel_text" where dict.tryConvert(forKey: key) != "":
self.textLabel?.text = value as? String
break
case "textLabel_textColor" where dict.tryConvert(forKey: key) != "":
self.textLabel?.textColor = RCFileManager.readJSONColor(keyVal: value as! String)
break
case "textLabel_BkgdColor" where dict.tryConvert(forKey: key) != "":
self.textLabel?.backgroundColor = RCFileManager.readJSONColor(keyVal: value as! String)
break
case "detailLabel_text" where dict.tryConvert(forKey: key) != "":
self.detailTextLabel?.text = value as? String
break
case "detailLabel_textColor" where dict.tryConvert(forKey: key) != "":
self.detailTextLabel?.textColor = RCFileManager.readJSONColor(keyVal: value as! String)
break
case "detailLabel_BkgdColor" where dict.tryConvert(forKey: key) != "":
self.detailTextLabel?.backgroundColor = RCFileManager.readJSONColor(keyVal: value as! String)
break
case "backgroundColor" where dict.tryConvert(forKey: key) != "":
self.contentView.backgroundColor = RCFileManager.readJSONColor(keyVal: value as! String)
break
case "font" where dict.tryConvert(forKey: key) != "":
fontName = (value as! String)
break
case "fontSize" where dict.tryConvert(forKey: key) != "":
size = value as! CGFloat
break
case "isMultipleTouchEnabled" where dict.tryConvert(forKey: key) != "":
self.isMultipleTouchEnabled = ((value as! Int) == 1) ? true : false
break
case "isHidden" where dict.tryConvert(forKey: key) != "":
self.isHidden = ((value as! Int) == 1) ? true : false
break
case "isUserInteractionEnabled" where dict.tryConvert(forKey: key) != "":
self.isUserInteractionEnabled = ((value as! Int) == 1) ? true : false
break
default: break
}
}
if !fontName.isEmpty && size > 0.0 {
self.textLabel?.font = UIFont(name: fontName, size: size)
self.detailTextLabel?.font = UIFont(name: fontName, size: size)
}
}
}
|
mit
|
bb37a81b6c443e4736bdc6caa5d83427
| 41.585366 | 109 | 0.57732 | 4.744565 | false | false | false | false |
iOSDevLog/iOSDevLog
|
201. UI Test/Swift/Lister WatchKit Extension/Glance/GlanceInterfaceController.swift
|
1
|
7954
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Controls the interface of the Glance. The controller displays statistics about the Today list.
*/
import WatchKit
import ListerKit
class GlanceInterfaceController: WKInterfaceController, ListsControllerDelegate, ListPresenterDelegate {
// MARK: Properties
@IBOutlet weak var glanceBadgeImage: WKInterfaceImage!
@IBOutlet weak var glanceBadgeGroup: WKInterfaceGroup!
@IBOutlet weak var remainingItemsLabel: WKInterfaceLabel!
var listsController: ListsController?
var listDocument: ListDocument?
var listPresenter: AllListItemsPresenter? {
return listDocument?.listPresenter as? AllListItemsPresenter
}
// Tracks underlying values that represent the badge.
var previousPresentedBadgeCounts: (totalListItemCount: Int, completeListItemCount: Int)?
// MARK: Initializers
override init() {
super.init()
if AppConfiguration.sharedConfiguration.isFirstLaunch {
print("Lister does not currently support configuring a storage option before the iOS app is launched. Please launch the iOS app first. See the Release Notes section in README.md for more information.")
}
}
// MARK: Setup
func setupInterface() {
// If no previously presented data exists, clear the initial UI elements.
if previousPresentedBadgeCounts == nil {
glanceBadgeGroup.setBackgroundImage(nil)
glanceBadgeImage.setImage(nil)
remainingItemsLabel.setHidden(true)
}
initializeListsController()
}
func initializeListsController() {
listsController = AppConfiguration.sharedConfiguration.listsControllerForCurrentConfigurationWithLastPathComponent(AppConfiguration.localizedTodayDocumentNameAndExtension)
listsController!.delegate = self
listsController!.startSearching()
}
// MARK: ListsControllerDelegate
func listsController(_: ListsController, didInsertListInfo listInfo: ListInfo, atIndex index: Int) {
// We only expect a single result to be returned, so we will treat this listInfo as the Today document.
processListInfoAsTodayDocument(listInfo)
}
// MARK: ListPresenterDelegate
func listPresenterDidRefreshCompleteLayout(_: ListPresenterType) {
// Since the list changed completely, show present the Glance badge.
presentGlanceBadge()
}
/**
These methods are no ops because all of the data is bulk rendered after the the content changes. This
can occur in `listPresenterDidRefreshCompleteLayout(_:)` or in `listPresenterDidChangeListLayout(_:isInitialLayout:)`.
*/
func listPresenterWillChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) {}
func listPresenter(_: ListPresenterType, didInsertListItem listItem: ListItem, atIndex index: Int) {}
func listPresenter(_: ListPresenterType, didRemoveListItem listItem: ListItem, atIndex index: Int) {}
func listPresenter(_: ListPresenterType, didUpdateListItem listItem: ListItem, atIndex index: Int) {}
func listPresenter(_: ListPresenterType, didUpdateListColorWithColor color: List.Color) {}
func listPresenter(_: ListPresenterType, didMoveListItem listItem: ListItem, fromIndex: Int, toIndex: Int) {}
func listPresenterDidChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) {
/*
The list's layout changed. However, since we don't care that a small detail about the list changed,
we're going to re-animate the badge.
*/
presentGlanceBadge()
}
// MARK: Lifecycle
override func willActivate() {
/*
Setup the interface in `willActivate` to ensure the interface is refreshed each time the interface
controller is presented.
*/
setupInterface()
}
override func didDeactivate() {
// Close the document when the interface controller is finished presenting.
listDocument?.closeWithCompletionHandler { success in
if !success {
NSLog("Couldn't close document: \(self.listDocument?.fileURL.absoluteString)")
return
}
self.listDocument = nil
}
listsController?.stopSearching()
listsController?.delegate = nil
listsController = nil
}
// MARK: Convenience
func processListInfoAsTodayDocument(listInfo: ListInfo) {
let listPresenter = AllListItemsPresenter()
listDocument = ListDocument(fileURL: listInfo.URL, listPresenter: listPresenter)
listPresenter.delegate = self
listDocument?.openWithCompletionHandler() { success in
if !success {
NSLog("Couldn't open document: \(self.listDocument?.fileURL.absoluteString)")
return
}
/*
Once the Today document has been found and opened, update the user activity with its URL path
to enable a tap on the glance to jump directly to the Today document in the watch app. A URL path
is passed instead of a URL because the `userInfo` dictionary of a WatchKit app's user activity
does not allow NSURL values.
*/
let userInfo: [NSObject: AnyObject] = [
AppConfiguration.UserActivity.listURLPathUserInfoKey: self.listDocument!.fileURL.path!,
AppConfiguration.UserActivity.listColorUserInfoKey: self.listPresenter!.color.rawValue
]
/*
Lister uses a specific user activity name registered in the Info.plist and defined as a constant to
separate this action from the built-in UIDocument handoff support.
*/
self.updateUserActivity(AppConfiguration.UserActivity.watch, userInfo: userInfo, webpageURL: nil)
}
}
func presentGlanceBadge() {
guard let listPresenter = listPresenter else { return }
let totalListItemCount = listPresenter.count
let completeListItemCount = listPresenter.presentedListItems.filter { $0.isComplete }.count
/*
If the `totalListItemCount` and the `completeListItemCount` haven't changed, there's no need to re-present
the badge.
*/
if let previousPresentedBadgeCounts = previousPresentedBadgeCounts {
if previousPresentedBadgeCounts.totalListItemCount == totalListItemCount && previousPresentedBadgeCounts.completeListItemCount == completeListItemCount {
return
}
}
// Update `previousPresentedBadgeCounts`.
previousPresentedBadgeCounts = (totalListItemCount, completeListItemCount)
// Construct and present the new badge.
let glanceBadge = GlanceBadge(totalItemCount: totalListItemCount, completeItemCount: completeListItemCount)
glanceBadgeGroup.setBackgroundImage(glanceBadge.groupBackgroundImage)
glanceBadgeImage.setImageNamed(glanceBadge.imageName)
glanceBadgeImage.startAnimatingWithImagesInRange(glanceBadge.imageRange, duration: glanceBadge.animationDuration, repeatCount: 1)
/*
Create a localized string for the # items remaining in the Glance badge. The string is retrieved
from the Localizable.stringsdict file.
*/
let itemsRemainingText = String.localizedStringWithFormat(NSLocalizedString("%d items left", comment: ""), glanceBadge.incompleteItemCount)
remainingItemsLabel.setText(itemsRemainingText)
remainingItemsLabel.setHidden(false)
}
}
|
mit
|
2b7e0d1b51c55c7c807046bfdc05abe2
| 40.202073 | 213 | 0.675176 | 5.795918 | false | true | false | false |
shridharmalimca/iOSDev
|
iOS/Swift 3.0/JSONParsing/JSONParsing/ViewController.swift
|
2
|
3269
|
//
// ViewController.swift
// JSONParsing
//
// Created by Shridhar Mali on 12/31/16.
// Copyright © 2016 Shridhar Mali. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tblView: UITableView!
var arr = [String]()
override func viewDidLoad() {
super.viewDidLoad()
getDataFromServer()
self.tblView.reloadData()
// 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.
}
// Get all json data from following URL
// http://www.apple.com/rss/
func getDataFromServer() {
let urlString: String = "https://itunes.apple.com/us/rss/topsongs/limit=100/json"
let url = URL(string: urlString)
//Prepare url request from url
var request = URLRequest(url: url!)
request.httpMethod = "GET"
// request.timeoutInterval = 60
let session = URLSession.shared
// Build a data task with the request and get data, response and error
let task = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
//If we get data properly and status code is 200
if let data = data, let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
print("Data is \(data)")
print("Response is \(httpResponse)")
do {
let dict = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: Any]
// print(dict)
let feed = dict["feed"] as! [String: Any]
// print(feed)
let entryArr = feed["entry"] as! [Any]
print("Entries \(entryArr)")
for (_, value) in entryArr.enumerated() {
// print(value)
let valueDict = value as! [String: Any]
let title = valueDict["title"] as! [String: Any]
// print(title)
let label = title["label"]
// print(label)
let titleStr: String! = label as! String!
self.arr.append(titleStr)
}
self.tblView.reloadData()
} catch {
print("Error with description \(error)")
}
self.tblView.reloadData()
}
}
//Resume or start the task in background
task.resume()
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = arr[indexPath.row]
return cell
}
}
|
apache-2.0
|
07e38b5ab8444d5580d1c3e44e5b57f2
| 36.563218 | 151 | 0.551102 | 5.122257 | false | false | false | false |
ppamorim/Gradle-iOS
|
Gradle-iOS/Extension/UIColorExtension.swift
|
1
|
1788
|
import UIKit
extension UIColor {
public convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = rgba.startIndex.advancedBy(1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
switch (hex.characters.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
}
} else {
print("Scan hex error")
}
} else {
print("Invalid RGB string, missing '#' as prefix")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
|
apache-2.0
|
848380182a02bd580689f2d4fab9a7ce
| 37.891304 | 99 | 0.528523 | 3.590361 | false | false | false | false |
GENG-GitHub/weibo-gd
|
GDWeibo/Class/Module/Compose/GDComposeViewController.swift
|
1
|
8069
|
//
// GDComposeViewController.swift
// GDWeibo
//
// Created by geng on 15/11/6.
// Copyright © 2015年 geng. All rights reserved.
//
import UIKit
class GDComposeViewController: UIViewController {
//MARK: - 属性
//toolBar底部的约束
private var toolBarBottomCons: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
prepareUI()
//添加监听键盘的通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//主动弹出键盘
textView.becomeFirstResponder()
}
// MARK: - 键盘frame改变方法
/// 键盘frame改变方法
func keyboardWillChangeFrame(notifiction: NSNotification) {
// print("notification: \(notifiction)")
//获取键盘最终的frame
let endFrame = notifiction.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
//toolBar的底部到父控件的底部
toolBarBottomCons?.constant = -(UIScreen.mainScreen().bounds.height - endFrame.origin.y)
// 获取动画时间
let duration = notifiction.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
// toolBar动画
UIView.animateWithDuration(duration) { () -> Void in
self.view.layoutIfNeeded()
// self.view.setNeedsLayout()
// self.view.layoutSubviews()
}
}
//准备UI
private func prepareUI()
{
prepareNavigation()
setToolBar()
setupTextView()
}
//MARK: - 设置导航栏
func prepareNavigation() {
// 导航栏左边按钮
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
// 导航栏右边按钮
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
// 设置发送按钮为灰色
navigationItem.rightBarButtonItem?.enabled = false
//设置标题
prepareNavTitle()
}
//设置导航栏标题
func prepareNavTitle() {
//设置文字前缀
let prefix = "发微博"
if let name = GDUserAccount.loadAccount()?.name{
//创建一个label
let nameLabel = UILabel()
let titleName = prefix + "\n" + name
//创建可变的文本
let attrStr = NSMutableAttributedString(string: titleName)
nameLabel.numberOfLines = 0
nameLabel.textAlignment = NSTextAlignment.Center
nameLabel.font = UIFont.systemFontOfSize(14)
//获取用户名
let nameRange = (titleName as NSString).rangeOfString(name)
//修改指定范围的文字的属性
attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12),range: nameRange)
attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
//为label赋值
nameLabel.attributedText = attrStr
nameLabel.sizeToFit()
//修改导航栏的标题
navigationItem.titleView = nameLabel
}else
{
//没有名字时
navigationController?.title = prefix
}
}
//设置toolBar
private func setToolBar()
{
//添加子控件
view.addSubview(toolBar)
//设置约束
let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSizeMake(view.bounds.width, 44))
//获取底部约束
toolBarBottomCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
//创建toolBar上的item
var items = [UIBarButtonItem]()
// 每个item对应的图片名称
let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
["imageName": "compose_trendbutton_background", "action": "trend"],
["imageName": "compose_mentionbutton_background", "action": "mention"],
["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
["imageName": "compose_addbutton_background", "action": "add"]]
//循环遍历数组
for dict in itemSettings
{
let item = UIBarButtonItem(imageName: dict["imageName"]!)
let action = dict["action"]
//为每个item添加点击事件
let btn = item.customView as! UIButton
//为按钮添加点击事件
btn.addTarget(self, action: Selector(action!), forControlEvents: UIControlEvents.TouchUpInside)
items.append(item)
//添加弹簧
items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
}
//删除最后一根弹簧
items.removeLast()
toolBar.items = items
}
//设置textView
private func setupTextView() {
//添加子控件
view.addSubview(textView)
//设置约束
textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
}
//MARK: - 创建子控件
private lazy var toolBar: UIToolbar = {
//创建toolBar
let toolBar = UIToolbar()
//设置背景颜色
toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
return toolBar
}()
private lazy var textView: GDPlaceHolderTextView = {
let textView = GDPlaceHolderTextView()
//设置textView背景
// textView.backgroundColor = UIColor.brownColor()
//设置contentInset
textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
//设置textView有回弹效果
textView.alwaysBounceVertical = true
//拖动textView关闭键盘
textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
textView.placeholder = "分享新鲜事..."
textView.font = UIFont.systemFontOfSize(18)
//设置代理
textView.delegate = self
// //实现显示占位文本
// let placeHolder = UILabel()
// placeHolder.text = "分享新鲜事..."
// placeHolder.sizeToFit()
// textView.addSubview(placeHolder)
return textView
}()
// MARK: - toolBarItem 监听点击事件
func picture() {
print("图片")
}
func trend() {
print("#")
}
func mention() {
print("@")
}
func emoticon() {
print("表情")
}
func add() {
print("加号")
}
// MARK: - 按钮点击事件
/// 关闭控制器
@objc private func close() {
//退出键盘
textView.resignFirstResponder()
dismissViewControllerAnimated(true, completion: nil)
}
/// 发微博
func sendStatus() {
print(__FUNCTION__)
}
}
//MARK: - 实现UITextViewDelegate
extension GDComposeViewController: UITextViewDelegate
{
func textViewDidChange(textView: UITextView) {
navigationItem.rightBarButtonItem?.enabled = textView.hasText()
}
}
|
apache-2.0
|
da7fcc541a6ada939ff1c170b75e03ca
| 25.71223 | 158 | 0.564638 | 5.28165 | false | false | false | false |
wikimedia/wikipedia-ios
|
WMF Framework/SharedContainerCache.swift
|
1
|
3315
|
import Foundation
@objc public class SharedContainerCacheCommonNames: NSObject {
@objc public static let pushNotificationsCache = "Push Notifications Cache"
@objc public static let talkPageCache = "Talk Page Cache"
}
public final class SharedContainerCache<T: Codable>: SharedContainerCacheHousekeepingProtocol {
private let fileName: String
private let subdirectoryPathComponent: String?
private let defaultCache: () -> T
public init(fileName: String, subdirectoryPathComponent: String? = nil, defaultCache: @escaping () -> T) {
self.fileName = fileName
self.subdirectoryPathComponent = subdirectoryPathComponent
self.defaultCache = defaultCache
}
private static var cacheDirectoryContainerURL: URL {
FileManager.default.wmf_containerURL()
}
private var cacheDataFileURL: URL {
let baseURL = subdirectoryURL() ?? Self.cacheDirectoryContainerURL
return baseURL.appendingPathComponent(fileName).appendingPathExtension("json")
}
private func subdirectoryURL() -> URL? {
guard let subdirectoryPathComponent = subdirectoryPathComponent else {
return nil
}
return Self.cacheDirectoryContainerURL.appendingPathComponent(subdirectoryPathComponent, isDirectory: true)
}
public func loadCache() -> T {
if let data = try? Data(contentsOf: cacheDataFileURL), let decodedCache = try? JSONDecoder().decode(T.self, from: data) {
return decodedCache
}
return defaultCache()
}
public func saveCache(_ cache: T) {
let encoder = JSONEncoder()
guard let encodedCache = try? encoder.encode(cache) else {
return
}
if let subdirectoryURL = subdirectoryURL() {
try? FileManager.default.createDirectory(at: subdirectoryURL, withIntermediateDirectories: true, attributes: nil)
}
try? encodedCache.write(to: cacheDataFileURL)
}
/// Persist only the last 50 visited talk pages
@objc public static func deleteStaleCachedItems(in subdirectoryPathComponent: String) {
let folderURL = cacheDirectoryContainerURL.appendingPathComponent(subdirectoryPathComponent)
if let urlArray = try? FileManager.default.contentsOfDirectory(at: folderURL,
includingPropertiesForKeys: [.contentModificationDateKey],
options: .skipsHiddenFiles) {
let maxCacheSize = 50
if urlArray.count > maxCacheSize {
let sortedArray = urlArray.map { url in
(url, (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? Date.distantPast)
}.sorted(by: {$0.1 > $1.1 })
.map { $0.0 }
let itemsToDelete = Array(sortedArray.suffix(from: maxCacheSize))
for urlItem in itemsToDelete {
try? FileManager.default.removeItem(at: urlItem)
}
}
}
}
}
@objc public protocol SharedContainerCacheHousekeepingProtocol: AnyObject {
static func deleteStaleCachedItems(in subdirectoryPathComponent: String)
}
|
mit
|
75bea89b3f7485d89d9886ef1ee8262a
| 38.939759 | 137 | 0.646757 | 5.543478 | false | false | false | false |
AthensWorks/OBWapp-iOS
|
Brew Week/Brew Week/Model Classes/BreweryExtension.swift
|
1
|
3602
|
//
// BreweryExtension.swift
// Brew Week
//
// Created by Ben Lachman on 3/19/15.
// Copyright (c) 2015 Ohio Brew Week. All rights reserved.
//
import UIKit
import CoreData
extension Brewery {
class func breweryFromJSON(jsonDict: [String: AnyObject]) -> Brewery? {
guard let context = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext, id = jsonDict["id"] as? Int, name = jsonDict["name"] as? String else {
return nil
}
let identifier = Int32(id)
let brewery: Brewery
if let existingBrewery = breweryForIdentifier(identifier, inContext: context) {
brewery = existingBrewery
} else if let newBrewery = NSEntityDescription.insertNewObjectForEntityForName("Brewery", inManagedObjectContext: context) as? Brewery {
newBrewery.identifier = identifier
newBrewery.name = name
brewery = newBrewery
do {
try context.save()
} catch {
print("Failed to save managed context after inserting new brewery: \(error)")
}
} else {
return nil
}
return brewery
}
class func breweriesFromJSON(jsonDict: [String: AnyObject]) {
guard let jsonBreweriesArray = jsonDict["breweries"] as? [[String: AnyObject]] else {
return
}
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
if jsonBreweriesArray.count == 0 {
return
}
var breweryIDs = [Int]()
for breweryJSON in jsonBreweriesArray {
if let id = breweryJSON["id"] as? Int {
let identifier = Int32(id)
var brewery = breweryForIdentifier(identifier, inContext: appDelegate.managedObjectContext)
if brewery == nil {
brewery = NSEntityDescription.insertNewObjectForEntityForName("Brewery", inManagedObjectContext: appDelegate.managedObjectContext) as? Brewery
print("Adding new brewery: " + (breweryJSON["name"] as? String ?? "No name") + "\n")
}
if let 🏬 = brewery {
🏬.identifier = identifier
🏬.name = breweryJSON["name"] as? String ?? "No Name"
}
breweryIDs.append(Int(identifier))
}
}
let fetchRemovedBreweries = NSFetchRequest(entityName: "Brewery")
fetchRemovedBreweries.predicate = NSPredicate(format: "NOT (identifier IN %@)", breweryIDs)
if let array = try? appDelegate.managedObjectContext.executeFetchRequest(fetchRemovedBreweries), results = array as? [NSManagedObject] {
if results.count > 0 {
print("Removing \(results.count) breweries")
for brewery in results {
appDelegate.managedObjectContext.deleteObject(brewery)
}
}
}
appDelegate.saveContext()
}
class func breweryForIdentifier(identifier: Int32, inContext context: NSManagedObjectContext) -> Brewery? {
let request = NSFetchRequest(entityName: "Brewery")
request.predicate = NSPredicate(format: "identifier == %d", identifier)
request.fetchLimit = 1
if let result = (try? context.executeFetchRequest(request)) as? [Brewery] {
if result.count > 0 {
return result[0]
}
}
return nil
}
}
|
apache-2.0
|
bc87acb38c8835c2980a59e2558687e0
| 34.574257 | 182 | 0.582243 | 4.87517 | false | false | false | false |
fespinoza/linked-ideas-osx
|
LinkedIdeas/Models/Document.swift
|
1
|
6536
|
//
// Document.swift
// LinkedIdeas
//
// Created by Felipe Espinoza Castillo on 02/11/15.
// Copyright © 2015 Felipe Espinoza Dev. All rights reserved.
//
import Cocoa
import LinkedIdeas_Shared
public class Document: NSDocument {
var documentData = DocumentData()
var observer: DocumentObserver?
public var concepts: [Concept] = [Concept]() {
willSet {
for concept in concepts {
stopObserving(concept: concept)
}
}
didSet {
for concept in concepts {
startObserving(concept: concept)
}
}
}
public var links: [Link] = [Link]() {
willSet {
for link in links {
stopObserving(link: link)
}
}
didSet {
for link in links {
startObserving(link: link)
}
}
}
public var rect: CGRect {
let minX = concepts.map { $0.area.minX }.min() ?? 0
let minY = concepts.map { $0.area.minY }.min() ?? 0
let maxX = concepts.map { $0.area.maxX }.max() ?? 800
let maxY = concepts.map { $0.area.maxY }.max() ?? 600
return CGRect(
point1: CGPoint(x: minX, y: minY),
point2: CGPoint(x: maxX, y: maxY)
)
}
private var KVOContext: Int = 0
override public func makeWindowControllers() {
let storyboard = NSStoryboard(name: "Main", bundle: nil)
if let windowController = storyboard.instantiateController(
withIdentifier: "Document Window Controller"
) as? WindowController {
self.addWindowController(windowController)
}
}
override public class var autosavesInPlace: Bool {
return true
}
override public func data(ofType typeName: String) throws -> Data {
Swift.print("write data!")
NSKeyedArchiver.setClassName("LinkedIdeas.DocumentData", for: DocumentData.self)
NSKeyedArchiver.setClassName("LinkedIdeas.Concept", for: Concept.self)
NSKeyedArchiver.setClassName("LinkedIdeas.Link", for: Link.self)
let writeDocumentData = DocumentData(concepts: self.concepts, links: self.links)
return NSKeyedArchiver.archivedData(withRootObject: writeDocumentData)
}
override public func read(from data: Data, ofType typeName: String) throws {
Swift.print("Document: -read")
NSKeyedUnarchiver.setClass(DocumentData.self, forClassName: "LinkedIdeas.DocumentData")
NSKeyedUnarchiver.setClass(Concept.self, forClassName: "LinkedIdeas.Concept")
NSKeyedUnarchiver.setClass(Link.self, forClassName: "LinkedIdeas.Link")
guard let documentData = NSKeyedUnarchiver.unarchiveObject(with: data) as? DocumentData else {
return
}
self.documentData = documentData
self.concepts = documentData.concepts
self.links = documentData.links
}
// MARK: - KeyValue Observing
func startObserving(concept: Concept) {
concept.addObserver(self, forKeyPath: Concept.attributedStringValuePath, options: .old, context: &KVOContext)
}
func stopObserving(concept: Concept) {
concept.removeObserver(self, forKeyPath: Concept.attributedStringValuePath, context: &KVOContext)
}
func startObserving(link: Link) {
link.addObserver(self, forKeyPath: Link.colorPath, options: .old, context: &KVOContext)
link.addObserver(self, forKeyPath: Link.attributedStringValuePath, options: .old, context: &KVOContext)
}
func stopObserving(link: Link) {
link.removeObserver(self, forKeyPath: Link.colorPath, context: &KVOContext)
link.removeObserver(self, forKeyPath: Link.attributedStringValuePath, context: &KVOContext)
}
// swiftlint:disable:next block_based_kvo
override public func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?
) {
guard context == &KVOContext else {
// If the context does not match, this message
// must be intended for our superclass.
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
if let keyPath = keyPath, let object = object, let change = change {
var oldValue: Any? = change[NSKeyValueChangeKey.oldKey]
if oldValue is NSNull {
oldValue = nil
}
if let object = object as? NSObject {
undoManager?.registerUndo(withTarget: (object), handler: { (object) in
object.setValue(oldValue, forKey: keyPath)
})
}
switch object {
case let concept as Concept:
observer?.documentChanged(withElement: concept)
case let link as Link:
observer?.documentChanged(withElement: link)
default:
break
}
}
}
}
extension Document: LinkedIdeasDocument {
@objc func save(concept: Concept) {
concepts.append(concept)
undoManager?.registerUndo(
withTarget: self,
selector: #selector(Document.remove(concept:)),
object: concept)
observer?.documentChanged(withElement: concept)
}
@objc func remove(concept: Concept) {
concepts.remove(at: concepts.index(of: concept)!)
undoManager?.registerUndo(
withTarget: self,
selector: #selector(Document.save(concept:)),
object: concept)
observer?.documentChanged(withElement: concept)
}
@objc func save(link: Link) {
links.append(link)
undoManager?.registerUndo(
withTarget: self,
selector: #selector(Document.remove(link:)),
object: link)
observer?.documentChanged(withElement: link)
}
@objc func remove(link: Link) {
links.remove(at: links.index(of: link)!)
undoManager?.registerUndo(
withTarget: self,
selector: #selector(Document.save(link:)),
object: link)
observer?.documentChanged(withElement: link)
}
func move(concept: Concept, toPoint: CGPoint) {
Swift.print("move concept \(concept) toPoint: \(toPoint)")
let originalPoint = concept.centerPoint
concept.centerPoint = toPoint
observer?.documentChanged(withElement: concept)
undoManager?.registerUndo(withTarget: self, handler: { (object) in
object.move(concept: concept, toPoint: originalPoint)
})
}
}
extension Document: CanvasViewDataSource {
public func drawableElements(forRect: CGRect) -> [DrawableElement] {
return drawableElements
}
public var drawableElements: [DrawableElement] {
var elements: [DrawableElement] = []
elements += concepts.map {
DrawableConcept(concept: $0) as DrawableElement
}
elements += links.map {
DrawableLink(link: $0) as DrawableElement
}
return elements
}
}
|
mit
|
0529623ec1d6222e46d6c379e70d60f8
| 28.840183 | 113 | 0.67697 | 4.310686 | false | false | false | false |
Tueno/IconHUD
|
IconHUD/ConsoleIO.swift
|
1
|
2860
|
//
// ConsoleIO.swift
// Summaricon
//
// Created by tueno on 2017/04/24.
// Copyright © 2017年 tueno Ueno. All rights reserved.
//
import Foundation
final class ConsoleIO {
// MARK: Input
class func optionsInCommandLineArguments() -> [OptionType] {
let arguments = CommandLine.arguments
let containingOptions = OptionType.allValues
.filter { (option) -> Bool in
return option.values
.filter({ (value) -> Bool in
return arguments.contains(value)
})
.count > 0
}
return containingOptions
}
class func optionArgument(option: OptionType) -> String? {
let arguments = CommandLine.arguments
let index = arguments
.enumerated()
.filter { (index: Int, argument: String) -> Bool in
return option.values.contains(argument)
}
.first?
.offset
guard let i = index, i+1 < arguments.count, !arguments[i+1].hasPrefix("-") else {
return nil
}
return arguments[i+1]
}
class func environmentVariable(key: EnvironmentVariable) -> String {
return ProcessInfo().environment[key.rawValue] ?? ""
}
class var executableName: String {
get {
return CommandLine.arguments.first!
.components(separatedBy: "/")
.last!
}
}
// MARK: Output
class func printVersion() {
print(IconConverter.Version)
}
class func printUsage() {
print("Usage:")
print("")
print(" Add the 'Run Scripts' phase to after 'Copy Bundle Resources' phase and then add the line below to 'Run Scripts' phase.")
print("")
print(" ----------")
print(" \(executableName)")
print(" ----------")
print("")
print("Options:")
print("")
OptionType.allValues
.forEach { (option) in
let argumentsStr = option.valuesToPrint
print(" [\(argumentsStr)]\(option.usage)")
}
printNotice()
}
class func printNotice() {
print("")
print("*** IMPORTANT ***")
print("")
print("1. \(executableName) uses 'Build Configurations' name of Xcode project to detect relase build. (There are 'Debug' and 'Release' values as default.)")
print(" So if you change Release BuildConfig name, \(executableName) will process icon even if you want to build for release.")
print("")
print("2. Don't forget to place 'Run Scripts' phase that contains 'iconhud' on after 'Copy Bundle Resources' phase.")
print("")
print("*****************")
}
}
|
mit
|
f04980869da6228df1c5f9cfebf1ed86
| 30.054348 | 164 | 0.531677 | 4.858844 | false | false | false | false |
bradhilton/Table
|
Table/UIView.swift
|
1
|
2913
|
//
// UIView.swift
// Table
//
// Created by Bradley Hilton on 3/28/18.
// Copyright © 2018 Brad Hilton. All rights reserved.
//
extension UIView {
var firstResponder: UIView? {
guard !isFirstResponder else { return self }
for subview in subviews {
if let firstResponder = subview.firstResponder {
return firstResponder
}
}
return nil
}
var isVisible: Bool {
return window != nil && layer.isVisible
}
}
extension CALayer {
fileprivate var isVisible: Bool {
return presentation()?.hasVisibleBoundsAndOpacity ?? hasVisibleBoundsAndOpacity
}
private var hasVisibleBoundsAndOpacity: Bool {
return bounds.width > 0 && bounds.height > 0 && opacity > 0
}
}
extension NSObjectProtocol where Self : UITextField {
public var inputView: View? {
get {
return storage[\.inputView]
}
set {
storage[\.inputView] = newValue
inputView = newValue?.view(reusing: inputView)
}
}
public var inputAccessoryView: View? {
get {
return storage[\.inputAccessoryView]
}
set {
storage[\.inputAccessoryView] = newValue
inputAccessoryView = newValue?.view(reusing: inputAccessoryView)
}
}
}
extension UIView {
var breadthFirstSubviews: AnySequence<UIView> {
var index = 0
var subviews = self.subviews
return AnySequence {
return AnyIterator {
guard index != subviews.endIndex else { return nil }
let subview = subviews[index]
subviews.append(contentsOf: subview.subviews)
index += 1
return subview
}
}
}
public func firstSubview<T : UIView>(class: T.Type = T.self, key: AnyHashable? = nil) -> T? {
return breadthFirstSubviews.first { subview in
guard
let subview = subview as? T,
key == nil || subview.key == key,
subview.alpha > 0,
!subview.isHidden
else { return nil }
return subview
}
}
}
func breadthFirstSubviews(of view: UIView) -> AnySequence<UIView> {
return AnySequence(
sequence(state: AnySequence(view.subviews)) { (state: inout AnySequence<UIView>) -> AnySequence<UIView>? in
guard state.underestimatedCount > 0 || state.makeIterator().next() != nil else { return nil }
defer {
state = AnySequence(
[
state,
AnySequence(state.lazy.flatMap { $0.subviews })
].lazy.flatMap { $0 }
)
}
return state
}.lazy.flatMap { $0 }
)
}
|
mit
|
9435587209c03a2c0f6d1a4204520fb3
| 25.962963 | 115 | 0.53331 | 5.090909 | false | false | false | false |
xmartlabs/Eureka
|
Source/Rows/SwitchRow.swift
|
1
|
2691
|
// SwitchRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
// MARK: SwitchCell
open class SwitchCell: Cell<Bool>, CellType {
@IBOutlet public weak var switchControl: UISwitch!
required public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let switchC = UISwitch()
switchControl = switchC
accessoryView = switchControl
editingAccessoryView = accessoryView
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func setup() {
super.setup()
selectionStyle = .none
switchControl.addTarget(self, action: #selector(SwitchCell.valueChanged), for: .valueChanged)
}
deinit {
switchControl?.removeTarget(self, action: nil, for: .allEvents)
}
open override func update() {
super.update()
switchControl.isOn = row.value ?? false
switchControl.isEnabled = !row.isDisabled
}
@objc (switchValueDidChange) func valueChanged() {
row.value = switchControl?.isOn ?? false
}
}
// MARK: SwitchRow
open class _SwitchRow: Row<SwitchCell> {
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
}
}
/// Boolean row that has a UISwitch as accessoryType
public final class SwitchRow: _SwitchRow, RowType {
required public init(tag: String?) {
super.init(tag: tag)
}
}
|
mit
|
a17e2ed077cce7e8e4b4694961e3ef4a
| 32.222222 | 101 | 0.701226 | 4.568761 | false | false | false | false |
SimonFairbairn/Stormcloud
|
Tests/StormcloudTests/StormcloudTestsBaseClass.swift
|
1
|
5847
|
//
// StormcloudTestsBaseClass.swift
// Stormcloud
//
// Created by Simon Fairbairn on 21/10/2015.
// Copyright © 2015 Simon Fairbairn. All rights reserved.
//
import XCTest
import Stormcloud
class StormcloudTestsBaseClass: XCTestCase {
enum ExpectationDescription : String {
case positionTestAddItems
case positionTestAddItems2
case addTestBackup
case addTestMetadataUpdates
case delegateTestCorrectCounts
case delegateTestThreeItems
case addThenFindTest
case maximumLimitsTestDidLoad
case restoringTest
case coreDataCreatesFileTest
case imageFileReady
case imagesReady
case coreDataRestore
case coreDataWeirdStrings
case waitForFilesToBeReady
}
var stormcloudExpectation: XCTestExpectation?
var fileExtension : String = "json"
var docsURL : URL?
var resourcesURL : URL?
let futureFilename = "2020-10-19 16-47-44--iPhone--1E7C8A50-FDDC-4904-AD64-B192CF3DD157"
let pastFilename = "2014-10-18 16-47-44--iPhone--1E7C8A50-FDDC-4904-AD64-B192CF3DD157"
override func setUp() {
super.setUp()
docsURL = FileManager.default.temporaryDirectory
let thisSourceFile = URL(fileURLWithPath: #file)
resourcesURL = thisSourceFile.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Resources", isDirectory: true)
deleteAllFiles()
}
override func tearDown() {
deleteAllFiles()
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func deleteAllFiles() {
guard let docsDir = docsURL else {
XCTFail("Couldn't get docs URL")
return
}
var docs : [URL] = []
do {
docs = try FileManager.default.contentsOfDirectory(at: docsDir, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions())
} catch {
fatalError("couldn't search path \(docsURL!): \(error)")
}
for url in docs {
do {
try FileManager.default.removeItem(at: url)
print("Deleting \(url)")
} catch {
fatalError("Couldn't delete item: \(error)")
}
}
}
func copyItemWith( filename: String, fileExtension : String ) {
let fullName = filename + "." + fileExtension
guard let resource = resourcesURL?.appendingPathComponent(fullName) else {
XCTFail("Failed to get resourcesURL.")
return
}
guard let docsURL = self.docsURL?.appendingPathComponent(fullName) else {
XCTFail("Failed to get temporary directory.")
return
}
do {
try FileManager.default.copyItem(at: resource, to: docsURL)
} catch let error as NSError {
XCTFail("Failed to copy past item \(error.localizedDescription)")
}
}
func copyItems(extra : Bool = false) {
self.copyItemWith(filename: self.pastFilename, fileExtension: self.fileExtension)
self.copyItemWith(filename: self.futureFilename, fileExtension: self.fileExtension)
if extra {
self.copyItemWith(filename: "fragment", fileExtension: self.fileExtension)
}
}
func listItemsAtURL() -> [URL] {
var jsonDocs : [URL] = []
if let docsURL = docsURL {
var docs : [URL] = []
do {
docs = try FileManager.default.contentsOfDirectory(at: docsURL, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions())
} catch {
print("couldn't search path \(docsURL)")
}
for url in docs {
if url.pathExtension == fileExtension {
jsonDocs.append(url)
}
}
}
return jsonDocs
}
func waitForFiles( _ stormcloud : Stormcloud ) {
if !stormcloud.fileListLoaded {
stormcloudExpectation = self.expectation(description: ExpectationDescription.waitForFilesToBeReady.rawValue)
waitForExpectations(timeout: 15, handler: nil)
}
}
}
extension StormcloudTestsBaseClass : StormcloudDelegate {
func stormcloudFileListDidLoad(_ stormcloud: Stormcloud) {
guard let desc = stormcloudExpectation?.expectationDescription else {
return
}
guard let expectationDescription = ExpectationDescription(rawValue:desc) else {
XCTFail("Incorrect description")
return
}
switch expectationDescription {
case .positionTestAddItems:
stormcloudExpectation?.fulfill()
case .waitForFilesToBeReady, .maximumLimitsTestDidLoad,
.restoringTest, .coreDataCreatesFileTest, .imagesReady, .coreDataRestore, .coreDataWeirdStrings:
stormcloudExpectation?.fulfill()
default:
break
}
}
func metadataDidUpdate(_ metadata: StormcloudMetadata, for type: StormcloudDocumentType) {
}
func metadataListDidAddItemsAt(_ addedItems: IndexSet?, andDeletedItemsAt deletedItems: IndexSet?, for type: StormcloudDocumentType) {
guard let desc = stormcloudExpectation?.expectationDescription else {
return
}
guard let expectationDescription = ExpectationDescription(rawValue:desc) else {
XCTFail("Incorrect description")
return
}
switch expectationDescription {
case .addTestBackup:
if let hasItems = addedItems, hasItems.count == 1 {
stormcloudExpectation?.fulfill()
}
case .addTestMetadataUpdates:
if addedItems == nil && deletedItems == nil {
stormcloudExpectation?.fulfill()
}
case .delegateTestCorrectCounts:
if let hasItems = addedItems, hasItems.count == 2 {
stormcloudExpectation?.fulfill()
}
case .delegateTestThreeItems, .imageFileReady:
if let hasItems = addedItems, hasItems.count == 1 {
stormcloudExpectation?.fulfill()
}
case .addThenFindTest:
if let hasItems = addedItems, hasItems.count == 2 {
stormcloudExpectation?.fulfill()
}
default:
break
}
}
public func metadataListDidChange(_ manager: Stormcloud) {
print("List did change")
}
}
|
mit
|
0845e2852971b06f8aaa04c51f9c9b4f
| 26.706161 | 170 | 0.7039 | 4.073868 | false | true | false | false |
lovehhf/edx-app-ios
|
Source/Stream.swift
|
1
|
17167
|
//
// Stream.swift
// edX
//
// Created by Akiva Leffert on 6/15/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
// Bookkeeping class for a listener of a stream
private class Listener<A> : Removable, Equatable, Printable {
private var removeAction : (Listener<A> -> Void)?
private var action : (Result<A> -> Void)?
init(action : Result<A> -> Void, removeAction : Listener<A> -> Void) {
self.action = action
self.removeAction = removeAction
}
func remove() {
self.removeAction?(self)
self.removeAction = nil
self.action = nil
}
var description : String {
let address = unsafeBitCast(self, UnsafePointer<Void>.self)
return NSString(format: "<%@: %p>", "\(self.dynamicType)", address) as String
}
}
private func == <A>(lhs : Listener<A>, rhs : Listener<A>) -> Bool {
/// We want to use pointer equality for equality since the main thing
/// we care about for listeners is are they the same instance so we can remove them
return lhs === rhs
}
public protocol StreamDependency : class, Printable {
var active : Bool {get}
}
// MARK: Reading Streams
// This should really be a protocol with Sink a concrete instantiation of that protocol
// But unfortunately Swift doesn't currently support generic protocols
// Revisit this if it ever does
private let backgroundQueue = NSOperationQueue()
/// A stream of values and errors. Note that, like all objects, a stream will get deallocated if it has no references.
public class Stream<A> : StreamDependency {
private let dependencies : [StreamDependency]
private(set) var lastResult : Result<A>?
public var description : String {
let deps = join(", ", self.dependencies.map({ $0.description }))
let ls = join(", ", self.listeners.map({ $0.description }))
let address = unsafeBitCast(self, UnsafePointer<Void>.self)
return NSString(format: "<%@: %p, deps = {%@}, listeners = {%@}>", "\(self.dynamicType)", address, deps, ls) as String
}
private var baseActive : Bool {
return false
}
public var active : Bool {
return reduce(dependencies, baseActive, {$0 || $1.active} )
}
public var value : A? {
return lastResult?.value
}
public var error : NSError? {
return lastResult?.error
}
private var listeners : [Listener<A>] = []
/// Make a new stream.
///
/// :param: dependencies A list of objects that this stream will retain.
/// Typically this is a stream or streams that this object is listening to so that
/// they don't get deallocated.
private init(dependencies : [StreamDependency]) {
self.dependencies = dependencies
}
public convenience init() {
self.init(dependencies : [])
}
/// Seed a new stream with a constant value.
///
/// :param: value The initial value of the stream.
public convenience init(value : A) {
self.init()
self.lastResult = Success(value)
}
/// Seed a new stream with a constant error.
///
/// :param: error The initial error for the stream
public convenience init(error : NSError) {
self.init()
self.lastResult = Failure(error)
}
private func joinHandlers<A>(#success : A -> Void, failure : NSError -> Void, finally : (Void -> Void)?) -> Result<A> -> Void {
return {
switch $0 {
case let .Success(v):
success(v.value)
case let .Failure(e):
failure(e)
}
finally?()
}
}
/// Add a listener to a stream.
///
/// :param: owner The listener will automatically be removed when owner gets deallocated.
/// :param: fireIfLoaded If true then this will fire the listener immediately if the signal has already received a value.
/// :param: action The action to fire when the stream receives a result.
public func listen(owner : NSObject, fireIfAlreadyLoaded : Bool = true, action : Result<A> -> Void) -> Removable {
let listener = Listener(action: action) {[weak self] (listener : Listener<A>) in
if let listeners = self?.listeners, index = find(listeners, listener) {
self?.listeners.removeAtIndex(index)
}
}
listeners.append(listener)
let removable = owner.oex_performActionOnDealloc {
listener.remove()
}
if let value = self.value where fireIfAlreadyLoaded {
action(Success(value))
}
else if let error = self.error where fireIfAlreadyLoaded {
action(Failure(error))
}
return BlockRemovable {
removable.remove()
listener.remove()
}
}
/// Add a listener to a stream.
///
/// :param: owner The listener will automatically be removed when owner gets deallocated.
/// :param: fireIfLoaded If true then this will fire the listener immediately if the signal has already received a value. If false the listener won't fire until a new result is supplied to the stream.
/// :param: success The action to fire when the stream receives a Success result.
/// :param: failure The action to fire when the stream receives a Failure result.
/// :param: finally An action that will be executed after both the success and failure actions
public func listen(owner : NSObject, fireIfAlreadyLoaded : Bool = true, success : A -> Void, failure : NSError -> Void, finally : (Void -> Void)? = nil) -> Removable {
return listen(owner, fireIfAlreadyLoaded: fireIfAlreadyLoaded, action: joinHandlers(success:success, failure:failure, finally:finally))
}
/// Add a listener to a stream. When the listener fires it will be removed automatically.
///
/// :param: owner The listener will automatically be removed when owner gets deallocated.
/// :param: fireIfLoaded If true then this will fire the listener immediately if the signal has already received a value. If false the listener won't fire until a new result is supplied to the stream.
/// :param: success The action to fire when the stream receives a Success result.
/// :param: success The action to fire when the stream receives a Failure result.
/// :param: finally An action that will be executed after both the success and failure actions
public func listenOnce(owner : NSObject, fireIfAlreadyLoaded : Bool = true, success : A -> Void, failure : NSError -> Void, finally : (Void -> Void)? = nil) -> Removable {
return listenOnce(owner, fireIfAlreadyLoaded: fireIfAlreadyLoaded, action : joinHandlers(success:success, failure:failure, finally:finally))
}
public func listenOnce(owner : NSObject, fireIfAlreadyLoaded : Bool = true, action : Result<A> -> Void) -> Removable {
let removable = listen(owner, fireIfAlreadyLoaded: fireIfAlreadyLoaded, action : action)
let followup = listen(owner, fireIfAlreadyLoaded: fireIfAlreadyLoaded,
action: {_ in
removable.remove()
}
)
return BlockRemovable {
removable.remove()
followup.remove()
}
}
/// :returns: A filtered stream based on the receiver that will only fire the first time a success value is sent. Use this if you want to capture a value and *not* update when the next one comes in.
public func firstSuccess() -> Stream<A> {
let sink = Sink<A>(dependencies: [self])
listen(sink.token) {[weak sink] result in
if sink?.lastResult?.isFailure ?? true {
sink?.send(result)
}
}
return sink
}
/// :returns: A filtered stream based on the receiver that won't fire on errors after a value is loaded. It will fire if a new value comes through after a value is already loaded.
public func dropFailuresAfterSuccess() -> Stream<A> {
let sink = Sink<A>(dependencies: [self])
listen(sink.token) {[weak sink] result in
if sink?.lastResult == nil || result.isSuccess {
sink?.send(result)
}
}
return sink
}
/// Transforms a stream into a new stream. Failure results will pass through untouched.
public func map<B>(f : A -> B) -> Stream<B> {
let sink = Sink<B>(dependencies: [self])
listen(sink.token) {[weak sink] result in
sink?.send(result.map(f))
}
return sink
}
/// Transforms a stream into a new stream.
public func flatMap<B>(f : A -> Result<B>) -> Stream<B> {
let sink = Sink<B>(dependencies: [self])
listen(sink.token) {[weak sink] current in
let next = current.flatMap(f)
sink?.send(next)
}
return sink
}
/// :returns: A stream that is automatically backed by a new stream whenever the receiver fires.
public func transform<B>(f : A -> Stream<B>) -> Stream<B> {
let backed = BackedStream<B>(dependencies: [self])
listen(backed.token) {[weak backed] current in
current.ifSuccess {
backed?.backWithStream(f($0))
}
}
return backed
}
/// Stream that calls a cancelation action if the stream gets deallocated.
/// Use if you want to perform an action once no one is listening to a stream
/// for example, an expensive operation or a network request
/// :param: cancel The action to perform when this stream gets deallocated.
public func autoCancel(cancelAction : Removable) -> Stream<A> {
let sink = CancellingSink<A>(dependencies : [self], removable: cancelAction)
listen(sink.token) {[weak sink] current in
sink?.send(current)
}
return sink
}
/// Extends the lifetime of a stream until the first result received.
///
/// :param: completion A completion that fires when the stream fires
public func extendLifetimeUntilFirstResult(completion : Result<A> -> Void) {
backgroundQueue.addOperation(StreamWaitOperation(stream: self, completion: completion))
}
/// Constructs a stream that returns values from the receiver, but will return any values from *stream* until
/// the first value is sent to the receiver. For example, if you're implementing a network cache, you want to
/// return the value saved to disk, but only if the network request hasn't finished yet.
public func cachedByStream(cacheStream : Stream<A>) -> Stream<A> {
let sink = Sink<A>(dependencies: [cacheStream, self])
listen(sink.token) {[weak sink] current in
sink?.send(current)
}
cacheStream.listen(sink.token) {[weak sink, weak self] current in
if self?.lastResult == nil {
sink?.send(current)
}
}
return sink
}
}
// MARK: Writing Streams
/// A writable stream.
/// Sink is a separate type from stream to make it easy to control who can write to the stream.
/// If you need a writeble stream, typically you'll use a Sink internally,
/// but upcast to stream outside of the relevant abstraction boundary
public class Sink<A> : Stream<A> {
// This gives us an NSObject with the same lifetime as our
// sink so that we can associate a removal action for when the sink gets deallocated
private let token = NSObject()
private var open : Bool
override private init(dependencies : [StreamDependency]) {
// Streams with dependencies typically want to use their dependencies' lifetimes exclusively.
// Streams with no dependencies need to manage their own lifetime
open = dependencies.count == 0
super.init(dependencies : dependencies)
}
override private var baseActive : Bool {
return open
}
public func send(value : A) {
send(Success(value))
}
public func send(error : NSError) {
send(Failure(error))
}
public func send(result : Result<A>) {
self.lastResult = result
for listener in listeners {
listener.action?(result)
}
}
// Mark the sink as inactive. Note that closed streams with active dependencies may still be active
public func close() {
open = false
}
}
// Sink that automatically cancels an operation when it deinits.
private class CancellingSink<A> : Sink<A> {
let removable : Removable
init(dependencies : [StreamDependency], removable : Removable) {
self.removable = removable
super.init(dependencies : dependencies)
}
deinit {
removable.remove()
}
}
/// A stream that is rewirable. This is shorthand for the pattern of having a variable
/// representing an optional stream that is imperatively updated.
/// Using a BackedStream lets you set listeners once and always have a
/// non-optional value to pass around that others can receive values from.
public class BackedStream<A> : Stream<A> {
private let token = NSObject()
private var backing : StreamDependency?
private var removeBackingAction : Removable?
override private init(dependencies : [StreamDependency]) {
super.init(dependencies : dependencies)
}
override private var baseActive : Bool {
return backing?.active ?? false
}
/// Removes the old backing and adds a new one. When the backing stream fires so will this one.
/// Think of this as rewiring a pipe from an old source to a new one.
public func backWithStream(backing : Stream<A>) {
removeBacking()
self.backing = backing
self.removeBackingAction = backing.listen(self.token) {[weak self] result in
self?.send(result)
}
}
public func removeBacking() {
removeBackingAction?.remove()
removeBackingAction = nil
backing = nil
}
var hasBacking : Bool {
return backing != nil
}
/// Send a new value to the stream.
private func send(result : Result<A>) {
self.lastResult = result
for listener in listeners {
listener.action?(result)
}
}
}
// MARK: Combining Streams
// This is different from an option, since you can't nest nils,
// so an A?? could resolve to nil and we wouldn't be able to detect that case
private enum Resolution<A> {
case Unresolved
case Resolved(Result<A>)
}
/// Combine a pair of streams into a stream of pairs.
/// The stream will both substreams have fired.
/// After the initial load, the stream will update whenever either of the substreams updates
public func joinStreams<T, U>(t : Stream<T>, u: Stream<U>) -> Stream<(T, U)> {
let sink = Sink<(T, U)>(dependencies: [t, u])
var tBox = MutableBox<Resolution<T>>(.Unresolved)
var uBox = MutableBox<Resolution<U>>(.Unresolved)
t.listen(sink.token) {[weak sink] tValue in
tBox.value = .Resolved(tValue)
switch uBox.value {
case let .Resolved(uValue):
sink?.send(join(tValue, uValue))
case .Unresolved:
break
}
}
u.listen(sink.token) {[weak sink] uValue in
uBox.value = .Resolved(uValue)
switch tBox.value {
case let .Resolved(tValue):
sink?.send(join(tValue, uValue))
case .Unresolved:
break
}
}
return sink
}
/// Combine an array of streams into a stream of arrays.
/// The stream will not fire until all substreams have fired.
/// After the initial load, the stream will update whenever any of the substreams updates.
public func joinStreams<T>(streams : [Stream<T>]) -> Stream<[T]> {
// This should be unnecesary since [Stream<T>] safely upcasts to [StreamDependency]
// but in practice it causes a runtime crash as of Swift 1.2.
// Explicitly mapping it prevents the crash
let dependencies = streams.map {x -> StreamDependency in x }
let sink = Sink<[T]>(dependencies : dependencies)
let pairs = streams.map {(stream : Stream<T>) -> (box : MutableBox<Resolution<T>>, stream : Stream<T>) in
let box = MutableBox<Resolution<T>>(.Unresolved)
return (box : box, stream : stream)
}
let boxes = pairs.map { return $0.box }
for (box, stream) in pairs {
stream.listen(sink.token) {[weak sink] value in
box.value = .Resolved(value)
let results = boxes.mapOrFailIfNil {(box : MutableBox<Resolution<T>>) -> Result<T>? in
switch box.value {
case .Unresolved: return nil
case let .Resolved(v): return v
}
}
if let r = results {
sink?.send(join(r))
}
}
}
if streams.count == 0 {
sink.send(Success([]))
}
return sink
}
|
apache-2.0
|
a3006c76d0387c35927fc30b5af5740f
| 35.603412 | 204 | 0.622823 | 4.58888 | false | false | false | false |
fattomhk/HLLocalizeHelper
|
HLLocalizeHelper/HLLocalizeHelper.swift
|
1
|
2277
|
//
// HLLocalizeHelper.swift
//
// Created by Horst Leung on 26/6/15.
// Copyright (c) 2015 Horst Leung. All rights reserved.
// Version 0.1
import UIKit
let HLLanguageDidSetKey: String = "hk.com.vdelegate.LanguageDidChange"
let HLKeyForSavingLocale: String = "DEFAULTS_KEY_LANGUAGE_CODE";
class HLLocalizeHelper: NSObject
{
class var sharedInstance: HLLocalizeHelper {
struct Static {
static var instance: HLLocalizeHelper?;
static var token: dispatch_once_t = 0;
}
dispatch_once(&Static.token) {
Static.instance = HLLocalizeHelper();
}
return Static.instance!;
}
//MARK: Class Functions
class func getSystemLanguage()->String
{
return NSLocale.currentLocale().localeIdentifier;
}
class func localizedString(key: NSString, stringFileName: String? = nil)->String
{
return HLLocalizeHelper.sharedInstance.localizedString(key, stringFileName: stringFileName);
}
class func setLanguage(languageCode: String)
{
println("Language becomes: \(languageCode)");
NSUserDefaults.standardUserDefaults().setObject(languageCode, forKey: HLKeyForSavingLocale);
NSNotificationCenter.defaultCenter().postNotificationName(HLLanguageDidSetKey, object: self);
}
//MARK: Private Functions
private func localizedString(key: NSString, stringFileName: String? = nil)->String
{
var languageCode = NSUserDefaults.standardUserDefaults().stringForKey(HLKeyForSavingLocale);
if(languageCode == nil){
languageCode = HLLocalizeHelper.getSystemLanguage();
}
var Languagebundle = NSBundle.mainBundle(); //if language is not support, use the main one.
// Get language bundle in the locale.
let bundlePath = NSBundle.mainBundle().pathForResource(languageCode as String?, ofType: "lproj");
if(bundlePath != nil){
Languagebundle = NSBundle(path: bundlePath!)!;
}
// Get the translated string using the language bundle.
let translatedString = Languagebundle.localizedStringForKey(key as String, value:"", table: stringFileName);
return translatedString;
}
}
|
mit
|
2569e80b205b483c2c5e1b03c21139c1
| 33 | 116 | 0.665788 | 4.928571 | false | false | false | false |
nguyenantinhbk77/practice-swift
|
CoreData/SuperDB/SuperDB/UIColorPicker.swift
|
2
|
3329
|
//
// UIControlPicker.swift
// SuperDB
//
// Created by Domenico on 02/06/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
import QuartzCore
let kTopBackgroundColor = UIColor(red: 0.98, green: 0.98, blue: 0.98, alpha: 1)
let kBottomBackgroundColor = UIColor(red: 0.79, green: 0.79, blue: 0.79, alpha: 1)
class UIColorPicker: UIControl {
var _color: UIColor!
private var _redSlider: UISlider!
private var _greenSlider: UISlider!
private var _blueSlider: UISlider!
private var _alphaSlider: UISlider!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
labelWithFrame(CGRectMake(20, 40, 60, 24), text: "Red")
labelWithFrame(CGRectMake(20, 80, 60, 24), text: "Green")
labelWithFrame(CGRectMake(20, 120, 60, 24), text: "Blue")
labelWithFrame(CGRectMake(20, 160, 60, 24), text: "Alpha")
let theFunc = "sliderChanged:"
self._redSlider = createSliderWithAction(CGRectMake(100, 40, 190, 24), function: theFunc)
self._greenSlider = createSliderWithAction(CGRectMake(100, 80, 190, 24), function: theFunc)
self._blueSlider = createSliderWithAction(CGRectMake(100, 120, 190, 24), function: theFunc)
self._alphaSlider = createSliderWithAction(CGRectMake(100, 160, 190, 24), function: theFunc)
}
private func labelWithFrame(frame: CGRect, text: String){
var label = UILabel(frame: frame)
label.userInteractionEnabled = false
label.backgroundColor = UIColor.clearColor()
label.font = UIFont.boldSystemFontOfSize(UIFont.systemFontSize())
label.textAlignment = NSTextAlignment.Right
label.textColor = UIColor.darkTextColor()
label.text = text
self.addSubview(label)
}
func createSliderWithAction(frame: CGRect, function: String)->UISlider{
var _slider = UISlider(frame: frame)
_slider.addTarget(self, action: Selector(function), forControlEvents: .ValueChanged)
self.addSubview(_slider)
return _slider
}
override func drawRect(rect: CGRect) {
var gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = [kTopBackgroundColor.CGColor, kBottomBackgroundColor.CGColor]
self.layer.insertSublayer(gradient, atIndex: 0)
}
//MARK: - Property Overrides
var color: UIColor{
get { return _color}
set {
_color = newValue
let components = CGColorGetComponents(_color.CGColor)
_redSlider.setValue(Float(components[0]), animated: true)
_greenSlider.setValue(Float(components[1]), animated: true)
_blueSlider.setValue(Float(components[2]), animated: true)
_alphaSlider.setValue(Float(components[3]), animated: true)
}
}
//MARK: - (Private) Instance Methods
@IBAction func sliderChanged(sender: AnyObject){
color = UIColor(red: CGFloat(_redSlider.value),
green: CGFloat(_greenSlider.value),
blue: CGFloat(_blueSlider.value),
alpha: CGFloat(_alphaSlider.value))
self.sendActionsForControlEvents(.ValueChanged)
}
}
|
mit
|
ceb01e304989d7458c6bee6753d9987c
| 35.988889 | 100 | 0.646741 | 4.289948 | false | false | false | false |
18775134221/SwiftBase
|
SwiftTest/SwiftTest/Classes/tools/Extention/UITextView-Extension.swift
|
2
|
963
|
//
// UITextView-Extension.swift
// SwiftTest
//
// Created by MAC on 2016/12/15.
// Copyright © 2016年 MAC. All rights reserved.
//
import Foundation
import UIKit
extension UITextView {
/*
* 便利构造器
* frame
* placeHolderText 提示语
* placeColor 提示语的颜色
* fontSize 提示语的字体大小
*/
convenience init(frame: CGRect, placeHolderText: String? = "", placeColor: UIColor? = UIColor.lightGray, fontSize: CGFloat? = 15.0) {
let textView = UITextView().then {
$0.frame = frame
}
let _ = UILabel().then {
$0.font = UIFont.systemFont(ofSize: fontSize!)
$0.text = placeHolderText
$0.numberOfLines = 0
$0.sizeToFit()
$0.textColor = placeColor
textView.addSubview($0)
textView.setValue($0, forKey: "_placeholderLabel")
}
self.init(frame:frame)
}
}
|
apache-2.0
|
69448e3f88bd91feac736c7b71e87799
| 22.487179 | 137 | 0.566594 | 4.071111 | false | false | false | false |
mgoenka/iOS-TipCalculator
|
SettingsViewController.swift
|
1
|
1705
|
//
// SettingsViewController.swift
// tipCaluculator
//
// Created by Mohit Goenka on 9/8/14.
// Copyright (c) 2014 mgoenka. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var defaultTipControl: UISegmentedControl!
var tipValues = [18, 20, 22]
override func viewDidLoad() {
super.viewDidLoad()
var defaults = NSUserDefaults.standardUserDefaults()
var defaultTipPercentage = defaults.integerForKey("default_tip")
if (defaultTipPercentage == tipValues[0]) {
defaultTipControl.selectedSegmentIndex = 0
} else if (defaultTipPercentage == tipValues[1]) {
defaultTipControl.selectedSegmentIndex = 1
} else {
defaultTipControl.selectedSegmentIndex = 2
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onDefaultTipChange(sender: AnyObject) {
var defaultTipPercentage = tipValues[defaultTipControl.selectedSegmentIndex]
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(defaultTipPercentage, forKey: "default_tip")
defaults.synchronize()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
9a263e935ed100eb591020aeccdb4dd1
| 30.574074 | 106 | 0.672727 | 5.059347 | false | false | false | false |
leoru/Brainstorage
|
Brainstorage-iOS/Classes/Controllers/Jobs/JobViewController.swift
|
1
|
5393
|
//
// JobViewController.swift
// Brainstorage
//
// Created by Kirill Kunst on 08.02.15.
// Copyright (c) 2015 Kirill Kunst. All rights reserved.
//
import Foundation
import UIKit
class JobViewController: UITableViewController, UIWebViewDelegate, UIActionSheetDelegate {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var workTimeLabel: UILabel!
@IBOutlet weak var worktimeIcon: UIImageView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var viewsLabel: UILabel!
@IBOutlet weak var detailsBrowser: UIWebView!
var detailsHeight : CGFloat?
@IBOutlet weak var detailsCell: UITableViewCell!
var job : Job?
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
func setup() {
self.updateJob()
var filterButton : UIButton = UIButton(frame: CGRectMake(0, 0, 24, 24))
filterButton.setImage(UIImage(named: "share"), forState: UIControlState.Normal)
filterButton.addTarget(self, action: Selector("actionOpenShare:"), forControlEvents: UIControlEvents.TouchUpInside)
filterButton.addTarget(self, action: Selector("clickAnimationNormal:"), forControlEvents: UIControlEvents.TouchUpOutside)
var barButtonItem : UIBarButtonItem = UIBarButtonItem(customView: filterButton)
self.navigationItem.rightBarButtonItem = barButtonItem
self.detailsBrowser.delegate = self
self.detailsBrowser.scrollView.scrollEnabled = false
detailsHeight = self.detailsBrowser.frame.size.height
SwiftLoader.show(title: "Загрузка...", animated: true)
RequestClient.sharedInstance.details(&self.job!, success: {
self.successLoadingDetails()
}, failure: {(error : NSError) in
})
}
// actions
func updateJob() {
if (self.job != nil) {
self.titleLabel.text = self.job?.title
self.locationLabel.text = self.job?.locationName
self.navigationItem.title = "Вакансии"
self.workTimeLabel.text = self.job?.occupationName()
self.workTimeLabel.textColor = self.job?.occupationColor()
self.worktimeIcon.image = UIImage(named: self.job!.occupationIcon())
self.dateLabel.text = self.job!.date
self.viewsLabel.text = self.job!.views
}
}
func successLoadingDetails() {
SwiftLoader.hide()
self.detailsBrowser.loadHTMLString(HTMLBuilder.htmlForJob(self.job!), baseURL: nil)
self.updateJob()
}
func actionOpenShare(sender:UIButton) {
clickAnimationNormal(sender)
var actionSheet : UIActionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "Отмена", destructiveButtonTitle: nil, otherButtonTitles: "Открыть в браузере", "Скопировать ссылку")
actionSheet.showInView(self.view)
}
func clickAnimationNormal(sender:UIButton) {
UIView.animateWithDuration(
0.05,
delay: 0,
options: UIViewAnimationOptions.CurveLinear,
animations: { () -> Void in
sender.transform = CGAffineTransformMakeScale(0.7, 0.7)
},
completion: nil)
UIView.animateWithDuration(
0.2,
delay: 0.05,
options: UIViewAnimationOptions.CurveLinear,
animations: { () -> Void in
sender.transform = CGAffineTransformMakeScale(1, 1)
},
completion: nil)
}
func openBrowser(url : NSURL) {
var browser = GDWebViewController()
browser.showToolbar = true
browser.loadURL(url, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 120.0)
self.navigationController?.pushViewController(browser, animated: true)
}
// TableView Delegate
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (indexPath.row == 2) {
println(self.detailsHeight)
return self.detailsHeight!
}
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
// WebView Delegate
func webViewDidFinishLoad(webView: UIWebView) {
webView.sizeToFit()
detailsHeight = webView.frame.size.height
self.tableView.reloadData()
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if (navigationType == UIWebViewNavigationType.LinkClicked) {
var url = request.URL
if (url!.scheme == "http" || url!.scheme == "https") {
self.openBrowser(url!)
return false
}
}
return true
}
// ActionSheet Delegate
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
if (buttonIndex == 1) {
UIApplication.sharedApplication().openURL(NSURL(string: self.job!.href)!)
} else if (buttonIndex == 2) {
UIPasteboard.generalPasteboard().string = self.job?.href
}
}
}
|
mit
|
6c1ce5ac51afd436f0f7b64d142b34cc
| 34.350993 | 204 | 0.634695 | 5.064516 | false | false | false | false |
KittenYang/A-GUIDE-TO-iOS-ANIMATION
|
Swift Version/ReplicatorLoaderDemo-Swift/ReplicatorLoaderDemo-Swift/ViewController.swift
|
1
|
1371
|
//
// ViewController.swift
// ReplicatorLoaderDemo-Swift
//
// Created by Kitten Yang on 2/3/16.
// Copyright © 2016 Kitten Yang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let pulseLoader = ReplicatorLoader(frame: CGRect(origin: view.center, size: CGSize(width: 100, height: 100)), type: .Pulse(option: Options(color: UIColor.redColor(), alpha: 0.3)))
pulseLoader.center = view.center
view.addSubview(pulseLoader)
let dotsFlipLoader = ReplicatorLoader(frame: CGRect(origin: view.center, size: CGSize(width: 100, height: 100)), type: .DotsFlip(option: Options(color: UIColor.redColor(), alpha: 0.3)))
dotsFlipLoader.center = CGPoint(x: pulseLoader.center.x, y: pulseLoader.center.y - CGFloat(120.0))
view.addSubview(dotsFlipLoader)
let gridScaleLoader = ReplicatorLoader(frame: CGRect(origin: view.center, size: CGSize(width: 100, height: 100)), type: .GridScale(option: Options(color: UIColor.redColor(), alpha: 0.3)))
gridScaleLoader.center = CGPoint(x: pulseLoader.center.x, y: pulseLoader.center.y + CGFloat(120.0))
view.addSubview(gridScaleLoader)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
gpl-2.0
|
2587d749b0471223e2bcdd07f9eaf5ca
| 36.027027 | 195 | 0.680292 | 3.971014 | false | false | false | false |
nghialv/Hakuba
|
Hakuba/Source/Bump/BumpTracker.swift
|
1
|
2509
|
//
// BumpTracker.swift
// Example
//
// Created by Le VanNghia on 3/4/16.
//
//
import Foundation
private enum UpdateState: Equatable {
case begin
case reload
case insert(indexes: [Int])
case move(from: Int, to: Int)
case remove(indexes: [Int])
}
final class BumpTracker {
private var state: UpdateState = .begin
var isChanged: Bool {
return state != .begin
}
func didBump() {
state = .begin
}
func didReset() {
state = .reload
}
func didInsert(indexes: [Int]) {
switch state {
case .begin:
state = .insert(indexes: indexes)
default:
state = .reload
}
}
func didMove(from: Int, to: Int) {
switch state {
case .begin:
state = .move(from: from, to: to)
default:
state = .reload
}
}
func didRemove(indexes: [Int]) {
switch state {
case .begin:
state = .remove(indexes: indexes)
default:
state = .reload
}
}
func getSectionBumpType(at index: Int) -> SectionBumpType {
let indexPath = { (row: Int) -> IndexPath in
return .init(row: row, section: index)
}
switch state {
case .insert(let indexes) where indexes.isNotEmpty:
return .insert(indexes.map(indexPath))
case .move(let from, let to):
return .move(indexPath(from), indexPath(to))
case .remove(let indexes) where indexes.isNotEmpty:
return .delete(indexes.map(indexPath))
default:
return .reload(.init(integer: index))
}
}
func getHakubaBumpType() -> HakubaBumpType {
let indexSet: ([Int]) -> IndexSet = { indexes in
let indexSet = NSMutableIndexSet()
for index in indexes {
indexSet.add(index)
}
return indexSet as IndexSet
}
switch state {
case .insert(let indexes) where indexes.isNotEmpty:
return .insert(indexSet(indexes))
case .move(let from, let to):
return .move(from, to)
case .remove(let indexes) where indexes.isNotEmpty:
return .delete(indexSet(indexes))
default:
return .reload
}
}
}
|
mit
|
c0f1870251fa8be69e618d6b66d7255c
| 22.448598 | 63 | 0.502591 | 4.570128 | false | false | false | false |
RMizin/PigeonMessenger-project
|
FalconMessenger/Supporting Files/UIComponents/INSPhotosGallery/INSPhoto.swift
|
1
|
4263
|
//
// INSPhoto.swift
// INSPhotoViewer
//
// Created by Michal Zaborowski on 28.02.2016.
// Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this library 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 SDWebImage
/*
* This is marked as @objc because of Swift bug http://stackoverflow.com/questions/30100787/fatal-error-array-cannot-be-bridged-from-objective-c-why-are-you-even-trying when passing for example [INSPhoto] array
* to INSPhotosViewController
*/
@objc public protocol INSPhotoViewable: class {
var image: UIImage? { get }
var thumbnailImage: UIImage? { get }
var messageUID: String? { get }
@objc optional var isDeletable: Bool { get }
var videoURL: String? { get }
var localVideoURL: String? { get }
var imageURL: URL? { get }
func loadImageWithCompletionHandler(_ completion: @escaping (_ image: UIImage?, _ error: Error?) -> ())
func loadThumbnailImageWithCompletionHandler(_ completion: @escaping (_ image: UIImage?, _ error: Error?) -> ())
var attributedTitle: NSAttributedString? { get }
}
@objc open class INSPhoto: NSObject, INSPhotoViewable {
@objc public var videoURL: String?
@objc public var localVideoURL: String?
@objc open var image: UIImage?
@objc open var thumbnailImage: UIImage?
@objc open var messageUID: String?
@objc open var isDeletable: Bool
// @objc open var videoURL: String?
// @objc open var localVideoURL: String?
public var imageURL: URL?
var thumbnailImageURL: URL?
// var messageUID: String?
@objc open var attributedTitle: NSAttributedString?
public init(image: UIImage?, thumbnailImage: UIImage?, messageUID: String?, videoURL: String? = nil, localVideoURL: String? = nil) {
self.image = image
self.thumbnailImage = thumbnailImage
self.messageUID = messageUID
self.isDeletable = false
self.videoURL = videoURL
self.localVideoURL = localVideoURL
}
public init(imageURL: URL?, thumbnailImageURL: URL?, messageUID: String?, videoURL: String? = nil, localVideoURL: String? = nil) {
self.imageURL = imageURL
self.thumbnailImageURL = thumbnailImageURL
self.messageUID = messageUID
self.isDeletable = false
self.videoURL = videoURL
self.localVideoURL = localVideoURL
}
public init (imageURL: URL?, thumbnailImage: UIImage?, messageUID: String?, videoURL: String? = nil, localVideoURL: String? = nil) {
self.imageURL = imageURL
self.thumbnailImage = thumbnailImage
self.messageUID = messageUID
self.isDeletable = false
self.videoURL = videoURL
self.localVideoURL = localVideoURL
}
@objc open func loadImageWithCompletionHandler(_ completion: @escaping (_ image: UIImage?, _ error: Error?) -> ()) {
if let image = image {
completion(image, nil)
return
}
SDWebImageManager.shared.loadImage(with: imageURL,
options: [.scaleDownLargeImages, .continueInBackground],
progress: nil) { (image, _, error, _, _, _) in
completion(image, error)
}
}
@objc open func loadThumbnailImageWithCompletionHandler(_ completion: @escaping (_ image: UIImage?, _ error: Error?) -> ()) {
if let thumbnailImage = thumbnailImage {
completion(thumbnailImage, nil)
return
}
SDWebImageManager.shared.loadImage(with: thumbnailImageURL,
options: [.scaleDownLargeImages, .continueInBackground],
progress: nil) { (image, _, error, _, _, _) in
completion(image, error)
}
}
}
public func ==<T: INSPhoto>(lhs: T, rhs: T) -> Bool {
return lhs === rhs
}
|
gpl-3.0
|
fe18d0cedc978ae9bc4325d0dc2da766
| 34.798319 | 210 | 0.671831 | 4.22619 | false | false | false | false |
jasnig/DouYuTVMutate
|
DouYuTVMutate/DouYuTV/Home/View/SectionHeaderView.swift
|
1
|
1210
|
//
// SectionHeaderView.swift
// DouYuTVMutate
//
// Created by ZeroJ on 16/7/13.
// Copyright © 2016年 ZeroJ. All rights reserved.
//
import UIKit
import Kingfisher
class SectionHeaderView: UICollectionReusableView {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var typeLabel: UILabel!
@IBAction func moreBtnOnClick(sender: UIButton) {
moreBtnOnClickClosure?(dataModel: dataModel)
}
var moreBtnOnClickClosure:((dataModel: TagModel) -> Void)?
func setMoreBtnOnClickClosure(closure: ((dataModel: TagModel) -> Void)?) {
moreBtnOnClickClosure = closure
}
var dataModel: TagModel = TagModel() {
didSet {
typeLabel.text = dataModel.tag_name
imageView.kf_setImageWithURL(NSURL(string: dataModel.icon_url)!, placeholderImage: nil) {[weak self] (image, error, cacheType, imageURL) in
guard let `self` = self where image != nil else { return }
self.imageView.zj_setCircleImage(image, radius: 20.0)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.groupTableViewBackgroundColor()
}
}
|
mit
|
23768c8f6382be1d406a168df3e42356
| 29.948718 | 151 | 0.650373 | 4.520599 | false | false | false | false |
dreamsxin/swift
|
stdlib/public/core/ClosedRange.swift
|
1
|
13924
|
//===--- ClosedRange.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME: swift-3-indexing-model: Generalize all tests to check both
// [Closed]Range and [Closed]CountableRange.
internal enum _ClosedRangeIndexRepresentation<Bound>
where
// WORKAROUND rdar://25214598 - should be Bound : Strideable
Bound : protocol<_Strideable, Comparable>,
Bound.Stride : Integer {
case pastEnd
case inRange(Bound)
}
// FIXME(ABI)(compiler limitation): should be a nested type in
// `ClosedRange`.
/// A position in a `CountableClosedRange` instance.
public struct ClosedRangeIndex<Bound> : Comparable
where
// WORKAROUND rdar://25214598 - should be Bound : Strideable
// swift-3-indexing-model: should conform to _Strideable, otherwise
// CountableClosedRange is not interchangeable with CountableRange in all
// contexts.
Bound : protocol<_Strideable, Comparable>,
Bound.Stride : Integer {
/// Creates the "past the end" position.
internal init() { _value = .pastEnd }
/// Creates a position `p` for which `r[p] == x`.
internal init(_ x: Bound) { _value = .inRange(x) }
internal func _successor(upperBound limit: Bound) -> ClosedRangeIndex {
switch _value {
case .inRange(let x): return x == limit
? ClosedRangeIndex() : ClosedRangeIndex(x.advanced(by: 1))
case .pastEnd: _preconditionFailure("Incrementing past end index")
}
}
internal func _predecessor(upperBound limit: Bound) -> ClosedRangeIndex {
switch _value {
case .inRange(let x): return ClosedRangeIndex(x.advanced(by: -1))
case .pastEnd: return ClosedRangeIndex(limit)
}
}
internal func _advanced(
by n: Bound.Stride, upperBound limit: Bound
) -> ClosedRangeIndex {
switch _value {
case .inRange(let x):
let d = x.distance(to: limit)
if n <= d { return ClosedRangeIndex(x.advanced(by: n)) }
if d - -1 == n { return ClosedRangeIndex() }
_preconditionFailure("Advancing past end index")
case .pastEnd:
return n == 0
? self :
ClosedRangeIndex(limit)._advanced(by: n, upperBound: limit)
}
}
internal var _value: _ClosedRangeIndexRepresentation<Bound>
internal var _dereferenced : Bound {
switch _value {
case .inRange(let x): return x
case .pastEnd: _preconditionFailure("Index out of range")
}
}
}
public func == <B>(lhs: ClosedRangeIndex<B>, rhs: ClosedRangeIndex<B>) -> Bool {
switch (lhs._value, rhs._value) {
case (.inRange(let l), .inRange(let r)):
return l == r
case (.pastEnd, .pastEnd):
return true
default:
return false
}
}
public func < <B>(lhs: ClosedRangeIndex<B>, rhs: ClosedRangeIndex<B>) -> Bool {
switch (lhs._value, rhs._value) {
case (.inRange(let l), .inRange(let r)):
return l < r
case (.inRange(_), .pastEnd):
return true
default:
return false
}
}
// WORKAROUND: needed because of rdar://25584401
/// An iterator over the elements of a `CountableClosedRange` instance.
public struct ClosedRangeIterator<Bound> : IteratorProtocol, Sequence
where
// WORKAROUND rdar://25214598 - should be just Bound : Strideable
Bound : protocol<_Strideable, Comparable>,
Bound.Stride : SignedInteger {
internal init(_range r: CountableClosedRange<Bound>) {
_nextResult = r.lowerBound
_upperBound = r.upperBound
}
public func makeIterator() -> ClosedRangeIterator {
return self
}
public mutating func next() -> Bound? {
let r = _nextResult
if let x = r {
_nextResult = x == _upperBound ? nil : x.advanced(by: 1)
}
return r
}
internal var _nextResult: Bound?
internal let _upperBound: Bound
}
/// A closed range that forms a collection of consecutive values.
///
/// You create a `CountableClosedRange` instance by using the closed range
/// operator (`...`).
///
/// let throughFive = 0...5
///
/// A `CountableClosedRange` instance contains both its lower bound and its
/// upper bound.
///
/// print(throughFive.contains(3)) // Prints "true"
/// print(throughFive.contains(10)) // Prints "false"
/// print(throughFive.contains(5)) // Prints "true"
///
/// Because a closed range includes its upper bound, a closed range whose lower
/// bound is equal to the upper bound contains one element. Therefore, a
/// `CountableClosedRange` instance cannot represent an empty range.
///
/// let zeroInclusive = 0...0
/// print(zeroInclusive.isEmpty)
/// // Prints "false"
/// print(zeroInclusive.count)
/// // Prints "1"
///
/// You can use a `for`-`in` loop or any sequence or collection method with a
/// countable range. The elements of the range are the consecutive values from
/// its lower bound up to, and including, its upper bound.
///
/// for n in throughFive.suffix(3) {
/// print(n)
/// }
/// // Prints "3"
/// // Prints "4"
/// // Prints "5"
///
/// You can create a countable range over any type that conforms to the
/// `Strideable` protocol and uses an integer as its associated `Stride` type.
/// By default, Swift's integer and pointer types are usable as the bounds of
/// a countable range.
///
/// Because floating-point types such as `Float` and `Double` are their own
/// `Stride` types, they cannot be used as the bounds of a countable range. If
/// you need to test whether values are contained within a closed interval
/// bound by floating-point values, see the `ClosedRange` type. If you need to
/// iterate over consecutive floating-point values, see the
/// `stride(from:through:by:)` function.
///
/// - SeeAlso: `CountableRange`, `ClosedRange`, `Range`
public struct CountableClosedRange<Bound> : RandomAccessCollection
where
// WORKAROUND rdar://25214598 - should be just Bound : Strideable
Bound : protocol<_Strideable, Comparable>,
Bound.Stride : SignedInteger {
/// The range's lower bound.
public let lowerBound: Bound
/// The range's upper bound.
///
/// `upperBound` is always reachable from `lowerBound` by zero or
/// more applications of `index(after:)`.
public let upperBound: Bound
/// The element type of the range; the same type as the range's bounds.
public typealias Element = Bound
/// A type that represents a position in the range.
public typealias Index = ClosedRangeIndex<Bound>
public typealias IndexDistance = Bound.Stride
// WORKAROUND: needed because of rdar://25584401
public typealias Iterator = ClosedRangeIterator<Bound>
// WORKAROUND: needed because of rdar://25584401
public func makeIterator() -> ClosedRangeIterator<Bound> {
return ClosedRangeIterator(_range: self)
}
/// The position of the first element in the range.
public var startIndex: ClosedRangeIndex<Bound> {
return ClosedRangeIndex(lowerBound)
}
/// The range's "past the end" position---that is, the position one greater
/// than the last valid subscript argument.
public var endIndex: ClosedRangeIndex<Bound> {
return ClosedRangeIndex()
}
public func index(after i: Index) -> Index {
// FIXME: swift-3-indexing-model: range checks and tests.
return i._successor(upperBound: upperBound)
}
public func index(before i: Index) -> Index {
// FIXME: swift-3-indexing-model: range checks and tests.
return i._predecessor(upperBound: upperBound)
}
// FIXME: swift-3-indexing-model: implement O(1) `index(_:offsetBy:)`
// and `distance(from:to:)`, and write tests for them.
/// Accesses the element at specified position.
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the range, and must not equal the range's end
/// index.
public subscript(position: ClosedRangeIndex<Bound>) -> Bound {
// FIXME: swift-3-indexing-model: range checks and tests.
return position._dereferenced
}
public subscript(bounds: Range<Index>)
-> RandomAccessSlice<CountableClosedRange<Bound>> {
return RandomAccessSlice(base: self, bounds: bounds)
}
public // WORKAROUND: needed because of rdar://25584401
var indices: DefaultRandomAccessIndices<CountableClosedRange<Bound>> {
return DefaultRandomAccessIndices(
_elements: self,
startIndex: self.startIndex,
endIndex: self.endIndex)
}
/// Creates an instance with the given bounds.
///
/// Because this initializer does not perform any checks, it should be used
/// as an optimization only when you are absolutely certain that `lower` is
/// less than or equal to `upper`. Using the closed range operator (`...`)
/// to form `CountableClosedRange` instances is preferred.
///
/// - Parameter bounds: A tuple of the lower and upper bounds of the range.
public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) {
self.lowerBound = bounds.lower
self.upperBound = bounds.upper
}
public func _customContainsEquatableElement(_ element: Bound) -> Bool? {
return element >= self.lowerBound && element <= self.upperBound
}
/// A Boolean value indicating whether the range contains no elements.
///
/// Because a closed range cannot represent an empty range, this property is
/// always `false`.
public var isEmpty: Bool {
return false
}
}
/// An interval over a comparable type, from a lower bound up to, and
/// including, an upper bound.
///
/// You create instances of `ClosedRange` by using the closed range operator
/// (`...`).
///
/// let lowercase = "a"..."z"
///
/// You can use a `ClosedRange` instance to quickly check if a value is
/// contained in a particular range of values. For example:
///
/// print(lowercase.contains("c")) // Prints "true"
/// print(lowercase.contains("5")) // Prints "false"
/// print(lowercase.contains("z")) // Prints "true"
///
/// Unlike `Range`, instances of `ClosedRange` cannot represent an empty
/// interval.
///
/// let lowercaseA = "a"..."a"
/// print(lowercaseA.isEmpty)
/// // Prints "false"
///
/// - SeeAlso: `CountableRange`, `Range`, `CountableClosedRange`
@_fixed_layout
public struct ClosedRange<
Bound : Comparable
> {
/// Creates an instance with the given bounds.
///
/// Because this initializer does not perform any checks, it should be used
/// as an optimization only when you are absolutely certain that `lower` is
/// less than or equal to `upper`. Using the closed range operator (`...`)
/// to form `ClosedRange` instances is preferred.
///
/// - Parameter bounds: A tuple of the lower and upper bounds of the range.
@inline(__always)
public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) {
self.lowerBound = bounds.lower
self.upperBound = bounds.upper
}
/// The range's lower bound.
public let lowerBound: Bound
/// The range's upper bound.
public let upperBound: Bound
/// Returns a Boolean value indicating whether the given element is contained
/// within the range.
///
/// A `ClosedRange` instance contains both its lower and upper bound.
/// `element` is contained in the range if it is between the two bounds or
/// equal to either bound.
///
/// - Parameter element: The element to check for containment.
/// - Returns: `true` if `element` is contained in the range; otherwise,
/// `false`.
public func contains(_ element: Bound) -> Bool {
return element >= self.lowerBound && element <= self.upperBound
}
/// A Boolean value indicating whether the range contains no elements.
///
/// Because a closed range cannot represent an empty range, this property is
/// always `false`.
public var isEmpty: Bool {
return false
}
}
/// Returns a closed range that contains both of its bounds.
///
/// For example:
///
/// let lowercase = "a"..."z"
/// print(lowercase.contains("z"))
/// // Prints "true"
///
/// - Parameters:
/// - minimum: The lower bound for the range.
/// - maximum: The upper bound for the range.
@_transparent
public func ... <Bound : Comparable> (minimum: Bound, maximum: Bound)
-> ClosedRange<Bound> {
_precondition(
minimum <= maximum, "Can't form Range with upperBound < lowerBound")
return ClosedRange(uncheckedBounds: (lower: minimum, upper: maximum))
}
/// Returns a countable closed range that contains both of its bounds.
///
/// For example:
///
/// let singleDigits = 0...9
/// print(singleDigits.contains(9))
/// // Prints "true"
///
/// - Parameters:
/// - minimum: The lower bound for the range.
/// - maximum: The upper bound for the range.
@_transparent
public func ... <Bound> (
minimum: Bound, maximum: Bound
) -> CountableClosedRange<Bound>
where
// WORKAROUND rdar://25214598 - should be just Bound : Strideable
Bound : protocol<_Strideable, Comparable>,
Bound.Stride : SignedInteger {
// FIXME: swift-3-indexing-model: tests for traps.
_precondition(
minimum <= maximum, "Can't form Range with upperBound < lowerBound")
return CountableClosedRange(uncheckedBounds: (lower: minimum, upper: maximum))
}
extension ClosedRange {
@available(*, unavailable, renamed: "lowerBound")
public var startIndex: Bound {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "upperBound")
public var endIndex: Bound {
Builtin.unreachable()
}
}
|
apache-2.0
|
986120536c90d91f2f0dcae367918112
| 32.63285 | 80 | 0.672508 | 4.254201 | false | false | false | false |
instacrate/Subber-api
|
Sources/App/Controllers/ShippingController.swift
|
2
|
3374
|
//
// ShippingController.swift
// subber-api
//
// Created by Hakon Hanesand on 11/12/16.
//
//
import Foundation
import Vapor
import HTTP
import FluentMySQL
extension Shipping {
func shouldAllow(request: Request) throws {
guard let customer = try? request.customer() else {
throw try Abort.custom(status: .forbidden, message: "Method \(request.method) is not allowed on resource Shipping(\(throwableId())) by this user. Must be logged in as Customer(\(customer_id?.int ?? 0)).")
}
guard try customer.throwableId() == customer_id?.int else {
throw try Abort.custom(status: .forbidden, message: "This Customer(\(customer.throwableId())) does not have access to resource Shipping(\(throwableId()). Must be logged in as Customer(\(customer_id?.int ?? 0).")
}
}
}
final class ShippingController: ResourceRepresentable {
func index(_ request: Request) throws -> ResponseRepresentable {
let customer = try request.customer()
return try customer.shippingAddresses().all().makeJSON()
}
func create(_ request: Request) throws -> ResponseRepresentable {
var customer = try request.customer()
var shipping: Shipping = try request.extractModel(injecting: request.customerInjectable())
if let defaultShipping = try request.customer().defaultShipping, defaultShipping == .null || defaultShipping == nil {
shipping.isDefault = true
try shipping.save()
customer.defaultShipping = shipping.id
try customer.save()
} else {
try shipping.save()
}
return shipping
}
func delete(_ request: Request, shipping: Shipping) throws -> ResponseRepresentable {
try shipping.shouldAllow(request: request)
var customer = try request.customer()
if shipping.isDefault {
if var next = try customer.defaultShippingAddress().filter("id", .notEquals, shipping.id!).first() {
next.isDefault = true
customer.defaultShipping = next.id
try next.save()
try customer.save()
}
}
try shipping.delete()
return Response(status: .noContent)
}
func modify(_ request: Request, shipping: Shipping) throws -> ResponseRepresentable {
try shipping.shouldAllow(request: request)
var customer = try request.customer()
guard shipping.customer_id == customer.id else {
throw Abort.custom(status: .forbidden, message: "Can not modify another user's shipping address.")
}
var updated: Shipping = try request.patchModel(shipping)
if updated.isDefault && !shipping.isDefault {
if var previous = try request.customer().defaultShippingAddress().first() {
previous.isDefault = false
customer.defaultShipping = updated.id
try previous.save()
try customer.save()
}
}
try updated.save()
return updated
}
func makeResource() -> Resource<Shipping> {
return Resource(
index: index,
store: create,
modify: modify,
destroy: delete
)
}
}
|
mit
|
81ec08e312bc81642b306d3b6959824b
| 31.442308 | 223 | 0.598992 | 5.020833 | false | false | false | false |
ben-ng/swift
|
test/SILGen/foreign_errors.swift
|
1
|
17163
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-silgen -parse-as-library %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import errors
// CHECK: sil hidden @_TF14foreign_errors5test0FzT_T_ : $@convention(thin) () -> @error Error
func test0() throws {
// CHECK: [[SELF:%.*]] = metatype $@thick ErrorProne.Type
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $@thick ErrorProne.Type, #ErrorProne.fail!1.foreign : (ErrorProne.Type) -> () throws -> () , $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
// CHECK: [[OBJC_SELF:%.*]] = thick_to_objc_metatype [[SELF]]
// Create a strong temporary holding nil.
// CHECK: [[ERR_TEMP0:%.*]] = alloc_stack $Optional<NSError>
// CHECK: inject_enum_addr [[ERR_TEMP0]] : $*Optional<NSError>, #Optional.none!enumelt
// Create an unmanaged temporary, copy into it, and make a AutoreleasingUnsafeMutablePointer.
// CHECK: [[ERR_TEMP1:%.*]] = alloc_stack $@sil_unmanaged Optional<NSError>
// CHECK: [[T0:%.*]] = load_borrow [[ERR_TEMP0]]
// CHECK: [[T1:%.*]] = ref_to_unmanaged [[T0]]
// CHECK: store [[T1]] to [trivial] [[ERR_TEMP1]]
// CHECK: address_to_pointer [[ERR_TEMP1]]
// Call the method.
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]({{.*}}, [[OBJC_SELF]])
// Writeback to the first temporary.
// CHECK: [[T0:%.*]] = load [trivial] [[ERR_TEMP1]]
// CHECK: [[T1:%.*]] = unmanaged_to_ref [[T0]]
// CHECK: [[T1_COPY:%.*]] = copy_value [[T1]]
// CHECK: assign [[T1_COPY]] to [[ERR_TEMP0]]
// Pull out the boolean value and compare it to zero.
// CHECK: [[BOOL_OR_INT:%.*]] = struct_extract [[RESULT]]
// CHECK: [[RAW_VALUE:%.*]] = struct_extract [[BOOL_OR_INT]]
// On some platforms RAW_VALUE will be compared against 0; on others it's
// already an i1 (bool) and those instructions will be skipped. Just do a
// looser check.
// CHECK: cond_br {{%.+}}, [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
try ErrorProne.fail()
// Normal path: fall out and return.
// CHECK: [[NORMAL_BB]]:
// CHECK: return
// Error path: fall out and rethrow.
// CHECK: [[ERROR_BB]]:
// CHECK: [[T0:%.*]] = load [take] [[ERR_TEMP0]]
// CHECK: [[T1:%.*]] = function_ref @swift_convertNSErrorToError : $@convention(thin) (@owned Optional<NSError>) -> @owned Error
// CHECK: [[T2:%.*]] = apply [[T1]]([[T0]])
// CHECK: throw [[T2]] : $Error
}
extension NSObject {
@objc func abort() throws {
throw NSError(domain: "", code: 1, userInfo: [:])
}
// CHECK-LABEL: sil hidden [thunk] @_TToFE14foreign_errorsCSo8NSObject5abort{{.*}} : $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> ObjCBool
// CHECK: [[T0:%.*]] = function_ref @_TFE14foreign_errorsCSo8NSObject5abort{{.*}} : $@convention(method) (@guaranteed NSObject) -> @error Error
// CHECK: try_apply [[T0]](
// CHECK: bb1(
// CHECK: [[BITS:%.*]] = integer_literal $Builtin.Int{{[18]}}, {{1|-1}}
// CHECK: [[VALUE:%.*]] = struct ${{Bool|UInt8}} ([[BITS]] : $Builtin.Int{{[18]}})
// CHECK: [[BOOL:%.*]] = struct $ObjCBool ([[VALUE]] : ${{Bool|UInt8}})
// CHECK: br bb6([[BOOL]] : $ObjCBool)
// CHECK: bb2([[ERR:%.*]] : $Error):
// CHECK: switch_enum %0 : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, case #Optional.some!enumelt.1: bb3, case #Optional.none!enumelt: bb4
// CHECK: bb3([[UNWRAPPED_OUT:%.+]] : $AutoreleasingUnsafeMutablePointer<Optional<NSError>>):
// CHECK: [[T0:%.*]] = function_ref @swift_convertErrorToNSError : $@convention(thin) (@owned Error) -> @owned NSError
// CHECK: [[T1:%.*]] = apply [[T0]]([[ERR]])
// CHECK: [[OBJCERR:%.*]] = enum $Optional<NSError>, #Optional.some!enumelt.1, [[T1]] : $NSError
// CHECK: [[SETTER:%.*]] = function_ref @_TFVs33AutoreleasingUnsafeMutablePointers7pointeex :
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<NSError>
// CHECK: store [[OBJCERR]] to [init] [[TEMP]]
// CHECK: apply [[SETTER]]<Optional<NSError>>([[TEMP]], [[UNWRAPPED_OUT]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br bb5
// CHECK: bb4:
// CHECK: destroy_value [[ERR]] : $Error
// CHECK: br bb5
// CHECK: bb5:
// CHECK: [[BITS:%.*]] = integer_literal $Builtin.Int{{[18]}}, 0
// CHECK: [[VALUE:%.*]] = struct ${{Bool|UInt8}} ([[BITS]] : $Builtin.Int{{[18]}})
// CHECK: [[BOOL:%.*]] = struct $ObjCBool ([[VALUE]] : ${{Bool|UInt8}})
// CHECK: br bb6([[BOOL]] : $ObjCBool)
// CHECK: bb6([[BOOL:%.*]] : $ObjCBool):
// CHECK: return [[BOOL]] : $ObjCBool
@objc func badDescription() throws -> String {
throw NSError(domain: "", code: 1, userInfo: [:])
}
// CHECK-LABEL: sil hidden [thunk] @_TToFE14foreign_errorsCSo8NSObject14badDescription{{.*}} : $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> @autoreleased Optional<NSString>
// CHECK: [[T0:%.*]] = function_ref @_TFE14foreign_errorsCSo8NSObject14badDescription{{.*}} : $@convention(method) (@guaranteed NSObject) -> (@owned String, @error Error)
// CHECK: try_apply [[T0]](
// CHECK: bb1([[RESULT:%.*]] : $String):
// CHECK: [[T0:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString : $@convention(method) (@guaranteed String) -> @owned NSString
// CHECK: [[T1:%.*]] = apply [[T0]]([[RESULT]])
// CHECK: [[T2:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[T1]] : $NSString
// CHECK: br bb6([[T2]] : $Optional<NSString>)
// CHECK: bb2([[ERR:%.*]] : $Error):
// CHECK: switch_enum %0 : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, case #Optional.some!enumelt.1: bb3, case #Optional.none!enumelt: bb4
// CHECK: bb3([[UNWRAPPED_OUT:%.+]] : $AutoreleasingUnsafeMutablePointer<Optional<NSError>>):
// CHECK: [[T0:%.*]] = function_ref @swift_convertErrorToNSError : $@convention(thin) (@owned Error) -> @owned NSError
// CHECK: [[T1:%.*]] = apply [[T0]]([[ERR]])
// CHECK: [[OBJCERR:%.*]] = enum $Optional<NSError>, #Optional.some!enumelt.1, [[T1]] : $NSError
// CHECK: [[SETTER:%.*]] = function_ref @_TFVs33AutoreleasingUnsafeMutablePointers7pointeex :
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<NSError>
// CHECK: store [[OBJCERR]] to [init] [[TEMP]]
// CHECK: apply [[SETTER]]<Optional<NSError>>([[TEMP]], [[UNWRAPPED_OUT]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br bb5
// CHECK: bb4:
// CHECK: destroy_value [[ERR]] : $Error
// CHECK: br bb5
// CHECK: bb5:
// CHECK: [[T0:%.*]] = enum $Optional<NSString>, #Optional.none!enumelt
// CHECK: br bb6([[T0]] : $Optional<NSString>)
// CHECK: bb6([[T0:%.*]] : $Optional<NSString>):
// CHECK: return [[T0]] : $Optional<NSString>
// CHECK-LABEL: sil hidden [thunk] @_TToFE14foreign_errorsCSo8NSObject7takeInt{{.*}} : $@convention(objc_method) (Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, NSObject) -> ObjCBool
// CHECK: bb0([[I:%[0-9]+]] : $Int, [[ERROR:%[0-9]+]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[SELF:%[0-9]+]] : $NSObject)
@objc func takeInt(_ i: Int) throws { }
// CHECK-LABEL: sil hidden [thunk] @_TToFE14foreign_errorsCSo8NSObject10takeDouble{{.*}} : $@convention(objc_method) (Double, Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @convention(block) (Int) -> Int, NSObject) -> ObjCBool
// CHECK: bb0([[D:%[0-9]+]] : $Double, [[INT:%[0-9]+]] : $Int, [[ERROR:%[0-9]+]] : $Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, [[CLOSURE:%[0-9]+]] : $@convention(block) (Int) -> Int, [[SELF:%[0-9]+]] : $NSObject):
@objc func takeDouble(_ d: Double, int: Int, closure: (Int) -> Int) throws {
throw NSError(domain: "", code: 1, userInfo: [:])
}
}
let fn = ErrorProne.fail
// CHECK-LABEL: sil shared [thunk] @_TTOZFCSo10ErrorProne4fail{{.*}} : $@convention(thin) (@thick ErrorProne.Type) -> @owned @callee_owned () -> @error Error
// CHECK: [[T0:%.*]] = function_ref @_TTOZFCSo10ErrorProne4fail{{.*}} : $@convention(method) (@thick ErrorProne.Type) -> @error Error
// CHECK-NEXT: [[T1:%.*]] = partial_apply [[T0]](%0)
// CHECK-NEXT: return [[T1]]
// CHECK-LABEL: sil shared [thunk] @_TTOZFCSo10ErrorProne4fail{{.*}} : $@convention(method) (@thick ErrorProne.Type) -> @error Error {
// CHECK: [[SELF:%.*]] = thick_to_objc_metatype %0 : $@thick ErrorProne.Type to $@objc_metatype ErrorProne.Type
// CHECK: [[METHOD:%.*]] = class_method [volatile] [[T0]] : $@objc_metatype ErrorProne.Type, #ErrorProne.fail!1.foreign : (ErrorProne.Type) -> () throws -> () , $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
// CHECK: [[TEMP:%.*]] = alloc_stack $Optional<NSError>
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]({{%.*}}, [[SELF]])
// CHECK: cond_br
// CHECK: return
// CHECK: [[T0:%.*]] = load [take] [[TEMP]]
// CHECK: [[T1:%.*]] = apply {{%.*}}([[T0]])
// CHECK: throw [[T1]]
func testArgs() throws {
try ErrorProne.consume(nil)
}
// CHECK: sil hidden @_TF14foreign_errors8testArgsFzT_T_ : $@convention(thin) () -> @error Error
// CHECK: debug_value undef : $Error, var, name "$error", argno 1
// CHECK: class_method [volatile] %1 : $@thick ErrorProne.Type, #ErrorProne.consume!1.foreign : (ErrorProne.Type) -> (Any!) throws -> () , $@convention(objc_method) (Optional<AnyObject>, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> ObjCBool
func testBridgedResult() throws {
let array = try ErrorProne.collection(withCount: 0)
}
// CHECK-LABEL: sil hidden @_TF14foreign_errors17testBridgedResultFzT_T_ : $@convention(thin) () -> @error Error {
// CHECK: debug_value undef : $Error, var, name "$error", argno 1
// CHECK: class_method [volatile] %1 : $@thick ErrorProne.Type, #ErrorProne.collection!1.foreign : (ErrorProne.Type) -> (Int) throws -> [Any] , $@convention(objc_method) (Int, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> @autoreleased Optional<NSArray>
// rdar://20861374
// Clear out the self box before delegating.
class VeryErrorProne : ErrorProne {
init(withTwo two: AnyObject?) throws {
try super.init(one: two)
}
}
// CHECK-LABEL: sil hidden @_TFC14foreign_errors14VeryErrorPronec{{.*}}
// CHECK: bb0([[ARG1:%.*]] : $Optional<AnyObject>, [[ARG2:%.*]] : $VeryErrorProne):
// CHECK: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <VeryErrorProne>
// CHECK: [[PB:%.*]] = project_box [[BOX]]
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[PB]]
// CHECK: store [[ARG2]] to [init] [[MARKED_BOX]]
// CHECK: [[T0:%.*]] = load_borrow [[MARKED_BOX]]
// CHECK-NEXT: [[T1:%.*]] = upcast [[T0]] : $VeryErrorProne to $ErrorProne
// CHECK-NEXT: [[T2:%.*]] = super_method [volatile] [[T0]] : $VeryErrorProne, #ErrorProne.init!initializer.1.foreign : (ErrorProne.Type) -> (Any?) throws -> ErrorProne , $@convention(objc_method) (Optional<AnyObject>, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @owned ErrorProne) -> @owned Optional<ErrorProne>
// CHECK: [[ARG1_COPY:%.*]] = copy_value [[ARG1]]
// CHECK-NOT: [[BOX]]{{^[0-9]}}
// CHECK-NOT: [[MARKED_BOX]]{{^[0-9]}}
// CHECK: apply [[T2]]([[ARG1_COPY]], {{%.*}}, [[T1]])
// rdar://21051021
// CHECK: sil hidden @_TF14foreign_errors12testProtocolFzPSo18ErrorProneProtocol_T_
func testProtocol(_ p: ErrorProneProtocol) throws {
// CHECK: [[T0:%.*]] = open_existential_ref %0 : $ErrorProneProtocol to $[[OPENED:@opened(.*) ErrorProneProtocol]]
// CHECK: [[T1:%.*]] = witness_method [volatile] $[[OPENED]], #ErrorProneProtocol.obliterate!1.foreign, [[T0]] : $[[OPENED]] :
// CHECK: apply [[T1]]<[[OPENED]]>({{%.*}}, [[T0]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : ErrorProneProtocol> (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, τ_0_0) -> ObjCBool
try p.obliterate()
// CHECK: [[T0:%.*]] = open_existential_ref %0 : $ErrorProneProtocol to $[[OPENED:@opened(.*) ErrorProneProtocol]]
// CHECK: [[T1:%.*]] = witness_method [volatile] $[[OPENED]], #ErrorProneProtocol.invigorate!1.foreign, [[T0]] : $[[OPENED]] :
// CHECK: apply [[T1]]<[[OPENED]]>({{%.*}}, {{%.*}}, [[T0]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : ErrorProneProtocol> (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, Optional<@convention(block) () -> ()>, τ_0_0) -> ObjCBool
try p.invigorate(callback: {})
}
// rdar://21144509 - Ensure that overrides of replace-with-() imports are possible.
class ExtremelyErrorProne : ErrorProne {
override func conflict3(_ obj: Any, error: ()) throws {}
}
// CHECK: sil hidden @_TFC14foreign_errors19ExtremelyErrorProne9conflict3{{.*}}
// CHECK: sil hidden [thunk] @_TToFC14foreign_errors19ExtremelyErrorProne9conflict3{{.*}} : $@convention(objc_method) (AnyObject, Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, ExtremelyErrorProne) -> ObjCBool
// These conventions are usable because of swift_error. rdar://21715350
func testNonNilError() throws -> Float {
return try ErrorProne.bounce()
}
// CHECK: sil hidden @_TF14foreign_errors15testNonNilErrorFzT_Sf :
// CHECK: [[T0:%.*]] = metatype $@thick ErrorProne.Type
// CHECK: [[T1:%.*]] = class_method [volatile] [[T0]] : $@thick ErrorProne.Type, #ErrorProne.bounce!1.foreign : (ErrorProne.Type) -> () throws -> Float , $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Float
// CHECK: [[OPTERR:%.*]] = alloc_stack $Optional<NSError>
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: assign {{%.*}} to [[OPTERR]]
// CHECK: [[T0:%.*]] = load [take] [[OPTERR]]
// CHECK: switch_enum [[T0]] : $Optional<NSError>, case #Optional.some!enumelt.1: [[ERROR_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NORMAL_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResult() throws -> CInt {
return try ErrorProne.ounce()
}
// CHECK: sil hidden @_TF14foreign_errors19testPreservedResultFzT_Vs5Int32
// CHECK: [[T0:%.*]] = metatype $@thick ErrorProne.Type
// CHECK: [[T1:%.*]] = class_method [volatile] [[T0]] : $@thick ErrorProne.Type, #ErrorProne.ounce!1.foreign : (ErrorProne.Type) -> () throws -> Int32 , $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int32
// CHECK: [[OPTERR:%.*]] = alloc_stack $Optional<NSError>
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int32"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResultBridged() throws -> Int {
return try ErrorProne.ounceWord()
}
// CHECK-LABEL: sil hidden @_TF14foreign_errors26testPreservedResultBridgedFzT_Si
// CHECK: [[T0:%.*]] = metatype $@thick ErrorProne.Type
// CHECK: [[T1:%.*]] = class_method [volatile] [[T0]] : $@thick ErrorProne.Type, #ErrorProne.ounceWord!1.foreign : (ErrorProne.Type) -> () throws -> Int , $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int
// CHECK: [[OPTERR:%.*]] = alloc_stack $Optional<NSError>
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int{{.*}}"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[NORMAL_BB:bb[0-9]+]], [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return [[RESULT]]
// CHECK: [[ERROR_BB]]
func testPreservedResultInverted() throws {
try ErrorProne.once()
}
// CHECK-LABEL: sil hidden @_TF14foreign_errors27testPreservedResultInvertedFzT_T_
// CHECK: [[T0:%.*]] = metatype $@thick ErrorProne.Type
// CHECK: [[T1:%.*]] = class_method [volatile] [[T0]] : $@thick ErrorProne.Type, #ErrorProne.once!1.foreign : (ErrorProne.Type) -> () throws -> () , $@convention(objc_method) (Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>, @objc_metatype ErrorProne.Type) -> Int32
// CHECK: [[OPTERR:%.*]] = alloc_stack $Optional<NSError>
// CHECK: [[RESULT:%.*]] = apply [[T1]](
// CHECK: [[T0:%.*]] = struct_extract [[RESULT]]
// CHECK: [[T1:%.*]] = integer_literal $[[PRIM:Builtin.Int[0-9]+]], 0
// CHECK: [[T2:%.*]] = builtin "cmp_ne_Int32"([[T0]] : $[[PRIM]], [[T1]] : $[[PRIM]])
// CHECK: cond_br [[T2]], [[ERROR_BB:bb[0-9]+]], [[NORMAL_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]:
// CHECK-NOT: destroy_value
// CHECK: return {{%.+}} : $()
// CHECK: [[ERROR_BB]]
|
apache-2.0
|
1fc2bff44cd5d01241d537073afe1ea4
| 61.155797 | 331 | 0.633518 | 3.462858 | false | true | false | false |
fdempers/eddystone
|
tools/ios-eddystone-scanner-sample/EddystoneScannerSampleSwift/DispatchTimer.swift
|
13
|
2482
|
// Copyright 2015 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 UIKit
///
/// DispatchTimer
///
/// Much like an NSTimer from Cocoa, but implemented using dispatch queues instead.
///
class DispatchTimer: NSObject {
/// Type for the handler block executed when a dispatch timer fires.
///
/// :param: timer The timer which triggered this block
typealias TimerHandler = (DispatchTimer) -> Void
private let timerBlock: TimerHandler
private let queue: dispatch_queue_t
private let delay: NSTimeInterval
private var wrappedBlock: (() -> Void)?
private let source: dispatch_source_t
init(delay: NSTimeInterval, queue: dispatch_queue_t, block: TimerHandler) {
timerBlock = block
self.queue = queue
self.delay = delay
self.source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue)
super.init()
let wrapper = { () -> Void in
if dispatch_source_testcancel(self.source) == 0 {
dispatch_source_cancel(self.source)
self.timerBlock(self)
}
}
self.wrappedBlock = wrapper
}
class func scheduledDispatchTimer(delay: NSTimeInterval,
queue: dispatch_queue_t,
block: TimerHandler) -> DispatchTimer {
let dt = DispatchTimer(delay: delay, queue: queue, block: block)
dt.schedule()
return dt
}
func schedule() {
self.reschedule()
dispatch_source_set_event_handler(self.source, self.wrappedBlock)
dispatch_resume(self.source)
}
func reschedule() {
let start = dispatch_time(DISPATCH_TIME_NOW, Int64(self.delay * Double(NSEC_PER_SEC)))
// Leeway is 10% of timer delay
dispatch_source_set_timer(self.source, start, DISPATCH_TIME_FOREVER,
UInt64((self.delay / 10.0) * Double(NSEC_PER_SEC)))
}
func suspend() {
dispatch_suspend(self.source)
}
func resume() {
dispatch_resume(self.source)
}
func cancel() {
dispatch_source_cancel(self.source)
}
}
|
apache-2.0
|
94cd6218269845fb1da2c0343f07de33
| 26.88764 | 90 | 0.69299 | 3.921011 | false | false | false | false |
adrfer/swift
|
test/Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift
|
27
|
970
|
@_exported import ObjectiveC
@_exported import CoreGraphics
public func == (lhs: CGPoint, rhs: CGPoint) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
public struct CGFloat {
#if arch(i386) || arch(arm)
public typealias UnderlyingType = Float
#elseif arch(x86_64) || arch(arm64)
public typealias UnderlyingType = Double
#endif
public init() {
self.value = 0.0
}
public init(_ value: Int) {
self.value = UnderlyingType(value)
}
public init(_ value: Float) {
self.value = UnderlyingType(value)
}
public init(_ value: Double) {
self.value = UnderlyingType(value)
}
var value: UnderlyingType
}
public func ==(lhs: CGFloat, rhs: CGFloat) -> Bool {
return lhs.value == rhs.value
}
extension CGFloat : IntegerLiteralConvertible, Equatable {
public init(integerLiteral value: UnderlyingType) {
self.value = value
}
}
public extension Double {
init(_ value: CGFloat) {
self = Double(value.value)
}
}
|
apache-2.0
|
e8eecb374d8e31bedda001843cc3f368
| 19.208333 | 58 | 0.665979 | 3.688213 | false | false | false | false |
csnu17/Firebase-iOS-Authentication-Demo
|
firebase authentication/EmailLoginViewController.swift
|
1
|
3305
|
//
// EmailLoginViewController.swift
// firebase authentication
//
// Created by Kittisak Phetrungnapha on 9/26/2559 BE.
// Copyright © 2559 Kittisak Phetrungnapha. All rights reserved.
//
import UIKit
import FirebaseAuth
import IQKeyboardManagerSwift
class EmailLoginViewController: UIViewController {
// MARK: - Property
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
private var authListener: FIRAuthStateDidChangeListenerHandle?
// MARK: - Action
@IBAction func loginButtonTouch(_ sender: AnyObject) {
FIRAuth.auth()?.signIn(withEmail: usernameTextField.text!, password: passwordTextField.text!) { (user, error) in
if let error = error {
AppDelegate.showAlertMsg(withViewController: self, message: error.localizedDescription)
}
}
}
@IBAction func registerButtonTouch(_ sender: AnyObject) {
FIRAuth.auth()?.createUser(withEmail: usernameTextField.text!, password: passwordTextField.text!) { (user, error) in
if let error = error {
AppDelegate.showAlertMsg(withViewController: self, message: error.localizedDescription)
}
}
}
@IBAction func resetPasswordButtonTouch(_ sender: AnyObject) {
let resetPasswordAlert = UIAlertController(title: "Reset Password", message: nil, preferredStyle: .alert)
resetPasswordAlert.addTextField { (textField: UITextField) in
textField.placeholder = "Enter your email"
textField.clearButtonMode = .whileEditing
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (action: UIAlertAction) in
let textField = resetPasswordAlert.textFields![0]
FIRAuth.auth()?.sendPasswordReset(withEmail: textField.text!) { error in
if let error = error {
AppDelegate.showAlertMsg(withViewController: self, message: error.localizedDescription)
} else {
AppDelegate.showAlertMsg(withViewController: self, message: "Password reset email was sent")
}
}
}
resetPasswordAlert.addAction(cancelAction)
resetPasswordAlert.addAction(confirmAction)
self.present(resetPasswordAlert, animated: true, completion: nil)
}
// MARK: - View controller life cycle
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Login with Email"
}
override func viewWillAppear(_ animated: Bool) {
authListener = FIRAuth.auth()?.addStateDidChangeListener({ (auth, user) in
if let _ = user {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.setRootViewControllerWith(viewIdentifier: ViewIdentifiers.profile.rawValue)
}
})
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
let _ = IQKeyboardManager.sharedManager().resignFirstResponder()
FIRAuth.auth()?.removeStateDidChangeListener(authListener!)
}
}
|
mit
|
c4b24112711f152530730ad111d78eaa
| 38.807229 | 124 | 0.655266 | 5.407529 | false | false | false | false |
AlbanPerli/HandWriting-Recognition-iOS
|
HandWriting-Learner/ViewController.swift
|
1
|
9304
|
//
// ViewController.swift
// HandWriting-Learner
//
// Created by Alban on 29.02.16.
// Copyright © 2016 Alban Perli. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDataSource {
var currentNetworkName:String!
//
var lastPoint:CGPoint!
var isSwiping:Bool!
var red:CGFloat!
var green:CGFloat!
var blue:CGFloat!
var xPoints:[Float] = []
var yPoints:[Float] = []
//
var historyDatasource = [NSDictionary]()
@IBOutlet weak var result: UILabel!
@IBOutlet weak var segmented: UISegmentedControl!
@IBOutlet weak var actionButton: UIBarButtonItem!
@IBOutlet weak var trainingSwitch: UISwitch!
@IBOutlet weak var tableView: UITableView!
@IBOutlet var imageView: UIImageView!
//MARK: Data preprocessing methods
func preprocessedImagePixelArray()->(pixels:[Float]?,resizedImg:UIImage)?{
guard self.imageView.image != nil else {
return nil
}
let framedImg = self.framedImg()
let resizedImg = framedImg!.toSize(CGSizeMake(30, 30))
return (resizedImg.pixelsArray().pixelValues,resizedImg)
}
func framedImg() -> UIImage? {
guard self.imageView.image != nil else {
return nil
}
let freeSpaceAroundDrawinFrame:CGFloat = 5.0
let topLeft = CGPointMake(CGFloat(xPoints.minElement()!), CGFloat(yPoints.minElement()!))
let bottomRight = CGPointMake(CGFloat(xPoints.maxElement()!), CGFloat(yPoints.maxElement()!))
return self.imageView.image!.extractFrame(topLeft,bottomRight: bottomRight, pixelMargin: freeSpaceAroundDrawinFrame)
}
//MARK: FFNN methods
func trainNeurons(){
// Retreive pixel from drawn image
if let preProcessedDatas = self.preprocessedImagePixelArray() {
let pixelArray = preProcessedDatas.pixels
let img = preProcessedDatas.resizedImg
guard pixelArray != nil else {
return
}
let answer : [Float]
switch segmented.selectedSegmentIndex {
case 0: // A
answer = [1.0,0.0,0.0,0.0]
case 1: // B
answer = [0.0,1.0,0.0,0.0]
case 2: // C
answer = [0.0,0.0,1.0,0.0]
case 3: // D
answer = [0.0,0.0,0.0,1.0]
default:
answer = []
}
let trainingValues = FFNNManager.instance.trainNetwork(pixelArray!, answer:answer, epoch: 1)
let result = String(trainingValues.output)
self.result.text = result
historyDatasource.insert(NSDictionary(dictionaryLiteral: ("img",img),("result",result)), atIndex: 0)
tableView.reloadData()
print(trainingValues.error)
}
return
}
func askNeurons(){
// Retreive pixel from drawn image
if let preProcessedDatas = self.preprocessedImagePixelArray() {
let pixelArray = preProcessedDatas.pixels
guard pixelArray != nil else {
return
}
// Send pixel arrays to the network and receive "prediction"
let output = FFNNManager.instance.predictionForInput(pixelArray!)
print(output)
let maxValue = output.maxElement()!
// Not sure enough
if maxValue < 0.8 {
self.result.text = "Not sure enough"
return
}
// Convert the max value (> 0.8) to int to get
// the index value of the switch
let index = output.indexOf(maxValue)! as Int
self.segmented.selectedSegmentIndex = index
switch index {
case 0:
self.result.text = "A"
case 1:
self.result.text = "B"
case 2:
self.result.text = "C"
case 3:
self.result.text = "D"
default:
self.result.text = "Not Sure"
}
}
}
//MARK: UI Actions
@IBAction func trainingModeSwitchDidChangeValue(sender: UISwitch) {
if sender.on {
actionButton.title = "Train"
}else {
actionButton.title = "Ask"
}
self.tableView.hidden = !sender.on
self.result.hidden = !sender.on
}
@IBAction func actionBtnClicked(sender: AnyObject) {
if trainingSwitch.on {
trainNeurons()
}else{
askNeurons()
}
// Release all the point
xPoints = []
yPoints = []
// Clear the image view
self.imageView.image = nil
}
@IBAction func saveNetworkBtnClicked(sender: AnyObject) {
self.imageView.image = nil
FFNNManager.instance.saveNetworkWithName(currentNetworkName)
self.dismissViewControllerAnimated(true, completion: nil)
}
//MARK: UI Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib
self.imageView.layer.borderWidth = 1.0
self.imageView.layer.borderColor = UIColor.grayColor().CGColor
self.tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: TableView Datasource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("historyCell", forIndexPath: indexPath) as! HistoryTableViewCell
let dico = historyDatasource[indexPath.row]
cell.sentImg.image = dico["img"] as? UIImage
cell.sentImg.layer.borderWidth = 1.0
cell.sentImg.layer.borderColor = UIColor.grayColor().CGColor
cell.predictionLabel.text = dico["result"] as? String
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return historyDatasource.count
}
//MARK: Drawing methods
override func touchesBegan(touches: Set<UITouch>,
withEvent event: UIEvent?){
isSwiping = false
let touch = touches.first
lastPoint = touch!.locationInView(imageView)
xPoints.append(Float(lastPoint.x))
yPoints.append(Float(lastPoint.y))
}
override func touchesMoved(touches: Set<UITouch>,
withEvent event: UIEvent?){
isSwiping = true;
let touch = touches.first
let currentPoint = touch!.locationInView(imageView)
UIGraphicsBeginImageContext(self.imageView.frame.size)
self.imageView.image?.drawInRect(CGRectMake(0, 0, self.imageView.frame.size.width, self.imageView.frame.size.height))
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y)
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y)
CGContextSetLineCap(UIGraphicsGetCurrentContext(),CGLineCap.Round)
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 9.0)
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(),0.0, 0.0, 0.0, 1.0)
CGContextStrokePath(UIGraphicsGetCurrentContext())
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
lastPoint = currentPoint
xPoints.append(Float(lastPoint.x))
yPoints.append(Float(lastPoint.y))
}
override func touchesEnded(touches: Set<UITouch>,
withEvent event: UIEvent?){
if(!isSwiping) {
// This is a single touch, draw a point
UIGraphicsBeginImageContext(self.imageView.frame.size)
self.imageView.image?.drawInRect(CGRectMake(0, 0, self.imageView.frame.size.width, self.imageView.frame.size.height))
CGContextSetLineCap(UIGraphicsGetCurrentContext(), CGLineCap.Round)
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 9.0)
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0)
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y)
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y)
CGContextStrokePath(UIGraphicsGetCurrentContext())
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
}
|
mit
|
4d7bd5ee74d6851f5b796f3d2dba6694
| 31.872792 | 133 | 0.577448 | 5.247039 | false | false | false | false |
alex-alex/S2Geometry
|
Sources/S2Cap.swift
|
1
|
11961
|
//
// S2Cap.swift
// S2Geometry
//
// Created by Alex Studnicka on 7/1/16.
// Copyright © 2016 Alex Studnicka. MIT License.
//
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
/**
This class represents a spherical cap, i.e. a portion of a sphere cut off by
a plane. The cap is defined by its axis and height. This representation has
good numerical accuracy for very small caps (unlike the (axis,
min-distance-from-origin) representation), and is also efficient for
containment tests (unlike the (axis, angle) representation).
Here are some useful relationships between the cap height (h), the cap
opening angle (theta), the maximum chord length from the cap's center (d),
and the radius of cap's base (a). All formulas assume a unit radius.
h = 1 - cos(theta) = 2 sin^2(theta/2) d^2 = 2 h = a^2 + h^2
*/
public struct S2Cap: S2Region {
/**
Multiply a positive number by this constant to ensure that the result of a
floating point operation is at least as large as the true
infinite-precision result.
*/
private static let roundUp = 2 / Double(1 << 52)
public let axis: S2Point
public let height: Double
/**
Create a cap given its axis and the cap height, i.e. the maximum projected
distance along the cap axis from the cap center. 'axis' should be a
unit-length vector.
*/
public init(axis: S2Point = S2Point(), height: Double = 0) {
self.axis = axis
self.height = height
}
/**
Create a cap given its axis and the cap opening angle, i.e. maximum angle
between the axis and a point on the cap. 'axis' should be a unit-length
vector, and 'angle' should be between 0 and 180 degrees.
*/
public init(axis: S2Point, angle: S1Angle) {
// The height of the cap can be computed as 1-cos(angle), but this isn't
// very accurate for angles close to zero (where cos(angle) is almost 1).
// Computing it as 2*(sin(angle/2)**2) gives much better precision.
// assert (S2.isUnitLength(axis));
let d = sin(0.5 * angle.radians)
self.init(axis: axis, height: 2 * d * d)
}
/**
Create a cap given its axis and its area in steradians. 'axis' should be a
unit-length vector, and 'area' should be between 0 and 4 * M_PI.
*/
public init(axis: S2Point, area: Double) {
// assert (S2.isUnitLength(axis));
self.init(axis: axis, height: area / (2 * M_PI))
}
/// Return an empty cap, i.e. a cap that contains no points.
public static let empty = S2Cap(axis: S2Point(x: 1, y: 0, z: 0), height: -1)
/// Return a full cap, i.e. a cap that contains all points.
public static let full = S2Cap(axis: S2Point(x: 1, y: 0, z: 0), height: 2)
public var area: Double {
return 2 * M_PI * max(0, height)
}
/// Return the cap opening angle in radians, or a negative number for empty caps.
public var angle: S1Angle {
// This could also be computed as acos(1 - height_), but the following
// formula is much more accurate when the cap height is small. It
// follows from the relationship h = 1 - cos(theta) = 2 sin^2(theta/2).
if isEmpty {
return S1Angle(radians: -1)
}
return S1Angle(radians: 2 * asin(sqrt(0.5 * height)))
}
/// We allow negative heights (to represent empty caps) but not heights greater than 2.
public var isValid: Bool {
return S2.isUnitLength(point: axis) && height <= 2
}
/// Return true if the cap is empty, i.e. it contains no points.
public var isEmpty: Bool {
return height < 0
}
/// Return true if the cap is full, i.e. it contains all points.
public var isFull: Bool {
return height >= 2
}
/**
Return the complement of the interior of the cap. A cap and its complement
have the same boundary but do not share any interior points. The complement
operator is not a bijection, since the complement of a singleton cap
(containing a single point) is the same as the complement of an empty cap.
*/
public var complement: S2Cap {
// The complement of a full cap is an empty cap, not a singleton.
// Also make sure that the complement of an empty cap has height 2.
let cHeight = isFull ? -1 : 2 - max(height, 0.0)
return S2Cap(axis: -axis, height: cHeight)
}
/**
* Return true if and only if this cap contains the given other cap (in a set
* containment sense, e.g. every cap contains the empty cap).
*/
public func contains(other: S2Cap) -> Bool {
if isFull || other.isEmpty {
return true
}
return angle.radians >= axis.angle(to: other.axis) + other.angle.radians
}
/**
Return true if and only if the interior of this cap intersects the given
other cap. (This relationship is not symmetric, since only the interior of
this cap is used.)
*/
public func interiorIntersects(with other: S2Cap) -> Bool {
// Interior(X) intersects Y if and only if Complement(Interior(X)) does not contain Y.
return !complement.contains(other: other)
}
/**
Return true if and only if the given point is contained in the interior of
the region (i.e. the region excluding its boundary). 'p' should be a
unit-length vector.
*/
public func interiorContains(point p: S2Point) -> Bool {
// assert (S2.isUnitLength(p));
return isFull || (axis - p).norm2 < 2 * height
}
/**
Increase the cap height if necessary to include the given point. If the cap
is empty the axis is set to the given point, but otherwise it is left
unchanged. 'p' should be a unit-length vector.
*/
public func add(point p: S2Point) -> S2Cap {
// Compute the squared chord length, then convert it into a height.
// assert (S2.isUnitLength(p));
if isEmpty {
return S2Cap(axis: p, height: 0)
} else {
// To make sure that the resulting cap actually includes this point,
// we need to round up the distance calculation. That is, after
// calling cap.AddPoint(p), cap.Contains(p) should be true.
let dist2 = (axis - p).norm2
let newHeight = max(height, S2Cap.roundUp * 0.5 * dist2)
return S2Cap(axis: axis, height: newHeight)
}
}
// Increase the cap height if necessary to include "other". If the current
// cap is empty it is set to the given other cap.
public func add(cap other: S2Cap) -> S2Cap {
if isEmpty {
return S2Cap(axis: other.axis, height: other.height)
} else {
// See comments for FromAxisAngle() and AddPoint(). This could be
// optimized by doing the calculation in terms of cap heights rather
// than cap opening angles.
let angle = axis.angle(to: other.axis) + other.angle.radians
if angle >= M_PI {
return S2Cap(axis: axis, height: 2) //Full cap
} else {
let d = sin(0.5 * angle)
let newHeight = max(height, S2Cap.roundUp * 2 * d * d)
return S2Cap(axis: axis, height: newHeight)
}
}
}
/// Return true if the cap intersects 'cell', given that the cap vertices have alrady been checked.
public func intersects(with cell: S2Cell, vertices: [S2Point]) -> Bool {
// Return true if this cap intersects any point of 'cell' excluding its
// vertices (which are assumed to already have been checked).
// If the cap is a hemisphere or larger, the cell and the complement of the
// cap are both convex. Therefore since no vertex of the cell is contained,
// no other interior point of the cell is contained either.
if height >= 1 {
return false
}
// We need to check for empty caps due to the axis check just below.
if isEmpty {
return false
}
// Optimization: return true if the cell contains the cap axis. (This
// allows half of the edge checks below to be skipped.)
if cell.contains(point: axis) {
return true
}
// At this point we know that the cell does not contain the cap axis,
// and the cap does not contain any cell vertex. The only way that they
// can intersect is if the cap intersects the interior of some edge.
let sin2Angle = height * (2 - height) // sin^2(capAngle)
for k in 0 ..< 4 {
let edge = cell.getRawEdge(k)
let dot = axis.dotProd(edge)
if dot > 0 {
// The axis is in the interior half-space defined by the edge. We don't
// need to consider these edges, since if the cap intersects this edge
// then it also intersects the edge on the opposite side of the cell
// (because we know the axis is not contained with the cell).
continue
}
// The Norm2() factor is necessary because "edge" is not normalized.
if dot * dot > sin2Angle * edge.norm2 {
return false // Entire cap is on the exterior side of this edge.
}
// Otherwise, the great circle containing this edge intersects
// the interior of the cap. We just need to check whether the point
// of closest approach occurs between the two edge endpoints.
let dir = edge.crossProd(axis)
if (dir.dotProd(vertices[k]) < 0 && dir.dotProd(vertices[(k + 1) & 3]) > 0) {
return true
}
}
return false
}
public func contains(point p: S2Point) -> Bool {
// The point 'p' should be a unit-length vector.
// assert (S2.isUnitLength(p));
return (axis - p).norm2 <= 2 * height
}
////////////////////////////////////////////////////////////////////////
// MARK: S2Region
////////////////////////////////////////////////////////////////////////
public var capBound: S2Cap {
return self
}
public var rectBound: S2LatLngRect {
if isEmpty {
return .empty
}
// Convert the axis to a (lat,lng) pair, and compute the cap angle.
let axisLatLng = S2LatLng(point: axis)
let capAngle = angle.radians
var allLongitudes = false
var lat: (Double, Double) = (0, 0)
var lng: (Double, Double) = (-M_PI, M_PI)
// Check whether cap includes the south pole.
lat.0 = axisLatLng.lat.radians - capAngle
if lat.0 <= -M_PI_2 {
lat.0 = -M_PI_2
allLongitudes = true
}
// Check whether cap includes the north pole.
lat.1 = axisLatLng.lat.radians + capAngle
if lat.1 >= M_PI_2 {
lat.1 = M_PI_2
allLongitudes = true
}
if !allLongitudes {
// Compute the range of longitudes covered by the cap. We use the law
// of sines for spherical triangles. Consider the triangle ABC where
// A is the north pole, B is the center of the cap, and C is the point
// of tangency between the cap boundary and a line of longitude. Then
// C is a right angle, and letting a,b,c denote the sides opposite A,B,C,
// we have sin(a)/sin(A) = sin(c)/sin(C), or sin(A) = sin(a)/sin(c).
// Here "a" is the cap angle, and "c" is the colatitude (90 degrees
// minus the latitude). This formula also works for negative latitudes.
//
// The formula for sin(a) follows from the relationship h = 1 - cos(a).
let sinA = sqrt(height * (2 - height))
let sinC = cos(axisLatLng.lat.radians)
if sinA <= sinC {
let angleA = asin(sinA / sinC)
lng.0 = remainder(axisLatLng.lng.radians - angleA, 2 * M_PI)
lng.1 = remainder(axisLatLng.lng.radians + angleA, 2 * M_PI)
}
}
return S2LatLngRect(lat: R1Interval(lo: lat.0, hi: lat.1), lng: S1Interval(lo: lng.0, hi: lng.1))
}
public func contains(cell: S2Cell) -> Bool {
// If the cap does not contain all cell vertices, return false.
// We check the vertices before taking the Complement() because we can't
// accurately represent the complement of a very small cap (a height
// of 2-epsilon is rounded off to 2).
var vertices: [S2Point] = []
for k in 0 ..< 4 {
let vertex = cell.getVertex(k)
if !contains(point: vertex) {
return false
}
vertices.append(vertex)
}
// Otherwise, return true if the complement of the cap does not intersect
// the cell. (This test is slightly conservative, because technically we
// want Complement().InteriorIntersects() here.)
return !complement.intersects(with: cell, vertices: vertices)
}
public func mayIntersect(cell: S2Cell) -> Bool {
// If the cap contains any cell vertex, return true.
var vertices: [S2Point] = []
for k in 0 ..< 4 {
let vertex = cell.getVertex(k)
if contains(point: vertex) {
return true
}
vertices.append(vertex)
}
return intersects(with: cell, vertices: vertices)
}
}
|
mit
|
eec960d0b8092cdfdab7473f78283fa1
| 34.073314 | 100 | 0.669314 | 3.313019 | false | false | false | false |
hengZhuo/DouYuZhiBo
|
swift-DYZB/swift-DYZB/Classes/Home/Controller/BaseController.swift
|
1
|
1231
|
//
// BaseController.swift
// swift-DYZB
//
// Created by chenrin on 2016/11/22.
// Copyright © 2016年 zhuoheng. All rights reserved.
//
import UIKit
class BaseController: UIViewController {
var baseView : UIView?
// MARK:- 懒加载
fileprivate lazy var animImageView: UIImageView = {[unowned self] in
let imageView = UIImageView(image: UIImage(named: "img_loading_1"))
imageView.center = self.view.center
imageView.animationImages = [UIImage(named:"img_loading_1")!,UIImage(named:"img_loading_2")!]
imageView.animationDuration = 0.5
imageView.animationRepeatCount = LONG_MAX
imageView.autoresizingMask = [.flexibleTopMargin,.flexibleBottomMargin]
return imageView
}()
// MARK:- 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
}
}
// MARK:- 设置UI界面
extension BaseController{
fileprivate func setUpUI() {
view.backgroundColor = UIColor.white
//执行动画
view.addSubview(animImageView)
animImageView.startAnimating()
}
func stopAnimImageView() {
animImageView.stopAnimating()
animImageView.isHidden = true
}
}
|
mit
|
354d2942d530fdfe4083c5df3ebeffae
| 24.489362 | 102 | 0.65025 | 4.625483 | false | false | false | false |
qutheory/vapor
|
Sources/Vapor/Utilities/DotEnv.swift
|
1
|
8647
|
#if os(Linux)
import Glibc
#else
import Darwin
#endif
/// Reads dotenv (`.env`) files and loads them into the current process.
///
/// let fileio: NonBlockingFileIO
/// let elg: EventLoopGroup
/// let file = try DotEnvFile.read(path: ".env", fileio: fileio, on: elg.next()).wait()
/// for line in file.lines {
/// print("\(line.key)=\(line.value)")
/// }
/// file.load(overwrite: true) // loads all lines into the process
///
/// Dotenv files are formatted using `KEY=VALUE` syntax. They support comments using the `#` symbol.
/// They also support strings, both single and double-quoted.
///
/// FOO=BAR
/// STRING='Single Quote String'
/// # Comment
/// STRING2="Double Quoted\nString"
///
/// Single-quoted strings are parsed literally. Double-quoted strings may contain escaped newlines
/// that will be converted to actual newlines.
public struct DotEnvFile {
/// Reads a dotenv file from the supplied path and loads it into the process.
///
/// let fileio: NonBlockingFileIO
/// let elg: EventLoopGroup
/// try DotEnvFile.load(path: ".env", fileio: fileio, on: elg.next()).wait()
/// print(Environment.process.FOO) // BAR
///
/// Use `DotEnvFile.read` to read the file without loading it.
///
/// - parameters:
/// - path: Absolute or relative path of the dotenv file.
/// - fileio: File loader.
/// - eventLoop: Eventloop to perform async work on.
/// - overwrite: If `true`, values already existing in the process' env
/// will be overwritten. Defaults to `false`.
public static func load(
path: String,
fileio: NonBlockingFileIO,
on eventLoop: EventLoop,
overwrite: Bool = false
) -> EventLoopFuture<Void> {
return self.read(path: path, fileio: fileio, on: eventLoop)
.map { $0.load(overwrite: overwrite) }
}
/// Reads a dotenv file from the supplied path.
///
/// let fileio: NonBlockingFileIO
/// let elg: EventLoopGroup
/// let file = try DotEnvFile.read(path: ".env", fileio: fileio, on: elg.next()).wait()
/// for line in file.lines {
/// print("\(line.key)=\(line.value)")
/// }
/// file.load(overwrite: true) // loads all lines into the process
/// print(Environment.process.FOO) // BAR
///
/// Use `DotEnvFile.load` to read and load with one method.
///
/// - parameters:
/// - path: Absolute or relative path of the dotenv file.
/// - fileio: File loader.
/// - eventLoop: Eventloop to perform async work on.
public static func read(
path: String,
fileio: NonBlockingFileIO,
on eventLoop: EventLoop
) -> EventLoopFuture<DotEnvFile> {
return fileio.openFile(path: path, eventLoop: eventLoop).flatMap { arg -> EventLoopFuture<ByteBuffer> in
return fileio.read(fileRegion: arg.1, allocator: .init(), eventLoop: eventLoop)
.flatMapThrowing
{ buffer in
try arg.0.close()
return buffer
}
}.map { buffer in
var parser = Parser(source: buffer)
return .init(lines: parser.parse())
}
}
/// Represents a `KEY=VALUE` pair in a dotenv file.
public struct Line: CustomStringConvertible, Equatable {
/// The key.
public let key: String
/// The value.
public let value: String
/// `CustomStringConvertible` conformance.
public var description: String {
return "\(self.key)=\(self.value)"
}
}
/// All `KEY=VALUE` pairs found in the file.
public let lines: [Line]
/// Creates a new DotEnvFile
init(lines: [Line]) {
self.lines = lines
}
/// Loads this file's `KEY=VALUE` pairs into the current process.
///
/// let file: DotEnvFile
/// file.load(overwrite: true) // loads all lines into the process
///
/// - parameters:
/// - overwrite: If `true`, values already existing in the process' env
/// will be overwritten. Defaults to `false`.
public func load(overwrite: Bool = false) {
for line in self.lines {
setenv(line.key, line.value, overwrite ? 1 : 0)
}
}
}
// MARK: Parser
extension DotEnvFile {
struct Parser {
var source: ByteBuffer
init(source: ByteBuffer) {
self.source = source
}
mutating func parse() -> [Line] {
var lines: [Line] = []
while let next = self.parseNext() {
lines.append(next)
}
return lines
}
private mutating func parseNext() -> Line? {
self.skipSpaces()
guard let peek = self.peek() else {
return nil
}
switch peek {
case .octothorpe:
// comment following, skip it
self.skipComment()
// then parse next
return self.parseNext()
case .newLine:
// empty line, skip
self.pop() // \n
// then parse next
return self.parseNext()
default:
// this is a valid line, parse it
return self.parseLine()
}
}
private mutating func skipComment() {
guard let commentLength = self.countDistance(to: .newLine) else {
return
}
self.source.moveReaderIndex(forwardBy: commentLength + 1) // include newline
}
private mutating func parseLine() -> Line? {
guard let keyLength = self.countDistance(to: .equal) else {
return nil
}
guard let key = self.source.readString(length: keyLength) else {
return nil
}
self.pop() // =
guard let value = self.parseLineValue() else {
return nil
}
return Line(key: key, value: value)
}
private mutating func parseLineValue() -> String? {
let valueLength: Int
if let toNewLine = self.countDistance(to: .newLine) {
valueLength = toNewLine
} else {
valueLength = self.source.readableBytes
}
guard let value = self.source.readString(length: valueLength) else {
return nil
}
guard let first = value.first, let last = value.last else {
return value
}
// check for quoted strings
switch (first, last) {
case ("\"", "\""):
// double quoted strings support escaped \n
return value.dropFirst().dropLast()
.replacingOccurrences(of: "\\n", with: "\n")
case ("'", "'"):
// single quoted strings just need quotes removed
return value.dropFirst().dropLast() + ""
default: return value
}
}
private mutating func skipSpaces() {
scan: while let next = self.peek() {
switch next {
case .space: self.pop()
default: break scan
}
}
}
private func peek() -> UInt8? {
return self.source.getInteger(at: self.source.readerIndex)
}
private mutating func pop() {
self.source.moveReaderIndex(forwardBy: 1)
}
private func countDistance(to byte: UInt8) -> Int? {
var copy = self.source
var found = false
scan: while let next = copy.readInteger(as: UInt8.self) {
if next == byte {
found = true
break scan
}
}
guard found else {
return nil
}
let distance = copy.readerIndex - source.readerIndex
guard distance != 0 else {
return nil
}
return distance - 1
}
}
}
private extension UInt8 {
static var newLine: UInt8 {
return 0xA
}
static var space: UInt8 {
return 0x20
}
static var octothorpe: UInt8 {
return 0x23
}
static var equal: UInt8 {
return 0x3D
}
}
|
mit
|
0bac48c0ed24bfbe6b6419cd1641314b
| 31.630189 | 112 | 0.519949 | 4.579979 | false | false | false | false |
icapps/ios_objective_c_workshop
|
Teacher/ObjcTextInput/Pods/Faro/Sources/Request/MultipartFile.swift
|
5
|
867
|
import Foundation
open class MultipartFile {
let parameterName: String
let data: Data
let mimeType: MultipartMimeType
/// Initializes MultipartFile to send to the server.
/// parameter parameterName: the name of the multipart file parameter as defined on the server.
/// parameter data: the file or image as Data. (e.g. a UIImage converted to Data using UIImageJPEGRepresentation())
/// parameter mimeType: the correct mime type for the file.
public required init(parameterName: String, data: Data, mimeType: MultipartMimeType) {
self.parameterName = parameterName
self.data = data
self.mimeType = mimeType
}
}
public enum MultipartMimeType: String {
// Supported image types
case jpeg = "image/jpg"
case png = "image/png"
// Supported text types
case plain = "text/plain"
}
|
mit
|
bf4953b06719125d9a8a4f2b0d01f163
| 32.346154 | 119 | 0.692042 | 4.763736 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift
|
Solutions/Solutions/Hard/Hard_084_Largest_Rectangle_In_Histogram.swift
|
1
|
1667
|
/*
https://leetcode.com/problems/largest-rectangle-in-histogram/
#84 Largest Rectangle in Histogram
Level: hard
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.
For example,
Given height = [2,1,5,6,2,3],
return 10.
Inspired by http://www.geeksforgeeks.org/largest-rectangle-under-histogram/
*/
import Foundation
struct Hard_084_Largest_Rectangle_In_Histogram {
static func largestRectangleArea(_ heights: [Int]) -> Int {
var stack:[Int] = []
var max_area = 0
var top_of_stack: Int
var area_with_top: Int
var i = 0
while i < heights.count {
if stack.isEmpty || heights[stack.last!] <= heights[i] {
stack.append(i)
i += 1
} else {
top_of_stack = stack.last!
stack.removeLast()
area_with_top = heights[top_of_stack] * (stack.isEmpty ? i : i - stack.last! - 1)
if max_area < area_with_top {
max_area = area_with_top
}
}
}
while stack.isEmpty == false {
top_of_stack = stack.last!
stack.removeLast()
area_with_top = heights[top_of_stack] * (stack.isEmpty ? i : i - stack.last! - 1)
if max_area < area_with_top {
max_area = area_with_top
}
}
return max_area
}
}
|
mit
|
1e43686d5cda61aa700d1d02fffc6e75
| 28.245614 | 156 | 0.566887 | 3.704444 | false | false | false | false |
mathcamp/Carlos
|
Tests/BatchTests.swift
|
1
|
9136
|
import Foundation
import Carlos
import Quick
import Nimble
import PiedPiper
class BatchTests: QuickSpec {
override func spec() {
let requestsCount = 5
var cache: CacheLevelFake<Int, String>!
var resultingFuture: Future<[String]>!
beforeEach {
cache = CacheLevelFake<Int, String>()
}
describe("batchGetAll") {
var result: [String]!
var errors: [ErrorType]!
var canceled: Bool!
beforeEach {
errors = []
result = nil
canceled = false
resultingFuture = cache.batchGetAll(Array(0..<requestsCount))
.onSuccess {
result = $0
}
.onFailure {
errors.append($0)
}
.onCancel {
canceled = true
}
}
it("should dispatch all of the requests to the underlying cache") {
expect(cache.numberOfTimesCalledGet).to(equal(requestsCount))
}
context("when one of the requests fails") {
beforeEach {
cache.promisesReturned[0].fail(TestError.SimpleError)
}
it("should fail the resulting future") {
expect(errors).notTo(beEmpty())
}
it("should pass the right error") {
expect(errors.first as? TestError).to(equal(TestError.SimpleError))
}
it("should not call the success closure") {
expect(result).to(beNil())
}
}
context("when one of the requests succeeds") {
beforeEach {
cache.promisesReturned[0].succeed("Test")
}
it("should not call the failure closure") {
expect(errors).to(beEmpty())
}
it("should not call the success closure") {
expect(result).to(beNil())
}
}
context("when all of the requests succeed") {
beforeEach {
cache.promisesReturned.enumerate().forEach { (iteration, promise) in
promise.succeed("\(iteration)")
}
}
it("should not call the failure closure") {
expect(errors).to(beEmpty())
}
it("should call the success closure") {
expect(result).notTo(beNil())
}
it("should pass all the values") {
expect(result.count).to(equal(cache.promisesReturned.count))
}
it("should pass the individual results in the right order") {
expect(result).to(equal(cache.promisesReturned.enumerate().map { (iteration, _) in
"\(iteration)"
}))
}
}
context("when one of the requests is canceled") {
beforeEach {
cache.promisesReturned[0].cancel()
}
it("should not call the success closure") {
expect(result).to(beNil())
}
it("should call the onCancel closure") {
expect(canceled).to(beTrue())
}
}
context("when the resulting request is canceled") {
beforeEach {
resultingFuture.cancel()
}
it("should cancel all the underlying requests") {
var canceledCount = 0
cache.promisesReturned.forEach { promise in
promise.onCancel {
canceledCount += 1
}
}
expect(canceledCount).to(equal(cache.promisesReturned.count))
}
}
}
describe("batchGetSome") {
var result: [String]!
var errors: [ErrorType]!
var canceled: Bool!
beforeEach {
errors = []
result = nil
canceled = false
resultingFuture = cache.batchGetSome(Array(0..<requestsCount))
.onSuccess {
result = $0
}
.onFailure {
errors.append($0)
}
.onCancel {
canceled = true
}
}
it("should dispatch all of the requests to the underlying cache") {
expect(cache.numberOfTimesCalledGet).to(equal(requestsCount))
}
context("when one of the requests fails") {
let failedIndex = 2
beforeEach {
cache.promisesReturned[failedIndex].fail(TestError.SimpleError)
}
it("should not call the success closure") {
expect(result).to(beNil())
}
it("should not call the failure closure") {
expect(errors).to(beEmpty())
}
it("should not call the cancel closure") {
expect(canceled).to(beFalse())
}
context("when all the other requests succeed") {
beforeEach {
cache.promisesReturned.enumerate().forEach { (iteration, promise) in
promise.succeed("\(iteration)")
}
}
it("should call the success closure") {
expect(result).notTo(beNil())
}
it("should pass the right number of results") {
expect(result.count).to(equal(cache.promisesReturned.count - 1))
}
it("should only pass the succeeded requests") {
var expectedResult = cache.promisesReturned.enumerate().map { (iteration, _) in
"\(iteration)"
}
expectedResult.removeAtIndex(failedIndex)
expect(result).to(equal(expectedResult))
}
it("should not call the failure closure") {
expect(errors).to(beEmpty())
}
it("should not call the cancel closure") {
expect(canceled).to(beFalse())
}
}
}
context("when one of the requests succeeds") {
beforeEach {
cache.promisesReturned[1].succeed("1")
}
it("should not call the failure closure") {
expect(errors).to(beEmpty())
}
it("should not call the success closure") {
expect(result).to(beNil())
}
context("when all the other requests complete") {
beforeEach {
cache.promisesReturned.enumerate().forEach { (iteration, promise) in
promise.succeed("\(iteration)")
}
}
it("should call the success closure") {
expect(result).notTo(beNil())
}
it("should pass the right number of results") {
expect(result.count).to(equal(cache.promisesReturned.count))
}
it("should only pass the succeeded requests") {
expect(result).to(equal(cache.promisesReturned.enumerate().map { (iteration, _) in
"\(iteration)"
}))
}
it("should not call the failure closure") {
expect(errors).to(beEmpty())
}
it("should not call the cancel closure") {
expect(canceled).to(beFalse())
}
}
}
context("when one of the requests is canceled") {
let canceledIndex = 3
beforeEach {
cache.promisesReturned[canceledIndex].cancel()
}
it("should not call the success closure") {
expect(result).to(beNil())
}
it("should not call the onCancel closure") {
expect(canceled).to(beFalse())
}
context("when all the other requests complete") {
beforeEach {
cache.promisesReturned.enumerate().forEach { (iteration, promise) in
promise.succeed("\(iteration)")
}
}
it("should call the success closure") {
expect(result).notTo(beNil())
}
it("should pass the right number of results") {
expect(result.count).to(equal(cache.promisesReturned.count - 1))
}
it("should only pass the succeeded requests") {
var expectedResult = cache.promisesReturned.enumerate().map { (iteration, _) in
"\(iteration)"
}
expectedResult.removeAtIndex(canceledIndex)
expect(result).to(equal(expectedResult))
}
it("should not call the failure closure") {
expect(errors).to(beEmpty())
}
it("should not call the cancel closure") {
expect(canceled).to(beFalse())
}
}
}
context("when the resulting request is canceled") {
beforeEach {
resultingFuture.cancel()
}
it("should cancel all the underlying requests") {
var canceledCount = 0
cache.promisesReturned.forEach { promise in
promise.onCancel {
canceledCount += 1
}
}
expect(canceledCount).to(equal(cache.promisesReturned.count))
}
}
}
}
}
|
mit
|
0623f493b853aa366014f2f2052787a5
| 27.200617 | 94 | 0.507115 | 5.229536 | false | false | false | false |
joearms/joearms.github.io
|
includes/swift/closures1.swift
|
1
|
234
|
class Demo {
var call: () -> Bool = {() -> Bool in true}
}
let x = Demo()
print(x.call())
var i = 10
var f = {() -> Bool in print("hello I'm a callback and i =", i); return true}
x.call = f
print(x.call())
i = 20
print(x.call())
|
mit
|
d914073d6621f5004f13b7dbec894232
| 18.5 | 77 | 0.551282 | 2.72093 | false | false | false | false |
Miridescen/M_365key
|
365KEY_swift/365KEY_swift/MainController/Class/Produce/view/ProductDetailView/SKProductDetailHeadView.swift
|
1
|
5363
|
//
// SKProductDetailHeadView.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/11/10.
// Copyright © 2016年 DoNews. All rights reserved.
//
import UIKit
class SKProductDetailHeadView: UIView {
var model: SKProductDetailProductInfoModel?{
didSet{
headImageView.sd_setImage(with: URL(string: (model?.showImage)!))
if model?.is_follow == 0 {
focusButton.isSelected = false
} else {
focusButton.isSelected = true
}
if model?.is_good == 0 {
upImageView.image = UIImage(named: "icon_up2")
goodButton.isSelected = false
} else {
upImageView.image = UIImage(named: "icon_up1")
goodButton.isSelected = true
goodButton.isUserInteractionEnabled = false
}
guard let priesent = model?.praisecount else {
return
}
numLabel.text = "\(priesent)"
peopleNameLabel.text = model?.userinfo?.username
if model?.userinfo?.showThumbnail == nil {
picTouxingImageView.image = UIImage(named: "pic_touxiang_little")
} else {
picTouxingImageView.sd_setImage(with: URL(string: (model?.userinfo?.showThumbnail)!), placeholderImage: UIImage(named: "pic_touxiang_little"))
}
if (model?.info?.isEmpty)! {
introduceLabel.text = "无简介"
} else {
introduceLabel.text = model?.info
}
}
}
@IBOutlet weak var headImageView: UIImageView!
@IBOutlet weak var bottemCoverView: UIView!{
didSet{
let bottemCoverLayer = CAGradientLayer()
bottemCoverLayer.bounds = bottemCoverView.bounds
bottemCoverLayer.borderWidth = 0
bottemCoverLayer.frame = bottemCoverView.bounds
bottemCoverLayer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
bottemCoverLayer.startPoint = CGPoint(x: 0, y: 0)
bottemCoverLayer.endPoint = CGPoint(x: 0, y: 1.0)
bottemCoverView.layer.insertSublayer(bottemCoverLayer, at: 0)
}
}
@IBOutlet weak var goodButton: UIButton!
@IBAction func goodBtn(_ sender: UIButton) {
print("点赞")
let userShard = SKUserShared.getUserSharedNeedPresentLoginView()
if userShard == nil {
return
}
var params = [String: AnyObject]()
params["uid"] = userShard?.uid as AnyObject?
params["id"] = model?.id as AnyObject?
params["type"] = "good" as AnyObject?
params["model"] = "pro" as AnyObject?
NSURLConnection.connection.productGoodBtnDidClick(with: params) { isSuccess in
if isSuccess {
self.upImageView.image = UIImage(named: "icon_up1")
sender.isUserInteractionEnabled = false
SKProgressHUD.setSuccessString(with: "点赞成功")
guard let priesent = self.model?.praisecount else {
return
}
self.numLabel.text = "\(priesent+1)"
} else {
SKProgressHUD.setErrorString(with: "点赞失败")
}
}
}
@IBOutlet weak var focusButton: UIButton!
@IBAction func focusBtn(_ sender: UIButton) {
print("关注")
let userShard = SKUserShared.getUserSharedNeedPresentLoginView()
if userShard == nil {
return
}
var params = [String: AnyObject]()
params["uid"] = userShard?.uid as AnyObject?
params["id"] = model?.id as AnyObject?
params["type"] = "gz" as AnyObject?
params["model"] = "pro" as AnyObject?
if !sender.isSelected {
NSURLConnection.connection.productGoodBtnDidClick(with: params) { isSuccess in
if isSuccess {
SKProgressHUD.setSuccessString(with: "关注成功")
sender.isSelected = !sender.isSelected
} else {
SKProgressHUD.setErrorString(with: "点赞失败")
}
}
} else {
NSURLConnection.connection.productCancleFocusRequest(params: params, completion: { (isSuccess) in
if isSuccess {
SKProgressHUD.setSuccessString(with: "取消关注成功")
sender.isSelected = !sender.isSelected
} else {
SKProgressHUD.setErrorString(with: "取消关注失败")
}
})
}
}
@IBOutlet weak var upImageView: UIImageView!{
didSet{
upImageView.isUserInteractionEnabled = true
}
}
@IBOutlet weak var numLabel: UILabel!
@IBOutlet weak var peopleNameLabel: UILabel!
@IBOutlet weak var picTouxingImageView: UIImageView!{
didSet{
picTouxingImageView.layer.cornerRadius = 20
picTouxingImageView.clipsToBounds = true
}
}
@IBOutlet weak var introduceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
}
|
apache-2.0
|
4fe1746cd57b902ac0244b7fbe7254da
| 32.66879 | 158 | 0.548808 | 4.862925 | false | false | false | false |
jellybeansoup/ios-melissa
|
Other/EmptyViewController.swift
|
2
|
4059
|
import UIKit
import ContactsUI
import Sherpa
class EmptyViewController: UIViewController, CNContactPickerDelegate {
//! The shared preferences manager.
let preferences = PreferencesManager.sharedManager
// MARK: View life cycle
@IBOutlet weak var stackView: UIStackView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.imageView.tintColor = PreferencesManager.tintColor
self.button.tintColor = PreferencesManager.tintColor
self.preferences?.addObserver(self, forKeyPath: "contact", options: [], context: nil)
if self.preferences?.contact != nil {
self.navigationController?.popToRootViewController(animated: false)
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.preferences?.removeObserver(self, forKeyPath: "contact")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let imageViewHeight = self.imageView.isHidden ? self.imageView.image!.size.height : 0
self.imageView.isHidden = self.stackView.frame.size.height + imageViewHeight >= self.stackView.superview!.frame.size.height
}
// MARK: IBActions
@IBAction func selectContact() {
let contactStore = CNContactStore()
switch CNContactStore.authorizationStatus(for: .contacts) {
case .restricted:
let message = "Unable to access contacts, as this functionality has been restricted."
let alertController = UIAlertController.alert(message)
self.present(alertController, animated: true, completion: nil)
break
case .denied:
let message = "To select a contact as your other, you will need to turn on access in Settings."
let alertController = UIAlertController.alert(message, action: "Open Settings", handler: { _ in
guard let url = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
UIApplication.shared.openURL(url)
})
self.present(alertController, animated: true, completion: nil)
break
case .notDetermined:
contactStore.requestAccess(for: .contacts, completionHandler: { granted, error in
DispatchQueue.main.async {
self.selectContact()
}
})
break
case .authorized:
let viewController = CNContactPickerViewController()
viewController.delegate = self
viewController.predicateForEnablingContact = NSPredicate(format: "emailAddresses.@count > 0 || phoneNumbers.@count > 0")
viewController.modalPresentationStyle = .formSheet
self.present(viewController, animated: true, completion: nil)
break
}
}
@IBAction func showUserGuide() {
if let url = Bundle.main.url(forResource: "userguide", withExtension: "json") {
let viewController = SherpaViewController(fileAtURL: url)
viewController.tintColor = PreferencesManager.tintColor
viewController.articleTextColor = PreferencesManager.textColor
viewController.articleBackgroundColor = PreferencesManager.backgroundColor
viewController.articleKey = "setting-up"
self.present(viewController, animated: true, completion: nil)
}
}
// MARK: Contact picker delegate
func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
if let preferences = self.preferences {
preferences.contact = contact
preferences.updateShortcutItems( UIApplication.shared )
self.navigationController?.popToRootViewController(animated: false)
}
else {
let message = "An error occurred while updating your selected contact. Can you give it another try in a moment?"
let alert = UIAlertController.alert(message)
self.present(alert, animated: true, completion: nil)
}
}
// MARK: Key-value observing
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if self.preferences?.contact != nil {
self.navigationController?.popToRootViewController(animated: false)
}
}
}
|
bsd-2-clause
|
376ff39acd58c45e9481945e94002290
| 30.96063 | 148 | 0.752895 | 4.383369 | false | false | false | false |
CocoaHeadsConference/CHConferenceApp
|
NSBrazilConf/Views/Schedule/FilterFeedView.swift
|
1
|
3626
|
//
// FilterFeedItem.swift
// NSBrazilConf
//
// Created by Mauricio Cardozo on 10/31/19.
// Copyright © 2019 Cocoaheadsbr. All rights reserved.
//
import Foundation
import SwiftUI
struct FilterFeedView: View {
init?(feedItem: FeedItem) {
guard let item = feedItem as? FilterFeedItem else { return nil }
self.feedItem = item
}
var feedItem: FilterFeedItem
@State var selectedFeed: Int = 0
@Environment(\.horizontalSizeClass) var horizontalSizeClass: UserInterfaceSizeClass?
var body: some View {
if horizontalSizeClass == .regular {
return AnyView(
ScrollView(.horizontal) {
HStack {
ForEach(0..<feedItem.feeds.count) { index in
ScrollView (.vertical) {
VStack {
Text(self.feedItem.feeds[index].title)
.font(.largeTitle)
.fontWeight(.bold)
.padding(2)
.padding([.leading, .trailing], 8)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
ForEach(self.feedItem.feeds[index].decoder.feedItems) { item in
FeedBuilder.view(for: item)
}
}
}
if (index != self.feedItem.feeds.count - 1) {
Divider()
}
}
}.frame(width: 1400)
.padding([.leading, .trailing], 20)
}
)
} else {
return AnyView(
VStack {
Picker("", selection: $selectedFeed) {
ForEach(0..<self.feedItem.feeds.count) { index in
Text(self.feedItem.feeds[index].title).tag(index)
}
}.pickerStyle(SegmentedPickerStyle())
.padding([.leading, .trailing], 10)
Text(self.feedItem.feeds[self.selectedFeed].title)
.font(.largeTitle)
.fontWeight(.bold)
.padding(2)
.padding([.leading, .trailing], 8)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
List(self.feedItem.feeds[selectedFeed].decoder.feedItems) { item in
FeedBuilder.view(for: item)
}
}
)
}
}
}
struct FilterFeedView_Previews: PreviewProvider {
static var items: [FeedItem] = [
TalkFeedItem(date: Date(), name: "Jonas", speaker: "Jonas", image: ""),
TalkFeedItem(date: Date(), name: "Jonas", speaker: "Jonas", image: ""),
TalkFeedItem(date: Date(), name: "Jonas", speaker: "Jonas", image: "")
]
static var previews: some View {
let item = FilterFeedItem(feeds: [
FilteredFeed(title: "Sexta", decoder: FeedDecoder(feedItems: items)),
FilteredFeed(title: "Sabado", decoder: FeedDecoder(feedItems: items)),
FilteredFeed(title: "Domingo", decoder: FeedDecoder(feedItems: items))
])
return Group {
FilterFeedView(feedItem: item).previewDevice(PreviewDevice(rawValue: "iPhone 11"))
FilterFeedView(feedItem: item).previewDevice(PreviewDevice(rawValue: "iPhone SE"))
}
}
}
|
mit
|
3faccbed8b8a68966985813aad4747d3
| 35.616162 | 99 | 0.485517 | 5.048747 | false | false | false | false |
IvanVorobei/RequestPermission
|
Example/SPPermission/SPPermission/Frameworks/SparrowKit/Extension/SPUIViewControllerExtenshion.swift
|
1
|
6789
|
// 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
import Photos
extension UIViewController {
func present(_ viewControllerToPresent: UIViewController, completion: (() -> Swift.Void)? = nil) {
self.present(viewControllerToPresent, animated: true, completion: completion)
}
@objc func dismiss() {
self.dismiss(animated: true, completion: nil)
}
func wrapToNavigationController(statusBar: SPStatusBar = .dark) -> UINavigationController {
let controller = SPStatusBarManagerNavigationController(rootViewController: self)
controller.statusBar = statusBar
return controller
}
}
extension UIViewController {
func dismissKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
extension UIViewController {
func save(image: UIImage) {
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
} else {
print("Saving image error. Not allowed permission")
}
}
func saveVideo(url: String, complection: @escaping (Bool)->()) {
DispatchQueue.global(qos: .utility).async {
let urls = URL(string: url)
let urldata = try? Data(contentsOf: urls!)
if urldata != nil {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let filepath = "\(documentsPath)/tempfile.mp4"
DispatchQueue.main.async {
let urlsave = URL(fileURLWithPath: filepath)
do {
try urldata!.write(to: urlsave, options: Data.WritingOptions.atomic)
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: urlsave)
}, completionHandler: { (status, error) in
try? FileManager.default.removeItem(atPath: filepath)
DispatchQueue.main.async {
complection(error == nil)
}
})
} catch {
try? FileManager.default.removeItem(atPath: filepath)
complection(false)
}
}
}
}
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let _ = error {
self.imageSaved(isSuccses: false)
} else {
self.imageSaved(isSuccses: true)
}
}
@objc func imageSaved(isSuccses: Bool) {
fatalError("SPUIViewControllerExtenshion - Need ovveride 'imageSaved' func")
}
}
extension UIViewController {
func setPrefersLargeNavigationTitle(_ title: String, smallScreenToSmallBar: Bool = true) {
self.navigationItem.title = title
if #available(iOS 11.0, *) {
self.navigationItem.largeTitleDisplayMode = .automatic
self.navigationController?.navigationBar.prefersLargeTitles = true
}
if smallScreenToSmallBar {
if self.view.frame.width < 375 {
self.setNavigationTitle(title, style: .small)
}
}
}
func setNavigationTitle(_ title: String, style: SPNavigationTitleStyle) {
self.navigationItem.title = title
switch style {
case .large:
if #available(iOS 11.0, *) {
self.navigationController?.navigationBar.prefersLargeTitles = true
self.navigationItem.largeTitleDisplayMode = .always
}
case .small:
if #available(iOS 11.0, *) {
self.navigationItem.largeTitleDisplayMode = .never
}
case .stork:
if #available(iOS 11.0, *) {
self.navigationItem.largeTitleDisplayMode = .never
}
case .noContent:
if #available(iOS 11.0, *) {
self.navigationItem.largeTitleDisplayMode = .never
}
}
}
}
extension UIViewController {
var safeArea: UIEdgeInsets {
if #available(iOS 11.0, *) {
return self.view.safeAreaInsets
} else {
return UIEdgeInsets.zero
}
}
var navigationBarHeight: CGFloat {
return self.navigationController?.navigationBar.frame.height ?? 0
}
static var statusBarHeight: CGFloat {
return UIApplication.shared.statusBarFrame.height
}
}
extension UIViewController {
var navigationTitleColor: UIColor? {
get {
return (self.navigationController?.navigationBar.titleTextAttributes?[NSAttributedString.Key.foregroundColor] as? UIColor) ?? nil
}
set {
let textAttributes: [NSAttributedString.Key: Any]? = [NSAttributedString.Key.foregroundColor: newValue ?? UIColor.black]
self.navigationController?.navigationBar.titleTextAttributes = textAttributes
if #available(iOS 11.0, *) {
self.navigationController?.navigationBar.largeTitleTextAttributes = textAttributes
}
}
}
}
|
mit
|
9a62aa63c3a4345d95640387d64f5af8
| 36.921788 | 141 | 0.622127 | 5.319749 | false | false | false | false |
lkzhao/YetAnotherAnimationLibrary
|
Sources/YetAnotherAnimationLibrary/Animations/ValueAnimation.swift
|
1
|
2521
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class ValueAnimation<Value: VectorConvertible>: Animation {
typealias Vector = Value.Vector
// getter returns optional because we dont want strong references inside the getter block
public var getter: () -> Value?
public var setter: (Value) -> Void
public let value: AnimationProperty<Value>
open override func willStart() {
super.willStart()
updateWithCurrentState()
}
open override func didUpdate() {
super.didUpdate()
setter(value.value)
}
public init(getter:@escaping () -> Value?, setter:@escaping (Value) -> Void) {
self.value = AnimationProperty<Value>()
self.getter = getter
self.setter = setter
}
public init(value: AnimationProperty<Value>) {
self.value = value
self.getter = { return nil }
self.setter = { newValue in }
}
public convenience override init() {
self.init(value: AnimationProperty<Value>())
}
public func setTo(_ value: Value) {
self.value.value = value
setter(value)
}
public func updateWithCurrentState() {
if let currentValue = getter() {
value.value = currentValue
}
}
public func from(_ value: Value) -> Self {
self.value.value = value
setter(value)
return self
}
}
|
mit
|
5bc9d2436b3d998ab0ba8cc627281fc4
| 32.171053 | 93 | 0.678302 | 4.600365 | false | false | false | false |
skedgo/tripkit-ios
|
Sources/TripKitUI/views/timetable/TKUITimetableAccessoryView.swift
|
1
|
6029
|
//
// TKUITimetableAccessoryView.swift
// TripKitUI-iOS
//
// Created by Adrian Schönig on 06.06.18.
// Copyright © 2018 SkedGo Pty Ltd. All rights reserved.
//
import UIKit
import TripKit
class TKUITimetableAccessoryView: UIView {
typealias TimetableCardActionsView = TKUICardActionsView<TKUITimetableCard, [TKUIStopAnnotation]>
struct Line: Hashable {
let text: String
var color: UIColor? = nil
var faded: Bool = false
}
@IBOutlet weak var serviceCollectionView: UICollectionView!
@IBOutlet weak var serviceCollectionLayout: TKUICollectionViewBubbleLayout!
@IBOutlet weak var serviceCollectionHeightConstraint: NSLayoutConstraint!
/// Constraint between collection view and bottom bar. Should be activated when `customActionStack` is hidden.
@IBOutlet weak var serviceCollectionToBottomBarConstraint: NSLayoutConstraint!
@IBOutlet weak var customActionView: UIView!
@IBOutlet weak var customActionViewToBottomBarConstraint: NSLayoutConstraint!
@IBOutlet weak var serviceCollectionToCustomActionViewConstraint: NSLayoutConstraint!
@IBOutlet weak var bottomBar: UIView!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var timeButton: UIButton!
var lines: [Line] = [] {
didSet {
serviceCollectionView.reloadData()
serviceCollectionView.bounds = CGRect(x: 0, y: 0, width: bounds.width, height: 200) // .infinity or .max lead to crashes or infinite loops in iOS 13 :(
serviceCollectionView.layoutIfNeeded()
serviceCollectionHeightConstraint.constant = serviceCollectionLayout.collectionViewContentSize.height
}
}
private var sizingCell: TKUIServiceNumberCell!
static func newInstance() -> TKUITimetableAccessoryView {
let bundle = Bundle(for: self)
guard
let view = bundle.loadNibNamed("TKUITimetableAccessoryView", owner: nil, options: nil)!.first as? TKUITimetableAccessoryView
else { preconditionFailure() }
return view
}
override func awakeFromNib() {
super.awakeFromNib()
sizingCell = TKUIServiceNumberCell.newInstance()
serviceCollectionView.register(TKUIServiceNumberCell.nib, forCellWithReuseIdentifier: TKUIServiceNumberCell.reuseIdentifier)
serviceCollectionView.dataSource = self
serviceCollectionLayout.delegate = self
customActionView.isHidden = true
customActionViewToBottomBarConstraint.isActive = false
serviceCollectionToCustomActionViewConstraint.isActive = false
serviceCollectionToBottomBarConstraint.isActive = true
bottomBar.backgroundColor = .tkBackgroundSecondary
// Apply default style, removing the search bar's background
TKStyleManager.style(searchBar, includingBackground: false) { textField in
textField.backgroundColor = .tkBackground
}
searchBar.placeholder = Loc.Search
timeButton.setTitle(nil, for: .normal)
timeButton.setImage(.iconChevronTimetable, for: .normal)
timeButton.tintColor = .tkAppTintColor
}
func setCustomActions(_ actions: [TKUITimetableCard.Action], for model: [TKUIStopAnnotation], card: TKUITimetableCard) {
customActionView.subviews.forEach { $0.removeFromSuperview() }
// We deal with empty actions separately here, since it's best to
// deactivate constraints first before activating. Otherwise, AL
// will complain about unable to satisfy simultaneously
if actions.isEmpty {
customActionView.isHidden = true
serviceCollectionToCustomActionViewConstraint.isActive = false
customActionViewToBottomBarConstraint.isActive = false
serviceCollectionToBottomBarConstraint.isActive = true
} else {
customActionView.isHidden = false
serviceCollectionToBottomBarConstraint.isActive = false
serviceCollectionToCustomActionViewConstraint.isActive = true
customActionViewToBottomBarConstraint.isActive = true
let actionView = TimetableCardActionsView(frame: CGRect(x: 0, y: 0, width: frame.width, height: 80))
actionView.configure(with: actions, model: model, card: card)
actionView.hideSeparator = true
customActionView.addSubview(actionView)
actionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
actionView.leadingAnchor.constraint(equalTo: customActionView.leadingAnchor),
actionView.topAnchor.constraint(equalTo: customActionView.topAnchor),
actionView.trailingAnchor.constraint(equalTo: customActionView.trailingAnchor),
actionView.bottomAnchor.constraint(equalTo: customActionView.bottomAnchor)
])
}
}
}
extension TKUITimetableAccessoryView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return lines.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TKUIServiceNumberCell.reuseIdentifier, for: indexPath) as! TKUIServiceNumberCell
cell.configure(lines[indexPath.item])
return cell
}
}
extension TKUITimetableAccessoryView: TKUICollectionViewBubbleLayoutDelegate {
func collectionView(_ collectionView: UICollectionView, itemSizeAt indexPath: IndexPath) -> CGSize {
sizingCell.configure(lines[indexPath.item])
sizingCell.layoutIfNeeded()
sizingCell.sizeToFit()
return sizingCell.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
}
}
extension TKUIServiceNumberCell {
func configure(_ line: TKUITimetableAccessoryView.Line) {
wrapperView.alpha = line.faded ? 0.2 : 1
numberLabel.text = line.text
if let serviceColor = line.color {
numberLabel.textColor = serviceColor.isDark ? .tkLabelOnDark : .tkLabelOnLight
wrapperView.backgroundColor = serviceColor
} else {
numberLabel.textColor = .tkBackground
wrapperView.backgroundColor = .tkLabelPrimary
}
}
}
|
apache-2.0
|
12e8562587e2077f4bfcb53673737c14
| 37.388535 | 157 | 0.759416 | 5.263755 | false | false | false | false |
zhiquan911/CHKLineChart
|
CHKLineChart/Example/Example/Demo/models/SeriesParam.swift
|
1
|
15867
|
//
// ChartIndex.swift
// Example
//
// Created by Chance on 2018/3/1.
// Copyright © 2018年 Chance. All rights reserved.
//
import Foundation
import CHKLineChartKit
class SeriesParamControl: NSObject, Codable {
var value: Double = 0
var note: String = ""
var min: Double = 0
var max: Double = 0
var step: Double = 0
convenience init(value: Double, note: String, min: Double, max: Double, step: Double) {
self.init()
self.value = value
self.note = note
self.min = min
self.max = max
self.step = step
}
}
/// 指标线参数设置
class SeriesParam: NSObject, Codable {
var seriesKey: String = ""
var name: String = ""
var params: [SeriesParamControl] = [SeriesParamControl]()
var order: Int = 0
var hidden: Bool = false
convenience init(seriesKey: String, name: String, params: [SeriesParamControl], order: Int, hidden: Bool) {
self.init()
self.seriesKey = seriesKey
self.name = name
self.params = params
self.order = order
self.hidden = hidden
}
/// 获取算法组
func getAlgorithms() -> [CHChartAlgorithmProtocol] {
var algorithms: [CHChartAlgorithmProtocol] = [CHChartAlgorithmProtocol]()
switch seriesKey {
case CHSeriesKey.ma:
for p in self.params {
let a = CHChartAlgorithm.ma(Int(p.value))
algorithms.append(a)
}
case CHSeriesKey.ema:
for p in self.params {
let a = CHChartAlgorithm.ema(Int(p.value))
algorithms.append(a)
}
case CHSeriesKey.kdj:
let a = CHChartAlgorithm.kdj(Int(self.params[0].value), Int(self.params[1].value), Int(self.params[2].value))
algorithms.append(a)
case CHSeriesKey.macd:
let p1 = CHChartAlgorithm.ema(Int(self.params[0].value))
algorithms.append(p1)
let p2 = CHChartAlgorithm.ema(Int(self.params[1].value))
algorithms.append(p2)
let a = CHChartAlgorithm.macd(Int(self.params[0].value), Int(self.params[1].value), Int(self.params[2].value))
algorithms.append(a)
case CHSeriesKey.boll:
let ma = CHChartAlgorithm.ma(Int(self.params[0].value)) //计算BOLL,必须先计算到同周期的MA
algorithms.append(ma)
let a = CHChartAlgorithm.boll(Int(self.params[0].value), Int(self.params[1].value))
algorithms.append(a)
case CHSeriesKey.sar:
let a = CHChartAlgorithm.sar(Int(self.params[0].value), CGFloat(self.params[1].value), CGFloat(self.params[2].value))
algorithms.append(a)
case CHSeriesKey.sam:
let a = CHChartAlgorithm.sam(Int(self.params[0].value))
algorithms.append(a)
case CHSeriesKey.rsi:
for p in self.params {
let a = CHChartAlgorithm.rsi(Int(p.value))
algorithms.append(a)
}
default:
let a = CHChartAlgorithm.none
algorithms.append(a)
}
return algorithms
}
/// 获取指标线段组
func appendIn(masterSection: CHSection,
assistSections: CHSection...) {
let styleParam = StyleParam.shared
//分区点线样式
let upcolor = (UIColor(hex: styleParam.upColor), true)
let downcolor = (UIColor(hex: styleParam.downColor), true)
let lineColors = [
UIColor(hex: styleParam.lineColors[0]),
UIColor(hex: styleParam.lineColors[1]),
UIColor(hex: styleParam.lineColors[2]),
]
switch seriesKey {
case CHSeriesKey.ma:
var maColor = [UIColor]()
for i in 0..<self.params.count {
maColor.append(lineColors[i])
}
let series = CHSeries.getPriceMA(
isEMA: false,
num: self.params.map {Int($0.value)},
colors: maColor,
section: masterSection)
masterSection.series.append(series)
for assistSection in assistSections {
let volWithMASeries = CHSeries.getVolumeWithMA(upStyle: upcolor,
downStyle: downcolor,
isEMA: false,
num: self.params.map {Int($0.value)},
colors: maColor,
section: assistSection)
assistSection.series.append(volWithMASeries)
}
case CHSeriesKey.ema:
var emaColor = [UIColor]()
for i in 0..<self.params.count {
emaColor.append(lineColors[i])
}
let series = CHSeries.getPriceMA(
isEMA: true,
num: self.params.map {Int($0.value)},
colors: emaColor,
section: masterSection)
masterSection.series.append(series)
case CHSeriesKey.kdj:
for assistSection in assistSections {
let kdjSeries = CHSeries.getKDJ(
lineColors[0],
dc: lineColors[1],
jc: lineColors[2],
section: assistSection)
kdjSeries.title = "KDJ(\(self.params[0].value.toString()),\(self.params[1].value.toString()),\(self.params[2].value.toString()))"
assistSection.series.append(kdjSeries)
}
case CHSeriesKey.macd:
for assistSection in assistSections {
let macdSeries = CHSeries.getMACD(
lineColors[0],
deac: lineColors[1],
barc: lineColors[2],
upStyle: upcolor, downStyle: downcolor,
section: assistSection)
macdSeries.title = "MACD(\(self.params[0].value.toString()),\(self.params[1].value.toString()),\(self.params[2].value.toString()))"
macdSeries.symmetrical = true
assistSection.series.append(macdSeries)
}
case CHSeriesKey.boll:
let priceBOLLSeries = CHSeries.getBOLL(
lineColors[0],
ubc: lineColors[1],
lbc: lineColors[2],
section: masterSection)
priceBOLLSeries.hidden = true
masterSection.series.append(priceBOLLSeries)
case CHSeriesKey.sar:
let priceSARSeries = CHSeries.getSAR(
upStyle: upcolor,
downStyle: downcolor,
titleColor: lineColors[0],
section: masterSection)
priceSARSeries.hidden = true
masterSection.series.append(priceSARSeries)
case CHSeriesKey.sam:
let priceSAMSeries = CHSeries.getPriceSAM(num: Int(self.params[0].value), barStyle: (UIColor.yellow, false), lineColor: UIColor(white: 0.4, alpha: 1), section: masterSection)
priceSAMSeries.hidden = true
masterSection.series.append(priceSAMSeries)
for assistSection in assistSections {
let volWithSAMSeries = CHSeries.getVolumeWithSAM(upStyle: upcolor,
downStyle: downcolor,
num: Int(self.params[0].value),
barStyle: (UIColor.yellow, false),
lineColor: UIColor(white: 0.4, alpha: 1),
section: assistSection)
assistSection.series.append(volWithSAMSeries)
}
case CHSeriesKey.rsi:
var maColor = [UIColor]()
for i in 0..<self.params.count {
maColor.append(lineColors[i])
}
for assistSection in assistSections {
let series = CHSeries.getRSI(
num: self.params.map {Int($0.value)},
colors: maColor,
section: assistSection)
assistSection.series.append(series)
}
default:break
}
}
}
class SeriesParamList: NSObject, Codable{
var results: [SeriesParam] = [SeriesParam]()
let error: Bool = false
static var shared: SeriesParamList = {
let instance = SeriesParamList()
return instance
}()
/// 读取用户指标配置
///
/// - Returns:
func loadUserData() -> [SeriesParam] {
guard results.isEmpty else {
return self.results
}
guard let json = UserDefaults.standard.value(forKey: "SeriesParamList") as? String else {
self.results = SeriesParamList.shared.defaultList
return self.results
}
guard let jsonData = json.data(using: String.Encoding.utf8) else {
self.results = SeriesParamList.shared.defaultList
return self.results
}
let jsonDecoder = JSONDecoder()
do {
let sp = try jsonDecoder.decode(SeriesParamList.self, from: jsonData)
self.results = sp.results.sorted { $0.order < $1.order }
return self.results
} catch _ {
self.results = SeriesParamList.shared.defaultList
return self.results
}
}
/// 重置为默认
func resetDefault() {
self.results = SeriesParamList.shared.defaultList
_ = self.saveUserData()
}
/// 保存用户设置指标数据
///
/// - Parameter data:
/// - Returns:
func saveUserData() -> Bool {
if results.isEmpty {
return false
}
let jsonEncoder = JSONEncoder()
do {
let jsonData = try jsonEncoder.encode(self)
let jsonString = String(data: jsonData, encoding: .utf8)
UserDefaults.standard.set(jsonString, forKey: "SeriesParamList")
UserDefaults.standard.synchronize()
return true
} catch _ {
return false
}
}
}
extension SeriesParamList {
/// 默认值
var defaultList: [SeriesParam] {
let ma = SeriesParam(seriesKey: CHSeriesKey.ma,
name: CHSeriesKey.ma,
params: [
SeriesParamControl(value: 5, note: "周期均线", min: 5, max: 120, step: 1),
SeriesParamControl(value: 10, note: "周期均线", min: 5, max: 120, step: 1),
SeriesParamControl(value: 30, note: "周期均线", min: 5, max: 120, step: 1),
],
order: 0,
hidden: false)
let ema = SeriesParam(seriesKey: CHSeriesKey.ema,
name: CHSeriesKey.ema,
params: [
SeriesParamControl(value: 5, note: "周期均线", min: 5, max: 120, step: 1),
SeriesParamControl(value: 10, note: "周期均线", min: 5, max: 120, step: 1),
SeriesParamControl(value: 30, note: "周期均线", min: 5, max: 120, step: 1),
],
order: 1,
hidden: false)
let boll = SeriesParam(seriesKey: CHSeriesKey.boll,
name: CHSeriesKey.boll,
params: [
SeriesParamControl(value: 20, note: "日布林线", min: 2, max: 120, step: 1),
SeriesParamControl(value: 2, note: "倍宽度", min: 1, max: 100, step: 1),
],
order: 2,
hidden: false)
let sar = SeriesParam(seriesKey: CHSeriesKey.sar,
name: CHSeriesKey.sar,
params: [
SeriesParamControl(value: 4, note: "基准周期", min: 4, max: 12, step: 2),
SeriesParamControl(value: 0.02, note: "最小加速", min: 0.02, max: 0.2, step: 0.01),
SeriesParamControl(value: 0.2, note: "最大加速", min: 0.02, max: 0.2, step: 0.01),
],
order: 3,
hidden: false)
let sam = SeriesParam(seriesKey: CHSeriesKey.sam,
name: CHSeriesKey.sam,
params: [
SeriesParamControl(value: 60, note: "统计周期", min: 10, max: 120, step: 1),
],
order: 4,
hidden: false)
let kdj = SeriesParam(seriesKey: CHSeriesKey.kdj,
name: CHSeriesKey.kdj,
params: [
SeriesParamControl(value: 9, note: "周期", min: 2, max: 90, step: 1),
SeriesParamControl(value: 3, note: "周期", min: 2, max: 30, step: 1),
SeriesParamControl(value: 3, note: "周期", min: 2, max: 30, step: 1),
],
order: 5,
hidden: false)
let macd = SeriesParam(seriesKey: CHSeriesKey.macd,
name: CHSeriesKey.macd,
params: [
SeriesParamControl(value: 12, note: "快线移动平均", min: 2, max: 60, step: 1),
SeriesParamControl(value: 26, note: "慢线移动平均", min: 2, max: 90, step: 1),
SeriesParamControl(value: 9, note: "移动平均", min: 2, max: 60, step: 1),
],
order: 6,
hidden: false)
let rsi = SeriesParam(seriesKey: "RSI",
name: "RSI",
params: [
SeriesParamControl(value: 6, note: "相对强弱指数", min: 5, max: 120, step: 1),
SeriesParamControl(value: 12, note: "相对强弱指数", min: 5, max: 120, step: 1),
SeriesParamControl(value: 24, note: "相对强弱指数", min: 5, max: 120, step: 1),
],
order: 7,
hidden: false)
return [
ma,
ema,
boll,
sar,
sam,
kdj,
macd,
rsi
]
}
}
|
mit
|
a590e5bf9aaf67686f195d41254212a2
| 36.408654 | 186 | 0.460738 | 4.788308 | false | false | false | false |
lieven/fietsknelpunten-ios
|
FietsknelpuntenAPI/API+BoundingBox.swift
|
1
|
1415
|
//
// API+BoundingBox.swift
// Fietsknelpunten
//
// Created by Lieven Dekeyser on 20/11/16.
// Copyright © 2016 Fietsknelpunten. All rights reserved.
//
import MapKit
extension API
{
public func getBoundingBox(completion: @escaping (Bool, MKCoordinateRegion?, Error?)->())
{
self.sendRequest(action: "bbox", arguments: nil)
{
(success, response, error) in
if success
{
if let regionDict = response as? [AnyHashable: Any], let region = MKCoordinateRegion(dictionary: regionDict)
{
completion(true, region, nil)
}
else
{
completion(false, nil, nil)
}
}
else
{
completion(false, nil, error)
}
}
}
}
extension MKCoordinateRegion
{
init?(dictionary: [AnyHashable:Any])
{
guard let minLat = dictionary.double(forKey: "minLat", allowConversion: true),
let minLon = dictionary.double(forKey: "minLon", allowConversion: true),
let maxLat = dictionary.double(forKey: "maxLat", allowConversion: true),
let maxLon = dictionary.double(forKey: "maxLon", allowConversion: true) else
{
return nil
}
let centerLat = 0.5*(minLat + maxLat)
let centerLon = 0.5*(minLon + maxLon)
let latDelta = abs(maxLat - minLat)
let lonDelta = abs(maxLon - minLon)
self.init(center: CLLocationCoordinate2D(latitude: centerLat, longitude: centerLon), span: MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta))
}
}
|
mit
|
8c5434be28e37c2b766bcacc8daf8efa
| 23.37931 | 161 | 0.683876 | 3.374702 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.