repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DungntVccorp/Game | refs/heads/master | GameServer/Sources/GameServer/ClientHander.swift | mit | 1 | //
// ClientHander.swift
// GameServer
//
// Created by Nguyen Dung on 9/30/16.
//
//
import Dispatch
import Foundation
import Socks
class ClientHander: NSObject {
private var client : TCPClient!
private var close : Bool = false
private var ClientMessage : Array<Array<UInt8>>!
var uuid : String!
convenience init(client : TCPClient) {
self.init()
self.client = client
self.uuid = UUID().uuidString
self.ClientMessage = Array<Array<UInt8>>()
print("Client: \(self.client.socket.address)")
DispatchQueue(label: "\(self.client.ipAddress()) : \(self.client.socket.address.port) : receive").async {
while !self.close{
do{
let data = try self.client.receiveAll()
if(data.count == 0){
print("Client disconnect and remove form connect list")
self.close = true
}else{
self.ClientMessage.append(data)
if(data.count == 61){
DispatchQueue.main.async {
//Timer.scheduledTimer(timeInterval: 45, target: self, selector: #selector(ClientHander.onSendTest), userInfo: nil, repeats: true)
self.sendMessage(msg: "DONE");
}
}
}
}catch{
print(error)
self.close = true
}
}
do{
try self.client.close()
GSShare.sharedInstance.removeClient(client: self)
}catch{
print(error)
}
}
}
deinit {
self.client = nil
self.uuid = nil
self.ClientMessage = nil
print("REMOVE CLASS")
}
func onSendTest(){
print("Send Test Message")
self.sendMessage(msg: "test \n")
}
func sendMessage(msg : String){
sendMessage(data: msg.data(using: String.Encoding.utf8)!)
}
func sendMessage(data : Data){
sendMessage(data: data.bytes)
}
func sendMessage(bytes : [UInt8]){
do{
try self.client.send(bytes: Data)
}catch{
print(error)
}
}
}
| 19b8b691a427d569f3b424703b3b8c70 | 27.72619 | 162 | 0.479486 | false | false | false | false |
zhouguangjie/DynamicColor | refs/heads/master | DynamicColor/UIColor.swift | mit | 1 | /*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
/**
Extension to manipulate colours easily.
It allows you to work hexadecimal strings and value, HSV and RGB components, derivating colours, and many more...
*/
public typealias DynamicColor = UIColor
public extension DynamicColor {
// MARK: - Manipulating Hexa-decimal Values and Strings
/**
Creates a color from an hex string.
:param: hexString A hexa-decimal color string representation.
*/
public convenience init(hexString: String) {
let hexString = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
let scanner = NSScanner(string: hexString)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color: UInt32 = 0
if scanner.scanHexInt(&color) {
self.init(hex: color)
}
else {
self.init(hex: 0x000000)
}
}
/**
Creates a color from an hex integer.
:param: hex A hexa-decimal UInt32 that represents a color.
*/
public convenience init(hex: UInt32) {
let mask = 0x000000FF
let r = Int(hex >> 16) & mask
let g = Int(hex >> 8) & mask
let b = Int(hex) & mask
let red = CGFloat(r) / 255
let green = CGFloat(g) / 255
let blue = CGFloat(b) / 255
self.init(red:red, green:green, blue:blue, alpha:1)
}
/**
Returns the color representation as hexadecimal string.
:returns: A string similar to this pattern "#f4003b".
*/
public final func toHexString() -> String {
return String(format:"#%06x", toHex())
}
/**
Returns the color representation as an integer.
:returns: A UInt32 that represents the hexa-decimal color.
*/
public final func toHex() -> UInt32 {
let rgba = toRGBAComponents()
let colorToInt = (UInt32)(rgba.r * 255) << 16 | (UInt32)(rgba.g * 255) << 8 | (UInt32)(rgba.b * 255) << 0
return colorToInt
}
// MARK: - Getting the RGBA Components
/**
Returns the RGBA (red, green, blue, alpha) components.
:returns: The RGBA components as a tuple (r, g, b, a).
*/
public final func toRGBAComponents() -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
return (r, g, b, a)
}
return (0, 0, 0, 0)
}
/**
Returns the red component.
:returns: The red component as CGFloat.
*/
public final func redComponent() -> CGFloat {
return toRGBAComponents().r
}
/**
Returns the green component.
:returns: The green component as CGFloat.
*/
public final func greenComponent() -> CGFloat {
return toRGBAComponents().g
}
/**
Returns the blue component.
:returns: The blue component as CGFloat.
*/
public final func blueComponent() -> CGFloat {
return toRGBAComponents().b
}
/**
Returns the alpha component.
:returns: The alpha component as CGFloat.
*/
public final func alphaComponent() -> CGFloat {
return toRGBAComponents().a
}
// MARK: - Working with HSL Components
/**
Initializes and returns a color object using the specified opacity and HSL component values.
:param: hue The hue component of the color object, specified as a value from 0.0 to 1.0 (0.0 for 0 degree and 1.0 for 360 degree).
:param: saturation The saturation component of the color object, specified as a value from 0.0 to 1.0.
:param: lightness The lightness component of the color object, specified as a value from 0.0 to 1.0.
:param: alpha The opacity value of the color object, specified as a value from 0.0 to 1.0.
*/
public convenience init(hue: CGFloat, saturation: CGFloat, lightness: CGFloat, alpha: CGFloat = 1) {
let color = HSL(hue: hue, saturation: saturation, lightness: lightness, alpha: alpha).toUIColor()
let components = color.toRGBAComponents()
self.init(red: components.r, green: components.g, blue: components.b, alpha: components.a)
}
/**
Returns the HSLA (hue, saturation, lightness, alpha) components.
Notes that the hue value is between 0.0 and 1.0 (0.0 for 0 degree and 1.0 for 360 degree).
:returns: The HSLA components as a tuple (h, s, l, a).
*/
public final func toHSLAComponents() -> (h: CGFloat, s: CGFloat, l: CGFloat, a: CGFloat) {
let hsl = HSL(color: self)
return (hsl.h, hsl.s, hsl.l, hsl.a)
}
// MARK: - Identifying and Comparing Colors
/**
Returns a boolean value that indicates whether the receiver is equal to the given hexa-decimal string.
:param: hexString A hexa-decimal color number representation to be compared to the receiver.
:returns: true if the receiver and the string are equals, otherwise false.
*/
public func isEqualToHexString(hexString: String) -> Bool {
return self.toHexString() == hexString
}
/**
Returns a boolean value that indicates whether the receiver is equal to the given hexa-decimal integer.
:param: hex A UInt32 that represents the hexa-decimal color.
:returns: true if the receiver and the integer are equals, otherwise false.
*/
public func isEqualToHex(hex: UInt32) -> Bool {
return self.toHex() == hex
}
// MARK: - Deriving Colors
/**
Creates and returns a color object with the hue rotated along the color wheel by the given amount.
:param: amount A float representing the number of degrees as ratio (usually -1.0 for -360 degree and 1.0 for 360 degree).
:returns: A UIColor object with the hue changed.
*/
public final func adjustedHueColor(amount: CGFloat) -> UIColor {
return HSL(color: self).adjustHue(amount).toUIColor()
}
/**
Creates and returns the complement of the color object.
This is identical to adjustedHueColor(0.5).
:returns: The complement UIColor.
:see: adjustedHueColor:
*/
public final func complementColor() -> UIColor {
return adjustedHueColor(0.5)
}
/**
Creates and returns a lighter color object.
:returns: An UIColor lightened with an amount of 0.2.
:see: lightenColor:
*/
public final func lighterColor() -> UIColor {
return lightenColor(0.2)
}
/**
Creates and returns a color object with the lightness increased by the given amount.
:param: amount Float between 0.0 and 1.0.
:returns: A lighter UIColor.
*/
public final func lightenColor(amount: CGFloat) -> UIColor {
let normalizedAmount = min(1, max(0, amount))
return HSL(color: self).lighten(normalizedAmount).toUIColor()
}
/**
Creates and returns a darker color object.
:returns: A UIColor darkened with an amount of 0.2.
:see: darkenColor:
*/
public final func darkerColor() -> UIColor {
return darkenColor(0.2)
}
/**
Creates and returns a color object with the lightness decreased by the given amount.
:param: amount Float between 0.0 and 1.0.
:returns: A darker UIColor.
*/
public final func darkenColor(amount: CGFloat) -> UIColor {
let normalizedAmount = min(1, max(0, amount))
return HSL(color: self).darken(normalizedAmount).toUIColor()
}
/**
Creates and returns a color object with the saturation increased by the given amount.
:returns: A UIColor more saturated with an amount of 0.2.
:see: saturateColor:
*/
public final func saturatedColor() -> UIColor {
return saturateColor(0.2)
}
/**
Creates and returns a color object with the saturation increased by the given amount.
:param: amount Float between 0.0 and 1.0.
:returns: A UIColor more saturated.
*/
public final func saturateColor(amount: CGFloat) -> UIColor {
let normalizedAmount = min(1, max(0, amount))
return HSL(color: self).saturate(normalizedAmount).toUIColor()
}
/**
Creates and returns a color object with the saturation decreased by the given amount.
:returns: A UIColor less saturated with an amount of 0.2.
:see: desaturateColor:
*/
public final func desaturatedColor() -> UIColor {
return desaturateColor(0.2)
}
/**
Creates and returns a color object with the saturation decreased by the given amount.
:param: amount Float between 0.0 and 1.0.
:returns: A UIColor less saturated.
*/
public final func desaturateColor(amount: CGFloat) -> UIColor {
let normalizedAmount = min(1, max(0, amount))
return HSL(color: self).desaturate(normalizedAmount).toUIColor()
}
/**
Creates and returns a color object converted to grayscale.
This is identical to desaturateColor(1).
:returns: A grayscale UIColor.
:see: desaturateColor:
*/
public final func grayscaledColor() -> UIColor {
return desaturateColor(1)
}
/**
Creates and return a color object where the red, green, and blue values are inverted, while the opacity is left alone.
:returns: An inverse (negative) of the original color.
*/
public final func invertColor() -> UIColor {
let rgba = toRGBAComponents()
return UIColor(red: 1 - rgba.r, green: 1 - rgba.g, blue: 1 - rgba.b, alpha: rgba.a)
}
// MARK: - Mixing Colors
/**
Mixes the given color object with the receiver.
Specifically, takes the average of each of the RGB components, optionally weighted by the given percentage. The opacity of the colors object is also considered when weighting the components.
:param: color A color object to mix with the receiver.
:param: weight The weight specifies the amount of the given color object (between 0 and 1). The default value is 0.5, which means that half the given color and half the receiver color object should be used. 0.25 means that a quarter of the given color object and three quarters of the receiver color object should be used.
:returns: A color object corresponding to the two colors object mixed together.
*/
public final func mixWithColor(color: UIColor, weight: CGFloat = 0.5) -> UIColor {
let normalizedWeight = min(1, max(0, weight))
let c1 = toRGBAComponents()
let c2 = color.toRGBAComponents()
let w = 2 * normalizedWeight - 1
let a = c1.a - c2.a
let w2 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2
let w1 = 1 - w2
let red = (w1 * c1.r + w2 * c2.r)
let green = (w1 * c1.g + w2 * c2.g)
let blue = (w1 * c1.b + w2 * c2.b)
let alpha = (c1.a * normalizedWeight + c2.a * (1 - normalizedWeight))
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
/**
Creates and returns a color object corresponding to the mix of the receiver and an amount of white color, which increases lightness.
:param: amount Float between 0.0 and 1.0. The default amount is equal to 0.2.
:returns: A lighter UIColor.
*/
public final func tintColor(amount: CGFloat = 0.2) -> UIColor {
return mixWithColor(UIColor.whiteColor(), weight: amount)
}
/**
Creates and returns a color object corresponding to the mix of the receiver and an amount of black color, which reduces lightness.
:param: amount Float between 0.0 and 1.0. The default amount is equal to 0.2.
:returns: A darker UIColor.
*/
public final func shadeColor(amount: CGFloat = 0.2) -> UIColor {
return mixWithColor(UIColor.blackColor(), weight: amount)
}
}
| 3270cf73aae2bc1c073469192c49a03d | 28.878345 | 324 | 0.688111 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | refs/heads/master | Swift/LeetCode.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import Foundation
import UIKit
// 228. Summary Ranges
// Given a sorted integer array without duplicates, return the summary of its ranges.
// For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
// [-1, 0, 1, 2, 4, 5, 6, 8, 9, 11, 12, 15]
// [1, 1, 1, 2, 1, 1, 2, 1, 2, 1, 3]
// [-2, 0, 1, 2, 4, 5, 6, 8, 9, 11, 12, 15]
// [2, 1, 1, 2, 1, 1, 2, 1, 2, 1, 3]
// [] -> []
// [1] -> ["1"]
// [1, 2] -> ["1->2"]
// [1, 3] -> ["1", "3"]
// [1, 2, 3] -> ["1->3"]
// [1, 2, 4] -> ["1->2", "4"]
// [1, 3, 4] -> ["1", "3->4"]
class Solution1 {
func summaryRanges(nums: [Int]) -> [String] {
var result: [String] = []
var start: Int!
var last: Int!
for num in nums {
if start == nil {
start = num
last = num
continue
}
// Continues
if (num - last) == 1 {
last = num
continue
}
// Breaks
else if (num - last) > 1 {
if start == last {
result.append("\(start)")
} else {
result.append("\(start)->\(last)")
}
start = num
last = num
continue
}
}
if start != nil {
if start == last {
result.append("\(start)")
} else {
result.append("\(start)->\(last)")
}
}
return result
}
}
func check<T where T: Equatable>(a: T, _ b: T) -> UIColor {
if a == b {
return .greenColor()
}
return .redColor()
}
//typealias A = Array where Element: Equatable
//extension Array where Element: Equatable {
//
//}
extension Array: Equatable {}
public func ==<T>(lhs: [T], rhs: [T]) -> Bool {
if T.self is Equatable {
}
// guard let lhs = lhs as? [Equatable] else {
//
// }
guard lhs.count == rhs.count else {
return false
}
return true
}
check(1, 1)
print([1] == [1])
Solution1().summaryRanges([])
check(Solution1().summaryRanges([1]), ["1"])
Solution1().summaryRanges([1, 2])
Solution1().summaryRanges([1, 3])
check(Solution1().summaryRanges([1, 2, 3]), ["1->3"])
Solution1().summaryRanges([1, 2, 4])
Solution1().summaryRanges([1, 2, 4, 5])
Solution1().summaryRanges([1, 2, 4, 6])
Solution1().summaryRanges([1, 2, 4, 7, 8])
| b2cd30afde679abab81a5d1dcdd4e99c | 18.831776 | 85 | 0.527333 | false | false | false | false |
GitHubStuff/SwiftIntervals | refs/heads/master | Pods/SwiftDate/Sources/SwiftDate/Date+Math.swift | apache-2.0 | 7 | //
// SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones.
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// 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
// MARK: - Shortcuts to convert Date to DateInRegion
public extension Date {
/// Return the current absolute datetime in local's device region (timezone+calendar+locale)
///
/// - returns: a new `DateInRegion` instance object which express passed absolute date in the context of the local device's region
public func inLocalRegion() -> DateInRegion {
return DateInRegion(absoluteDate: self)
}
/// Return the current absolute datetime in UTC/GMT timezone. `Calendar` and `Locale` are set automatically to the device's current settings.
///
/// - returns: a new `DateInRegion` instance object which express passed absolute date in UTC timezone
public func inGMTRegion() -> DateInRegion {
return DateInRegion(absoluteDate: self, in: Region.GMT())
}
/// Return the current absolute datetime in the context of passed `Region`.
///
/// - parameter region: region you want to use to express `self` date.
///
/// - returns: a new `DateInRegion` which represent `self` in the context of passed `Region`
public func inRegion(region: Region? = nil) -> DateInRegion {
return DateInRegion(absoluteDate: self, in: region)
}
/// Create a new Date object which is the sum of passed calendar components in `DateComponents` to `self`
///
/// - parameter components: components to set
///
/// - returns: a new `Date`
public func add(components: DateComponents) -> Date {
let date: DateInRegion = self.inDateDefaultRegion() + components
return date.absoluteDate
}
/// Create a new Date object which is the sum of passed calendar components in dictionary of `Calendar.Component` values to `self`
///
/// - parameter components: components to set
///
/// - returns: a new `Date`
public func add(components: [Calendar.Component: Int]) -> Date {
let date: DateInRegion = self.inDateDefaultRegion() + components
return date.absoluteDate
}
/// Enumerate dates between two intervals by adding specified time components and return an array of dates.
/// `startDate` interval will be the first item of the resulting array. The last item of the array is evaluated automatically.
///
/// - throws: throw `.DifferentCalendar` if dates are expressed in a different calendar, '.FailedToCalculate'
///
/// - Parameters:
/// - startDate: starting date
/// - endDate: ending date
/// - components: components to add
/// - Returns: an array of DateInRegion objects
public static func dates(between startDate: Date, and endDate: Date, increment components: DateComponents) -> [Date] {
var dates = [startDate]
var currentDate = startDate
repeat {
currentDate = currentDate.add(components: components)
dates.append(currentDate)
} while (currentDate <= endDate)
return dates
}
}
// MARK: - Sum of Dates and Date & Components
public func - (lhs: Date, rhs: DateComponents) -> Date {
return lhs + (-rhs)
}
public func + (lhs: Date, rhs: DateComponents) -> Date {
return lhs.add(components: rhs)
}
public func + (lhs: Date, rhs: TimeInterval) -> Date {
return lhs.addingTimeInterval(rhs)
}
public func - (lhs: Date, rhs: TimeInterval) -> Date {
return lhs.addingTimeInterval(-rhs)
}
public func + (lhs: Date, rhs: [Calendar.Component : Int]) -> Date {
return lhs.add(components: DateInRegion.componentsFrom(values: rhs))
}
public func - (lhs: Date, rhs: [Calendar.Component : Int]) -> Date {
return lhs.add(components: DateInRegion.componentsFrom(values: rhs, multipler: -1))
}
public func - (lhs: Date, rhs: Date) -> TimeInterval {
return DateTimeInterval(start: lhs, end: rhs).duration
}
| b31a5cae0d8a02fa1dcc0408b801c4ee | 37.275591 | 142 | 0.726805 | false | false | false | false |
Skrapit/ALCameraViewController | refs/heads/master | ALCameraViewController/Views/PermissionsView.swift | mit | 2 | //
// PermissionsView.swift
// ALCameraViewController
//
// Created by Alex Littlejohn on 2015/06/24.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
internal class PermissionsView: UIView {
let iconView = UIImageView()
let titleLabel = UILabel()
let descriptionLabel = UILabel()
let settingsButton = UIButton()
let horizontalPadding: CGFloat = 50
let verticalPadding: CGFloat = 50
let verticalSpacing: CGFloat = 10
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func configureInView(_ view: UIView, title: String, description: String, completion: @escaping ButtonAction) {
let closeButton = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
view.addSubview(self)
addSubview(closeButton)
titleLabel.text = title
descriptionLabel.text = description
closeButton.action = completion
closeButton.setImage(UIImage(named: "retakeButton", in: CameraGlobals.shared.bundle, compatibleWith: nil), for: UIControlState())
closeButton.sizeToFit()
let size = view.frame.size
let closeSize = closeButton.frame.size
let closeX = horizontalPadding
let closeY = size.height - (closeSize.height + verticalPadding)
closeButton.frame.origin = CGPoint(x: closeX, y: closeY)
}
func commonInit() {
backgroundColor = UIColor(white: 0.2, alpha: 1)
titleLabel.textColor = UIColor.white
titleLabel.numberOfLines = 0
titleLabel.textAlignment = NSTextAlignment.center
titleLabel.font = UIFont(name: "AppleSDGothicNeo-Light", size: 22)
titleLabel.text = localizedString("permissions.title")
descriptionLabel.textColor = UIColor.lightGray
descriptionLabel.numberOfLines = 0
descriptionLabel.textAlignment = NSTextAlignment.center
descriptionLabel.font = UIFont(name: "AppleSDGothicNeo-Regular", size: 16)
descriptionLabel.text = localizedString("permissions.description")
let icon = UIImage(named: "permissionsIcon", in: CameraGlobals.shared.bundle, compatibleWith: nil)!
iconView.image = icon
settingsButton.contentEdgeInsets = UIEdgeInsetsMake(6, 12, 6, 12)
settingsButton.setTitle(localizedString("permissions.settings"), for: UIControlState())
settingsButton.setTitleColor(UIColor.white, for: UIControlState())
settingsButton.layer.cornerRadius = 4
settingsButton.titleLabel?.font = UIFont(name: "AppleSDGothicNeo-Regular", size: 14)
settingsButton.backgroundColor = UIColor(red: 52.0/255.0, green: 183.0/255.0, blue: 250.0/255.0, alpha: 1)
settingsButton.addTarget(self, action: #selector(PermissionsView.openSettings), for: UIControlEvents.touchUpInside)
addSubview(iconView)
addSubview(titleLabel)
addSubview(descriptionLabel)
addSubview(settingsButton)
}
func openSettings() {
if let appSettings = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.openURL(appSettings)
}
}
override func layoutSubviews() {
super.layoutSubviews()
let maxLabelWidth = frame.width - horizontalPadding * 2
let iconSize = iconView.image!.size
let constrainedTextSize = CGSize(width: maxLabelWidth, height: CGFloat.greatestFiniteMagnitude)
let titleSize = titleLabel.sizeThatFits(constrainedTextSize)
let descriptionSize = descriptionLabel.sizeThatFits(constrainedTextSize)
let settingsSize = settingsButton.sizeThatFits(constrainedTextSize)
let iconX = frame.width/2 - iconSize.width/2
let iconY: CGFloat = frame.height/2 - (iconSize.height + verticalSpacing + verticalSpacing + titleSize.height + verticalSpacing + descriptionSize.height)/2;
iconView.frame = CGRect(x: iconX, y: iconY, width: iconSize.width, height: iconSize.height)
let titleX = frame.width/2 - titleSize.width/2
let titleY = iconY + iconSize.height + verticalSpacing + verticalSpacing
titleLabel.frame = CGRect(x: titleX, y: titleY, width: titleSize.width, height: titleSize.height)
let descriptionX = frame.width/2 - descriptionSize.width/2
let descriptionY = titleY + titleSize.height + verticalSpacing
descriptionLabel.frame = CGRect(x: descriptionX, y: descriptionY, width: descriptionSize.width, height: descriptionSize.height)
let settingsX = frame.width/2 - settingsSize.width/2
let settingsY = descriptionY + descriptionSize.height + verticalSpacing
settingsButton.frame = CGRect(x: settingsX, y: settingsY, width: settingsSize.width, height: settingsSize.height)
}
}
| 033b5f6313a13a74cedb603a63eed677 | 40.252033 | 164 | 0.6689 | false | false | false | false |
meninsilicium/apple-swifty | refs/heads/development | Operators.swift | mpl-2.0 | 1 | //
// author: fabrice truillot de chambrier
// created: 25.07.2014
//
// license: See license.txt
//
// © 2014-2015, men in silicium sàrl
//
import Foundation
import CoreGraphics
import Darwin.C.math
// Documentation: http://www.unicode.org/charts/
// Documentation: http://www.unicode.org/charts/PDF/U2200.pdf
// MARK: operator definitions
// not
prefix operator ¬ {}
// complement
prefix operator ∁ {}
// and
infix operator ⋀ { associativity left precedence 120 }
// nand
infix operator !&& { associativity left precedence 120 }
infix operator ⊼ { associativity left precedence 120 }
// or
infix operator ⋁ { associativity left precedence 110 }
// nor
infix operator !|| { associativity left precedence 110 }
infix operator ⊽ { associativity left precedence 110 }
// xor
infix operator ^^ { associativity left precedence 110 }
infix operator ⊻ { associativity left precedence 110 }
// nxor
infix operator !^^ { associativity left precedence 110 }
// element of
infix operator ∈ { associativity none precedence 130 }
// not element of
infix operator !∈ { associativity none precedence 130 }
infix operator ∉ { associativity none precedence 130 }
// contains
infix operator ∋ { associativity none precedence 130 }
// doesn't contain
infix operator !∋ { associativity none precedence 130 }
infix operator ∌ { associativity none precedence 130 }
// exists
prefix operator ∃ {}
// doesn't exist
prefix operator !∃ {}
prefix operator ∄ {}
// MARK: not, ¬
func not( value: Bool ) -> Bool {
return !value
}
func not<T: BooleanType>( value: T ) -> Bool {
return !value
}
prefix func ¬( value: Bool ) -> Bool {
return !value
}
prefix func ¬<T: BooleanType>( value: T ) -> Bool {
return !value
}
// MARK: bit not
func bitnot( value: Int ) -> Int {
return ~value
}
func bitnot( value: UInt ) -> UInt {
return ~value
}
// MARK: complement, ∁
public prefix func ∁( value: Int ) -> Int {
return ~value
}
public prefix func ∁( value: UInt ) -> UInt {
return ~value
}
// MARK: - and, ⋀
func and( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return lhs && rhs
}
func and<L: BooleanType>( lhs: L, @autoclosure rhs: () -> Bool ) -> Bool {
return lhs && rhs
}
func and<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return lhs && rhs
}
func ⋀( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return lhs && rhs
}
func ⋀<L: BooleanType>( lhs: L, @autoclosure rhs: () -> Bool ) -> Bool {
return lhs && rhs
}
func ⋀<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return lhs && rhs
}
// MARK: nand, !&&, ⊼
func nand( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs && rhs)
}
func nand<L: BooleanType>( lhs: L, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs && rhs)
}
func nand<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs && rhs)
}
public func !&&( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs && rhs)
}
func ⊼( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs && rhs)
}
func ⊼<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs && rhs)
}
// MARK: - bit and
func band( lhs: Int, rhs: Int ) -> Int {
return lhs & rhs
}
func band( lhs: UInt, rhs: UInt ) -> UInt {
return lhs & rhs
}
// MARK: - or, ⋁
func or( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return lhs || rhs
}
func or<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return lhs || rhs
}
func ⋁( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return lhs || rhs
}
func ⋁<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return lhs || rhs
}
// MARK: nor, !||, ⊽
func nor( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs || rhs)
}
func nor<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs || rhs)
}
public func !||( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs || rhs)
}
func ⊽( lhs: Bool, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs || rhs)
}
public func !||<L: BooleanType>( lhs: L, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs || rhs)
}
func ⊽<L: BooleanType>( lhs: L, @autoclosure rhs: () -> Bool ) -> Bool {
return !(lhs || rhs)
}
public func !||<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs || rhs)
}
func ⊽<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs || rhs)
}
// MARK: - bit or
func bor( lhs: Int, rhs: Int ) -> Int {
return lhs | rhs
}
func bor( lhs: UInt, rhs: UInt ) -> UInt {
return lhs | rhs
}
// MARK: - xor, ^^, ⊻
func xor( lhs: Bool, rhs: Bool ) -> Bool {
return (lhs || rhs) && !(lhs && rhs)
//return (lhs && !rhs) || (!lhs && rhs)
}
func xor<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return (lhs || rhs) && !(lhs && rhs)
}
public func ^^( lhs: Bool, rhs: Bool ) -> Bool {
return (lhs || rhs) && !(lhs && rhs)
}
public func ^^<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return (lhs || rhs) && !(lhs && rhs)
}
func ⊻( lhs: Bool, rhs: Bool ) -> Bool {
return (lhs || rhs) && !(lhs && rhs)
}
func ⊻<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return (lhs || rhs) && !(lhs && rhs)
}
// MARK: - nxor, !^^
func nxor( lhs: Bool, rhs: Bool ) -> Bool {
return !(lhs ^^ rhs)
}
func nxor<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs ^^ rhs)
}
public func !^^( lhs: Bool, rhs: Bool ) -> Bool {
return !(lhs ^^ rhs)
}
public func !^^<L: BooleanType, R: BooleanType>( lhs: L, @autoclosure rhs: () -> R ) -> Bool {
return !(lhs ^^ rhs)
}
// MARK: - elementOf, ∈
func elementOf<S: SequenceType where S.Generator.Element: Equatable>( value: S.Generator.Element, sequence: S ) -> Bool {
return contains( sequence, value )
}
public func ∈<S: SequenceType where S.Generator.Element: Equatable>( value: S.Generator.Element, sequence: S ) -> Bool {
return contains( sequence, value )
}
func !∈<S: SequenceType where S.Generator.Element: Equatable>( value: S.Generator.Element, sequence: S ) -> Bool {
return !contains( sequence, value )
}
public func ∉<S: SequenceType where S.Generator.Element: Equatable>( value: S.Generator.Element, sequence: S ) -> Bool {
return !contains( sequence, value )
}
// MARK: - contains, ∋
public func ∋<S: SequenceType where S.Generator.Element: Equatable>( sequence: S, value: S.Generator.Element ) -> Bool {
return contains( sequence, value )
}
public func !∋<S: SequenceType where S.Generator.Element: Equatable>( sequence: S, value: S.Generator.Element ) -> Bool {
return !contains( sequence, value )
}
public func ∌<S: SequenceType where S.Generator.Element: Equatable>( sequence: S, value: S.Generator.Element ) -> Bool {
return !contains( sequence, value )
}
// MARK: - exists, ∃
func exists<T>( value: T? ) -> Bool {
return (value != nil) && !(value is NSNull)
}
func isNil<T>( value: T? ) -> Bool {
return (value == nil) || (value is NSNull)
}
func isNull<T>( value: T? ) -> Bool {
return (value == nil) || (value is NSNull)
}
public prefix func ∃<T>( value: T? ) -> Bool {
return value != nil
}
public prefix func !∃<T>( value: T? ) -> Bool {
return value == nil
}
public prefix func ∄<T>( value: T? ) -> Bool {
return value == nil
}
// MARK: - promote, ➚
prefix operator ➚ {}
prefix func ➚( value: Int8 ) -> Int {
return Int( value )
}
prefix func ➚( value: Int16 ) -> Int {
return Int( value )
}
prefix func ➚( value: Int32 ) -> Int {
return Int( value )
}
prefix func ➚( value: Int ) -> Int {
return Int( value )
}
prefix func ➚( value: UInt8 ) -> UInt {
return UInt( value )
}
prefix func ➚( value: UInt16 ) -> UInt {
return UInt( value )
}
prefix func ➚( value: UInt32 ) -> UInt {
return UInt( value )
}
prefix func ➚( value: UInt ) -> UInt {
return UInt( value )
}
prefix func ➚( value: Float ) -> Double {
return Double( value )
}
prefix func ➚( value: Double ) -> Double {
return Double( value )
}
// MARK: - demote, ➘
prefix operator ➘ {}
prefix func ➘( value: Int ) -> Int {
return Int( value )
}
prefix func ➘( value: Int64 ) -> Int {
return Int( value )
}
prefix func ➘( value: UInt ) -> UInt {
return UInt( value )
}
prefix func ➘( value: UInt64 ) -> UInt {
return UInt( value )
}
prefix func ➘( value: Float ) -> Float {
return Float( value )
}
prefix func ➘( value: Double ) -> Float {
return Float( value )
}
prefix func ➘( value: CGFloat ) -> Float {
return Float( value )
}
// MARK: - square root, √
prefix operator √ {}
public prefix func √( value: Float ) -> Float {
return sqrtf( value )
}
public prefix func √( value: Double ) -> Double {
return sqrt( value )
}
// MARK: cube root, ∛
prefix operator ∛ {}
prefix func ∛( value: Float ) -> Float {
return cbrtf( value )
}
prefix func ∛( value: Double ) -> Double {
return cbrt( value )
}
| 1c8d1e866f9346541f5a829abfcb854d | 19.960829 | 121 | 0.611081 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | refs/heads/master | Pods/HXPHPicker/Sources/HXPHPicker/Core/Extension/Core+PHAsset.swift | mit | 1 | //
// Core+PHAsset.swift
// HXPHPicker
//
// Created by Slience on 2021/6/9.
//
import Photos
extension PHAsset: HXPickerCompatible {
var isImageAnimated: Bool {
var isAnimated: Bool = false
let fileName = value(forKey: "filename") as? String
if fileName != nil {
isAnimated = fileName!.hasSuffix("GIF")
}
if #available(iOS 11, *) {
if playbackStyle == .imageAnimated {
isAnimated = true
}
}
return isAnimated
}
var isLivePhoto: Bool {
var isLivePhoto: Bool = false
if #available(iOS 9.1, *) {
isLivePhoto = mediaSubtypes == .photoLive
if #available(iOS 11, *) {
if playbackStyle == .livePhoto {
isLivePhoto = true
}
}
}
return isLivePhoto
}
/// 如果在获取到PHAsset之前还未下载的iCloud,之后下载了还是会返回存在
var inICloud: Bool {
if let isCloud = isCloudPlaceholder, isCloud {
return true
}
var isICloud = false
if mediaType == .image {
let options = PHImageRequestOptions()
options.isSynchronous = true
options.deliveryMode = .fastFormat
options.resizeMode = .fast
AssetManager.requestImageData(for: self, options: options) { (result) in
switch result {
case .failure(let error):
if let inICloud = error.info?.inICloud {
isICloud = inICloud
}
default:
break
}
}
return isICloud
}else {
return !isLocallayAvailable
}
}
var isCloudPlaceholder: Bool? {
if let isICloud = self.value(forKey: "isCloudPlaceholder") as? Bool {
return isICloud
}
return nil
}
var isLocallayAvailable: Bool {
if let isCloud = isCloudPlaceholder, isCloud {
return false
}
let resourceArray = PHAssetResource.assetResources(for: self)
let isLocallayAvailable = resourceArray.first?.value(forKey: "locallyAvailable") as? Bool ?? true
return isLocallayAvailable
}
@discardableResult
func checkAdjustmentStatus(completion: @escaping (Bool) -> Void) -> PHContentEditingInputRequestID {
requestContentEditingInput(with: nil) { (input, info) in
if let isCancel = info[PHContentEditingInputCancelledKey] as? Int, isCancel == 1 {
return
}
let avAsset = input?.audiovisualAsset
var isAdjusted: Bool = false
if let path = avAsset != nil ? avAsset?.description : input?.fullSizeImageURL?.path {
if path.contains("/Mutations/") {
isAdjusted = true
}
}
completion(isAdjusted)
}
}
}
public extension HXPickerWrapper where Base: PHAsset {
var isImageAnimated: Bool {
base.isImageAnimated
}
var isLivePhoto: Bool {
base.isLivePhoto
}
var inICloud: Bool {
base.inICloud
}
var isCloudPlaceholder: Bool? {
base.isCloudPlaceholder
}
var isLocallayAvailable: Bool {
base.isLocallayAvailable
}
@discardableResult
func checkAdjustmentStatus(
completion: @escaping (Bool) -> Void
) -> PHContentEditingInputRequestID {
base.checkAdjustmentStatus(completion: completion)
}
}
| 0e8acde8853109516ca0cb0d64449023 | 28.040323 | 105 | 0.550125 | false | false | false | false |
zjjzmw1/SwiftCodeFragments | refs/heads/master | Pods/ImageViewer/ImageViewer/Source/Thumbnails Controller/ThumbnailsViewController.swift | mit | 1 | //
// ThumbnailsViewController.swift
// ImageViewer
//
// Created by Zeno Foltin on 07/07/2016.
// Copyright © 2016 MailOnline. All rights reserved.
//
import UIKit
class ThumbnailsViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UINavigationBarDelegate {
fileprivate let reuseIdentifier = "ThumbnailCell"
fileprivate let sectionInsets = UIEdgeInsets(top: 50.0, left: 20.0, bottom: 50.0, right: 20.0)
fileprivate var isAnimating = false
fileprivate let rotationAnimationDuration = 0.2
var onItemSelected: ((Int) -> Void)?
let layout = UICollectionViewFlowLayout()
weak var itemsDatasource: GalleryItemsDatasource!
var closeButton: UIButton?
var closeLayout: ButtonLayout?
required init(itemsDatasource: GalleryItemsDatasource) {
self.itemsDatasource = itemsDatasource
super.init(collectionViewLayout: layout)
NotificationCenter.default.addObserver(self, selector: #selector(rotate), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func rotate() {
guard UIApplication.isPortraitOnly else { return }
guard UIDevice.current.orientation.isFlat == false &&
isAnimating == false else { return }
isAnimating = true
UIView.animate(withDuration: rotationAnimationDuration, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: { [weak self] () -> Void in
self?.view.transform = windowRotationTransform()
self?.view.bounds = rotationAdjustedBounds()
self?.view.setNeedsLayout()
self?.view.layoutIfNeeded()
})
{ [weak self] finished in
self?.isAnimating = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
let screenWidth = self.view.frame.width
layout.sectionInset = UIEdgeInsets(top: 50, left: 8, bottom: 8, right: 8)
layout.itemSize = CGSize(width: screenWidth/3 - 8, height: screenWidth/3 - 8)
layout.minimumInteritemSpacing = 4
layout.minimumLineSpacing = 4
self.collectionView?.register(ThumbnailCell.self, forCellWithReuseIdentifier: reuseIdentifier)
addCloseButton()
}
fileprivate func addCloseButton() {
guard let closeButton = closeButton, let closeLayout = closeLayout else { return }
switch closeLayout {
case .pinRight(let marginTop, let marginRight):
closeButton.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin]
closeButton.frame.origin.x = self.view.bounds.size.width - marginRight - closeButton.bounds.size.width
closeButton.frame.origin.y = marginTop
case .pinLeft(let marginTop, let marginLeft):
closeButton.autoresizingMask = [.flexibleBottomMargin, .flexibleRightMargin]
closeButton.frame.origin.x = marginLeft
closeButton.frame.origin.y = marginTop
}
closeButton.addTarget(self, action: #selector(close), for: .touchUpInside)
self.view.addSubview(closeButton)
}
func close() {
self.dismiss(animated: true, completion: nil)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemsDatasource.itemCount()
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ThumbnailCell
let item = itemsDatasource.provideGalleryItem((indexPath as NSIndexPath).row)
switch item {
case .image(let fetchImageBlock):
fetchImageBlock() { image in
if let image = image {
cell.imageView.image = image
}
}
case .video(let fetchImageBlock, _):
fetchImageBlock() { image in
if let image = image {
cell.imageView.image = image
}
}
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
onItemSelected?((indexPath as NSIndexPath).row)
close()
}
}
| e1676e130cd049fb03a5a7955a946c87 | 33.014599 | 158 | 0.648498 | false | false | false | false |
batoulapps/QamarDeen | refs/heads/dev | QamarDeen/QamarDeen/Services/Points.swift | mit | 1 | //
// Points.swift
// QamarDeen
//
// Created by Mazyad Alabduljaleel on 12/28/16.
// Copyright © 2016 Batoul Apps. All rights reserved.
//
import Foundation
/// Points
/// class which holds the points calculation
private final class Points {
static func `for`(_ fast: Fast) -> Int {
guard let rawValue = fast.type, let fastKind = Fast.Kind(rawValue: rawValue) else {
return 0
}
switch fastKind {
case .none: return 0
case .forgiveness: return 100
case .vow: return 250
case .reconcile: return 400
case .voluntary: return 500
case .mandatory: return 500
}
}
static func `for`(_ charity: Charity) -> Int {
guard let rawValue = charity.type, let charityKind = Charity.Kind(rawValue: rawValue) else {
return 0
}
switch charityKind {
case .smile: return 25
default: return 100
}
}
static func `for`(_ prayer: Prayer) -> Int {
guard let methodValue = prayer.method,
let method = Prayer.Method(rawValue: methodValue),
let kindValue = prayer.type,
let kind = Prayer.Kind(rawValue: kindValue)
else
{
return 0
}
switch (method, kind) {
case (.alone, .shuruq): return 200
case (.alone, .qiyam): return 300
case (.alone, _): return 100
case (.group, .qiyam): return 300
case (.group, _): return 400
case (.aloneWithVoluntary, _): return 200
case (.groupWithVoluntary, _): return 500
case (.late, _): return 25
case (.excused, _): return 300
default: return 0
}
}
static func `for`(_ reading: Reading) -> Int {
return reading.ayahCount * 2
}
}
/// Extensions
/// convenience access to point calculation through model classes
// MARK: CountableAction
extension Collection where Iterator.Element: CountableAction {
var points: Int {
return map { $0.points }
.reduce(0, +)
}
}
// MARK: Fasting
extension Fast: CountableAction {
var points: Int {
return Points.for(self)
}
}
// MARK: Charity
extension Charity: CountableAction {
var points: Int {
return Points.for(self)
}
}
// MARK: Prayer
extension Prayer: CountableAction {
var points: Int {
return Points.for(self)
}
}
/// MARK: Reading
extension Reading: CountableAction {
var points: Int {
return Points.for(self)
}
}
// MARK: Day
extension Day: CountableAction {
var charityCollection: [Charity] {
return charities?.flatMap { $0 as? Charity } ?? []
}
var prayerCollection: [Prayer] {
return prayers?.flatMap { $0 as? Prayer } ?? []
}
var readingsCollection: [Reading] {
return readings?.flatMap { $0 as? Reading } ?? []
}
var points: Int {
return [
fast?.points ?? 0,
prayerCollection.points,
charityCollection.points,
readingsCollection.points
].reduce(0, +)
}
}
| f8725257af08974842670c12a1f7ec3b | 22.222222 | 100 | 0.53439 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | refs/heads/master | 34--First-Contact/Friends/Friends/PersonDetailViewController.swift | cc0-1.0 | 1 | //
// PersonDetailViewController.swift
// Friends
//
// Created by Ben Gohlke on 11/19/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import RealmSwift
class PersonDetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
@IBOutlet weak var friendCountLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
let realm = try! Realm()
var person: Person?
var allPeople: Results<Person>!
override func viewDidLoad()
{
super.viewDidLoad()
allPeople = realm.objects(Person).filter("name != %@", person!.name).sorted("name")
updateFriendCountLabel()
}
func updateFriendCountLabel()
{
friendCountLabel.text = "\(person!.name) has \(person!.friendCount) friend\(person!.friendCount == 1 ? "" : "s")"
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UITableView Data Source
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return allPeople.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
return "Add some friends"
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("FriendCell", forIndexPath: indexPath)
let aPossibleFriend = allPeople[indexPath.row]
cell.textLabel?.text = aPossibleFriend.name
let results = person!.friends.filter("name == %@", aPossibleFriend.name)
if results.count == 1
{
cell.accessoryType = .Checkmark
}
else
{
cell.accessoryType = .None
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let cell = tableView.cellForRowAtIndexPath(indexPath)
if cell?.accessoryType == UITableViewCellAccessoryType.None
{
cell?.accessoryType = .Checkmark
try! realm.write { () -> Void in
self.person!.friends.append(self.allPeople[indexPath.row])
self.person!.friendCount++
}
updateFriendCountLabel()
}
else
{
cell?.accessoryType = .None
try! realm.write { () -> Void in
let index = self.person!.friends.indexOf(self.allPeople[indexPath.row])
self.person!.friends.removeAtIndex(index!)
self.person!.friendCount--
}
updateFriendCountLabel()
}
}
} | 8d45cf097c9c188cf8f7b230e9695ca9 | 28.95 | 121 | 0.616566 | false | false | false | false |
apple/swift | refs/heads/main | test/Interop/SwiftToCxx/structs/resilient-struct-in-cxx.swift | apache-2.0 | 1 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -enable-library-evolution -typecheck -module-name Structs -clang-header-expose-decls=all-public -emit-clang-header-path %t/structs.h
// RUN: %FileCheck %s < %t/structs.h
// RUN: %check-interop-cxx-header-in-clang(%t/structs.h)
public struct FirstSmallStruct {
public var x: UInt32
#if CHANGE_LAYOUT
public var y: UInt32 = 0
#endif
public func dump() {
print("find - small dump")
#if CHANGE_LAYOUT
print("x&y = \(x)&\(y)")
#else
print("x = \(x)")
#endif
}
public mutating func mutate() {
x = x * 2
#if CHANGE_LAYOUT
y = ~y
#endif
}
}
// CHECK: class FirstSmallStruct;
// CHECK: template<>
// CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<Structs::FirstSmallStruct> = true;
// CHECK: class FirstSmallStruct final {
// CHECK-NEXT: public:
// CHECK: inline FirstSmallStruct(const FirstSmallStruct &other) {
// CHECK-NEXT: auto metadata = _impl::$s7Structs16FirstSmallStructVMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: _storage = swift::_impl::OpaqueStorage(vwTable->size, vwTable->getAlignment());
// CHECK-NEXT: vwTable->initializeWithCopy(_getOpaquePointer(), const_cast<char *>(other._getOpaquePointer()), metadata._0);
// CHECK-NEXT: }
// CHECK: private:
// CHECK-NEXT: inline FirstSmallStruct(swift::_impl::ValueWitnessTable * _Nonnull vwTable) : _storage(vwTable->size, vwTable->getAlignment()) {}
// CHECK-NEXT: static inline FirstSmallStruct _make() {
// CHECK-NEXT: auto metadata = _impl::$s7Structs16FirstSmallStructVMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: return FirstSmallStruct(vwTable);
// CHECK-NEXT: }
// CHECK-NEXT: inline const char * _Nonnull _getOpaquePointer() const { return _storage.getOpaquePointer(); }
// CHECK-NEXT: inline char * _Nonnull _getOpaquePointer() { return _storage.getOpaquePointer(); }
// CHECK-EMPTY:
// CHECK-NEXT: swift::_impl::OpaqueStorage _storage;
// CHECK-NEXT: friend class _impl::_impl_FirstSmallStruct;
// CHECK-NEXT:};
// CHECK: class _impl_FirstSmallStruct {
// CHECK: };
// CHECK-EMPTY:
// CHECK-NEXT: }
// CHECK-EMPTY:
// CHECK-NEXT: } // end namespace
// CHECK-EMPTY:
// CHECK-NEXT: namespace swift {
// CHECK-NEXT: #pragma clang diagnostic push
// CHECK-NEXT: #pragma clang diagnostic ignored "-Wc++17-extensions"
// CHECK-NEXT: template<>
// CHECK-NEXT: struct TypeMetadataTrait<Structs::FirstSmallStruct> {
// CHECK-NEXT: inline void * _Nonnull getTypeMetadata() {
// CHECK-NEXT: return Structs::_impl::$s7Structs16FirstSmallStructVMa(0)._0;
// CHECK-NEXT: }
// CHECK-NEXT: };
// CHECK-NEXT: namespace _impl{
// CHECK-NEXT: template<>
// CHECK-NEXT: static inline const constexpr bool isValueType<Structs::FirstSmallStruct> = true;
// CHECK-NEXT: template<>
// CHECK-NEXT: static inline const constexpr bool isOpaqueLayout<Structs::FirstSmallStruct> = true;
// CHECK-NEXT: template<>
// CHECK-NEXT: struct implClassFor<Structs::FirstSmallStruct> { using type = Structs::_impl::_impl_FirstSmallStruct; };
// CHECK-NEXT: } // namespace
// CHECK-NEXT: #pragma clang diagnostic pop
// CHECK-NEXT: } // namespace swift
// CHECK-EMPTY:
// CHECK-NEXT: namespace Structs __attribute__((swift_private)) {
@frozen public struct FrozenStruct {
private let storedInt: Int32
}
// CHECK: class FrozenStruct final {
// CHECK: alignas(4) char _storage[4];
// CHECK-NEXT: friend class _impl::_impl_FrozenStruct;
// CHECK-NEXT: };
public struct LargeStruct {
public let x1: Int
let x2, x3, x4, x5, x6: Int
public var firstSmallStruct: FirstSmallStruct {
return FirstSmallStruct(x: 65)
}
public func dump() {
print("x.1 = \(x1), .2 = \(x2), .3 = \(x3), .4 = \(x4), .5 = \(x5)")
}
}
// CHECK: class LargeStruct final {
// CHECK-NEXT: public:
// CHECK: inline LargeStruct(const LargeStruct &other) {
// CHECK-NEXT: auto metadata = _impl::$s7Structs11LargeStructVMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: _storage = swift::_impl::OpaqueStorage(vwTable->size, vwTable->getAlignment());
// CHECK-NEXT: vwTable->initializeWithCopy(_getOpaquePointer(), const_cast<char *>(other._getOpaquePointer()), metadata._0);
// CHECK-NEXT: }
// CHECK: private:
// CHECK-NEXT: inline LargeStruct(swift::_impl::ValueWitnessTable * _Nonnull vwTable) : _storage(vwTable->size, vwTable->getAlignment()) {}
// CHECK-NEXT: static inline LargeStruct _make() {
// CHECK-NEXT: auto metadata = _impl::$s7Structs11LargeStructVMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: return LargeStruct(vwTable);
// CHECK-NEXT: }
// CHECK-NEXT: inline const char * _Nonnull _getOpaquePointer() const { return _storage.getOpaquePointer(); }
// CHECK-NEXT: inline char * _Nonnull _getOpaquePointer() { return _storage.getOpaquePointer(); }
// CHECK-EMPTY:
// CHECK-NEXT: swift::_impl::OpaqueStorage _storage;
// CHECK-NEXT: friend class _impl::_impl_LargeStruct;
// CHECK-NEXT: };
private class RefCountedClass {
let x: Int
init(x: Int) {
self.x = x
print("create RefCountedClass \(x)")
}
deinit {
print("destroy RefCountedClass \(x)")
}
}
public struct StructWithRefCountStoredProp {
private let storedRef: RefCountedClass
init(x: Int) {
storedRef = RefCountedClass(x: x)
}
public func dump() {
print("storedRef = \(storedRef.x)")
}
}
// CHECK: inline StructWithRefCountStoredProp(swift::_impl::ValueWitnessTable * _Nonnull vwTable) : _storage(vwTable->size, vwTable->getAlignment()) {}
public func createLargeStruct(_ x: Int) -> LargeStruct {
return LargeStruct(x1: x, x2: -x, x3: x * 2, x4: x - 4, x5: 0, x6: 21)
}
public func printSmallAndLarge(_ x: FirstSmallStruct, _ y: LargeStruct) {
x.dump()
y.dump()
}
public func createStructWithRefCountStoredProp() -> StructWithRefCountStoredProp {
return StructWithRefCountStoredProp(x: 0)
}
public func mutateSmall(_ x: inout FirstSmallStruct) {
#if CHANGE_LAYOUT
let y = x.y
x.y = x.x
x.x = y
#else
x.x += 1
#endif
}
// CHECK: inline LargeStruct createLargeStruct(swift::Int x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Structs17createLargeStructyAA0cD0VSiF(result, x);
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline StructWithRefCountStoredProp createStructWithRefCountStoredProp() noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::_impl_StructWithRefCountStoredProp::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Structs34createStructWithRefCountStoredPropAA0cdefgH0VyF(result);
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline void mutateSmall(FirstSmallStruct& x) noexcept {
// CHECK-NEXT: return _impl::$s7Structs11mutateSmallyyAA05FirstC6StructVzF(_impl::_impl_FirstSmallStruct::getOpaquePointer(x));
// CHECK-NEXT: }
// CHECK: inline void printSmallAndLarge(const FirstSmallStruct& x, const LargeStruct& y) noexcept {
// CHECK-NEXT: return _impl::$s7Structs18printSmallAndLargeyyAA05FirstC6StructV_AA0eG0VtF(_impl::_impl_FirstSmallStruct::getOpaquePointer(x), _impl::_impl_LargeStruct::getOpaquePointer(y));
// CHECK-NEXT: }
// CHECK: inline uint32_t FirstSmallStruct::getX() const {
// CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV1xs6UInt32Vvg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline void FirstSmallStruct::setX(uint32_t value) {
// CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV1xs6UInt32Vvs(value, _getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline void FirstSmallStruct::dump() const {
// CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV4dumpyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline void FirstSmallStruct::mutate() {
// CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV6mutateyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline swift::Int LargeStruct::getX1() const {
// CHECK-NEXT: return _impl::$s7Structs11LargeStructV2x1Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct LargeStruct::getFirstSmallStruct() const {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Structs11LargeStructV010firstSmallC0AA05FirsteC0Vvg(result, _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline void LargeStruct::dump() const {
// CHECK-NEXT: return _impl::$s7Structs11LargeStructV4dumpyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline void StructWithRefCountStoredProp::dump() const {
// CHECK-NEXT: return _impl::$s7Structs28StructWithRefCountStoredPropV4dumpyyF(_getOpaquePointer());
// CHECK-NEXT: }
| 39cad0bd5c78e4dcc6c0582178c65baf | 41.95122 | 231 | 0.699886 | false | false | false | false |
hollisliu/Spacetime-Rhapsody | refs/heads/master | Spacetime Rhapsody.playgroundbook/Contents/Sources/TouchHandler.swift | mit | 1 | //
// TouchHandler.swift
// Fabric
//
// Created by Hanjie Liu on 3/30/17.
// Copyright © 2017 Hanjie Liu. All rights reserved.
//
import Foundation
import SceneKit
public extension UniverseViewController {
private func computeWoldClippingZFromScreenPointY(screenPoint p: CGFloat) -> CGFloat{
let z1 = fabricVanishPoint.z
let z0 = fabricZero.z
let y1 = fabricVanishPoint.y
let y0 = fabricZero.y
let a = -(z1 - z0)
let z = a * ((SCNFloat(p) - y1) / (y0 - y1)) + z1
return CGFloat(z)
}
func handlePan(_ gestureRecognize: UIPanGestureRecognizer){
let p = gestureRecognize.location(in: scnView)
// add touch points to queue for velocity calculation
previousTouchedPoints.enqueue(point: p)
switch gestureRecognize.state{
case .began:
let hitResults = scnView.hitTest(p, options: nil)
if hitResults.count > 0 {
let result = hitResults[0]
let node = result.node
// avoid moving the spacetime fabic
if (node.name == Constants.fabricName) {
return
}
selectedNode = node
objectPicked = true
if (selectedNode?.physicsBody?.type == .static) {
// play sound effect
playFabricSound(node: selectedNode!)
}
}
case .changed:
// move objects
if objectPicked {
// enter scene
if (selectedNode?.physicsBody?.type == .none){
let body = SCNPhysicsBody(type: .dynamic, shape: SCNPhysicsShape(geometry: selectedNode!.geometry!, options: nil))
body.isAffectedByGravity = false
body.friction = 0
body.damping = 0
//body.angularVelocity.y = 0.5
switch selectedNode!.name! {
case "earth":
body.mass = 1
case "mars":
body.mass = 0.8
case "venus":
body.mass = 0.7
case "jupiter":
body.mass = 3
case "neptune":
body.mass = 2
default:
break
}
selectedNode!.physicsBody = body
// play sound effect
playFabricSound(node: selectedNode!)
}
// remove velocity when select an object
let v = selectedNode?.physicsBody?.velocity.norm()
if (v != 0) {
selectedNode?.physicsBody?.type = .static
}
let z = computeWoldClippingZFromScreenPointY(screenPoint: p.y)
let worldPoint = scnView.unprojectPoint(SCNVector3(p.x, p.y, z))
let action = SCNAction.move(to: worldPoint, duration: Constants.refreshRate)
selectedNode?.runAction(action)
}
// change camera angle
else {
let fingers = gestureRecognize.numberOfTouches
// pitch camera
if (fingers == 2) {
// positive velocity means downwards
let v = gestureRecognize.velocity(in: scnView).y
if (v < 0) {
camera?.eulerAngles.x += 0.008
camera?.position.y -= 0.1
} else {
camera?.eulerAngles.x -= 0.008
camera?.position.y += 0.1
}
}
}
case .ended:
if objectPicked {
// apply force
let head = previousTouchedPoints.first()
let z0 = computeWoldClippingZFromScreenPointY(screenPoint: head.y)
let p0 = scnView.unprojectPoint(SCNVector3(head.x, head.y, z0))
let z1 = computeWoldClippingZFromScreenPointY(screenPoint: p.y)
let p1 = scnView.unprojectPoint(SCNVector3(p.x, p.y, z1))
let dx = p1 - p0
let dt = SCNFloat(Constants.touchSampleRate) / Constants.screenRefreshRate
var vel = dx / dt
// avoid flying error
if (dx.norm() < 1) {
selectedNode?.physicsBody?.type = .dynamic
return
}
// smoothing factor to avoid quick swipe resulting in huge velocity
let fineTuneFactor = Constants.fingerStrengthFactor / log(vel.norm())
vel = (vel / vel.norm()) * fineTuneFactor
selectedNode?.physicsBody?.type = .dynamic
selectedNode?.physicsBody?.velocity = vel
}
previousTouchedPoints.clear()
objectPicked = false
default: break
}
}
/// camera zoom
func handlePintch(_ gestureRecognize: UIPinchGestureRecognizer) {
switch gestureRecognize.state {
case .changed:
let s = gestureRecognize.scale
if (s > 1) {
// zoom in
if (camera!.camera!.xFov < 40) {break}
camera?.camera?.xFov -= 0.9
camera?.camera?.yFov -= 0.9
} else {
if (s == 1) {return}
//zoom out
if (camera!.camera!.xFov > 100) {break}
camera?.camera?.xFov += 1.1
camera?.camera?.yFov += 1.1
}
default:
break
}
}
}
| f59e7500e216cf9653df34bc3db64110 | 33.043478 | 134 | 0.442369 | false | false | false | false |
wdkk/CAIM | refs/heads/master | AR/caimar00/CAIMMetal/CAIMMetalShader.swift | mit | 15 | //
// CAIMMetalView.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
#if os(macOS) || (os(iOS) && !arch(x86_64))
import Foundation
import Metal
// Metalライブラリでコードを読み込むのを簡単にするための拡張
public extension MTLLibrary
{
static func make( with code:String ) -> MTLLibrary? {
return try! CAIMMetal.device?.makeLibrary( source: code, options:nil )
}
}
// シェーダオブジェクトクラス
public class CAIMMetalShader
{
// Metalシェーダ関数オブジェクト
public private(set) var function:MTLFunction?
// デフォルトライブラリでシェーダ関数作成
public init( _ shader_name:String ) {
guard let lib:MTLLibrary = CAIMMetal.device?.makeDefaultLibrary() else { return }
function = lib.makeFunction( name: shader_name )
}
// 外部ライブラリファイルでシェーダ関数作成
public init( libname:String, shaderName shader_name:String ) {
let lib_path = Bundle.main.path(forResource: libname, ofType: "metallib")!
guard let lib:MTLLibrary = try! CAIMMetal.device?.makeLibrary( filepath: lib_path ) else { return }
function = lib.makeFunction( name: shader_name )
}
// クラス名指定でバンドル元を指定し(たとえば外部frameworkなど)そこにそこに含まれるdefault.metallibを用いてシェーダ関数作成
public init( class cls:AnyClass, shaderName shader_name:String ) {
let bundle = Bundle(for: cls.self )
guard let lib:MTLLibrary = try! CAIMMetal.device?.makeDefaultLibrary(bundle: bundle) else { return }
function = lib.makeFunction( name: shader_name )
}
// クラス名指定でバンドル元を指定し(たとえば外部frameworkなど)そこにそこに含まれるdefault.metallibを用いてシェーダ関数作成
public init( class cls:AnyClass, libname:String, shaderName shader_name:String ) {
let lib_path = Bundle(for: cls.self ).path(forResource: libname, ofType: "metallib")!
guard let lib:MTLLibrary = try! CAIMMetal.device?.makeLibrary( filepath: lib_path ) else { return }
function = lib.makeFunction( name: shader_name )
}
// コード文字列でシェーダ関数作成
public init( code:String, shaderName shader_name:String ) {
guard let lib:MTLLibrary = try! CAIMMetal.device?.makeLibrary( source: code, options:nil ) else { return }
function = lib.makeFunction( name: shader_name )
}
// MTLLibraryでシェーダ関数作成
public init( mtllib:MTLLibrary, shaderName shader_name:String ) {
function = mtllib.makeFunction( name: shader_name )
}
}
#endif
| 008408f6505b612618ed86db41e17d39 | 34.28169 | 114 | 0.684631 | false | false | false | false |
liangbo707/LB-SwiftProject | refs/heads/master | LBPersonalApp/Main/SinaOAuth/LBSinaOAuthController.swift | apache-2.0 | 1 | //
// LBSinaOAuthController.swift
// LBPersonalApp
//
// Created by MR on 16/6/15.
// Copyright © 2016年 LB. All rights reserved.
//
import UIKit
import SVProgressHUD
class LBSinaOAuthController: UIViewController{
// MARK:父类方法
override func loadView() {
webView.delegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
title = "what are you 弄啥勒"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
webView.loadRequest(NSURLRequest(URL: LBNetworkTool.sharedInstance.oauthURL()))
}
// MARK:关闭页面
func close(){
SVProgressHUD.dismiss()
dismissViewControllerAnimated(true, completion: nil)
}
// MARK:填充密码
func autoFill(){
// 创建js代码
let js = "document.getElementById('userId').value='13009374527'; document.getElementById('passwd').value='lb8522707';"
// 让webView执行js代码
webView.stringByEvaluatingJavaScriptFromString(js)
}
// MARK: 加载accessToken
func loadAccessToken(code: String){
LBNetworkTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
if error != nil || result == nil {
SVProgressHUD.showWithStatus("你的网络不给力")
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), { () -> Void in
self.close() //闭包要用self
})
return
}
let userAccount = LBUserAccount(dict: result!)
userAccount.saveAccount()
NSNotificationCenter.defaultCenter().postNotificationName(LBSwitchRootVCNotification, object: false)
SVProgressHUD.dismiss()
self.close()
}
}
// MARK:懒加载
private lazy var webView = UIWebView()
}
// MARK:扩展webview 协议
extension LBSinaOAuthController : UIWebViewDelegate{
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let urlString = request.URL!.absoluteString
// 如果不是回调的url 继续加载
if !urlString.hasPrefix(LBNetworkTool.sharedInstance.redirect_URI){
return true
}
//可选绑定
if let query = request.URL!.query {// query 是url中参数字符串
let codeStr = "code="
if query.hasPrefix(codeStr){ //授权
let nsQuery = query as NSString
let code = nsQuery.substringFromIndex(codeStr.characters.count)
loadAccessToken(code)
}else{ //取消授权
close()
}
}
return false
}
func webViewDidStartLoad(webView: UIWebView) {
SVProgressHUD.showWithStatus("正在加载...")
}
func webViewDidFinishLoad(webView: UIWebView) {
SVProgressHUD.dismiss()
}
/*
授权成功 : code=e33906d3d2943f7ee4397e93788ffc5b
授权失败 : URL: https://m.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330&from=844b&vit=fps
*/
} | 889e9d13b567aff2d11b9878ce3a41c1 | 34.602151 | 173 | 0.629909 | false | false | false | false |
jhend11/Coinvert | refs/heads/master | Coinvert/Coinvert/MenuTransitionManager.swift | lgpl-3.0 | 1 | //
// MenuTransitionManager.swift
// Menu
//
// Created by Mathew Sanders on 9/7/14.
// Copyright (c) 2014 Mat. All rights reserved.
//
import UIKit
class MenuTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
private var presenting = false
// MARK: UIViewControllerAnimatedTransitioning protocol methods
// animate a change from one viewcontroller to another
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// get reference to our fromView, toView and the container view that we should perform the transition in
let container = transitionContext.containerView()
// create a tuple of our screens
let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!, transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!)
// assign references to our menu view controller and the 'bottom' view controller from the tuple
// remember that our menuViewController will alternate between the from and to view controller depending if we're presenting or dismissing
let menuViewController = !self.presenting ? screens.from as MenuViewController : screens.to as MenuViewController
let bottomViewController = !self.presenting ? screens.to as UIViewController : screens.from as UIViewController
let menuView = menuViewController.view
let bottomView = bottomViewController.view
// prepare menu items to slide in
if (self.presenting){
self.offStageMenuController(menuViewController)
}
// add the both views to our view controller
container.addSubview(bottomView)
container.addSubview(menuView)
let duration = self.transitionDuration(transitionContext)
// perform the animation!
UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: nil, animations: {
if (self.presenting){
self.onStageMenuController(menuViewController) // onstage items: slide in
}
else {
self.offStageMenuController(menuViewController) // offstage items: slide out
}
}, completion: { finished in
// tell our transitionContext object that we've finished animating
transitionContext.completeTransition(true)
// bug: we have to manually add our 'to view' back http://openradar.appspot.com/radar?id=5320103646199808
UIApplication.sharedApplication().keyWindow!.addSubview(screens.to.view)
})
}
func offStage(amount: CGFloat) -> CGAffineTransform {
return CGAffineTransformMakeTranslation(amount, 0)
}
func offStageMenuController(menuViewController: MenuViewController){
menuViewController.view.alpha = 0
// setup paramaters for 2D transitions for animations
let topRowOffset :CGFloat = 111
let middle1RowOffset :CGFloat = 223
let middle2RowOffset :CGFloat = 334
let bottomRowOffset :CGFloat = 446
menuViewController.bitcoinIcon.transform = self.offStage(topRowOffset)
menuViewController.bitcoinLabel.transform = self.offStage(topRowOffset)
menuViewController.litecoinIcon.transform = self.offStage(topRowOffset)
menuViewController.litecoinLabel.transform = self.offStage(topRowOffset)
menuViewController.dogecoinIcon.transform = self.offStage(middle1RowOffset)
menuViewController.dogecoinLabel.transform = self.offStage(middle1RowOffset)
// menuViewController.darcoinIcon.transform = self.offStage(-middle1RowOffset)
// menuViewController.darkcoinLabel.transform = self.offStage(-middle1RowOffset)
//
//
// menuViewController.feathercoinIcon.transform = self.offStage(-middle2RowOffset)
// menuViewController.feathercoinLabel.transform = self.offStage(-middle2RowOffset)
//
// menuViewController.namecoinIcon.transform = self.offStage(middle2RowOffset)
// menuViewController.namecoinLabel.transform = self.offStage(middle2RowOffset)
//
// menuViewController.peercoinIcon.transform = self.offStage(-bottomRowOffset)
// menuViewController.peercoinLabel.transform = self.offStage(-bottomRowOffset)
//
// menuViewController.blackcoinIcon.transform = self.offStage(bottomRowOffset)
// menuViewController.blackcoinLabel.transform = self.offStage(bottomRowOffset)
}
func onStageMenuController(menuViewController: MenuViewController){
// prepare menu to fade in
menuViewController.view.alpha = 1
menuViewController.bitcoinIcon.transform = CGAffineTransformIdentity
menuViewController.bitcoinLabel.transform = CGAffineTransformIdentity
menuViewController.litecoinIcon.transform = CGAffineTransformIdentity
menuViewController.litecoinLabel.transform = CGAffineTransformIdentity
menuViewController.dogecoinIcon.transform = CGAffineTransformIdentity
menuViewController.dogecoinLabel.transform = CGAffineTransformIdentity
// menuViewController.darcoinIcon.transform = CGAffineTransformIdentity
// menuViewController.darkcoinLabel.transform = CGAffineTransformIdentity
//
// menuViewController.feathercoinIcon.transform = CGAffineTransformIdentity
// menuViewController.feathercoinLabel.transform = CGAffineTransformIdentity
//
// menuViewController.namecoinIcon.transform = CGAffineTransformIdentity
// menuViewController.namecoinLabel.transform = CGAffineTransformIdentity
//
// menuViewController.peercoinIcon.transform = CGAffineTransformIdentity
// menuViewController.peercoinLabel.transform = CGAffineTransformIdentity
//
// menuViewController.blackcoinIcon.transform = CGAffineTransformIdentity
// menuViewController.blackcoinLabel.transform = CGAffineTransformIdentity
}
// return how many seconds the transiton animation will take
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 0.6
}
// MARK: UIViewControllerTransitioningDelegate protocol methods
// return the animataor when presenting a viewcontroller
// rememeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
return self
}
// return the animator used when dismissing from a viewcontroller
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = false
return self
}
}
| 3c5e62bc7ccea491c66ef975050b22ad | 45.135802 | 233 | 0.706583 | false | false | false | false |
itechline/bonodom_new | refs/heads/master | SlideMenuControllerSwift/MessageTableCell.swift | mit | 1 | //
// MessageItemViewController.swift
// Bonodom
//
// Created by Attila Dan on 06/06/16.
// Copyright © 2016 Itechline. All rights reserved.
//
import UIKit
import SwiftyJSON
struct MessageTableCellData {
init(date: String, fel_vezeteknev: String, fel_keresztnev: String, ingatlan_varos: String, ingatlan_utca: String, hash: String, uid: Int) {
self.date = date
self.fel_keresztnev = fel_keresztnev
self.fel_vezeteknev = fel_vezeteknev
self.ingatlan_varos = ingatlan_varos
self.ingatlan_utca = ingatlan_utca
self.hash = hash
self.uid = uid
}
var date: String
var fel_vezeteknev: String
var fel_keresztnev: String
var ingatlan_varos: String
var ingatlan_utca: String
var hash: String
var uid: Int
}
class MessageTableCell: BaseTableViewCell {
@IBOutlet weak var name_text: UILabel!
@IBOutlet weak var date_text: UILabel!
@IBOutlet weak var adress_text: UILabel!
@IBOutlet weak var profile_picture: UIImageView!
@IBOutlet weak var name: UILabel!
override func awakeFromNib() {
//self.dataText?.font = UIFont.boldSystemFontOfSize(16)
//self.dataText?.textColor = UIColor(hex: "000000")
}
override class func height() -> CGFloat {
return 57
}
override func setData(data: Any?) {
if let data = data as? MessageTableCellData {
self.name_text.text = data.fel_vezeteknev + " " + data.fel_keresztnev
self.date_text.text = data.date
self.adress_text.text = data.ingatlan_varos + " " + data.ingatlan_utca
}
}
}
| 1aefab4330effa71f1f2cb984a904de0 | 27.338983 | 143 | 0.633373 | false | false | false | false |
Fenrikur/ef-app_ios | refs/heads/master | Domain Model/EurofurenceModel/Public/Default Dependency Implementations/Core Data Store/Model Adaptation/ReadAnnouncementEntity+Adaptation.swift | mit | 3 | import Foundation
extension ReadAnnouncementEntity: EntityAdapting {
typealias AdaptedType = AnnouncementIdentifier
static func makeIdentifyingPredicate(for model: AnnouncementIdentifier) -> NSPredicate {
return NSPredicate(format: "announcementIdentifier == %@", model.rawValue)
}
func asAdaptedType() -> AnnouncementIdentifier {
guard let announcementIdentifier = announcementIdentifier else {
abandonDueToInconsistentState()
}
return AnnouncementIdentifier(announcementIdentifier)
}
func consumeAttributes(from value: AnnouncementIdentifier) {
announcementIdentifier = value.rawValue
}
}
| 6dc523d988e9a24a59a8882a20b3f814 | 28.826087 | 92 | 0.72449 | false | false | false | false |
s4cha/Matrix | refs/heads/master | CNNApp/ConvolutionalNeuralNetwork.swift | mit | 1 | //
// ConvolutionalNeuralNetwork.swift
// CNNApp
//
// Created by Sacha Durand Saint Omer on 20/06/2017.
// Copyright © 2017 freshOS. All rights reserved.
//
import Foundation
struct Params {
struct Convolution {
static let numberOfFeatures = 1
static let sizeOfOfFeatures = 3
}
struct Pooling {
static let windowSize = 2
static let stride = 2
}
struct FullyConnected {
static let numberOfNeurons = 3
}
static let learningRate: Float = 2
}
class ConvolutionalNeuralNetwork {
var previousGlobalErrorRate:Float = 1
var previousPrediction = [Float]()
var previousResult:Float = 0
// var previousErrorRate:Float = 1
// var Xweights = [Float]()
var linearVotes = [Float]()
var minError:Float = 1
let convolution = ConvolutionLayer()
let reLU = RectifiedLinearUnitLayer()
let pooling = PoolingLayer()
let fullyConectedLayer = FullyConectedLayer()
func train(with trainingData: [(Matrix<Float>, [Float])]) {
var previouslyChangedThatWeight = false
for _ in 0...10 { //M
var isReducingGlobalErrorRate = true
var tunedWeightIndex = 0
var windex = 0
var bestWeight:Float = -1
while isReducingGlobalErrorRate {
var errors:Float = 0
for sample in trainingData {
let matrix = sample.0
let minusMatrix = replace(value: 0, by: -1, in: matrix)
let correctPrediction = sample.1
let prediction = predict(minusMatrix)
let numberOfPredictions:Float = 2
// print(correctPrediction)
// print("🤔 prediction : \(prediction)")
let errorRate = (abs(correctPrediction[0]-prediction[0])
+ abs(correctPrediction[1]-prediction[1]))
/ numberOfPredictions
// print(errorRate)
// print("🤔 ERRROR : \(errorRate)")
errors += errorRate
}
let globalErrorRate = errors / Float(trainingData.count)
print(" 🚨 Global Error :\(globalErrorRate)")
print("previousErrorRate :\(previousGlobalErrorRate)")
print("Tryin with weight[0] : ------- \(fullyConectedLayer.weights[0])")
// print("weights[1] = :\(fullyConectedLayer.weights[1])")
if globalErrorRate == 0 {
break
}
if globalErrorRate < 0.2 {
break
}
minError = min(previousGlobalErrorRate,minError)
if previousGlobalErrorRate > minError {
print("wtf")
}
let isReducingError = globalErrorRate < previousGlobalErrorRate
let reachedEndOfWeight = fullyConectedLayer.weights[windex][tunedWeightIndex] == 1
print("isReducingError : ------- \(isReducingError)")
if isReducingError {
previousGlobalErrorRate = globalErrorRate
bestWeight = fullyConectedLayer.weights[windex][tunedWeightIndex]
}
// if isReducingError && !reachedEndOfWeight {
// fullyConectedLayer.weights[windex][tunedWeightIndex] += Params.learningRate
// }
if reachedEndOfWeight {
// Keep best weight
fullyConectedLayer.weights[windex][tunedWeightIndex] = bestWeight
// GO TRY ADJUST NEXT PARAM
tunedWeightIndex += 1
fullyConectedLayer.weights[windex][tunedWeightIndex] += Params.learningRate
bestWeight = -1
} else {
// keep going
fullyConectedLayer.weights[windex][tunedWeightIndex] += Params.learningRate
}
if fullyConectedLayer.weights[windex][tunedWeightIndex] > 1 {
print("wtf")
}
if tunedWeightIndex == 3 && windex == 0 {
// isReducingGlobalErrorRate = false //Break
windex = 1
tunedWeightIndex = 0
// previousGlobalErrorRate = globalErrorRate
}
//
if tunedWeightIndex == 3 && windex == 1 {
isReducingGlobalErrorRate = false
}
}
}
print("Trained")
print("Found Weights")
print("weight[0] : ------- \(fullyConectedLayer.weights[0])")
print("weight[1] : ------- \(fullyConectedLayer.weights[1])")
}
func predict(_ matrix: Matrix<Float>) -> [Float] {
let feature1: Matrix<Float> = [
[1,-1],
[-1,1],
]
let c1 = convolution.runOn(matrix: matrix, withFeature: feature1)
// print("Convolution")
// print(c1)
// ReLU
let r1 = reLU.runOn(matrix: c1)
// print("RelU")
// print(r1)
// Pooling
var p1 = pooling.runOn(matrix: r1)
p1 = replace(value: 0, by: -1, in: p1)
// print("Pooling")
// print(p1)
let prediction = fullyConectedLayer.runOn(matrices: [p1])
//
// print("Prediction")
// print(prediction)
//
return prediction
}
}
// TODO pick random filters 1 per pass and see wchich ones are the best at clasifying Xs and Os
class FullyConectedLayer {
var linearVotes = [Float]()
var predictions = [Float]()
var weights: [[Float]] = [[Float](), [Float]()]
var weightedVotes: [[Float]] = [[Float](), [Float]()]
func runOn(matrices: [Matrix<Float>]) -> [Float] {
linearVotes = [Float]()
for m in matrices {
for i in 0..<m.backing.count {
for j in 0..<m.backing.count {
linearVotes.append(m[i,j])
}
}
}
// print("linearVotes")
// print(linearVotes)
// Initialize with defaut weights of 1
for i in 0..<2 {
if weights[i].isEmpty {
for _ in linearVotes {
weights[i].append(-1)
}
}
}
// print("weights")
// print(weights)
// Clean weightedVotes
weightedVotes = [[Float](), [Float]()]
// Weighted Votes
for k in 0..<2 {
for (i,v) in linearVotes.enumerated() {
let weight = weights[k][i]
weightedVotes[k].append(v*weight)
}
}
//
// print("weightedVotes")
// print(weightedVotes)
//
var predictions = [Float]()
for i in 0..<2 {
var addition:Float = 0
for v in weightedVotes[i] {
addition += v
}
let result = addition / Float(weightedVotes[i].count)
predictions.append(result)
}
return predictions
}
}
| 4969cbd268b6a80f2455393fd9bd7e13 | 27.029412 | 95 | 0.480588 | false | false | false | false |
mseemann/D2Layers | refs/heads/master | Example/Tests/OrdinalScaleTest.swift | mit | 1 | //
// OrdinalScaleTest.swift
// D2Layers
//
// Created by Michael Seemann on 24.11.15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import Quick
import Nimble
@testable import D2Layers
class OrdinalScaleSpec: QuickSpec {
override func spec() {
describe("domain"){
it("should default to an empty array"){
let scale = OrdinalScale<Int, String>()
expect(scale.domain().count) == 0
}
it("should forget previous values if domain ist set"){
let x = OrdinalScale<Int, String>().range(["foo", "bar"])
expect(x.scale(1)) == "foo"
expect(x.scale(0)) == "bar"
expect(x.domain()) == [1, 0]
x.domain([0, 1])
expect(x.scale(0)) == "foo" // it changed!
expect(x.scale(1)) == "bar"
expect(x.domain()) == [0, 1]
}
it("should order domain values by the order in which they are seen") {
let x = OrdinalScale<String, String>()
x.scale("foo")
x.scale("bar")
x.scale("baz")
expect(x.domain()) == ["foo", "bar", "baz"]
x.domain(["baz", "bar"])
x.scale("foo")
expect(x.domain()) == ["baz", "bar", "foo"]
x.domain(["baz", "foo"])
expect(x.domain()) == ["baz", "foo"]
x.domain([])
x.scale("foo")
x.scale("bar")
expect(x.domain()) == ["foo", "bar"]
}
}
describe("range"){
it("should default to an empty array"){
let x = OrdinalScale<Int, String>()
expect(x.range().count) == 0
}
it("should apend new input values to the domain"){
let x = OrdinalScale<Int, String>().range(["foo", "bar"])
expect(x.scale(0)) == "foo"
expect(x.domain()) == [0]
expect(x.scale(1)) == "bar"
expect(x.domain()) == [0, 1]
expect(x.scale(0)) == "foo"
expect(x.domain()) == [0, 1]
}
it("should remember previous values if the range is set"){
let x = OrdinalScale<Int, String>()
expect(x.scale(0)).to(beNil())
expect(x.scale(1)).to(beNil())
x.range(["foo", "bar"])
expect(x.scale(0)) == "foo"
expect(x.scale(1)) == "bar"
}
it("should work like a circle structure"){
let x = OrdinalScale<Int, String>().range(["a", "b", "c"])
expect(x.scale(0)) == "a"
expect(x.scale(1)) == "b"
expect(x.scale(2)) == "c"
expect(x.scale(3)) == "a"
expect(x.scale(4)) == "b"
expect(x.scale(5)) == "c"
expect(x.scale(2)) == "c"
expect(x.scale(1)) == "b"
expect(x.scale(0)) == "a"
}
}
describe("rangePoints"){
it("computes discrete points in a continuous range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:0, stop:120)
expect(x.range()) == [0, 60, 120]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:0, stop:120, padding:1)
expect(x.range()) == [20, 60, 100]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:0, stop:120, padding:2)
expect(x.range()) == [30, 60, 90]
}
it("correctly handles empty domains") {
let x = try! OrdinalScale<String, Double>().domain([]).rangePoints(start:0, stop:120)
expect(x.range()) == []
expect(x.scale("b")).to(beNil())
expect(x.domain()) == []
}
it("correctly handles singleton domains") {
let x = try! OrdinalScale<String, Double>().domain(["a"]).rangePoints(start:0, stop:120)
expect(x.range()) == [60]
expect(x.scale("b")).to(beNil())
expect(x.domain()) == ["a"]
}
it("can be set to a descending range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:120, stop:0)
expect(x.range()) == [120, 60, 0]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:120, stop:0, padding:1)
expect(x.range()) == [100, 60, 20]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:120, stop:0, padding:2)
expect(x.range()) == [90, 60, 30]
}
it("has a rangeBand of zero") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:0, stop:120)
expect(x.rangeBand) == 0
}
it("returns undefined for values outside the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:0, stop:1)
expect(x.scale("d")).to(beNil())
expect(x.scale("e")).to(beNil())
expect(x.scale("f")).to(beNil())
}
it("does not implicitly add values to the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:0, stop:1)
x.scale("d")
x.scale("e")
expect(x.domain()) == ["a", "b", "c"]
}
it("supports realy double values") {
let o = try! OrdinalScale<Double, Double>().domain([1, 2, 3, 4]).rangePoints(start:0, stop:100)
expect(o.range()[1]) == 100/3
}
}
describe("rangeRoundPoints") {
it("computes discrete points in a continuous range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:120)
expect(x.range()) == [0, 60, 120]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:120, padding:1)
expect(x.range()) == [20, 60, 100]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:120, padding:2);
expect(x.range()) == [30, 60, 90]
}
it("rounds to the nearest equispaced integer values") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:119)
expect(x.range()) == [1, 60, 119]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:119, padding:1)
expect(x.range()) == [21, 60, 99]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:119, padding:2)
expect(x.range()) == [31, 60, 89]
}
it("correctly handles empty domains") {
let x = try! OrdinalScale<String, Double>().domain([]).rangeRoundPoints(start:0, stop:119)
expect(x.range()) == []
expect(x.scale("b")).to(beNil())
expect(x.domain()) == []
}
it("correctly handles singleton domains") {
let x = try! OrdinalScale<String, Double>().domain(["a"]).rangeRoundPoints(start:0, stop:119)
expect(x.range()) == [60]
expect(x.scale("b")).to(beNil())
expect(x.domain()) == ["a"]
}
it("can be set to a descending range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:119, stop:0)
expect(x.range()) == [119, 60, 1]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:119, stop:0, padding:1)
expect(x.range()) == [99, 60, 21]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:119, stop:0, padding:2)
expect(x.range()) == [89, 60, 31]
}
it("has a rangeBand of zero") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:119)
expect(x.rangeBand) == 0
}
it("returns nul for values outside the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:1)
expect(x.scale("d")).to(beNil())
expect(x.scale("e")).to(beNil())
expect(x.scale("f")).to(beNil())
}
it("does not implicitly add values to the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundPoints(start:0, stop:1)
x.scale("d")
x.scale("e")
expect(x.domain()) == ["a", "b", "c"]
}
}
describe("rangeBands") {
it("computes discrete bands in a continuous range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:0, stop:120)
expect(x.range()) == [0, 40, 80]
expect(x.rangeBand) == 40
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:0, stop:120, padding:0.2, outerPadding:0.2)
expect(x.range()) == [7.5, 45, 82.5]
expect(x.rangeBand) == 30
}
// FIXME currently not possible - maybe every range-funktion must be an object to recompute the ranges with the original values.
// it("setting domain recomputes range bands") {
// let x = try! OrdinalScale<String, Double>().rangeBands(start:0, stop:100).domain(["a", "b", "c"])
// expect(x.range()) == [1, 34, 67]
// expect(x.rangeBand) == 33
// x.domain(["a", "b", "c", "d"])
// expect(x.range()) == [0, 25, 50, 75]
// expect(x.rangeBand) == 25
// }
it("can be set to a descending range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:120, stop:0)
expect(x.range()) == [80, 40, 0]
expect(x.rangeBand) == 40
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:120, stop:0, padding:0.2, outerPadding:0.2)
expect(x.range()) == [82.5, 45, 7.5]
expect(x.rangeBand) == 30
}
it("can specify a different outer padding") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:120, stop:0, padding:0.2, outerPadding:0.1)
expect(x.range()) == [84, 44, 4]
expect(x.rangeBand) == 32
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:120, stop:0, padding:0.2, outerPadding:1)
expect(x.range()) == [75, 50, 25]
expect(x.rangeBand) == 20
}
it("returns undefined for values outside the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:0, stop:1)
expect(x.scale("d")).to(beNil())
expect(x.scale("e")).to(beNil())
expect(x.scale("f")).to(beNil())
}
it("does not implicitly add values to the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:0, stop:1)
x.scale("d")
x.scale("e")
expect(x.domain()) == ["a", "b", "c"]
}
}
describe("rangeRoundBands"){
it("computes discrete rounded bands in a continuous range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:0, stop:100)
expect(x.range()) == [1, 34, 67]
expect(x.rangeBand) == 33
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:0, stop:100, padding:0.2, outerPadding:0.2)
expect(x.range()) == [7, 38, 69]
expect(x.rangeBand) == 25
}
it("can be set to a descending range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:100, stop:0)
expect(x.range()) == [67, 34, 1]
expect(x.rangeBand) == 33
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:100, stop:0, padding:0.2, outerPadding:0.2)
expect(x.range()) == [69, 38, 7]
expect(x.rangeBand) == 25
}
it("can specify a different outer padding") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:120, stop:0, padding:0.2, outerPadding:0.1)
expect(x.range()) == [84, 44, 4]
expect(x.rangeBand) == 32
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:120, stop:0, padding:0.2, outerPadding:1)
expect(x.range()) == [75, 50, 25]
expect(x.rangeBand) == 20
}
it("returns undefined for values outside the domain"){
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:0, stop:1)
expect(x.scale("d")).to(beNil())
expect(x.scale("e")).to(beNil())
expect(x.scale("f")).to(beNil())
}
it("does not implicitly add values to the domain") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:0, stop:1)
x.scale("d")
x.scale("e")
expect(x.domain()) == ["a", "b", "c"]
}
}
describe("rangeExtent") {
it("returns the continuous range") {
var x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangePoints(start:20, stop:120)
expect(x.rangeExtent) == [20, 120]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:10, stop:110)
expect(x.rangeExtent) == [10, 110]
x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeRoundBands(start:0, stop:100)
expect(x.rangeExtent) == [0, 100]
x = OrdinalScale<String, Double>().domain(["a", "b", "c"]).range([0, 20, 100])
expect(x.rangeExtent) == [0, 100]
}
it("can handle descending ranges") {
let x = try! OrdinalScale<String, Double>().domain(["a", "b", "c"]).rangeBands(start:100, stop:0)
expect(x.rangeExtent) == [0, 100]
}
}
}
}
| 4601a5785a4dd0947b75307eb751be93 | 44.997183 | 149 | 0.450426 | false | false | false | false |
CodaFi/swift-compiler-crashes | refs/heads/master | crashes-duplicates/08813-llvm-errs.swift | mit | 11 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
typealias F = 1
struct c<T where g.d: String {
var d {
struct d<T : String {
var d {
func c>() {
let c = f.c = F>() {
enum S<T : e
typealias F = c(x: A.b(x: I.d<T : String {
func b
class C<d {
st
func b: String {
let c = F>: I.d: I.b<T where g.e = F>
class A {}
let c = F>
enum S<T : I.e where I.e = 1
var d : e
class A {
import CoreData
func c
<d {
for b in c
}
class A {
}
func c<T where H.e where I.b<T where I.d<c
class func c(x: String {
class C<T where g: e, g.e where I.b> {
class A {
struct S<c<T where H.h == 1
typealias F = 1
func c
st
class A {
}
enum S<T where S<f : Range<d : e
func b<d {
struct S.h == f.c {
func b
struct c<T where I.h> U) {
class func c<T where I.d: e
func b<T : e = f.h == f: T>
struct S.d: Any) -> Self
struct c
func c<T : e
enum S<d : NSObject {
<T where S<d {}
struct S<T : I.e = c>(")
struct d.h> {
import CoreData
class A {
class func b([Void{
protocol B : I.e where g: e, g: String {
typealias F = c<T : String {
protocol B : NSObject {
protocol B : T>: C {
struct d: A.d.b: a {}
struct S<T where S<d {
if true {
func b> U) {
class A {
let c = f: e, g.e where I.b> {
struct S.d.e = 1
struct c<T where S<T where H.h : Any) {
typealias f = f.h> {
enum S<T where I.e = c>: NSObject {
}
var d {
typealias F = b
class A {
typealias f : e
class A {
var f = b: a {
}
var d {
for b in c<d {
st
st
}
typealias F = 0
func c(([Void{
func c>
import CoreData
class func b() {
enum S.h == c<T where g: e where g: I.h> U) {
protocol B : NSObject {
(([Void{
let c {
protocol B : e where I.d: A.d<T where I.c = b> U) {
class C<T where S<d {
func b<d : I.d.h> U) {
if true {
enum S<d {
func c>: T>(")
protocol B : C {
func c>([Void{}
struct c
typealias f = F>() -> U) {
class func c<T : T>: NSObject {
func c<T where I.d.h == f.e = c() -> Self
var f = F>
for b in c<T where S<T where S<T where I.e where I.e = 1
func b
struct S<T where I.e where g: Any) -> Self
(((x: e, g.d.e = f.b(x: String {
func b([Void{
<f : e, g.h == c<T where g.e = 1
enum S.h == f.d<d {}
import CoreData
let c = e
class C<f = e
enum S<T where H.h == f: e
let c {
var f : String {
if true {
(() -> Self
}
typealias f : I.d: f.e where g.e = f: NSObject
| 5a5dda30d0e962d1a3a972c2c4b822e2 | 17.829268 | 87 | 0.592832 | false | false | false | false |
marcelvoss/MVFollow | refs/heads/master | MVFollow/Follow.swift | mit | 1 | //
// Follow.swift
// Example
//
// Created by Marcel Voß on 09/12/2016.
// Copyright © 2016 Marcel Voß. All rights reserved.
//
import UIKit
import Accounts
import Social
class Follow: NSObject {
var availableAccounts: [ACAccount]?
/// Generates a UIAlertController with action sheet style, including actions for every Twitter account that was found in the ACAccountStore. The actions are configured as well and will follow the specified user with an account selected by the user.
///
/// - Parameters:
/// - accounts: The account array that shall be used to generate the action sheet.
/// - username: The username that shall be followed.
/// - Returns: A UIAlertController with action sheet style.
func actionSheet(accounts: [ACAccount]?, username: String) -> UIAlertController? {
if let accountArray = accounts {
let actionSheet = UIAlertController(title: nil, message: "Choose account for following @\(username)", preferredStyle: .actionSheet)
for account in accountArray {
actionSheet.addAction(UIAlertAction(title: account.username, style: .default, handler: { (action) in
self.follow(username: username, account: account, completionHandler: { (success, error) in
actionSheet.dismiss(animated: true, completion: {
if error != nil {
let alertController = UIAlertController(title: "Error", message: "Couldn't follow @\(username). \(error!.localizedDescription).", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
}
})
})
}))
}
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
return actionSheet
}
return nil
}
/// Retrieves an array of ACAccounts with the ACAccountTypeIdentifierTwitter.
///
/// - Parameter completionHandler: A closure with an array of ACAccounts, a boolean determining wether the retrival was succesful and an error instance containing a more described error description.
func accounts(completionHandler:@escaping ([ACAccount]?, Bool, Error?) -> Void) {
let accountStore = ACAccountStore()
let accountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccounts(with: accountType, options: nil) {(granted: Bool, error: Error?) -> Void in
if granted {
let accounts = accountStore.accounts(with: accountType) as? [ACAccount]
self.availableAccounts = accounts
completionHandler(accounts, true, error)
}
completionHandler(nil, false, error)
}
}
/// Follows the user with the specified username with the specified account.
///
/// - Parameters:
/// - username: The user to follow.
/// - account: The account that shall follow.
/// - completionHandler: A closure containing a boolean for determining wether following was successful and an error instance containing a more described error description.
func follow(username: String, account: ACAccount, completionHandler:@escaping (Bool, Error?) -> Void) {
let requestParameters = ["follow": "true", "screen_name": username]
performFollowRequest(account: account, parameters: requestParameters, completionHandler: { (error) in
if error == nil {
completionHandler(false, error)
} else {
completionHandler(true, error)
}
})
}
/// Opens the profile of the specified user in an installed Twitter client or in Safari.
///
/// - Parameter username: The user's Twitter handle.
/// - Returns: A boolean determining wether it was possible to open the Twitter profile.
func showProfile(username: String) -> Bool {
if canOpenApplication(identifier: "twitter://") {
// Twitter.app
return openApplication(string: "twitter://user?screen_name=\(username)")
} else if canOpenApplication(identifier: "tweetbot://") {
// Tweetbot
return openApplication(string: "tweetbot:///user_profile/\(username)")
} else if canOpenApplication(identifier: "twitterrific://") {
// Twitterrific
return openApplication(string: "twitterrific:///profile?screen_name=\(username)")
} else {
// Web
return openApplication(string: "http://twitter.com/\(username)")
}
}
// MARK: - Private
private func openApplication(string: String) -> Bool {
var successful = false
if let url = URL(string: string) {
UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
successful = success
})
}
return successful
}
private func canOpenApplication(identifier: String) -> Bool {
if let url = URL(string: identifier) {
return UIApplication.shared.canOpenURL(url)
}
return false
}
private func performFollowRequest(account: ACAccount?, parameters: [String:String], completionHandler:@escaping (Error?) -> Void) {
let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .POST,
url: URL(string: "https://api.twitter.com/1.1/friendships/create.json"), parameters: parameters)
request?.account = account
request?.perform(handler: { (data, response, error) in
let statusCode = response?.statusCode
if error == nil && (statusCode == 200 || statusCode == 201) {
completionHandler(nil)
} else {
completionHandler(error)
}
})
}
}
| ea288a1a5cf3c4cce165623b2447f8b2 | 44.543478 | 252 | 0.611138 | false | false | false | false |
MTR2D2/TIY-Assignments | refs/heads/master | ToDo/ToDo/TodoTableViewController.swift | cc0-1.0 | 1 | //
// TodoTableViewController.swift
// ToDo
//
// Created by Michael Reynolds on 10/20/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
class TodoTableViewController: UITableViewController, UITextFieldDelegate
{
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var itemDescription = Array<ToDoCore>()
override func viewDidLoad()
{
super.viewDidLoad()
title = "Task List"
let fetchRequest = NSFetchRequest(entityName: "ToDoCore")
do
{
let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as? [ToDoCore]
itemDescription = fetchResults!
}
catch
{
let nserror = error as NSError
NSLog("Unresoved error \(nserror), \(nserror.userInfo)")
abort()
}
// 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()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// #warning Incomplete implementation, return the number of rows
return itemDescription.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ToDoList", forIndexPath: indexPath) as! ToDoCell
// Configure the cell...
let aTask = itemDescription[indexPath.row]
if aTask.something == nil
{
cell.toDoText.becomeFirstResponder()
}
else
{
cell.toDoText.text = aTask.something
}
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
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
let aTask = itemDescription[indexPath.row]
itemDescription.removeAtIndex(indexPath.row)
managedObjectContext.deleteObject(aTask)
saveContext()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: TextField Delegate
func textFieldShouldReturn(toDoText: UITextField) -> Bool
{
var rc = false //rc stands for return code
if toDoText.text != ""
{
rc = true
let contentView = toDoText.superview
let cell = contentView?.superview as! ToDoCell
let indexPath = tableView.indexPathForCell(cell)
// tableView, here is the cell, give me the indexPath
let aTask = itemDescription[indexPath!.row]
aTask.something = toDoText.text
toDoText.resignFirstResponder()
saveContext()
}
return rc
}
// MARK: Action Handlers
@IBAction func newTask(sender: UIBarButtonItem)
{
let aTask = NSEntityDescription.insertNewObjectForEntityForName("ToDoCore", inManagedObjectContext: managedObjectContext) as! ToDoCore
itemDescription.append(aTask)
tableView.reloadData()
// saveContext()
}
@IBAction func doneButton(sender: UIButton)
{
let contentView = sender.superview
let cell = contentView?.superview as! ToDoCell
let indexPath = tableView.indexPathForCell(cell)
// tableView, here is the cell, give me the indexPath
let aTask = itemDescription[indexPath!.row]
if sender.currentTitle == "☑"
{
cell.backgroundColor = UIColor.whiteColor()
sender.setTitle("☐", forState: UIControlState.Normal)
aTask.done = false
}
else
{
cell.backgroundColor = UIColor.greenColor()
sender.setTitle("☑", forState: UIControlState.Normal)
aTask.done = true
}
}
//MARK: - Private
func saveContext()
{
do
{
try managedObjectContext.save()
}
catch
{
let nserror = error as NSError
NSLog("Unresoved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
| 3ce4112471dfcfe811a0bf2960733326 | 30.050251 | 155 | 0.630685 | false | false | false | false |
huangboju/Eyepetizer | refs/heads/master | Eyepetizer/Eyepetizer/Controllers/MenuViewController.swift | mit | 1 | //
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
class MenuViewController: UIViewController, GuillotineMenu {
let titles = ["我的缓存", "功能开关", "我要投稿", "更多应用"]
private let menuViewCellId = "menuViewCellId"
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = UIColor.clearColor()
tableView.tableHeaderView = MenuHeaderView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 200))
tableView.sectionHeaderHeight = 200
tableView.rowHeight = 70
tableView.separatorStyle = .None
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
lazy var dismissButton: UIButton! = {
let dismissButton = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 40))
dismissButton.setImage(R.image.ic_action_menu(), forState: .Normal)
dismissButton.addTarget(self, action: #selector(dismissButtonTapped), forControlEvents: .TouchUpInside)
return dismissButton
}()
lazy var titleLabel: UILabel! = {
var titleLabel = UILabel()
titleLabel.numberOfLines = 1
titleLabel.text = "petizer"
titleLabel.textColor = UIColor.blackColor()
titleLabel.sizeToFit()
return titleLabel
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clearColor()
let blurEffect = UIBlurEffect(style: .Light)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = view.bounds
view.addSubview(blurView)
view.addSubview(tableView)
tableView.snp_makeConstraints { make in
make.left.right.bottom.equalTo(view)
make.top.equalTo(view).offset(TOP_BAR_HEIGHT)
}
}
func dismissButtonTapped(sende: UIButton) {
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension MenuViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(menuViewCellId)
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: menuViewCellId)
}
cell?.backgroundColor = UIColor.clearColor()
cell?.contentView.backgroundColor = UIColor.clearColor()
cell?.selectionStyle = .None
cell?.textLabel?.textAlignment = .Center
cell?.textLabel?.text = titles[indexPath.row]
return cell!
}
}
| 2dc56a434fe3d4c40c51122e46db90a4 | 35.814815 | 120 | 0.664319 | false | false | false | false |
fitpay/fitpay-ios-sdk | refs/heads/develop | FitpaySDK/PaymentDevice/SyncQueue/SyncRequest.swift | mit | 1 | import Foundation
public typealias SyncRequestCompletion = (EventStatus, Error?) -> Void
open class SyncRequest {
static var syncManager: SyncManagerProtocol = SyncManager.sharedInstance
public let requestTime: Date
public let syncId: String?
public private(set) var syncStartTime: Date?
public var syncInitiator: SyncInitiator?
public var notification: NotificationDetail? {
didSet {
FitpayNotificationsManager.sharedInstance.updateRestClientForNotificationDetail(self.notification)
}
}
var isEmptyRequest: Bool {
return user == nil || deviceInfo == nil || paymentDevice == nil
}
var user: User?
var deviceInfo: Device?
var paymentDevice: PaymentDevice?
var completion: SyncRequestCompletion?
private var state = SyncRequestState.pending
// MARK: - Lifecycle
/// Creates sync request.
///
/// - Parameters:
/// - requestTime: time as Date object when request was made. Used for filtering unnecessary syncs. Defaults to Date().
/// - syncId: sync identifier used for not running duplicates
/// - user: User object.
/// - deviceInfo: DeviceInfo object.
/// - paymentDevice: PaymentDevice object.
/// - initiator: syncInitiator Enum object. Defaults to .NotDefined.
/// - notificationAsc: NotificationDetail object.
public init(requestTime: Date = Date(), syncId: String? = nil, user: User, deviceInfo: Device, paymentDevice: PaymentDevice, initiator: SyncInitiator = .notDefined, notification: NotificationDetail? = nil) {
self.requestTime = requestTime
self.syncId = syncId
self.user = user
self.deviceInfo = deviceInfo
self.paymentDevice = paymentDevice
self.syncInitiator = initiator
self.notification = notification
}
/// Create sync request from Notificatoin
///
/// This can be created with no parameters but will never sync as a deviceId is required moving forward
///
/// - Parameters:
/// - notification: Notification Detail created from a FitPay notification
/// - initiator: where the sync is coming from, defaulting to notification
/// - user: The user associated with the notification, defaulting to nil
public init(notification: NotificationDetail? = nil, initiator: SyncInitiator = .notification, user: User? = nil) {
self.requestTime = Date()
self.syncId = notification?.syncId
self.user = user
let deviceInfo = Device()
deviceInfo.deviceIdentifier = notification?.deviceId
self.deviceInfo = deviceInfo
self.paymentDevice = nil
self.syncInitiator = initiator
self.notification = notification
if !SyncRequest.syncManager.synchronousModeOn && isEmptyRequest {
assert(false, "You should pass all params to SyncRequest in parallel sync mode.")
}
}
// MARK: - Internal Functions
func update(state: SyncRequestState) {
if state == .inProgress && syncStartTime == nil {
syncStartTime = Date()
}
self.state = state
}
func syncCompleteWith(status: EventStatus, error: Error?) {
completion?(status, error)
}
func isSameUserAndDevice(otherRequest: SyncRequest) -> Bool {
return user?.id == otherRequest.user?.id && deviceInfo?.deviceIdentifier == otherRequest.deviceInfo?.deviceIdentifier
}
}
| d1669d08c459236dc03f7914e1b089ce | 35.75 | 211 | 0.65788 | false | false | false | false |
Asura19/SwiftAlgorithm | refs/heads/master | SwiftAlgorithm/SwiftAlgorithm/LC054.swift | mit | 1 | //
// LC054.swift
// SwiftAlgorithm
//
// Created by phoenix on 2022/2/23.
// Copyright © 2022 Phoenix. All rights reserved.
//
import Foundation
struct MatrixSpiralIterator {
typealias Index = (row: Int, col: Int, idx: Int)
let rowCount: Int
let colCount: Int
private var top: Int
private var left: Int
private var bottom: Int
private var right: Int
private let total: Int
init(rowCount: Int, colCount: Int) {
assert(rowCount >= 1 && colCount >= 1)
self.rowCount = rowCount
self.colCount = colCount
self.top = 0
self.left = 0
self.bottom = rowCount - 1
self.right = colCount - 1
total = rowCount * colCount
}
var current: Index?
mutating func next() -> Index? {
guard var c = current else {
current = (0, 0, 0)
return self.current
}
if c.idx == total - 1 {
return nil
}
if rowCount == 1 {
current = c.col < right ? (0, c.col + 1, c.idx + 1) : nil
return current
}
if colCount == 1 {
current = c.row < bottom ? (c.row + 1, 0, c.idx + 1) : nil
return current
}
if c.row == top && c.col < right {
c.col += 1
}
else if c.col == right && c.row < bottom {
c.row += 1
}
else if c.row == bottom && c.col > left {
c.col -= 1
}
else if c.col == left && c.row > top {
c.row -= 1
}
if c.row == top, c.col == left {
top += 1
left += 1
bottom -= 1
right -= 1
c.row = top
c.col = left
}
c.idx += 1
current = c
return current
}
}
extension LeetCode {
static func printMatrixBySpiral<T>(_ matrix: [[T]]) {
guard isMatrix(matrix) else {
assert(false, "not a matrix")
return
}
let rowCount = matrix.count
let colCount = matrix[0].count
var iterator = MatrixSpiralIterator(rowCount: rowCount, colCount: colCount)
while let index = iterator.next() {
print("\(index.idx): \(matrix[index.row][index.col])")
}
}
private static func isMatrix<T>(_ matrix: [[T]]) -> Bool {
if matrix.count == 0 { return false }
let colCount = matrix[0].count
return matrix.filter { $0.count != colCount }.count == 0
}
}
| 96df5a80bcd1d4409f42aeec6fc2c7ae | 23.257143 | 83 | 0.485669 | false | false | false | false |
Bruno-Furtado/holt_winters | refs/heads/master | HoltWinters/main.swift | mit | 1 | //
// main.swift
// HoltWinters
//
// Created by Bruno Tortato Furtado on 03/05/16.
// Copyright © 2016 Bruno Tortato Furtado. All rights reserved.
//
import Foundation
let dataFileName = "input.txt"
let forecastingFileName = "forecasting.csv"
let errorsFileName = "errors.csv"
let s: Int = 3
let alpha: Float = 0.3
let beta: Float = 0.3
let gamma: Float = 0.3
print("Processing has been started.")
print("Waiting...")
let controller = Controller(dataFileName: dataFileName, s: s, alpha: alpha, beta: beta, gamma: gamma)
controller.saveResultAtFiles(forecastingFileName, errorsFileName: errorsFileName, forecastingCompletion:
{ (forecastingSaved) in
if (forecastingSaved) {
print("Forecasting has been saved successfully.")
} else {
print("Forecasting has not been saved.")
}
}) { (errorsSaved) in
if (errorsSaved) {
print("Erros has been saved successfully.")
} else {
print("Erros has not been saved.")
}
}
print("") | 75b84463f876d5b7bdf5d2631dd5bf82 | 23.65 | 104 | 0.686294 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/UIScrollViewDemo/UIScrollViewDemo/AutoLayout/AutoLayoutCookbook/AspectRatioImageView.swift | mit | 1 | //
// ImageViewsAndAspectFitMode.swift
// UIScrollViewDemo
//
// Created by 黄伯驹 on 2017/10/24.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
class AspectRatioImageView: AutoLayoutBaseController {
override func initSubviews() {
let topContentView = generatContentView()
view.addSubview(topContentView)
let imageView = UIImageView(image: UIImage(named: "flowers"))
imageView.setContentHuggingPriority(UILayoutPriority(rawValue: 251), for: .vertical)
imageView.setContentHuggingPriority(UILayoutPriority(rawValue: 251), for: .horizontal)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.backgroundColor = UIColor(white: 0.8, alpha: 1)
view.addSubview(imageView)
let bottomContentView = generatContentView()
view.addSubview(bottomContentView)
let leadingContentView = generatContentView()
view.addSubview(leadingContentView)
let trailingContentView = generatContentView()
view.addSubview(trailingContentView)
do {
if #available(iOS 11, *) {
topContentView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
} else {
topContentView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 20).isActive = true
}
topContentView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true
topContentView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true
topContentView.heightAnchor.constraint(equalTo: bottomContentView.heightAnchor).isActive = true
}
do {
leadingContentView.topAnchor.constraint(equalTo: topContentView.bottomAnchor, constant: 8).isActive = true
leadingContentView.leadingAnchor.constraint(equalTo: topContentView.leadingAnchor).isActive = true
leadingContentView.bottomAnchor.constraint(equalTo: imageView.bottomAnchor).isActive = true
}
do {
imageView.topAnchor.constraint(equalTo: topContentView.bottomAnchor, constant: 8).isActive = true
imageView.heightAnchor.constraint(equalTo: bottomContentView.heightAnchor, multiplier: 2).isActive = true
imageView.leadingAnchor.constraint(equalTo: leadingContentView.trailingAnchor, constant: 8).isActive = true
}
do {
trailingContentView.trailingAnchor.constraint(equalTo: topContentView.trailingAnchor).isActive = true
trailingContentView.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 8).isActive = true
trailingContentView.widthAnchor.constraint(equalTo: leadingContentView.widthAnchor).isActive = true
trailingContentView.heightAnchor.constraint(equalTo: leadingContentView.heightAnchor).isActive = true
trailingContentView.topAnchor.constraint(equalTo: leadingContentView.topAnchor).isActive = true
}
do {
bottomContentView.trailingAnchor.constraint(equalTo: topContentView.trailingAnchor).isActive = true
bottomContentView.leadingAnchor.constraint(equalTo: topContentView.leadingAnchor).isActive = true
bottomContentView.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 8).isActive = true
if #available(iOS 11, *) {
view.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: bottomContentView.bottomAnchor, constant: 20).isActive = true
} else {
bottomLayoutGuide.topAnchor.constraint(equalTo: bottomContentView.bottomAnchor, constant: 20).isActive = true
}
}
}
private func generatContentView() -> UIView {
let contentView = UIView()
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.backgroundColor = .lightGray
return contentView
}
}
| b6d3ff690a33b4215e94bb9f746358ab | 48.47561 | 135 | 0.702243 | false | false | false | false |
FoodForTech/Handy-Man | refs/heads/1.0.0 | HandyMan/HandyMan/Features/Login/Views/LoginAnimateView.swift | mit | 1 | //
// LoginAnimateView.swift
// HandyMan
//
// Created by Don Johnson on 5/3/16.
// Copyright © 2016 Don Johnson. All rights reserved.
//
import UIKit
final class LoginAnimateView: DesignableView {
override func draw(_ rect: CGRect) {
if let color = backgroundColor {
color.setFill()
}
UIRectFill(rect)
let layer = CAShapeLayer()
let path = CGMutablePath()
_ = CGMutablePath.addEllipse(path)
_ = CGMutablePath.addRect(path)
layer.path = path
layer.fillRule = kCAFillRuleEvenOdd
self.layer.mask = layer
}
}
| aa722fd9285fbbcb6c5042f00b3a9214 | 20.633333 | 54 | 0.577812 | false | false | false | false |
visenze/visearch-sdk-swift | refs/heads/master | ViSearchSDK/Carthage/Checkouts/visenze-tracking-swift/ViSenzeAnalytics/ViSenzeAnalytics/Classes/Helper/SettingHelper.swift | mit | 1 | //
// SettingHelper.swift
// ViSenzeAnalytics
//
// Created by Hung on 8/9/20.
// Copyright © 2020 ViSenze. All rights reserved.
//
import UIKit
open class SettingHelper: NSObject {
public static func setBoolSettingProp(propName: String , newValue: Bool) -> Void {
let userDefault = UserDefaults.standard
userDefault.set(newValue, forKey: propName)
}
public static func getBoolSettingProp (propName: String) -> Bool? {
let userDefault = UserDefaults.standard
return userDefault.bool(forKey: propName)
}
public static func getInt64Prop(propName: String) -> Int64 {
if let storeString = getStringSettingProp(propName: propName) {
if let num = Int64(storeString) {
return num
}
}
return 0;
}
public static func setInt64Prop(propName: String, newValue: Int64) {
return setSettingProp(propName: propName, newValue: String(newValue))
}
/// Set a property , store in userDefault
///
/// - parameter propName: property name
/// - parameter newValue: new value for property
public static func setSettingProp(propName: String , newValue: Any?) -> Void {
let userDefault = UserDefaults.standard
userDefault.set(newValue, forKey: propName)
}
/// retrieve setting in userdefault as String
///
/// - parameter propName: name of property
///
/// - returns: value as String?
public static func getStringSettingProp (propName: String) -> String? {
let userDefault = UserDefaults.standard
return userDefault.string(forKey: propName)
}
}
| 0c3c34d8b748c2a59b788d3752c018a4 | 29.053571 | 86 | 0.639335 | false | false | false | false |
RaviDesai/RSDRestServices | refs/heads/master | Pod/Classes/ModelResourceProtocol.swift | mit | 1 | //
// ModelResourceProtocol.swift
// Pods
//
// Created by Ravi Desai on 1/8/16.
//
//
import Foundation
import RSDSerialization
public enum ModelResourceVersionRepresentation {
case URLVersioning
case CustomRequestHeader
case CustomContentType
}
public protocol ModelResource : ModelItem {
typealias T : ModelItem = Self
static var resourceApiEndpoint: String { get }
static var resourceName: String { get }
static var resourceVersion: String { get }
static var resourceVersionRepresentedBy: ModelResourceVersionRepresentation { get }
static var resourceVendor: String { get }
static func getAll(session: APISession, completionHandler: ([T]?, NSError?) -> ())
static func get(session: APISession, resourceId: NSUUID, completionHandler: (T?, NSError?) -> ())
func save(session: APISession, completionHandler: (T?, NSError?) -> ())
func create(session: APISession, completionHandler: (T?, NSError?) -> ())
func delete(session: APISession, completionHandler: (NSError?) -> ())
}
private let invalidId = NSError(domain: "com.github.RaviDesai", code: 48118002, userInfo: [NSLocalizedDescriptionKey: "Invalid ID", NSLocalizedFailureReasonErrorKey: "Invalid ID"])
public extension ModelResource {
static var customResourceHeaderWithVendorAndVersion: String {
get {
return "\(resourceVendor).v\(resourceVersion)"
}
}
static var versionedResourceEndpoint: String {
get {
if resourceVersionRepresentedBy == ModelResourceVersionRepresentation.URLVersioning {
return "\(Self.resourceApiEndpoint)/v\(Self.resourceVersion)/\(Self.resourceName)"
}
return "\(Self.resourceApiEndpoint)/\(Self.resourceName)"
}
}
static var additionalHeadersForRequest: [String: String]? {
get {
if resourceVersionRepresentedBy == ModelResourceVersionRepresentation.CustomRequestHeader {
return ["api-version": resourceVersion]
}
return nil
}
}
static func getAll(session: APISession, completionHandler: ([T]?, NSError?)->()) {
let endpoint = APIEndpoint.GET(URLAndParameters(url: Self.versionedResourceEndpoint))
let parser = APIJSONSerializableResponseParser<T>(versionRepresentation: Self.resourceVersionRepresentedBy, vendor: Self.resourceVendor, version: Self.resourceVersion)
let request = APIRequest(baseURL: session.baseURL, endpoint: endpoint, bodyEncoder: nil, responseParser: parser, additionalHeaders: Self.additionalHeadersForRequest)
let call = APICall(session: session, request: request)
call.executeRespondWithArray(completionHandler)
}
static func get(session: APISession, resourceId: NSUUID, completionHandler: (T?, NSError?) -> ()) {
let uuid = resourceId.UUIDString
let endpoint = APIEndpoint.GET(URLAndParameters(url: "\(Self.versionedResourceEndpoint)/\(uuid)"))
let parser = APIJSONSerializableResponseParser<T>(versionRepresentation: Self.resourceVersionRepresentedBy, vendor: Self.resourceVendor, version: Self.resourceVersion)
let request = APIRequest(baseURL: session.baseURL, endpoint: endpoint, bodyEncoder: nil, responseParser: parser, additionalHeaders: Self.additionalHeadersForRequest)
let call = APICall(session: session, request: request)
call.executeRespondWithObject(completionHandler)
}
func save(session: APISession, completionHandler: (T?, NSError?) -> ()) {
if let uuid = self.id?.UUIDString {
let endpoint = APIEndpoint.PUT(URLAndParameters(url: "\(Self.versionedResourceEndpoint)/\(uuid)"))
let parser = APIJSONSerializableResponseParser<T>(versionRepresentation: Self.resourceVersionRepresentedBy, vendor: Self.resourceVendor, version: Self.resourceVersion)
let encoder = APIJSONBodyEncoder(model: self)
let request = APIRequest(baseURL: session.baseURL, endpoint: endpoint, bodyEncoder: encoder, responseParser: parser, additionalHeaders: Self.additionalHeadersForRequest)
let call = APICall(session: session, request: request)
call.executeRespondWithObject(completionHandler)
} else {
completionHandler(nil, invalidId)
}
}
func create(session: APISession, completionHandler: (T?, NSError?) -> ()) {
if self.id?.UUIDString == nil {
let endpoint = APIEndpoint.POST(URLAndParameters(url: Self.versionedResourceEndpoint))
let parser = APIJSONSerializableResponseParser<T>(versionRepresentation: Self.resourceVersionRepresentedBy, vendor: Self.resourceVendor, version: Self.resourceVersion)
let encoder = APIJSONBodyEncoder(model: self)
let request = APIRequest(baseURL: session.baseURL, endpoint: endpoint, bodyEncoder: encoder, responseParser: parser, additionalHeaders: Self.additionalHeadersForRequest)
let call = APICall(session: session, request: request)
call.executeRespondWithObject(completionHandler)
} else {
completionHandler(nil, invalidId)
}
}
func delete(session: APISession, completionHandler: (NSError?) -> ()) {
if let uuid = self.id?.UUIDString {
let endpoint = APIEndpoint.DELETE(URLAndParameters(url: "\(Self.versionedResourceEndpoint)/\(uuid)"))
let parser = APIJSONSerializableResponseParser<T>(versionRepresentation: Self.resourceVersionRepresentedBy, vendor: Self.resourceVendor, version: Self.resourceVersion)
let encoder = APIJSONBodyEncoder(model: self)
let request = APIRequest(baseURL: session.baseURL, endpoint: endpoint, bodyEncoder: encoder, responseParser: parser, additionalHeaders: Self.additionalHeadersForRequest)
let call = APICall(session: session, request: request)
call.execute(completionHandler)
} else {
completionHandler(invalidId)
}
}
} | ba758aae1aa47ac2de65edc605eb6293 | 51.025862 | 181 | 0.702188 | false | false | false | false |
Dougly/2For1 | refs/heads/master | 2for1/UIViewExtension.swift | mit | 1 | //
// ViewExtension.swift
// 2for1
//
// Created by Douglas Galante on 12/24/16.
// Copyright © 2016 Flatiron. All rights reserved.
//
import UIKit
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
func constrain(_ view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
view.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
view.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
view.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
view.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
}
class func applyGradient(to view: UIView, topColor: UIColor, bottomColor: UIColor) {
let gradient: CAGradientLayer = CAGradientLayer()
gradient.bounds = view.bounds
gradient.frame = view.bounds
gradient.colors = [topColor.cgColor , bottomColor.cgColor]
view.layer.insertSublayer(gradient, at: 0)
}
}
| a913efb3c2617ff9c30b1aeaea16345f | 27.186047 | 88 | 0.65099 | false | false | false | false |
frtlupsvn/Vietnam-To-Go | refs/heads/master | Pods/Former/Former/RowFormers/SliderRowFormer.swift | mit | 1 | //
// SliderRowFormer.swift
// Former-Demo
//
// Created by Ryo Aoyama on 7/31/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
public protocol SliderFormableRow: FormableRow {
func formSlider() -> UISlider
func formTitleLabel() -> UILabel?
func formDisplayLabel() -> UILabel?
}
public final class SliderRowFormer<T: UITableViewCell where T: SliderFormableRow>
: BaseRowFormer<T>, Formable {
// MARK: Public
public var value: Float = 0
public var titleDisabledColor: UIColor? = .lightGrayColor()
public var displayDisabledColor: UIColor? = .lightGrayColor()
public required init(instantiateType: Former.InstantiateType = .Class, cellSetup: (T -> Void)? = nil) {
super.init(instantiateType: instantiateType, cellSetup: cellSetup)
}
public override func initialized() {
super.initialized()
rowHeight = 88
}
public final func onValueChanged(handler: (Float -> Void)) -> Self {
onValueChanged = handler
return self
}
public final func displayTextFromValue(handler: (Float -> String)) -> Self {
displayTextFromValue = handler
return self
}
public final func adjustedValueFromValue(handler: (Float -> Float)) -> Self {
adjustedValueFromValue = handler
return self
}
public override func cellInitialized(cell: T) {
super.cellInitialized(cell)
cell.formSlider().addTarget(self, action: "valueChanged:", forControlEvents: .ValueChanged)
}
public override func update() {
super.update()
cell.selectionStyle = .None
let titleLabel = cell.formTitleLabel()
let displayLabel = cell.formDisplayLabel()
let slider = cell.formSlider()
slider.value = adjustedValueFromValue?(value) ?? value
slider.enabled = enabled
displayLabel?.text = displayTextFromValue?(value) ?? "\(value)"
if enabled {
_ = titleColor.map { titleLabel?.textColor = $0 }
_ = displayColor.map { displayLabel?.textColor = $0 }
titleColor = nil
displayColor = nil
} else {
if titleColor == nil { titleColor = titleLabel?.textColor ?? .blackColor() }
if displayColor == nil { displayColor = displayLabel?.textColor ?? .blackColor() }
titleLabel?.textColor = titleDisabledColor
displayLabel?.textColor = displayDisabledColor
}
}
// MARK: Private
private final var onValueChanged: (Float -> Void)?
private final var displayTextFromValue: (Float -> String)?
private final var adjustedValueFromValue: (Float -> Float)?
private final var titleColor: UIColor?
private final var displayColor: UIColor?
private dynamic func valueChanged(slider: UISlider) {
let displayLabel = cell.formDisplayLabel()
let value = slider.value
let adjustedValue = adjustedValueFromValue?(value) ?? value
self.value = adjustedValue
slider.value = adjustedValue
displayLabel?.text = displayTextFromValue?(adjustedValue) ?? "\(adjustedValue)"
onValueChanged?(adjustedValue)
}
} | 399b1b2d3132a8d1071d2ef462d84cf0 | 32.608247 | 107 | 0.639153 | false | false | false | false |
andrewBatutin/SwiftYamp | refs/heads/master | Pods/ByteBackpacker/ByteBackpacker/ByteBackpacker.swift | mit | 1 | /*
This file is part of ByteBackpacker Project. It is subject to the license terms in the LICENSE file found in the top-level directory of this distribution and at https://github.com/michaeldorner/ByteBackpacker/blob/master/LICENSE. No part of ByteBackpacker Project, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the LICENSE file.
*/
import Foundation
public typealias Byte = UInt8
public enum ByteOrder {
case bigEndian
case littleEndian
static let nativeByteOrder: ByteOrder = (Int(CFByteOrderGetCurrent()) == Int(CFByteOrderLittleEndian.rawValue)) ? .littleEndian : .bigEndian
}
open class ByteBackpacker {
private static let referenceTypeErrorString = "TypeError: Reference Types are not supported."
open class func unpack<T: Any>(_ valueByteArray: [Byte], byteOrder: ByteOrder = .nativeByteOrder) -> T {
assert(!(T.self is AnyClass), ByteBackpacker.referenceTypeErrorString)
let bytes = (byteOrder == .littleEndian) ? valueByteArray : valueByteArray.reversed()
return bytes.withUnsafeBufferPointer {
return $0.baseAddress!.withMemoryRebound(to: T.self, capacity: 1) {
$0.pointee
}
}
}
open class func unpack<T: Any>(_ valueByteArray: [Byte], toType type: T.Type, byteOrder: ByteOrder = .nativeByteOrder) -> T {
assert(!(T.self is AnyClass), ByteBackpacker.referenceTypeErrorString)
let bytes = (byteOrder == .littleEndian) ? valueByteArray : valueByteArray.reversed()
return bytes.withUnsafeBufferPointer {
return $0.baseAddress!.withMemoryRebound(to: T.self, capacity: 1) {
$0.pointee
}
}
}
open class func pack<T: Any>( _ value: T, byteOrder: ByteOrder = .nativeByteOrder) -> [Byte] {
assert(!(T.self is AnyClass), ByteBackpacker.referenceTypeErrorString)
var value = value // inout works only for var not let types
let valueByteArray = withUnsafePointer(to: &value) {
Array(UnsafeBufferPointer(start: $0.withMemoryRebound(to: Byte.self, capacity: 1){$0}, count: MemoryLayout<T>.size))
}
return (byteOrder == .littleEndian) ? valueByteArray : valueByteArray.reversed()
}
}
public extension Data {
func toByteArray() -> [Byte] {
let count = self.count / MemoryLayout<Byte>.size
var array = [Byte](repeating: 0, count: count)
copyBytes(to: &array, count:count * MemoryLayout<Byte>.size)
return array
}
}
| ee03f44353ba6a8bf7f8b25c2cf4ea0e | 38.318182 | 398 | 0.674759 | false | false | false | false |
f2m2/f2m2-swift-forms | refs/heads/master | FormGenerator/FormGenerator/FormGenerator/FormController.swift | mit | 3 | //
// FormSerializerClasses.swift
// FormSerializer
//
// Created by Michael L Mork on 12/1/14.
// Copyright (c) 2014 f2m2. All rights reserved.
//
import Foundation
import UIKit
/**
Simple convenience extensions on FormControllerProtocol-conforming UIViewController; tableview is provided and added.
*/
extension UIViewController: FormControllerProtocol {
/**
Convenience on convenience; provide only the form data data.
:param: data FormObjectProtocol-conforming objects.
:return: FormController a formController.
*/
public func newFormController (data: [FormObjectProtocol]) -> FormController {
return newFormController(data, headerView: nil)
}
/**
Provide data and a header view for a tableview which is added to self.
:param: data FormObjectProtocol-conforming objects.
:param: headerView an optional custom header for the tableView
:return: FormController a formController.
*/
public func newFormController (data: [FormObjectProtocol], headerView: UIView?) -> FormController {
let tableView = UITableView(frame: CGRectZero)
view.addSubview(tableView)
layout(tableView, view) { (TableView, View) -> () in
TableView.edges == inset(View.edges, 20, 0, 0, 0); return
}
if let headerView = headerView as UIView! {
tableView.tableHeaderView = headerView
}
let formController = FormController(data: data, tableView: tableView)
formController.delegate = self
return formController
}
}
/**
The EntityController holds the FormSerializationProtocol collection.
It sorts this collection in order to find the data which will be displayed.
It sorts to find the number of sections.
It sets its displayed data values as the interface is manipulated.
Meant-For-Consumption functions include:
/// - init: init with FormSerializationProtocol-conforming objects.
/// - validateForm: Validate all FormObjectProtocol objects which implement isValid().
/// - assembleSubmissionDictionary: Assemble a network SubmissionDictionary from the values set on the display data which are implementing the key variable in FormObjectProtocol.
/// - updateDataModelWithIdentifier: Update a FormObjectProtocolObject with a value and its user - given identifier.
*/
@objc public class FormController: NSObject, UITableViewDataSource, UITableViewDelegate {
let data: [FormObjectProtocol]
var delegate: FormControllerProtocol?
var tableView: UITableView
var customFormObjects: [String: FormObjectProtocol] = [String: FormObjectProtocol]()
var sectionHeaderTitles: [String] = [String]()
lazy var displayData: [FormObjectProtocol] = {
var mData = self.data
mData = sorted(mData) {
f0, f01 in
//Display order here.
return f0.rowIdx < f01.rowIdx
}
var nData = mData.filter { (T) -> Bool in
//filter whether to display here.
T.displayed == true
}
return nData
}()
/********
public
********/
/**
init with data conforming to the FormSerializationProtocol.
:param: data An array of objects conforming to the FormSerializationProtocol
:returns: self
*/
init(data: [FormObjectProtocol], tableView: UITableView) {
self.data = data
self.tableView = tableView
super.init()
tableView.registerClass(FormCell.self, forCellReuseIdentifier: "Cell")
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
}
/**
Update the data model with identifier and the new value.
:param: identifier A string assigned to a given
:param: newValue Whatever type of anyObject the user desires to set on the given identifier's FormObjectProtocol object.
*/
func updateDataModelWithIdentifier(identifier: String, newValue: AnyObject) {
// if let formObject = customFormObjects?[identifier] as FormObjectProtocol? {
println("update data model: \(customFormObjects)")
updateDataModel(customFormObjects[identifier])
}
/**
Update the data model with a unique ForhObjectProtocol object.
:param: object A FormObjectProtocol object
*/
func updateDataModel(object: FormObjectProtocol?) {
if let object = object as FormObjectProtocol? {
let index = collectionIndexOfObjectInSection(object.rowIdx, itemIndexInSection: object.sectionIdx)
self.displayData.removeAtIndex(index)
self.displayData.insert(object, atIndex: index)
/*
This is an example of optional chaining.
The delegate may or may not exist (an optional), and it may or may not be implementing formValueChanged.
This is what the question marks are delineating.
*/
self.delegate?.formValueChanged?(object)
let indexPath = NSIndexPath(forRow: object.rowIdx, inSection: object.sectionIdx)
if object.reloadOnValueChange == true {
println("\n reloading index at row: \n\n indexPath row: \(indexPath.row) \n indexPath section: \(indexPath.section) \n\n")
tableView.reloadRowsAtIndexPaths([indexPath as NSIndexPath], withRowAnimation: UITableViewRowAnimation.None)
}
//tableView.reloadData()
}
}
/**
Check form objects implementing this method for being valid
:return: An array of validation error strings to be presented however the user wishes.
*/
func validateFormItems(formItemIsValid: FieldNeedsValidation) -> (Bool) {
var isValid = true
var dataThatValidates = data.filter { (filtered: FormObjectProtocol) -> Bool in
filtered.needsValidation == true
}
for protocolObject in dataThatValidates {
if let formIsValid = formItemIsValid(value: protocolObject) as Bool? {
if formIsValid == false {
isValid = false
}
}
}
return isValid
}
/**
Assemble a urlRequest form dictionary.
:return: a urlRequest form dictionary.
*/
func assembleSubmissionDictionary() -> NSDictionary {
var nData = data.filter { (FieldObject) -> Bool in
//Get data which is not being displayed; its value is required and already provided.
FieldObject.displayed == false
}
//Append the display data to nData.
nData += displayData
var filteredData = nData.filter { (T) -> Bool in
var hasKey = false
if let keyAsString = T.key as String? {
if countElements(keyAsString) > 0 {
hasKey = true
}
}
return hasKey == true
}
let mDict: NSMutableDictionary = NSMutableDictionary()
for kV in filteredData {
mDict.setValue(kV.value, forKey: kV.key)
}
return mDict.copy() as NSDictionary
}
/********
private
********/
/**
Compute number of sections for the data.
:return: number of sections for the data.
*/
private func numberOfSections() -> (Int) {
var prevIdx = 0
var mSectionsCount: NSMutableDictionary = NSMutableDictionary()
for data in displayData {
var numSectionsForIdx = mSectionsCount[String(data.sectionIdx)] as Int!
if let sectionsCount = numSectionsForIdx as Int! {
var section = sectionsCount
mSectionsCount.setValue(++section, forKey: String(data.sectionIdx))
} else {
mSectionsCount.setValue(0, forKey: String(data.sectionIdx))
}
++prevIdx
}
return mSectionsCount.allKeys.count
}
func numberOfItemsInSection(section: Int) -> (Int) {
return displayDataForSection(section).count
}
/**
Called in CellForRowAtIndexPath.
:param: FormCell The cell to configure to display its data for the display data for section and row.
:param: NSIndexPath Pretty standard, really.
*/
private func formCellForRowAtIndexPath(cell: UITableViewCell, indexPath: NSIndexPath) {
if let cell = cell as? FormCell {
let displayData = displayDataForSection(indexPath.section)
//A sanity check
if indexPath.row < displayData.count {
var field = displayData[indexPath.row]
requestViewObject(field, cell: cell, {value in
/*
Upon a value change, set the field's value to the new value and replace the current model's object.
*/
field.value = value
self.updateDataModel(field)
})
}
}
}
/**
Filter the display data for the corresponding section.
:param: The section idx.
:returns: Array of
*/
private func displayDataForSection(sectionIdx: Int) -> ([FormObjectProtocol]) {
var dataForSection = displayData.filter { (T) -> Bool in
return T.sectionIdx == sectionIdx
}
dataForSection = dataForSection.sorted { (previous, current) -> Bool in
previous.rowIdx < current.rowIdx
}
return dataForSection
}
/**
Determine the enum then call the associated function, passing an optional UI element. (the cell will create one on its own otherwise)
:param: FormObjectProtocol: an FOP conforming object
:param: FormCell: a form cell
:param: ValueDidChange:
*/
private func requestViewObject(field: FormObjectProtocol, cell: FormCell, valueChangeCallback: FieldDidChange) {
//update the custom field values
if let fieldId = field.identifier as String! {
if fieldId != "" {
customFormObjects.updateValue(field, forKey: fieldId)
println("field added to customFormObjects: \(customFormObjects)")
}
}
let type = UIType(rawValue: field.uiType)
switch type! {
case .TypeNone:
return
case .TypeTextField:
cell.addTextField(delegate?.textFieldForFormObject?(field, aTextField: UITextField()))
case .TypeASwitch:
println("switch value bein set to: \(field.value)")
let aNewSwitch = UISwitch()
aNewSwitch.setOn(field.value as Bool, animated: true)
cell.addSwitch(delegate?.accompanyingLabel?(field, aLabel: UILabel()), aSwitch: delegate?.switchForFormObject?(field, aSwitch: aNewSwitch))
case .TypeCustomView:
cell.addCustomView(delegate?.customViewForFormObject?(field, aView: UIView()))
}
cell.valueDidChange = valueChangeCallback
}
private func collectionIndexOfObjectInSection(section: Int, itemIndexInSection: Int) -> (Int) {
let map = sectionsMap()
var totalCount = 0
for key in map.allKeys {
let count = key.integerValue
let sectionIdx = map[String(key as NSString)] as Int
if sectionIdx < section {
totalCount += count
}
if sectionIdx == section {
totalCount += itemIndexInSection
}
}
return totalCount
}
private func sectionsMap () -> (NSDictionary) {
var prevIdx = 0
var mSectionsCount: NSMutableDictionary = NSMutableDictionary()
for data in displayData {
var numSectionsForIdx = mSectionsCount[String(data.sectionIdx)] as Int!
if let sectionsCount = numSectionsForIdx as Int! {
var section = sectionsCount
mSectionsCount.setValue(++section, forKey: String(data.sectionIdx))
} else {
mSectionsCount.setValue(0, forKey: String(data.sectionIdx))
}
++prevIdx
}
return mSectionsCount.copy() as NSDictionary
}
/*
**************************
tableView delegate methods
**************************
*/
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfItemsInSection(section) // filteredArrayCount
}
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return numberOfSections()
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: AnyObject? = tableView.dequeueReusableCellWithIdentifier("Cell")
formCellForRowAtIndexPath(cell as UITableViewCell, indexPath: indexPath)
return cell as UITableViewCell
}
public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = ""
if section < sectionHeaderTitles.count {
title = sectionHeaderTitles[section]
}
return title
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let displayData = displayDataForSection(indexPath.section)
//A sanity check
if indexPath.row < displayData.count {
var field = displayData[indexPath.row]
delegate?.didSelectFormObject?(field)
}
}
}
| e3239ec3bfba3381baecc9c8f42110e0 | 28.809055 | 178 | 0.563561 | false | false | false | false |
MIPsoft/miauth-ios-sampleApp | refs/heads/master | miauth-ios-sampleApp/MiauthClient.swift | mit | 1 | //
// miauthClient.swift
// miauth-ios-sampleApp
//
// Created by developer on 03/04/16.
// Copyright © 2016 MIPsoft. All rights reserved.
//
import Foundation
import UIKit
enum AuthenticationState {
case Unknown
case Ok
case Fail
}
class MiauthClient {
static let sharedInstance = MiauthClient()
var registeredCallback: [()->()] = []
var authenticationState: AuthenticationState = .Unknown
var authenticationData: [String: String] = [:]
init() {
}
private func miauthIsInstalled() -> Bool {
if let miauthURL:NSURL = NSURL(string:"miauth://test") {
let application:UIApplication = UIApplication.sharedApplication()
if (application.canOpenURL(miauthURL)) {
return true
}
}
return false
}
func buttonTitle() -> String {
if !miauthIsInstalled() {
return "Asenna miauth-sovellus";
}
else {
return "Tunnistaudu miauth-sovelluksella"
}
}
func authenticate( callback:()->() ) -> Bool {
if let miauthURL:NSURL = NSURL(string:"miauth://authenticate?callbackurl=com.mipsoft.miauth-ios-sampleApp&app=miAuth-esimerkkiohjelma") {
let application:UIApplication = UIApplication.sharedApplication()
registeredCallback = [callback]
application.openURL(miauthURL);
return true
}
return false
}
func callBackURL(url: NSURL, fromApplication: String?) -> Bool {
if fromApplication == "com.mipsoft.miauth" {
print("Received \(url) from \(fromApplication) host=\(url.host)")
//TODO: Dynaaminen parseri
if url.host == "authentication" {
authenticationState = .Fail
authenticationData = [:]
if let params = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)?.queryItems,
data = params.filter({ $0.name == "status" }).first,
value = data.value {
if value=="true" {
authenticationState = .Ok
}
authenticationData[data.name] = data.value
}
for key:String in ["name","email","address"] {
if let params = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)?.queryItems,
data = params.filter({ $0.name == key}).first,
value = data.value {
authenticationData[data.name] = value
}
}
} //authenticate
if ( registeredCallback.count>0 ) {
let function: ()->() = registeredCallback[0]
function()
}
return false;
}
return true;
}
}
| 0461bb607412adbe1626f4b5b9dd617b | 29.8125 | 145 | 0.526031 | false | false | false | false |
exaphaser/HG5 | refs/heads/master | Frameless/ViewController.swift | mit | 2 | //
// ViewController.swift
// Frameless
//
// Created by Jay Stakelon on 10/23/14.
// Copyright (c) 2014 Jay Stakelon. All rights reserved.
//
import UIKit
import WebKit
class ViewController: UIViewController, UISearchBarDelegate, FramelessSearchBarDelegate, UIGestureRecognizerDelegate, WKNavigationDelegate, FramerBonjourDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var _searchBar: FramelessSearchBar!
@IBOutlet weak var _progressView: UIProgressView!
@IBOutlet weak var _loadingErrorView: UIView!
let _confirmFramerConnect = true
var _webView: WKWebView?
var _isMainFrameNavigationAction: Bool?
var _loadingTimer: NSTimer?
var _tapRecognizer: UITapGestureRecognizer?
var _panFromBottomRecognizer: UIScreenEdgePanGestureRecognizer?
var _panFromTopRecognizer: UIScreenEdgePanGestureRecognizer?
var _panFromRightRecognizer: UIScreenEdgePanGestureRecognizer?
var _panFromLeftRecognizer: UIScreenEdgePanGestureRecognizer?
var _areControlsVisible = true
var _isFirstRun = true
var _effectView: UIVisualEffectView?
var _errorView: UIView?
var _settingsBarView: UIView?
var _settingsButton: UIButton?
var _topBorder: UIView?
var _defaultsObject: NSUserDefaults?
var _onboardingViewController: OnboardingViewController?
var _isCurrentPageLoaded = false
var _framerBonjour = FramerBonjour()
var _framerAddress: String?
var _alertBuilder: JSSAlertView = JSSAlertView()
var _keyboardHeight:CGFloat = 216
var _suggestionsTableView: UITableView?
var _clearHistoryButton: UIButton?
// Loading progress? Fake it till you make it.
var _progressTimer: NSTimer?
var _isWebViewLoading = false
// did we just rewrite framer html?
var _isRewritten = false
override func viewDidLoad() {
super.viewDidLoad()
let webViewConfiguration: WKWebViewConfiguration = WKWebViewConfiguration()
webViewConfiguration.allowsInlineMediaPlayback = true
webViewConfiguration.mediaPlaybackRequiresUserAction = false
_webView = WKWebView(frame: self.view.frame, configuration: webViewConfiguration)
self.view.addSubview(_webView!)
// _webView!.scalesPageToFit = true
_webView!.navigationDelegate = self
self.view.sendSubviewToBack(_webView!)
_defaultsObject = NSUserDefaults.standardUserDefaults()
_loadingErrorView.hidden = true
_tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("hideSearch"))
_panFromBottomRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("handleBottomEdgePan:"))
_panFromBottomRecognizer!.edges = UIRectEdge.Bottom
_panFromBottomRecognizer!.delegate = self
self.view.addGestureRecognizer(_panFromBottomRecognizer!)
_panFromTopRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("handleTopEdgePan:"))
_panFromTopRecognizer!.edges = UIRectEdge.Top
_panFromTopRecognizer!.delegate = self
self.view.addGestureRecognizer(_panFromTopRecognizer!)
_panFromLeftRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("handleGoBackPan:"))
_panFromLeftRecognizer!.edges = UIRectEdge.Left
_panFromLeftRecognizer!.delegate = self
self.view.addGestureRecognizer(_panFromLeftRecognizer!)
_panFromRightRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("handleGoForwardPan:"))
_panFromRightRecognizer!.edges = UIRectEdge.Right
_panFromRightRecognizer!.delegate = self
self.view.addGestureRecognizer(_panFromRightRecognizer!)
_searchBar.delegate = self
_searchBar.framelessSearchBarDelegate = self
_searchBar.showsCancelButton = false
_searchBar.autocapitalizationType = .None
_searchBar.becomeFirstResponder()
AppearanceBridge.setSearchBarTextInputAppearance()
_settingsBarView = UIView(frame: CGRectMake(0, self.view.frame.height, self.view.frame.width, 44))
_settingsBarView?.backgroundColor = LIGHT_GREY
_settingsButton = UIButton(frame: CGRectZero)
_settingsButton!.setTitle("Settings", forState: .Normal)
_settingsButton!.setTitleColor(BLUE, forState: .Normal)
_settingsButton!.setTitleColor(HIGHLIGHT_BLUE, forState: .Highlighted)
_settingsButton!.titleLabel!.font = UIFont.systemFontOfSize(14)
_settingsButton!.sizeToFit()
var settingsFrame = _settingsButton!.frame
settingsFrame.origin.x = _settingsBarView!.frame.width - settingsFrame.width - 14
settingsFrame.origin.y = 7
_settingsButton!.frame = settingsFrame
_clearHistoryButton = UIButton(frame: CGRectZero)
_clearHistoryButton!.setTitle("Clear History", forState: .Normal)
_clearHistoryButton!.setTitleColor(BLUE, forState: .Normal)
_clearHistoryButton!.setTitleColor(HIGHLIGHT_BLUE, forState: .Highlighted)
_clearHistoryButton!.setTitleColor(LIGHT_TEXT, forState: .Disabled)
_clearHistoryButton!.titleLabel!.font = UIFont.systemFontOfSize(14)
_clearHistoryButton!.sizeToFit()
var clearFrame = _clearHistoryButton!.frame
clearFrame.origin.x = 14
clearFrame.origin.y = 7
_clearHistoryButton!.frame = clearFrame
_settingsButton!.addTarget(self, action: "presentSettingsView:", forControlEvents: .TouchUpInside)
_clearHistoryButton!.addTarget(self, action: "didTapClearHistory:", forControlEvents: .TouchUpInside)
_topBorder = UIView()
_topBorder!.frame = CGRectMake(0, 0, _settingsBarView!.frame.width, 0.5)
_topBorder!.backgroundColor = LIGHT_GREY_BORDER
_settingsBarView?.addSubview(_topBorder!)
_settingsBarView?.addSubview(_settingsButton!)
_settingsBarView?.addSubview(_clearHistoryButton!)
self.view.addSubview(_settingsBarView!)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardShown:"), name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("historyUpdated:"), name: HISTORY_UPDATED_NOTIFICATION, object: nil)
_framerBonjour.delegate = self
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.FramerBonjour.rawValue) as! Bool == true {
_framerBonjour.start()
}
_progressView.hidden = true
showSuggestionsTableView()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func introCompletion() {
_onboardingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
//MARK: - UI show/hide
func keyboardShown(sender: NSNotification) {
let info = sender.userInfo!
let value: AnyObject = info[UIKeyboardFrameEndUserInfoKey]!
let rawFrame = value.CGRectValue
let keyboardFrame = view.convertRect(rawFrame, fromView: nil)
_keyboardHeight = keyboardFrame.height
}
func keyboardWillShow(sender: NSNotification) {
if _searchBar.isFirstResponder() {
let dict:NSDictionary = sender.userInfo! as NSDictionary
let s:NSValue = dict.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let rect :CGRect = s.CGRectValue()
_settingsBarView!.frame.origin.y = self.view.frame.height - rect.height - _settingsBarView!.frame.height
_settingsBarView!.alpha = 1
}
}
func keyboardWillHide(sender: NSNotification) {
_settingsBarView!.frame.origin.y = self.view.frame.height
_settingsBarView!.alpha = 0
}
func handleBottomEdgePan(sender: AnyObject) {
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.PanFromBottomGesture.rawValue) as! Bool == true {
showSearch()
}
}
func handleTopEdgePan(sender: AnyObject) {
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.PanFromTopGesture.rawValue) as! Bool == true {
showSearch()
}
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if let _:Bool = NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.ShakeGesture.rawValue) as? Bool {
// if(event.subtype == UIEventSubtype.MotionShake && isShakeActive == true) {
// if (!_areControlsVisible) {
// showSearch()
// } else {
// hideSearch()
// }
// }
searchBarRefreshWasPressed()
}
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
return true
}
func hideSearch() {
removeSuggestionsTableView()
_searchBar.resignFirstResponder()
UIView.animateWithDuration(0.5, delay: 0.05, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: {
self._searchBar.transform = CGAffineTransformMakeTranslation(0, -44)
}, completion: nil)
_areControlsVisible = false
removeBackgroundBlur()
}
func showSearch() {
if !_areControlsVisible {
if let urlString = _webView?.URL?.absoluteString {
_searchBar.text = urlString
}
UIView.animateWithDuration(0.5, delay: 0.05, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: {
self._searchBar.transform = CGAffineTransformMakeTranslation(0, 0)
}, completion: nil)
_areControlsVisible = true
_searchBar.selectAllText()
_searchBar.becomeFirstResponder()
showSuggestionsTableView()
fadeInSuggestionsTable()
blurBackground()
}
}
func blurBackground() {
if !_isFirstRun {
if _effectView == nil {
let blur:UIBlurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
_effectView = UIVisualEffectView(effect: blur)
let size = _webView!.frame.size
_effectView!.frame = CGRectMake(0,0,size.width,size.height)
_effectView!.alpha = 0
_effectView?.addGestureRecognizer(_tapRecognizer!)
_webView!.addSubview(_effectView!)
_webView!.alpha = 0.25
UIView.animateWithDuration(0.25, animations: {
self._effectView!.alpha = 1
}, completion: nil)
}
}
}
func removeBackgroundBlur() {
if _effectView != nil {
UIView.animateWithDuration(0.25, animations: {
self._effectView!.alpha = 0
}, completion: { finished in
self._effectView = nil
})
_webView!.alpha = 1
}
}
func focusOnSearchBar() {
_searchBar.becomeFirstResponder()
}
func fadeInSuggestionsTable() {
if let tableView = _suggestionsTableView {
tableView.alpha = 0
UIView.animateWithDuration(0.25, delay: 0.25, options: [], animations: {
self._suggestionsTableView!.alpha = 1
}, completion: nil)
}
}
//MARK: - Settings view
func presentSettingsView(sender:UIButton!) {
let settingsNavigationController = storyboard?.instantiateViewControllerWithIdentifier("settingsController") as! UINavigationController
let settingsTableViewController = settingsNavigationController.topViewController as! SettingsTableViewController
settingsTableViewController.delegate = self
// Animated form sheet presentation was crashing on regular size class (all iPads, and iPhone 6+ landscape).
// Disabling the animation until the root cause of that crash is found.
let shouldAnimateSettingsPresentation: Bool = self.traitCollection.horizontalSizeClass != .Regular
self.presentViewController(settingsNavigationController, animated: shouldAnimateSettingsPresentation, completion: nil)
}
//MARK: - Web view
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
_searchBar.showsCancelButton = true
_loadingErrorView.hidden = true
_isFirstRun = false
_isWebViewLoading = true
_progressView.hidden = false
_progressView.progress = 0
_progressTimer = NSTimer.scheduledTimerWithTimeInterval(0.01667, target: self, selector: "progressTimerCallback", userInfo: nil, repeats: true)
_loadingTimer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: "loadingTimeoutCallback", userInfo: nil, repeats: false)
}
func loadingTimeoutCallback() {
_webView?.stopLoading()
handleWebViewError()
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
HistoryManager.manager.addToHistory(webView)
removeSuggestionsTableView()
_isCurrentPageLoaded = true
_loadingTimer!.invalidate()
_isWebViewLoading = false
}
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
if let _ = _isMainFrameNavigationAction {
// do nothing, I'm pretty sure it's a new page load into target="_blank" before the old one's subframes are finished
} else {
handleWebViewError()
}
}
func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
if let _ = _isMainFrameNavigationAction {
// do nothing, it's a new page load before the old one's subframes are finished
} else {
handleWebViewError()
}
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.FixiOS9.rawValue) as! Bool == true {
// resize Framer prototypes to fix iOS9 "bug"
if let absURL = navigationAction.request.URL {
let isFramerExt = absURL.lastPathComponent!.rangeOfString(".framer")
let isFramerShare = absURL.host?.rangeOfString("share.framerjs.com")
if (isFramerExt != nil) || (isFramerShare != nil) {
if _isRewritten == false {
decisionHandler(.Cancel)
let screenWidth = UIScreen.mainScreen().bounds.width * UIScreen.mainScreen().scale
do {
var html = try String(contentsOfURL: absURL, encoding: NSASCIIStringEncoding)
html = html.stringByReplacingOccurrencesOfString("width=device-width", withString: "width=\(screenWidth)")
_webView?.loadHTMLString(html, baseURL: absURL)
_isRewritten = true
} catch {
}
} else {
_isRewritten = false
}
}
}
}
if (navigationAction.targetFrame == nil && navigationAction.navigationType == .LinkActivated) {
_isRewritten == false
_webView!.loadRequest(navigationAction.request)
}
_isMainFrameNavigationAction = navigationAction.targetFrame?.mainFrame
decisionHandler(.Allow)
}
func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
let hostname = webView.URL?.host
let authMethod = challenge.protectionSpace.authenticationMethod
// in ios9, https requests run through this method
// so just handle it otherwise they get canceled out
if authMethod == NSURLAuthenticationMethodServerTrust {
completionHandler(NSURLSessionAuthChallengeDisposition.PerformDefaultHandling, nil)
} else if authMethod == NSURLAuthenticationMethodHTTPBasic {
if let loadTimer = _loadingTimer {
loadTimer.invalidate()
}
if let progTimer = _progressTimer {
progTimer.invalidate()
}
_progressView.hidden = true
let title = "Authentication Required"
var message = "The server requires a username and password."
if let hostStr = hostname {
message = "The server at \(hostStr) requires a username and password."
}
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler( { (textField: UITextField) in
textField.placeholder = "Username"
})
alert.addTextFieldWithConfigurationHandler( { (textField: UITextField) in
textField.placeholder = "Password"
textField.secureTextEntry = true
})
let okAction = UIAlertAction(title: "OK", style: .Default, handler: { (UIAlertaction) in
let usernameTextfield = alert.textFields![0]
let pwTextfield = alert.textFields![1]
let username = usernameTextfield.text
let pw = pwTextfield.text
let credential = NSURLCredential(user: username!, password: pw!, persistence: .ForSession)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (UIAlertAction) in
completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
})
alert.addAction(okAction)
alert.addAction(cancelAction)
dispatch_async(dispatch_get_main_queue(), {
self.presentViewController(alert, animated: true, completion: nil)
})
} else {
completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
}
}
func handleWebViewError() {
_loadingTimer!.invalidate()
_isCurrentPageLoaded = false
_isWebViewLoading = false
showSearch()
displayLoadingErrorMessage()
}
func progressTimerCallback() {
if (!_isWebViewLoading) {
if (_progressView.progress >= 1) {
_progressView.hidden = true
_progressTimer?.invalidate()
} else {
_progressView.progress += 0.2
}
} else {
_progressView.progress += 0.003
if (_progressView.progress >= 0.95) {
_progressView.progress = 0.95
}
}
}
func loadURL(urlString: String, andCloseSearch: Bool = false) {
let addrStr = urlifyUserInput(urlString)
let addr = NSURL(string: addrStr)
if let webAddr = addr {
if let loadTimer = _loadingTimer {
loadTimer.invalidate()
}
_webView!.stopLoading()
let req = NSURLRequest(URL: webAddr)
_isRewritten == false
_webView!.loadRequest(req)
} else {
displayLoadingErrorMessage()
}
if andCloseSearch == true {
hideSearch()
}
}
func displayLoadingErrorMessage() {
self.view.sendSubviewToBack(_loadingErrorView)
_loadingErrorView.hidden = false
if let suggestions = _suggestionsTableView {
suggestions.hidden = true
}
}
func handleGoBackPan(sender: UIScreenEdgePanGestureRecognizer) {
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.ForwardBackGesture.rawValue) as! Bool == true {
if (sender.state == .Began) {
_webView!.goBack()
}
}
}
func handleGoForwardPan(sender: AnyObject) {
if NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.ForwardBackGesture.rawValue) as! Bool == true {
if (sender.state == .Began) {
_webView!.goForward()
}
}
}
// Framer.js Bonjour Integration
func didResolveAddress(address: String) {
if _confirmFramerConnect {
if !_alertBuilder.isAlertOpen {
let windowCount = UIApplication.sharedApplication().windows.count
if let targetView = UIApplication.sharedApplication().windows[windowCount-1].rootViewController {
_framerAddress = address
// let paragraphStyle = NSMutableParagraphStyle()
// paragraphStyle.lineSpacing = 2
// paragraphStyle.alignment = .Center
// let alertStr = NSMutableAttributedString(string: "Framer Studio is running on your network. Connect now?")
// alertStr.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, alertStr.length))
let alert = _alertBuilder.show(targetView as UIViewController!, title: "Framer Mirror", text: "Framer Studio is running on your network. Connect now?", cancelButtonText: "Cancel", buttonText: "Connect", color: BLUE)
alert.addAction(handleAlertConfirmTap)
alert.setTextTheme(.Light)
}
}
} else {
loadFramer(address)
}
}
func handleAlertConfirmTap() {
loadFramer(_framerAddress!)
}
func loadFramer(address: String) {
hideSearch()
loadURL(address)
}
func startSearching() {
_framerBonjour.start()
}
func stopSearching() {
_framerBonjour.stop()
}
//MARK: - Search bar
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
hideSearch()
loadURL(searchBar.text!)
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
hideSearch()
}
func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
var enable = false
if let txt = _searchBar.text {
if ((txt as String).characters.count > 0) && _isCurrentPageLoaded {
enable = true
}
}
_searchBar.refreshButton().enabled = enable
return true
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
updateSuggestions(searchText)
_searchBar.refreshButton().enabled = false
}
func searchBarRefreshWasPressed() {
if let timer = _loadingTimer {
timer.invalidate()
hideSearch()
if let urlString = _webView?.URL?.absoluteString {
_searchBar.text = urlString
}
loadURL(_searchBar.text!)
}
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animateAlongsideTransition({ context in
self._webView!.frame = CGRectMake(0, 0, size.width, size.height)
let availHeight = size.height - 88 - CGFloat(self._keyboardHeight)
if let suggestionsTableView = self._suggestionsTableView {
suggestionsTableView.frame = CGRectMake(0, 44, size.width, availHeight)
}
if let settingsBar = self._settingsBarView {
settingsBar.frame = CGRectMake(0, self.view.frame.height, self.view.frame.width, 44)
}
if let topBorder = self._topBorder {
topBorder.frame = CGRectMake(0, 0, self._settingsBarView!.frame.width, 0.5)
}
if let settingsButton = self._settingsButton {
var settingsFrame = settingsButton.frame
settingsFrame.origin.x = self._settingsBarView!.frame.width - settingsFrame.width - 14
settingsFrame.origin.y = 7
settingsButton.frame = settingsFrame
}
}, completion: nil)
}
//MARK: - History & favorites suggestions
func historyUpdated(notification: NSNotification) {
checkHistoryButton()
_suggestionsTableView?.reloadData()
}
func didTapClearHistory(sender: UIButton!) {
HistoryManager.manager.clearHistory()
_suggestionsTableView?.reloadData()
}
func checkHistoryButton() {
if HistoryManager.manager.totalEntries > 0 {
_clearHistoryButton!.enabled = true
} else {
_clearHistoryButton!.enabled = false
}
}
func updateSuggestions(text: String) {
showSuggestionsTableView()
}
func showSuggestionsTableView() {
if _suggestionsTableView == nil {
let size = UIScreen.mainScreen().bounds.size
let availHeight = size.height - 88 - CGFloat(_keyboardHeight)
_suggestionsTableView = UITableView(frame: CGRectMake(0, 44, size.width, availHeight), style: .Grouped)
_suggestionsTableView?.delegate = self
_suggestionsTableView?.dataSource = self
_suggestionsTableView?.backgroundColor = UIColor.clearColor()
_suggestionsTableView?.separatorColor = UIColorFromHex(0x000000, alpha: 0.1)
self.view.insertSubview(_suggestionsTableView!, belowSubview: _settingsBarView!)
}
if let errorView = _loadingErrorView {
errorView.hidden = true
}
_suggestionsTableView?.hidden = false
populateSuggestionsTableView()
}
func populateSuggestionsTableView() {
HistoryManager.manager.getHistoryDataFor(_searchBar.text!)
}
func removeSuggestionsTableView() {
_suggestionsTableView?.removeFromSuperview()
_suggestionsTableView = nil
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:HistoryTableViewCell = HistoryTableViewCell(style: .Subtitle, reuseIdentifier: nil)
var entry:HistoryEntry
if indexPath.section == 0 {
entry = HistoryManager.manager.studio!
} else if indexPath.section == 1 {
entry = HistoryManager.manager.matches[indexPath.row]
} else {
entry = HistoryManager.manager.history[indexPath.row]
}
cell.backgroundColor = UIColor.clearColor()
cell.entry = entry
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = _suggestionsTableView?.cellForRowAtIndexPath(indexPath) as? HistoryTableViewCell {
loadURL(cell.entry!.url.absoluteString, andCloseSearch: true)
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
if let _ = HistoryManager.manager.studio {
return 1
} else {
return 0
}
} else if section == 1 {
return HistoryManager.manager.matches.count
} else {
return HistoryManager.manager.history.count
}
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let rows = self.tableView(tableView, numberOfRowsInSection: section)
if rows == 0 {
return ""
} else if section == 0 {
return "Last Connection to Framer Studio"
} else if section == 1 {
return "Top Matches"
} else {
return "History"
}
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let size = UIScreen.mainScreen().bounds.size
let label = UILabel(frame: CGRectMake(14, 4, size.width - 28, 13))
label.font = UIFont.systemFontOfSize(13)
label.textColor = UIColorFromHex(0x000000, alpha: 0.5)
label.text = self.tableView(tableView, titleForHeaderInSection: section)?.uppercaseString
let headerView = UIView()
headerView.backgroundColor = UIColorFromHex(0x000000, alpha: 0.05)
headerView.addSubview(label)
return headerView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 && HistoryManager.manager.studio != nil {
return 21
} else if section == 1 && HistoryManager.manager.matches.count > 0 {
return 21
}else if section == 2 && HistoryManager.manager.history.count > 0 {
return 21
} else {
return CGFloat.min
}
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.min
}
}
| 1b246ea9a3b8dc95eb2e8576aadb1e41 | 40.184 | 235 | 0.626813 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/Views/Chat/New Chat/ChatItems/MessageReplyThreadChatItem.swift | mit | 1 | //
// MessageReplyThreadChatItem.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 17/04/19.
// Copyright © 2019 Rocket.Chat. All rights reserved.
//
import Foundation
import DifferenceKit
import RocketChatViewController
final class MessageReplyThreadChatItem: BaseMessageChatItem, ChatItem, Differentiable {
var isSequential: Bool = false
var relatedReuseIdentifier: String {
return ThreadReplyCollapsedCell.identifier
}
init(user: UnmanagedUser?, message: UnmanagedMessage?, sequential: Bool = false) {
super.init(user: user, message: message)
isSequential = sequential
}
internal var threadName: String? {
guard
!isSequential,
let message = message
else {
return nil
}
return message.mainThreadMessage
}
var differenceIdentifier: String {
return message?.identifier ?? ""
}
func isContentEqual(to source: MessageReplyThreadChatItem) -> Bool {
guard let message = message, let sourceMessage = source.message else {
return false
}
return message == sourceMessage
}
}
| 85e4ae232ac8e844730d7ffce5ba9228 | 24.042553 | 87 | 0.660153 | false | false | false | false |
Detailscool/YHRefresh | refs/heads/master | YHRefreshDemo/DemoViewController.swift | mit | 1 | //
// DemoViewController.swift
// YHRefresh
//
// Created by HenryLee on 16/8/30.
// Copyright © 2016年 HenryLee. All rights reserved.
//
import UIKit
import YHRefresh
class DemoViewController: UITableViewController {
var numbers = [Int]()
var s = 0
var style : YHRefreshStyle
init(style:YHRefreshStyle) {
self.style = style
super.init(style: .plain)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Test
/*
tableView.rowHeight = 10;
tableView.tableFooterView = UIView()
tableView.contentInset.bottom = 50
let bottomView = UIView(frame: CGRect(x: 0, y: yh_ScreenH - 50, width: yh_ScreenW, height: 50))
bottomView.backgroundColor = UIColor.redColor()
UIApplication.sharedApplication().keyWindow!.addSubview(bottomView)
*/
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
for i in s..<s+20 {
numbers.append(i)
}
switch style{
case .normalHeader :
tableView.yh_header = YHRefreshNormalHeader.header(self, selector: #selector(DemoViewController.loadData))
case .springHeader :
tableView.yh_header = YHRefreshSpringHeader.header(self, selector: #selector(DemoViewController.loadData))
case .gifHeader :
let header = YHRefreshGifHeader.header(self, selector: #selector(DemoViewController.loadData))
var refreshingImages = [UIImage]()
for i in 1...3 {
let image = UIImage(named: String(format:"dropdown_loading_0%zd", i))
refreshingImages.append(image!)
}
var nomalImages = [UIImage]()
for i in 1...60 {
let image = UIImage(named: String(format:"dropdown_anim__000%zd", i))
nomalImages.append(image!)
}
header.setGifHeader(nomalImages, state: YHRefreshState.normal)
header.setGifHeader(refreshingImages, state: YHRefreshState.willRefresh)
header.setGifHeader(refreshingImages, state: YHRefreshState.refreshing)
tableView.yh_header = header
case .materialHeader :
let header = YHRefreshMaterialHeader.header(self, selector: #selector(DemoViewController.loadData))
header.shouldStayOnWindow = true
tableView.yh_header = header
case .normalFooter :
tableView.yh_footer = YHRefreshNormalFooter.footer(self, selector: #selector(DemoViewController.loadData))
case .autoFooter :
tableView.yh_footer = YHRefreshAutoFooter.footer(self, selector: #selector(DemoViewController.loadData))
case .gifFooter :
let footer = YHRefreshGifFooter.footer(self, selector: #selector(DemoViewController.loadData))
var refreshingImages = [UIImage]()
for i in 1...3 {
let image = UIImage(named: String(format:"dropdown_loading_0%zd", i))
refreshingImages.append(image!)
}
var nomalImages = [UIImage]()
for i in 1...60 {
let image = UIImage(named: String(format:"dropdown_anim__000%zd", i))
nomalImages.append(image!)
}
footer.setGifFooter(nomalImages, state: YHRefreshState.normal)
footer.setGifFooter(refreshingImages, state: YHRefreshState.willRefresh)
footer.setGifFooter(refreshingImages, state: YHRefreshState.refreshing)
tableView.yh_footer = footer
}
// tableView.yh_footer?.showNoMoreData()
}
@objc func loadData() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double((Int64)(2 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: { () -> Void in
self.s += 20
for i in self.s..<self.s+20 {
self.numbers.append(i)
}
self.tableView.reloadData()
switch self.style {
case .normalHeader :
self.tableView.yh_header?.endRefreshing()
case .springHeader :
self.tableView.yh_header?.endRefreshing()
case .gifHeader :
self.tableView.yh_header?.endRefreshing()
case .materialHeader :
self.tableView.yh_header?.endRefreshing()
case .normalFooter :
self.tableView.yh_footer?.endRefreshing()
case .autoFooter :
self.tableView.yh_footer?.endRefreshing()
case .gifFooter :
self.tableView.yh_footer?.endRefreshing()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numbers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier")
cell!.textLabel?.text = "\(indexPath.row)"
cell?.textLabel?.textColor = UIColor.white
return cell!
}
func colorforIndex(_ index: Int) -> UIColor {
let itemCount = numbers.count - 1
let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6
return UIColor(red: color, green: 0.0, blue: 1.0, alpha: 1.0)
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = colorforIndex(indexPath.row)
}
}
| 9200347eeaccceba86b95d8fffeae54f | 33.139785 | 151 | 0.562677 | false | false | false | false |
ethanneff/iOS-Swift-Animated-Reorder-And-Indent | refs/heads/master | NotesApp/Task.swift | mit | 1 | //
// Tasks.swift
// NotesApp
//
// Created by Ethan Neff on 4/4/16.
// Copyright © 2016 Ethan Neff. All rights reserved.
//
import Foundation
class Task: NSObject, NSCoding, DataCompleteable, DataCollapsible, DataIndentable, DataTagable {
// PROPERTIES
var title: String
var body: String?
var tags: [Tag] = []
var indent: Int = 0
var collapsed: Bool = false
var children: Int = 0
var completed: Bool = false
override var description: String {
return "\(title) \(indent) \(collapsed)" // | \(collapsed)"
}
// INIT
init?(title: String, body: String?, tags: [Tag], indent: Int, collapsed: Bool, children: Int, completed: Bool) {
self.title = title
self.body = body
self.tags = tags
self.indent = indent
self.collapsed = collapsed
self.children = children
self.completed = completed
super.init()
if title.isEmpty {
return nil
}
}
convenience init?(title: String) {
self.init(title: title, body: nil, tags: [], indent: 0, collapsed: false, children: 0, completed: false)
}
convenience init?(title: String, indent: Int) {
self.init(title: title, body: nil, tags: [], indent: indent, collapsed: false, children: 0, completed: false)
}
// METHODS
class func loadTestData() -> [Task] {
var array = [Task]()
array.append(Task(title: "0", indent: 0)!)
array.append(Task(title: "1", indent: 1)!)
array.append(Task(title: "2", indent: 1)!)
array.append(Task(title: "3", indent: 2)!)
array.append(Task(title: "4", indent: 3)!)
array.append(Task(title: "5", indent: 2)!)
array.append(Task(title: "6", indent: 0)!)
array.append(Task(title: "7", indent: 1)!)
array.append(Task(title: "8", indent: 2)!)
array.append(Task(title: "9", indent: 0)!)
array.append(Task(title: "1.0.0", indent: 0)!)
array.append(Task(title: "1.1.0", indent: 1)!)
array.append(Task(title: "1.2.0", indent: 1)!)
array.append(Task(title: "1.2.1", indent: 2)!)
array.append(Task(title: "1.2.2", indent: 2)!)
array.append(Task(title: "1.3.0", indent: 1)!)
array.append(Task(title: "1.3.1", indent: 2)!)
array.append(Task(title: "1.3.2", indent: 2)!)
array.append(Task(title: "1.4.0", indent: 1)!)
array.append(Task(title: "2.0.0", indent: 0)!)
array.append(Task(title: "2.1.0", indent: 1)!)
array.append(Task(title: "2.2.0", indent: 1)!)
array.append(Task(title: "2.2.2", indent: 2)!)
array.append(Task(title: "2.3.0", indent: 1)!)
array.append(Task(title: "2.3.1", indent: 2)!)
array.append(Task(title: "2.3.2", indent: 2)!)
array.append(Task(title: "2.4.0", indent: 1)!)
array.append(Task(title: "3.0.0", indent: 0)!)
array.append(Task(title: "3.1.0", indent: 1)!)
array.append(Task(title: "3.1.1", indent: 2)!)
array.append(Task(title: "3.1.2", indent: 2)!)
array.append(Task(title: "3.1.3", indent: 2)!)
array.append(Task(title: "3.2.0", indent: 1)!)
array.append(Task(title: "4.0.0", indent: 0)!)
array.append(Task(title: "5.0.0", indent: 0)!)
array.append(Task(title: "5.1.0", indent: 1)!)
array.append(Task(title: "5.2.0", indent: 1)!)
array.append(Task(title: "5.2.1", indent: 2)!)
array.append(Task(title: "5.2.2", indent: 2)!)
array.append(Task(title: "5.3.0", indent: 1)!)
array.append(Task(title: "5.4.0", indent: 1)!)
array.append(Task(title: "6.0.0", indent: 0)!)
array.append(Task(title: "6.1.0", indent: 1)!)
array.append(Task(title: "6.2.0", indent: 1)!)
array.append(Task(title: "6.2.1", indent: 2)!)
array.append(Task(title: "6.2.2", indent: 2)!)
array.append(Task(title: "6.3.0", indent: 1)!)
array.append(Task(title: "6.4.0", indent: 1)!)
array.append(Task(title: "8.0.0", indent: 0)!)
array.append(Task(title: "7.0.0", indent: 0)!)
array.append(Task(title: "7.1.0", indent: 1)!)
array.append(Task(title: "7.1.1", indent: 2)!)
array.append(Task(title: "7.1.2", indent: 2)!)
array.append(Task(title: "7.1.3", indent: 2)!)
array.append(Task(title: "7.2.0", indent: 1)!)
array.append(Task(title: "7.2.1", indent: 2)!)
array.append(Task(title: "7.2.2", indent: 2)!)
array.append(Task(title: "9.0.0", indent: 0)!)
// array.append(Task(title: "9.1.0", indent: 0)!)
// array.append(Task(title: "9.1.1", indent: 0)!)
// array.append(Task(title: "9.1.2", indent: 0)!)
// array.append(Task(title: "9.1.3", indent: 0)!)
// array.append(Task(title: "9.2.0", indent: 0)!)
// array.append(Task(title: "9.0.0", indent: 0)!)
// array.append(Task(title: "9.0.0", indent: 0)!)
// array.append(Task(title: "9.1.0", indent: 0)!)
// array.append(Task(title: "9.1.1", indent: 0)!)
// array.append(Task(title: "9.1.2", indent: 0)!)
// array.append(Task(title: "9.1.3", indent: 0)!)
// array.append(Task(title: "9.2.0", indent: 0)!)
array.append(Task(title: "envision who you want to become in 2 minutes", indent: 0)!)
return array
}
// SAVE
struct PropertyKey {
static let title = "title"
static let body = "body"
static let tags = "tags"
static let indent = "indent"
static let collapsed = "collapsed"
static let children = "children"
static let completed = "completed"
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(title, forKey: PropertyKey.title)
aCoder.encodeObject(body, forKey: PropertyKey.body)
aCoder.encodeObject(tags, forKey: PropertyKey.tags)
aCoder.encodeObject(indent, forKey: PropertyKey.indent)
aCoder.encodeObject(collapsed, forKey: PropertyKey.collapsed)
aCoder.encodeObject(children, forKey: PropertyKey.children)
aCoder.encodeObject(completed, forKey: PropertyKey.completed)
}
required convenience init?(coder aDecoder: NSCoder) {
let title = aDecoder.decodeObjectForKey(PropertyKey.title) as! String
let body = aDecoder.decodeObjectForKey(PropertyKey.body) as! String
let tags = aDecoder.decodeObjectForKey(PropertyKey.tags) as! [Tag]
let indent = aDecoder.decodeObjectForKey(PropertyKey.indent) as! Int
let collapsed = aDecoder.decodeObjectForKey(PropertyKey.collapsed) as! Bool
let children = aDecoder.decodeObjectForKey(PropertyKey.children) as! Int
let completed = aDecoder.decodeObjectForKey(PropertyKey.completed) as! Bool
self.init(title: title, body: body, tags: tags, indent: indent, collapsed: collapsed, children: children, completed: completed)
}
}
| 19b60ba59f073fea157169d8df3a0e94 | 39.803797 | 131 | 0.635179 | false | false | false | false |
mmllr/CleanTweeter | refs/heads/master | CleanTweeter/UseCases/NewPost/UI/Presenter/TagAndMentionHighlightingTransformer.swift | mit | 1 |
import Foundation
class TagAndMentionHighlightingTransformer : ValueTransformer {
let resourceFactory: ResourceFactory
init(factory: ResourceFactory) {
self.resourceFactory = factory
super.init()
}
override class func transformedValueClass() -> AnyClass {
return NSAttributedString.self
}
override class func allowsReverseTransformation() -> Bool {
return false
}
override func transformedValue(_ value: Any?) -> Any? {
guard let transformedValue = value as! String? else {
return nil
}
return transformedValue.findRangesWithPattern("((@|#)([A-Z0-9a-z(é|ë|ê|è|à|â|ä|á|ù|ü|û|ú|ì|ï|î|í)_]+))|(http(s)?://([A-Z0-9a-z._-]*(/)?)*)").reduce(NSMutableAttributedString(string: transformedValue)) {
let string = $0
let length = transformedValue.distance(from: $1.lowerBound, to: $1.upperBound)
let range = NSMakeRange(transformedValue.distance(from: transformedValue.startIndex, to: $1.lowerBound), length)
string.addAttribute(resourceFactory.highlightingAttribute.0, value: self.resourceFactory.highlightingAttribute.1, range: range)
return string
}
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToNSAttributedStringKey(_ input: String) -> NSAttributedString.Key {
return NSAttributedString.Key(rawValue: input)
}
| 03b18801fdb2a4951da019544a3bd069 | 33.864865 | 204 | 0.744186 | false | false | false | false |
Mai-Tai-D/maitaid001 | refs/heads/master | Pods/SwiftCharts/SwiftCharts/Layers/ChartCandleStickLayer.swift | mit | 2 | //
// ChartCandleStickLayer.swift
// SwiftCharts
//
// Created by ischuetz on 28/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
// TODO correct scaling mode - currently it uses default, uniform scaling with which items don't stay sharp. Needs to draw views similar to ChartPointsScatterLayer
open class ChartCandleStickLayer<T: ChartPointCandleStick>: ChartPointsLayer<T> {
fileprivate var screenItems: [CandleStickScreenItem] = []
fileprivate let itemWidth: CGFloat
fileprivate let strokeWidth: CGFloat
public init(xAxis: ChartAxis, yAxis: ChartAxis, chartPoints: [T], itemWidth: CGFloat = 10, strokeWidth: CGFloat = 1) {
self.itemWidth = itemWidth
self.strokeWidth = strokeWidth
super.init(xAxis: xAxis, yAxis: yAxis, chartPoints: chartPoints)
}
open override func chartInitialized(chart: Chart) {
super.chartInitialized(chart: chart)
self.screenItems = generateScreenItems()
}
override open func chartContentViewDrawing(context: CGContext, chart: Chart) {
for screenItem in screenItems {
context.setLineWidth(strokeWidth)
context.setStrokeColor(UIColor.black.cgColor)
context.move(to: CGPoint(x: screenItem.x, y: screenItem.lineTop))
context.addLine(to: CGPoint(x: screenItem.x, y: screenItem.lineBottom))
context.strokePath()
context.setFillColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.0)
context.setFillColor(screenItem.fillColor.cgColor)
context.fill(screenItem.rect)
context.stroke(screenItem.rect)
}
}
fileprivate func generateScreenItems() -> [CandleStickScreenItem] {
return chartPointsModels.map {model in
let chartPoint = model.chartPoint
let x = model.screenLoc.x
let highScreenY = modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.high)).y
let lowScreenY = modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.low)).y
let openScreenY = modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.open)).y
let closeScreenY = modelLocToScreenLoc(x: Double(x), y: Double(chartPoint.close)).y
let (rectTop, rectBottom, fillColor) = closeScreenY < openScreenY ? (closeScreenY, openScreenY, UIColor.white) : (openScreenY, closeScreenY, UIColor.black)
return CandleStickScreenItem(x: x, lineTop: highScreenY, lineBottom: lowScreenY, rectTop: rectTop, rectBottom: rectBottom, width: itemWidth, fillColor: fillColor)
}
}
override func updateChartPointsScreenLocations() {
super.updateChartPointsScreenLocations()
screenItems = generateScreenItems()
}
}
private struct CandleStickScreenItem {
let x: CGFloat
let lineTop: CGFloat
let lineBottom: CGFloat
let fillColor: UIColor
let rect: CGRect
init(x: CGFloat, lineTop: CGFloat, lineBottom: CGFloat, rectTop: CGFloat, rectBottom: CGFloat, width: CGFloat, fillColor: UIColor) {
self.x = x
self.lineTop = lineTop
self.lineBottom = lineBottom
self.rect = CGRect(x: x - (width / 2), y: rectTop, width: width, height: rectBottom - rectTop)
self.fillColor = fillColor
}
}
| 52bec39ea1012eb97965e1f752440d7b | 37.840909 | 174 | 0.656817 | false | false | false | false |
pgherveou/PromiseKit | refs/heads/master | Swift Sources/CLLocationManager+Promise.swift | mit | 1 | import CoreLocation.CLLocationManager
private class LocationManager: CLLocationManager, CLLocationManagerDelegate {
let fulfiller: ([CLLocation]) -> Void
let rejecter: (NSError) -> Void
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
fulfiller(locations as [CLLocation])
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
rejecter(error)
}
init(_ fulfiller: ([CLLocation]) -> Void, _ rejecter: (NSError) -> Void) {
self.fulfiller = fulfiller
self.rejecter = rejecter
super.init()
PMKRetain(self)
delegate = self
}
}
private class AuthorizationCatcher: CLLocationManager, CLLocationManagerDelegate {
let fulfill: (CLAuthorizationStatus) -> Void
init(fulfiller: (CLAuthorizationStatus)->(), auther: (CLLocationManager)->()) {
fulfill = fulfiller
super.init()
let status = CLLocationManager.authorizationStatus()
if status == .NotDetermined {
delegate = self
PMKRetain(self)
auther(self)
} else {
fulfill(status)
}
}
private func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status != .NotDetermined {
fulfill(status)
PMKRelease(self)
}
}
}
private func auther(requestAuthorizationType: CLLocationManager.RequestAuthorizationType)(manager: CLLocationManager)
{
func hasInfoPListKey(key: String) -> Bool {
let value = NSBundle.mainBundle().objectForInfoDictionaryKey("NSLocationAlwaysUsageDescription") as? String ?? ""
return !value.isEmpty
}
#if os(iOS)
switch requestAuthorizationType {
case .Automatic:
let always = hasInfoPListKey("NSLocationAlwaysUsageDescription")
let whenInUse = hasInfoPListKey("NSLocationWhenInUseUsageDescription")
if hasInfoPListKey("NSLocationAlwaysUsageDescription") {
manager.requestAlwaysAuthorization()
} else {
manager.requestWhenInUseAuthorization()
}
case .WhenInUse:
manager.requestWhenInUseAuthorization()
break
case .Always:
manager.requestAlwaysAuthorization()
break
}
#endif
}
extension CLLocationManager {
public enum RequestAuthorizationType {
case Automatic
case Always
case WhenInUse
}
/**
Returns the most recent CLLocation.
@param requestAuthorizationType We read your Info plist and try to
determine the authorization type we should request automatically. If you
want to force one or the other, change this parameter from its default
value.
*/
public class func promise(requestAuthorizationType: RequestAuthorizationType = .Automatic) -> Promise<CLLocation> {
let p: Promise<[CLLocation]> = promise(requestAuthorizationType: requestAuthorizationType)
return p.then { (locations)->CLLocation in
return locations[locations.count - 1]
}
}
/**
Returns the first batch of location objects a CLLocationManager instance
provides.
*/
public class func promise(requestAuthorizationType: RequestAuthorizationType = .Automatic) -> Promise<[CLLocation]> {
return promise(yield: auther(requestAuthorizationType))
}
private class func promise(yield: (CLLocationManager)->() = { _ in }) -> Promise<[CLLocation]> {
let deferred = Promise<[CLLocation]>.defer()
let manager = LocationManager(deferred.fulfill, deferred.reject)
yield(manager)
manager.startUpdatingLocation()
deferred.promise.finally {
manager.delegate = nil
manager.stopUpdatingLocation()
PMKRelease(manager)
}
return deferred.promise
}
/**
Cannot error, despite the fact this might be more useful in some
circumstances, we stick with our decision that errors are errors
and errors only. Thus your catch handler is always catching failures
and not being abused for logic.
*/
public class func requestAuthorization(type: RequestAuthorizationType = .Automatic) -> Promise<CLAuthorizationStatus> {
let d = Promise<CLAuthorizationStatus>.defer()
AuthorizationCatcher(fulfiller: d.fulfill, auther: auther(type))
return d.promise
}
@availability(*, deprecated=1.3.0)
public class func requestAlwaysAuthorization() -> Promise<CLAuthorizationStatus> {
return requestAuthorization(type: .Always)
}
}
| f15b99cd2b0d1a62ca8a11fe53811432 | 32.683453 | 123 | 0.672149 | false | false | false | false |
mahuiying0126/MDemo | refs/heads/master | BangDemo/BangDemo/Modules/Home/viewModel/MHomeViewModel.swift | mit | 1 | //
// MHomeViewModel.swift
// BangDemo
//
// Created by yizhilu on 2017/7/24.
// Copyright © 2017年 Magic. All rights reserved.
//
import UIKit
typealias courseDidSelectModelBlock = (_ cellModel : HomeCourseModel) -> ()
class MHomeViewModel: NSObject,UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
/** *cell点击事件 */
var cellDidSelectEvent : courseDidSelectModelBlock?
func numberOfSections(in collectionView: UICollectionView) -> Int{
return self.dataArray.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
let tempArray:NSArray = self.dataArray[section] as! NSArray
return tempArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell :HomeCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: MHomeViewController.reuseIdentifier, for: indexPath as IndexPath) as! HomeCollectionViewCell
let array = self.dataArray[indexPath.section] as! NSArray
let model = array[indexPath.row] as! HomeCourseModel
cell.cellForModel(model)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
return CGSize.init(width: Screen_width * 0.5, height: Screen_width * 0.41 )
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView{
var view = UICollectionReusableView();
if kind == UICollectionElementKindSectionHeader {
let headView = collectionView .dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: MHomeViewController.reusableView, for: indexPath) as! HomeHeadCollectionReusableView
view = headView
headView.moreBtnBlock = {
///更多课程
}
if indexPath.section == 0 {
headView.recommandLabel?.text = "热门课程"
headView.recommadIcon?.image = UIImage.init(named: "热")
}else{
headView.recommandLabel?.text = "小编推荐"
headView.recommadIcon?.image = UIImage.init(named: "荐")
}
}
return view
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
return CGSize.init(width: Screen_width, height: 50.0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
return 0
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let tempArray = self.dataArray[indexPath.section] as! NSArray
let model = tempArray[indexPath.row] as! HomeCourseModel
self.cellDidSelectEvent!(model)
}
lazy var dataArray : Array<Any> = {
let tempArray = Array<Any>()
return tempArray
}()
}
| 334c8da5d6f5ade1ca1801409ed3a6ae | 40.252874 | 195 | 0.683477 | false | false | false | false |
pixyzehn/MediumScrollFullScreen | refs/heads/master | MediumScrollFullScreen/MediumScrollFullScreen.swift | mit | 1 | //
// MediumMenuInScroll.swift
// MediumMenuInScroll
//
// Created by pixyzehn on 2/14/15.
// Copyright (c) 2015 pixyzehn. All rights reserved.
//
import UIKit
public protocol MediumScrollFullScreenDelegate: class {
func scrollFullScreen(fullScreenProxy: MediumScrollFullScreen, scrollViewDidScrollUp deltaY: CGFloat, userInteractionEnabled enabled: Bool)
func scrollFullScreen(fullScreenProxy: MediumScrollFullScreen, scrollViewDidScrollDown deltaY: CGFloat, userInteractionEnabled enabled: Bool)
func scrollFullScreenScrollViewDidEndDraggingScrollUp(fullScreenProxy: MediumScrollFullScreen, userInteractionEnabled enabled: Bool)
func scrollFullScreenScrollViewDidEndDraggingScrollDown(fullScreenProxy: MediumScrollFullScreen, userInteractionEnabled enabled: Bool)
}
public class MediumScrollFullScreen: NSObject {
public enum Direction {
case None
case Up
case Down
}
private func detectScrollDirection(currentOffsetY: CGFloat, previousOffsetY: CGFloat) -> Direction {
if currentOffsetY > previousOffsetY {
return .Up
} else if currentOffsetY < previousOffsetY {
return .Down
} else {
return .None
}
}
public weak var delegate: MediumScrollFullScreenDelegate?
public var upThresholdY: CGFloat = 0.0
public var downThresholdY: CGFloat = 0.0
public var forwardTarget: UIScrollViewDelegate?
private var previousScrollDirection: Direction = .None
private var previousOffsetY: CGFloat = 0.0
private var accumulatedY: CGFloat = 0.0
override public init() {
super.init()
}
convenience public init(forwardTarget: UIScrollViewDelegate) {
self.init()
self.forwardTarget = forwardTarget
}
}
extension MediumScrollFullScreen: UIScrollViewDelegate {
public func scrollViewDidScroll(scrollView: UIScrollView) {
forwardTarget?.scrollViewDidScroll!(scrollView)
let currentOffsetY = scrollView.contentOffset.y
let currentScrollDirection = detectScrollDirection(currentOffsetY, previousOffsetY: previousOffsetY)
let topBoundary = -scrollView.contentInset.top
let bottomBoundary = scrollView.contentSize.height + scrollView.contentInset.bottom
let isOverTopBoundary = currentOffsetY <= topBoundary
let isOverBottomBoundary = currentOffsetY >= bottomBoundary
let isBouncing = (isOverTopBoundary && currentScrollDirection != .Down) || (isOverBottomBoundary && currentScrollDirection != .Up)
if isBouncing || !scrollView.dragging {
return
}
let deltaY = previousOffsetY - currentOffsetY
accumulatedY += deltaY
switch currentScrollDirection {
case .Up:
let isOverThreshold = accumulatedY < -upThresholdY
if isOverThreshold || isOverBottomBoundary {
if currentOffsetY <= 0 {
delegate?.scrollFullScreen(self, scrollViewDidScrollUp: deltaY, userInteractionEnabled: true)
} else {
delegate?.scrollFullScreen(self, scrollViewDidScrollUp: deltaY, userInteractionEnabled: false)
}
}
case .Down:
let isOverThreshold = accumulatedY > downThresholdY
if isOverThreshold || isOverTopBoundary {
if currentOffsetY <= 0 {
delegate?.scrollFullScreen(self, scrollViewDidScrollDown: deltaY, userInteractionEnabled: true)
} else {
delegate?.scrollFullScreen(self, scrollViewDidScrollDown: deltaY, userInteractionEnabled: false)
}
}
case .None: break
}
if !isOverTopBoundary && !isOverBottomBoundary && previousScrollDirection != currentScrollDirection {
accumulatedY = 0
}
previousScrollDirection = currentScrollDirection
previousOffsetY = currentOffsetY
}
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
forwardTarget?.scrollViewDidEndDragging!(scrollView, willDecelerate: decelerate)
let currentOffsetY = scrollView.contentOffset.y
let topBoundary = -scrollView.contentInset.top
let bottomBoundary = scrollView.contentSize.height + scrollView.contentInset.bottom
switch previousScrollDirection {
case .Up:
let isOverThreshold = accumulatedY < -upThresholdY
let isOverBottomBoundary = currentOffsetY >= bottomBoundary
if isOverBottomBoundary || isOverThreshold {
if currentOffsetY < 0 {
delegate?.scrollFullScreenScrollViewDidEndDraggingScrollUp(self, userInteractionEnabled: true)
} else {
delegate?.scrollFullScreenScrollViewDidEndDraggingScrollUp(self, userInteractionEnabled: false)
}
}
case .Down:
let isOverThreshold = accumulatedY > downThresholdY
let isOverTopBoundary = currentOffsetY <= topBoundary
if isOverThreshold || isOverTopBoundary {
if currentOffsetY < 0 {
delegate?.scrollFullScreenScrollViewDidEndDraggingScrollDown(self, userInteractionEnabled: true)
} else {
delegate?.scrollFullScreenScrollViewDidEndDraggingScrollDown(self, userInteractionEnabled: false)
}
}
case .None: break
}
}
}
public extension UIViewController {
// MARK: NavigationBar
public func showNavigationBar() {
let statusBarHeight = getStatusBarHeight()
let appKeyWindow = UIApplication.sharedApplication().keyWindow!
let appBaseView = appKeyWindow.rootViewController!.view
let viewControllerFrame = appBaseView.convertRect(appBaseView.bounds, toView: appKeyWindow)
let overwrapStatusBarHeight = statusBarHeight - viewControllerFrame.origin.y
setNavigationBarOriginY(overwrapStatusBarHeight)
}
public func hideNavigationBar() {
let navigationBarHeight = navigationController!.navigationBar.frame.size.height
setNavigationBarOriginY(-navigationBarHeight)
}
public func moveNavigationBar(deltaY deltaY: CGFloat) {
let frame = navigationController!.navigationBar.frame
let nextY = frame.origin.y + deltaY
setNavigationBarOriginY(nextY)
}
public func setNavigationBarOriginY(y: CGFloat) {
let statusBarHeight = getStatusBarHeight()
let appKeyWindow = UIApplication.sharedApplication().keyWindow!
let appBaseView = appKeyWindow.rootViewController!.view
let viewControllerFrame = appBaseView.convertRect(appBaseView.bounds, toView: appKeyWindow)
let overwrapStatusBarHeight = statusBarHeight - viewControllerFrame.origin.y
var frame = navigationController!.navigationBar.frame
let navigationBarHeight = frame.size.height
let topLimit = -navigationBarHeight
let bottomLimit = overwrapStatusBarHeight
frame.origin.y = min(max(y, topLimit), bottomLimit)
let navBarHiddenRatio = overwrapStatusBarHeight > 0 ? (overwrapStatusBarHeight - frame.origin.y) / overwrapStatusBarHeight : 0
let alpha = max(1.0 - navBarHiddenRatio, 0.000001)
UIView.animateWithDuration(0.3, animations: {[unowned self]() -> () in
self.navigationController!.navigationBar.frame = frame
var index = 0
for v in self.navigationController!.navigationBar.subviews {
let navView = v
index++
if index == 1 || navView.hidden == true || navView.alpha <= 0.0 {
continue
}
navView.alpha = alpha
}
})
}
private func getStatusBarHeight() -> CGFloat {
let statusBarFrameSize = UIApplication.sharedApplication().statusBarFrame.size
return statusBarFrameSize.height
}
// MARK:ToolBar
public func showToolbar() {
if navigationController?.toolbarHidden == true {
navigationController?.setToolbarHidden(false, animated: true)
}
let viewSize = navigationController!.view.frame.size
let viewHeight = bottomBarViewControlleViewHeightFromViewSize(viewSize)
let toolbarHeight = navigationController!.toolbar.frame.size.height
setToolbarOriginY(y: viewHeight - toolbarHeight)
}
public func hideToolbar() {
let viewSize = navigationController!.view.frame.size
let viewHeight = bottomBarViewControlleViewHeightFromViewSize(viewSize)
setToolbarOriginY(y: viewHeight)
}
public func moveToolbar(deltaY deltaY: CGFloat) {
let frame = navigationController!.toolbar.frame
let nextY = frame.origin.y + deltaY
setToolbarOriginY(y: nextY)
}
public func setToolbarOriginY(y y: CGFloat) {
var frame = navigationController!.toolbar.frame
let toolBarHeight = frame.size.height
let viewSize = navigationController!.view.frame.size
let viewHeight = bottomBarViewControlleViewHeightFromViewSize(viewSize)
let topLimit = viewHeight - toolBarHeight
let bottomLimit = viewHeight
frame.origin.y = fmin(fmax(y, topLimit), bottomLimit)
UIView.animateWithDuration(0.3, animations: {[unowned self]() -> () in
self.navigationController!.toolbar.frame = frame
})
}
private func bottomBarViewControlleViewHeightFromViewSize(viewSize: CGSize) -> CGFloat {
var viewHeight: CGFloat = 0.0
viewHeight += viewSize.height
return viewHeight
}
}
public extension UINavigationBar {
public override func sizeThatFits(size: CGSize) -> CGSize {
return CGSizeMake(UIScreen.mainScreen().bounds.size.width, 60)
}
}
public extension UIToolbar {
public override func sizeThatFits(size: CGSize) -> CGSize {
return CGSizeMake(UIScreen.mainScreen().bounds.size.width, 60)
}
}
| 65e59c256cfa9f0c629708888263d08c | 39.451737 | 145 | 0.655818 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/GIFPlayerView.swift | gpl-2.0 | 1 | //
// GIFPlayerView.swift
// Telegram-Mac
//
// Created by keepcoder on 10/11/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import AVFoundation
import SwiftSignalKit
final class CIStickerContext : CIContext {
deinit {
var bp:Int = 0
bp += 1
}
}
private class AlphaFrameFilter: CIFilter {
static var kernel: CIColorKernel? = {
return CIColorKernel(source: """
kernel vec4 alphaFrame(__sample s, __sample m) {
return vec4( s.rgb, m.r );
}
""")
}()
var inputImage: CIImage?
var maskImage: CIImage?
override var outputImage: CIImage? {
let kernel = AlphaFrameFilter.kernel!
guard let inputImage = inputImage, let maskImage = maskImage else {
return nil
}
let args = [inputImage as AnyObject, maskImage as AnyObject]
return kernel.apply(extent: inputImage.extent, arguments: args)
}
}
let sampleBufferQueue = DispatchQueue.init(label: "sampleBufferQueue", qos: DispatchQoS.background, attributes: [])
private let veryLongTimeInterval = CFTimeInterval(8073216000)
struct AVGifData : Equatable {
let asset: AVURLAsset
let track: AVAssetTrack
let animatedSticker: Bool
let swapOnComplete: Bool
private init(asset: AVURLAsset, track: AVAssetTrack, animatedSticker: Bool, swapOnComplete: Bool) {
self.asset = asset
self.track = track
self.swapOnComplete = swapOnComplete
self.animatedSticker = animatedSticker
}
static func dataFrom(_ path: String?, animatedSticker: Bool = false, swapOnComplete: Bool = false) -> AVGifData? {
let new = link(path: path, ext: "mp4")
if let new = new {
let avAsset = AVURLAsset(url: URL(fileURLWithPath: new))
let t = avAsset.tracks(withMediaType: .video).first
if let t = t {
return AVGifData(asset: avAsset, track: t, animatedSticker: animatedSticker, swapOnComplete: swapOnComplete)
}
}
return nil
}
static func ==(lhs: AVGifData, rhs: AVGifData) -> Bool {
return lhs.asset.url == rhs.asset.url && lhs.animatedSticker == rhs.animatedSticker
}
}
private final class TAVSampleBufferDisplayLayer : AVSampleBufferDisplayLayer {
deinit {
}
}
class GIFPlayerView: TransformImageView {
enum LoopActionResult {
case pause
}
private let sampleLayer:TAVSampleBufferDisplayLayer = TAVSampleBufferDisplayLayer()
private var _reader:Atomic<AVAssetReader?> = Atomic(value:nil)
private var _asset:Atomic<AVURLAsset?> = Atomic(value:nil)
private let _output:Atomic<AVAssetReaderTrackOutput?> = Atomic(value:nil)
private let _track:Atomic<AVAssetTrack?> = Atomic(value:nil)
private let _needReset:Atomic<Bool> = Atomic(value:false)
private let _timer:Atomic<CFRunLoopTimer?> = Atomic(value:nil)
private let _loopAction:Atomic<(()->LoopActionResult)?> = Atomic(value:nil)
private let _timebase:Atomic<CMTimebase?> = Atomic(value:nil)
private let _stopRequesting:Atomic<Bool> = Atomic(value:false)
private let _swapNext:Atomic<Bool> = Atomic(value:true)
private let _data:Atomic<AVGifData?> = Atomic(value:nil)
func setLoopAction(_ action:(()->LoopActionResult)?) {
_ = _loopAction.swap(action)
}
private let maskLayer = CAShapeLayer()
var positionFlags: LayoutPositionFlags? {
didSet {
if let positionFlags = positionFlags {
let path = CGMutablePath()
let minx:CGFloat = 0, midx = frame.width/2.0, maxx = frame.width
let miny:CGFloat = 0, midy = frame.height/2.0, maxy = frame.height
path.move(to: NSMakePoint(minx, midy))
var topLeftRadius: CGFloat = .cornerRadius
var bottomLeftRadius: CGFloat = .cornerRadius
var topRightRadius: CGFloat = .cornerRadius
var bottomRightRadius: CGFloat = .cornerRadius
if positionFlags.contains(.top) && positionFlags.contains(.left) {
bottomLeftRadius = .cornerRadius * 3 + 2
}
if positionFlags.contains(.top) && positionFlags.contains(.right) {
bottomRightRadius = .cornerRadius * 3 + 2
}
if positionFlags.contains(.bottom) && positionFlags.contains(.left) {
topLeftRadius = .cornerRadius * 3 + 2
}
if positionFlags.contains(.bottom) && positionFlags.contains(.right) {
topRightRadius = .cornerRadius * 3 + 2
}
path.addArc(tangent1End: NSMakePoint(minx, miny), tangent2End: NSMakePoint(midx, miny), radius: bottomLeftRadius)
path.addArc(tangent1End: NSMakePoint(maxx, miny), tangent2End: NSMakePoint(maxx, midy), radius: bottomRightRadius)
path.addArc(tangent1End: NSMakePoint(maxx, maxy), tangent2End: NSMakePoint(midx, maxy), radius: topRightRadius)
path.addArc(tangent1End: NSMakePoint(minx, maxy), tangent2End: NSMakePoint(minx, midy), radius: topLeftRadius)
maskLayer.path = path
layer?.mask = maskLayer
} else {
layer?.mask = nil
}
}
}
override init() {
super.init()
sampleLayer.actions = ["onOrderIn":NSNull(),"sublayers":NSNull(),"bounds":NSNull(),"frame":NSNull(),"position":NSNull(),"contents":NSNull(),"opacity":NSNull(), "transform": NSNull()
]
sampleLayer.videoGravity = .resizeAspect
sampleLayer.backgroundColor = NSColor.clear.cgColor
layer?.addSublayer(sampleLayer)
}
func setVideoLayerGravity(_ gravity: AVLayerVideoGravity) {
sampleLayer.videoGravity = gravity
}
var controlTimebase: CMTimebase? {
return sampleLayer.controlTimebase
}
var isHasData: Bool {
return _data.modify({$0}) != nil
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layout() {
super.layout()
sampleLayer.frame = bounds
}
override func setFrameSize(_ newSize: NSSize) {
super.setFrameSize(newSize)
sampleLayer.frame = bounds
}
func set(data: AVGifData?, timebase:CMTimebase? = nil) -> Void {
assertOnMainThread()
if data != _data.swap(data) {
_ = _timebase.swap(timebase)
let _data = self._data
let layer:AVSampleBufferDisplayLayer = self.sampleLayer
let reader = self._reader
let output = self._output
let reset = self._needReset
let stopRequesting = self._stopRequesting
let swapNext = self._swapNext
let track = self._track
let asset = self._asset
let timer = self._timer
let timebase = self._timebase
let loopAction = self._loopAction
if let data = data {
let _ = track.swap(data.track)
let _ = asset.swap(data.asset)
_ = stopRequesting.swap(false)
if data.swapOnComplete {
_ = timebase.swap(self.controlTimebase)
}
_ = swapNext.swap(true)
} else {
_ = asset.swap(nil)
_ = track.swap(nil)
_ = stopRequesting.swap(true)
_ = swapNext.swap(false)
return
}
layer.requestMediaDataWhenReady(on: sampleBufferQueue, using: {
if stopRequesting.swap(false) {
if let controlTimebase = layer.controlTimebase, let current = timer.swap(nil) {
CMTimebaseRemoveTimer(controlTimebase, timer: current)
_ = timebase.swap(nil)
}
layer.stopRequestingMediaData()
layer.flushAndRemoveImage()
var reader = reader.swap(nil)
Queue.concurrentBackgroundQueue().async {
reader?.cancelReading()
reader = nil
}
return
}
if swapNext.swap(false) {
_ = output.swap(nil)
var reader = reader.swap(nil)
Queue.concurrentBackgroundQueue().async {
reader?.cancelReading()
reader = nil
}
}
if let readerValue = reader.with({ $0 }), let outputValue = output.with({ $0 }) {
let affineTransform = track.with { $0?.preferredTransform.inverted() }
if let affineTransform = affineTransform {
layer.setAffineTransform(affineTransform)
}
while layer.isReadyForMoreMediaData {
if !stopRequesting.with({ $0 }) {
if readerValue.status == .reading, let sampleBuffer = outputValue.copyNextSampleBuffer() {
layer.enqueue(sampleBuffer)
continue
}
_ = stopRequesting.modify { _ in _data.with { $0 } == nil }
break
} else {
break
}
}
if readerValue.status == .completed || readerValue.status == .cancelled {
if reset.swap(false) {
let loopActionResult = loopAction.with({ $0?() })
if let loopActionResult = loopActionResult {
switch loopActionResult {
case .pause:
return
}
}
let result = restartReading(_reader: reader, _asset: asset, _track: track, _output: output, _needReset: reset, _timer: timer, layer: layer, _timebase: timebase)
if result {
layer.flush()
}
}
}
} else if !stopRequesting.modify({$0}) {
let result = restartReading(_reader: reader, _asset: asset, _track: track, _output: output, _needReset: reset, _timer: timer, layer: layer, _timebase: timebase)
if result {
layer.flush()
}
}
})
}
}
func reset(with timebase:CMTimebase? = nil, _ resetImage: Bool = true) {
// if resetImage {
sampleLayer.flushAndRemoveImage()
// } else {
// sampleLayer.flush()
// }
_ = _swapNext.swap(true)
_ = _timebase.swap(timebase)
}
deinit {
_ = _stopRequesting.swap(true)
}
required convenience init(frame frameRect: NSRect) {
self.init()
}
}
fileprivate func restartReading(_reader:Atomic<AVAssetReader?>, _asset:Atomic<AVURLAsset?>, _track:Atomic<AVAssetTrack?>, _output:Atomic<AVAssetReaderTrackOutput?>, _needReset:Atomic<Bool>, _timer:Atomic<CFRunLoopTimer?>, layer: AVSampleBufferDisplayLayer, _timebase:Atomic<CMTimebase?>) -> Bool {
if let timebase = layer.controlTimebase, let timer = _timer.modify({$0}) {
_ = _timer.swap(nil)
CMTimebaseRemoveTimer(timebase, timer: timer)
}
if let asset = _asset.modify({$0}), let track = _track.modify({$0}) {
let _ = _reader.swap(try? AVAssetReader(asset: asset))
if let reader = _reader.modify({$0}) {
var params:[String:Any] = [:]
params[kCVPixelBufferPixelFormatTypeKey as String] = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
let _ = _output.swap(AVAssetReaderTrackOutput(track: track, outputSettings: params))
if let output = _output.modify({$0}) {
output.alwaysCopiesSampleData = false
if reader.canAdd(output) {
reader.add(output)
var timebase:CMTimebase? = _timebase.swap(nil)
if timebase == nil {
CMTimebaseCreateWithMasterClock( allocator: kCFAllocatorDefault, masterClock: CMClockGetHostTimeClock(), timebaseOut: &timebase )
CMTimebaseSetRate(timebase!, rate: 1.0)
}
if let timebase = timebase {
reader.timeRange = CMTimeRangeMake(start: CMTimebaseGetTime(timebase), duration: asset.duration)
let runLoop = CFRunLoopGetMain()
var context = CFRunLoopTimerContext()
context.info = UnsafeMutableRawPointer(Unmanaged.passRetained(_needReset).toOpaque())
let timer = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent(), veryLongTimeInterval, 0, 0, {
(cfRunloopTimer, info) -> Void in
if let info = info {
let s = Unmanaged<Atomic<Bool>>.fromOpaque(info).takeUnretainedValue()
_ = s.swap(true)
}
}, &context);
if let timer = timer, let runLoop = runLoop {
_ = _timer.swap(timer)
CMTimebaseAddTimer(timebase, timer: timer, runloop: runLoop)
CFRunLoopAddTimer(runLoop, timer, CFRunLoopMode.defaultMode);
CMTimebaseSetTimerNextFireTime(timebase, timer: timer, fireTime: asset.duration, flags: 0)
}
layer.controlTimebase = timebase
}
reader.startReading()
return true
}
}
}
}
return false
}
/*
if isAnimatedSticker {
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
var newSampleBuffer:CMSampleBuffer? = nil
if let imageBuffer = imageBuffer {
let sourceImage = CIImage(cvImageBuffer: imageBuffer)
var cvPixelBuffer: CVPixelBuffer?
let videoSize = CGSize(width: 400, height: 400)
CVPixelBufferCreate(nil, 400, 400, kCVPixelFormatType_32BGRA, nil, &cvPixelBuffer)
if let cvPixelBuffer = cvPixelBuffer {
let sourceRect = CGRect(origin: .zero, size: videoSize)
let alphaRect = sourceRect.offsetBy(dx: 0, dy: sourceRect.height)
let filter = AlphaFrameFilter()
filter.inputImage = sourceImage.cropped(to: alphaRect)
.transformed(by: CGAffineTransform(translationX: 0, y: -sourceRect.height))
filter.maskImage = sourceImage.cropped(to: sourceRect)
let outputImage = filter.outputImage!
context.render(outputImage, to: cvPixelBuffer)
var formatRef: CMVideoFormatDescription?
let _ = CMVideoFormatDescriptionCreateForImageBuffer(allocator: kCFAllocatorDefault, imageBuffer: cvPixelBuffer, formatDescriptionOut: &formatRef)
var sampleTimingInfo: CMSampleTimingInfo = CMSampleTimingInfo()
CMSampleBufferGetSampleTimingInfo(sampleBuffer, at: 0, timingInfoOut: &sampleTimingInfo)
CMSampleBufferCreateReadyWithImageBuffer(allocator: nil, imageBuffer: cvPixelBuffer, formatDescription: formatRef!, sampleTiming: &sampleTimingInfo, sampleBufferOut: &newSampleBuffer)
if let newSampleBuffer = newSampleBuffer {
sampleBuffer = newSampleBuffer
}
}
}
}
*/
| dee0f6636cdeb5e0b8c28464ba2bc17b | 36.487585 | 297 | 0.542301 | false | false | false | false |
JadenGeller/Generational | refs/heads/master | Sources/Cycle.swift | mit | 1 | //
// Cycle.swift
// Generational
//
// Created by Jaden Geller on 12/28/15.
// Copyright © 2015 Jaden Geller. All rights reserved.
//
public struct CyclicSequence<Base: CollectionType>: SequenceType {
private let base: Base
public init(_ base: Base) {
self.base = base
}
public func generate() -> CyclicGenerator<Base> {
return CyclicGenerator(base)
}
}
public struct CyclicGenerator<Base: CollectionType>: GeneratorType {
private let base: Base
private var index: Base.Index
public init(_ base: Base) {
self.base = base
self.index = base.startIndex
}
public mutating func next() -> Base.Generator.Element? {
let value = base[index]
index = index.successor()
if index == base.endIndex { index = base.startIndex }
return value
}
}
extension CollectionType {
func cycle() -> CyclicSequence<Self> {
return CyclicSequence(self)
}
} | 1e56a8b98f7ac9f9376b4aca25f7d565 | 22.333333 | 68 | 0.624106 | false | false | false | false |
valleyman86/ReactiveCocoa | refs/heads/swift-development | ReactiveCocoa/Swift/Signal.swift | mit | 1 | import Result
/// A push-driven stream that sends Events over time, parameterized by the type
/// of values being sent (`T`) and the type of error that can occur (`E`). If no
/// errors should be possible, NoError can be specified for `E`.
///
/// An observer of a Signal will see the exact same sequence of events as all
/// other observers. In other words, events will be sent to all observers at the
/// same time.
///
/// Signals are generally used to represent event streams that are already “in
/// progress,” like notifications, user input, etc. To represent streams that
/// must first be _started_, see the SignalProducer type.
///
/// Signals do not need to be retained. A Signal will be automatically kept
/// alive until the event stream has terminated.
public final class Signal<T, E: ErrorType> {
public typealias Observer = SinkOf<Event<T, E>>
private let lock = NSRecursiveLock()
private var observers: Bag<Observer>? = Bag()
/// Initializes a Signal that will immediately invoke the given generator,
/// then forward events sent to the given observer.
///
/// The Signal will remain alive until a terminating event is sent to the
/// observer, at which point the disposable returned from the closure will
/// be disposed as well.
public init(_ generator: Observer -> Disposable?) {
lock.name = "org.reactivecocoa.ReactiveCocoa.Signal"
let generatorDisposable = SerialDisposable()
let sink = Observer { event in
self.lock.lock()
if let observers = self.observers {
if event.isTerminating {
// Disallow any further events (e.g., any triggered
// recursively).
self.observers = nil
}
for sink in observers {
sink.put(event)
}
if event.isTerminating {
// Dispose only after notifying observers, so disposal logic
// is consistently the last thing to run.
generatorDisposable.dispose()
}
}
self.lock.unlock()
}
generatorDisposable.innerDisposable = generator(sink)
}
/// A Signal that never sends any events to its observers.
public class var never: Signal {
return self { _ in nil }
}
/// Creates a Signal that will be controlled by sending events to the given
/// observer (sink).
///
/// The Signal will remain alive until a terminating event is sent to the
/// observer.
public class func pipe() -> (Signal, Observer) {
var sink: Observer!
let signal = self { innerSink in
sink = innerSink
return nil
}
return (signal, sink)
}
/// Observes the Signal by sending any future events to the given sink. If
/// the Signal has already terminated, the sink will immediately receive an
/// `Interrupted` event.
///
/// Returns a Disposable which can be used to disconnect the sink. Disposing
/// of the Disposable will have no effect on the Signal itself.
public func observe<S: SinkType where S.Element == Event<T, E>>(observer: S) -> Disposable? {
let sink = Observer(observer)
lock.lock()
let token = self.observers?.insert(sink)
lock.unlock()
if let token = token {
return ActionDisposable {
self.lock.lock()
self.observers?.removeValueForToken(token)
self.lock.unlock()
}
} else {
sink.put(.Interrupted)
return nil
}
}
/// Observes the Signal by invoking the given callbacks when events are
/// received. If the Signal has already terminated, the `interrupted`
/// callback will be invoked immediately.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callbacks. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observe(error: (E -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, next: (T -> ())? = nil) -> Disposable? {
return observe(Event.sink(next: next, error: error, completed: completed, interrupted: interrupted))
}
}
infix operator |> {
associativity left
// Bind tighter than assignment, but looser than everything else.
precedence 95
}
/// Applies a Signal operator to a Signal.
///
/// Example:
///
/// intSignal
/// |> filter { num in num % 2 == 0 }
/// |> map(toString)
/// |> observe(next: { string in println(string) })
public func |> <T, E, X>(signal: Signal<T, E>, @noescape transform: Signal<T, E> -> X) -> X {
return transform(signal)
}
/// Maps each value in the signal to a new value.
public func map<T, U, E>(transform: T -> U)(signal: Signal<T, E>) -> Signal<U, E> {
return Signal { observer in
return signal.observe(Signal.Observer { event in
observer.put(event.map(transform))
})
}
}
/// Maps errors in the signal to a new error.
public func mapError<T, E, F>(transform: E -> F)(signal: Signal<T, E>) -> Signal<T, F> {
return Signal { observer in
return signal.observe(Signal.Observer { event in
switch event {
case let .Next(value):
sendNext(observer, value.value)
case let .Error(error):
sendError(observer, transform(error.value))
case .Completed:
sendCompleted(observer)
case .Interrupted:
sendInterrupted(observer)
}
})
}
}
/// Preserves only the values of the signal that pass the given predicate.
public func filter<T, E>(predicate: T -> Bool)(signal: Signal<T, E>) -> Signal<T, E> {
return Signal { observer in
return signal.observe(Signal.Observer { event in
switch event {
case let .Next(value):
if predicate(value.value) {
sendNext(observer, value.value)
}
default:
observer.put(event)
}
})
}
}
/// Unwraps non-`nil` values from `signal` and forwards them on the returned
/// signal, `nil` values are dropped.
public func ignoreNil<T, E>(signal: Signal<T?, E>) -> Signal<T, E> {
return signal |> filter { $0 != nil } |> map { $0! }
}
/// Returns a signal that will yield the first `count` values from the
/// input signal.
public func take<T, E>(count: Int)(signal: Signal<T, E>) -> Signal<T, E> {
precondition(count >= 0)
return Signal { observer in
if count == 0 {
sendCompleted(observer)
return nil
}
var taken = 0
return signal.observe(Signal.Observer { event in
switch event {
case let .Next(value):
if taken < count {
taken++
sendNext(observer, value.value)
}
if taken == count {
sendCompleted(observer)
}
default:
observer.put(event)
}
})
}
}
/// A reference type which wraps an array to avoid copying it for performance and
/// memory usage optimization.
private final class CollectState<T> {
var values: [T] = []
func append(value: T) -> Self {
values.append(value)
return self
}
}
/// Returns a signal that will yield an array of values when `signal` completes.
public func collect<T, E>(signal: Signal<T, E>) -> Signal<[T], E> {
return signal |> reduce(CollectState()) { $0.append($1) } |> map { $0.values }
}
/// Forwards all events onto the given scheduler, instead of whichever
/// scheduler they originally arrived upon.
public func observeOn<T, E>(scheduler: SchedulerType) -> (Signal<T, E>) -> Signal<T, E> {
return { signal in
return Signal { observer in
return signal.observe(Signal.Observer { event in
scheduler.schedule {
observer.put(event)
}
return
})
}
}
}
private final class CombineLatestState<T> {
var latestValue: T?
var completed = false
}
private func observeWithStates<T, U, E>(signalState: CombineLatestState<T>, otherState: CombineLatestState<U>, lock: NSRecursiveLock, onBothNext: () -> (), onError: E -> (), onBothCompleted: () -> (), onInterrupted: () -> ())(signal: Signal<T, E>) -> Disposable? {
return signal.observe(next: { value in
lock.lock()
signalState.latestValue = value
if otherState.latestValue != nil {
onBothNext()
}
lock.unlock()
}, error: onError, completed: {
lock.lock()
signalState.completed = true
if otherState.completed {
onBothCompleted()
}
lock.unlock()
}, interrupted: onInterrupted)
}
/// Combines the latest value of the receiver with the latest value from
/// the given signal.
///
/// The returned signal will not send a value until both inputs have sent
/// at least one value each. If either signal is interrupted, the returned signal
/// will also be interrupted.
public func combineLatestWith<T, U, E>(otherSignal: Signal<U, E>)(signal: Signal<T, E>) -> Signal<(T, U), E> {
return Signal { observer in
let lock = NSRecursiveLock()
lock.name = "org.reactivecocoa.ReactiveCocoa.combineLatestWith"
let signalState = CombineLatestState<T>()
let otherState = CombineLatestState<U>()
let onBothNext = { () -> () in
sendNext(observer, (signalState.latestValue!, otherState.latestValue!))
}
let onError = { sendError(observer, $0) }
let onBothCompleted = { sendCompleted(observer) }
let onInterrupted = { sendInterrupted(observer) }
let signalDisposable = signal |> observeWithStates(signalState, otherState, lock, onBothNext, onError, onBothCompleted, onInterrupted)
let otherDisposable = otherSignal |> observeWithStates(otherState, signalState, lock, onBothNext, onError, onBothCompleted, onInterrupted)
return CompositeDisposable(ignoreNil([ signalDisposable, otherDisposable ]))
}
}
internal func combineLatestWith<T, E>(otherSignal: Signal<T, E>)(signal: Signal<[T], E>) -> Signal<[T], E> {
return signal |> combineLatestWith(otherSignal) |> map { $0.0 + [$0.1] }
}
/// Delays `Next` and `Completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// `Error` and `Interrupted` events are always scheduled immediately.
public func delay<T, E>(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<T, E> -> Signal<T, E> {
precondition(interval >= 0)
return { signal in
return Signal { observer in
return signal.observe(Signal.Observer { event in
switch event {
case .Error, .Interrupted:
scheduler.schedule {
observer.put(event)
}
default:
let date = scheduler.currentDate.dateByAddingTimeInterval(interval)
scheduler.scheduleAfter(date) {
observer.put(event)
}
}
})
}
}
}
/// Returns a signal that will skip the first `count` values, then forward
/// everything afterward.
public func skip<T, E>(count: Int)(signal: Signal<T, E>) -> Signal<T, E> {
precondition(count >= 0)
if (count == 0) {
return signal
}
return Signal { observer in
var skipped = 0
return signal.observe(Signal.Observer { event in
switch event {
case let .Next(value):
if skipped >= count {
fallthrough
} else {
skipped++
}
default:
observer.put(event)
}
})
}
}
/// Treats all Events from the input signal as plain values, allowing them to be
/// manipulated just like any other value.
///
/// In other words, this brings Events “into the monad.”
public func materialize<T, E>(signal: Signal<T, E>) -> Signal<Event<T, E>, NoError> {
return Signal { observer in
return signal.observe(Signal.Observer { event in
sendNext(observer, event)
if event.isTerminating {
sendCompleted(observer)
}
})
}
}
/// The inverse of materialize(), this will translate a signal of `Event`
/// _values_ into a signal of those events themselves.
public func dematerialize<T, E>(signal: Signal<Event<T, E>, NoError>) -> Signal<T, E> {
return Signal { observer in
return signal.observe(Signal.Observer { event in
switch event {
case let .Next(innerEvent):
observer.put(innerEvent.value)
case .Error:
fatalError()
case .Completed:
sendCompleted(observer)
case .Interrupted:
sendInterrupted(observer)
}
})
}
}
private struct SampleState<T> {
var latestValue: T? = nil
var signalCompleted: Bool = false
var samplerCompleted: Bool = false
}
/// Forwards the latest value from `signal` whenever `sampler` sends a Next
/// event.
///
/// If `sampler` fires before a value has been observed on `signal`, nothing
/// happens.
///
/// Returns a signal that will send values from `signal`, sampled (possibly
/// multiple times) by `sampler`, then complete once both input signals have
/// completed, or interrupt if either input signal is interrupted.
public func sampleOn<T, E>(sampler: Signal<(), NoError>)(signal: Signal<T, E>) -> Signal<T, E> {
return Signal { observer in
let state = Atomic(SampleState<T>())
let signalDisposable = signal.observe(next: { value in
state.modify { (var st) in
st.latestValue = value
return st
}
return
}, error: { error in
sendError(observer, error)
}, completed: {
let oldState = state.modify { (var st) in
st.signalCompleted = true
return st
}
if oldState.samplerCompleted {
sendCompleted(observer)
}
}, interrupted: {
sendInterrupted(observer)
})
let samplerDisposable = sampler.observe(next: { _ in
if let value = state.value.latestValue {
sendNext(observer, value)
}
}, completed: {
let oldState = state.modify { (var st) in
st.samplerCompleted = true
return st
}
if oldState.signalCompleted {
sendCompleted(observer)
}
}, interrupted: {
sendInterrupted(observer)
})
return CompositeDisposable(ignoreNil([ signalDisposable, samplerDisposable ]))
}
}
/// Forwards events from `signal` until `trigger` sends a Next or Completed
/// event, at which point the returned signal will complete.
public func takeUntil<T, E>(trigger: Signal<(), NoError>)(signal: Signal<T, E>) -> Signal<T, E> {
return Signal { observer in
let signalDisposable = signal.observe(observer)
let triggerDisposable = trigger.observe(Signal.Observer { event in
switch event {
case .Next, .Completed:
sendCompleted(observer)
case .Error, .Interrupted:
break
}
})
return CompositeDisposable(ignoreNil([ signalDisposable, triggerDisposable ]))
}
}
/// Forwards events from `signal` with history: values of the returned signal
/// are a tuple whose first member is the previous value and whose second member
/// is the current value. `initial` is supplied as the first member when `signal`
/// sends its first value.
public func combinePrevious<T, E>(initial: T) -> Signal<T, E> -> Signal<(T, T), E> {
return { signal in
return signal |> scan((initial, initial)) { previousCombinedValues, newValue in
return (previousCombinedValues.1, newValue)
}
}
}
/// Like `scan`, but sends only the final value and then immediately completes.
public func reduce<T, U, E>(initial: U, combine: (U, T) -> U) -> Signal<T, E> -> Signal<U, E> {
return { signal in
// We need to handle the special case in which `signal` sends no values.
// We'll do that by sending `initial` on the output signal (before taking
// the last value).
let (scannedSignalWithInitialValue: Signal<U, E>, outputSignalObserver) = Signal.pipe()
let outputSignal = scannedSignalWithInitialValue |> takeLast(1)
// Now that we've got takeLast() listening to the piped signal, send that initial value.
sendNext(outputSignalObserver, initial)
// Pipe the scanned input signal into the output signal.
signal |> scan(initial, combine) |> observe(outputSignalObserver)
return outputSignal
}
}
/// Aggregates `signal`'s values into a single combined value. When `signal` emits
/// its first value, `combine` is invoked with `initial` as the first argument and
/// that emitted value as the second argument. The result is emitted from the
/// signal returned from `reduce`. That result is then passed to `combine` as the
/// first argument when the next value is emitted, and so on.
public func scan<T, U, E>(initial: U, combine: (U, T) -> U) -> Signal<T, E> -> Signal<U, E> {
return { signal in
return Signal { observer in
var accumulator = initial
return signal.observe(Signal.Observer { event in
observer.put(event.map { value in
accumulator = combine(accumulator, value)
return accumulator
})
})
}
}
}
/// Forwards only those values from `signal` which are not duplicates of the
/// immedately preceding value. The first value is always forwarded.
public func skipRepeats<T: Equatable, E>(signal: Signal<T, E>) -> Signal<T, E> {
return signal |> skipRepeats { $0 == $1 }
}
/// Forwards only those values from `signal` which do not pass `isRepeat` with
/// respect to the previous value. The first value is always forwarded.
public func skipRepeats<T, E>(isRepeat: (T, T) -> Bool)(signal: Signal<T, E>) -> Signal<T, E> {
return signal
|> map { Optional($0) }
|> combinePrevious(nil)
|> filter { (a, b) in
if let a = a, b = b where isRepeat(a, b) {
return false
} else {
return true
}
}
|> map { $0.1! }
}
/// Does not forward any values from `signal` until `predicate` returns false,
/// at which point the returned signal behaves exactly like `signal`.
public func skipWhile<T, E>(predicate: T -> Bool)(signal: Signal<T, E>) -> Signal<T, E> {
return Signal { observer in
var shouldSkip = true
return signal.observe(Signal.Observer { event in
switch event {
case let .Next(value):
shouldSkip = shouldSkip && predicate(value.value)
if !shouldSkip {
fallthrough
}
default:
observer.put(event)
}
})
}
}
/// Forwards events from `signal` until `replacement` begins sending events.
///
/// Returns a signal which passes through `Next`, `Error`, and `Interrupted`
/// events from `signal` until `replacement` sends an event, at which point the
/// returned signal will send that event and switch to passing through events
/// from `replacement` instead, regardless of whether `signal` has sent events
/// already.
public func takeUntilReplacement<T, E>(replacement: Signal<T, E>)(signal: Signal<T, E>) -> Signal<T, E> {
return Signal { observer in
let signalDisposable = signal.observe(Signal.Observer { event in
switch event {
case .Completed:
break
case .Next, .Error, .Interrupted:
observer.put(event)
}
})
let replacementDisposable = replacement.observe(Signal.Observer { event in
signalDisposable?.dispose()
observer.put(event)
})
return CompositeDisposable(ignoreNil([ signalDisposable, replacementDisposable ]))
}
}
/// Waits until `signal` completes and then forwards the final `count` values
/// on the returned signal.
public func takeLast<T, E>(count: Int)(signal: Signal<T, E>) -> Signal<T, E> {
return Signal { observer in
var buffer = [T]()
buffer.reserveCapacity(count)
return signal.observe(next: { value in
// To avoid exceeding the reserved capacity of the buffer, we remove then add.
// Remove elements until we have room to add one more.
while (buffer.count + 1) > count {
buffer.removeAtIndex(0)
}
buffer.append(value)
}, error: { error in
sendError(observer, error)
}, completed: {
for bufferedValue in buffer {
sendNext(observer, bufferedValue)
}
sendCompleted(observer)
}, interrupted: {
sendInterrupted(observer)
})
}
}
/// Forwards any values from `signal` until `predicate` returns false,
/// at which point the returned signal will complete.
public func takeWhile<T, E>(predicate: T -> Bool)(signal: Signal<T, E>) -> Signal<T, E> {
return Signal { observer in
return signal.observe(Signal.Observer { event in
switch event {
case let .Next(value):
if predicate(value.value) {
fallthrough
} else {
sendCompleted(observer)
}
default:
observer.put(event)
}
})
}
}
private struct ZipState<T> {
var values: [T] = []
var completed = false
var isFinished: Bool {
return values.isEmpty && completed
}
}
/// Zips elements of two signals into pairs. The elements of any Nth pair
/// are the Nth elements of the two input signals.
public func zipWith<T, U, E>(otherSignal: Signal<U, E>)(signal: Signal<T, E>) -> Signal<(T, U), E> {
return Signal { observer in
let initialStates: (ZipState<T>, ZipState<U>) = (ZipState(), ZipState())
let states: Atomic<(ZipState<T>, ZipState<U>)> = Atomic(initialStates)
let flush = { () -> () in
var originalStates: (ZipState<T>, ZipState<U>)!
states.modify { states in
originalStates = states
var updatedStates = states
let extractCount = min(states.0.values.count, states.1.values.count)
removeRange(&updatedStates.0.values, 0 ..< extractCount)
removeRange(&updatedStates.1.values, 0 ..< extractCount)
return updatedStates
}
while !originalStates.0.values.isEmpty && !originalStates.1.values.isEmpty {
let left = originalStates.0.values.removeAtIndex(0)
let right = originalStates.1.values.removeAtIndex(0)
sendNext(observer, (left, right))
}
if originalStates.0.isFinished || originalStates.1.isFinished {
sendCompleted(observer)
}
}
let onError = { sendError(observer, $0) }
let onInterrupted = { sendInterrupted(observer) }
let signalDisposable = signal.observe(next: { value in
states.modify { (var states) in
states.0.values.append(value)
return states
}
flush()
}, error: onError, completed: {
states.modify { (var states) in
states.0.completed = true
return states
}
flush()
}, interrupted: onInterrupted)
let otherDisposable = otherSignal.observe(next: { value in
states.modify { (var states) in
states.1.values.append(value)
return states
}
flush()
}, error: onError, completed: {
states.modify { (var states) in
states.1.completed = true
return states
}
flush()
}, interrupted: onInterrupted)
return CompositeDisposable(ignoreNil([ signalDisposable, otherDisposable ]))
}
}
internal func zipWith<T, E>(otherSignal: Signal<T, E>)(signal: Signal<[T], E>) -> Signal<[T], E> {
return signal |> zipWith(otherSignal) |> map { $0.0 + [$0.1] }
}
/// Applies `operation` to values from `signal` with `Success`ful results
/// forwarded on the returned signal and `Failure`s sent as `Error` events.
public func try<T, E>(operation: T -> Result<(), E>)(signal: Signal<T, E>) -> Signal<T, E> {
return signal |> tryMap { value in
return operation(value).map {
return value
}
}
}
/// Applies `operation` to values from `signal` with `Success`ful results mapped
/// on the returned signal and `Failure`s sent as `Error` events.
public func tryMap<T, U, E>(operation: T -> Result<U, E>)(signal: Signal<T, E>) -> Signal<U, E> {
return Signal { observer in
signal.observe(next: { value in
operation(value).analysis(ifSuccess: { value in
sendNext(observer, value)
}, ifFailure: { error in
sendError(observer, error)
})
}, error: { error in
sendError(observer, error)
}, completed: {
sendCompleted(observer)
}, interrupted: {
sendInterrupted(observer)
})
}
}
/// Throttle values sent by the receiver, so that at least `interval`
/// seconds pass between each, then forwards them on the given scheduler.
///
/// If multiple values are received before the interval has elapsed, the
/// latest value is the one that will be passed on.
///
/// If the input signal terminates while a value is being throttled, that value
/// will be discarded and the returned signal will terminate immediately.
public func throttle<T, E>(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<T, E> -> Signal<T, E> {
precondition(interval >= 0)
return { signal in
return Signal { observer in
let state: Atomic<ThrottleState<T>> = Atomic(ThrottleState())
let schedulerDisposable = SerialDisposable()
let disposable = CompositeDisposable()
disposable.addDisposable(schedulerDisposable)
let signalDisposable = signal.observe(Signal.Observer { event in
switch event {
case let .Next(value):
var scheduleDate: NSDate!
state.modify { (var state) in
state.pendingValue = value.value
let proposedScheduleDate = state.previousDate?.dateByAddingTimeInterval(interval) ?? scheduler.currentDate
scheduleDate = proposedScheduleDate.laterDate(scheduler.currentDate)
return state
}
schedulerDisposable.innerDisposable = scheduler.scheduleAfter(scheduleDate) {
let previousState = state.modify { (var state) in
if state.pendingValue != nil {
state.pendingValue = nil
state.previousDate = scheduleDate
}
return state
}
if let pendingValue = previousState.pendingValue {
sendNext(observer, pendingValue)
}
}
default:
schedulerDisposable.innerDisposable = scheduler.schedule {
observer.put(event)
}
}
})
disposable.addDisposable(signalDisposable)
return disposable
}
}
}
private struct ThrottleState<T> {
var previousDate: NSDate? = nil
var pendingValue: T? = nil
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public func combineLatest<A, B, Error>(a: Signal<A, Error>, b: Signal<B, Error>) -> Signal<(A, B), Error> {
return a |> combineLatestWith(b)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public func combineLatest<A, B, C, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>) -> Signal<(A, B, C), Error> {
return combineLatest(a, b)
|> combineLatestWith(c)
|> map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public func combineLatest<A, B, C, D, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>) -> Signal<(A, B, C, D), Error> {
return combineLatest(a, b, c)
|> combineLatestWith(d)
|> map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public func combineLatest<A, B, C, D, E, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>, e: Signal<E, Error>) -> Signal<(A, B, C, D, E), Error> {
return combineLatest(a, b, c, d)
|> combineLatestWith(e)
|> map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public func combineLatest<A, B, C, D, E, F, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>, e: Signal<E, Error>, f: Signal<F, Error>) -> Signal<(A, B, C, D, E, F), Error> {
return combineLatest(a, b, c, d, e)
|> combineLatestWith(f)
|> map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public func combineLatest<A, B, C, D, E, F, G, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>, e: Signal<E, Error>, f: Signal<F, Error>, g: Signal<G, Error>) -> Signal<(A, B, C, D, E, F, G), Error> {
return combineLatest(a, b, c, d, e, f)
|> combineLatestWith(g)
|> map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public func combineLatest<A, B, C, D, E, F, G, H, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>, e: Signal<E, Error>, f: Signal<F, Error>, g: Signal<G, Error>, h: Signal<H, Error>) -> Signal<(A, B, C, D, E, F, G, H), Error> {
return combineLatest(a, b, c, d, e, f, g)
|> combineLatestWith(h)
|> map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public func combineLatest<A, B, C, D, E, F, G, H, I, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>, e: Signal<E, Error>, f: Signal<F, Error>, g: Signal<G, Error>, h: Signal<H, Error>, i: Signal<I, Error>) -> Signal<(A, B, C, D, E, F, G, H, I), Error> {
return combineLatest(a, b, c, d, e, f, g, h)
|> combineLatestWith(i)
|> map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
public func combineLatest<A, B, C, D, E, F, G, H, I, J, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>, e: Signal<E, Error>, f: Signal<F, Error>, g: Signal<G, Error>, h: Signal<H, Error>, i: Signal<I, Error>, j: Signal<J, Error>) -> Signal<(A, B, C, D, E, F, G, H, I, J), Error> {
return combineLatest(a, b, c, d, e, f, g, h, i)
|> combineLatestWith(j)
|> map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`. No events will be sent if the sequence is empty.
public func combineLatest<S: SequenceType, T, Error where S.Generator.Element == Signal<T, Error>>(signals: S) -> Signal<[T], Error> {
var generator = signals.generate()
if let first = generator.next() {
let initial = first |> map { [$0] }
return reduce(GeneratorSequence(generator), initial) { $0 |> combineLatestWith($1) }
}
return Signal.never
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public func zip<A, B, Error>(a: Signal<A, Error>, b: Signal<B, Error>) -> Signal<(A, B), Error> {
return a |> zipWith(b)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public func zip<A, B, C, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>) -> Signal<(A, B, C), Error> {
return zip(a, b)
|> zipWith(c)
|> map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public func zip<A, B, C, D, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>) -> Signal<(A, B, C, D), Error> {
return zip(a, b, c)
|> zipWith(d)
|> map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public func zip<A, B, C, D, E, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>, e: Signal<E, Error>) -> Signal<(A, B, C, D, E), Error> {
return zip(a, b, c, d)
|> zipWith(e)
|> map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public func zip<A, B, C, D, E, F, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>, e: Signal<E, Error>, f: Signal<F, Error>) -> Signal<(A, B, C, D, E, F), Error> {
return zip(a, b, c, d, e)
|> zipWith(f)
|> map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public func zip<A, B, C, D, E, F, G, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>, e: Signal<E, Error>, f: Signal<F, Error>, g: Signal<G, Error>) -> Signal<(A, B, C, D, E, F, G), Error> {
return zip(a, b, c, d, e, f)
|> zipWith(g)
|> map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public func zip<A, B, C, D, E, F, G, H, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>, e: Signal<E, Error>, f: Signal<F, Error>, g: Signal<G, Error>, h: Signal<H, Error>) -> Signal<(A, B, C, D, E, F, G, H), Error> {
return zip(a, b, c, d, e, f, g)
|> zipWith(h)
|> map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public func zip<A, B, C, D, E, F, G, H, I, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>, e: Signal<E, Error>, f: Signal<F, Error>, g: Signal<G, Error>, h: Signal<H, Error>, i: Signal<I, Error>) -> Signal<(A, B, C, D, E, F, G, H, I), Error> {
return zip(a, b, c, d, e, f, g, h)
|> zipWith(i)
|> map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
public func zip<A, B, C, D, E, F, G, H, I, J, Error>(a: Signal<A, Error>, b: Signal<B, Error>, c: Signal<C, Error>, d: Signal<D, Error>, e: Signal<E, Error>, f: Signal<F, Error>, g: Signal<G, Error>, h: Signal<H, Error>, i: Signal<I, Error>, j: Signal<J, Error>) -> Signal<(A, B, C, D, E, F, G, H, I, J), Error> {
return zip(a, b, c, d, e, f, g, h, i)
|> zipWith(j)
|> map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`. No events will be sent if the sequence is empty.
public func zip<S: SequenceType, T, Error where S.Generator.Element == Signal<T, Error>>(signals: S) -> Signal<[T], Error> {
var generator = signals.generate()
if let first = generator.next() {
let initial = first |> map { [$0] }
return reduce(GeneratorSequence(generator), initial) { $0 |> zipWith($1) }
}
return Signal.never
}
/// Forwards events from `signal` until `interval`. Then if signal isn't completed yet,
/// errors with `error` on `scheduler`.
///
/// If the interval is 0, the timeout will be scheduled immediately. The signal
/// must complete synchronously (or on a faster scheduler) to avoid the timeout.
public func timeoutWithError<T, E>(error: E, afterInterval interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<T, E> -> Signal<T, E> {
precondition(interval >= 0)
return { signal in
return Signal { observer in
let date = scheduler.currentDate.dateByAddingTimeInterval(interval)
let schedulerDisposable = scheduler.scheduleAfter(date) {
sendError(observer, error)
}
let signalDisposable = signal.observe(observer)
return CompositeDisposable(ignoreNil([ signalDisposable, schedulerDisposable ]))
}
}
}
/// Promotes a signal that does not generate errors into one that can.
///
/// This does not actually cause errors to be generated for the given signal,
/// but makes it easier to combine with other signals that may error; for
/// example, with operators like `combineLatestWith`, `zipWith`, `flatten`, etc.
public func promoteErrors<T, E: ErrorType>(_: E.Type)(signal: Signal<T, NoError>) -> Signal<T, E> {
return Signal { observer in
return signal.observe(next: { value in
sendNext(observer, value)
}, completed: {
sendCompleted(observer)
}, interrupted: {
sendInterrupted(observer)
})
}
}
/// Signal.observe() as a free function, for easier use with |>.
public func observe<T, E, S: SinkType where S.Element == Event<T, E>>(sink: S)(signal: Signal<T, E>) -> Disposable? {
return signal.observe(sink)
}
/// Signal.observe() as a free function, for easier use with |>.
public func observe<T, E>(error: (E -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, next: (T -> ())? = nil)(signal: Signal<T, E>) -> Disposable? {
return signal.observe(next: next, error: error, completed: completed, interrupted: interrupted)
}
/// Describes how multiple signals or producers should be joined together.
public enum FlattenStrategy: Equatable {
/// The signals should be merged, so that any value received on any of the
/// input signals will be forwarded immediately to the output signal.
///
/// The resulting signal will complete only when all inputs have completed.
case Merge
/// The signals should be concatenated, so that their values are sent in the
/// order of the signals themselves.
///
/// The resulting signal will complete only when all inputs have completed.
case Concat
/// Only the events from the latest input signal should be considered for
/// the output. Any signals received before that point will be disposed of.
///
/// The resulting signal will complete only when the signal-of-signals and
/// the latest signal has completed.
case Latest
}
public func == (lhs: FlattenStrategy, rhs: FlattenStrategy) -> Bool {
switch (lhs, rhs) {
case (.Merge, .Merge), (.Concat, .Concat), (.Latest, .Latest):
return true
default:
return false
}
}
extension FlattenStrategy: Printable {
public var description: String {
switch self {
case .Merge:
return "merge"
case .Concat:
return "concatenate"
case .Latest:
return "latest"
}
}
}
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` or an active inner producer emits an error, the returned
/// producer will forward that error immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
public func flatten<T, E>(strategy: FlattenStrategy)(producer: Signal<SignalProducer<T, E>, E>) -> Signal<T, E> {
switch strategy {
case .Merge:
return producer |> merge
case .Concat:
return producer |> concat
case .Latest:
return producer |> switchToLatest
}
}
/// Maps each event from `signal` to a new producer, then flattens the
/// resulting producers (into a single signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created producers emit an error, the returned
/// signal will forward that error immediately.
public func flatMap<T, U, E>(strategy: FlattenStrategy, transform: T -> SignalProducer<U, E>)(signal: Signal<T, E>) -> Signal<U, E> {
return signal |> map(transform) |> flatten(strategy)
}
/// Returns a signal which sends all the values from each producer emitted from
/// `signal`, waiting until each inner signal completes before beginning to
/// send the values from the next inner signal.
///
/// If any of the inner signals emit an error, the returned signal will emit
/// that error.
///
/// The returned signal completes only when `signal` and all signals
/// emitted from `signal` complete.
private func concat<T, E>(signal: Signal<SignalProducer<T, E>, E>) -> Signal<T, E> {
return Signal { observer in
let disposable = CompositeDisposable()
let state = ConcatState(observer: observer, disposable: disposable)
signal.observe(next: { producer in
state.enqueueSignalProducer(producer)
}, error: { error in
sendError(observer, error)
}, completed: {
// Add one last producer to the queue, whose sole job is to
// "turn out the lights" by completing `observer`.
let completion: SignalProducer<T, E> = .empty |> on(completed: {
sendCompleted(observer)
})
state.enqueueSignalProducer(completion)
}, interrupted: {
sendInterrupted(observer)
})
return disposable
}
}
private final class ConcatState<T, E: ErrorType> {
/// The observer of a started `concat` producer.
let observer: Signal<T, E>.Observer
/// The top level disposable of a started `concat` producer.
let disposable: CompositeDisposable
/// The active producer, if any, and the producers waiting to be started.
let queuedSignalProducers: Atomic<[SignalProducer<T, E>]> = Atomic([])
init(observer: Signal<T, E>.Observer, disposable: CompositeDisposable) {
self.observer = observer
self.disposable = disposable
}
func enqueueSignalProducer(producer: SignalProducer<T, E>) {
var shouldStart = true
queuedSignalProducers.modify { (var queue) in
// An empty queue means the concat is idle, ready & waiting to start
// the next producer.
shouldStart = queue.isEmpty
queue.append(producer)
return queue
}
if shouldStart {
startNextSignalProducer(producer)
}
}
func dequeueSignalProducer() -> SignalProducer<T, E>? {
var nextSignalProducer: SignalProducer<T, E>?
queuedSignalProducers.modify { (var queue) in
// Active producers remain in the queue until completed. Since
// dequeueing happens at completion of the active producer, the
// first producer in the queue can be removed.
if !queue.isEmpty { queue.removeAtIndex(0) }
nextSignalProducer = queue.first
return queue
}
return nextSignalProducer
}
/// Subscribes to the given signal producer.
func startNextSignalProducer(signalProducer: SignalProducer<T, E>) {
signalProducer.startWithSignal { signal, disposable in
let handle = self.disposable.addDisposable(disposable)
signal.observe(Signal.Observer { event in
switch event {
case .Completed, .Interrupted:
handle.remove()
if let nextSignalProducer = self.dequeueSignalProducer() {
self.startNextSignalProducer(nextSignalProducer)
}
default:
self.observer.put(event)
}
})
}
}
}
/// Merges a `signal` of SignalProducers down into a single signal, biased toward the producers
/// added earlier. Returns a Signal that will forward events from the inner producers as they arrive.
private func merge<T, E>(signal: Signal<SignalProducer<T, E>, E>) -> Signal<T, E> {
return Signal<T, E> { relayObserver in
let inFlight = Atomic(1)
let decrementInFlight: () -> () = {
let orig = inFlight.modify { $0 - 1 }
if orig == 1 {
sendCompleted(relayObserver)
}
}
let disposable = CompositeDisposable()
signal.observe(next: { producer in
producer.startWithSignal { innerSignal, innerDisposable in
inFlight.modify { $0 + 1 }
let handle = disposable.addDisposable(innerDisposable)
innerSignal.observe(Signal<T,E>.Observer { event in
if event.isTerminating {
handle.remove()
}
switch event {
case .Completed, .Interrupted:
decrementInFlight()
default:
relayObserver.put(event)
}
})
}
}, error: { error in
sendError(relayObserver, error)
}, completed: {
decrementInFlight()
}, interrupted: {
sendInterrupted(relayObserver)
})
return disposable
}
}
/// Returns a signal that forwards values from the latest producer sent on
/// `signal`, ignoring values sent on previous inner producers.
///
/// An error sent on `signal` or the latest inner producer will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// producer have both completed.
private func switchToLatest<T, E>(signal: Signal<SignalProducer<T, E>, E>) -> Signal<T, E> {
return Signal<T, E> { sink in
let disposable = CompositeDisposable()
let latestInnerDisposable = SerialDisposable()
disposable.addDisposable(latestInnerDisposable)
let state = Atomic(LatestState<T, E>(outerSignalComplete: false, latestIncompleteSignal: nil))
let updateState = { (action: LatestState<T, E> -> LatestState<T, E>) -> () in
state.modify(action)
if state.value.isComplete {
sendCompleted(sink)
}
}
signal.observe(next: { innerProducer in
innerProducer.startWithSignal { innerSignal, innerDisposable in
state.modify { state in
return state.isComplete
? state
: LatestState(
outerSignalComplete: state.outerSignalComplete,
latestIncompleteSignal: innerSignal)
}
// Don't dispose of the previous signal until we've
// registered this new signal as the latest, or else we
// may inadvertently send Interrupted to our observer.
latestInnerDisposable.innerDisposable = innerDisposable
innerSignal.observe(Signal.Observer { event in
switch event {
case .Completed, .Interrupted:
updateState { state in
return state.isLatestIncompleteSignal(innerSignal)
? LatestState(
outerSignalComplete: state.outerSignalComplete,
latestIncompleteSignal: nil)
: state
}
default:
state.withValue { value -> () in
if value.isLatestIncompleteSignal(innerSignal) {
sink.put(event)
}
}
}
})
}
}, error: { error in
sendError(sink, error)
}, completed: {
updateState { state in
LatestState(
outerSignalComplete: true,
latestIncompleteSignal: state.latestIncompleteSignal)
}
}, interrupted: {
sendInterrupted(sink)
})
return disposable
}
}
private struct LatestState<T, E: ErrorType> {
let outerSignalComplete: Bool
let latestIncompleteSignal: Signal<T, E>?
func isLatestIncompleteSignal(signal: Signal<T, E>) -> Bool {
if let latestIncompleteSignal = latestIncompleteSignal {
return latestIncompleteSignal === signal
} else {
return false
}
}
var isComplete: Bool {
return outerSignalComplete && latestIncompleteSignal == nil
}
}
| da687d92461507660da70985efd5b768 | 31.078056 | 323 | 0.678229 | false | true | false | false |
zef/Fly | refs/heads/master | Sources/FlyRequest.swift | mit | 1 | import HTTPStatus
public enum HTTPMethod: String {
case GET, PUT, POST, DELETE
// Patch?
}
public struct FlyRequest {
public let path: String
public let method: HTTPMethod
public var parameters = [String: String]()
public init(_ path: String, method: HTTPMethod = .GET) {
self.path = path
self.method = method
}
}
public struct FlyResponse {
public var request: FlyRequest = FlyRequest("")
public var status: HTTPStatus = HTTPStatus.OK
public var body: String = ""
public init() { }
public init(status: HTTPStatus) {
self.status = status
}
public init(body: String) {
self.body = body
}
}
extension FlyResponse: StringLiteralConvertible {
public typealias UnicodeScalarLiteralType = StringLiteralType
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.init(stringLiteral: value)
}
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(stringLiteral: value)
}
public init(stringLiteral value: StringLiteralType) {
self.init(body: value)
}
}
| 02db638b562850baec69e27809a0d13a | 24.22449 | 91 | 0.686084 | false | false | false | false |
IBM-Swift/BluePic | refs/heads/master | BluePic-iOS/BluePic/Views/ImageFeedTableViewCell.swift | apache-2.0 | 1 | /**
* Copyright IBM Corporation 2016, 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import UIKit
import SDWebImage
class ImageFeedTableViewCell: ProfileTableViewCell {
override func setupDataWith(_ image: Image) {
super.setupDataWith(image)
//set the photographerNameLabel's text
let ownerNameString = NSLocalizedString("by", comment: "") + " \(image.user.name)"
self.photographerNameLabel.text = ownerNameString
}
}
class ProfileTableViewCell: UITableViewCell {
//image view used to display image
@IBOutlet weak var userImageView: UIImageView!
//textView that displays the caption of the photo
@IBOutlet weak var captionTextView: UITextView!
//the view that is shown while we wait for the image to download and display
@IBOutlet weak var loadingView: UIView!
//label that displays the photographer's name
@IBOutlet weak var photographerNameLabel: UILabel!
//label shows the number of tags an image has
@IBOutlet weak var numberOfTagsLabel: UILabel!
//label that displays the amount of time since the photo was taken
@IBOutlet weak var timeSincePostedLabel: UILabel!
//constraint for top of textView
@IBOutlet weak var topConstraint: NSLayoutConstraint!
//string that is added to the numberOfTagsLabel at the end if there are multiple tags
fileprivate let kNumberOfTagsPostFix_MultipleTags = NSLocalizedString("Tags", comment: "")
//String that is added to the numberOfTagsLabel at the end if there is one tag
fileprivate let kNumberOfTagsPostFix_OneTag = NSLocalizedString("Tag", comment: "")
var defaultAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 13.0)]
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = UITableViewCellSelectionStyle.none
let style = NSMutableParagraphStyle()
style.alignment = .center
defaultAttributes[NSAttributedStringKey.paragraphStyle] = style
}
/// Method sets up the data for the profile collection view cell
///
/// - parameter image: Image object to use for populating UI
func setupDataWith(_ image: Image) {
let numOfTags = image.tags.count
if numOfTags == 0 {
self.numberOfTagsLabel.isHidden = true
} else if numOfTags == 1 {
self.numberOfTagsLabel.isHidden = false
self.numberOfTagsLabel.text = "\(numOfTags)" + " " + self.kNumberOfTagsPostFix_OneTag
} else {
self.numberOfTagsLabel.isHidden = false
self.numberOfTagsLabel.text = "\(numOfTags)" + " " + self.kNumberOfTagsPostFix_MultipleTags
}
//set the image view's image
self.setImageView(image.url, fileName: image.fileName)
//label that displays the photos caption
_ = self.setCaptionText(image: image)
//set the time since posted label's text
if let ts = image.timeStamp {
self.timeSincePostedLabel.text = Date.timeSinceDateString(ts)
} else {
self.timeSincePostedLabel.text = ""
}
}
func setCaptionText(image: Image) -> Bool {
let cutoffLength = 40
if image.caption == CameraDataManager.SharedInstance.kEmptyCaptionPlaceHolder {
self.captionTextView.text = ""
self.captionTextView.textContainerInset = UIEdgeInsets.zero
return false
} else if image.caption.count >= cutoffLength {
if !image.isExpanded {
let moreText = "...more"
let abc: String = (image.caption as NSString).substring(with: NSRange(location: 0, length: cutoffLength)) + moreText
let attributedString = NSMutableAttributedString(string: abc, attributes: defaultAttributes)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.gray, range: NSRange(location: cutoffLength, length: 7))
self.captionTextView.attributedText = attributedString
} else {
self.captionTextView.attributedText = NSMutableAttributedString(string: image.caption, attributes: defaultAttributes)
}
self.captionTextView.textContainerInset = UIEdgeInsets(top: 8.0, left: 0, bottom: 8.0, right: 0)
return true
} else {
self.captionTextView.attributedText = NSMutableAttributedString(string: image.caption, attributes: defaultAttributes)
self.captionTextView.textContainerInset = UIEdgeInsets(top: 8.0, left: 0, bottom: 8.0, right: 0)
return false
}
}
/**
Method sets up the image view with the url provided or a locally cached verion of the image
- parameter url: String?
- parameter fileName: String?
*/
func setImageView(_ url: String?, fileName: String?) {
self.loadingView.isHidden = false
//first try to set image view with locally cached image (from a photo the user has posted during the app session)
let locallyCachedImage = self.tryToSetImageViewWithLocallyCachedImage(fileName)
//then try to set the imageView with a url, using the locally cached image as the placeholder (if there is one)
self.tryToSetImageViewWithURL(url, placeHolderImage: locallyCachedImage)
}
/**
Method trys to set the image view with a locally cached image if there is one and then returns the locally cached image
- parameter fileName: String?
- returns: UIImage?
*/
fileprivate func tryToSetImageViewWithLocallyCachedImage(_ fileName: String?) -> UIImage? {
//check if file name and facebook user id aren't nil
if let fName = fileName {
//generate id which is a concatenation of the file name and facebook user id
let id = fName + CurrentUser.facebookUserId
//check to see if there is an image cached in the camera data manager's picturesTakenDuringAppSessionById cache
if let img = BluemixDataManager.SharedInstance.imagesTakenDuringAppSessionById[id] {
//hide loading placeholder view
self.loadingView.isHidden = true
//set image view's image to locally cached image
self.userImageView.image = img
return img
}
}
return nil
}
/**
Method trys to set the image view with a url to an image and sets the placeholder to a locally cached image if its not nil
- parameter url: String?
- parameter placeHolderImage: UIImage?
*/
fileprivate func tryToSetImageViewWithURL(_ url: String?, placeHolderImage: UIImage?) {
let urlString = url ?? ""
//check if string is empty, if it is, then its not a valid url
if urlString != "" {
//check if we can turn the string into a valid URL
if let nsurl = URL(string: urlString) {
//if placeHolderImage parameter isn't nil, then set image with URL and use placeholder image
if let image = placeHolderImage {
self.setImageViewWithURLAndPlaceHolderImage(nsurl, placeHolderImage: image)
}
//else dont use placeholder image and
else {
self.setImageViewWithURL(nsurl)
}
}
}
}
/**
Method sets the imageView with a url to an image and uses a locally cached image
- parameter url: URL
- parameter placeHolderImage: UIImage
*/
fileprivate func setImageViewWithURLAndPlaceHolderImage(_ url: URL, placeHolderImage: UIImage) {
self.userImageView.sd_setImage(with: url, placeholderImage: placeHolderImage, options: [.delayPlaceholder]) { image, error, _, _ in
self.loadingView.isHidden = image != nil && error == nil
}
}
/**
Method sets the imageView with a url to an image using no placeholder
- parameter url: URL
*/
fileprivate func setImageViewWithURL(_ url: URL) {
self.userImageView.sd_setImage(with: url) { (image, error, _, _) in
self.loadingView.isHidden = image != nil && error == nil
}
}
}
| 9bada55b24d94d02eb2682aa7881772e | 37.112069 | 156 | 0.660936 | false | false | false | false |
T1ger/LeetCode | refs/heads/master | src/subsets_ii/solution1.swift | mit | 3 | class Solution {
func subsetsWithDup(_ nums: [Int]) -> [[Int]] {
var res = [[Int]]()
var path = [Int]()
let nums = nums.sorted(by: <)
subsetsWithDupHelper(&res, path, nums, 0)
return res
}
private func subsetsWithDupHelper(_ res: inout [[Int]], _ path: [Int], _ nums: [Int], _ startIndex: Int) {
res.append(path)
var list = path
for i in startIndex ..< nums.count {
if i != 0 && i != startIndex && nums[i] == nums[i-1] {
continue
}
list.append(nums[i])
subsetsWithDupHelper(&res, list, nums, i + 1)
list.removeLast()
}
}
} | 80df905d5f2f78626058099339f1e56b | 25.785714 | 110 | 0.430412 | false | false | false | false |
tsaievan/XYReadBook | refs/heads/master | XYReadBook/XYReadBook/Classes/Views/Profile/XYSettingController.swift | mit | 1 | //
// XYSettingController.swift
// XYReadBook
//
// Created by tsaievan on 2017/9/3.
// Copyright © 2017年 tsaievan. All rights reserved.
//
import UIKit
fileprivate let kSettingCellId = "kSettingCellId"
class XYSettingController: XYViewController {
lazy var tableView = UITableView()
var cellInfo = [[XYElement]]()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
fileprivate func setupUI() {
if let info = XYProfileElementVM.settingElements() {
cellInfo = info
}
setupTableView()
}
fileprivate func setupTableView() {
tableView = UITableView(frame: view.bounds, style: .grouped)
tableView.showsVerticalScrollIndicator = false
tableView.showsHorizontalScrollIndicator = false
tableView.isPagingEnabled = false
tableView.bounces = false
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.register(XYSettingCell.self, forCellReuseIdentifier: kSettingCellId)
}
}
// MARK: - 数据源方法, 代理方法
extension XYSettingController: UITableViewDataSource, UITableViewDelegate{
///< 返回组数
func numberOfSections(in tableView: UITableView) -> Int {
return cellInfo.count
}
///< 返回行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellInfo[section].count
}
///< 返回cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:kSettingCellId , for: indexPath) as? XYSettingCell
let model = cellInfo[indexPath.section][indexPath.row]
if let cell = cell {
cell.model = model
cell.accViewName = model.accessViewName
return cell
}
return UITableViewCell()
}
///< 返回cell高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
///< 返回组尾高度
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
///< 返回组头高度
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.2
}
}
| a397bf97a61b5208f12a93c81d08f1d4 | 28.222222 | 114 | 0.65188 | false | false | false | false |
weblogng/example-weblogng-WNGTwitter | refs/heads/master | WNGTwitter/AuthView.swift | apache-2.0 | 1 | import UIKit
import Accounts
import Social
import SwifteriOS
// our AuthView is assigned to the first UIViewController in the Main.storyboard
class AuthView: UIViewController
{
@IBAction func doTwitterLogin(sender : AnyObject) {
let account = ACAccountStore()
let accountType = account.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
account.requestAccessToAccountsWithType(accountType, options: nil,
completion: { (granted, error) in
if (granted) {
let arrayOfAccount: NSArray = account.accountsWithAccountType(accountType)
if (arrayOfAccount.count > 0) {
let twitterAccount = arrayOfAccount.lastObject as ACAccount
let swifter = Swifter(account: twitterAccount)
self.fetchTwitterHomeStream(swifter)
}
} else {
self.alert("Unable to login")
}
}
)
}
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// Keeping things DRY by creating a simple alert method that we can reuse for generic errors
func alert(message: String)
{
// This is the iOS8 way of doing alerts. For older versions, look into UIAlertView
var alert = UIAlertController(
title: nil,
message: message,
preferredStyle: UIAlertControllerStyle.Alert
)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
// More DRY code, fetch the users home timeline if all went well
func fetchTwitterHomeStream(swifter: Swifter)
{
let failureHandler: ((NSError) -> Void) = {
error in
self.alert(error.localizedDescription)
}
swifter.getStatusesHomeTimelineWithCount(20, sinceID: nil, maxID: nil, trimUser: true, contributorDetails: false, includeEntities: true, success: {
(statuses: [JSONValue]?) in
// Successfully fetched timeline, so lets create and push the table view
let tweetsViewController = self.storyboard!.instantiateViewControllerWithIdentifier("RecentTweets") as RecentTweets
if statuses != nil {
tweetsViewController.tweets = statuses!
self.presentViewController(tweetsViewController, animated: true, completion: nil)
}
}, failure: failureHandler)
}
}
| 0dffb6b58c4687b43693730bad284035 | 35.302632 | 155 | 0.610366 | false | false | false | false |
Caiflower/SwiftWeiBo | refs/heads/master | 花菜微博/花菜微博/Classes/ViewModel(视图模型)/CFStatusViewModel.swift | apache-2.0 | 1 | //
// CFStatusViewModel.swift
// 花菜微博
//
// Created by 花菜ChrisCai on 2016/12/23.
// Copyright © 2016年 花菜ChrisCai. All rights reserved.
//
import Foundation
/// 微博视图模型
/**
如果没有任何父类,如果希望在开发时调试,输出调试信息
1. 遵守 CustomStringConvertible 协议
2. 实现 description 计算属性
*/
// 设置微博属性文本
let originalStatusTextFont = UIFont.systemFont(ofSize: 15)
let retweetedStatusTextFont = UIFont.systemFont(ofSize: 14)
class CFStatusViewModel: CustomStringConvertible {
/// 模型数据
var status: CFStatus
/// 会员图标
var memberIcon: UIImage?
/// 认证图标
var vipIcon: UIImage?
/// 转发
var retweetStr: String?
/// 评论
var commentStr: String?
/// 点赞
var likeStr: String?
/// 配图视图尺寸
var pictureViewSize = CGSize.zero
/// 图片模型数组
/// 如果是被转发的微博,原创的一定没有配图
var picUrls: [CFStatusPicture]? {
return status.retweeted_status?.pic_urls ?? status.pic_urls
}
/// 缓存高度
var rowHeight: CGFloat = 0
/// 微博正文属性文本
var retweetedAttrText: NSAttributedString?
/// 被转发的微博属性文本
var statusAttrText: NSAttributedString?
init(model: CFStatus) {
self.status = model
setMemberlevel()
setVerifiedType()
setCountString()
// 有原创的计算原创的,有转发的计算转发的
pictureViewSize = calculatePictureViewSize(count: picUrls?.count ?? 0)
// 设置正文属性文本
statusAttrText = CFEmoticonHelper.sharedHelper.emoticonString(targetString: status.text ?? "", font: originalStatusTextFont)
// 获取转发文本
let text = "@" + (status.retweeted_status?.user?.screen_name ?? "") + ":" + (status.retweeted_status?.text ?? "")
// 设置转发属性文本
retweetedAttrText = CFEmoticonHelper.sharedHelper.emoticonString(targetString: text, font: retweetedStatusTextFont)
// 计算高度
updateRowHeight()
}
/// 设置会员等级
func setMemberlevel() {
if let mbrank = self.status.user?.mbrank {
if mbrank > 0 && mbrank < 7 {
let imageName = "common_icon_membership_level" + "\(mbrank)"
memberIcon = UIImage(named: imageName)
}
}
}
/// 设置用户认证类型
fileprivate func setVerifiedType() {
// 认证类型 -1: 没有认证, 0: 认证用户, 2,3,5:企业认证,220:达人认证
switch self.status.user?.verified_type ?? -1{
case 0:
vipIcon = UIImage(named: "avatar_vip")
case 2,3,5:
vipIcon = UIImage(named: "avatar_enterprise_vip")
case 220:
vipIcon = UIImage(named: "avatar_grassroot")
default:
break
}
}
fileprivate func setCountString() {
retweetStr = countString(count: self.status.reposts_count, defaultString: "转发")
commentStr = countString(count: self.status.comments_count, defaultString: "评论")
likeStr = countString(count: self.status.attitudes_count, defaultString: "赞")
}
/// 设置转发,评论,点赞的描述
///
/// - Parameters:
/// - count: 转发,评论,点赞的数量
/// - defaultString: 默认文字
/// - Returns: 描述文字
fileprivate func countString(count: Int, defaultString: String) -> String {
if count == 0 {
return defaultString
}
if count < 10000 {
return count.description
}
return String(format: "%.2f 万", Double(count) / 10000)
}
/// 计算微博配图视图的大小
///
/// - Parameter count: 图片个数
/// - Returns: 配图尺寸
fileprivate func calculatePictureViewSize(count: Int) -> CGSize {
if count == 0 {
return CGSize.zero
}
// 计算行数
let row = (count - 1) / 3 + 1
// 计算高度
let height = CFStatusPictureViewOutterMargin + CGFloat(row - 1) * CFStatusPictureViewInnerMargin + CGFloat(row) * CFStatusPictureItemWidth
return CGSize(width: CFStatusPictureViewWidth, height: height)
}
/// 计算单张配图视图的尺寸
///
/// - Parameter image: 单张的配图
func updatePictureViewSize(image: UIImage) {
var size = image.size
// 宽度太宽或者太窄处理
let minWidth: CGFloat = 100
let maxWidth: CGFloat = 300
if size.width > maxWidth {
size.width = maxWidth
size.height = size.width / image.size.width * image.size.height
}
if size.width < minWidth {
size.width = minWidth
size.height = size.width / image.size.width * image.size.height
if size.height > maxWidth {
size.height = maxWidth
}
}
// 添加顶部间距
size.height += CFStatusPictureViewOutterMargin
pictureViewSize = size
// 重新计算行高
updateRowHeight()
}
fileprivate func updateRowHeight() {
// 原创微博 顶部分隔(12) + 间距(12) + 头像高度(34) + 间距(12) + 正文(计算) + 配图高度(计算) + 间距(12) + 底部工具视图高度(36)
// 转发微博 顶部分隔(12) + 间距(12) + 头像高度(34) + 间距(12) + 正文(计算) + 间距(12) + 间距(12) + 被转发的正文(计算) + 配图高度(计算) + 间距(12) + 底部工具视图高度(36)
// 定义行高
var rowHeight: CGFloat = 0
// label最大宽度
let maxWidth: CGFloat = UIScreen.main.cf_screenWidth - 2 * CFCommonMargin
let viewSize = CGSize(width: maxWidth, height: CGFloat(MAXFLOAT))
// 顶部高度
let topHeight: CGFloat = CFCommonMargin * 2 + CFStatusIconViewHeight + CFCommonMargin
rowHeight += topHeight
if let text = statusAttrText {
let textHeight = text.boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], context: nil).height
rowHeight += CGFloat(ceilf(Float(textHeight)))
}
// 被转发的微博
if status.retweeted_status != nil {
if let text = retweetedAttrText {
let textHeight = text.boundingRect(with: viewSize, options: [.usesLineFragmentOrigin], context: nil).height
rowHeight += CGFloat(ceilf(Float(textHeight)))
rowHeight += CFCommonMargin * 2
}
}
rowHeight += pictureViewSize.height + CFCommonMargin + CFStatusToolbarHeight
self.rowHeight = rowHeight
}
var description: String {
return self.status.description
}
}
| cd8d35b2e487939868b22e4d82389bd7 | 29.676617 | 146 | 0.580765 | false | false | false | false |
obozhdi/handy_extensions | refs/heads/master | HandyExtensions/HandyExtensions/Extensions/UIImage+TintLinearGradient.swift | unlicense | 1 | import UIKit
extension UIImage {
func tintWithLinearGradientColors(colorsArr: [CGColor?]) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
let context = UIGraphicsGetCurrentContext()
context!.translateBy(x: 0, y: self.size.height)
context!.scaleBy(x: 1.0, y: -1.0)
context!.setBlendMode(.normal)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
let colors = colorsArr as CFArray
let space = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradient(colorsSpace: space, colors: colors, locations: nil)
context?.clip(to: rect, mask: self.cgImage!)
context!.drawLinearGradient(gradient!, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 0, y: self.size.height), options: CGGradientDrawingOptions(rawValue: 0))
let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return gradientImage!
}
}
| 1ee1a45284ac3f9e2615271ed1103bc9 | 35.111111 | 159 | 0.70359 | false | false | false | false |
google-research/swift-tfp | refs/heads/master | Tests/TFPTests/FrontendTests.swift | apache-2.0 | 1 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
@testable import LibTFP
import SIL
import XCTest
@available(macOS 10.13, *)
final class FrontendTests: XCTestCase {
func testAssertRecovery() {
func makeCheck(_ cond: String) -> String {
return """
@_silgen_name("f") func f(x: Tensor<Float>, y: Tensor<Float>, i: Int) {
assert(\(cond))
}
"""
}
// NB: Variable number 0 is the result
let xVar = ListExpr.var(ListVar(1))
let yVar = ListExpr.var(ListVar(2))
let iVar = IntExpr.var(IntVar(3))
let asserts: [(String, BoolExpr)] = [
("x.rank == 2", .intEq(.length(of: xVar), 2)),
("x.rank == y.rank", .intEq(.length(of: xVar), .length(of: yVar))),
("x.rank == y.rank + 4", .intEq(.length(of: xVar), .add(.length(of: yVar), .literal(4)))),
("x.shape == y.shape", .listEq(xVar, yVar)),
("x.shape[1] == y.shape[2]", .intEq(.element(1, of: xVar), .element(2, of: yVar))),
("x.shape[0] == y.shape[0] + y.shape[1] * y.shape[2] / y.shape[3]",
.intEq(.element(0, of: xVar), .add(
.element(0, of: yVar),
.div(
.mul(.element(1, of: yVar), .element(2, of: yVar)),
.element(3, of: yVar))
))),
("x.shape[0] > y.shape[0]", .intGt(.element(0, of: xVar), .element(0, of: yVar))),
("x.shape[0] >= y.shape[0]", .intGe(.element(0, of: xVar), .element(0, of: yVar))),
("x.shape[0] < y.shape[0]", .intLt(.element(0, of: xVar), .element(0, of: yVar))),
("x.shape[0] <= y.shape[0]", .intLe(.element(0, of: xVar), .element(0, of: yVar))),
("x.shape == y.shape", .listEq(xVar, yVar)),
("x.shape == [1, 2 + y.shape[0], i]",
.listEq(xVar, .literal([1, .add(2, .element(0, of: yVar)), iVar]))),
]
for (cond, expectedExpr) in asserts {
withSIL(forSource: makeCheck(cond)) { module, _ in
for function in module.functions {
if function.blocks.count != 1 { continue }
guard let summary = abstract(function, inside: [:]) else { continue }
guard case let .bool(.var(retVarName)) = summary.retExpr else { continue }
for assertedExpr in summary.constraints.compactMap({ $0.exprWithoutCond }) {
if case .boolEq(.var(retVarName), expectedExpr) = assertedExpr {
return
}
}
}
XCTFail("Failed to find \(expectedExpr)")
}
}
}
static var allTests = [
("testAssertRecovery", testAssertRecovery),
]
}
| 059b8944bc2189c648b5b4086328117d | 40.054054 | 96 | 0.583608 | false | true | false | false |
PureSwift/Bluetooth | refs/heads/master | Sources/BluetoothGATT/ATTError.swift | mit | 1 | //
// ATTError.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 4/12/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
/**
The possible errors returned by a GATT server (a remote peripheral) during Bluetooth low energy ATT transactions.
These error constants are based on the Bluetooth ATT error codes, defined in the Bluetooth 4.0 specification.
For more information about these errors, see the Bluetooth 4.0 specification, Volume 3, Part F, Section 3.4.1.1.
*/
@frozen
public enum ATTError: UInt8, Error {
/// Invalid Handle
///
/// The attribute handle given was not valid on this server.
case invalidHandle = 0x01
/// Read Not Permitted
///
/// The attribute cannot be read.
case readNotPermitted = 0x02
/// Write Not Permitted
///
/// The attribute cannot be written.
case writeNotPermitted = 0x03
/// Invalid PDU
///
/// The attribute PDU was invalid.
case invalidPDU = 0x04
/// Insufficient Authentication
///
/// The attribute requires authentication before it can be read or written.
case insufficientAuthentication = 0x05
/// Request Not Supported
///
/// Attribute server does not support the request received from the client.
case requestNotSupported = 0x06
/// Invalid Offset
///
/// Offset specified was past the end of the attribute.
case invalidOffset = 0x07
/// Insufficient Authorization
///
/// The attribute requires authorization before it can be read or written.
case insufficientAuthorization = 0x08
/// Prepare Queue Full
///
/// Too many prepare writes have been queued.
case prepareQueueFull = 0x09
/// Attribute Not Found
///
/// No attribute found within the given attribute handle range.
case attributeNotFound = 0x0A
/// Attribute Not Long
///
/// The attribute cannot be read or written using the *Read Blob Request*.
case attributeNotLong = 0x0B
/// Insufficient Encryption Key Size
///
/// The *Encryption Key Size* used for encrypting this link is insufficient.
case insufficientEncryptionKeySize = 0x0C
/// Invalid Attribute Value Length
///
/// The attribute value length is invalid for the operation.
case invalidAttributeValueLength = 0x0D
/// Unlikely Error
///
/// The attribute request that was requested has encountered an error that was unlikely,
/// and therefore could not be completed as requested.
case unlikelyError = 0x0E
/// Insufficient Encryption
///
/// The attribute requires encryption before it can be read or written.
case insufficientEncryption = 0x0F
/// Unsupported Group Type
///
/// The attribute type is not a supported grouping attribute as defined by a higher layer specification.
case unsupportedGroupType = 0x10
/// Insufficient Resources
///
/// Insufficient Resources to complete the request.
case insufficientResources = 0x11
}
// MARK: - CustomStringConvertible
extension ATTError: CustomStringConvertible {
public var description: String {
return name
}
}
// MARK: - Description Values
public extension ATTError {
var name: String {
switch self {
case .invalidHandle:
return "Invalid Handle"
case .readNotPermitted:
return "Read Not Permitted"
case .writeNotPermitted:
return "Write Not Permitted"
case .invalidPDU:
return "Invalid PDU"
case .insufficientAuthentication:
return "Insufficient Authentication"
case .requestNotSupported:
return "Request Not Supported"
case .invalidOffset:
return "Invalid Offset"
case .insufficientAuthorization:
return "Insufficient Authorization"
case .prepareQueueFull:
return "Prepare Queue Full"
case .attributeNotFound:
return "Attribute Not Found"
case .attributeNotLong:
return "Attribute Not Long"
case .insufficientEncryptionKeySize:
return "Insufficient Encryption Key Size"
case .invalidAttributeValueLength:
return "Invalid Attribute Value Length"
case .unlikelyError:
return "Unlikely Error"
case .insufficientEncryption:
return "Insufficient Encryption"
case .unsupportedGroupType:
return "Unsupported Group Type"
case .insufficientResources:
return "Insufficient Resources"
}
}
var errorDescription: String {
switch self {
case .invalidHandle:
return "The attribute handle given was not valid on this server."
case .readNotPermitted:
return "The attribute cannot be read."
case .writeNotPermitted:
return "The attribute cannot be written."
case .invalidPDU:
return "The attribute PDU was invalid."
case .insufficientAuthentication:
return "The attribute requires authentication before it can be read or written."
case .requestNotSupported:
return "Attribute server does not support the request received from the client."
case .invalidOffset:
return "Offset specified was past the end of the attribute."
case .insufficientAuthorization:
return "The attribute requires authorization before it can be read or written."
case .prepareQueueFull:
return "Too many prepare writes have been queued."
case .attributeNotFound:
return "No attribute found within the given attri- bute handle range."
case .attributeNotLong:
return "The attribute cannot be read using the Read Blob Request."
case .insufficientEncryptionKeySize:
return "The Encryption Key Size used for encrypting this link is insufficient."
case .invalidAttributeValueLength:
return "The attribute value length is invalid for the operation."
case .unlikelyError:
return "The attribute request that was requested has encountered an error that was unlikely, and therefore could not be completed as requested."
case .insufficientEncryption:
return "The attribute requires encryption before it can be read or written."
case .unsupportedGroupType:
return "The attribute type is not a supported grouping attribute as defined by a higher layer specification."
case .insufficientResources:
return "Insufficient Resources to complete the request."
}
}
}
// MARK: - CustomNSError
import Foundation
extension ATTError: CustomNSError {
public static var errorDomain: String {
return "org.pureswift.Bluetooth.ATTError"
}
public var errorCode: Int {
return Int(rawValue)
}
public var errorUserInfo: [String: Any] {
return [
NSLocalizedDescriptionKey: name,
NSLocalizedFailureReasonErrorKey: errorDescription
]
}
}
| b96f0c998c0fa8d215d3d5b7eb6c097d | 33.642534 | 156 | 0.61651 | false | false | false | false |
efremidze/animated-tab-bar | refs/heads/master | RAMAnimatedTabBarController/Animations/TransitionAniamtions/RAMTransitionItemAnimation.swift | mit | 1 | // RAMTransitionItemAniamtions.swift
//
// Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public class RAMTransitionItemAniamtions : RAMItemAnimation {
var transitionOptions : UIViewAnimationOptions!
override init() {
super.init()
transitionOptions = UIViewAnimationOptions.TransitionNone
}
public override func playAnimation(icon : UIImageView, textLabel : UILabel) {
selectedColor(icon, textLabel: textLabel)
UIView.transitionWithView(icon, duration: NSTimeInterval(duration), options: transitionOptions, animations: {
}, completion: { _ in
})
}
public override func deselectAnimation(icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor) {
if let iconImage = icon.image {
let renderImage = iconImage.imageWithRenderingMode(.AlwaysOriginal)
icon.image = renderImage
textLabel.textColor = defaultTextColor
}
}
public override func selectedState(icon : UIImageView, textLabel : UILabel) {
selectedColor(icon, textLabel: textLabel)
}
func selectedColor(icon : UIImageView, textLabel : UILabel) {
if let iconImage = icon.image {
let renderImage = iconImage.imageWithRenderingMode(.AlwaysTemplate)
icon.image = renderImage
icon.tintColor = iconSelectedColor
}
textLabel.textColor = textSelectedColor
}
}
public class RAMFlipLeftTransitionItemAniamtions : RAMTransitionItemAniamtions {
public override init() {
super.init()
transitionOptions = UIViewAnimationOptions.TransitionFlipFromLeft
}
}
public class RAMFlipRightTransitionItemAniamtions : RAMTransitionItemAniamtions {
public override init() {
super.init()
transitionOptions = UIViewAnimationOptions.TransitionFlipFromRight
}
}
public class RAMFlipTopTransitionItemAniamtions : RAMTransitionItemAniamtions {
public override init() {
super.init()
transitionOptions = UIViewAnimationOptions.TransitionFlipFromTop
}
}
public class RAMFlipBottomTransitionItemAniamtions : RAMTransitionItemAniamtions {
public override init() {
super.init()
transitionOptions = UIViewAnimationOptions.TransitionFlipFromBottom
}
}
| d3ec54465c4bbff2e6ac18d98aa08055 | 31.245283 | 117 | 0.721767 | false | false | false | false |
iankunneke/TIY-Assignmnts | refs/heads/master | 22-SwiftBriefing/22-SwiftBriefing/MyViewController.swift | cc0-1.0 | 1 | //
// MyViewController.swift
// 22-SwiftBriefing
//
// Created by ian kunneke on 7/15/15.
// Copyright (c) 2015 The Iron Yard. All rights reserved.
//
import UIKit
class MyViewController: UIViewController
{
@IBOutlet weak var agentNameTextField: UITextField!
@IBOutlet weak var agentPasswordTextField: UITextField!
@IBOutlet weak var greetingLabel: UILabel!
@IBOutlet weak var missionBriefingTextView: UITextView!
@IBAction func authenticateAgent (sender: AnyObject)
{
if agentNameTextField .isFirstResponder()
{
agentNameTextField .resignFirstResponder()
}
if !agentNameTextField.text.isEmpty && !agentPasswordTextField.text.isEmpty && agentNameTextField.text.componentsSeparatedByString(" ").count == 2
{
let agentName = agentNameTextField.text
let nameComponents = agentName.componentsSeparatedByString(" ")
greetingLabel.text = "Good Evening, Agent \(nameComponents[1])"
missionBriefingTextView.text = "This mission will be an arduous one, fraught with peril. You will cover much strange and unfamiliar territory. Should you choose to accept this mission, Agent \(nameComponents[1]), you will certainly be disavowed, but you will be doing your country a great service. This message will self destruct in 5 seconds."
self.view.backgroundColor = UIColor.greenColor()
}
else
{
self.view.backgroundColor = UIColor.redColor()
}
}
override func viewDidLoad()
{
super.viewDidLoad()
self.agentNameTextField.text = ""
self.agentPasswordTextField.text = ""
self.missionBriefingTextView.text = ""
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
if !agentNameTextField.text.isEmpty && !agentPasswordTextField.text.isEmpty
{
resignFirstResponder()
}
/*
// 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.
}
*/
}
}
| a4b1e4e5915934cf17637a47e56caeb2 | 30.987013 | 356 | 0.662201 | false | false | false | false |
AbidHussainCom/HackingWithSwift | refs/heads/master | project30-files/Project30/ImageViewController.swift | unlicense | 20 | //
// ImageViewController.swift
// Project30
//
// Created by Hudzilla on 26/11/2014.
// Copyright (c) 2014 Hudzilla. All rights reserved.
//
import UIKit
class ImageViewController: UIViewController {
var owner: SelectionViewController!
var image: String!
var animTimer: NSTimer!
var imageView: UIImageView!
override func loadView() {
super.loadView()
view.backgroundColor = UIColor.blackColor()
// create an image view that fills the screen
imageView = UIImageView()
imageView.contentMode = .ScaleAspectFit
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
imageView.alpha = 0
view.addSubview(imageView)
// make the image view fill the screen
let viewsDictionary = ["imageView": imageView]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[imageView]|", options: .allZeros, metrics:nil, views: viewsDictionary))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[imageView]|", options: .allZeros, metrics:nil, views: viewsDictionary))
// schedule an animation that does something vaguely interesting
self.animTimer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "animateImage", userInfo: nil, repeats: true)
}
override func viewDidLoad() {
super.viewDidLoad()
title = image.stringByDeletingPathExtension
imageView.image = UIImage(named: image)
// force the image to rasterize so we don't have to keep loading it at the original, large size
imageView.layer.shouldRasterize = true
imageView.layer.rasterizationScale = UIScreen.mainScreen().scale
// NOTE: See if you can use the "Color hits green and misses red" option in the
// Core Animation instrument to see what effect the above has in this project!
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
imageView.alpha = 0
UIView.animateWithDuration(3) { [unowned self] in
self.imageView.alpha = 1
}
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let defaults = NSUserDefaults.standardUserDefaults()
var currentVal = defaults.integerForKey(image) ?? 0
++currentVal
defaults.setInteger(currentVal, forKey:image)
// tell the parent view controller that it should refresh its table counters when we go back
owner.dirty = true
}
func animateImage() {
// do something exciting with our image
imageView.transform = CGAffineTransformIdentity
UIView.animateWithDuration(3) { [unowned self] in
self.imageView.transform = CGAffineTransformMakeScale(0.8, 0.8)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 909c7cd48bfa77c2612a91e520672436 | 30.12 | 145 | 0.740681 | false | false | false | false |
smud/TextUserInterface | refs/heads/master | Sources/TextUserInterface/Extensions/Creature+Info.swift | apache-2.0 | 1 | //
// Creature+Info.swift
//
// This source file is part of the SMUD open source project
//
// Copyright (c) 2016 SMUD project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SMUD project authors
//
import Foundation
import Smud
extension Creature {
var textUserInterfaceData: CreatureData { return pluginData() }
func look() {
guard let room = room else {
send("You aren't standing in any room.")
return
}
let map = room.areaInstance.textUserInterfaceData.renderedAreaMap?.fragment(near: room, playerRoom: room, horizontalRooms: 3, verticalRooms: 3) ?? ""
send(room.title, "\n", room.description.wrapping(aroundTextColumn: map, totalWidth: 76, rightMargin: 1, bottomMargin: 1))
for creature in room.creatures {
if let mobile = creature as? Mobile {
print(mobile.shortDescription)
} else {
print(creature.name, " is standing here.")
}
}
}
func send(items: [Any], separator: String = "", terminator: String = "", isPrompt: Bool = false) {
for session in textUserInterfaceData.sessions {
session.send(items: items, separator: separator, terminator: terminator)
}
}
func send(_ items: Any..., separator: String = "", terminator: String = "\n", isPrompt: Bool = false) {
send(items: items, separator: separator, terminator: terminator)
}
}
| 4b901fdee67b47e1bacf9bd0f16b06f0 | 32.595745 | 157 | 0.632046 | false | false | false | false |
dvlproad/CJUIKit | refs/heads/master | CJBaseUIKit-Swift/CJAlert/CJAlertView.swift | mit | 1 | //
// CJAlertView.m
// CJUIKitDemo
//
// Created by ciyouzen on 2016/3/11.
// Copyright © 2016年 dvlproad. All rights reserved.
//
import UIKit
import CoreText
import SnapKit
class CJAlertView: UIView {
private var _flagImageViewHeight: CGFloat = 0.0
private var _titleLabelHeight: CGFloat = 0.0
private var _messageLabelHeight: CGFloat = 0.0
private var _bottomPartHeight: CGFloat = 0.0 //底部区域高度(包含底部按钮及可能的按钮上部的分隔线及按钮下部与边缘的距离)
private(set) var size: CGSize = CGSize.zero
//第一个视图(一般为flagImageView,如果flagImageView不存在,则为下一个即titleLabel,以此类推)与顶部的间隔
private(set) var firstVerticalInterval: CGFloat = 0
//第二个视图与第一个视图的间隔
private(set) var secondVerticalInterval: CGFloat = 0
//第三个视图与第二个视图的间隔
private(set) var thirdVerticalInterval: CGFloat = 0
//底部buttons视图与其上面的视图的最小间隔(上面的视图一般为message;如果不存在message,则是title;如果再不存在,则是flagImage)
private(set) var bottomMinVerticalInterval: CGFloat = 0
var flagImageView: UIImageView?
var titleLabel: UILabel?
var messageScrollView: UIScrollView?
var messageContainerView: UIView?
var messageLabel: UILabel?
var cancelButton: UIButton?
var okButton: UIButton?
var cancelHandle: (()->())?
var okHandle: (()->())?
// MARK: - ClassMethod
class func alertViewWithSize(size: CGSize,
flagImage: UIImage!,
title: String,
message: String,
cancelButtonTitle: String,
okButtonTitle: String,
cancelHandle:(()->())?,
okHandle: (()->())?) -> CJAlertView
{
//①创建
let alertView: CJAlertView = CJAlertView.init(size: size, firstVerticalInterval: 15, secondVerticalInterval: 10, thirdVerticalInterval: 10, bottomMinVerticalInterval: 10)
//②添加 flagImage、titleLabel、messageLabel
//[alertView setupFlagImage:flagImage title:title message:message configure:configure]; //已拆解成以下几个方法
if flagImage != nil {
alertView.addFlagImage(flagImage, CGSize(width: 38, height: 38))
}
if title.count > 0 {
alertView.addTitleWithText(title, font: UIFont.systemFont(ofSize: 18.0), textAlignment: .center, margin: 20, paragraphStyle: nil)
}
if message.count > 0 {
let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = .byCharWrapping
paragraphStyle.lineSpacing = 4
alertView.addMessageWithText(message, font: UIFont.systemFont(ofSize: 14.0), textAlignment: .center, margin: 20, paragraphStyle: paragraphStyle)
}
//③添加 cancelButton、okButton
alertView.addBottomButtons(actionButtonHeight: 50, cancelButtonTitle: cancelButtonTitle, okButtonTitle: okButtonTitle, cancelHandle: cancelHandle, okHandle: okHandle)
return alertView;
}
// MARK: - Init
// required init?(coder aDecoder: NSCoder) {
// super.init(coder: aDecoder)
// }
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
* 创建alertView
* @brief 这里所说的三个视图范围为:flagImageView(有的话,一定是第一个)、titleLabel(有的话,有可能一或二)、messageLabel(有的话,有可能一或二或三)
*
* @param size alertView的大小
* @param firstVerticalInterval 第一个视图(一般为flagImageView,如果flagImageView不存在,则为下一个即titleLabel,以此类推)与顶部的间隔
* @param secondVerticalInterval 第二个视图与第一个视图的间隔(如果少于两个视图,这个值设为0即可)
* @param thirdVerticalInterval 第三个视图与第二个视图的间隔(如果少于三个视图,这个值设为0即可)
* @param bottomMinVerticalInterval 底部buttons区域视图与其上面的视图的最小间隔(上面的视图一般为message;如果不存在message,则是title;如果再不存在,则是flagImage)
*
* @return alertView
*/
init(size: CGSize,
firstVerticalInterval: CGFloat,
secondVerticalInterval: CGFloat,
thirdVerticalInterval: CGFloat,
bottomMinVerticalInterval: CGFloat)
{
super.init(frame: CGRect.zero)
self.backgroundColor = UIColor.white
self.layer.cornerRadius = 3
self.size = size
self.firstVerticalInterval = firstVerticalInterval
self.secondVerticalInterval = secondVerticalInterval
self.thirdVerticalInterval = thirdVerticalInterval
self.bottomMinVerticalInterval = bottomMinVerticalInterval
}
/// 添加指示图标
func addFlagImage(_ flagImage: UIImage, _ imageViewSize: CGSize) {
if self.flagImageView == nil {
let flagImageView: UIImageView = UIImageView.init()
self.addSubview(flagImageView)
self.flagImageView = flagImageView;
}
self.flagImageView!.image = flagImage;
self.flagImageView?.snp.makeConstraints({ (make) in
make.centerX.equalTo(self);
make.width.equalTo(imageViewSize.width);
make.top.equalTo(self).offset(self.firstVerticalInterval);
make.height.equalTo(imageViewSize.height);
})
_flagImageViewHeight = imageViewSize.height;
if (self.titleLabel != nil) {
//由于约束部分不一样,使用update会增加一个新约束,又没设置优先级,从而导致约束冲突。而如果用remake的话,又需要重新设置之前已经设置过的,否则容易缺失。所以使用masnory时候,使用优先级比较合适
self.titleLabel!.snp.updateConstraints({ (make) in
make.top.equalTo(self.flagImageView!.snp_bottom).offset(self.secondVerticalInterval);
})
}
if self.messageScrollView != nil {
self.messageScrollView!.snp.updateConstraints { (make) in
if self.titleLabel != nil {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.thirdVerticalInterval);
} else {
make.top.greaterThanOrEqualTo(self.flagImageView!.snp_bottom).offset(self.secondVerticalInterval);
}
}
}
}
// MARK: - AddView
///添加title
func addTitleWithText(_ text: String? = "",
font: UIFont,
textAlignment: NSTextAlignment,
margin titleLabelLeftOffset: CGFloat,
paragraphStyle: NSMutableParagraphStyle?)
{
if self.size.equalTo(CGSize.zero) {
return
}
if self.titleLabel == nil {
let titleLabel: UILabel = UILabel(frame: CGRect.zero)
//titleLabel.backgroundColor = [UIColor purpleColor];
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor.black
self.addSubview(titleLabel)
self.titleLabel = titleLabel
}
// if text == nil {
// text = ""
// //若为nil,则设置[[NSMutableAttributedString alloc] initWithString:labelText]的时候会崩溃
// }
let titleLabelMaxWidth: CGFloat = self.size.width-2*titleLabelLeftOffset
let titleLabelMaxSize: CGSize = CGSize(width: titleLabelMaxWidth, height: CGFloat.greatestFiniteMagnitude)
let titleTextSize: CGSize = CJAlertView.getTextSize(from: text!, with: font, maxSize: titleLabelMaxSize, lineBreakMode: .byCharWrapping, paragraphStyle: paragraphStyle)
var titleTextHeight: CGFloat = titleTextSize.height
let lineStringArray: [NSString] = CJAlertView.getLineStringArray(labelText: text!, font: font, maxTextWidth: titleLabelMaxWidth)
let lineCount: NSInteger = lineStringArray.count
var lineSpacing: CGFloat = paragraphStyle?.lineSpacing ?? 0
if lineSpacing == 0 {
lineSpacing = 2
}
titleTextHeight += CGFloat(lineCount)*lineSpacing
if paragraphStyle == nil {
self.titleLabel!.text = text
} else {
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.paragraphStyle: paragraphStyle!,
NSAttributedString.Key.font: font,
//NSAttributedString.Key.foregroundColor: textColor,
//NSAttributedString.Key.kern: 1.5f //字体间距
]
let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: text!)
attributedText.addAttributes(attributes, range: NSMakeRange(0, text!.count))
//[attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
self.titleLabel!.attributedText = attributedText
}
self.titleLabel!.font = font
self.titleLabel!.textAlignment = textAlignment
self.titleLabel!.snp.makeConstraints({ (make) in
make.centerX.equalTo(self);
make.left.equalTo(self).offset(titleLabelLeftOffset);
if self.flagImageView != nil {
make.top.equalTo(self.flagImageView!.snp_bottom).offset(self.secondVerticalInterval);
} else {
make.top.greaterThanOrEqualTo(self).offset(self.firstVerticalInterval);//优先级
}
make.height.equalTo(titleTextHeight);
})
_titleLabelHeight = titleTextHeight
if self.messageScrollView != nil {
self.messageScrollView?.snp.updateConstraints({ (make) in
if self.flagImageView != nil {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.thirdVerticalInterval);
} else {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.secondVerticalInterval);
}
})
}
}
// MARK: - Private
//以下获取textSize方法取自NSString+CJTextSize
class func getTextSize(from string: String, with font: UIFont, maxSize: CGSize, lineBreakMode: NSLineBreakMode, paragraphStyle: NSMutableParagraphStyle?) -> CGSize {
var paragraphStyle = paragraphStyle
if (string.count == 0) {
return CGSize.zero
}
if paragraphStyle == nil {
paragraphStyle = NSParagraphStyle.default as? NSMutableParagraphStyle
paragraphStyle?.lineBreakMode = lineBreakMode
}
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.paragraphStyle: paragraphStyle!,
NSAttributedString.Key.font: font
]
let options: NSStringDrawingOptions = .usesLineFragmentOrigin
let textRect: CGRect = string.boundingRect(with: maxSize, options: options, attributes: attributes, context: nil)
let size: CGSize = textRect.size
return CGSize(width: ceil(size.width), height: ceil(size.height))
}
///获取每行的字符串组成的数组
class func getLineStringArray(labelText: String, font: UIFont, maxTextWidth: CGFloat) -> [NSString] {
//convert UIFont to a CTFont
let fontName: CFString = font.fontName as CFString
let fontSize: CGFloat = font.pointSize
let fontRef: CTFont = CTFontCreateWithName(fontName, fontSize, nil);
let attString: NSMutableAttributedString = NSMutableAttributedString.init(string: labelText)
attString.addAttribute(kCTFontAttributeName as NSAttributedString.Key, value: fontRef, range: NSMakeRange(0, attString.length))
let framesetter: CTFramesetter = CTFramesetterCreateWithAttributedString(attString)
let path: CGMutablePath = CGMutablePath();
path.addRect(CGRect(x: 0, y: 0, width: maxTextWidth, height: 100000))
let frame: CTFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil)
let lines: NSArray = CTFrameGetLines(frame)
let lineStringArray: NSMutableArray = NSMutableArray.init()
for line in lines {
let lineRef: CTLine = line as! CTLine
let lineRange: CFRange = CTLineGetStringRange(lineRef)
let range: NSRange = NSRange(location: lineRange.location, length: lineRange.length)
let startIndex = labelText.index(labelText.startIndex, offsetBy: range.location)
let endIndex = labelText.index(startIndex, offsetBy: range.length)
let lineString: String = String(labelText[startIndex ..< endIndex])
lineStringArray.add(lineString)
}
return lineStringArray as! [NSString]
}
///添加message的方法(paragraphStyle:当需要设置message行距、缩进等的时候才需要设置,其他设为nil即可)
func addMessageWithText(_ text: String? = "",
font: UIFont,
textAlignment: NSTextAlignment,
margin messageLabelLeftOffset: CGFloat,
paragraphStyle: NSMutableParagraphStyle?)
{
//NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
//paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
//paragraphStyle.lineSpacing = lineSpacing;
//paragraphStyle.headIndent = 10;
if self.size.equalTo(CGSize.zero) {
return
}
if self.messageScrollView == nil {
let scrollView: UIScrollView = UIScrollView()
//scrollView.backgroundColor = [UIColor redColor];
self.addSubview(scrollView)
self.messageScrollView = scrollView
let containerView: UIView = UIView()
//containerView.backgroundColor = [UIColor greenColor];
scrollView.addSubview(containerView)
self.messageContainerView = containerView
let messageTextColor: UIColor = UIColor(red: 136/255.0, green: 136/255.0, blue: 136/255.0, alpha: 1)
//#888888
let messageLabel: UILabel = UILabel(frame: CGRect.zero)
messageLabel.numberOfLines = 0
//UITextView *messageLabel = [[UITextView alloc] initWithFrame:CGRectZero];
//messageLabel.editable = NO;
messageLabel.textAlignment = .center
messageLabel.textColor = messageTextColor
containerView.addSubview(messageLabel)
self.messageLabel = messageLabel
}
let messageLabelMaxWidth: CGFloat = self.size.width-2*messageLabelLeftOffset
let messageLabelMaxSize: CGSize = CGSize(width: messageLabelMaxWidth, height: CGFloat.greatestFiniteMagnitude)
let messageTextSize: CGSize = CJAlertView.getTextSize(from: text!, with: font, maxSize: messageLabelMaxSize, lineBreakMode: .byCharWrapping, paragraphStyle: paragraphStyle)
var messageTextHeight: CGFloat = messageTextSize.height
let lineStringArray: [NSString] = CJAlertView.getLineStringArray(labelText: text!, font: font, maxTextWidth: messageLabelMaxWidth)
let lineCount: NSInteger = lineStringArray.count
var lineSpacing: CGFloat = paragraphStyle!.lineSpacing
if lineSpacing == 0 {
lineSpacing = 2
}
messageTextHeight += CGFloat(lineCount)*lineSpacing
if (paragraphStyle == nil) {
self.messageLabel!.text = text;
} else {
let attributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.paragraphStyle: paragraphStyle!,
NSAttributedString.Key.font: font,
//NSAttributedString.Key.foregroundColor: textColor,
//NSAttributedString.Key.kern: 1.5f //字体间距
]
let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: text!)
attributedText.addAttributes(attributes, range: NSMakeRange(0, text!.count))
//[attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
self.messageLabel!.attributedText = attributedText
}
self.messageLabel!.font = font
self.messageLabel!.textAlignment = textAlignment
self.messageScrollView?.snp.makeConstraints({ (make) in
make.centerX.equalTo(self);
make.left.equalTo(self).offset(messageLabelLeftOffset);
if (self.titleLabel != nil) {
if (self.flagImageView != nil) {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.thirdVerticalInterval);
} else {
make.top.equalTo(self.titleLabel!.snp_bottom).offset(self.secondVerticalInterval);
}
} else if (self.flagImageView != nil) {
make.top.greaterThanOrEqualTo(self.flagImageView!.snp_bottom).offset(self.secondVerticalInterval);//优先级
} else {
make.top.greaterThanOrEqualTo(self).offset(self.firstVerticalInterval);//优先级
}
make.height.equalTo(messageTextHeight);
})
self.messageContainerView!.snp.makeConstraints({ (make) in
make.left.right.equalTo(self.messageScrollView!)
make.top.bottom.equalTo(self.messageScrollView!)
make.width.equalTo(self.messageScrollView!.snp_width)
make.height.equalTo(messageTextHeight)
})
self.messageLabel?.snp.makeConstraints({ (make) in
make.left.right.equalTo(self.messageContainerView!);
make.top.equalTo(self.messageContainerView!);
make.height.equalTo(messageTextHeight);
})
_messageLabelHeight = messageTextHeight;
}
///添加 message 的边框等(几乎不会用到)
func addMessageLayer(borderWidth: CGFloat, borderColor: CGColor?, cornerRadius: CGFloat) {
assert((self.messageScrollView != nil), "请先添加messageScrollView")
self.messageScrollView!.layer.borderWidth = borderWidth
if borderColor != nil {
self.messageScrollView!.layer.borderColor = borderColor
}
self.messageScrollView!.layer.cornerRadius = cornerRadius
}
///添加底部按钮
/**
* 添加底部按钮方法①:按指定布局添加底部按钮
*
* @param bottomButtons 要添加的按钮组合(得在外部额外实现点击后的关闭alert操作)
* @param actionButtonHeight 按钮高度
* @param bottomInterval 按钮与底部的距离
* @param axisType 横排还是竖排
* @param fixedSpacing 两个控件间隔
* @param leadSpacing 第一个控件与边缘的间隔
* @param tailSpacing 最后一个控件与边缘的间隔
*/
func addBottomButtons(bottomButtons: [UIButton],
actionButtonHeight: CGFloat, //withHeight
bottomInterval: CGFloat,
axisType: NSLayoutConstraint.Axis,
fixedSpacing: CGFloat,
leadSpacing: CGFloat,
tailSpacing: CGFloat
)
{
let buttonCount: Int = bottomButtons.count
if axisType == .horizontal {
_bottomPartHeight = 0+actionButtonHeight+bottomInterval
} else {
_bottomPartHeight = leadSpacing+CGFloat(buttonCount)*(actionButtonHeight+fixedSpacing)-fixedSpacing+tailSpacing
}
for bottomButton in bottomButtons {
self.addSubview(bottomButton)
}
// if buttonCount > 1 {
// bottomButtons.snp.makeConstraints { (make) in
// make.bottom.equalTo(-bottomInterval)
// make.height.equalTo(actionButtonHeight)
// }
// bottomButtons.snp.distributeViews(along: axisType, withFixedSpacing: fixedSpacing, leadSpacing: leadSpacing, tailSpacing: tailSpacing)
// } else {
// bottomButtons.snp.makeConstraints { (make) in
// make.bottom.equalTo(-bottomInterval)
// make.height.equalTo(actionButtonHeight)
// make.left.equalTo(self).offset(leadSpacing)
// make.right.equalTo(self).offset(-tailSpacing)
// }
// }
}
///只添加一个按钮
func addOnlyOneBottomButton(_ bottomButton: UIButton,
withHeight actionButtonHeight: CGFloat,
bottomInterval: CGFloat,
leftOffset: CGFloat,
rightOffset: CGFloat)
{
_bottomPartHeight = 0 + actionButtonHeight + bottomInterval
self.addSubview(bottomButton)
bottomButton.snp.makeConstraints { (make) in
make.bottom.equalTo(-bottomInterval);
make.height.equalTo(actionButtonHeight);
make.left.equalTo(self).offset(leftOffset);
make.right.equalTo(self).offset(-rightOffset);
}
}
func addBottomButtons(actionButtonHeight: CGFloat,
cancelButtonTitle: String,
okButtonTitle: String,
cancelHandle: (()->())?,
okHandle: (()->())?)
{
let lineColor: UIColor = UIColor(red: 229/255.0, green: 229/255.0, blue: 229/255.0, alpha: 1)
//#e5e5e5
let cancelTitleColor: UIColor = UIColor(red: 136/255.0, green: 136/255.0, blue: 136/255.0, alpha: 1)
//#888888
let okTitleColor: UIColor = UIColor(red: 66/255.0, green: 135/255.0, blue: 255/255.0, alpha: 1)
//#4287ff
self.cancelHandle = cancelHandle
self.okHandle = okHandle
let existCancelButton: Bool = cancelButtonTitle.count > 0
let existOKButton: Bool = okButtonTitle.count > 0
if existCancelButton == false && existOKButton == false {
return
}
var cancelButton: UIButton?
if existCancelButton {
cancelButton = UIButton(type: .custom)
cancelButton!.backgroundColor = UIColor.clear
cancelButton!.setTitle(cancelButtonTitle, for: .normal)
cancelButton!.setTitleColor(cancelTitleColor, for: .normal)
cancelButton!.titleLabel!.font = UIFont.systemFont(ofSize: 14)
cancelButton!.addTarget(self, action: #selector(cancelButtonAction(button:)), for: .touchUpInside)
self.cancelButton = cancelButton
}
var okButton: UIButton?
if existOKButton {
okButton = UIButton(type: .custom)
okButton!.backgroundColor = UIColor.clear
okButton!.setTitle(okButtonTitle, for: .normal)
okButton!.setTitleColor(okTitleColor, for: .normal)
okButton!.titleLabel!.font = UIFont.systemFont(ofSize: 14)
okButton!.addTarget(self, action: #selector(okButtonAction(button:)), for: .touchUpInside)
self.okButton = okButton
}
let lineView: UIView = UIView()
lineView.backgroundColor = lineColor
self.addSubview(lineView)
lineView.snp.makeConstraints { (make) in
make.left.right.equalTo(self)
make.bottom.equalTo(self).offset(-actionButtonHeight-1)
make.height.equalTo(1)
}
_bottomPartHeight = actionButtonHeight+1
if (existCancelButton == true && existOKButton == true) {
self.addSubview(cancelButton!)
cancelButton!.snp.makeConstraints { (make) in
make.left.equalTo(self)
make.width.equalTo(self).multipliedBy(0.5)
make.bottom.equalTo(self)
make.height.equalTo(actionButtonHeight)
}
let actionSeprateLineView: UIView = UIView.init()
actionSeprateLineView.backgroundColor = lineColor
self.addSubview(actionSeprateLineView)
actionSeprateLineView.snp.makeConstraints { (make) in
make.left.equalTo(cancelButton!.snp_right)
make.width.equalTo(1)
make.top.bottom.equalTo(cancelButton!)
}
self.addSubview(okButton!)
okButton!.snp.makeConstraints { (make) in
make.left.equalTo(actionSeprateLineView.snp_right)
make.right.equalTo(self)
make.bottom.equalTo(self)
make.height.equalTo(actionButtonHeight)
}
} else if (existCancelButton == true) {
self.addSubview(cancelButton!)
cancelButton!.snp.makeConstraints { (make) in
make.left.equalTo(self)
make.width.equalTo(self).multipliedBy(1)
make.bottom.equalTo(self)
make.height.equalTo(actionButtonHeight)
}
} else if (existOKButton == true) {
self.addSubview(okButton!)
okButton!.snp.makeConstraints { (make) in
make.right.equalTo(self)
make.width.equalTo(self).multipliedBy(1)
make.bottom.equalTo(self)
make.height.equalTo(actionButtonHeight)
}
}
}
// MARK: - 文字颜色等Option
///更改 Title 文字颜色
func updateTitleTextColor(_ textColor: UIColor) {
self.titleLabel?.textColor = textColor
}
///更改 Message 文字颜色
func updateMessageTextColor(_ textColor: UIColor) {
self.messageLabel?.textColor = textColor
}
///更改底部 Cancel 按钮的文字颜色
func updateCancelButtonTitleColor(normalTitleColor: UIColor, highlightedTitleColor: UIColor) {
self.cancelButton?.setTitleColor(normalTitleColor, for: .normal)
self.cancelButton?.setTitleColor(highlightedTitleColor, for: .highlighted)
}
///更改底部 OK 按钮的文字颜色
func updateOKButtonTitleColor(normalTitleColor: UIColor, highlightedTitleColor: UIColor) {
self.okButton?.setTitleColor(normalTitleColor, for: .normal)
self.okButton?.setTitleColor(highlightedTitleColor, for: .highlighted)
}
// MARK: - Event
/**
* 显示 alert 弹窗
*
* @param shouldFitHeight 是否需要自动适应高度(否:会以之前指定的size的height来显示)
* @param blankBGColor 空白区域的背景颜色
*/
func showWithShouldFitHeight(_ shouldFitHeight: Bool, blankBGColor: UIColor) {
self.checkAndUpdateVerticalInterval()
var fixHeight: CGFloat = 0
if (shouldFitHeight == true) {
let minHeight: CGFloat = self.getMinHeight()
fixHeight = minHeight
} else {
fixHeight = self.size.height
}
self.showWithFixHeight(&fixHeight, blankBGColor: blankBGColor)
}
/**
* 显示弹窗并且是以指定高度显示的
*
* @param fixHeight 高度
* @param blankBGColor 空白区域的背景颜色
*/
func showWithFixHeight(_ fixHeight: inout CGFloat, blankBGColor: UIColor) {
self.checkAndUpdateVerticalInterval()
let minHeight: CGFloat = self.getMinHeight()
if fixHeight < minHeight {
let warningString: String = String(format: "CJ警告:您设置的size高度小于视图本身的最小高度%.2lf,会导致视图显示不全,请检查", minHeight)
print("\(warningString)")
}
let maxHeight: CGFloat = UIScreen.main.bounds.height-60
if fixHeight > maxHeight {
fixHeight = maxHeight
//NSString *warningString = [NSString stringWithFormat:@"CJ警告:您设置的size高度超过视图本身的最大高度%.2lf,会导致视图显示不全,已自动缩小", maxHeight];
//NSLog(@"%@", warningString);
if self.messageScrollView != nil {
let minHeightWithoutMessageLabel: CGFloat = self.firstVerticalInterval + _flagImageViewHeight + self.secondVerticalInterval + _titleLabelHeight + self.thirdVerticalInterval + self.bottomMinVerticalInterval + _bottomPartHeight;
_messageLabelHeight = fixHeight - minHeightWithoutMessageLabel
self.messageScrollView?.snp.updateConstraints({ (make) in
make.height.equalTo(_messageLabelHeight)
})
}
}
let popupViewSize: CGSize = CGSize(width: self.size.width, height: fixHeight)
self.cj_popupInCenterWindow(animationType: .normal, popupViewSize: popupViewSize, blankBGColor: blankBGColor, showPopupViewCompleteBlock: nil, tapBlankViewCompleteBlock: nil)
}
///获取当前alertView最小应有的高度值
func getMinHeight() -> CGFloat {
var minHeightWithMessageLabel: CGFloat = self.firstVerticalInterval + _flagImageViewHeight + self.secondVerticalInterval + _titleLabelHeight + self.thirdVerticalInterval + _messageLabelHeight + self.bottomMinVerticalInterval + _bottomPartHeight
minHeightWithMessageLabel = ceil(minHeightWithMessageLabel);
return minHeightWithMessageLabel;
}
/**
* 通过检查位于bottomButtons上view的个数来判断并修正之前设置的VerticalInterval(防止比如有时候只设置两个view,thirdVerticalInterval却不为0)
* @brief 问题来源:比如少于三个视图,thirdVerticalInterval却没设为0,此时如果不通过此方法检查并修正,则容易出现高度计算错误的问题
*/
func checkAndUpdateVerticalInterval() {
var upViewCount: Int = 0
if self.flagImageView != nil {
upViewCount += 1
}
if self.titleLabel != nil {
upViewCount += 1
}
if self.messageScrollView != nil {
upViewCount += 1
}
if upViewCount == 2 {
self.thirdVerticalInterval = 0
} else if upViewCount == 1 {
self.secondVerticalInterval = 0
}
}
// MARK: - Private
@objc func cancelButtonAction(button: UIButton) {
self.dismiss(0)
self.cancelHandle?()
}
@objc func okButtonAction(button: UIButton) {
self.dismiss(0)
self.okHandle?()
}
func dismiss(_ delay: CGFloat) {
let time = DispatchTime.now() + 1.5
DispatchQueue.main.asyncAfter(deadline: time) {
self.cj_hidePopupView(.normal)
}
}
}
//
//@implementation CJAlertView
//
//
//
//
///* //已拆解成以下几个方法
//- (void)setupFlagImage:(UIImage *)flagImage
// title:(NSString *)title
// message:(NSString *)message
//{
// if (CGSizeEqualToSize(self.size, CGSizeZero)) {
// return;
// }
//
// UIColor *messageTextColor = [UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1]; //#888888
//
//
// if (flagImage) {
// UIImageView *flagImageView = [[UIImageView alloc] init];
// flagImageView.image = flagImage;
// [self addSubview:flagImageView];
// [flagImageView mas_makeConstraints:^(MASConstraintMaker *make) {
// make.centerX.equalTo(self);
// make.width.equalTo(38);
// make.top.equalTo(self).offset(25);
// make.height.equalTo(38);
// }];
// _flagImageView = flagImageView;
// }
//
//
// // titleLabel
// CGFloat titleLabelLeftOffset = 20;
// UIFont *titleLabelFont = [UIFont systemFontOfSize:18.0];
// CGFloat titleLabelMaxWidth = self.size.width - 2*titleLabelLeftOffset;
// CGSize titleLabelMaxSize = CGSizeMake(titleLabelMaxWidth, CGFLOAT_MAX);
// CGSize titleTextSize = [CJAlertView getTextSizeFromString:title withFont:titleLabelFont maxSize:titleLabelMaxSize mode:NSLineBreakByCharWrapping];
// CGFloat titleTextHeight = titleTextSize.height;
//
// UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
// //titleLabel.backgroundColor = [UIColor clearColor];
// titleLabel.numberOfLines = 0;
// titleLabel.textAlignment = NSTextAlignmentCenter;
// titleLabel.font = titleLabelFont;
// titleLabel.textColor = [UIColor blackColor];
// titleLabel.text = title;
// [self addSubview:titleLabel];
// [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
// make.centerX.equalTo(self);
// make.left.equalTo(self).offset(titleLabelLeftOffset);
// if (self.flagImageView) {
// make.top.equalTo(self.flagImageView.mas_bottom).offset(10);
// } else {
// make.top.equalTo(self).offset(25);
// }
// make.height.equalTo(titleTextHeight);
// }];
// _titleLabel = titleLabel;
//
//
// // messageLabel
// CGFloat messageLabelLeftOffset = 20;
// UIFont *messageLabelFont = [UIFont systemFontOfSize:15.0];
// CGFloat messageLabelMaxWidth = self.size.width - 2*messageLabelLeftOffset;
// CGSize messageLabelMaxSize = CGSizeMake(messageLabelMaxWidth, CGFLOAT_MAX);
// CGSize messageTextSize = [CJAlertView getTextSizeFromString:message withFont:messageLabelFont maxSize:messageLabelMaxSize mode:NSLineBreakByCharWrapping];
// CGFloat messageTextHeight = messageTextSize.height;
//
// UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectZero];
// //messageLabel.backgroundColor = [UIColor clearColor];
// messageLabel.numberOfLines = 0;
// messageLabel.textAlignment = NSTextAlignmentCenter;
// messageLabel.font = messageLabelFont;
// messageLabel.textColor = messageTextColor;
// messageLabel.text = message;
// [self addSubview:messageLabel];
// [messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
// make.centerX.equalTo(self);
// make.left.equalTo(self).offset(messageLabelLeftOffset);
// make.top.equalTo(titleLabel.mas_bottom).offset(10);
// make.height.equalTo(messageTextHeight);
// }];
// _messageLabel = messageLabel;
//}
//*/
//
//
//
//@end
| 7a64e2984dce5bcd1886a13a6182f58c | 39.98773 | 252 | 0.621943 | false | false | false | false |
AppCron/ACInteractor | refs/heads/master | Tests/ACInteractorTests/LazyInteractorTests.swift | apache-2.0 | 1 | import XCTest
@testable import ACInteractor
class LazyInteractorTests: XCTestCase {
let testDependency = "testDependency"
let testFactory = {return TestInteractor(dependency: "testDependency")}
var lazyInteractor: LazyInteractor<TestInteractor>!
override func setUp() {
super.setUp()
lazyInteractor = LazyInteractor(factory: testFactory)
}
// MARK: - Init
func testInit_doesNotInitializeLazyInstance()
{
// Assert
XCTAssertNil(lazyInteractor.lazyInstance)
}
// MARK: - getInteractor
func testGetInteractor_returnsInstanceBuiltWithFactory()
{
// Act
let interactor = lazyInteractor.getInteractor()
// Assert
XCTAssertEqual(interactor.dependency, testDependency)
}
func testGetInteractor_alwaysReturnsSameInstance()
{
// Act
let firstInteractor = lazyInteractor.getInteractor()
let secondInteractor = lazyInteractor.getInteractor()
// Assert
XCTAssert(firstInteractor === secondInteractor)
}
// MARK: - execute
func testExceute_callsExecuteOfInteractor()
{
// Arrange
let request = TestInteractor.Request()
// Act
lazyInteractor.execute(request)
// Assert
let interactor = lazyInteractor.lazyInstance
XCTAssertEqual(interactor?.executedRequests.count, 1)
XCTAssert(interactor?.executedRequests.first === request)
}
func testExecute_alwaysUsesSameInteractorInstance() {
// Arrange
let firstRequest = TestInteractor.Request()
let secondRequest = TestInteractor.Request()
// Act
lazyInteractor.execute(firstRequest)
lazyInteractor.execute(secondRequest)
// Assert
let interactor = lazyInteractor.lazyInstance
XCTAssertEqual(interactor?.executedRequests.count, 2)
XCTAssert(interactor?.executedRequests.first === firstRequest)
XCTAssert(interactor?.executedRequests.last === secondRequest)
}
}
| dba6ffb736c62b0d193bfafa63b69f67 | 26.883117 | 75 | 0.639497 | false | true | false | false |
crazypoo/PTools | refs/heads/master | Pods/CollectionViewPagingLayout/Lib/TransformCurve.swift | mit | 1 | //
// TransformCurve.swift
// CollectionViewPagingLayout
//
// Created by Amir Khorsandi on 2/16/20.
// Copyright © 2020 Amir Khorsandi. All rights reserved.
//
import UIKit
/// Curve function type for transforming
public enum TransformCurve {
case linear
case easeIn
case easeOut
}
public extension TransformCurve {
/// Converting linear progress to curve progress
/// input and output are between 0 and 1
///
/// - Parameter progress: the current linear progress
/// - Returns: Curved progress based on self
func computeFromLinear(progress: CGFloat) -> CGFloat {
switch self {
case .linear:
return progress
case .easeIn, .easeOut:
let logValue = progress * 9
let value: CGFloat
if self == .easeOut {
value = 1 - log10(1 + (9 - logValue))
} else {
value = log10(1 + logValue)
}
return value
}
}
}
| ac8a610a2b379c402fa3b47942287998 | 22.809524 | 58 | 0.582 | false | false | false | false |
ZeeQL/ZeeQL3 | refs/heads/develop | Sources/ZeeQL/Access/Join.swift | apache-2.0 | 1 | //
// Join.swift
// ZeeQL
//
// Created by Helge Hess on 18/02/2017.
// Copyright © 2017 ZeeZide GmbH. All rights reserved.
//
/**
* Used by `Relationship` objects to connect two entities. Usually
* source/destination are the primary and foreign keys forming the
* relationship.
*/
public struct Join : Equatable, SmartDescription {
public enum Semantic : Hashable {
case fullOuterJoin, innerJoin, leftOuterJoin, rightOuterJoin
}
// TBD: rather do unowned?
public weak var source : Attribute?
public weak var destination : Attribute?
public let sourceName : String?
public let destinationName : String?
public init(source: Attribute, destination: Attribute) {
self.source = source
self.destination = destination
self.sourceName = source.name
self.destinationName = destination.name
}
public init(source: String, destination: String) {
self.sourceName = source
self.destinationName = destination
}
public init(join: Join, disconnect: Bool = false) {
if disconnect {
sourceName = join.sourceName ?? join.source?.name
destinationName = join.destinationName ?? join.destination?.name
}
else {
source = join.source
destination = join.destination
sourceName = join.sourceName
destinationName = join.destinationName
}
}
public func references(property: Property) -> Bool {
// TODO: look into data-path for flattened relationships
// TODO: call ==
return property === source || property === destination
}
// MARL: - resolve objects in models
public mutating func connectToEntities(from: Entity, to: Entity) {
if let n = sourceName { source = from[attribute: n] }
if let n = destinationName { destination = to [attribute: n] }
}
public mutating func disconnect() {
source = nil
destination = nil
}
public var isConnected : Bool {
if sourceName != nil && source == nil { return false }
if destinationName != nil && destination == nil { return false }
return true
}
// MARK: - operations
public var inverse : Join {
if let ndest = source, let nsource = destination {
return Join(source: nsource, destination: ndest)
}
return Join(source : destinationName ?? "ERROR",
destination : sourceName ?? "ERROR")
}
public func isReciprocalTo(join other: Join) -> Bool {
/* fast check (should work often) */
if let msource = self.source,
let osource = other.source,
let mdest = self.destination,
let odest = other.destination
{
if msource === odest && mdest === osource { return true }
}
/* slow check */
// hm
guard let msn = sourceName ?? source?.name else { return false }
guard let odn = other.destinationName ?? other.destination?.name
else { return false }
guard msn == odn else { return false }
guard let osn = other.sourceName ?? other.source?.name else { return false }
guard let mdn = destinationName ?? destination?.name else { return false }
guard osn == mdn else { return false }
return true
}
// MARK: - Description
public func appendToDescription(_ ms: inout String) {
ms += " "
ms += shortDescription
}
var shortDescription : String {
let fromKey: String?, toKey: String?
if let s = source { fromKey = s.name }
else if let s = sourceName { fromKey = "'\(s)'" }
else { fromKey = nil }
if let s = destination { toKey = s.name }
else if let s = destinationName { toKey = "'\(s)'" }
else { toKey = nil }
if let from = fromKey, let to = toKey { return "\(from)=>\(to)" }
else if let from = fromKey { return "\(from)=>?" }
else if let to = toKey { return "?=>\(to)" }
else { return "?" }
}
// MARK: - Equatable
public static func ==(lhs: Join, rhs: Join) -> Bool {
/* fast check (should work often) */
if lhs.source === rhs.source && lhs.destination === rhs.destination {
return true
}
/* slow check */
// TODO: call ==
return false
}
public func isEqual(to object: Any?) -> Bool {
guard let other = object as? Join else { return false }
return self == other
}
}
extension Join {
// Maybe that should be public API, but then framework users don't usually
// have to deal with this.
func source(in entity: Entity) -> Attribute? {
if let attr = source { return attr }
if let name = sourceName, let attr = entity[attribute: name] { return attr }
return nil
}
func destination(in entity: Entity) -> Attribute? {
if let attr = destination { return attr }
if let name = destinationName,
let attr = entity[attribute: name] { return attr }
return nil
}
}
| e40b2d21cb507498e11605c67f2e3b53 | 28.32948 | 80 | 0.592826 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | refs/heads/master | 19--Keep-On-The-Sunny-Side/Forecaster/Forecaster/CityCell.swift | cc0-1.0 | 1 | //
// GitHubFriendCell.swift
// GitHub Friends
//
// Created by Pedro Trujillo on 10/27/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import UIKit
class CityCell: UITableViewCell
{
let WeatherLabelEmoji:UILabel = UILabel(frame: CGRect(x: 5, y: 10, width: 100, height: 60))
let TemperatureLabel:UILabel = UILabel(frame: CGRect(x: UIScreen.mainScreen().bounds.width * 6/10, y: 0, width: 100, height: 80))
let SummaryLabel:UILabel = UILabel(frame: CGRect(x: UIScreen.mainScreen().bounds.width * 3/10, y: 40, width: UIScreen.mainScreen().bounds.width * 3/10, height: 40))
let NameLabel:UILabel = UILabel(frame: CGRect(x: UIScreen.mainScreen().bounds.width * 3/10, y: 5, width: UIScreen.mainScreen().bounds.width * 3/10, height: 40))
var weekDays = ["1":"Sunday","2":"Monday","3":"Tuesday","4":"Wednesday","5":"Thursday","6":"Friday","7":"Saturday","0":"Today"]
override func awakeFromNib()
{
super.awakeFromNib()
// Initialization codes
}
override func setSelected(selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setTemperaturLabel(temperature:String = "0")
{
TemperatureLabel.text = temperature+"°F"
// WeatherLabelEmoji.center.y = (imageView?.center.y)!
TemperatureLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 45)//-Next-Condensed
TemperatureLabel.textAlignment = .Center
TemperatureLabel.textColor = UIColor.blackColor()
self.addSubview(TemperatureLabel)
}
func setSummaryLabel(summary:String = "0")
{
if summary.characters.count < 7
{
self.SummaryLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 30)//-Next-Condensed
}
else
{
if summary.characters.count < 9
{
self.SummaryLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 24)//-Next-Condensed
}
else
{
self.SummaryLabel.font = UIFont(name: "AvenirNextCondensed-Bold", size: 18)//-Next-Condensed
self.SummaryLabel.numberOfLines = 2
}
}
SummaryLabel.text = summary
SummaryLabel.textAlignment = .Center
SummaryLabel.textColor = UIColor.grayColor()
self.addSubview(SummaryLabel)
}
func setNameLabel(name:String = "0")
{
if name.characters.count < 8
{
NameLabel.font = UIFont(name: "AvenirNextCondensed", size: 30)//-Next-Condensed
}
else
{
NameLabel.font = UIFont(name: "AvenirNextCondensed", size: 15)//-Next-Condensed
}
NameLabel.text = name
NameLabel.textAlignment = .Center
NameLabel.textColor = UIColor.blackColor()
self.addSubview(NameLabel)
}
func loadImage(wEmoji:String = "fog" , ImagePath:String = "gravatar.png")
{
//var cosa = "⚡️🌙☀️⛅️☁️💧💦☔️💨❄️🔥🌌⛄️⚠️❗️🌁🚀"
let dictEmoji:Dictionary = [ "clear-day": "☀️","clear-night": "🌙", "rain":"☔️", "snow":"❄️", "sleet":"💦", "wind":"💨","fog":"🌁", "cloudy":"☁️", "partly-cloudy-day":"⛅️", "partly-cloudy-night":"🌌", "hail":"⛄️", "thunderstorm":"⚡️", "tornado":"⚠️","rocket":"🚀"]
WeatherLabelEmoji.text = dictEmoji[wEmoji]
// WeatherLabelEmoji.center.y = (imageView?.center.y)!
WeatherLabelEmoji.font = UIFont(name: "HelveticaNeue-Bold", size: 80)
WeatherLabelEmoji.textAlignment = .Center
WeatherLabelEmoji.textColor = UIColor.cyanColor()
self.imageView!.image = UIImage(named: ImagePath)
self.addSubview(WeatherLabelEmoji)
// WeatherLabelEmoji.center.x = (imageView?.frame.size.width)!/2
// WeatherLabelEmoji.center.y = (imageView?.center.y)! - ((imageView?.frame.size.height)!/2)
}
func getDateDayString(wdate:String = "0") -> String //http://stackoverflow.com/questions/28875356/how-to-get-next-10-days-from-current-date-in-swift
{//http://stackoverflow.com/questions/25533147/get-day-of-week-using-nsdate-swift
let date = NSDate(timeIntervalSince1970: NSTimeInterval(wdate)! ) //1415637900 )
if wdate == "0"
{
return wdate
}
else
{
let formatter = NSDateFormatter()
formatter.dateFormat = "YYYY-MM-dd"
let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components(.Weekday, fromDate: date)
let weekDay = myComponents.weekday
//let newDate = formatter.stringFromDate(date)
return self.weekDays[weekDay.description]!
}
}
}
| fe28a9c4547c90ae682d6d456469b897 | 32.726667 | 266 | 0.582922 | false | false | false | false |
vulgur/WeeklyFoodPlan | refs/heads/master | WeeklyFoodPlan/WeeklyFoodPlan/Views/Food/FoodCells/FoodHeaderViewCell.swift | mit | 1 | //
// FoodHeaderViewCell.swift
// WeeklyFoodPlan
//
// Created by vulgur on 2017/2/19.
// Copyright © 2017年 MAD. All rights reserved.
//
import UIKit
import ImagePicker
protocol FoodHeaderViewCellDelegate {
func didInputName(_ name: String)
func didToggleFavorButton()
func didTapHeaderImageView(_ imageView: UIImageView)
}
class FoodHeaderViewCell: UITableViewCell {
@IBOutlet var headerImageView: UIImageView!
@IBOutlet var headerLabel: UILabel!
@IBOutlet var favorButton: UIButton!
static let placeholderText = "输入美食名称".localized()
var delegate: FoodHeaderViewCellDelegate?
private var headerTextField: UITextField = UITextField()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let tapLabel = UITapGestureRecognizer(target: self, action: #selector(headerLabelTapped))
headerLabel.addGestureRecognizer(tapLabel)
headerLabel.isUserInteractionEnabled = true
headerLabel.isHidden = false
headerImageView.isUserInteractionEnabled = true
let tapImageView = UITapGestureRecognizer(target: self, action: #selector(headerImageViewTapped))
headerImageView.addGestureRecognizer(tapImageView)
favorButton.addTarget(self, action: #selector(toggleButton), for: .touchUpInside)
headerTextField.isHidden = true
}
func setFavorButtonState(_ isFavored: Bool) {
if isFavored {
favorButton.setImage(#imageLiteral(resourceName: "heart"), for: .normal)
} else {
favorButton.setImage(#imageLiteral(resourceName: "unheart"), for: .normal)
}
}
@objc private func toggleButton() {
delegate?.didToggleFavorButton()
}
@objc private func headerImageViewTapped() {
delegate?.didTapHeaderImageView(headerImageView)
}
@objc private func headerLabelTapped() {
let frame = headerLabel.frame
headerLabel.isHidden = true
self.contentView.addSubview(headerTextField)
headerTextField.frame = frame
headerTextField.backgroundColor = UIColor.white
headerTextField.textAlignment = .center
headerTextField.delegate = self
headerTextField.isHidden = false
headerTextField.becomeFirstResponder()
}
}
extension FoodHeaderViewCell: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if headerLabel.text == FoodHeaderViewCell.placeholderText {
textField.text = ""
} else {
textField.text = headerLabel.text
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
headerLabel.isHidden = false
if let text = textField.text {
if text.isEmpty {
headerLabel.text = FoodHeaderViewCell.placeholderText
} else {
headerLabel.text = text
delegate?.didInputName(text)
}
}
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
headerLabel.isHidden = false
if let text = textField.text {
if text.isEmpty {
headerLabel.text = FoodHeaderViewCell.placeholderText
} else {
headerLabel.text = text
delegate?.didInputName(text)
}
}
textField.removeFromSuperview()
}
}
| a962f669320bf721b93acfceaa981ee0 | 31.299065 | 105 | 0.651331 | false | false | false | false |
MessageKit/MessageKit | refs/heads/main | Sources/Views/Cells/AudioMessageCell.swift | mit | 1 | // MIT License
//
// Copyright (c) 2017-2019 MessageKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import AVFoundation
import UIKit
/// A subclass of `MessageContentCell` used to display video and audio messages.
open class AudioMessageCell: MessageContentCell {
// MARK: Open
/// Responsible for setting up the constraints of the cell's subviews.
open func setupConstraints() {
playButton.constraint(equalTo: CGSize(width: 25, height: 25))
playButton.addConstraints(
left: messageContainerView.leftAnchor,
centerY: messageContainerView.centerYAnchor,
leftConstant: 5)
activityIndicatorView.addConstraints(centerY: playButton.centerYAnchor, centerX: playButton.centerXAnchor)
durationLabel.addConstraints(
right: messageContainerView.rightAnchor,
centerY: messageContainerView.centerYAnchor,
rightConstant: 15)
progressView.addConstraints(
left: playButton.rightAnchor,
right: durationLabel.leftAnchor,
centerY: messageContainerView.centerYAnchor,
leftConstant: 5,
rightConstant: 5)
}
open override func setupSubviews() {
super.setupSubviews()
messageContainerView.addSubview(playButton)
messageContainerView.addSubview(activityIndicatorView)
messageContainerView.addSubview(durationLabel)
messageContainerView.addSubview(progressView)
setupConstraints()
}
open override func prepareForReuse() {
super.prepareForReuse()
progressView.progress = 0
playButton.isSelected = false
activityIndicatorView.stopAnimating()
playButton.isHidden = false
durationLabel.text = "0:00"
}
/// Handle tap gesture on contentView and its subviews.
open override func handleTapGesture(_ gesture: UIGestureRecognizer) {
let touchLocation = gesture.location(in: self)
// compute play button touch area, currently play button size is (25, 25) which is hardly touchable
// add 10 px around current button frame and test the touch against this new frame
let playButtonTouchArea = CGRect(
playButton.frame.origin.x - 10.0,
playButton.frame.origin.y - 10,
playButton.frame.size.width + 20,
playButton.frame.size.height + 20)
let translateTouchLocation = convert(touchLocation, to: messageContainerView)
if playButtonTouchArea.contains(translateTouchLocation) {
delegate?.didTapPlayButton(in: self)
} else {
super.handleTapGesture(gesture)
}
}
// MARK: - Configure Cell
open override func configure(
with message: MessageType,
at indexPath: IndexPath,
and messagesCollectionView: MessagesCollectionView)
{
super.configure(with: message, at: indexPath, and: messagesCollectionView)
guard let dataSource = messagesCollectionView.messagesDataSource else {
fatalError(MessageKitError.nilMessagesDataSource)
}
let playButtonLeftConstraint = messageContainerView.constraints.filter { $0.identifier == "left" }.first
let durationLabelRightConstraint = messageContainerView.constraints.filter { $0.identifier == "right" }.first
if !dataSource.isFromCurrentSender(message: message) {
playButtonLeftConstraint?.constant = 12
durationLabelRightConstraint?.constant = -8
} else {
playButtonLeftConstraint?.constant = 5
durationLabelRightConstraint?.constant = -15
}
guard let displayDelegate = messagesCollectionView.messagesDisplayDelegate else {
fatalError(MessageKitError.nilMessagesDisplayDelegate)
}
let tintColor = displayDelegate.audioTintColor(for: message, at: indexPath, in: messagesCollectionView)
playButton.imageView?.tintColor = tintColor
durationLabel.textColor = tintColor
progressView.tintColor = tintColor
if case .audio(let audioItem) = message.kind {
durationLabel.text = displayDelegate.audioProgressTextFormat(
audioItem.duration,
for: self,
in: messagesCollectionView)
}
displayDelegate.configureAudioCell(self, message: message)
}
// MARK: Public
/// The play button view to display on audio messages.
public lazy var playButton: UIButton = {
let playButton = UIButton(type: .custom)
let playImage = UIImage.messageKitImageWith(type: .play)
let pauseImage = UIImage.messageKitImageWith(type: .pause)
playButton.setImage(playImage?.withRenderingMode(.alwaysTemplate), for: .normal)
playButton.setImage(pauseImage?.withRenderingMode(.alwaysTemplate), for: .selected)
return playButton
}()
/// The time duration label to display on audio messages.
public lazy var durationLabel: UILabel = {
let durationLabel = UILabel(frame: CGRect.zero)
durationLabel.textAlignment = .right
durationLabel.font = UIFont.systemFont(ofSize: 14)
durationLabel.text = "0:00"
return durationLabel
}()
public lazy var activityIndicatorView: UIActivityIndicatorView = {
let activityIndicatorView = UIActivityIndicatorView(style: .medium)
activityIndicatorView.hidesWhenStopped = true
activityIndicatorView.isHidden = true
return activityIndicatorView
}()
public lazy var progressView: UIProgressView = {
let progressView = UIProgressView(progressViewStyle: .default)
progressView.progress = 0.0
return progressView
}()
}
| 4b5bcd54efac8eb0c38cd57984fe4054 | 37.901235 | 113 | 0.745795 | false | false | false | false |
soapyigu/LeetCode_Swift | refs/heads/master | DP/HouseRobberII.swift | mit | 1 | /**
* Question Link: https://leetcode.com/problems/house-robber-ii/
* Primary idea: Dynamic Programming, dp[i] = max(dp[i - 1], dp[i - 2], + nums[i])
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class HouseRobberII {
func rob(_ nums: [Int]) -> Int {
guard nums.count != 1 else {
return nums[0]
}
return max(helper(nums, 0, nums.count - 2), helper(nums, 1, nums.count - 1))
}
fileprivate func helper(_ nums: [Int], _ start: Int, _ end: Int) -> Int {
if start > end {
return 0
}
var prev = 0, current = 0
for i in start...end {
(current, prev) = (max(prev + nums[i], current), current)
}
return current
}
} | 546c674d8873340349866a1238b184bc | 25.133333 | 84 | 0.49553 | false | false | false | false |
HTWDD/HTWDresden-iOS | refs/heads/master | HTWDD/Components/Management/Main/Views/StudenAdministrationViewCell.swift | gpl-2.0 | 1 | //
// StudenAdministrationViewCell.swift
// HTWDD
//
// Created by Mustafa Karademir on 01.07.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import UIKit
class StudenAdministrationViewCell: UITableViewCell, FromNibLoadable {
// MARK: Outlets
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblSubtitle: UILabel!
@IBOutlet weak var main: UIView!
@IBOutlet weak var stackContent: UIStackView!
// MARK: - Properties
private var link: URL? = nil
override func awakeFromNib() {
super.awakeFromNib()
// Main View (Background)
main.apply {
$0.layer.cornerRadius = 4
$0.backgroundColor = UIColor.htw.cellBackground
}
// Title
lblTitle.apply {
$0.textColor = UIColor.htw.Label.primary
}
// Subtitle
lblSubtitle.apply {
$0.textColor = UIColor.htw.Label.secondary
}
}
// MARK: - View Setup
func setup(with data: StudentAdministration?) {
guard let data = data else { return }
link = URL(string: data.link)
stackContent.subviews.forEach { $0.removeFromSuperview() }
// Title
lblTitle.text = R.string.localizable.managementStudentAdministration()
// Offered Services
stackContent.addArrangedSubview(UILabel().also {
$0.text = R.string.localizable.managementStudentAdministrationOfferedServices()
$0.textColor = UIColor.htw.Label.primary
$0.font = UIFont.htw.Labels.primary
})
// REGION - Offered Services
data.offeredServices.forEach { service in
self.stackContent.addArrangedSubview(BadgeLabel().also {
$0.text = service
$0.backgroundColor = UIColor.htw.Badge.primary
$0.textColor = UIColor.htw.Label.primary
$0.font = UIFont.htw.Badges.primary
})
}
// ENDREGION - Offered Services
// SPACER
stackContent.addArrangedSubview(UIView())
// Opening Hours
stackContent.addArrangedSubview(UILabel().also {
$0.text = R.string.localizable.managementStudentAdministrationOpeningHours()
$0.textColor = UIColor.htw.Label.primary
$0.font = UIFont.htw.Labels.primary
})
// REGION - Opening Hours
data.officeHours.forEach { time in
let hStack = UIStackView().also {
$0.axis = .horizontal
$0.alignment = .top
$0.distribution = .fillEqually
}
hStack.addArrangedSubview(UILabel().also {
$0.text = time.day.localizedDescription
$0.textColor = UIColor.htw.Label.secondary
$0.font = UIFont.htw.Labels.secondary
})
let vStack = UIStackView().also {
$0.axis = .vertical
$0.alignment = .fill
$0.distribution = .fill
$0.spacing = 8
$0.setContentHuggingPriority(.required, for: .horizontal)
}
// REGION - Times
time.times.forEach { openingTime in
vStack.addArrangedSubview(BadgeLabel().also { label in
label.text = R.string.localizable.managementStudentAdministrationOpeningTimes(openingTime.begin, openingTime.end)
label.font = UIFont.htw.Badges.primary
label.backgroundColor = UIColor.htw.Badge.secondary
label.textColor = UIColor.htw.Label.secondary
label.contentMode = .scaleToFill
})
}
// ENDREGION - Times
hStack.addArrangedSubview(vStack)
self.stackContent.addArrangedSubview(hStack)
}
// ENDREGION - Opening Hours
stackContent.addArrangedSubview(UIView())
stackContent.addArrangedSubview(UIButton().also {
$0.titleLabel?.font = UIFont.from(style: .small, isBold: true)
$0.layer.cornerRadius = 4
$0.backgroundColor = UIColor.htw.lightBlueMaterial
$0.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
$0.makeDropShadow()
$0.setTitleColor(.white, for: .normal)
$0.setTitle(R.string.localizable.visit_website(), for: .normal)
$0.addTarget(self, action: #selector(visitLink), for: .touchUpInside)
})
// SPACER
stackContent.addArrangedSubview(UIView())
stackContent.addArrangedSubview(UIView())
stackContent.addArrangedSubview(UIView())
stackContent.addArrangedSubview(UIView())
stackContent.addArrangedSubview(UIView())
}
@objc private func visitLink() {
UIApplication.shared.open(link!, options: [:], completionHandler: nil)
}
}
| 0dae86ef537940c132e8d6768802652b | 35.645833 | 146 | 0.548797 | false | false | false | false |
ZacharyKhan/ZKNavigationController | refs/heads/master | ZKNavigationController/Classes/ZKNavigationController.swift | mit | 1 | //
// ZKNavigationController.swift
// ZKNavigationPopup
//
// Created by Zachary Khan on 7/25/16.
// Copyright © 2016 ZacharyKhan. All rights reserved.
//
import UIKit
import CoreGraphics
import Foundation
public class ZKNavigationController: UINavigationController {
var shown : Bool! = false
public func showAlert(PopupView: ZKNavigationPopupView?) {
if !self.shown {
print("NOTHIN SHOWN, GO AHEAD!")
let view = PopupView!
self.shown = true
let coverBarView = UIView(frame: CGRect(x: 0, y: -20, width: self.navigationBar.frame.width, height: 9))
coverBarView.backgroundColor = view.backgroundColor!
coverBarView.alpha = 0
self.navigationBar.addSubview(coverBarView)
dispatch_async(dispatch_get_main_queue(), {
UIView.animateWithDuration(1.2, animations: {
self.navigationBar.addSubview(view)
coverBarView.alpha = 1.0
view.alpha = 1.0
}, completion: { (val) in
UIView.animateWithDuration(0.65, delay: 0.3, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.65, options: .CurveEaseInOut, animations: {
coverBarView.frame = CGRect(x: 0, y: -20, width: self.navigationBar.frame.width, height: 20)
view.frame.origin.y += 55
}, completion: { (val) in
UIView.animateWithDuration(0.85, delay: 1, options: .CurveEaseIn, animations: {
view.alpha = 0
coverBarView.alpha = 0
}, completion: { (value) in
view.removeFromSuperview()
coverBarView.removeFromSuperview()
self.shown = false
})
})
})
})
} else {
print("UH OH! THERE'S ALREADY A NOTIFICATION SHOWN!")
}
}
} | 7f4469e43ad7affc30722a01a24fd6d7 | 38.12069 | 167 | 0.48545 | false | false | false | false |
wtrumler/FluentSwiftAssertions | refs/heads/master | FluentSwiftAssertions/ComparableExtension.swift | mit | 1 | //
// ComparableExtension.swift
// FluentSwiftAssertions
//
// Created by Wolfgang Trumler on 13.05.17.
// Copyright © 2017 Wolfgang Trumler. All rights reserved.
//
import Foundation
import XCTest
extension Comparable {
public var should : Self {
return self
}
public func beGreaterThan<T : Comparable>(_ expression2: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line,
assertionFunction: @escaping (_ expr1: @autoclosure () throws -> T, _ expr2: @autoclosure () throws -> T, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertGreaterThan) {
assertionFunction(self as! T, expression2, message, file, line)
}
public func beGreaterThanOrEqualTo<T : Comparable>(_ expression2: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line,
assertionFunction: @escaping (_ expr1: @autoclosure () throws -> T, _ expr2: @autoclosure () throws -> T, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertGreaterThanOrEqual) {
assertionFunction(self as! T, expression2, message, file, line)
}
public func beLessThan<T : Comparable>(_ expression2: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line,
assertionFunction: @escaping (_ expr1: @autoclosure () throws -> T, _ expr2: @autoclosure () throws -> T, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertLessThan) {
assertionFunction(self as! T, expression2, message, file, line)
}
public func beLessThanOrEqualTo<T : Comparable>(_ expression2: @autoclosure () throws -> T,
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line,
assertionFunction: @escaping (_ expr1: @autoclosure () throws -> T, _ expr2: @autoclosure () throws -> T, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertLessThanOrEqual) {
assertionFunction(self as! T, expression2, message, file, line)
}
}
| c0a664e859253a3ca362eccdafc05126 | 50.301887 | 254 | 0.539169 | false | false | false | false |
prebid/prebid-mobile-ios | refs/heads/master | PrebidMobileTests/RenderingTests/Tests/3dPartyWrappers/OpenMeasurement/OXMOpenMeasurementEventTrackerTest.swift | apache-2.0 | 1 | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
class PBMOpenMeasurementEventTrackerTest: XCTestCase {
private var logToFile: LogToFileLock?
override func tearDown() {
logToFile = nil
super.tearDown()
}
func testEventsForWebViewSession() {
let measurement = PBMOpenMeasurementWrapper()
measurement.jsLib = "{}"
let webViewSession = measurement.initializeWebViewSession(WKWebView(), contentUrl: nil)
XCTAssertNotNil(webViewSession)
XCTAssertNotNil(webViewSession?.eventTracker)
let pbmTracker = webViewSession?.eventTracker as? PBMOpenMeasurementEventTracker
XCTAssertNotNil(pbmTracker)
XCTAssertNotNil(pbmTracker?.adEvents)
XCTAssertNil(pbmTracker?.mediaEvents)
}
func testEventsForNativeVideoSession() {
let measurement = PBMOpenMeasurementWrapper()
measurement.jsLib = "{}"
let verificationParams = PBMVideoVerificationParameters()
let resource = PBMVideoVerificationResource()
resource.url = "openx.com"
resource.vendorKey = "OpenX"
resource.params = "no params"
verificationParams.verificationResources.add(resource)
let nativeVideoSession = measurement.initializeNativeVideoSession(UIView(), verificationParameters:verificationParams)
XCTAssertNotNil(nativeVideoSession)
XCTAssertNotNil(nativeVideoSession?.eventTracker)
let pbmTracker = nativeVideoSession?.eventTracker as? PBMOpenMeasurementEventTracker
XCTAssertNotNil(pbmTracker)
XCTAssertNotNil(pbmTracker?.adEvents)
XCTAssertNotNil(pbmTracker?.mediaEvents)
}
func testInvalidSession() {
logToFile = .init()
var pbmTracker = PBMOpenMeasurementEventTracker(session: OMIDPrebidorgAdSession())
XCTAssertNotNil(pbmTracker)
XCTAssertNotNil(pbmTracker.session)
UtilitiesForTesting.checkLogContains("Open Measurement can't create ad events with error")
pbmTracker = PBMOpenMeasurementEventTracker()
XCTAssertNotNil(pbmTracker)
XCTAssertNil(pbmTracker.session)
logToFile = nil
logToFile = .init()
pbmTracker.trackEvent(PBMTrackingEvent.request)
UtilitiesForTesting.checkLogContains("Measurement Session is missed")
}
}
| ed4b23f29e61f987771510ae0e283cbd | 34.517647 | 126 | 0.690626 | false | true | false | false |
blokadaorg/blokada | refs/heads/main | ios/App/Repository/PermsRepo.swift | mpl-2.0 | 1 | //
// This file is part of Blokada.
//
// 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 https://mozilla.org/MPL/2.0/.
//
// Copyright © 2021 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import Foundation
import Combine
typealias Granted = Bool
class PermsRepo: Startable {
var dnsProfilePerms: AnyPublisher<Granted, Never> {
writeDnsProfilePerms.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
var vpnProfilePerms: AnyPublisher<Granted, Never> {
writeVpnProfilePerms.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
var notificationPerms: AnyPublisher<Granted, Never> {
writeNotificationPerms.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
private lazy var notification = Services.notification
private lazy var dialog = Services.dialog
private lazy var systemNav = Services.systemNav
private lazy var sheetRepo = Repos.sheetRepo
private lazy var netxRepo = Repos.netxRepo
private lazy var dnsProfileActivatedHot = Repos.cloudRepo.dnsProfileActivatedHot
private lazy var enteredForegroundHot = Repos.stageRepo.enteredForegroundHot
private lazy var successfulPurchasesHot = Repos.paymentRepo.successfulPurchasesHot
private lazy var accountTypeHot = Repos.accountRepo.accountTypeHot
fileprivate let writeDnsProfilePerms = CurrentValueSubject<Granted?, Never>(nil)
fileprivate let writeVpnProfilePerms = CurrentValueSubject<Granted?, Never>(nil)
fileprivate let writeNotificationPerms = CurrentValueSubject<Granted?, Never>(nil)
private var previousAccountType: AccountType? = nil
private let bgQueue = DispatchQueue(label: "PermsRepoBgQueue")
private var cancellables = Set<AnyCancellable>()
func start() {
onDnsProfileActivated()
onForeground_checkNotificationPermsAndClearNotifications()
onVpnPerms()
onPurchaseSuccessful_showActivatedSheet()
onAccountTypeUpgraded_showActivatedSheet()
}
func maybeDisplayDnsProfilePermsDialog() -> AnyPublisher<Ignored, Error> {
return dnsProfilePerms.first()
.tryMap { granted -> Ignored in
if !granted {
throw "show the dns profile dialog"
} else {
return true
}
}
.tryCatch { _ in
self.displayDnsProfilePermsInstructions()
.tryMap { _ in throw "we never know if dns profile has been chosen" }
}
.eraseToAnyPublisher()
}
func maybeAskVpnProfilePerms() -> AnyPublisher<Granted, Error> {
return accountTypeHot.first()
.flatMap { it -> AnyPublisher<Granted, Error> in
if it == .Plus {
return self.vpnProfilePerms.first()
.tryMap { granted -> Ignored in
if !granted {
throw "ask for vpn profile"
} else {
return true
}
}
.eraseToAnyPublisher()
} else {
return Just(true)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
}
.tryCatch { _ in self.netxRepo.createVpnProfile() }
.eraseToAnyPublisher()
}
func askNotificationPerms() -> AnyPublisher<Granted, Error> {
return notification.askForPermissions()
.tryCatch { err in
self.dialog.showAlert(
message: L10n.notificationPermsDenied,
header: L10n.notificationPermsHeader,
okText: L10n.dnsprofileActionOpenSettings,
okAction: { self.systemNav.openAppSettings() }
)
}
.eraseToAnyPublisher()
}
func askForAllMissingPermissions() -> AnyPublisher<Ignored, Error> {
return sheetRepo.dismiss()
.delay(for: 0.3, scheduler: self.bgQueue)
.flatMap { _ in self.notification.askForPermissions() }
.tryCatch { err in
// Notification perm is optional, ask for others
return Just(true)
}
.flatMap { _ in self.maybeAskVpnProfilePerms() }
.delay(for: 0.3, scheduler: self.bgQueue)
.flatMap { _ in self.maybeDisplayDnsProfilePermsDialog() }
// Show the activation sheet again to confirm user choices, and propagate error
.tryCatch { err -> AnyPublisher<Ignored, Error> in
return Just(true)
.delay(for: 0.3, scheduler: self.bgQueue)
.tryMap { _ -> Ignored in
self.sheetRepo.showSheet(.Activated)
throw err
}
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
func displayNotificationPermsInstructions() -> AnyPublisher<Ignored, Error> {
return dialog.showAlert(
message: L10n.notificationPermsDesc,
header: L10n.notificationPermsHeader,
okText: L10n.dnsprofileActionOpenSettings,
okAction: { self.systemNav.openAppSettings() }
)
}
private func displayDnsProfilePermsInstructions() -> AnyPublisher<Ignored, Error> {
return dialog.showAlert(
message: L10n.dnsprofileDesc,
header: L10n.dnsprofileHeader,
okText: L10n.dnsprofileActionOpenSettings,
okAction: { self.systemNav.openSystemSettings() }
)
}
private func onDnsProfileActivated() {
dnsProfileActivatedHot
.sink(onValue: { it in self.writeDnsProfilePerms.send(it) })
.store(in: &cancellables)
}
private func onForeground_checkNotificationPermsAndClearNotifications() {
enteredForegroundHot
.flatMap { _ in self.notification.getPermissions() }
// When entering foreground also clear all notifications.
// It's so that we do not clutter the lock screen.
// We do have any notifications that need to stay after entering fg.
.map { allowed in
if allowed {
self.notification.clearAllNotifications()
}
return allowed
}
.sink(onValue: { it in self.writeNotificationPerms.send(it) })
.store(in: &cancellables)
}
private func onVpnPerms() {
netxRepo.permsHot
.sink(onValue: { it in self.writeVpnProfilePerms.send(it) })
.store(in: &cancellables)
}
// Will display Activated sheet on successful purchase.
// This will happen on any purchase by user or if necessary perms are missing.
// It will ignore StoreKit auto restore if necessary perms are granted.
private func onPurchaseSuccessful_showActivatedSheet() {
// successfulPurchasesHot
// .flatMap { it -> AnyPublisher<(Account, UserInitiated, Granted, Granted), Never> in
// let (account, userInitiated) = it
// return Publishers.CombineLatest4(
// Just(account), Just(userInitiated),
// self.dnsProfilePerms, self.vpnProfilePerms
// )
// .eraseToAnyPublisher()
// }
// .map { it -> Granted in
// let (account, userinitiated, dnsAllowed, vpnAllowed) = it
// if dnsAllowed && (account.type != "plus" || vpnAllowed) && !userinitiated {
// return true
// } else {
// return false
// }
// }
// .sink(onValue: { permsOk in
// if !permsOk {
// self.sheetRepo.showSheet(.Activated)
// }
// })
// .store(in: &cancellables)
}
// We want user to notice when they upgrade.
// From Libre to Cloud or Plus, as well as from Cloud to Plus.
// In the former case user will have to grant several permissions.
// In the latter case, probably just the VPN perm.
// If user is returning, it may be that he already has granted all perms.
// But we display the Activated sheet anyway, as a way to show that upgrade went ok.
// This will also trigger if StoreKit sends us transaction (on start) that upgrades.
private func onAccountTypeUpgraded_showActivatedSheet() {
accountTypeHot
.filter { now in
if self.previousAccountType == nil {
self.previousAccountType = now
return false
}
let prev = self.previousAccountType
self.previousAccountType = now
if prev == .Libre && now != .Libre {
return true
} else if prev == .Cloud && now == .Plus {
return true
} else {
return false
}
}
.sink(onValue: { _ in self.sheetRepo.showSheet(.Activated)} )
.store(in: &cancellables)
}
}
| fc96e45dcd95febf695cec40f660423e | 36.220833 | 93 | 0.611217 | false | false | false | false |
hhsolar/MemoryMaster-iOS | refs/heads/master | MemoryMaster/Utility/Transition/SlideOutAnimationController.swift | mit | 1 | import UIKit
class SlideOutAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) {
let containerView = transitionContext.containerView
let duration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, animations: {
fromView.center.y -= containerView.bounds.size.height
fromView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
}, completion: { finished in
transitionContext.completeTransition(finished)
})
}
}
}
| e2193553dea184ca38511dab7cfabaf1 | 40.55 | 107 | 0.756919 | false | false | false | false |
EmmaXiYu/SE491 | refs/heads/master | DonateParkSpot/DonateParkSpot/BuyDetailController.swift | apache-2.0 | 1 | //
// BuyDetailController.swift
// DonateParkSpot
//
// Created by Rafael Guerra on 10/29/15.
// Copyright © 2015 Apple. All rights reserved.
//
import UIKit
import MapKit
import Parse
class BuyDetailController : UIViewController, MKMapViewDelegate {
var spot : Spot?
//var ownerName:String = ""
//var ownerId:String = ""
@IBOutlet weak var map: MKMapView!
@IBOutlet weak var type: UILabel!
@IBOutlet weak var rate: UILabel!
@IBOutlet weak var timeToLeave: UILabel!
@IBOutlet weak var minDonation: UILabel!
@IBOutlet weak var donation: UIStepper!
let locationManager=CLLocationManager()
override func viewDidLoad() {
if spot != nil {
self.title = spot!.owner!.email! + "'s Spot"
if spot!.type == 1 {
type.text = "Paid Spot"
rate.text = "U$ " + spot!.rate.description + "0"
timeToLeave.text = spot!.timeToLeave?.description
minDonation.text = "U$ " + spot!.minDonation.description + ".00"
}else{
type.text = "Free Spot"
rate.text = "Free"
timeToLeave.text = "Zero Minutes"
minDonation.text = "U$ " + spot!.minDonation.description + ".00"
}
donation.minimumValue = Double(spot!.minDonation)
donation.maximumValue = 1.79e307
donation.stepValue = 1
self.map.delegate = self
self.locationManager.desiredAccuracy=kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
let pinLocation: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: (spot?.location.latitude)!, longitude: (spot?.location.longitude)!)
let region=MKCoordinateRegion(center: pinLocation, span: MKCoordinateSpan(latitudeDelta: 0.004, longitudeDelta: 0.004))
self.map.setRegion(region, animated: true)
let annotation = CustomerAnnotation(coordinate: pinLocation,spotObject: spot!, title :(spot!.owner!.email!),subtitle: (spot!.owner?.objectId)!)
//annotation.subtitle = "Rating bar here"
self.map.addAnnotation(annotation)
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation
) -> MKAnnotationView!{
if let a = annotation as? CustomerAnnotation {
let pinAnnotationView = MKPinAnnotationView(annotation: a, reuseIdentifier: "myPin")
//let ownerID:String = a.subtitle!
let spot = a.spot
let ownerScore = a.spot.owner?.getRatingAsSeller()
let name = a.title!
let ownerID:String = (a.spot.owner?.objectId)!
a.subtitle = String(ownerScore!)
let pic = UIImageView (image: UIImage(named: "test.png"))
pinAnnotationView.canShowCallout = true
pinAnnotationView.draggable = false
pinAnnotationView.canShowCallout = true
pinAnnotationView.animatesDrop = true
pinAnnotationView.pinColor = MKPinAnnotationColor.Purple
let query = PFUser.query()
do{ let user = try query!.getObjectWithId(ownerID) as! PFUser
if let userPicture = user["Image"] as? PFFile {
userPicture.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
if error == nil {
pic.image = UIImage(data:imageData!)
}
}
}
}
catch{
//Throw exception here
}
pic.frame = CGRectMake(0, 0, 40, 40);
pinAnnotationView.leftCalloutAccessoryView = pic
pinAnnotationView.frame = CGRectMake(0,0,500,500)
return pinAnnotationView
}
return nil
}
@IBAction func upDown(sender: UIStepper) {
minDonation.text = "U$ " + sender.value.description + "0"
}
@IBAction func buy() {
if(IsValidBuyer() == true){
let user = PFUser.currentUser()
let query = PFQuery.init(className: "Bid")
query.whereKey("user", equalTo: user!)
query.whereKey("spot", equalTo: spot!.toPFObject())
query.whereKey("StatusId", notEqualTo: 4) // 4 is cancel by bid owner
do{
let results = try query.findObjects()
if results.count > 0 {
let alert = UIAlertView.init(title: "Bid already made", message: "You cannot bid twice on a Spot. You can cancel your current Bid and bid again for this Spot", delegate: nil, cancelButtonTitle: "OK")
alert.show()
return
}
}catch{
}
let bid = Bid()
bid.bidder = user
bid.value = donation.value
bid.spot = spot
bid.statusId = 1
bid.toPFObjet().saveInBackgroundWithBlock{
(success: Bool, error: NSError?) -> Void in
if(success){
print(success)
}else{
print(error)
}
}
updateSpot((self.spot?.spotId)!, status : 1)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
func IsValidBuyer()->Bool
{
var IsValid = true
var msg = ""
if(spot?.owner?.email == PFUser.currentUser()?.email)
{
IsValid = false
msg = "You can not Bid your Own Spot" + "\r\n"
}
if(msg.characters.count > 0)
{
let alertController = UIAlertController(title: "Validation Error", message: msg, preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion:nil)
}
return IsValid
}
func updateSpot(spotid : String, status :Int)-> Void
{
let prefQuery = PFQuery(className: "Spot")
prefQuery.getObjectInBackgroundWithId(spotid){
(prefObj: PFObject?, error: NSError?) -> Void in
if error != nil {
print(error)
} else if let prefObj = prefObj {
prefObj["StatusId"] = status
prefObj.saveInBackground()
}
}
}
}
| 481b9afc0b9b561156d9abe6095e31f1 | 36.2 | 219 | 0.527731 | false | false | false | false |
jdbateman/Lendivine | refs/heads/master | Lendivine/CountriesAPI.swift | mit | 1 | //
// CountriesAPI.swift
// Lendivine
//
// Created by john bateman on 3/9/16.
// Copyright © 2016 John Bateman. All rights reserved.
//
// An extension of RESTCountries providing a wrapper api that acquires data on countries using the RestCountries API: http://restcountries.eu/,
// JSON data returned by rest queries is converted to core data manage objects on the main thread in this extension.
import Foundation
import CoreData
extension RESTCountries {
/*
@brief Get a collection of Country objects representing all countries.
@discussion Parses the data returned from the RESTCountries api into a collection of Country objects. Invokes the https://restcountries.eu/rest/v1/all endpoint.
@return A collection of Country objects, else nil if an error occurred.
*/
func getCountries(completionHandler: (countries: [Country]?, error: NSError?) -> Void) {
/* 1. Specify parameters */
// none
// set up http header parameters
// none
/* 2. Make the request */
//let apiEndpoint = "name/canada"
let apiEndpoint = "all"
taskForGETMethod(baseUrl: "https://restcountries.eu/rest/v1/", method: apiEndpoint, headerParameters: nil, queryParameters: nil) { JSONResult, error in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
// didn't work. bubble up error.
completionHandler(countries: nil, error: error)
} else {
// parse the json response
var countries = [Country]()
if let returnData = JSONResult as! [[String:AnyObject]]? {
// Ensure cored data operations happen on the main thread.
dispatch_async(dispatch_get_main_queue()) {
// Convert each dictionary in the response data into a Country object.
for dictionary in returnData {
let country:Country = Country(dictionary: dictionary, context: CoreDataContext.sharedInstance().countriesContext)
countries.append(country)
}
completionHandler(countries: countries, error: nil)
}
}
else {
completionHandler(countries: nil, error: error)
}
}
}
}
} | 12d340138bfd852a91ff7eefcc08266a | 40.852459 | 168 | 0.571708 | false | false | false | false |
a2/passcards | refs/heads/master | Sources/PasscardsServer/PasscardsServer+Vanity.swift | mit | 1 | import Foundation
import MongoKitten
import Kitura
import Shove
extension PasscardsServer {
func makeVanityRouter() -> Router {
let router = Router()
router.all(middleware: BodyParser())
router.get("/:passId", handler: getPass)
router.post("/:passId", handler: uploadPass)
router.put("/:passId", handler: updatePass)
return router
}
func getPass(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws {
guard let passName = request.parameters["passId"],
let vanityId = parseVanityId(from: passName),
let pass = try passes.findOne(matching: "vanityId" == vanityId)
else {
try response.status(.notFound).end()
return
}
guard case .binary(_, let data) = pass["data"], !data.isEmpty else {
try response.status(.noContent).end()
return
}
response.headers["Content-Type"] = "application/vnd.apple.pkpass"
if let updatedAt = pass["updatedAt"].dateValue {
response.headers["Last-Modified"] = rfc2616DateFormatter.string(from: updatedAt)
}
try response.send(data: Data(data)).end()
}
func isAuthorized(request: RouterRequest) -> Bool {
return request.headers["Authorization"] == "Token \(updateToken)"
}
func uploadPass(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws {
guard isAuthorized(request: request) else {
try response.status(.unauthorized).end()
return
}
guard let passName = request.parameters["passId"],
let vanityId = parseVanityId(from: passName)
else {
try response.status(.badRequest).end()
return
}
guard try passes.findOne(matching: "vanityId" == vanityId) == nil else {
response.headers["Location"] = request.url
try response.status(.seeOther).end()
return
}
guard case .some(.multipart(let parts)) = request.body else {
try response.status(.badRequest).end()
return
}
guard let authenticationToken = findString(in: parts, byName: "authenticationToken"),
let passTypeIdentifier = findString(in: parts, byName: "passTypeIdentifier"),
let serialNumber = findString(in: parts, byName: "serialNumber"),
let bodyData = findData(in: parts, byName: "file")
else {
try response.status(.badRequest).end()
return
}
var bodyBytes = [UInt8](repeating: 0, count: bodyData.count)
_ = bodyBytes.withUnsafeMutableBufferPointer { bufferPtr in bodyData.copyBytes(to: bufferPtr) }
let pass: Document = [
"vanityId": ~vanityId,
"authenticationToken": ~authenticationToken,
"passTypeIdentifier": ~passTypeIdentifier,
"serialNumber": ~serialNumber,
"updatedAt": ~Date(),
"data": BSON.Value.binary(subtype: .generic, data: bodyBytes),
]
try passes.insert(pass)
try response.status(.created).end()
}
func updatePass(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws {
guard isAuthorized(request: request) else {
try response.status(.unauthorized).end()
return
}
guard let passName = request.parameters["passId"],
let vanityId = parseVanityId(from: passName)
else {
try response.status(.badRequest).end()
return
}
guard var pass = try passes.findOne(matching: "vanityId" == vanityId) else {
try response.status(.notFound).end()
return
}
guard case .some(.multipart(let parts)) = request.body,
let bodyData = findData(in: parts, byName: "file")
else {
try response.status(.badRequest).end()
return
}
var bodyBytes = [UInt8](repeating: 0, count: bodyData.count)
_ = bodyBytes.withUnsafeMutableBufferPointer { bufferPtr in bodyData.copyBytes(to: bufferPtr) }
pass["data"] = .binary(subtype: .generic, data: bodyBytes)
pass["updatedAt"] = ~Date()
try passes.update(matching: "vanityId" == vanityId, to: pass)
let payload = "{\"aps\":{}}".data(using: .utf8)!
var notification = PushNotification(payload: payload)
notification.topic = pass["passTypeIdentifier"].stringValue
for installation in try installations.find(matching: "passId" == pass["_id"]) {
let deviceToken = installation["deviceToken"].string
shoveClient.send(notification: notification, to: deviceToken)
}
try response.status(.OK).end()
}
}
| 475ebf41b8c16437691ca02f094634f6 | 35.074074 | 106 | 0.598973 | false | false | false | false |
Foild/SugarRecord | refs/heads/develop | library/Core/SugarRecordResults.swift | mit | 1 | //
// SugarRecordResults.swift
// project
//
// Created by Pedro Piñera Buendía on 25/12/14.
// Copyright (c) 2014 SugarRecord. All rights reserved.
//
import Foundation
import CoreData
import Realm
public class SugarRecordResults<T>: SequenceType
{
//MARK: - Attributes
/// Array with the results of CoreData
public var coredataResults: [NSManagedObject]?
/// Array with the results of Realm
private var realmResults: RLMResults?
/// Finder element with information about predicates, sortdescriptors,...
private var finder: SugarRecordFinder<T>
/// Database Engine: CoreData, Realm, ...
internal var engine: SugarRecordEngine {
if (coredataResults != nil) {
return SugarRecordEngine.SugarRecordEngineCoreData
}
else {
return SugarRecordEngine.SugarRecordEngineRealm
}
}
//MARK: - Constructors
/**
Initializes SugarRecordResults using CoreDataResults
- parameter coredataResults: Array with NSManagedObjects
- parameter finder: Finder used to query those elements
- returns: Initialized SugarRecordResults
*/
internal init(coredataResults: [NSManagedObject], finder: SugarRecordFinder<T>)
{
self.coredataResults = coredataResults
self.finder = finder
}
/**
Initializes SugarRecordResults using Realm results
- parameter realmResults: RLMResults with the Realm results
- parameter finder: Finder used to query those elements
- returns: Initialized SugarRecordResults
*/
internal init(realmResults: RLMResults, finder: SugarRecordFinder<T>) {
self.realmResults = realmResults
self.finder = finder
}
//MARK: - Public methods
/// Returns the count of elements
public var count:Int {
get {
if (engine == SugarRecordEngine.SugarRecordEngineCoreData) {
return coredataResults!.count
}
else {
let (firstIndex, lastIndex) = indexes()
if (lastIndex == 0 && firstIndex == 0) { return Int(realmResults!.count) }
return lastIndex - firstIndex + 1
}
}
}
/**
Returns the object at a given index
- parameter index: Index of the object to be returned
- returns: Object at index position
*/
func objectAtIndex(index: UInt) -> T!
{
if (engine == SugarRecordEngine.SugarRecordEngineCoreData) {
return coredataResults![Int(index)] as! T
}
else {
let (firstIndex, _) = indexes()
return realmResults!.objectAtIndex(UInt(firstIndex) + index) as? T
}
}
/**
Returns the first object of the results
- returns: Object at position 0
*/
func firstObject() -> T!
{
if (engine == SugarRecordEngine.SugarRecordEngineCoreData) {
return coredataResults!.first! as! T
}
else {
let (firstIndex, _) = indexes()
return realmResults!.objectAtIndex(UInt(firstIndex)) as! T
}
}
/**
Returns the last object of the list
- returns: Object at last position
*/
func lastObject() -> T!
{
if (engine == SugarRecordEngine.SugarRecordEngineCoreData) {
return coredataResults!.last! as! T
}
else {
let (_, lastIndex) = indexes()
return realmResults!.objectAtIndex(UInt(lastIndex)) as! T
}
}
/**
Returns the index of a given object
- parameter object: Object whose index'll be returned
- returns: index of the given object
*/
func indexOfObject(object: T) -> Int
{
if (engine == SugarRecordEngine.SugarRecordEngineCoreData) {
if let i = coredataResults?.indexOf(object as! NSManagedObject) {
return i
}
else {
return NSNotFound
}
}
else {
let (firstIndex, _) = indexes()
return Int(realmResults!.indexOfObject(object as! RLMObject)) - firstIndex
}
}
/**
Index of a given object passed a predicate
- parameter predicate: NSPredicate to filter results
- returns: Int with the index on the filtered results
*/
func indexOfObjectWithPredicate(predicate: NSPredicate!) -> Int
{
if (engine == SugarRecordEngine.SugarRecordEngineCoreData) {
let filteredArray: SugarRecordResults<T>! = objectsWithPredicate(predicate)
let first: T! = filteredArray.firstObject()
if first != nil {
return indexOfObject(first)
}
else {
return NSNotFound
}
}
else {
let (firstIndex, _) = indexes()
return Int(realmResults!.indexOfObjectWithPredicate(predicate)) - firstIndex
}
}
/**
Returns objects filtered with the given predicate
- parameter predicate: NSPredicate for filtering
- returns: Filtered SugarRecordResults
*/
func objectsWithPredicate(predicate: NSPredicate!) -> SugarRecordResults<T>!
{
if (engine == SugarRecordEngine.SugarRecordEngineCoreData) {
let array: NSArray = NSArray(array: coredataResults!)
return SugarRecordResults(coredataResults: array.filteredArrayUsingPredicate(predicate) as! [NSManagedObject], finder: finder)
}
else {
return SugarRecordResults(realmResults: realmResults!.objectsWithPredicate(predicate), finder: SugarRecordFinder<T>())
}
}
/**
Returns objects sortered with the given sort descriptor
- parameter property: Sort descriptor key as String
- parameter ascending: Sort descriptor ascending value as Bool
- returns: Sortered SugarRecordResults
*/
func sortedResultsUsingProperty(property: String!, ascending: Bool) -> SugarRecordResults<T>!
{
if (engine == SugarRecordEngine.SugarRecordEngineCoreData) {
let array: NSArray = NSArray(array: coredataResults!)
return SugarRecordResults(coredataResults: (array.sortedArrayUsingDescriptors([NSSortDescriptor(key: property, ascending: ascending)]) as! [NSManagedObject]), finder: finder)
}
else {
return SugarRecordResults(realmResults: realmResults!.sortedResultsUsingProperty(property, ascending: ascending), finder: SugarRecordFinder<T>())
}
}
/**
Returns the REALM database engine collection.
- CoreData: Array with NSManagedObjects
- Realm: RLMResults object
- returns: original collection that depends on the database engine
*/
func realCollection() -> AnyObject
{
if (engine == SugarRecordEngine.SugarRecordEngineCoreData) {
return coredataResults!
}
else {
return realmResults!
}
}
/**
* Access to the element at a given index
*/
subscript (index: Int) -> T! {
get {
if (engine == SugarRecordEngine.SugarRecordEngineCoreData) {
return coredataResults![index] as! T
}
else {
let (firstIndex, _) = indexes()
return realmResults![UInt(index+firstIndex)] as! T
}
}
}
//MARK: - Helpers
/**
Returns the first and the last element taking into account the SugarRecordFinder options
- returns: Tuple with the first and last index
*/
func indexes() -> (Int, Int)
{
var firstIndex: Int = 0
var lastIndex: Int = Int(realmResults!.count) - 1
switch(finder.elements) {
case .first:
firstIndex = 0
lastIndex = 0
case .last:
lastIndex = Int(realmResults!.count) - 1
firstIndex = Int(realmResults!.count) - 1
case .firsts(let number):
firstIndex = 0
lastIndex = firstIndex + number - 1
if (lastIndex > Int(realmResults!.count) - 1) { lastIndex = Int(realmResults!.count) - 1 }
case .lasts(let number):
lastIndex = Int(realmResults!.count) - 1
firstIndex = firstIndex - (number - 1)
if (firstIndex < 0) { firstIndex = 0 }
default:
break
}
return (firstIndex, lastIndex)
}
//MARK: SequenceType Protocol
public func generate() -> SugarRecordResultsGenerator<T>
{
return SugarRecordResultsGenerator(results: self)
}
}
//MARK: Generator
public class SugarRecordResultsGenerator<T>: GeneratorType {
private var results: SugarRecordResults<T>
private var nextIndex: Int
init(results: SugarRecordResults<T>) {
self.results = results
nextIndex = 0
}
public func next() -> T? {
if (nextIndex < 0) {
return nil
}
return self.results[nextIndex--]
}
} | a2f47c0fccf381f41e129939d07123e4 | 28.341853 | 186 | 0.59425 | false | false | false | false |
bearjaw/RBSRealmBrowser | refs/heads/master | Pod/Classes/BrowserTools.swift | mit | 1 | //
// RBSTools.swift
// Pods
//
// Created by Max Baumbach on 03/05/2017.
//
//
import AVFoundation
import RealmSwift
final class BrowserTools {
private static let localVersion = "v0.5.0"
static func stringForProperty(_ property: Property, object: Object) -> String {
if property.isArray || property.type == .linkingObjects {
return arrayString(for: property, object: object)
}
return handleSupportedTypes(for: property, object: object)
}
static func previewText(for properties: [Property], object: Object) -> String {
properties.prefix(2).reduce(into: "") { result, property in
result += previewText(for: property, object: object)
}
}
static func previewText(for property: Property, object: Object) -> String {
guard property.type != .object, property.type != .data else { return "\(property.name):\t\t Value not supported" }
return """
\(property.name): \(handleSupportedTypes(for: property, object: object))
"""
}
static func checkForUpdates() {
guard !isPlayground() else { return }
let url = "https://img.shields.io/cocoapods/v/RBSRealmBrowser.svg"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request,
completionHandler: { data, response, _ in
guard let callback = response as? HTTPURLResponse else {
return
}
guard let data = data, callback.statusCode == 200 else { return }
let websiteData = String(data: data, encoding: .utf8)
guard let gitVersion = websiteData?.contains(localVersion) else {
return
}
if !gitVersion {
print("""
🚀 A new version of RBSRealmBrowser is now available:
https://github.com/bearjaw/RBSRealmBrowser/blob/master/CHANGELOG.md
""")
}
}).resume()
}
private static func isPlayground() -> Bool {
guard let isInPlayground = (Bundle.main.bundleIdentifier?.hasPrefix("com.apple.dt.playground")) else {
return false
}
return isInPlayground
}
private static func arrayString(for property: Property, object: Object) -> String {
if property.isArray || property.type == .linkingObjects {
let array = object.dynamicList(property.name)
return "\(array.count) objects ->"
}
return ""
}
// Disabled
// swiftlint:disable cyclomatic_complexity
private static func handleSupportedTypes(for property: Property, object: Object) -> String {
switch property.type {
case .bool:
if let value = object[property.name] as? Bool {
return value.humanReadable
}
case .int, .float, .double:
if let number = object[property.name] as? NSNumber {
return number.humanReadable
}
case .string:
if let string = object[property.name] as? String {
return string
}
case .object:
if let objectData = object[property.name] as? Object {
return objectData.humanReadable
}
return "nil"
case .any, .data, .linkingObjects:
let data = object[property.name]
return "\(data.debugDescription)"
case .date:
if let date = object[property.name] as? Date {
return "\(date)"
}
case .objectId:
if let id = object[property.name] as? ObjectId {
return id.stringValue
}
case .decimal128:
if let decimal = object[property.name] as? Decimal128 {
return "\(decimal)"
}
default:
return "\(object[property.name] as Any)"
}
return "Unsupported type"
}
}
struct RealmStyle {
static let tintColor = UIColor(red:0.35, green:0.34, blue:0.62, alpha:1.0)
}
| 2bc0c500ab5a52ed725edcaf1205b5dc | 35.934426 | 122 | 0.521971 | false | false | false | false |
C4Framework/C4iOS | refs/heads/master | C4/UI/TextShape.swift | mit | 4 | // Copyright © 2014 C4
//
// 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 QuartzCore
import UIKit
import Foundation
/// TextShape defines a concrete subclass of Shape that draws a bezier curve whose shape looks like text.
public class TextShape: Shape {
/// The text used to define the shape's path. Defaults to "C4".
public var text: String = "C4" {
didSet {
updatePath()
}
}
/// The font used to define the shape's path. Defaults to AvenirNext-DemiBold, 80pt.
public var font = Font(name: "AvenirNext-DemiBold", size: 80)! {
didSet {
updatePath()
}
}
/// Initializes an empty TextShape.
override init() {
super.init()
lineWidth = 0.0
fillColor = C4Pink
}
/// Initializes a new TextShape from a specifed string and a font
///
/// ````
/// let f = Font(name:"Avenir Next", size: 120)
/// let t = TextShape(text:"C4", font: f)
/// t.center = canvas.center
/// canvas.add(t)
/// ````
///
/// - parameter text: The string to be rendered as a shape
/// - parameter font: The font used to define the shape of the text
public convenience init?(text: String, font: Font) {
self.init()
self.text = text
self.font = font
updatePath()
origin = Point()
}
/// Initializes a new TextShape from a specifed string, using C4's default font.
///
/// ````
/// let t = TextShape(text:"C4")
/// t.center = canvas.center
/// canvas.add(t)
/// ````
///
/// - parameter text: text The string to be rendered as a shape
public convenience init?(text: String) {
guard let font = Font(name: "AvenirNext-DemiBold", size: 80) else {
return nil
}
self.init(text: text, font: font)
}
override func updatePath() {
path = TextShape.createTextPath(text: text, font: font)
adjustToFitPath()
}
internal class func createTextPath(text: String, font: Font) -> Path? {
let ctfont = font.ctFont as CTFont?
if ctfont == nil {
return nil
}
var unichars = [UniChar](text.utf16)
var glyphs = [CGGlyph](repeating: 0, count: unichars.count)
if !CTFontGetGlyphsForCharacters(ctfont!, &unichars, &glyphs, unichars.count) {
// Failed to encode characters into glyphs
return nil
}
var advances = [CGSize](repeating: CGSize(), count: glyphs.count)
CTFontGetAdvancesForGlyphs(ctfont!, .default, &glyphs, &advances, glyphs.count)
let textPath = CGMutablePath()
var invert = CGAffineTransform(scaleX: 1, y: -1)
var origin = CGPoint()
for (advance, glyph) in zip(advances, glyphs) {
if let glyphPath = CTFontCreatePathForGlyph(ctfont!, glyph, &invert) {
let translation = CGAffineTransform(translationX: origin.x, y: origin.y)
textPath.addPath(glyphPath, transform: translation)
}
origin.x += CGFloat(advance.width)
origin.y += CGFloat(advance.height)
}
return Path(path: textPath)
}
}
| aa0fa1294afaed93ea8105e26153c188 | 35.439655 | 105 | 0.630944 | false | false | false | false |
necrowman/CRLAlamofireFuture | refs/heads/master | Carthage/Checkouts/Future/Future/Promise.swift | mit | 111 | //===--- Promise.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
import Boilerplate
import Result
import ExecutionContext
public class Promise<V> : MutableFutureType {
public typealias Value = V
private let _future:MutableFuture<V>
public var future:Future<V> {
get {
return _future
}
}
public init() {
_future = MutableFuture(context: immediate)
}
public func tryComplete<E : ErrorProtocol>(result:Result<Value, E>) -> Bool {
return _future.tryComplete(result)
}
} | aecffe98bf3a59524efcefd305c17d29 | 30.8 | 82 | 0.616837 | false | false | false | false |
D-32/DMSwipeCards | refs/heads/master | DMSwipeCards/Classes/DMSwipeCard.swift | mit | 1 | //
// DMSwipeCard.swift
// Pods
//
// Created by Dylan Marriott on 18/12/16.
//
//
import Foundation
import UIKit
protocol DMSwipeCardDelegate: class {
func cardSwipedLeft(_ card: DMSwipeCard)
func cardSwipedRight(_ card: DMSwipeCard)
func cardTapped(_ card: DMSwipeCard)
}
class DMSwipeCard: UIView {
weak var delegate: DMSwipeCardDelegate?
var obj: Any!
var leftOverlay: UIView?
var rightOverlay: UIView?
private let actionMargin: CGFloat = 120.0
private let rotationStrength: CGFloat = 320.0
private let rotationAngle: CGFloat = CGFloat(Double.pi) / CGFloat(8.0)
private let rotationMax: CGFloat = 1
private let scaleStrength: CGFloat = -2
private let scaleMax: CGFloat = 1.02
private var xFromCenter: CGFloat = 0.0
private var yFromCenter: CGFloat = 0.0
private var originalPoint = CGPoint.zero
override init(frame: CGRect) {
super.init(frame: frame)
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(dragEvent(gesture:)))
panGesture.delegate = self
self.addGestureRecognizer(panGesture)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapEvent(gesture:)))
tapGesture.delegate = self
self.addGestureRecognizer(tapGesture)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureOverlays() {
self.configureOverlay(overlay: self.leftOverlay)
self.configureOverlay(overlay: self.rightOverlay)
}
private func configureOverlay(overlay: UIView?) {
if let o = overlay {
self.addSubview(o)
o.alpha = 0.0
}
}
@objc func dragEvent(gesture: UIPanGestureRecognizer) {
xFromCenter = gesture.translation(in: self).x
yFromCenter = gesture.translation(in: self).y
switch gesture.state {
case .began:
self.originalPoint = self.center
break
case .changed:
let rStrength = min(xFromCenter / self.rotationStrength, rotationMax)
let rAngle = self.rotationAngle * rStrength
let scale = min(1 - fabs(rStrength) / self.scaleStrength, self.scaleMax)
self.center = CGPoint(x: self.originalPoint.x + xFromCenter, y: self.originalPoint.y + yFromCenter)
let transform = CGAffineTransform(rotationAngle: rAngle)
let scaleTransform = transform.scaledBy(x: scale, y: scale)
self.transform = scaleTransform
self.updateOverlay(xFromCenter)
break
case .ended:
self.afterSwipeAction()
break
default:
break
}
}
@objc func tapEvent(gesture: UITapGestureRecognizer) {
self.delegate?.cardTapped(self)
}
private func afterSwipeAction() {
if xFromCenter > actionMargin {
self.rightAction()
} else if xFromCenter < -actionMargin {
self.leftAction()
} else {
UIView.animate(withDuration: 0.3) {
self.center = self.originalPoint
self.transform = CGAffineTransform.identity
self.leftOverlay?.alpha = 0.0
self.rightOverlay?.alpha = 0.0
}
}
}
private func updateOverlay(_ distance: CGFloat) {
var activeOverlay: UIView?
if (distance > 0) {
self.leftOverlay?.alpha = 0.0
activeOverlay = self.rightOverlay
} else {
self.rightOverlay?.alpha = 0.0
activeOverlay = self.leftOverlay
}
activeOverlay?.alpha = min(fabs(distance)/100, 1.0)
}
private func rightAction() {
let finishPoint = CGPoint(x: 500, y: 2 * yFromCenter + self.originalPoint.y)
UIView.animate(withDuration: 0.3, animations: {
self.center = finishPoint
}) { _ in
self.removeFromSuperview()
}
self.delegate?.cardSwipedRight(self)
}
private func leftAction() {
let finishPoint = CGPoint(x: -500, y: 2 * yFromCenter + self.originalPoint.y)
UIView.animate(withDuration: 0.3, animations: {
self.center = finishPoint
}) { _ in
self.removeFromSuperview()
}
self.delegate?.cardSwipedLeft(self)
}
}
extension DMSwipeCard: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| 9ebc243ebca1f957e9d9d528ea37202b | 26.129252 | 154 | 0.726429 | false | false | false | false |
ideafamily/Emonar | refs/heads/master | Emonar/ArchiveViewController.swift | mit | 1 | //
// ArchiveViewController.swift
// Emonar
//
// Created by ZengJintao on 3/8/16.
// Copyright © 2016 ZengJintao. All rights reserved.
//
import UIKit
class ArchiveViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var archiveTableView: UITableView!
var dataArray = FileManager.sharedInstance.getAllLocalRecordFileFromStorage()
var recordFileIndex:Int!
override func viewDidLoad() {
super.viewDidLoad()
let backButton = UIBarButtonItem()
backButton.title = ""
navigationItem.backBarButtonItem = backButton
// navigationItem.titleView
self.navigationController?.navigationBar.titleTextAttributes = [
NSForegroundColorAttributeName: UIColor.white
]
navigationController!.navigationBar.barTintColor = UIColor.black
}
override func viewWillAppear(_ animated: Bool) {
archiveTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ArchiveTableViewCell", for: indexPath) as! ArchiveTableViewCell
let index = dataArray.count - indexPath.row - 1
cell.recordNameLabel.text = self.dataArray[index].name
cell.timeLengthLabel.text = self.dataArray[index].recordLength
cell.dateLabel.text = self.dataArray[index].currentDate
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let index = dataArray.count - indexPath.row - 1
if editingStyle == .delete {
// Delete the row from the data source
dataArray.remove(at: indexPath.row)
FileManager.sharedInstance.deleteRecordFileFromStorage(index)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let index = dataArray.count - indexPath.row - 1
self.recordFileIndex = index
self.performSegue(withIdentifier: "goToReplay", sender: self)
tableView.deselectRow(at: indexPath, animated: true)
}
@IBAction func mainPressed(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "goToReplay" {
let destination = segue.destination as! ArchiveReplayViewController
let indexPath = archiveTableView.indexPathForSelectedRow!.row
let index = dataArray.count - indexPath - 1
destination.audioName = dataArray[index].name
destination.recordFileIndex = self.recordFileIndex
// print("indexpath is \(archiveTableView.indexPathForSelectedRow!.row)")
}
}
}
| 07f421e12d0fabfc452d6896159e0dcf | 35.524752 | 129 | 0.676606 | false | false | false | false |
dtartaglia/MVVM_Redux | refs/heads/master | MVVM Redux/Flow.swift | mit | 1 | //
// Flow.swift
// MVVM Redux
//
// Created by Daniel Tartaglia on 1/16/16.
// Copyright © 2016 Daniel Tartaglia. All rights reserved.
//
import Foundation
struct AppState {
var detailState = DetailState()
}
struct DetailState {
var firstName: String = ""
var lastName: String = ""
var amount: Double = 0.0
var resultText: String {
return firstName + " " + lastName + "\n" + "$" + String(amount)
}
}
enum DetailAction {
case NameChanged(String?)
case AmountChanged(String?)
}
private let combinedReducer = CombinedReducer([DetailReducer()])
struct DetailReducer: Reducer {
typealias ReducerStateType = DetailState
func handleAction(state: ReducerStateType, action: Action) -> ReducerStateType {
var result = state
switch action as! DetailAction {
case .NameChanged(let newName):
if let newName = newName {
result.firstName = extractFirstName(newName)
result.lastName = extractLastName(newName)
}
else {
result.firstName = ""
result.lastName = ""
}
case .AmountChanged(let newAmount):
if let newAmount = newAmount, let value = Double(newAmount) {
result.amount = value
}
else {
result.amount = 0.0
}
}
return result;
}
}
func extractFirstName(nameText: String) -> String {
let names = nameText.componentsSeparatedByString(" ").filter { !$0.isEmpty }
var result = ""
if names.count == 1 {
result = names[0]
}
else if names.count > 1 {
result = names[0..<names.count - 1].joinWithSeparator(" ")
}
return result
}
func extractLastName(nameText: String) -> String {
let names = nameText.componentsSeparatedByString(" ").filter { !$0.isEmpty }
var result = ""
if names.count > 1 {
result = names.last!
}
return result
}
let mainStore = MainStore(reducer: combinedReducer, state: DetailState())
| c82a221464225adb25ccececc2482d82 | 20.235294 | 81 | 0.68144 | false | false | false | false |
morbrian/udacity-nano-onthemap | refs/heads/master | OnTheMap/ParseClient.swift | mit | 1 | //
// ParseClient.swift
// OnTheMap
//
// Created by Brian Moriarty on 4/24/15.
// Copyright (c) 2015 Brian Moriarty. All rights reserved.
//
import Foundation
// ParseClient
// Provides simple api layer on top of WebClient designed to encapsulate
// the common patterns associated with REST apis based on the Parse framework.
public class ParseClient {
private var applicationId: String!
private var restApiKey: String!
private var StandardHeaders: [String:String] {
return [
"X-Parse-Application-Id":applicationId,
"X-Parse-REST-API-Key":restApiKey
]
}
private var webClient: WebClient!
// Initialize with app specific keys and id
// client: insteance of a WebClient
// applicationId: valid ID provided to this App for use with the Parse service.
// restApiKey: a developer API Key provided by registering with the Parse service.
public init(client: WebClient, applicationId: String, restApiKey: String) {
self.webClient = client
self.applicationId = applicationId
self.restApiKey = restApiKey
}
// Fetch a list of objects from the Parse service for the specified class type.
// className: the object model classname of the data type on Parse
// limit: maximum number of objects to fetch
// skip: number of objects to skip before fetching the limit.
// orderedBy: name of an attribute on the object model to sort results by.
// whereClause: Parse formatted query where clause to constrain query results.
public func fetchResultsForClassName(className: String, limit: Int = 50, skip: Int = 0, orderedBy: String = ParseJsonKey.UpdatedAt,
whereClause: String? = nil,
completionHandler: (resultsArray: [[String:AnyObject]]?, error: NSError?) -> Void) {
var parameterList: [String:AnyObject] = [ParseParameter.Limit:limit, ParseParameter.Skip: skip, ParseParameter.Order: orderedBy]
if let whereClause = whereClause {
parameterList[ParseParameter.Where] = whereClause
}
if let request = webClient.createHttpRequestUsingMethod(WebClient.HttpGet, forUrlString: "\(ParseClient.ObjectUrl)/\(className)",
includeHeaders: StandardHeaders,
includeParameters: parameterList) {
webClient.executeRequest(request) { jsonData, error in
if let resultsArray = jsonData?.valueForKey(ParseJsonKey.Results) as? [[String:AnyObject]] {
completionHandler(resultsArray: resultsArray, error: nil)
} else if let error = error {
completionHandler(resultsArray: nil, error: error)
} else if let errorMessage = jsonData?.valueForKey(ParseJsonKey.Error) as? String {
completionHandler(resultsArray: nil, error: ParseClient.errorForCode(.ParseServerError, message: errorMessage))
} else {
completionHandler(resultsArray: nil, error: ParseClient.errorForCode(.ResponseContainedNoResultObject))
}
}
} else {
completionHandler(resultsArray: nil, error: WebClient.errorForCode(.UnableToCreateRequest))
}
}
// Create an object of the specified class type.
// PRE: properties MUST NOT already contain an objectId, createdAt, or updatedAt properties.
// className: the object model classname of the data type on Parse
// withProperties: key value pair attributes of the new object.
// completionHandler - objectId: the ID of the newly create object
// completionHandler - createdAt: the time of creation for newly created object.
public func createObjectOfClassName(className: String, withProperties properties: [String:AnyObject],
completionHandler: (objectId: String?, createdAt: String?, error: NSError?) -> Void) {
performHttpMethod(WebClient.HttpPost, ofClassName: className, withProperties: properties) { jsonData, error in
if let objectId = jsonData?.valueForKey(ParseJsonKey.ObjectId) as? String,
createdAt = jsonData?.valueForKey(ParseJsonKey.CreateAt) as? String {
completionHandler(objectId: objectId, createdAt: createdAt, error: nil)
} else if let error = error {
completionHandler(objectId: nil, createdAt: nil, error: error)
} else if let errorMessage = jsonData?.valueForKey(ParseJsonKey.Error) as? String {
completionHandler(objectId: nil, createdAt: nil, error: ParseClient.errorForCode(.ParseServerError, message: errorMessage))
} else {
let responseError = ParseClient.errorForCode(.ResponseForCreateIsMissingExpectedValues)
completionHandler(objectId: nil, createdAt: nil, error: responseError)
}
}
}
// Delete an object of the specified class type with the given objectId
// className: the object model classname of the data type on Parse
public func deleteObjectOfClassName(className: String, objectId: String? = nil, completionHandler: (error: NSError?) -> Void) {
performHttpMethod(WebClient.HttpDelete, ofClassName: className, objectId: objectId) { jsonData, error in
completionHandler(error: error)
}
}
// Update an object of the specified class type and objectId with the new properties.
// className: the object model classname of the data type on Parse
// withProperties: key value pair attributes to update the object.
// objectId: the unique id of the object to update.
// completionHandler - updatedAt: the time object is updated when update successful
public func updateObjectOfClassName(className: String, withProperties properties: [String:AnyObject], objectId: String? = nil,
completionHandler: (updatedAt: String?, error: NSError?) -> Void) {
print("Raw Data: \(properties)")
performHttpMethod(WebClient.HttpPut, ofClassName: className, withProperties: properties, objectId: objectId) { jsonData, error in
if let updatedAt = jsonData?.valueForKey(ParseJsonKey.UpdatedAt) as? String {
completionHandler(updatedAt: updatedAt, error: nil)
} else if error != nil {
completionHandler(updatedAt: nil, error: error)
} else {
let responseError = ParseClient.errorForCode(.ResponseForUpdateIsMissingExpectedValues)
completionHandler(updatedAt: nil, error: responseError)
}
}
}
// Perform an HTTP/HTTPS request with the specified configuration and content.
// method: the HTTP method to use
// ofClassName: the PARSE classname targeted by the request.
// withProperties: the data properties
// objectId: the objectId targeted by the request
// requestHandler - jsonData: the parsed body content of the response
private func performHttpMethod(method: String, ofClassName className: String, withProperties properties: [String:AnyObject] = [String:AnyObject](),
objectId: String? = nil, requestHandler: (jsonData: AnyObject?, error: NSError?) -> Void ) {
do {
let body = try NSJSONSerialization.dataWithJSONObject(properties, options: NSJSONWritingOptions.PrettyPrinted)
var targetUrlString = "\(ParseClient.ObjectUrl)/\(className)"
if let objectId = objectId {
targetUrlString += "/\(objectId)"
}
if let request = webClient.createHttpRequestUsingMethod(method, forUrlString: targetUrlString,
withBody: body, includeHeaders: StandardHeaders) {
webClient.executeRequest(request, completionHandler: requestHandler)
} else {
requestHandler(jsonData: nil, error: WebClient.errorForCode(.UnableToCreateRequest))
}
} catch {
requestHandler(jsonData: nil, error: ParseClient.errorForCode(ErrorCode.ParseServerError))
}
}
}
// MARK: - Constants
extension ParseClient {
static let BaseUrl = "https://api.parse.com"
static let BasePath = "/1/classes"
static let ObjectUrl = BaseUrl + BasePath
// use reverse-sort by Updated time as default
static let DefaultSortOrder = "-\(ParseJsonKey.UpdatedAt)"
struct DateFormat {
static let ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SZZZZZ"
}
struct Locale {
static let EN_US_POSIX = "en_US_POSIX"
}
static var DateFormatter: NSDateFormatter {
let dateFormatter = NSDateFormatter()
let enUSPosixLocale = NSLocale(localeIdentifier: ParseClient.Locale.EN_US_POSIX)
dateFormatter.locale = enUSPosixLocale
dateFormatter.dateFormat = ParseClient.DateFormat.ISO8601
return dateFormatter
}
struct ParseParameter {
static let Limit = "limit"
static let Skip = "skip"
static let Order = "order"
static let Where = "where"
}
struct ParseJsonKey {
static let Results = "results"
static let Error = "error"
static let Count = "count"
static let ObjectId = "objectId"
static let CreateAt = "createdAt"
static let UpdatedAt = "updatedAt"
}
struct Logic {
static let LessThan = "lt"
static let GreaterThan = "gt"
}
}
// MARK: - Errors {
extension ParseClient {
private static let ErrorDomain = "ParseClient"
private enum ErrorCode: Int, CustomStringConvertible {
case ResponseContainedNoResultObject = 1
case ResponseForCreateIsMissingExpectedValues
case ResponseForUpdateIsMissingExpectedValues
case ParseServerError
var description: String {
switch self {
case ResponseContainedNoResultObject: return "Server did not send any results."
case ResponseForCreateIsMissingExpectedValues: return "Response for Creating Object did not return an error but did not contain expected properties either."
case ResponseForUpdateIsMissingExpectedValues: return "Response for Updating Object did not return an error but did not contain expected properties either."
default: return "Unknown Error"
}
}
}
// createErrorWithCode
// helper function to simplify creation of error object
private static func errorForCode(code: ErrorCode, var message: String? = nil) -> NSError {
if message == nil {
message = code.description
}
let userInfo = [NSLocalizedDescriptionKey : message!]
return NSError(domain: ParseClient.ErrorDomain, code: code.rawValue, userInfo: userInfo)
}
} | 7b1354b37e18d8a28f9fc587d54239a7 | 46.454936 | 168 | 0.653039 | false | false | false | false |
DrabWeb/Komikan | refs/heads/master | Komikan/Komikan/KMFavouriteButton.swift | gpl-3.0 | 1 | //
// KMFavouriteButton.swift
// Komikan
//
// Created by Seth on 2016-02-13.
//
import Cocoa
class KMFavouriteButton: NSButton {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
// Set the alternate and regular images to the star
self.image = NSImage(named: "Star");
self.alternateImage = NSImage(named: "Star");
// Set the alternate and regular images to be vibrant
self.image?.isTemplate = true;
self.alternateImage?.isTemplate = true;
// Set the target to this
self.target = self;
// Set the action to update the button
self.action = #selector(KMFavouriteButton.updateButton);
}
/// Updates the button based on its state
func updateButton() {
// If state is true...
if(Bool(self.state as NSNumber)) {
// Animate the buttons alpha value to 1
self.animator().alphaValue = 1;
}
else {
// Animate the buttons alpha value to 0.2
self.animator().alphaValue = 0.2;
}
}
}
| 5f47ca0d3064b1886452d4575187021a | 25.697674 | 64 | 0.573171 | false | false | false | false |
levantAJ/ResearchKit | refs/heads/master | TestVoiceActions/PromptCollectionViewController.swift | mit | 1 | //
// PromptCollectionViewController.swift
// TestVoiceActions
//
// Created by Le Tai on 8/25/16.
// Copyright © 2016 Snowball. All rights reserved.
//
import UIKit
final class PromptCollectionViewController: UICollectionViewController {
var shakeManager: ShakeManager!
var currentIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.scrollEnabled = false
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
shakeManager = ShakeManager()
currentIndex = 0
shakeManager.shakeLeft = {
guard self.currentIndex > 0 else {
ShakeManager.vibrate()
return
}
self.currentIndex = self.currentIndex - 1
self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: self.currentIndex, inSection: 0), atScrollPosition: .None, animated: true)
}
shakeManager.shakeRight = {
guard self.currentIndex < 4 else {
ShakeManager.vibrate()
return
}
self.currentIndex = self.currentIndex + 1
self.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: self.currentIndex, inSection: 0), atScrollPosition: .None, animated: true)
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
shakeManager = nil
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PromptCellectuonViewCell", forIndexPath: indexPath) as! PromptCellectuonViewCell
cell.promptImageView.image = UIImage(named: "p\(indexPath.row+1).png")
return cell
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return view.frame.size
}
}
final class PromptCellectuonViewCell: UICollectionViewCell {
@IBOutlet weak var promptImageView: UIImageView!
}
| 9654c299bac4e3f3bdc400e01da186c1 | 32.807229 | 154 | 0.659301 | false | false | false | false |
qihuang2/Game3 | refs/heads/master | Game3/Utility/GameKitHelper.swift | mit | 1 | //
// GameKitHelper.swift
// Game2
//
// Created by Qi Feng Huang on 9/9/15.
// Copyright © 2015 Qi Feng Huang. All rights reserved.
//
import GameKit
import Foundation
let singleton = GameKitHelper()
let PresentAuthenticationViewController = "PresentAuthenticationViewController"
class GameKitHelper: NSObject, GKGameCenterControllerDelegate {
var authenticationViewController: UIViewController?
var lastError:NSError?
var gameCenterEnabled:Bool
class var sharedInstance:GameKitHelper{
return singleton
}
override init(){
gameCenterEnabled = true
super.init()
}
func authenticateLocalPlayer(){
let player = GKLocalPlayer.localPlayer()
player.authenticateHandler = {(viewController,error) in
self.lastError = error
if viewController != nil{
self.authenticationViewController = viewController
NSNotificationCenter.defaultCenter().postNotificationName(PresentAuthenticationViewController, object: self)
}
else if player.authenticated{
self.gameCenterEnabled = true
}
else {
self.gameCenterEnabled = false
}
}
}
func reportScores(score:Int64, forLeaderBoardId leaderBoardId: String){
if !gameCenterEnabled{
print("player not authenticated")
return
}
let scoreReporter = GKScore(leaderboardIdentifier: leaderBoardId)
scoreReporter.value = score
scoreReporter.context = 0
let scores = [scoreReporter]
GKScore.reportScores(scores){(error) in
self.lastError = error
}
}
func showGKGameCenterViewController(viewController:GameViewController!){
let gameCenterViewController = GKGameCenterViewController()
gameCenterViewController.gameCenterDelegate = self
gameCenterViewController.viewState = .Leaderboards
viewController.presentViewController(gameCenterViewController, animated: true, completion: nil)
}
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) {
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
| b087f4426922b9e32519753a05a7496b | 30.133333 | 124 | 0.667666 | false | false | false | false |
GENG-GitHub/weibo-gd | refs/heads/master | GDWeibo/Class/Module/Home/View/RefreshControl/GDRefreshControl.swift | apache-2.0 | 1 | //
// GDRefreshControl.swift
// GDWeibo
//
// Created by geng on 15/11/5.
// Copyright © 2015年 geng. All rights reserved.
//
import UIKit
class GDRefreshControl: UIRefreshControl {
//MARK: - 属性
private let RefreshControlOffest: CGFloat = -60
//MARK: - 记录箭头的指向
private var isUp = false
//重写父类的frame属性
override var frame:CGRect {
didSet{
if frame.origin.y >= 0 {
return
}
//如果当前菊花在转
if refreshing
{
refreshView.startLoading()
}
if frame.origin.y > RefreshControlOffest && !isUp
{
print("箭头向上")
isUp = true
refreshView.startRotateTipView(isUp)
return
}else if frame.origin.y < RefreshControlOffest && isUp
{
print("箭头向下")
isUp = false
refreshView.startRotateTipView(isUp)
return
}
}
}
//MARK: - 重写endRefreshingfangf
override func endRefreshing() {
//停止系统的菊花
super.endRefreshing()
//停止自己定义的菊花转动
refreshView.stopRotating()
}
//MARK: - 重写构造方法
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init() {
super.init()
//设置菊花的颜色
tintColor = UIColor.clearColor()
//设置子控件
prepareUI()
}
//准备子控件
func prepareUI()
{
//设置子控件
self.addSubview(refreshView)
//添加约束,这里的size必须要设置,否则出现意想不到的结果
refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
}
//MARK: - 懒加载
private lazy var refreshView: GDRefreshView = GDRefreshView.refreshView()
}
//MARK: - 自定义
class GDRefreshView: UIView
{
//下拉刷新View
@IBOutlet weak var tipView: UIView!
//箭头
@IBOutlet weak var tipIcon: UIImageView!
//加载圆圈
@IBOutlet weak var loadingIcon: UIImageView!
//MARK: - 类方法加载xib
class func refreshView() -> GDRefreshView {
return NSBundle.mainBundle().loadNibNamed("GDRefreshView", owner: nil, options: nil).last as! GDRefreshView
}
//开始转动箭头
func startRotateTipView(isUp: Bool)
{
//动画移动箭头
UIView.animateWithDuration(0.25) { () -> Void in
self.tipIcon.transform = isUp ? CGAffineTransformIdentity : CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01))
}
}
//停止转动
func stopRotating()
{
//显示下拉刷新View
tipView.hidden = false
//移除动画
loadingIcon.layer.removeAllAnimations()
}
//开始加载
func startLoading(){
let animKey = "animKey"
//如果当前有动画在执行就返回
if let _ = loadingIcon.layer.animationForKey(animKey)
{
return
}
//隐藏箭头View
tipView.hidden = true
//动画旋转圆圈
let animation = CABasicAnimation(keyPath: "transform.rotation")
//设置动画时间
animation.duration = 0.25
//设置动画次数
animation.repeatCount = MAXFLOAT
//设置动画范围
animation.toValue = 2 * M_PI
//仿真切换控制器动画被停止
animation.removedOnCompletion = false
//添加动画到layer上
loadingIcon.layer.addAnimation(animation, forKey: animKey)
}
}
| a50038f270095040c86e5a156c7be503 | 19.032609 | 123 | 0.514107 | false | false | false | false |
glustful/ImageLoaderSwift | refs/heads/master | ImageLoader/UIImageView+ImageLoader.swift | mit | 1 | //
// UIImageView+ImageLoader.swift
// ImageLoader
//
// Created by Hirohisa Kawasaki on 10/17/14.
// Copyright (c) 2014 Hirohisa Kawasaki. All rights reserved.
//
import Foundation
import UIKit
private var ImageLoaderURLKey: UInt = 0
private var ImageLoaderBlockKey: UInt = 0
/**
Extension using ImageLoader sends a request, receives image and displays.
*/
extension UIImageView {
// MARK: - properties
private var URL: NSURL? {
get {
return objc_getAssociatedObject(self, &ImageLoaderURLKey) as? NSURL
}
set(newValue) {
objc_setAssociatedObject(self, &ImageLoaderURLKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
private var block: AnyObject? {
get {
return objc_getAssociatedObject(self, &ImageLoaderBlockKey)
}
set(newValue) {
objc_setAssociatedObject(self, &ImageLoaderBlockKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
// MARK: - public
public func load(URL: URLLiteralConvertible) {
load(URL, placeholder: nil) { _ in }
}
public func load(URL: URLLiteralConvertible, placeholder: UIImage?) {
load(URL, placeholder: placeholder) { _ in }
}
public func load(URL: URLLiteralConvertible, placeholder: UIImage?, completionHandler:(NSURL, UIImage?, NSError?) -> ()) {
cancelLoading()
if let placeholder = placeholder {
image = placeholder
}
let URL = URL.URL
self.URL = URL
_load(URL, completionHandler: completionHandler)
}
public func cancelLoading() {
if let URL = URL {
Manager.sharedInstance.cancel(URL, block: block as? Block)
}
}
// MARK: - private
private static let _requesting_queue = dispatch_queue_create("swift.imageloader.queues.requesting", DISPATCH_QUEUE_SERIAL)
private func _load(URL: NSURL, completionHandler:(NSURL, UIImage?, NSError?) -> ()) {
weak var wSelf = self
let completionHandler: (NSURL, UIImage?, NSError?) -> () = { URL, image, error in
if wSelf == nil {
return
}
dispatch_async(dispatch_get_main_queue(), {
// requesting is success then set image
if self.URL != nil && self.URL!.isEqual(URL) {
if let image = image {
wSelf!.image = image
}
}
completionHandler(URL, image, error)
})
}
// caching
if let image = Manager.sharedInstance.cache[URL] {
completionHandler(URL, image, nil)
return
}
dispatch_async(UIImageView._requesting_queue, {
let loader = Manager.sharedInstance.load(URL).completionHandler(completionHandler)
self.block = loader.blocks.last
return
})
}
} | ab2c3b858c91868ec1ff277bb915aa76 | 25.738739 | 126 | 0.586788 | false | false | false | false |
polenoso/TMDBiOS | refs/heads/master | theiostmdb/theiostmdb/SidePanelViewController.swift | mit | 1 | //
// SidePanelViewController.swift
// theiostmdb
//
// Created by bbva on 23/3/17.
//
//
import UIKit
@objc
protocol SidePanelViewControllerDelegate {
func optionSelected(vc: UIViewController)
}
class SidePanelViewController: UIViewController {
var delegate: SidePanelViewControllerDelegate?
let optionArray = [String](arrayLiteral: "Discover","Search")
@IBOutlet weak var optionsTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
optionsTable.delegate = self
optionsTable.dataSource = self
optionsTable.register(UINib.init(nibName: "OptionCell", bundle: nil), forCellReuseIdentifier: "optionCell")
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension SidePanelViewController: UITableViewDelegate, UITableViewDataSource{
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return 2
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
@available(iOS 2.0, *)
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "optionCell", for: indexPath) as! OptionCell
cell.titleforIndex(title: self.optionArray[indexPath.row])
return cell
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return tableView.frame.size.height/2.0
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
delegate?.optionSelected(vc: ViewController())
break
case 1:
let svc = SearchViewController(nibName: "SearchViewController", bundle: nil)
delegate?.optionSelected(vc: svc)
default:
return
}
}
}
class OptionCell: UITableViewCell{
@IBOutlet weak var optionLabel: UILabel!
func titleforIndex(title: String){
self.optionLabel.text = title
}
}
| ab5aa0f4a290821160e43823f5b19ff3 | 30.202128 | 188 | 0.684282 | false | false | false | false |
Sutto/Dollar.swift | refs/heads/master | Cent/Cent/Range.swift | mit | 16 | //
// Range.swift
// Cent
//
// Created by Ankur Patel on 6/30/14.
// Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved.
//
import Foundation
import Dollar
internal extension Range {
/// For each index in the range invoke the callback by passing the item in range
///
/// :param callback The callback function to invoke that take an element
func eachWithIndex(callback: (T) -> ()) {
for index in self {
callback(index)
}
}
/// For each index in the range invoke the callback
///
/// :param callback The callback function to invoke
func each(callback: () -> ()) {
self.eachWithIndex { (T) -> () in
callback()
}
}
}
public func ==<T: ForwardIndexType>(left: Range<T>, right: Range<T>) -> Bool {
return left.startIndex == right.startIndex && left.endIndex == right.endIndex
}
| 6f6b5686a2c8803149195cec56ae2cc5 | 24.027778 | 84 | 0.603774 | false | false | false | false |
handsomecode/InteractiveSideMenu | refs/heads/master | Sample/Sample/Menu Controllers/TweakViewController.swift | apache-2.0 | 1 | //
// TweakViewController.swift
// Sample
//
// Created by Eric Miller on 2/9/18.
// Copyright © 2018 Handsome. All rights reserved.
//
import UIKit
import InteractiveSideMenu
class TweakViewController: UIViewController, SideMenuItemContent, Storyboardable {
@IBOutlet private weak var animationDurationValueLabel: UILabel!
@IBOutlet private weak var contentScaleValueLabel: UILabel!
@IBOutlet private weak var visibilityValueLabel: UILabel!
@IBOutlet private weak var visibilitySlider: UISlider!
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
override func viewDidLoad() {
super.viewDidLoad()
visibilitySlider.maximumValue = Float(UIScreen.main.bounds.width)
if let navController = parent as? UINavigationController,
let menuContainerController = navController.parent as? MenuContainerViewController {
visibilitySlider.value = Float(menuContainerController.transitionOptions.visibleContentWidth)
visibilityValueLabel.text = "\(menuContainerController.transitionOptions.visibleContentWidth)"
}
}
@IBAction func openMenu(_ sender: UIBarButtonItem) {
showSideMenu()
}
@IBAction func animationDurationDidChange(_ slider: UISlider) {
animationDurationValueLabel.text = "\(TimeInterval(slider.value))"
if let navController = parent as? UINavigationController,
let menuContainerController = navController.parent as? MenuContainerViewController {
menuContainerController.transitionOptions.duration = TimeInterval(slider.value)
}
}
@IBAction func contentScaleDidChange(_ slider: UISlider) {
contentScaleValueLabel.text = "\(CGFloat(slider.value))"
if let navController = parent as? UINavigationController,
let menuContainerController = navController.parent as? MenuContainerViewController {
menuContainerController.transitionOptions.contentScale = CGFloat(slider.value)
}
}
@IBAction func visibilityDidChange(_ slider: UISlider) {
visibilityValueLabel.text = "\(CGFloat(slider.value))"
if let navController = parent as? UINavigationController,
let menuContainerController = navController.parent as? MenuContainerViewController {
menuContainerController.transitionOptions.visibleContentWidth = CGFloat(slider.value)
}
}
}
| c27c8ac5d266c93496f8d0d04a4e8217 | 39.114754 | 106 | 0.724561 | false | false | false | false |
mgireesh05/leetcode | refs/heads/master | LeetCodeSwiftPlayground.playground/Sources/integer-replacement.swift | mit | 1 |
/**
* Solution to the problem: https://leetcode.com/problems/integer-replacement/
*/
//Note: The number here denotes the problem id in leetcode. This is to avoid name conflict with other solution classes in the Swift playground.
public class Solution397 {
public init() {
}
var dict = [Int: Int]()
public func integerReplacement(_ n: Int) -> Int {
if(n == 1){
return 0
}
if(dict[n] != nil){
return dict[n]!
}
/* The logic is very similar to solving fibonacci using DP. Save the computed
subproblems (f(n/2) or f(n-1) or f(n+1)) in a dictionary and look them up when
encountered instead of recomputing. This will solve the problem in linear time
which would otherwise will be exponential.
*/
var minVal = 0
if(n%2 == 0){
let min0 = integerReplacement(n/2)
dict[n/2] = min0
minVal = min0 + 1
}else{
let min0 = integerReplacement(n+1)
dict[n+1] = min0
let min1 = integerReplacement(n-1)
dict[n-1] = min1
minVal = min(min0, min1) + 1
}
return minVal
}
}
| b63110c07973a432a4b37cb3ee092971 | 20.770833 | 143 | 0.647847 | false | false | false | false |
NghiaTranUIT/MaterialKit | refs/heads/master | Pods/MaterialKit/Source/MKLayer.swift | mit | 6 | //
// MKLayer.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/15/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
import QuartzCore
public enum MKTimingFunction {
case Linear
case EaseIn
case EaseOut
case Custom(Float, Float, Float, Float)
public var function: CAMediaTimingFunction {
switch self {
case .Linear:
return CAMediaTimingFunction(name: "linear")
case .EaseIn:
return CAMediaTimingFunction(name: "easeIn")
case .EaseOut:
return CAMediaTimingFunction(name: "easeOut")
case .Custom(let cpx1, let cpy1, let cpx2, let cpy2):
return CAMediaTimingFunction(controlPoints: cpx1, cpy1, cpx2, cpy2)
}
}
}
public enum MKRippleLocation {
case Center
case Left
case Right
case TapLocation
}
public class MKLayer {
private var superLayer: CALayer!
private let rippleLayer = CALayer()
private let backgroundLayer = CALayer()
private let maskLayer = CAShapeLayer()
public var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
let origin: CGPoint?
let sw = CGRectGetWidth(superLayer.bounds)
let sh = CGRectGetHeight(superLayer.bounds)
switch rippleLocation {
case .Center:
origin = CGPoint(x: sw/2, y: sh/2)
case .Left:
origin = CGPoint(x: sw*0.25, y: sh/2)
case .Right:
origin = CGPoint(x: sw*0.75, y: sh/2)
default:
origin = nil
}
if let origin = origin {
setCircleLayerLocationAt(origin)
}
}
}
public var ripplePercent: Float = 0.9 {
didSet {
if ripplePercent > 0 {
let sw = CGRectGetWidth(superLayer.bounds)
let sh = CGRectGetHeight(superLayer.bounds)
let circleSize = CGFloat(max(sw, sh)) * CGFloat(ripplePercent)
let circleCornerRadius = circleSize/2
rippleLayer.cornerRadius = circleCornerRadius
setCircleLayerLocationAt(CGPoint(x: sw/2, y: sh/2))
}
}
}
public init(superLayer: CALayer) {
self.superLayer = superLayer
let sw = CGRectGetWidth(superLayer.bounds)
let sh = CGRectGetHeight(superLayer.bounds)
// background layer
backgroundLayer.frame = superLayer.bounds
backgroundLayer.opacity = 0.0
superLayer.addSublayer(backgroundLayer)
// ripple layer
let circleSize = CGFloat(max(sw, sh)) * CGFloat(ripplePercent)
let rippleCornerRadius = circleSize/2
rippleLayer.opacity = 0.0
rippleLayer.cornerRadius = rippleCornerRadius
setCircleLayerLocationAt(CGPoint(x: sw/2, y: sh/2))
backgroundLayer.addSublayer(rippleLayer)
// mask layer
setMaskLayerCornerRadius(superLayer.cornerRadius)
backgroundLayer.mask = maskLayer
}
public func superLayerDidResize() {
CATransaction.begin()
CATransaction.setDisableActions(true)
backgroundLayer.frame = superLayer.bounds
setMaskLayerCornerRadius(superLayer.cornerRadius)
CATransaction.commit()
setCircleLayerLocationAt(CGPoint(x: superLayer.bounds.width/2, y: superLayer.bounds.height/2))
}
public func enableOnlyCircleLayer() {
backgroundLayer.removeFromSuperlayer()
superLayer.addSublayer(rippleLayer)
}
public func setBackgroundLayerColor(color: UIColor) {
backgroundLayer.backgroundColor = color.CGColor
}
public func setCircleLayerColor(color: UIColor) {
rippleLayer.backgroundColor = color.CGColor
}
public func didChangeTapLocation(location: CGPoint) {
if rippleLocation == .TapLocation {
setCircleLayerLocationAt(location)
}
}
public func setMaskLayerCornerRadius(cornerRadius: CGFloat) {
maskLayer.path = UIBezierPath(roundedRect: backgroundLayer.bounds, cornerRadius: cornerRadius).CGPath
}
public func enableMask(enable: Bool = true) {
backgroundLayer.mask = enable ? maskLayer : nil
}
public func setBackgroundLayerCornerRadius(cornerRadius: CGFloat) {
backgroundLayer.cornerRadius = cornerRadius
}
private func setCircleLayerLocationAt(center: CGPoint) {
let bounds = superLayer.bounds
let width = CGRectGetWidth(bounds)
let height = CGRectGetHeight(bounds)
let subSize = CGFloat(max(width, height)) * CGFloat(ripplePercent)
let subX = center.x - subSize/2
let subY = center.y - subSize/2
// disable animation when changing layer frame
CATransaction.begin()
CATransaction.setDisableActions(true)
rippleLayer.cornerRadius = subSize / 2
rippleLayer.frame = CGRect(x: subX, y: subY, width: subSize, height: subSize)
CATransaction.commit()
}
// MARK - Animation
public func animateScaleForCircleLayer(fromScale: Float, toScale: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) {
let rippleLayerAnim = CABasicAnimation(keyPath: "transform.scale")
rippleLayerAnim.fromValue = fromScale
rippleLayerAnim.toValue = toScale
let opacityAnim = CABasicAnimation(keyPath: "opacity")
opacityAnim.fromValue = 1.0
opacityAnim.toValue = 0.0
let groupAnim = CAAnimationGroup()
groupAnim.duration = duration
groupAnim.timingFunction = timingFunction.function
groupAnim.removedOnCompletion = false
groupAnim.fillMode = kCAFillModeForwards
groupAnim.animations = [rippleLayerAnim, opacityAnim]
rippleLayer.addAnimation(groupAnim, forKey: nil)
}
public func animateAlphaForBackgroundLayer(timingFunction: MKTimingFunction, duration: CFTimeInterval) {
let backgroundLayerAnim = CABasicAnimation(keyPath: "opacity")
backgroundLayerAnim.fromValue = 1.0
backgroundLayerAnim.toValue = 0.0
backgroundLayerAnim.duration = duration
backgroundLayerAnim.timingFunction = timingFunction.function
backgroundLayer.addAnimation(backgroundLayerAnim, forKey: nil)
}
public func animateSuperLayerShadow(fromRadius: CGFloat, toRadius: CGFloat, fromOpacity: Float, toOpacity: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) {
animateShadowForLayer(superLayer, fromRadius: fromRadius, toRadius: toRadius, fromOpacity: fromOpacity, toOpacity: toOpacity, timingFunction: timingFunction, duration: duration)
}
public func animateMaskLayerShadow() {
}
private func animateShadowForLayer(layer: CALayer, fromRadius: CGFloat, toRadius: CGFloat, fromOpacity: Float, toOpacity: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) {
let radiusAnimation = CABasicAnimation(keyPath: "shadowRadius")
radiusAnimation.fromValue = fromRadius
radiusAnimation.toValue = toRadius
let opacityAnimation = CABasicAnimation(keyPath: "shadowOpacity")
opacityAnimation.fromValue = fromOpacity
opacityAnimation.toValue = toOpacity
let groupAnimation = CAAnimationGroup()
groupAnimation.duration = duration
groupAnimation.timingFunction = timingFunction.function
groupAnimation.removedOnCompletion = false
groupAnimation.fillMode = kCAFillModeForwards
groupAnimation.animations = [radiusAnimation, opacityAnimation]
layer.addAnimation(groupAnimation, forKey: nil)
}
}
| df2355f7cccd1588015925ca9c9a03e1 | 34.266055 | 194 | 0.668965 | false | false | false | false |
bustoutsolutions/siesta | refs/heads/main | Source/Siesta/Request/NetworkRequest.swift | mit | 1 | //
// NetworkRequest.swift
// Siesta
//
// Created by Paul on 2015/12/15.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
internal final class NetworkRequestDelegate: RequestDelegate
{
// Basic metadata
private let resource: Resource
internal var config: Configuration
{ resource.configuration(for: underlyingRequest) }
internal let requestDescription: String
// Networking
private let requestBuilder: () -> URLRequest // so repeated() can re-read config
private let underlyingRequest: URLRequest
internal var networking: RequestNetworking? // present only after start()
// Progress
private var progressComputation: RequestProgressComputation
// MARK: Managing request
init(resource: Resource, requestBuilder: @escaping () -> URLRequest)
{
self.resource = resource
self.requestBuilder = requestBuilder
underlyingRequest = requestBuilder()
requestDescription =
SiestaLog.Category.enabled.contains(.network) || SiestaLog.Category.enabled.contains(.networkDetails)
? debugStr([underlyingRequest.httpMethod, underlyingRequest.url])
: "NetworkRequest"
progressComputation = RequestProgressComputation(isGet: underlyingRequest.httpMethod == "GET")
}
func startUnderlyingOperation(passingResponseTo completionHandler: RequestCompletionHandler)
{
let networking = resource.service.networkingProvider.startRequest(underlyingRequest)
{
res, data, err in
DispatchQueue.main.async
{
self.responseReceived(
underlyingResponse: res,
body: data,
error: err,
completionHandler: completionHandler)
}
}
self.networking = networking
}
func cancelUnderlyingOperation()
{
networking?.cancel()
}
func repeated() -> RequestDelegate
{
NetworkRequestDelegate(resource: resource, requestBuilder: requestBuilder)
}
// MARK: Progress
func computeProgress() -> Double
{
if let networking = networking
{ progressComputation.update(from: networking.transferMetrics) }
return progressComputation.fractionDone
}
var progressReportingInterval: TimeInterval
{ config.progressReportingInterval }
// MARK: Response handling
// Entry point for response handling. Triggered by RequestNetworking completion callback.
private func responseReceived(
underlyingResponse: HTTPURLResponse?,
body: Data?,
error: Error?,
completionHandler: RequestCompletionHandler)
{
DispatchQueue.mainThreadPrecondition()
SiestaLog.log(.network, ["Response: ", underlyingResponse?.statusCode ?? error, "←", requestDescription])
SiestaLog.log(.networkDetails, ["Raw response headers:", underlyingResponse?.allHeaderFields])
SiestaLog.log(.networkDetails, ["Raw response body:", body?.count ?? 0, "bytes"])
let responseInfo = interpretResponse(underlyingResponse, body, error)
if completionHandler.willIgnore(responseInfo)
{ return }
progressComputation.complete()
transformResponse(responseInfo, then: completionHandler.broadcastResponse)
}
private func isError(httpStatusCode: Int?) -> Bool
{
guard let httpStatusCode = httpStatusCode else
{ return false }
return httpStatusCode >= 400
}
private func interpretResponse(
_ underlyingResponse: HTTPURLResponse?,
_ body: Data?,
_ error: Error?)
-> ResponseInfo
{
if isError(httpStatusCode: underlyingResponse?.statusCode) || error != nil
{
return ResponseInfo(
response: .failure(RequestError(response: underlyingResponse, content: body, cause: error)))
}
else if underlyingResponse?.statusCode == 304
{
if let entity = resource.latestData
{
return ResponseInfo(response: .success(entity), isNew: false)
}
else
{
return ResponseInfo(
response: .failure(RequestError(
userMessage: NSLocalizedString("No data available", comment: "userMessage"),
cause: RequestError.Cause.NoLocalDataFor304())))
}
}
else
{
return ResponseInfo(response: .success(Entity<Any>(response: underlyingResponse, content: body ?? Data())))
}
}
private func transformResponse(
_ rawInfo: ResponseInfo,
then afterTransformation: @escaping (ResponseInfo) -> Void)
{
let processor = config.pipeline.makeProcessor(rawInfo.response, resource: resource)
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async
{
let processedInfo =
rawInfo.isNew
? ResponseInfo(response: processor(), isNew: true)
: rawInfo
DispatchQueue.main.async
{ afterTransformation(processedInfo) }
}
}
}
| 1c3c6e36f6865e12d03839830ce08abf | 32.814815 | 119 | 0.608251 | false | false | false | false |
IBM-MIL/BluePic | refs/heads/master | BluePic-iOS/BluePic/ViewModels/ProfileViewModel.swift | apache-2.0 | 1 | /**
* Copyright IBM Corporation 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import UIKit
class ProfileViewModel: NSObject {
//array that holds all that pictures that are displayed in the collection view
var pictureDataArray = [Picture]()
//callback used to tell the ProfileViewController when to refresh its collection view
var refreshVCCallback : (()->())!
//state variable to keep try of if the view model has receieved data from cloudant yet
var hasRecievedDataFromCloudant = false
//constant that represents the number of sections in the collection view
let kNumberOfSectionsInCollectionView = 1
//constant that represents the height of the info view in the collection view cell that shows the photos caption and photographer name
let kCollectionViewCellInfoViewHeight : CGFloat = 60
//constant that represents the limit of how big the colection view cell height can be
let kCollectionViewCellHeightLimit : CGFloat = 480
//constant that represents a value added to the height of the EmptyFeedCollectionViewCell when its given a size in the sizeForItemAtIndexPath method, this value allows the collection view to scroll
let kEmptyFeedCollectionViewCellBufferToAllowForScrolling : CGFloat = 1
//constant that represents the number of cells in the collection view when there is no photos
let kNumberOfCellsWhenUserHasNoPhotos = 1
/**
Method called upon init, it sets up the callback to refresh the profile collection view
- parameter refreshVCCallback: (()->())
- returns:
*/
init(refreshVCCallback : (()->())){
super.init()
self.refreshVCCallback = refreshVCCallback
DataManagerCalbackCoordinator.SharedInstance.addCallback(handleDataManagerNotifications)
getPictureObjects()
}
/**
Method handles notifications when there are DataManagerNotifications, it passes DataManagerNotifications to the Profile VC
- parameter dataManagerNotification: DataManagerNotification
*/
func handleDataManagerNotifications(dataManagerNotification : DataManagerNotification){
if (dataManagerNotification == DataManagerNotification.UserDecidedToPostPhoto){
getPictureObjects()
}
if (dataManagerNotification == DataManagerNotification.CloudantPullDataSuccess){
getPictureObjects()
}
else if(dataManagerNotification == DataManagerNotification.ObjectStorageUploadImageAndCloudantCreatePictureDocSuccess){
getPictureObjects()
}
}
/**
Method adds a locally stored version of the image the user just posted to the pictureDataArray
*/
func addUsersLastPhotoTakenToPictureDataArrayAndRefreshCollectionView(){
let lastPhotoTaken = CameraDataManager.SharedInstance.lastPictureObjectTaken
var lastPhotoTakenArray = [Picture]()
lastPhotoTakenArray.append(lastPhotoTaken)
pictureDataArray = lastPhotoTakenArray + pictureDataArray
callRefreshCallBack()
}
/**
Method gets the picture objects from cloudant based on the facebook unique user id. When this completes it tells the profile view controller to refresh its collection view
*/
func getPictureObjects(){
pictureDataArray = CloudantSyncDataManager.SharedInstance!.getPictureObjects(FacebookDataManager.SharedInstance.fbUniqueUserID!)
hasRecievedDataFromCloudant = true
dispatch_async(dispatch_get_main_queue()) {
self.callRefreshCallBack()
}
}
/**
method repulls for new data from cloudant
*/
func repullForNewData(){
do {
try CloudantSyncDataManager.SharedInstance!.pullFromRemoteDatabase()
} catch {
print("repullForNewData error: \(error)")
DataManagerCalbackCoordinator.SharedInstance.sendNotification(DataManagerNotification.CloudantPullDataFailure)
}
}
/**
Method returns the number of sections in the collection view
- returns: Int
*/
func numberOfSectionsInCollectionView() -> Int {
return kNumberOfSectionsInCollectionView
}
/**
Method returns the number of items in a section
- parameter section: Int
- returns: Int
*/
func numberOfItemsInSection(section : Int) -> Int {
if(pictureDataArray.count == 0 && hasRecievedDataFromCloudant == true) {
return kNumberOfCellsWhenUserHasNoPhotos
}
else {
return pictureDataArray.count
}
}
/**
Method returns the size for item at indexPath
- parameter indexPath: NSIndexPath
- parameter collectionView: UICollectionView
- parameter heightForEmptyProfileCollectionViewCell: CGFloat
- returns: CGSize
*/
func sizeForItemAtIndexPath(indexPath : NSIndexPath, collectionView : UICollectionView, heightForEmptyProfileCollectionViewCell : CGFloat) -> CGSize {
if(pictureDataArray.count == 0) {
return CGSize(width: collectionView.frame.width, height: heightForEmptyProfileCollectionViewCell + kEmptyFeedCollectionViewCellBufferToAllowForScrolling)
}
else{
let picture = pictureDataArray[indexPath.row]
if let width = picture.width, let height = picture.height {
let ratio = height / width
var height = collectionView.frame.width * ratio
if(height > kCollectionViewCellHeightLimit){
height = kCollectionViewCellHeightLimit
}
return CGSize(width: collectionView.frame.width, height: height + kCollectionViewCellInfoViewHeight)
}
else{
return CGSize(width: collectionView.frame.width, height: collectionView.frame.width + kCollectionViewCellInfoViewHeight)
}
}
}
/**
Method sets up the collection view cell for indexPath. If the pictureDataArray.count is equal to 0 then we return an instance EmptyfeedCollectionviewCell
- parameter indexPath: NSIndexPath
- parameter collectionView: UICollectionViewCell
- returns: UICollectionViewCell
*/
func setUpCollectionViewCell(indexPath : NSIndexPath, collectionView : UICollectionView) -> UICollectionViewCell {
if(pictureDataArray.count == 0){
let cell: EmptyFeedCollectionViewCell
cell = collectionView.dequeueReusableCellWithReuseIdentifier("EmptyFeedCollectionViewCell", forIndexPath: indexPath) as! EmptyFeedCollectionViewCell
return cell
}
else{
let cell: ProfileCollectionViewCell
cell = collectionView.dequeueReusableCellWithReuseIdentifier("ProfileCollectionViewCell", forIndexPath: indexPath) as! ProfileCollectionViewCell
let picture = pictureDataArray[indexPath.row]
cell.setupData(picture.url,
image: picture.image,
displayName: picture.displayName,
timeStamp: picture.timeStamp,
fileName: picture.fileName
)
cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.mainScreen().scale
return cell
}
}
/**
Method sets up the section header for the indexPath parameter
- parameter indexPath: NSIndexPath
- parameter kind: String
- parameter collectionView: UICollectionView
- returns: TripDetailSupplementaryView
*/
func setUpSectionHeaderViewForIndexPath(indexPath : NSIndexPath, kind: String, collectionView : UICollectionView) -> ProfileHeaderCollectionReusableView {
let header : ProfileHeaderCollectionReusableView
header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "ProfileHeaderCollectionReusableView", forIndexPath: indexPath) as! ProfileHeaderCollectionReusableView
header.setupData(FacebookDataManager.SharedInstance.fbUserDisplayName, numberOfShots: pictureDataArray.count, profilePictureURL : FacebookDataManager.SharedInstance.getUserFacebookProfilePictureURL())
return header
}
/**
Method tells the profile view controller to reload its collectionView
*/
func callRefreshCallBack(){
if let callback = refreshVCCallback {
callback()
}
}
}
| 744a921fb85196543ffede8ff84b7477 | 33.927007 | 208 | 0.658203 | false | false | false | false |
KaiCode2/swift-corelibs-foundation | refs/heads/master | Foundation/NSURLSession.swift | apache-2.0 | 3 | // 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
//
/*
NSURLSession is a replacement API for NSURLConnection. It provides
options that affect the policy of, and various aspects of the
mechanism by which NSURLRequest objects are retrieved from the
network.
An NSURLSession may be bound to a delegate object. The delegate is
invoked for certain events during the lifetime of a session, such as
server authentication or determining whether a resource to be loaded
should be converted into a download.
NSURLSession instances are threadsafe.
The default NSURLSession uses a system provided delegate and is
appropriate to use in place of existing code that uses
+[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]
An NSURLSession creates NSURLSessionTask objects which represent the
action of a resource being loaded. These are analogous to
NSURLConnection objects but provide for more control and a unified
delegate model.
NSURLSessionTask objects are always created in a suspended state and
must be sent the -resume message before they will execute.
Subclasses of NSURLSessionTask are used to syntactically
differentiate between data and file downloads.
An NSURLSessionDataTask receives the resource as a series of calls to
the URLSession:dataTask:didReceiveData: delegate method. This is type of
task most commonly associated with retrieving objects for immediate parsing
by the consumer.
An NSURLSessionUploadTask differs from an NSURLSessionDataTask
in how its instance is constructed. Upload tasks are explicitly created
by referencing a file or data object to upload, or by utilizing the
-URLSession:task:needNewBodyStream: delegate message to supply an upload
body.
An NSURLSessionDownloadTask will directly write the response data to
a temporary file. When completed, the delegate is sent
URLSession:downloadTask:didFinishDownloadingToURL: and given an opportunity
to move this file to a permanent location in its sandboxed container, or to
otherwise read the file. If canceled, an NSURLSessionDownloadTask can
produce a data blob that can be used to resume a download at a later
time.
Beginning with iOS 9 and Mac OS X 10.11, NSURLSessionStream is
available as a task type. This allows for direct TCP/IP connection
to a given host and port with optional secure handshaking and
navigation of proxies. Data tasks may also be upgraded to a
NSURLSessionStream task via the HTTP Upgrade: header and appropriate
use of the pipelining option of NSURLSessionConfiguration. See RFC
2817 and RFC 6455 for information about the Upgrade: header, and
comments below on turning data tasks into stream tasks.
*/
/* DataTask objects receive the payload through zero or more delegate messages */
/* UploadTask objects receive periodic progress updates but do not return a body */
/* DownloadTask objects represent an active download to disk. They can provide resume data when canceled. */
/* StreamTask objects may be used to create NSInput and NSOutputStreams, or used directly in reading and writing. */
/*
NSURLSession is not available for i386 targets before Mac OS X 10.10.
*/
public let NSURLSessionTransferSizeUnknown: Int64 = -1
public class NSURLSession : NSObject {
/*
* The shared session uses the currently set global NSURLCache,
* NSHTTPCookieStorage and NSURLCredentialStorage objects.
*/
public class func sharedSession() -> NSURLSession { NSUnimplemented() }
/*
* Customization of NSURLSession occurs during creation of a new session.
* If you only need to use the convenience routines with custom
* configuration options it is not necessary to specify a delegate.
* If you do specify a delegate, the delegate will be retained until after
* the delegate has been sent the URLSession:didBecomeInvalidWithError: message.
*/
public /*not inherited*/ init(configuration: NSURLSessionConfiguration) { NSUnimplemented() }
public /*not inherited*/ init(configuration: NSURLSessionConfiguration, delegate: NSURLSessionDelegate?, delegateQueue queue: NSOperationQueue?) { NSUnimplemented() }
public var delegateQueue: NSOperationQueue { NSUnimplemented() }
public var delegate: NSURLSessionDelegate? { NSUnimplemented() }
/*@NSCopying*/ public var configuration: NSURLSessionConfiguration { NSUnimplemented() }
/*
* The sessionDescription property is available for the developer to
* provide a descriptive label for the session.
*/
public var sessionDescription: String?
/* -finishTasksAndInvalidate returns immediately and existing tasks will be allowed
* to run to completion. New tasks may not be created. The session
* will continue to make delegate callbacks until URLSession:didBecomeInvalidWithError:
* has been issued.
*
* -finishTasksAndInvalidate and -invalidateAndCancel do not
* have any effect on the shared session singleton.
*
* When invalidating a background session, it is not safe to create another background
* session with the same identifier until URLSession:didBecomeInvalidWithError: has
* been issued.
*/
public func finishTasksAndInvalidate() { NSUnimplemented() }
/* -invalidateAndCancel acts as -finishTasksAndInvalidate, but issues
* -cancel to all outstanding tasks for this session. Note task
* cancellation is subject to the state of the task, and some tasks may
* have already have completed at the time they are sent -cancel.
*/
public func invalidateAndCancel() { NSUnimplemented() }
public func resetWithCompletionHandler(_ completionHandler: () -> Void) { NSUnimplemented() }/* empty all cookies, cache and credential stores, removes disk files, issues -flushWithCompletionHandler:. Invokes completionHandler() on the delegate queue if not nil. */
public func flushWithCompletionHandler(_ completionHandler: () -> Void) { NSUnimplemented() }/* flush storage to disk and clear transient network caches. Invokes completionHandler() on the delegate queue if not nil. */
public func getTasksWithCompletionHandler(_ completionHandler: ([NSURLSessionDataTask], [NSURLSessionUploadTask], [NSURLSessionDownloadTask]) -> Void) { NSUnimplemented() }/* invokes completionHandler with outstanding data, upload and download tasks. */
public func getAllTasksWithCompletionHandler(_ completionHandler: ([NSURLSessionTask]) -> Void) { NSUnimplemented() }/* invokes completionHandler with all outstanding tasks. */
/*
* NSURLSessionTask objects are always created in a suspended state and
* must be sent the -resume message before they will execute.
*/
/* Creates a data task with the given request. The request may have a body stream. */
public func dataTaskWithRequest(_ request: NSURLRequest) -> NSURLSessionDataTask { NSUnimplemented() }
/* Creates a data task to retrieve the contents of the given URL. */
public func dataTaskWithURL(_ url: NSURL) -> NSURLSessionDataTask { NSUnimplemented() }
/* Creates an upload task with the given request. The body of the request will be created from the file referenced by fileURL */
public func uploadTaskWithRequest(_ request: NSURLRequest, fromFile fileURL: NSURL) -> NSURLSessionUploadTask { NSUnimplemented() }
/* Creates an upload task with the given request. The body of the request is provided from the bodyData. */
public func uploadTaskWithRequest(_ request: NSURLRequest, fromData bodyData: NSData) -> NSURLSessionUploadTask { NSUnimplemented() }
/* Creates an upload task with the given request. The previously set body stream of the request (if any) is ignored and the URLSession:task:needNewBodyStream: delegate will be called when the body payload is required. */
public func uploadTaskWithStreamedRequest(_ request: NSURLRequest) -> NSURLSessionUploadTask { NSUnimplemented() }
/* Creates a download task with the given request. */
public func downloadTaskWithRequest(_ request: NSURLRequest) -> NSURLSessionDownloadTask { NSUnimplemented() }
/* Creates a download task to download the contents of the given URL. */
public func downloadTaskWithURL(_ url: NSURL) -> NSURLSessionDownloadTask { NSUnimplemented() }
/* Creates a download task with the resume data. If the download cannot be successfully resumed, URLSession:task:didCompleteWithError: will be called. */
public func downloadTaskWithResumeData(_ resumeData: NSData) -> NSURLSessionDownloadTask { NSUnimplemented() }
/* Creates a bidirectional stream task to a given host and port.
*/
public func streamTaskWithHostName(_ hostname: String, port: Int) -> NSURLSessionStreamTask { NSUnimplemented() }
}
/*
* NSURLSession convenience routines deliver results to
* a completion handler block. These convenience routines
* are not available to NSURLSessions that are configured
* as background sessions.
*
* Task objects are always created in a suspended state and
* must be sent the -resume message before they will execute.
*/
extension NSURLSession {
/*
* data task convenience methods. These methods create tasks that
* bypass the normal delegate calls for response and data delivery,
* and provide a simple cancelable asynchronous interface to receiving
* data. Errors will be returned in the NSURLErrorDomain,
* see <Foundation/NSURLError.h>. The delegate, if any, will still be
* called for authentication challenges.
*/
public func dataTaskWithRequest(_ request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask { NSUnimplemented() }
public func dataTaskWithURL(_ url: NSURL, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask { NSUnimplemented() }
/*
* upload convenience method.
*/
public func uploadTaskWithRequest(_ request: NSURLRequest, fromFile fileURL: NSURL, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionUploadTask { NSUnimplemented() }
public func uploadTaskWithRequest(_ request: NSURLRequest, fromData bodyData: NSData?, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionUploadTask { NSUnimplemented() }
/*
* download task convenience methods. When a download successfully
* completes, the NSURL will point to a file that must be read or
* copied during the invocation of the completion routine. The file
* will be removed automatically.
*/
public func downloadTaskWithRequest(_ request: NSURLRequest, completionHandler: (NSURL?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDownloadTask { NSUnimplemented() }
public func downloadTaskWithURL(_ url: NSURL, completionHandler: (NSURL?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDownloadTask { NSUnimplemented() }
public func downloadTaskWithResumeData(_ resumeData: NSData, completionHandler: (NSURL?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDownloadTask { NSUnimplemented() }
}
public enum NSURLSessionTaskState : Int {
case Running /* The task is currently being serviced by the session */
case Suspended
case Canceling /* The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError: message. */
case Completed /* The task has completed and the session will receive no more delegate notifications */
}
/*
* NSURLSessionTask - a cancelable object that refers to the lifetime
* of processing a given request.
*/
public class NSURLSessionTask : NSObject, NSCopying {
public override init() {
NSUnimplemented()
}
public override func copy() -> AnyObject {
return copyWithZone(nil)
}
public func copyWithZone(_ zone: NSZone) -> AnyObject {
NSUnimplemented()
}
public var taskIdentifier: Int { NSUnimplemented() } /* an identifier for this task, assigned by and unique to the owning session */
/*@NSCopying*/ public var originalRequest: NSURLRequest? { NSUnimplemented() } /* may be nil if this is a stream task */
/*@NSCopying*/ public var currentRequest: NSURLRequest? { NSUnimplemented() } /* may differ from originalRequest due to http server redirection */
/*@NSCopying*/ public var response: NSURLResponse? { NSUnimplemented() } /* may be nil if no response has been received */
/* Byte count properties may be zero if no body is expected,
* or NSURLSessionTransferSizeUnknown if it is not possible
* to know how many bytes will be transferred.
*/
/* number of body bytes already received */
public var countOfBytesReceived: Int64 { NSUnimplemented() }
/* number of body bytes already sent */
public var countOfBytesSent: Int64 { NSUnimplemented() }
/* number of body bytes we expect to send, derived from the Content-Length of the HTTP request */
public var countOfBytesExpectedToSend: Int64 { NSUnimplemented() }
/* number of byte bytes we expect to receive, usually derived from the Content-Length header of an HTTP response. */
public var countOfBytesExpectedToReceive: Int64 { NSUnimplemented() }
/*
* The taskDescription property is available for the developer to
* provide a descriptive label for the task.
*/
public var taskDescription: String?
/* -cancel returns immediately, but marks a task as being canceled.
* The task will signal -URLSession:task:didCompleteWithError: with an
* error value of { NSURLErrorDomain, NSURLErrorCancelled }. In some
* cases, the task may signal other work before it acknowledges the
* cancelation. -cancel may be sent to a task that has been suspended.
*/
public func cancel() { NSUnimplemented() }
/*
* The current state of the task within the session.
*/
public var state: NSURLSessionTaskState { NSUnimplemented() }
/*
* The error, if any, delivered via -URLSession:task:didCompleteWithError:
* This property will be nil in the event that no error occured.
*/
/*@NSCopying*/ public var error: NSError? { NSUnimplemented() }
/*
* Suspending a task will prevent the NSURLSession from continuing to
* load data. There may still be delegate calls made on behalf of
* this task (for instance, to report data received while suspending)
* but no further transmissions will be made on behalf of the task
* until -resume is sent. The timeout timer associated with the task
* will be disabled while a task is suspended. -suspend and -resume are
* nestable.
*/
public func suspend() { NSUnimplemented() }
public func resume() { NSUnimplemented() }
/*
* Sets a scaling factor for the priority of the task. The scaling factor is a
* value between 0.0 and 1.0 (inclusive), where 0.0 is considered the lowest
* priority and 1.0 is considered the highest.
*
* The priority is a hint and not a hard requirement of task performance. The
* priority of a task may be changed using this API at any time, but not all
* protocols support this; in these cases, the last priority that took effect
* will be used.
*
* If no priority is specified, the task will operate with the default priority
* as defined by the constant NSURLSessionTaskPriorityDefault. Two additional
* priority levels are provided: NSURLSessionTaskPriorityLow and
* NSURLSessionTaskPriorityHigh, but use is not restricted to these.
*/
public var priority: Float
}
public let NSURLSessionTaskPriorityDefault: Float = 0.0 // NSUnimplemented
public let NSURLSessionTaskPriorityLow: Float = 0.0 // NSUnimplemented
public let NSURLSessionTaskPriorityHigh: Float = 0.0 // NSUnimplemented
/*
* An NSURLSessionDataTask does not provide any additional
* functionality over an NSURLSessionTask and its presence is merely
* to provide lexical differentiation from download and upload tasks.
*/
public class NSURLSessionDataTask : NSURLSessionTask {
}
/*
* An NSURLSessionUploadTask does not currently provide any additional
* functionality over an NSURLSessionDataTask. All delegate messages
* that may be sent referencing an NSURLSessionDataTask equally apply
* to NSURLSessionUploadTasks.
*/
public class NSURLSessionUploadTask : NSURLSessionDataTask {
}
/*
* NSURLSessionDownloadTask is a task that represents a download to
* local storage.
*/
public class NSURLSessionDownloadTask : NSURLSessionTask {
/* Cancel the download (and calls the superclass -cancel). If
* conditions will allow for resuming the download in the future, the
* callback will be called with an opaque data blob, which may be used
* with -downloadTaskWithResumeData: to attempt to resume the download.
* If resume data cannot be created, the completion handler will be
* called with nil resumeData.
*/
public func cancelByProducingResumeData(_ completionHandler: (NSData?) -> Void) { NSUnimplemented() }
}
/*
* An NSURLSessionStreamTask provides an interface to perform reads
* and writes to a TCP/IP stream created via NSURLSession. This task
* may be explicitly created from an NSURLSession, or created as a
* result of the appropriate disposition response to a
* -URLSession:dataTask:didReceiveResponse: delegate message.
*
* NSURLSessionStreamTask can be used to perform asynchronous reads
* and writes. Reads and writes are enquened and executed serially,
* with the completion handler being invoked on the sessions delegate
* queuee. If an error occurs, or the task is canceled, all
* outstanding read and write calls will have their completion
* handlers invoked with an appropriate error.
*
* It is also possible to create NSInputStream and NSOutputStream
* instances from an NSURLSessionTask by sending
* -captureStreams to the task. All outstanding read and writess are
* completed before the streams are created. Once the streams are
* delivered to the session delegate, the task is considered complete
* and will receive no more messsages. These streams are
* disassociated from the underlying session.
*/
public class NSURLSessionStreamTask : NSURLSessionTask {
/* Read minBytes, or at most maxBytes bytes and invoke the completion
* handler on the sessions delegate queue with the data or an error.
* If an error occurs, any outstanding reads will also fail, and new
* read requests will error out immediately.
*/
public func readDataOfMinLength(_ minBytes: Int, maxLength maxBytes: Int, timeout: NSTimeInterval, completionHandler: (NSData?, Bool, NSError?) -> Void) { NSUnimplemented() }
/* Write the data completely to the underlying socket. If all the
* bytes have not been written by the timeout, a timeout error will
* occur. Note that invocation of the completion handler does not
* guarantee that the remote side has received all the bytes, only
* that they have been written to the kernel. */
public func writeData(_ data: NSData, timeout: NSTimeInterval, completionHandler: (NSError?) -> Void) { NSUnimplemented() }
/* -captureStreams completes any already enqueued reads
* and writes, and then invokes the
* URLSession:streamTask:didBecomeInputStream:outputStream: delegate
* message. When that message is received, the task object is
* considered completed and will not receive any more delegate
* messages. */
public func captureStreams() { NSUnimplemented() }
/* Enqueue a request to close the write end of the underlying socket.
* All outstanding IO will complete before the write side of the
* socket is closed. The server, however, may continue to write bytes
* back to the client, so best practice is to continue reading from
* the server until you receive EOF.
*/
public func closeWrite() { NSUnimplemented() }
/* Enqueue a request to close the read side of the underlying socket.
* All outstanding IO will complete before the read side is closed.
* You may continue writing to the server.
*/
public func closeRead() { NSUnimplemented() }
/*
* Begin encrypted handshake. The hanshake begins after all pending
* IO has completed. TLS authentication callbacks are sent to the
* session's -URLSession:task:didReceiveChallenge:completionHandler:
*/
public func startSecureConnection() { NSUnimplemented() }
/*
* Cleanly close a secure connection after all pending secure IO has
* completed.
*/
public func stopSecureConnection() { NSUnimplemented() }
}
/*
* Configuration options for an NSURLSession. When a session is
* created, a copy of the configuration object is made - you cannot
* modify the configuration of a session after it has been created.
*
* The shared session uses the global singleton credential, cache
* and cookie storage objects.
*
* An ephemeral session has no persistent disk storage for cookies,
* cache or credentials.
*
* A background session can be used to perform networking operations
* on behalf of a suspended application, within certain constraints.
*/
public class NSURLSessionConfiguration : NSObject, NSCopying {
public override init() {
NSUnimplemented()
}
public override func copy() -> AnyObject {
return copyWithZone(nil)
}
public func copyWithZone(_ zone: NSZone) -> AnyObject {
NSUnimplemented()
}
public class func defaultSessionConfiguration() -> NSURLSessionConfiguration { NSUnimplemented() }
public class func ephemeralSessionConfiguration() -> NSURLSessionConfiguration { NSUnimplemented() }
public class func backgroundSessionConfigurationWithIdentifier(_ identifier: String) -> NSURLSessionConfiguration { NSUnimplemented() }
/* identifier for the background session configuration */
public var identifier: String? { NSUnimplemented() }
/* default cache policy for requests */
public var requestCachePolicy: NSURLRequestCachePolicy
/* default timeout for requests. This will cause a timeout if no data is transmitted for the given timeout value, and is reset whenever data is transmitted. */
public var timeoutIntervalForRequest: NSTimeInterval
/* default timeout for requests. This will cause a timeout if a resource is not able to be retrieved within a given timeout. */
public var timeoutIntervalForResource: NSTimeInterval
/* type of service for requests. */
public var networkServiceType: NSURLRequestNetworkServiceType
/* allow request to route over cellular. */
public var allowsCellularAccess: Bool
/* allows background tasks to be scheduled at the discretion of the system for optimal performance. */
public var discretionary: Bool
/* The identifier of the shared data container into which files in background sessions should be downloaded.
* App extensions wishing to use background sessions *must* set this property to a valid container identifier, or
* all transfers in that session will fail with NSURLErrorBackgroundSessionRequiresSharedContainer.
*/
public var sharedContainerIdentifier: String?
/*
* Allows the app to be resumed or launched in the background when tasks in background sessions complete
* or when auth is required. This only applies to configurations created with +backgroundSessionConfigurationWithIdentifier:
* and the default value is YES.
*/
/* The proxy dictionary, as described by <CFNetwork/CFHTTPStream.h> */
public var connectionProxyDictionary: [NSObject : AnyObject]?
// TODO: We don't have the SSLProtocol type from Security
/*
/* The minimum allowable versions of the TLS protocol, from <Security/SecureTransport.h> */
public var TLSMinimumSupportedProtocol: SSLProtocol
/* The maximum allowable versions of the TLS protocol, from <Security/SecureTransport.h> */
public var TLSMaximumSupportedProtocol: SSLProtocol
*/
/* Allow the use of HTTP pipelining */
public var HTTPShouldUsePipelining: Bool
/* Allow the session to set cookies on requests */
public var HTTPShouldSetCookies: Bool
/* Policy for accepting cookies. This overrides the policy otherwise specified by the cookie storage. */
public var HTTPCookieAcceptPolicy: NSHTTPCookieAcceptPolicy
/* Specifies additional headers which will be set on outgoing requests.
Note that these headers are added to the request only if not already present. */
public var HTTPAdditionalHeaders: [NSObject : AnyObject]?
/* The maximum number of simultanous persistent connections per host */
public var HTTPMaximumConnectionsPerHost: Int
/* The cookie storage object to use, or nil to indicate that no cookies should be handled */
public var HTTPCookieStorage: NSHTTPCookieStorage?
/* The credential storage object, or nil to indicate that no credential storage is to be used */
public var URLCredentialStorage: NSURLCredentialStorage?
/* The URL resource cache, or nil to indicate that no caching is to be performed */
public var URLCache: NSURLCache?
/* Enable extended background idle mode for any tcp sockets created. Enabling this mode asks the system to keep the socket open
* and delay reclaiming it when the process moves to the background (see https://developer.apple.com/library/ios/technotes/tn2277/_index.html)
*/
public var shouldUseExtendedBackgroundIdleMode: Bool
/* An optional array of Class objects which subclass NSURLProtocol.
The Class will be sent +canInitWithRequest: when determining if
an instance of the class can be used for a given URL scheme.
You should not use +[NSURLProtocol registerClass:], as that
method will register your class with the default session rather
than with an instance of NSURLSession.
Custom NSURLProtocol subclasses are not available to background
sessions.
*/
public var protocolClasses: [AnyClass]?
}
/*
* Disposition options for various delegate messages
*/
public enum NSURLSessionAuthChallengeDisposition : Int {
case UseCredential /* Use the specified credential, which may be nil */
case PerformDefaultHandling /* Default handling for the challenge - as if this delegate were not implemented; the credential parameter is ignored. */
case CancelAuthenticationChallenge /* The entire request will be canceled; the credential parameter is ignored. */
case RejectProtectionSpace /* This challenge is rejected and the next authentication protection space should be tried; the credential parameter is ignored. */
}
public enum NSURLSessionResponseDisposition : Int {
case Cancel /* Cancel the load, this is the same as -[task cancel] */
case Allow /* Allow the load to continue */
case BecomeDownload /* Turn this request into a download */
case BecomeStream /* Turn this task into a stream task */
}
/*
* NSURLSessionDelegate specifies the methods that a session delegate
* may respond to. There are both session specific messages (for
* example, connection based auth) as well as task based messages.
*/
/*
* Messages related to the URL session as a whole
*/
public protocol NSURLSessionDelegate : NSObjectProtocol {
/* The last message a session receives. A session will only become
* invalid because of a systemic error or when it has been
* explicitly invalidated, in which case the error parameter will be nil.
*/
func URLSession(_ session: NSURLSession, didBecomeInvalidWithError error: NSError?)
/* If implemented, when a connection level authentication challenge
* has occurred, this delegate will be given the opportunity to
* provide authentication credentials to the underlying
* connection. Some types of authentication will apply to more than
* one request on a given connection to a server (SSL Server Trust
* challenges). If this delegate message is not implemented, the
* behavior will be to use the default handling, which may involve user
* interaction.
*/
func URLSession(_ session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
}
extension NSURLSessionDelegate {
func URLSession(_ session: NSURLSession, didBecomeInvalidWithError error: NSError?) { }
func URLSession(_ session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { }
}
/* If an application has received an
* -application:handleEventsForBackgroundURLSession:completionHandler:
* message, the session delegate will receive this message to indicate
* that all messages previously enqueued for this session have been
* delivered. At this time it is safe to invoke the previously stored
* completion handler, or to begin any internal updates that will
* result in invoking the completion handler.
*/
/*
* Messages related to the operation of a specific task.
*/
public protocol NSURLSessionTaskDelegate : NSURLSessionDelegate {
/* An HTTP request is attempting to perform a redirection to a different
* URL. You must invoke the completion routine to allow the
* redirection, allow the redirection with a modified request, or
* pass nil to the completionHandler to cause the body of the redirection
* response to be delivered as the payload of this request. The default
* is to follow redirections.
*
* For tasks in background sessions, redirections will always be followed and this method will not be called.
*/
func URLSession(_ session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void)
/* The task has received a request specific authentication challenge.
* If this delegate is not implemented, the session specific authentication challenge
* will *NOT* be called and the behavior will be the same as using the default handling
* disposition.
*/
func URLSession(_ session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
/* Sent if a task requires a new, unopened body stream. This may be
* necessary when authentication has failed for any request that
* involves a body stream.
*/
func URLSession(_ session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: (NSInputStream?) -> Void)
/* Sent periodically to notify the delegate of upload progress. This
* information is also available as properties of the task.
*/
func URLSession(_ session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64)
/* Sent as the last message related to a specific task. Error may be
* nil, which implies that no error occurred and this task is complete.
*/
func URLSession(_ session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)
}
extension NSURLSessionTaskDelegate {
func URLSession(_ session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void) { }
func URLSession(_ session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { }
func URLSession(_ session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: (NSInputStream?) -> Void) { }
func URLSession(_ session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { }
func URLSession(_ session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { }
}
/*
* Messages related to the operation of a task that delivers data
* directly to the delegate.
*/
public protocol NSURLSessionDataDelegate : NSURLSessionTaskDelegate {
/* The task has received a response and no further messages will be
* received until the completion block is called. The disposition
* allows you to cancel a request or to turn a data task into a
* download task. This delegate message is optional - if you do not
* implement it, you can get the response as a property of the task.
*
* This method will not be called for background upload tasks (which cannot be converted to download tasks).
*/
func URLSession(_ session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void)
/* Notification that a data task has become a download task. No
* future messages will be sent to the data task.
*/
func URLSession(_ session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
/*
* Notification that a data task has become a bidirectional stream
* task. No future messages will be sent to the data task. The newly
* created streamTask will carry the original request and response as
* properties.
*
* For requests that were pipelined, the stream object will only allow
* reading, and the object will immediately issue a
* -URLSession:writeClosedForStream:. Pipelining can be disabled for
* all requests in a session, or by the NSURLRequest
* HTTPShouldUsePipelining property.
*
* The underlying connection is no longer considered part of the HTTP
* connection cache and won't count against the total number of
* connections per host.
*/
func URLSession(_ session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeStreamTask streamTask: NSURLSessionStreamTask)
/* Sent when data is available for the delegate to consume. It is
* assumed that the delegate will retain and not copy the data. As
* the data may be discontiguous, you should use
* [NSData enumerateByteRangesUsingBlock:] to access it.
*/
func URLSession(_ session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData)
/* Invoke the completion routine with a valid NSCachedURLResponse to
* allow the resulting data to be cached, or pass nil to prevent
* caching. Note that there is no guarantee that caching will be
* attempted for a given resource, and you should not rely on this
* message to receive the resource data.
*/
func URLSession(_ session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: (NSCachedURLResponse?) -> Void)
}
extension NSURLSessionDataDelegate {
func URLSession(_ session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { }
func URLSession(_ session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) { }
func URLSession(_ session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeStreamTask streamTask: NSURLSessionStreamTask) { }
func URLSession(_ session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: (NSCachedURLResponse?) -> Void) { }
}
/*
* Messages related to the operation of a task that writes data to a
* file and notifies the delegate upon completion.
*/
public protocol NSURLSessionDownloadDelegate : NSURLSessionTaskDelegate {
/* Sent when a download task that has completed a download. The delegate should
* copy or move the file at the given location to a new location as it will be
* removed when the delegate message returns. URLSession:task:didCompleteWithError: will
* still be called.
*/
func URLSession(_ session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL)
/* Sent periodically to notify the delegate of download progress. */
func URLSession(_ session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
/* Sent when a download has been resumed. If a download failed with an
* error, the -userInfo dictionary of the error will contain an
* NSURLSessionDownloadTaskResumeData key, whose value is the resume
* data.
*/
func URLSession(_ session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64)
}
extension NSURLSessionDownloadDelegate {
func URLSession(_ session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { }
func URLSession(_ session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { }
}
public protocol NSURLSessionStreamDelegate : NSURLSessionTaskDelegate {
/* Indiciates that the read side of a connection has been closed. Any
* outstanding reads complete, but future reads will immediately fail.
* This may be sent even when no reads are in progress. However, when
* this delegate message is received, there may still be bytes
* available. You only know that no more bytes are available when you
* are able to read until EOF. */
func URLSession(_ session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask)
/* Indiciates that the write side of a connection has been closed.
* Any outstanding writes complete, but future writes will immediately
* fail.
*/
func URLSession(_ session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask)
/* A notification that the system has determined that a better route
* to the host has been detected (eg, a wi-fi interface becoming
* available.) This is a hint to the delegate that it may be
* desirable to create a new task for subsequent work. Note that
* there is no guarantee that the future task will be able to connect
* to the host, so callers should should be prepared for failure of
* reads and writes over any new interface. */
func URLSession(_ session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask)
/* The given task has been completed, and unopened NSInputStream and
* NSOutputStream objects are created from the underlying network
* connection. This will only be invoked after all enqueued IO has
* completed (including any necessary handshakes.) The streamTask
* will not receive any further delegate messages.
*/
func URLSession(_ session: NSURLSession, streamTask: NSURLSessionStreamTask, didBecomeInputStream inputStream: NSInputStream, outputStream: NSOutputStream)
}
extension NSURLSessionStreamDelegate {
func URLSession(_ session: NSURLSession, readClosedForStreamTask streamTask: NSURLSessionStreamTask) { }
func URLSession(_ session: NSURLSession, writeClosedForStreamTask streamTask: NSURLSessionStreamTask) { }
func URLSession(_ session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask) { }
func URLSession(_ session: NSURLSession, streamTask: NSURLSessionStreamTask, didBecomeInputStream inputStream: NSInputStream, outputStream: NSOutputStream) { }
}
/* Key in the userInfo dictionary of an NSError received during a failed download. */
public let NSURLSessionDownloadTaskResumeData: String = "" // NSUnimplemented
| 8baa8da1643169b8ce7131867c93f2b4 | 50.101124 | 270 | 0.741718 | false | false | false | false |
MaeseppTarvo/FullScreenAlert | refs/heads/master | Example/FullScreenAlert/ViewController.swift | mit | 1 | //
// ViewController.swift
// FullScreenAlert
//
// Created by MaeseppTarvo on 06/16/2017.
// Copyright (c) 2017 MaeseppTarvo. All rights reserved.
//
import UIKit
import FullScreenAlert
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//WITHOUT ACTION
@IBAction func didTapSuccess(_ sender: Any) {
let successAlert = AlertView(type: .Success, title: "Success", message: "You just opened this \"Success\" type alert without action", config: nil)
successAlert.present(on: self)
}
@IBAction func didTapWarning(_ sender: Any) {
let warningAlert = AlertView(type: .Warning, title: "Warning", message: "You just opened this \"Warning\" type alert without action", config: nil)
warningAlert.present(on: self)
}
@IBAction func didTapError(_ sender: Any) {
let errorAlert = AlertView(type: .Error, title: "Error", message: "You just opened this \"Error\" type alert without action", config: nil)
errorAlert.present(on: self)
}
//WITH ACTION
@IBAction func didTapSuccessWithAction(_ sender: Any) {
var fullScreenALertConfig = AlertView.Config()
fullScreenALertConfig.alertBackgroundColor = UIColor.blue.withAlphaComponent(0.7)
let successAlertWithAction = AlertView(type: .Success, title: "Success", message: "You just opened this \"Success\" type alert with action", config: fullScreenALertConfig) {
print("SOME ACTION")
}
successAlertWithAction.present(on: self)
}
@IBAction func didTapWarningWithAction(_ sender: Any) {
}
@IBAction func didTapErrorWithWarning(_ sender: Any) {
}
}
| 2f0a92500001b0b6d8b0dda2b41f87de | 32.711864 | 181 | 0.660131 | false | true | false | false |
terflogag/FacebookImagePicker | refs/heads/master | GBHFacebookImagePicker/Classes/Utils/Reusable.swift | mit | 1 | //
// Reusable.swift
// GBHFacebookImagePicker
//
// Created by Florian Gabach on 21/11/2018.
//
import UIKit
public protocol Reusable: class {
static var reuseIdentifier: String { get }
}
public extension Reusable {
static var reuseIdentifier: String {
return String(describing: self)
}
}
extension UITableView {
final func register<T: UITableViewCell>(cellType: T.Type)
where T: Reusable {
self.register(cellType.self, forCellReuseIdentifier: cellType.reuseIdentifier)
}
final func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath, cellType: T.Type = T.self) -> T
where T: Reusable {
guard let cell = self.dequeueReusableCell(withIdentifier: cellType.reuseIdentifier, for: indexPath) as? T else {
fatalError(
"Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). "
+ "Check that the reuseIdentifier is set properly in your XIB/Storyboard "
+ "and that you registered the cell beforehand"
)
}
return cell
}
}
extension UICollectionView {
func register<T: UICollectionViewCell>(cellType: T.Type)
where T: Reusable {
self.register(cellType.self, forCellWithReuseIdentifier: cellType.reuseIdentifier)
}
func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath, cellType: T.Type = T.self) -> T
where T: Reusable {
let bareCell = self.dequeueReusableCell(withReuseIdentifier: cellType.reuseIdentifier, for: indexPath)
guard let cell = bareCell as? T else {
fatalError(
"Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). "
+ "Check that the reuseIdentifier is set properly in your XIB/Storyboard "
+ "and that you registered the cell beforehand"
)
}
return cell
}
}
| 2ef44d50ad4e23cbe2f84ac81d74a639 | 35.912281 | 124 | 0.627376 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.