repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
EasySwift/EasySwift
|
Carthage/Checkouts/DKChainableAnimationKit/DKChainableAnimationKit/Classes/DKChainableAnimationKit.swift
|
2
|
10824
|
//
// DKChainableAnimationKit.swift
// DKChainableAnimationKit
//
// Created by Draveness on 15/5/13.
// Copyright (c) 2015年 Draveness. All rights reserved.
//
import UIKit
open class DKChainableAnimationKit {
weak var view: UIView!
typealias AnimationCalculationAction = (UIView) -> Void
typealias AnimationCompletionAction = (UIView) -> Void
internal var animationCalculationActions: [[AnimationCalculationAction]]!
internal var animationCompletionActions: [[AnimationCompletionAction]]!
internal var animationGroups: NSMutableArray!
internal var animations: [[DKKeyFrameAnimation]]!
open var animationCompletion: ((Void) -> Void)?
// MARK: - Initialize
init() {
self.setup()
}
fileprivate func setup() {
self.animations = [[]]
self.animationGroups = [self.basicAnimationGroup()]
self.animationCompletionActions = [[]]
self.animationCalculationActions = [[]]
}
fileprivate func clear() {
self.animations.removeAll()
self.animationGroups.removeAllObjects()
self.animationCompletionActions.removeAll()
self.animationCalculationActions.removeAll()
self.animations.append([])
self.animationCompletionActions.append([AnimationCalculationAction]())
self.animationCalculationActions.append([AnimationCompletionAction]())
self.animationGroups.add(self.basicAnimationGroup())
}
// MARK: - Animation Time
open func delay(_ delay: TimeInterval) -> DKChainableAnimationKit {
var delay = delay
for group in self.animationGroups {
let duration = (group as AnyObject).duration as TimeInterval
delay += duration
}
if let group = self.animationGroups.lastObject as? CAAnimationGroup {
group.beginTime = CACurrentMediaTime() + delay
}
return self
}
open func delay(_ time: CGFloat) -> DKChainableAnimationKit {
return delay(TimeInterval(time))
}
open var seconds: DKChainableAnimationKit {
get {
return self
}
}
open func wait(_ delay: TimeInterval) -> DKChainableAnimationKit {
return self.delay(delay)
}
@discardableResult open func animate(_ duration: TimeInterval) -> DKChainableAnimationKit {
if let group = self.animationGroups.lastObject as? CAAnimationGroup {
group.duration = duration
self.animateChain()
}
return self
}
@discardableResult open func animate(_ duration: CGFloat) -> DKChainableAnimationKit {
return animate(TimeInterval(duration))
}
// public func animateWithRepeat(duration: NSTimeInterval) -> DKChainableAnimationKit {
// if let group = self.animationGroups.lastObject as? CAAnimationGroup {
// group.duration = duration
// saveAnimations()
// animationCompletion = {
// self.restoreAnimations()
// self.animateChain()
// }
// self.animateChain()
// }
// return self
// }
//
// internal var tempAnimationCalculationActions: [[AnimationCalculationAction]]!
// internal var tempAnimationCompletionActions: [[AnimationCompletionAction]]!
// internal var tempAnimationGroups: NSMutableArray!
// internal var tempAnimations: [[DKKeyFrameAnimation]]!
//
// internal func saveAnimations() {
// self.tempAnimationCalculationActions = self.animationCalculationActions
// self.tempAnimationCompletionActions = self.animationCompletionActions
// self.tempAnimationGroups = self.animationGroups.mutableCopy() as! NSMutableArray
// self.tempAnimations = self.animations
// }
//
// internal func restoreAnimations() {
// self.animationCalculationActions = self.tempAnimationCalculationActions
// self.animationCompletionActions = self.tempAnimationCompletionActions
// self.animationGroups = self.tempAnimationGroups.mutableCopy() as! NSMutableArray
// self.animations = self.tempAnimations
// }
open func thenAfter(_ after: TimeInterval) -> DKChainableAnimationKit {
if let group = self.animationGroups.lastObject as? CAAnimationGroup {
group.duration = after
let newGroup = self.basicAnimationGroup()
self.animationGroups.add(newGroup)
self.animations.append([])
self.animationCalculationActions.append([])
self.animationCompletionActions.append([])
}
return self
}
open func thenAfter(_ after: CGFloat) -> DKChainableAnimationKit {
return thenAfter(TimeInterval(after))
}
@discardableResult open func animateWithCompletion(_ duration: TimeInterval, _ completion: @escaping (Void) -> Void) -> DKChainableAnimationKit {
if let group = self.animationGroups.lastObject as? CAAnimationGroup {
group.duration = duration
self.animationCompletion = completion
self.animateChain()
}
return self
}
@discardableResult open func animateWithCompletion(_ duration: CGFloat, _ completion: @escaping (Void) -> Void) -> DKChainableAnimationKit {
return animateWithCompletion(TimeInterval(duration), completion)
}
internal func degreesToRadians(_ degree: Double) -> Double {
return (degree / 180.0) * M_PI
}
fileprivate func animateChain() {
self.sanityCheck()
CATransaction.begin()
CATransaction.setCompletionBlock { () -> Void in
self.view?.layer.removeAnimation(forKey: "AnimationChain")
self.chainLinkDidFinishAnimating()
}
self.animateChainLink()
CATransaction.commit()
self.executeCompletionActions()
}
fileprivate func animateChainLink() {
self.makeAnchor(0.5, 0.5)
if let animationCluster = self.animationCalculationActions.first, let _ = self.view {
for action in animationCluster {
action(self.view)
}
}
if let group: CAAnimationGroup = self.animationGroups.firstObject as? CAAnimationGroup,
let animationCluster: [DKKeyFrameAnimation] = self.animations.first {
for animation in animationCluster {
animation.duration = group.duration
animation.calculte()
}
group.animations = animationCluster
self.view?.layer.add(group, forKey: "AnimationChain")
}
}
fileprivate func executeCompletionActions() {
if let group = self.animationGroups.firstObject as? CAAnimationGroup {
let delay = max(group.beginTime - CACurrentMediaTime(), 0.0)
let delayTime = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
if let
actionCluster: [AnimationCompletionAction] = self.animationCompletionActions.first,
let view = self.view {
for action in actionCluster {
action(view)
}
}
}
}
}
fileprivate func chainLinkDidFinishAnimating() {
self.animationCompletionActions.remove(at: 0)
self.animationCalculationActions.remove(at: 0)
self.animations.remove(at: 0)
self.animationGroups.removeObject(at: 0)
if self.animationGroups.count == 0 {
self.clear()
if let completion = self.animationCompletion {
self.animationCompletion = nil
completion()
}
} else {
self.animateChain()
}
}
fileprivate func sanityCheck() {
assert(self.animations.count == self.animationGroups.count, "FATAL ERROR: ANIMATION GROUPS AND ANIMATIONS ARE OUT OF SYNC");
assert(self.animationCalculationActions.count == self.animationCompletionActions.count, "FATAL ERROR: ANIMATION CALCULATION OBJECTS AND ANIMATION COMPLETION OBJECTS ARE OUT OF SYNC");
assert(self.animations.count == self.animationCompletionActions.count, "FATAL ERROR: ANIMATIONS AND ANIMATION COMPLETION OBJECTS ARE OUT OF SYNC");
}
// MARK: - Animation Action
internal func addAnimationKeyframeCalculation(_ functionBlock: @escaping DKKeyframeAnimationFunctionBlock) {
self.addAnimationCalculationAction { (view: UIView) -> Void in
let animationCluster = self.animations.first
if let animation = animationCluster?.last {
animation.functionBlock = functionBlock
}
}
}
internal func addAnimationCalculationAction(_ action: @escaping AnimationCalculationAction) {
if var actions = self.animationCalculationActions.last as [AnimationCalculationAction]? {
actions.append(action)
self.animationCalculationActions.removeLast()
self.animationCalculationActions.append(actions)
}
}
internal func addAnimationCompletionAction(_ action: @escaping AnimationCompletionAction) {
if var actions = self.animationCompletionActions.last as [AnimationCompletionAction]? {
actions.append(action)
self.animationCompletionActions.removeLast()
self.animationCompletionActions.append(actions)
}
}
internal func addAnimationFromCalculationBlock(_ animation: DKKeyFrameAnimation) {
if var animationCluster = self.animations.first {
animationCluster.append(animation)
self.animations.remove(at: 0)
self.animations.insert(animationCluster, at: 0)
}
}
// MARK: - Basic Animation Helper
internal func basicAnimationGroup() -> CAAnimationGroup {
return CAAnimationGroup()
}
internal func basicAnimationForKeyPath(_ keyPath: String) -> DKKeyFrameAnimation {
let animation = DKKeyFrameAnimation(keyPath: keyPath)
animation.repeatCount = 0
animation.autoreverses = false
return animation
}
internal func newPositionFrom(newOrigin: CGPoint) -> CGPoint {
let anchor = self.view.layer.anchorPoint
let size = self.view.bounds.size
let newPosition = CGPoint(x: newOrigin.x + anchor.x * size.width, y: newOrigin.y + anchor.y * size.height)
return newPosition
}
internal func newPositionFrom(newCenter: CGPoint) -> CGPoint {
let anchor = self.view.layer.anchorPoint
let size = self.view.bounds.size
let newPosition = CGPoint(x: newCenter.x + (anchor.x - 0.5) * size.width, y: newCenter.y + (anchor.y - 0.5) * size.height)
return newPosition
}
}
|
apache-2.0
|
eb432edf68167dadaf8dfad396f04ba8
| 36.97193 | 191 | 0.652929 | 5.04287 | false | false | false | false |
poolmyride/DataStoreKit
|
Pod/Classes/Restify.swift
|
1
|
3371
|
//
// Restify.swift
//
//
// Created by Rohit Talwar on 15/06/15.
// Copyright (c) 2015 Rajat Talwar. All rights reserved.
//
import Foundation
open class Restify<T>:ModelProtocol where T:ObjectCoder{
let base_url:String;
let ALL_PATH = "/all"
var networkClient:NetworkInterface!
public init(path:String,networkClient:NetworkInterface){
base_url = path
self.networkClient = networkClient
}
lazy var deserializer:ObjectDeserializer<T> = {
var objD = ObjectDeserializer<T>()
return objD
}()
fileprivate func _deserializeArray(_ objectArray : Any?,callback: ModelArrayCallback? ){
self.deserializer.deSerializeArrayAsync(objectArray as? NSArray, callback: callback)
}
fileprivate func _deserializeObject(_ object : Any?,callback: ModelObjectCallback? ){
self.deserializer.deSerializeObjectAsync(object as? [String:Any], callback: callback)
}
open func query(params:[String:Any]? = nil, options:[String:Any]? = nil, callback: ModelArrayCallback? ){
let path = base_url
networkClient.GET(path, parameters: params) { (error, jsonObject) -> Void in
(error == nil) ? self._deserializeArray(jsonObject as? NSArray, callback: callback) : callback?(error,jsonObject)
}
}
open func all(_ callback:ModelArrayCallback?){
let path = base_url + ALL_PATH
networkClient.GET(path, parameters: nil) { (error, jsonObject) -> Void in
(error == nil) ? self._deserializeArray(jsonObject, callback: callback) : callback?(error,jsonObject)
}
}
open func get(id:CVarArg?,params:[String:Any]?, callback: ModelObjectCallback? ){
let resourceString = id != nil ? ("/" + (id as! String)) : ""
let path = base_url + resourceString
networkClient.GET(path, parameters: params) { (error, jsonObject) -> Void in
(error == nil) ? self._deserializeObject(jsonObject, callback: callback) : callback?(error,jsonObject)
}
}
open func put(id: CVarArg?, object: ObjectCoder, callback: ModelObjectCallback?) {
let resourceString = id != nil ? ("/" + (id as! String)) : ""
let path = base_url + resourceString
let dic = object.toDictionary()
networkClient.PUT(path, parameters: dic) { (error, object) -> Void in
callback?(error,object)
}
}
open func add(_ object: ObjectCoder, callback: ModelObjectCallback?) {
let path = base_url
let dic = object.toDictionary()
networkClient.POST(path, parameters: dic) { (error, object) -> Void in
callback?(error,object)
}
}
open func remove(id: CVarArg?, params:[String:Any]?, callback: ModelObjectCallback?) {
let resourceString = id != nil ? ("/" + (id as! String)) : ""
let path = base_url + resourceString
let dic:[String:Any]? = (params != nil) ? params : nil
networkClient.DELETE(path, parameters: dic) { (error, object) -> Void in
callback?(error,object)
}
}
}
|
mit
|
f2add38af995c0dee7237e412a63d3b7
| 29.098214 | 125 | 0.57609 | 4.494667 | false | false | false | false |
1457792186/JWSwift
|
SwiftLearn/SwiftDemo/SwiftDemo/UserCenter/JWUserCenterViewController.swift
|
1
|
3928
|
//
// JWMeViewController.swift
// SwiftDemo
//
// Created by apple on 17/5/4.
// Copyright © 2017年 UgoMedia. All rights reserved.
//
import UIKit
class JWUserCenterViewController: JWBasicViewController {
@IBOutlet weak var avatarBtn: UIButton!
@IBOutlet weak var integralBtn: JWButton!
/*button tag:
101-每日签到
102-我的话题
103-我的活动
104-积分商城
201~208-关注与粉丝~手机认证
@IBAction func userInfoEditButtonClickAction(_ sender: Any) {
}
*/
@IBOutlet weak var baseScrollView: UIScrollView!
@IBOutlet weak var baseViewHeight: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "个人中心";
self.prepareUI();
}
@objc func prepareUI() {
// 基视图高度适配
let mainViewHeight = mainScreenHeight - JWSwiftConst.NaviBarHeight() - JWSwiftConst.TabBarHeight()
let baseViewHeight : CGFloat = mainViewHeight <= 600 ? 600.0 : 10.0;
self.baseScrollView.contentSize = CGSize.init(width: mainScreenWidth, height: baseViewHeight)
self.baseScrollView.alwaysBounceVertical = true
self.baseViewHeight.constant = 600.0;
self.view.updateConstraints();
// 控件设置
self.avatarBtn.layer.cornerRadius = self.avatarBtn.frame.size.width / 2.0;
self.avatarBtn.layer.masksToBounds = true;
self.integralBtn.layer.cornerRadius = self.integralBtn.frame.size.height / 2.0;
self.integralBtn.layer.borderWidth = 1.0;
self.integralBtn.layer.borderColor = JWTools.colorWithHexString(hex: "#f5f5f5").cgColor
self.integralBtn.layer.masksToBounds = true;
for index in 101..<104 {
let btn = self.view.viewWithTag(index)
(btn as! UIButton).addTarget(self, action: #selector(JWUserCenterViewController.buttonClickAction(_:)), for: UIControlEvents.touchUpInside)
}
for index in 201..<208 {
let btn = self.view.viewWithTag(index)
(btn as! UIButton).addTarget(self, action: #selector(JWUserCenterViewController.buttonClickAction(_:)), for: UIControlEvents.touchUpInside)
}
}
// MARK: - ButtonAction
@objc func buttonClickAction(_ sender: UIButton) {
var pushVC = UIViewController()
let targetID = sender.tag
switch targetID {
case 101:
pushVC = JWSignInViewController()
case 102:
pushVC = JWUserTopicViewController()
case 103:
pushVC = JWUserActivityViewController()
case 104:
pushVC = JWIntegralShopViewController()
case 201:
pushVC = JWUserFansViewController()
case 202:
pushVC = JWUserDynamicViewController()
case 203:
pushVC = JWUserCollectionViewController()
case 204:
pushVC = JWUserOrderViewController()
case 205:
pushVC = JWSysNotificationViewController()
case 206:
pushVC = JWUserMessageViewController()
case 207:
pushVC = JWUserSettingViewController()
case 208:
pushVC = JWUserPhoneCheckViewController()
default:
pushVC = UIViewController()
}
self.navigationController?.pushViewController(pushVC, animated: true)
}
@IBAction func userInfoEditBtnAction(_ sender: Any) {
let userEditVC = JWUserEditViewController()
self.navigationController?.pushViewController(userEditVC, animated: true)
}
@IBAction func userIntegralBtnAction(_ sender: Any) {
let userIntegralVC = JWUserIntegralViewController()
self.navigationController?.pushViewController(userIntegralVC, animated: true)
}
}
|
apache-2.0
|
eaa05039c047d20ca1358776fc5c0924
| 32.146552 | 151 | 0.630429 | 4.824341 | false | false | false | false |
lukesutton/uut
|
Sources/StyleExtension.swift
|
1
|
1221
|
public struct StyleExtension {
let properties: [Property]
let children: [Style]
}
extension StyleExtension: Hashable {
public var hashValue: Int {
return "\(self.properties)\(self.children)".hashValue
}
}
public func ==(lhs: StyleExtension, rhs: StyleExtension) -> Bool {
return lhs.hashValue == rhs.hashValue
}
public struct ExtensionCollection: StyleComponent {
let extensions: [StyleExtension]
}
public func styleExtension(components: ExtensionComponent...) -> StyleExtension {
let extracted = extractComponents(components)
return StyleExtension(properties: extracted.properties, children: extracted.children)
}
public protocol ExtensionComponent {}
extension Style: ExtensionComponent {}
extension Property: ExtensionComponent {}
internal func extractComponents(components: [ExtensionComponent]) -> (children: [Style], properties: [Property]) {
var properties = [Property]()
var children = [Style]()
for component in components {
switch component {
case let property as Property:
properties.append(property)
case let style as Style:
children.append(style)
default:
false
}
}
return (children: children, properties: properties)
}
|
mit
|
5b4014d4d001620b0093a787c43d146d
| 26.133333 | 114 | 0.728092 | 4.573034 | false | false | false | false |
TG908/iOS
|
TUM Campus App/EditCardsViewController.swift
|
1
|
3425
|
//
// EditCardsViewController.swift
// TUM Campus App
//
// Created by Mathias Quintero on 12/17/16.
// Copyright © 2016 LS1 TUM. All rights reserved.
//
import UIKit
import Sweeft
class EditCardsViewController: UITableViewController {
var enabled: [CardKey] {
get {
return PersistentCardOrder.value.cards
}
set {
PersistentCardOrder.value.cards = newValue
}
}
var disabled: [CardKey] {
return (CardKey.all - enabled).array
}
var arrays: [[CardKey]] {
return [enabled, disabled]
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.setEditing(true, animated: true)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "Enabled"
case 1:
return "Disabled"
default:
return nil
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return enabled.count
case 1:
return disabled.count
default:
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "card", for: indexPath)
cell.textLabel?.text = arrays[indexPath.section][indexPath.row].description
return cell
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
switch indexPath.section {
case 0:
return .delete
case 1:
return .insert
default:
return .none
}
}
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return indexPath.section == 0
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if destinationIndexPath.section == 0 {
enabled.move(itemAt: sourceIndexPath.row, to: destinationIndexPath.row)
} else {
enabled.remove(at: sourceIndexPath.row)
tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
print("Editing!!!")
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0:
enabled.remove(at: indexPath.row)
tableView.reloadData()
case 1:
enabled.append(disabled[indexPath.row])
tableView.reloadData()
default:
break
}
}
@IBAction func pressedDone(_ sender: Any) {
navigationController?.dismiss(animated: true, completion: nil)
}
}
|
gpl-3.0
|
c017f1df0e35d8b08d820c1f34377725
| 27.065574 | 136 | 0.598715 | 5.358372 | false | false | false | false |
loopwxservices/WXKDarkSky
|
Sources/WXKDarkSky/DarkSkyResponse.swift
|
1
|
2228
|
//
// DarkSkyResponse.swift
// WXKDarkSky
//
// © 2020; MIT License.
//
// Please see the included LICENSE file for details.
//
import Foundation
/// The DarkSkyResponse struct contains support for encoding/decoding of JSON responses from the Dark Sky API.
public struct DarkSkyResponse: Codable {
/// The requested point's latitude.
public var latitude: Double
/// The requested point's longitude.
public var longitude: Double
/// The requested point's timezone.
public var timezone: String
/// Current conditions for the requested point.
public var currently: DataPoint?
/// Minute-by-minute forecast for the next hour at the requested point.
public var minutely: DataBlock?
/// Hourly forecast for the next 48 hours at the requested point.
public var hourly: DataBlock?
/// Daily forecast for the next week at the requested point.
public var daily: DataBlock?
/// Any active alerts for the requested point.
public var alerts: [Alert]?
/// Metadata about the data returned for the requested point.
public var flags: Flags?
/**
Creates a DarkSkyResponse struct from Dark Sky JSON data, if possible. This initializer is simply a wrapper around a `JSONDecoder`.
This initializer will fail if the Dark Sky JSON provided to it cannot be decoded by a `JSONDecoder` into a `DarkSkyResponse` object for whatever reason, such as an incomplete download or other badly formatted JSON.
- parameter data: Dark Sky JSON `Data` to be converted.
*/
public init?(data: Data) {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
do {
let response = try decoder.decode(DarkSkyResponse.self, from: data)
self.latitude = response.latitude
self.longitude = response.longitude
self.timezone = response.timezone
self.currently = response.currently
self.minutely = response.minutely
self.hourly = response.hourly
self.daily = response.daily
self.alerts = response.alerts
self.flags = response.flags
} catch {
return nil
}
}
}
|
mit
|
1e39f9b05e53b3d6a0a4f590c3e3c9a5
| 37.396552 | 219 | 0.670858 | 4.738298 | false | false | false | false |
lorentey/swift
|
test/SILOptimizer/diagnostic_constant_propagation_floats.swift
|
5
|
10164
|
// RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify
// RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify -enable-ownership-stripping-after-serialization
//
// These are tests for diagnostics produced by constant propagation pass
// on floating-point operations.
import StdlibUnittest
func testFPToIntConversion() {
_blackHole(Int8(-1.28E2))
_blackHole(Int8(-128.5)) // the result is -128 and is not an overflow
_blackHole(Int8(1.27E2))
_blackHole(Int8(-0))
_blackHole(Int8(3.33333))
_blackHole(Int8(-2E2)) // expected-error {{invalid conversion: '-2E2' overflows 'Int8'}}
_blackHole(UInt8(2E2))
_blackHole(UInt8(3E2)) // expected-error {{invalid conversion: '3E2' overflows 'UInt8'}}
_blackHole(UInt8(-0E0))
_blackHole(UInt8(-2E2)) // expected-error {{negative literal '-2E2' cannot be converted to 'UInt8'}}
_blackHole(Int8(1E6000)) // expected-error {{invalid conversion: '1E6000' overflows 'Int8'}}
// expected-warning@-1 {{'1E6000' overflows to inf because its magnitude exceeds the limits of a float literal}}
_blackHole(UInt8(1E6000)) // expected-error {{invalid conversion: '1E6000' overflows 'UInt8'}}
// expected-warning@-1 {{'1E6000' overflows to inf because its magnitude exceeds the limits of a float literal}}
_blackHole(Int16(3.2767E4))
_blackHole(Int16(3.2768E4)) // expected-error {{invalid conversion: '3.2768E4' overflows 'Int16'}}
_blackHole(Int16(-4E4)) // expected-error {{invalid conversion: '-4E4' overflows 'Int16'}}
_blackHole(UInt16(6.5535E4))
_blackHole(UInt16(6.5536E4)) // expected-error {{invalid conversion: '6.5536E4' overflows 'UInt16'}}
_blackHole(UInt16(7E4)) // expected-error {{invalid conversion: '7E4' overflows 'UInt16'}}
_blackHole(UInt16(-0E0))
_blackHole(UInt16(-2E2)) // expected-error {{negative literal '-2E2' cannot be converted to 'UInt16'}}
_blackHole(Int32(-2.147483648E9))
_blackHole(Int32(-2.147483649E9)) // expected-error {{invalid conversion: '-2.147483649E9' overflows 'Int32'}}
_blackHole(Int32(3E9)) // expected-error {{invalid conversion: '3E9' overflows 'Int32'}}
_blackHole(UInt32(4.294967295E9))
_blackHole(UInt32(4.294967296E9)) // expected-error {{invalid conversion: '4.294967296E9' overflows 'UInt32'}}
_blackHole(UInt32(5E9)) // expected-error {{invalid conversion: '5E9' overflows 'UInt32'}}
_blackHole(UInt32(-0E0))
_blackHole(UInt32(-2E2)) // expected-error {{negative literal '-2E2' cannot be converted to 'UInt32'}}
_blackHole(Int64(9.223372036854775E18))
// A case where the imprecision due to the implicit conversion of
// float literals to 'Double' results in an overflow.
_blackHole(Int64(9.223372036854775807E18)) // expected-error {{invalid conversion: '9.223372036854775807E18' overflows 'Int64'}}
// A case where implicit conversion of the float literal to 'Double'
// elides an overflow that one would expect during conversion to 'Int64'.
_blackHole(Int64(-9.223372036854775809E18))
// Cases of definite overflow.
_blackHole(Int64(9.223372036854775808E18)) // expected-error {{invalid conversion: '9.223372036854775808E18' overflows 'Int64'}}
_blackHole(Int64(1E19)) // expected-error {{invalid conversion: '1E19' overflows 'Int64'}}
// A case where implicit conversion of the float literal to 'Double'
// results in an overflow during conversion to 'UInt64''.
_blackHole(UInt64(1.844674407370955E19))
_blackHole(UInt64(1.8446744073709551615E19)) // expected-error {{invalid conversion: '1.8446744073709551615E19' overflows 'UInt64'}}
_blackHole(UInt64(2E19)) // expected-error {{invalid conversion: '2E19' overflows 'UInt64'}}
_blackHole(UInt64(-0E0))
_blackHole(UInt64(-2E2)) // expected-error {{negative literal '-2E2' cannot be converted to 'UInt64'}}
_blackHole(Int64(1E6000)) // expected-error {{invalid conversion: '1E6000' overflows 'Int64'}}
// expected-warning@-1 {{'1E6000' overflows to inf because its magnitude exceeds the limits of a float literal}}
_blackHole(UInt64(1E6000)) // expected-error {{invalid conversion: '1E6000' overflows 'UInt64'}}
// expected-warning@-1 {{'1E6000' overflows to inf because its magnitude exceeds the limits of a float literal}}
}
func testFloatConvertOverflow() {
let f1: Float = 1E38
_blackHole(f1)
let f2: Float = 1E39 // expected-warning {{'1E39' overflows to inf during conversion to 'Float'}}
_blackHole(f2)
let f3: Float = 1234567891012345678912345671234561234512.0 // expected-warning {{'1234567891012345678912345671234561234512.0' overflows to inf during conversion to 'Float'}}
_blackHole(f3)
let f4: Float = 0.1234567891012345678912345671234561234512
_blackHole(f4)
let f5: Float32 = -3.4028236E+38 // expected-warning {{'-3.4028236E+38' overflows to -inf during conversion to 'Float32' (aka 'Float')}}
_blackHole(f5)
// Diagnositcs for Double truncations have architecture dependent
// messages. See _nonx86 and _x86 test files.
let d1: Double = 1E308
_blackHole(d1)
let d2: Double = 1234567891012345678912345671234561234512.0
_blackHole(d2)
// All warnings are disabled during explicit conversions.
// Except when the number is so large that it wouldn't even fit into largest
// FP type available.
_blackHole(Float(1E38))
_blackHole(Float(1E39))
_blackHole(Float(100000000000000000000000000000000000000000000000.0))
_blackHole(Double(1E308))
_blackHole(Float(1E6000)) // expected-warning {{'1E6000' overflows to inf because its magnitude exceeds the limits of a float literal}}
_blackHole(Float(-1E6000)) // expected-warning {{'-1E6000' overflows to -inf because its magnitude exceeds the limits of a float literal}}
_blackHole(Double(1E6000)) // expected-warning {{'1E6000' overflows to inf because its magnitude exceeds the limits of a float literal}}
}
func testFloatConvertUnderflow() {
let f0: Float = 0.500000006364665322827
_blackHole(f0)
let f1: Float = 1E-37
_blackHole(f1)
let f2: Float = 1E-39 // expected-warning {{'1E-39' underflows and loses precision during conversion to 'Float'}}
_blackHole(f2)
let f3: Float = 1E-45 // expected-warning {{'1E-45' underflows and loses precision during conversion to 'Float'}}
_blackHole(f3)
// A number close to 2^-150 (smaller than least non-zero float: 2^-149)
let f6: Float = 7.0064923E-46 // expected-warning {{'7.0064923E-46' underflows and loses precision during conversion to 'Float'}}
_blackHole(f6)
// Some cases where tininess doesn't cause extra imprecision.
// A number so close to 2^-130 that 2^-130 is its best approximation
// even in Float80.
let f4: Float = 7.3468396926392969248E-40
_blackHole(f4)
// A number very close to 2^-149.
let f5: Float = 1.4012984821624085566E-45
_blackHole(f5)
let f7: Float = 1.1754943E-38 // expected-warning {{'1.1754943E-38' underflows and loses precision during conversion to 'Float'}}
_blackHole(f7)
let f8: Float = 1.17549428E-38 // expected-warning {{'1.17549428E-38' underflows and loses precision during conversion to 'Float'}}
_blackHole(f8)
let d1: Double = 1E-307
_blackHole(d1)
// All warnings are disabled during explict conversions.
_blackHole(Float(1E-37))
_blackHole(Float(1E-39))
_blackHole(Float(1E-45))
_blackHole(Double(1E-307))
}
func testHexFloatImprecision() {
let f1: Float = 0x0.800000p-126
_blackHole(f1)
// Smallest Float subnormal number.
let f2: Float = 0x0.000002p-126
_blackHole(f2)
let f3: Float = 0x1.000002p-127 // expected-warning {{'0x1.000002p-127' loses precision during conversion to 'Float'}}
_blackHole(f3)
let f4: Float = 0x1.000001p-127 // expected-warning {{'0x1.000001p-127' loses precision during conversion to 'Float'}}
_blackHole(f4)
let f5: Float = 0x1.0000002p-126 // expected-warning {{'0x1.0000002p-126' loses precision during conversion to 'Float'}}
_blackHole(f5)
// In the following cases, the literal is truncated to a Float through a
// (lossless) conversion to Double. There should be no warnings here.
let t1: Double = 0x1.0000002p-126
_blackHole(Float(t1))
let t2: Double = 0x1.000001p-126
_blackHole(Float(t2))
let t3 = 0x1.000000fp25
_blackHole(Float(t3))
let d1: Double = 0x0.8p-1022
_blackHole(d1)
// Smallest non-zero number representable in Double.
let d2: Double = 0x0.0000000000001p-1022
_blackHole(d2)
let d3: Double = 0x1p-1074
_blackHole(d3)
// Test the case where conversion results in subnormality in the destination.
let d4: Float = 0x1p-149
_blackHole(d4)
let d5: Float = 0x1.8p-149 // expected-warning {{'0x1.8p-149' loses precision during conversion to 'Float}}
_blackHole(d5)
// All warnings are disabled during explict conversions.
_blackHole(Float(0x1.000002p-126))
_blackHole(Float(0x1.0000002p-126))
_blackHole(Float(0x1.000002p-127))
_blackHole(Float(0x1.000001p-127))
_blackHole(Float(Double(0x1.000000fp25)))
_blackHole(Double(0x1p-1074))
}
func testFloatArithmetic() {
// Ignore inf and Nan during arithmetic operations.
// This may become a warning in the future.
let infV: Float = 3.0 / 0.0
_blackHole(infV)
let a: Float = 1E38
let b: Float = 10.0
_blackHole(a * b)
}
func testIntToFloatConversion() {
let f1: Float = 16777216
_blackHole(f1)
let f2: Float = 1_000_000_000_000 // expected-warning {{'1000000000000' is not exactly representable as 'Float'; it becomes '999999995904'}}
_blackHole(f2)
// First positive integer that cannot be precisely represented in Float: 2^24 + 1
let f3: Float = 16777217 // expected-warning {{'16777217' is not exactly representable as 'Float'; it becomes '16777216'}}
_blackHole(f3)
let d1: Double = 9_007_199_254_740_992 // This value is 2^53
_blackHole(d1)
let d2: Double = 9_007_199_254_740_993 // expected-warning {{'9007199254740993' is not exactly representable as 'Double'; it becomes '9007199254740992'}}
_blackHole(d2)
// No warnings are emitted for conversion through explicit constructor calls.
_blackHole(Float(16777217))
_blackHole(Double(2_147_483_647))
}
|
apache-2.0
|
0ff621604af1c3114cf82496f2c7ef5e
| 44.375 | 175 | 0.714286 | 3.310749 | false | false | false | false |
jasnig/DouYuTVMutate
|
DouYuTVMutate/DouYuTV/Live/Controller/DetailColumnListController.swift
|
1
|
4877
|
//
// DetailColumnListController.swift
// DouYuTVMutate
//
// Created by ZeroJ on 16/7/18.
// Copyright © 2016年 ZeroJ. All rights reserved.
//
import UIKit
class DetailColumnListController: BaseViewController {
struct ConstantValue {
static let sectionHeaderHeight = CGFloat(44.0)
static let anchorCellHeight = CGFloat(150.0)
static let anchorCellMargin = CGFloat(10.0)
}
lazy var layout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = ConstantValue.anchorCellMargin
layout.minimumInteritemSpacing = ConstantValue.anchorCellMargin
// 每一排显示两个cell
layout.itemSize = CGSize(width: (self.view.bounds.width - 3*layout.minimumInteritemSpacing)/2, height: ConstantValue.anchorCellHeight)
layout.scrollDirection = .Vertical
// 间距
layout.sectionInset = UIEdgeInsets(top: ConstantValue.anchorCellMargin, left: ConstantValue.anchorCellMargin, bottom: ConstantValue.anchorCellMargin, right: ConstantValue.anchorCellMargin)
return layout
}()
lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: self.layout)
collectionView.registerNib(UINib(nibName: String(AnchorCell), bundle: nil), forCellWithReuseIdentifier: self.anchorCell)
collectionView.backgroundColor = UIColor.whiteColor()
collectionView.delegate = self
collectionView.dataSource = self
return collectionView
}()
let anchorCell = "anchorCell"
private let viewModel: DetailColumnListViewModel
var isFirstTimeLoadData = true
init(viewModel: DetailColumnListViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 这里面获取到的view.bounds 不是最终的(ContentView里面设置之后才是准确的frame)
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
//
addRefreshHeader()
///
addRefreshFooter()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if isFirstTimeLoadData {
collectionView.zj_startHeaderAnimation()
isFirstTimeLoadData = false
}
}
func addRefreshHeader() {
collectionView.zj_addRefreshHeader(NormalAnimator.loadNormalAnimatorFromNib()) { [weak self] in
// 加载数据
guard let `self` = self else { return }
self.viewModel.headerRefreshWithHandler({ (loadState) in
self.collectionView.reloadData()
self.collectionView.zj_stopHeaderAnimation()
})
}
}
func addRefreshFooter() {
collectionView.zj_addRefreshFooter(NormalAnimator.loadNormalAnimatorFromNib()) { [weak self] in
guard let `self` = self else { return }
self.viewModel.footerRefreshWithHandler({ (loadState) in
self.collectionView.reloadData()
self.collectionView.zj_stopFooterAnimation()
})
}
}
override func addConstraints() {
collectionView.snp_makeConstraints { (make) in
make.leading.equalTo(view)
make.trailing.equalTo(view)
make.top.equalTo(view)
make.bottom.equalTo(view)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension DetailColumnListController: UICollectionViewDelegate, UICollectionViewDataSource {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.data.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(anchorCell, forIndexPath: indexPath) as! AnchorCell
// 设置数据
cell.configCell(viewModel.data[indexPath.row])
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let playerVc = PlayerController()
playerVc.roomID = viewModel.data[indexPath.row].room_id
playerVc.title = "播放"
showViewController(playerVc, sender: nil)
}
}
|
mit
|
df9f8c7149e8d99bf9adbf7f66247589
| 31.147651 | 196 | 0.65428 | 5.357942 | false | false | false | false |
iDevelopper/PBRevealViewController
|
Example4Swift/Example4Swift/MainViewController.swift
|
1
|
3577
|
//
// MainViewController.swift
// Example4Swift
//
// Created by Patrick BODET on 09/08/2016.
// Copyright © 2016 iDevelopper. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var menuButton: UIBarButtonItem!
@IBOutlet weak var rightButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
menuButton.target = self.revealViewController()
menuButton.action = #selector(PBRevealViewController.revealLeftView)
rightButton.target = self.revealViewController()
rightButton.action = #selector(PBRevealViewController.revealRightView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func resizeLeftView(_ sender: UIButton) {
if revealViewController().leftViewRevealWidth < 260 {
revealViewController().leftViewRevealWidth = 260
}
else {
revealViewController().leftViewRevealWidth = 160
}
}
@IBAction func replaceLeftView(_ sender: UIButton) {
var controller: UIViewController?
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nc = revealViewController().leftViewController as! UINavigationController
if nc.topViewController! is MenuTableViewController {
controller = storyboard.instantiateViewController(withIdentifier: "RightMenuTableViewController")
}
else {
controller = storyboard.instantiateViewController(withIdentifier: "MenuTableViewController")
}
let newNc = UINavigationController(rootViewController: controller!)
revealViewController().setLeft(newNc, animated: true)
}
@IBAction func replaceMainView(_ sender: UIButton) {
var controller: UIViewController?
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nc = revealViewController().mainViewController as! UINavigationController
if nc.topViewController! is MainViewController {
controller = storyboard.instantiateViewController(withIdentifier: "SecondViewController")
}
else {
controller = storyboard.instantiateViewController(withIdentifier: "MainViewController")
}
let newNc = UINavigationController(rootViewController: controller!)
revealViewController().setMain(newNc, animated: true)
}
@IBAction func replaceRightView(_ sender: UIButton) {
var controller: UIViewController?
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nc = revealViewController().rightViewController as! UINavigationController
if nc.topViewController! is RightMenuTableViewController {
controller = storyboard.instantiateViewController(withIdentifier: "MenuTableViewController")
}
else {
controller = storyboard.instantiateViewController(withIdentifier: "RightMenuTableViewController")
}
let newNc = UINavigationController(rootViewController: controller!)
revealViewController().setRight(newNc, animated: true)
}
@IBAction func resizeRightView(_ sender: UIButton) {
if revealViewController().rightViewRevealWidth < 260 {
revealViewController().rightViewRevealWidth = 260
}
else {
revealViewController().rightViewRevealWidth = 160
}
}
}
|
mit
|
e4ea9a1c0b5df9ad7958cc4a0fd4c315
| 36.25 | 109 | 0.677013 | 6.091993 | false | false | false | false |
csnu17/My-Swift-learning
|
WeatherOrNotApp/WeatherOrNot-Finished/WeatherOrNot/WeatherViewController.swift
|
1
|
6933
|
/// Copyright (c) 2018 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import UIKit
import PromiseKit
import CoreLocation
private let errorColor = UIColor(red: 0.96, green: 0.667, blue: 0.690, alpha: 1)
private let oneHour: TimeInterval = 3600 // Seconds per hour
private let randomCities = [("Tokyo", "JP", 35.683333, 139.683333),
("Jakarta", "ID", -6.2, 106.816667),
("Delhi", "IN", 28.61, 77.23),
("Manila", "PH", 14.58, 121),
("São Paulo", "BR", -23.55, -46.633333)]
class WeatherViewController: UIViewController {
@IBOutlet private var placeLabel: UILabel!
@IBOutlet private var tempLabel: UILabel!
@IBOutlet private var iconImageView: UIImageView!
@IBOutlet private var conditionLabel: UILabel!
@IBOutlet private var randomWeatherButton: UIButton!
let weatherAPI = WeatherHelper()
let locationHelper = LocationHelper()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateWithCurrentLocation()
}
private func updateWithCurrentLocation() {
locationHelper.getLocation()
.done { [weak self] placemark in
self?.handleLocation(placemark: placemark)
}
.catch { [weak self] error in
guard let self = self else { return }
self.tempLabel.text = "--"
self.placeLabel.text = "--"
switch error {
case is CLError where (error as? CLError)?.code == .denied:
self.conditionLabel.text = "Enable Location Permissions in Settings"
self.conditionLabel.textColor = UIColor.white
default:
self.conditionLabel.text = error.localizedDescription
self.conditionLabel.textColor = errorColor
}
}
after(seconds: oneHour).done { [weak self] in
self?.updateWithCurrentLocation()
}
}
private func handleMockLocation() {
let coordinate = CLLocationCoordinate2DMake(37.966667, 23.716667)
handleLocation(city: "Athens", state: "Greece", coordinate: coordinate)
}
private func handleLocation(placemark: CLPlacemark) {
handleLocation(city: placemark.locality,
state: placemark.administrativeArea,
coordinate: placemark.location!.coordinate)
}
private func handleLocation(city: String?,
state: String?,
coordinate: CLLocationCoordinate2D) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
weatherAPI.getWeather(atLatitude: coordinate.latitude,
longitude: coordinate.longitude)
.then { [weak self] weatherInfo -> Promise<UIImage> in
guard let self = self else { return brokenPromise() }
self.updateUI(with: weatherInfo)
return self.weatherAPI.getIcon(named: weatherInfo.weather.first!.icon)
}
.done(on: DispatchQueue.main) { icon in
self.iconImageView.image = icon
}
.catch { error in
self.tempLabel.text = "--"
self.conditionLabel.text = error.localizedDescription
self.conditionLabel.textColor = errorColor
}
.finally {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
private func updateUI(with weatherInfo: WeatherHelper.WeatherInfo) {
let tempMeasurement = Measurement(value: weatherInfo.main.temp, unit: UnitTemperature.kelvin)
let formatter = MeasurementFormatter()
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .none
formatter.numberFormatter = numberFormatter
let tempStr = formatter.string(from: tempMeasurement)
self.tempLabel.text = tempStr
self.placeLabel.text = weatherInfo.name
self.conditionLabel.text = weatherInfo.weather.first?.description ?? "empty"
self.conditionLabel.textColor = UIColor.white
}
@IBAction func showRandomWeather(_ sender: AnyObject) {
randomWeatherButton.isEnabled = false
let weatherPromises = randomCities.map { weatherAPI.getWeather(atLatitude: $0.2, longitude: $0.3) }
UIApplication.shared.isNetworkActivityIndicatorVisible = true
race(weatherPromises)
.then { [weak self] weatherInfo -> Promise<UIImage> in
guard let self = self else { return brokenPromise() }
self.placeLabel.text = weatherInfo.name
self.updateUI(with: weatherInfo)
return self.weatherAPI.getIcon(named: weatherInfo.weather.first!.icon)
}
.done { icon in
self.iconImageView.image = icon
}
.catch { error in
self.tempLabel.text = "--"
self.conditionLabel.text = error.localizedDescription
self.conditionLabel.textColor = errorColor
}
.finally {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.randomWeatherButton.isEnabled = true
}
}
}
// MARK: - UITextFieldDelegate
extension WeatherViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
guard let text = textField.text else { return false }
locationHelper.searchForPlacemark(text: text)
.done { placemark in
self.handleLocation(placemark: placemark)
}
.catch { _ in }
return true
}
}
|
mit
|
2c1092c49ec7242591d126e59654aa78
| 37.94382 | 103 | 0.685228 | 4.72529 | false | false | false | false |
hayleyqinn/windWeather
|
风生/WechatKit-master/WechatKit/WechatAuth.swift
|
1
|
3114
|
//
// WechatAuth.swift
// WechatKit
//
// Created by starboychina on 2015/12/03.
// Copyright © 2015年 starboychina. All rights reserved.
//
// MARK: - public
extension WechatManager {
/**
微信认证
- parameter completionHandler: 取得的token信息
*/
public func checkAuth(_ completionHandler: @escaping AuthHandle) {
if !WXApi.isWXAppInstalled() {
// 微信没有安装
completionHandler(.failure(WXErrCodeUnsupport.rawValue))
} else {
self.completionHandler = completionHandler
if let _ = WechatManager.openid,
let _ = WechatManager.accessToken,
let _ = WechatManager.refreshToken {
self.checkToken()
} else {
self.sendAuth()
}
}
}
/**
获取微信用户基本信息
- parameter completionHandler: 微信基本用户信息
*/
public func getUserInfo (_ completionHandler: @escaping AuthHandle) {
self.completionHandler = completionHandler
AlamofireController.request(WechatRoute.userinfo) { result in
if let err = result["errcode"] as? Int32 {
// let _ = result["errmsg"] as! String
completionHandler(.failure(err))
return
}
self.completionHandler(.success(result))
}
}
/**
退出
*/
public func logout() {
WechatManager.openid = ""
WechatManager.accessToken = ""
WechatManager.refreshToken = ""
}
}
// MARK: - private
extension WechatManager {
fileprivate func sendAuth() {
let req = SendAuthReq()
req.scope = "snsapi_userinfo"
req.state = WechatManager.csrfState
WXApi.send(req)
}
fileprivate func checkToken() {
AlamofireController.request(WechatRoute.checkToken) { result in
if !result.keys.contains("errcode") {
self.completionHandler(.success(result))
return
}
self.refreshAccessToken()
}
}
func getAccessToken(_ code: String) {
AlamofireController.request(WechatRoute.accessToken(code)) { result in
if let err = result["errcode"] as? Int32 {
// let _ = result["errmsg"] as! String
self.completionHandler(.failure(err))
return
}
self.saveOpenId(result)
}
}
fileprivate func refreshAccessToken() {
AlamofireController.request(WechatRoute.refreshToken) { result in
if !result.keys.contains("errcode") {
self.saveOpenId(result)
} else {
self.sendAuth()
}
}
}
fileprivate func saveOpenId(_ info: Dictionary<String, Any>) {
WechatManager.openid = info["openid"] as? String
WechatManager.accessToken = info["access_token"] as? String
WechatManager.refreshToken = info["refresh_token"] as? String
self.completionHandler(.success(info))
}
}
|
mit
|
340835f1fa10accee901209e58f987df
| 24.771186 | 78 | 0.564617 | 4.729393 | false | false | false | false |
joerocca/GitHawk
|
Classes/Views/UIImageView+Avatar.swift
|
1
|
539
|
//
// UIImageView+Avatar.swift
// Freetime
//
// Created by Ryan Nystrom on 11/19/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
extension UIImageView {
func configureForAvatar() {
contentMode = .scaleAspectFill
backgroundColor = Styles.Colors.Gray.lighter.color
layer.cornerRadius = Styles.Sizes.avatarCornerRadius
layer.borderColor = Styles.Colors.Gray.light.color.cgColor
layer.borderWidth = 1.0 / UIScreen.main.scale
clipsToBounds = true
}
}
|
mit
|
c8da64932e113c56a75908ec7d1bfdc5
| 23.454545 | 66 | 0.684015 | 4.23622 | false | false | false | false |
jiecao-fm/SwiftTheme
|
Source/NSAttributedString+Merge.swift
|
2
|
1431
|
//
// NSAttributedString+Merge.swift
// SwiftTheme
//
// Created by kcramer on 3/31/18.
// Copyright © 2018 kcramer. All rights reserved.
//
import Foundation
extension NSAttributedString {
// Initialize a new attributed string from an existing attributed string,
// merging the specified attributes.
// The specified attributes overwrite existing attributes with the
/// same keys. All other attributes are preserved.
convenience init(attributedString attrStr: NSAttributedString,
merging newAttributes: [NSAttributedString.Key: Any]) {
let newString = NSMutableAttributedString(attributedString: attrStr)
let range = NSMakeRange(0, attrStr.length)
newString.enumerateAttributes(in: range, options: []) {
(currentAttributes, range, _) in
let mergedAttributes = currentAttributes.merge(with: newAttributes)
newString.setAttributes(mergedAttributes, range: range)
}
self.init(attributedString: newString)
}
}
// Merge a dictionary into another dictionary, returning a new dictionary.
// The values of the other dictionary overwrite the values of the current
// dictionary.
private extension Dictionary {
func merge(with dict: Dictionary) -> Dictionary {
return dict.reduce(into: self) { (result, pair) in
let (key, value) = pair
result[key] = value
}
}
}
|
mit
|
99a9c00871d8acc0994e93924afe0532
| 35.666667 | 79 | 0.684615 | 4.880546 | false | false | false | false |
contentful/blog-app-ios
|
Code/BlogPostByCategoryList.swift
|
1
|
871
|
//
// BlogPostByCategoryList.swift
// Blog
//
// Created by Boris Bügling on 05/02/15.
// Copyright (c) 2015 Contentful GmbH. All rights reserved.
//
import UIKit
class BlogPostByCategoryList: BlogPostList {
weak var category: Category!
override var predicate: String? {
get { return String(format:"ANY category.identifier == '%@'", category!.identifier) }
set { }
}
override func viewDidLoad() {
super.viewDidLoad()
showMetadataHeader()
metadataViewController.backgroundView.backgroundColor = metadataViewController.backgroundView.backgroundColor?.colorWithAlphaComponent(0.85)
metadataViewController.metadata = PostListMetadata(body: category.categoryDescription, photo: category.icon, title: category.title)
metadataViewController.numberOfPostsFormatString = "%d posts in %@"
}
}
|
mit
|
f059c56fa156a8a98daf9cbb92397692
| 30.071429 | 148 | 0.711494 | 4.652406 | false | false | false | false |
NitWitStudios/NWSExtensions
|
NWSExtensions/Classes/UIView+Extensions.swift
|
1
|
8906
|
//
// UIView+Extensions.swift
// Bobblehead-TV
//
// Created by James Hickman on 7/27/16.
// Copyright © 2016 NitWit Studios. All rights reserved.
//
import UIKit
private var loadingView: UIView!
private var activityIndicatorView: UIActivityIndicatorView!
public extension UIView {
func showLoadingView() {
loadingView = UIView()
loadingView.backgroundColor = UIColor.red
self.addSubviewWithFullConstraints(loadingView)
activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activityIndicatorView.startAnimating()
loadingView.addSubviewWithCenteredConstraints(activityIndicatorView)
}
func hideLoadingView() {
activityIndicatorView.stopAnimating()
loadingView.removeFromSuperview()
}
func cropAsCircle() {
roundCornersWithRadius(self.bounds.width/2.0)
}
func roundCornersWithRadius(_ radius: CGFloat) {
layer.cornerRadius = radius
clipsToBounds = true
}
func removeCrop() {
layer.cornerRadius = 0.0
}
func addBorder(withWidth width: CGFloat, color: UIColor) {
layer.borderWidth = width
layer.borderColor = color.cgColor
}
func removeBorder() {
layer.borderWidth = 0.0
layer.borderColor = UIColor.clear.cgColor
}
var borderColor: UIColor? {
get {
return UIColor(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.cgColor
}
}
var leftBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: newValue, height: bounds.height))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = UIColor(cgColor: layer.borderColor!)
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line(==lineWidth)]", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line]|", options: [], metrics: nil, views: views))
}
}
var topBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: bounds.width, height: newValue))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = UIColor(cgColor: layer.borderColor!)
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line(==lineWidth)]", options: [], metrics: metrics, views: views))
}
}
var rightBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: bounds.width, y: 0.0, width: newValue, height: bounds.height))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = UIColor(cgColor: layer.borderColor!)
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "[line(==lineWidth)]|", options: [], metrics: metrics, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line]|", options: [], metrics: nil, views: views))
}
}
var bottomBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: bounds.height, width: bounds.width, height: newValue))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = UIColor(cgColor: layer.borderColor!)
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[line(==lineWidth)]|", options: [], metrics: metrics, views: views))
}
}
func addSubviewWithFullConstraints(_ subview: UIView, belowView: UIView? = nil, aboveView: UIView? = nil) {
subview.translatesAutoresizingMaskIntoConstraints = false
if let belowView = belowView {
self.insertSubview(subview, belowSubview: belowView)
} else if let aboveView = aboveView {
self.insertSubview(subview, aboveSubview: aboveView)
} else {
self.addSubview(subview)
}
let metrics = [ String: AnyObject ]()
let views = [ "subview" : subview ]
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "|[subview]|", options: [], metrics: metrics, views: views))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[subview]|", options: [], metrics: metrics, views: views))
self.updateConstraintsIfNeeded()
self.layoutIfNeeded()
}
func addSubviewWithCenteredConstraints(_ subview: UIView, belowView: UIView? = nil, aboveView: UIView? = nil) {
subview.translatesAutoresizingMaskIntoConstraints = false
if let belowView = belowView {
self.insertSubview(subview, belowSubview: belowView)
} else if let aboveView = aboveView {
self.insertSubview(subview, aboveSubview: aboveView)
} else {
self.addSubview(subview)
}
NSLayoutConstraint(item: subview, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: subview, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: subview, attribute: .left, relatedBy: .greaterThanOrEqual, toItem: self, attribute: .left, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: subview, attribute: .right, relatedBy: .greaterThanOrEqual, toItem: self, attribute: .right, multiplier: 1.0, constant: 0).isActive = true
self.updateConstraintsIfNeeded()
self.layoutIfNeeded()
}
func addSubviewWithBottomConstraints(_ subview: UIView) {
self.addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: subview, attribute: .top, relatedBy: .greaterThanOrEqual, toItem: self, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: subview, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: subview, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: subview, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: 0).isActive = true
self.updateConstraintsIfNeeded()
self.layoutIfNeeded()
}
func addSubviewWithTopConstraints(_ subview: UIView) {
self.addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = NSLayoutConstraint(item: subview, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: subview, attribute: .bottom, relatedBy: .greaterThanOrEqual, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0)
let leftConstraint = NSLayoutConstraint(item: subview, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1.0, constant: 0)
let rightConstraint = NSLayoutConstraint(item: subview, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: 0)
self.addConstraints([topConstraint,bottomConstraint,leftConstraint,rightConstraint])
self.updateConstraintsIfNeeded()
self.layoutIfNeeded()
}
}
|
mit
|
0f738e0f20b923c32b3e48b4cc6cfc1b
| 43.748744 | 180 | 0.645817 | 5.071185 | false | false | false | false |
AnsonHui/AHCategories
|
Classes/UIView+AHExtension.swift
|
1
|
2542
|
//
// UIView+AHExtension.swift
// Meepoo
//
// Created by AnsonHui on 2/17/16.
// Copyright © 2015 com.fantasy.ahcategories. All rights reserved.
//
import UIKit
public extension UIView {
public var ahLeft: CGFloat {
get {
return self.frame.minX
}
set {
var origin = self.frame.origin
origin.x = newValue
self.frame.origin = origin
}
}
public var ahRight: CGFloat {
get {
return self.frame.maxX
}
set {
var origin = self.frame.origin
origin.x = newValue - self.frame.size.width
self.frame.origin = origin
}
}
public var ahTop: CGFloat {
get {
return self.frame.minY
}
set {
var origin = self.frame.origin
origin.y = newValue
self.frame.origin = origin
}
}
public var ahBottom: CGFloat {
get {
return self.frame.maxY
}
set {
var origin = self.frame.origin
origin.y = newValue - self.frame.size.height
self.frame.origin = origin
}
}
public var ahWidth: CGFloat {
get {
return self.frame.size.width
}
set {
var size = self.frame.size
size.width = newValue
self.frame.size = size
}
}
public var ahHeight: CGFloat {
get {
return self.frame.size.height
}
set {
var size = self.frame.size
size.height = newValue
self.frame.size = size
}
}
public var ahCenterX: CGFloat {
get {
return self.center.x
}
set {
self.center.x = newValue
}
}
public var ahCenterY: CGFloat {
get {
return self.center.y
}
set {
self.center.y = newValue
}
}
public var ahSize: CGSize {
get {
return self.bounds.size
}
set {
self.frame.size = CGSize(width: newValue.width, height: newValue.height)
}
}
public func screenFrame() -> CGRect {
var superView: UIView?
superView = self.superview
var rect = self.frame
while (superView?.superview != nil) {
rect = superView!.convert(rect, to: superView!.superview!)
superView = superView!.superview
}
return rect
}
}
|
mit
|
a8915b4280ce7148ff759fdf209eb226
| 20.905172 | 84 | 0.491145 | 4.381034 | false | false | false | false |
dehlen/OMDBAPI
|
Classes/OMDBAPI/Movie.swift
|
1
|
3242
|
//
// MovieModel.swift
// Cineast
//
// Created by David Ehlen on 28.07.15.
// Copyright © 2015 David Ehlen. All rights reserved.
//
import Foundation
class Movie {
var title: String?
var year: Int?
var rated: String?
var releaseDate: NSDate?
var runtimeMins: Int?
var genres: [String]?
var directors: [String]?
var writers: [String]?
var actors: [String]?
var plot: String?
var languages: [String]?
var countries: [String]?
var awards: String?
var poster: String?
var metascore: Int?
var imdbRating: Float?
var imdbVotes: Int?
var imdbId: String?
var error: String?
var tomatoRatings: RottenTomatoRatings
init(jsonDict: NSDictionary)
{
title = jsonDict[kTitleKey] as! String?
if let s = jsonDict[kYearKey]as! String?
{
year = Int(s)
}
rated = jsonDict[kRatedKey] as! String?
if let s = jsonDict[kReleasedKey]as! String?
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd LLL yyyy"
releaseDate = dateFormatter.dateFromString(s)
}
if let s = jsonDict[kRuntimeKey] as! String?
{
var parts = s.componentsSeparatedByString(" ")
if parts.count > 0
{
runtimeMins = Int(parts[0])
}
}
if let s = jsonDict[kGenreKey]as! String?
{
genres = s.componentsSeparatedByString(", ")
}
if let s = jsonDict[kDirectorKey] as! String?
{
directors = s.componentsSeparatedByString(", ")
}
if let s = jsonDict[kWriterKey]as! String?
{
writers = s.componentsSeparatedByString(", ")
}
if let s = jsonDict[kActorsKey] as! String?
{
actors = s.componentsSeparatedByString(", ")
}
plot = jsonDict[kPlotKey]as! String?
if let s = jsonDict[kLanguageKey] as! String?
{
languages = s.componentsSeparatedByString(", ")
}
if let s = jsonDict[kCountryKey]as! String?
{
countries = s.componentsSeparatedByString(", ")
}
awards = jsonDict[kAwardsKey] as! String?
poster = jsonDict[kPosterKey] as! String?
if let s = jsonDict[kMetascoreKey] as! String?
{
metascore = Int(s)
}
if let s = jsonDict[kImdbRatingKey] as! String?
{
imdbRating = (s as NSString).floatValue
}
if let s = jsonDict[kImdbVotesKey] as! String?
{
imdbVotes = Int(s.stringByReplacingOccurrencesOfString(",", withString: ""))
}
imdbId = jsonDict[kImdbIdKey] as! String?
error = jsonDict[kErrorKey] as! String?
tomatoRatings = RottenTomatoRatings(jsonDict: jsonDict)
}
func description() -> String {
var titleString = ""
var yearString = ""
if let title = self.title {
titleString += title
}
if let year = self.year {
yearString += "\(year)"
}
return "\(titleString) (\(yearString))"
}
}
|
mit
|
5ff54576afb905c754bad6e3c658a580
| 27.182609 | 88 | 0.545202 | 4.304117 | false | false | false | false |
Witcast/witcast-ios
|
Pods/Material/Sources/iOS/CollectionViewController.swift
|
1
|
4741
|
/*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public protocol CollectionViewDelegate: UICollectionViewDelegate {}
public protocol CollectionViewDataSource: UICollectionViewDataSource {
/**
Retrieves the data source items for the collectionView.
- Returns: An Array of DataSourceItem objects.
*/
var dataSourceItems: [DataSourceItem] { get }
}
extension UIViewController {
/**
A convenience property that provides access to the CollectionViewController.
This is the recommended method of accessing the CollectionViewController
through child UIViewControllers.
*/
public var collectionViewController: CollectionViewController? {
var viewController: UIViewController? = self
while nil != viewController {
if viewController is CollectionViewController {
return viewController as? CollectionViewController
}
viewController = viewController?.parent
}
return nil
}
}
open class CollectionViewController: UIViewController {
/// A reference to a Reminder.
open let collectionView = CollectionView()
open var dataSourceItems = [DataSourceItem]()
open override func viewDidLoad() {
super.viewDidLoad()
prepare()
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
layoutSubviews()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepareView method
to initialize property values and other setup operations.
The super.prepareView method should always be called immediately
when subclassing.
*/
open func prepare() {
view.clipsToBounds = true
view.backgroundColor = .white
view.contentScaleFactor = Screen.scale
prepareCollectionView()
}
/// Calls the layout functions for the view heirarchy.
open func layoutSubviews() {
layoutCollectionView()
}
}
extension CollectionViewController {
/// Prepares the collectionView.
fileprivate func prepareCollectionView() {
collectionView.delegate = self
collectionView.dataSource = self
view.addSubview(collectionView)
layoutCollectionView()
}
}
extension CollectionViewController {
/// Sets the frame for the collectionView.
fileprivate func layoutCollectionView() {
collectionView.frame = view.bounds
}
}
extension CollectionViewController: CollectionViewDelegate {}
extension CollectionViewController: CollectionViewDataSource {
@objc
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
@objc
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSourceItems.count
}
@objc
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
}
}
|
apache-2.0
|
c9f798bcb37a1eaedc409a37fbf21677
| 35.19084 | 126 | 0.723054 | 5.590802 | false | false | false | false |
bringg/customer-sdk-ios-demo
|
Pods/Socket.IO-Client-Swift/Source/SocketIO/Client/SocketRawView.swift
|
5
|
6430
|
//
// SocketRawView.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/30/18.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Class that gives a backwards compatible way to cause an emit not to recursively check for Data objects.
///
/// Usage:
///
/// ```swift
/// socket.rawEmitView.emit("myEvent", myObject)
/// ```
public final class SocketRawView : NSObject {
private unowned let socket: SocketIOClient
init(socket: SocketIOClient) {
self.socket = socket
}
/// Send an event to the server, with optional data items.
///
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
/// will be emitted. The structure of the error data is `[eventName, items, theError]`
///
/// - parameter event: The event to send.
/// - parameter items: The items to send with this event. May be left out.
public func emit(_ event: String, _ items: SocketData...) {
do {
try emit(event, with: items.map({ try $0.socketRepresentation() }))
} catch {
DefaultSocketLogger.Logger.error("Error creating socketRepresentation for emit: \(event), \(items)",
type: "SocketIOClient")
socket.handleClientEvent(.error, data: [event, items, error])
}
}
/// Same as emit, but meant for Objective-C
///
/// - parameter event: The event to send.
/// - parameter items: The items to send with this event. Send an empty array to send no data.
@objc
public func emit(_ event: String, with items: [Any]) {
socket.emit([event] + items, binary: false)
}
/// Sends a message to the server, requesting an ack.
///
/// **NOTE**: It is up to the server send an ack back, just calling this method does not mean the server will ack.
/// Check that your server's api will ack the event being sent.
///
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
/// will be emitted. The structure of the error data is `[eventName, items, theError]`
///
/// Example:
///
/// ```swift
/// socket.emitWithAck("myEvent", 1).timingOut(after: 1) {data in
/// ...
/// }
/// ```
///
/// - parameter event: The event to send.
/// - parameter items: The items to send with this event. May be left out.
/// - returns: An `OnAckCallback`. You must call the `timingOut(after:)` method before the event will be sent.
public func emitWithAck(_ event: String, _ items: SocketData...) -> OnAckCallback {
do {
return emitWithAck(event, with: try items.map({ try $0.socketRepresentation() }))
} catch {
DefaultSocketLogger.Logger.error("Error creating socketRepresentation for emit: \(event), \(items)",
type: "SocketIOClient")
socket.handleClientEvent(.error, data: [event, items, error])
return OnAckCallback(ackNumber: -1, items: [], socket: socket)
}
}
/// Same as emitWithAck, but for Objective-C
///
/// **NOTE**: It is up to the server send an ack back, just calling this method does not mean the server will ack.
/// Check that your server's api will ack the event being sent.
///
/// Example:
///
/// ```swift
/// socket.emitWithAck("myEvent", with: [1]).timingOut(after: 1) {data in
/// ...
/// }
/// ```
///
/// - parameter event: The event to send.
/// - parameter items: The items to send with this event. Use `[]` to send nothing.
/// - returns: An `OnAckCallback`. You must call the `timingOut(after:)` method before the event will be sent.
@objc
public func emitWithAck(_ event: String, with items: [Any]) -> OnAckCallback {
return socket.createOnAck([event] + items, binary: false)
}
}
/// Class that gives a backwards compatible way to cause an emit not to recursively check for Data objects.
///
/// Usage:
///
/// ```swift
/// ack.rawEmitView.with(myObject)
/// ```
public final class SocketRawAckView : NSObject {
private unowned let socket: SocketIOClient
private let ackNum: Int
init(socket: SocketIOClient, ackNum: Int) {
self.socket = socket
self.ackNum = ackNum
}
/// Call to ack receiving this event.
///
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
/// will be emitted. The structure of the error data is `[ackNum, items, theError]`
///
/// - parameter items: A variable number of items to send when acking.
public func with(_ items: SocketData...) {
guard ackNum != -1 else { return }
do {
socket.emit(try items.map({ try $0.socketRepresentation() }), ack: ackNum, binary: false, isAck: true)
} catch {
socket.handleClientEvent(.error, data: [ackNum, items, error])
}
}
/// Call to ack receiving this event.
///
/// - parameter items: An array of items to send when acking. Use `[]` to send nothing.
@objc
public func with(_ items: [Any]) {
guard ackNum != -1 else { return }
socket.emit(items, ack: ackNum, binary: false, isAck: true)
}
}
|
mit
|
9d33f9eff83182c53237cbb04b5b47ef
| 38.447853 | 118 | 0.635614 | 4.25546 | false | false | false | false |
pawan007/SmartZip
|
SmartZip/Library/Extensions/Dictionary+Additions.swift
|
1
|
10464
|
//
// Dictionary+Additions.swift
//
// Created by Geetika Gupta on 31/03/16.
// Copyright © 2016 Modi. All rights reserved.
//
import Foundation
// MARK: - Dictionary Extension
internal extension Dictionary {
/**
Difference of self and the input dictionaries.
Two dictionaries are considered equal if they contain the same [key: value] pairs.
- parameter dictionaries: Dictionaries to subtract
- returns: Difference of self and the input dictionaries
*/
func difference <V: Equatable> (dictionaries: [Key: V]...) -> [Key: V] {
var result = [Key: V]()
each {
if let item = $1 as? V {
result[$0] = item
}
}
// Difference
for dictionary in dictionaries {
for (key, value) in dictionary {
if result.has(key) && result[key] == value {
result.removeValueForKey(key)
}
}
}
return result
}
/**
Union of self and the input dictionaries.
- parameter dictionaries: Dictionaries to join
- returns: Union of self and the input dictionaries
*/
func union (dictionaries: Dictionary...) -> Dictionary {
var result = self
dictionaries.each { (dictionary) -> Void in
dictionary.each { (key, value) -> Void in
_ = result.updateValue(value, forKey: key)
}
}
return result
}
/**
Checks if a key exists in the dictionary.
- parameter key: Key to check
- returns: true if the key exists
*/
func has (key: Key) -> Bool {
return indexForKey(key) != nil
}
/**
Creates an Array with values generated by running
each [key: value] of self through the mapFunction.
- parameter mapFunction:
- returns: Mapped array
*/
func toArray <V> (map: (Key, Value) -> V) -> [V] {
var mapped = [V]()
each {
mapped.append(map($0, $1))
}
return mapped
}
/**
Creates a Dictionary with the same keys as self and values generated by running
each [key: value] of self through the mapFunction.
- parameter mapFunction:
- returns: Mapped dictionary
*/
func mapValues <V> (map: (Key, Value) -> V) -> [Key: V] {
var mapped = [Key: V]()
each {
mapped[$0] = map($0, $1)
}
return mapped
}
/**
Creates a Dictionary with the same keys as self and values generated by running
each [key: value] of self through the mapFunction discarding nil return values.
- parameter mapFunction:
- returns: Mapped dictionary
*/
func mapFilterValues <V> (map: (Key, Value) -> V?) -> [Key: V] {
var mapped = [Key: V]()
each {
if let value = map($0, $1) {
mapped[$0] = value
}
}
return mapped
}
/**
Creates a Dictionary with keys and values generated by running
each [key: value] of self through the mapFunction discarding nil return values.
- parameter mapFunction:
- returns: Mapped dictionary
*/
func mapFilter <K, V> (map: (Key, Value) -> (K, V)?) -> [K: V] {
var mapped = [K: V]()
each {
if let value = map($0, $1) {
mapped[value.0] = value.1
}
}
return mapped
}
/**
Creates a Dictionary with keys and values generated by running
each [key: value] of self through the mapFunction.
- parameter mapFunction:
- returns: Mapped dictionary
*/
func map <K, V> (map: (Key, Value) -> (K, V)) -> [K: V] {
var mapped = [K: V]()
self.each({
let (_key, _value) = map($0, $1)
mapped[_key] = _value
})
return mapped
}
/**
Loops trough each [key: value] pair in self.
- parameter eachFunction: Function to inovke on each loop
*/
func each (each: (Key, Value) -> ()) {
for (key, value) in self {
each(key, value)
}
}
/**
Constructs a dictionary containing every [key: value] pair from self
for which testFunction evaluates to true.
- parameter testFunction: Function called to test each key, value
- returns: Filtered dictionary
*/
func filter (test: (Key, Value) -> Bool) -> Dictionary {
var result = Dictionary()
for (key, value) in self {
if test(key, value) {
result[key] = value
}
}
return result
}
/**
Creates a dictionary composed of keys generated from the results of
running each element of self through groupingFunction. The corresponding
value of each key is an array of the elements responsible for generating the key.
- parameter groupingFunction:
- returns: Grouped dictionary
*/
func groupBy <T> (group: (Key, Value) -> T) -> [T: [Value]] {
var result = [T: [Value]]()
for (key, value) in self {
let groupKey = group(key, value)
// If element has already been added to dictionary, append to it. If not, create one.
if result.has(groupKey) {
result[groupKey]! += [value]
} else {
result[groupKey] = [value]
}
}
return result
}
/**
Similar to groupBy. Doesn't return a list of values, but the number of values for each group.
- parameter groupingFunction: Function called to define the grouping key
- returns: Grouped dictionary
*/
func countBy <T> (group: (Key, Value) -> (T)) -> [T: Int] {
var result = [T: Int]()
for (key, value) in self {
let groupKey = group(key, value)
// If element has already been added to dictionary, append to it. If not, create one.
if result.has(groupKey) {
result[groupKey]! += 1
} else {
result[groupKey] = 1
}
}
return result
}
/**
Checks if test evaluates true for all the elements in self.
- parameter test: Function to call for each element
- returns: true if test returns true for all the elements in self
*/
func all (test: (Key, Value) -> (Bool)) -> Bool {
for (key, value) in self {
if !test(key, value) {
return false
}
}
return true
}
/**
Checks if test evaluates true for any element of self.
- parameter test: Function to call for each element
- returns: true if test returns true for any element of self
*/
func any (test: (Key, Value) -> (Bool)) -> Bool {
for (key, value) in self {
if test(key, value) {
return true
}
}
return false
}
/**
Returns the number of elements which meet the condition
- parameter test: Function to call for each element
- returns: the number of elements meeting the condition
*/
func countWhere (test: (Key, Value) -> (Bool)) -> Int {
var result = 0
for (key, value) in self {
if test(key, value) {
result += 1
}
}
return result
}
/**
Recombines the [key: value] couples in self trough combine using initial as initial value.
- parameter initial: Initial value
- parameter combine: Function that reduces the dictionary
- returns: Resulting value
*/
func reduce <U> (initial: U, combine: (U, Element) -> U) -> U {
return self.reduce(initial, combine: combine)
}
/**
Returns a copy of self, filtered to only have values for the whitelisted keys.
- parameter keys: Whitelisted keys
- returns: Filtered dictionary
*/
func pick (keys: [Key]) -> Dictionary {
return filter { (key: Key, _) -> Bool in
return keys.contains(key)
}
}
/**
Returns a copy of self, filtered to only have values for the whitelisted keys.
- parameter keys: Whitelisted keys
- returns: Filtered dictionary
*/
func pick (keys: Key...) -> Dictionary {
return pick(unsafeBitCast(keys, [Key].self))
}
/**
Returns a copy of self, filtered to only have values for the whitelisted keys.
- parameter keys: Keys to get
- returns: Dictionary with the given keys
*/
func at (keys: Key...) -> Dictionary {
return pick(keys)
}
/**
Removes a (key, value) pair from self and returns it as tuple.
If the dictionary is empty returns nil.
- returns: (key, value) tuple
*/
mutating func shift () -> (Key, Value)? {
if let key = keys.first {
return (key, removeValueForKey(key)!)
}
return nil
}
func queryItems() -> [NSURLQueryItem]? {
if self.keys.count > 0 {
var items = [NSURLQueryItem]()
for key in self.keys {
if key is String && self[key] is String {
items.append(NSURLQueryItem(name: key as! String, value: self[key] as? String))
} else {
assertionFailure("Key and values should be String type")
}
}
return items
}
return nil
}
}
///**
// Difference operator
// */
//public func - <K, V: Equatable> (first: [K: V], second: [K: V]) -> [K: V] {
// return first.difference(second)
//}
//
///**
// Intersection operator
// */
//public func & <K, V: Equatable> (first: [K: V], second: [K: V]) -> [K: V] {
// return first.intersection(second)
//}
//
///**
// Union operator
// */
//public func | <K: Hashable, V> (first: [K: V], second: [K: V]) -> [K: V] {
// return first.union(second)
//}
|
mit
|
b3406232501e7eec30f6764322215c92
| 25.424242 | 99 | 0.516773 | 4.54913 | false | false | false | false |
iosengineer/presentations
|
WhatsNewInXcode6/getoffmylawn/cloudView/cloudView/CloudView.swift
|
1
|
1749
|
//
// CloudView.swift
// cloudView
//
// Created by Adam Iredale on 16/06/2014.
// Copyright (c) 2014 Bionic Monocle Pty Ltd. All rights reserved.
//
import UIKit
import QuartzCore
@IBDesignable
class CloudView: UIView {
@IBInspectable
var xOffset:CGFloat = 100.0 {
didSet { setNeedsLayout() }
}
@IBInspectable
var yOffset:CGFloat = 40.0 {
didSet { setNeedsLayout() }
}
var cloud: CAShapeLayer?
init(frame: CGRect) {
super.init(frame: frame)
setupCloudLayer()
}
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
setupCloudLayer()
}
func setupCloudLayer() {
backgroundColor = UIColor.clearColor()
if let oldCloud = cloud {
oldCloud.removeFromSuperlayer()
}
cloud = CAShapeLayer()
layer.addSublayer(cloud)
var circle = CGPathCreateMutable()
cloud!.path = circle
cloud!.fillColor = UIColor.whiteColor().CGColor
CGPathAddEllipseInRect(circle, nil, CGRect(x: xOffset, y: yOffset, width: 100, height: 100))
CGPathAddEllipseInRect(circle, nil, CGRect(x: xOffset + 60, y: yOffset + 40, width: 100, height: 60))
CGPathAddEllipseInRect(circle, nil, CGRect(x: xOffset - 50, y: yOffset + 54, width: 100, height: 45))
CGPathAddEllipseInRect(circle, nil, CGRect(x: xOffset - 20, y: yOffset + 30, width: 50, height: 50))
CGPathAddEllipseInRect(circle, nil, CGRect(x: xOffset + 100, y: yOffset + 54, width: 100, height: 45))
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.setupCloudLayer()
}
}
|
cc0-1.0
|
cd699fdfaff294e7cf576c52f489a538
| 26.328125 | 110 | 0.608919 | 4.361596 | false | false | false | false |
GoodMorningCody/EverybodySwift
|
WeeklyToDo/WeeklyToDo/WeeklyToDoDB.swift
|
1
|
6998
|
//
// WeeklyToDoDB.swift
// WeeklyToDo
//
// Created by Cody on 2015. 1. 26..
// Copyright (c) 2015년 TIEKLE. All rights reserved.
//
import CoreData
import UiKit
var todoCoreModelFileName = "Weekly_To_Do_DB"
class WeeklyToDoDB : CoreDataController {
class var sharedInstance : WeeklyToDoDB {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : WeeklyToDoDB? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = WeeklyToDoDB()
}
return Static.instance!
}
override init() {
super.init()
var storedSymbols : [String] = [String]()
if let fetchResults = self.managedObjectContext!.executeFetchRequest(NSFetchRequest(entityName: "Weekend"), error: nil) as? [Weekend] {
for weekend in fetchResults {
storedSymbols.append(weekend.symbol)
}
}
var symbol : String
for index in 0...6 {
symbol = Weekly.weekday(index, useStandardFormat: false)
let filtered = storedSymbols.filter { $0 == symbol }
if filtered.count==0 {
let weekend = NSEntityDescription.insertNewObjectForEntityForName("Weekend", inManagedObjectContext: self.managedObjectContext!) as Weekend
weekend.symbol = symbol
}
}
sync()
}
func getWeekend( dayFromToday:Int ) -> Weekend? {
var symbolAtIndex = Weekly.weekdayFromNow(dayFromToday, useStandardFormat: true)
if let fetchResults = self.managedObjectContext!.executeFetchRequest(NSFetchRequest(entityName: "Weekend"), error: nil) as? [Weekend] {
for weekend in fetchResults {
if weekend.symbol==symbolAtIndex {
return weekend
}
}
}
return nil
}
func insertTaskInWeekend(todo:String, when:String, isRepeat:Bool) {
var task = NSEntityDescription.insertNewObjectForEntityForName("Task", inManagedObjectContext: self.managedObjectContext!) as Task
task.todo = todo
task.done = NSNumber(bool: false)
task.repeat = NSNumber(bool: isRepeat)
task.creationDate = NSDate()
if let fetchResults = self.managedObjectContext!.executeFetchRequest(NSFetchRequest(entityName: "Weekend"), error: nil) as? [Weekend] {
for weekend in fetchResults {
if let date = Weekly.dateFromNow(weekend.symbol) {
weekend.date = date
}
if weekend.symbol==when {
var tasks = weekend.mutableSetValueForKey("tasks")
task.weekend = weekend
tasks.addObject(task)
break
}
}
}
sync()
}
func removeTaskInWeekend(dayFromToday:Int, atIndex:Int) {
if let fetched = getWeekend(dayFromToday) {
if fetched.tasks.count>atIndex {
var tasks = fetched.mutableSetValueForKey("tasks")
var tasksArray = tasks.allObjects
tasksArray.removeAtIndex(atIndex)
fetched.tasks = NSSet(array: tasksArray)
}
}
sync()
}
func updateTaskInWeekend(dayFromToday:Int, atIndex:Int, todo:String, isRepeat:Bool) {
if let fetched = getWeekend(dayFromToday) {
if fetched.tasks.count>atIndex {
var tasks = fetched.tasks
var taskArray = tasks.allObjects
if let task = taskArray[atIndex] as? Task {
task.todo = todo
task.repeat = NSNumber(bool: isRepeat)
taskArray[atIndex] = task
}
fetched.tasks = NSSet(array: taskArray)
}
}
sync()
}
func switchRepeatOptionInWeekend(dayFromToday:Int, atIndex:Int) {
if let fetched = getWeekend(dayFromToday) {
if fetched.tasks.count>atIndex {
var task = fetched.tasks.allObjects[atIndex] as Task
task.repeat = !task.repeat.boolValue
}
}
sync()
}
func switchDoneTaskInWeekend(dayFromToday:Int, atIndex:Int) {
if let fetched = getWeekend(dayFromToday) {
if fetched.tasks.count>atIndex {
var task = fetched.tasks.allObjects[atIndex] as Task
task.done = !task.done.boolValue
if task.done==true {
task.doneDate = NSDate()
}
else {
task.doneDate = nil
}
}
}
sync()
}
func taskInWeekend(dayFromToday:Int, atIndex:Int) -> Task? {
if let fetched = getWeekend(dayFromToday) {
if fetched.tasks.count>atIndex {
return fetched.tasks.allObjects[atIndex] as? Task
}
}
return nil
}
func countOfDoneTaskInWeekend(dayFromToday:Int) -> Int {
var countOfDone = 0
if let fetched = getWeekend(dayFromToday) {
for task in fetched.tasks.allObjects {
if task.done.boolValue==true {
++countOfDone
}
}
}
return countOfDone
}
func countOfTaskInWeekend(dayFromToday:Int) -> Int {
if let fetched = getWeekend(dayFromToday) {
return fetched.tasks.count
}
return 0
}
func needUpdate() {
for i in 0...6 {
if let weekend = getWeekend(i) {
var tasks = weekend.mutableSetValueForKey("tasks")
var taskArray = tasks.allObjects
// 1. repeat false이고, creationDate가 오늘보다 작으면 삭제해야합니다
// 2. repeat가 true이고, done이 true이면서, doneDate가 오늘보다 작으면 done을 false변경 해야 합니다
// 3. 기존에 저장되어 있던 값을 갱신한 후 Weekend의 date값을 업데이트 합니다.
for( var i=taskArray.count-1; i>=0; --i ) {
var task = taskArray[i] as Task
if task.didCreataionWhenPresent()==true {
taskArray.removeAtIndex(i)
}
else if task.didDoneWhenPresent()==true {
task.done = NSNumber(bool: false)
}
}
if let date = Weekly.dateFromNow(weekend.symbol) {
weekend.date = date
}
weekend.tasks = NSSet(array: taskArray)
}
}
sync()
}
}
|
mit
|
c1432ed1545ed21b00af268ed12d26ab
| 32.661765 | 155 | 0.523886 | 4.811493 | false | false | false | false |
Awalz/SwiftyCam
|
DemoSwiftyCam/DemoSwiftyCam/ViewController.swift
|
1
|
6610
|
/*Copyright (c) 2016, Andrew Walz.
Redistribution and use in source and binary forms, with or without modification,are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import UIKit
import AVFoundation
class ViewController: SwiftyCamViewController, SwiftyCamViewControllerDelegate {
@IBOutlet weak var captureButton : SwiftyRecordButton!
@IBOutlet weak var flipCameraButton : UIButton!
@IBOutlet weak var flashButton : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
shouldPrompToAppSettings = true
cameraDelegate = self
maximumVideoDuration = 10.0
shouldUseDeviceOrientation = true
allowAutoRotate = true
audioEnabled = true
flashMode = .auto
flashButton.setImage(#imageLiteral(resourceName: "flashauto"), for: UIControl.State())
captureButton.buttonEnabled = false
}
override var prefersStatusBarHidden: Bool {
return true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
captureButton.delegate = self
}
func swiftyCamSessionDidStartRunning(_ swiftyCam: SwiftyCamViewController) {
print("Session did start running")
captureButton.buttonEnabled = true
}
func swiftyCamSessionDidStopRunning(_ swiftyCam: SwiftyCamViewController) {
print("Session did stop running")
captureButton.buttonEnabled = false
}
func swiftyCam(_ swiftyCam: SwiftyCamViewController, didTake photo: UIImage) {
let newVC = PhotoViewController(image: photo)
self.present(newVC, animated: true, completion: nil)
}
func swiftyCam(_ swiftyCam: SwiftyCamViewController, didBeginRecordingVideo camera: SwiftyCamViewController.CameraSelection) {
print("Did Begin Recording")
captureButton.growButton()
hideButtons()
}
func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFinishRecordingVideo camera: SwiftyCamViewController.CameraSelection) {
print("Did finish Recording")
captureButton.shrinkButton()
showButtons()
}
func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFinishProcessVideoAt url: URL) {
let newVC = VideoViewController(videoURL: url)
self.present(newVC, animated: true, completion: nil)
}
func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFocusAtPoint point: CGPoint) {
print("Did focus at point: \(point)")
focusAnimationAt(point)
}
func swiftyCamDidFailToConfigure(_ swiftyCam: SwiftyCamViewController) {
let message = NSLocalizedString("Unable to capture media", comment: "Alert message when something goes wrong during capture session configuration")
let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Alert OK button"), style: .cancel, handler: nil))
present(alertController, animated: true, completion: nil)
}
func swiftyCam(_ swiftyCam: SwiftyCamViewController, didChangeZoomLevel zoom: CGFloat) {
print("Zoom level did change. Level: \(zoom)")
print(zoom)
}
func swiftyCam(_ swiftyCam: SwiftyCamViewController, didSwitchCameras camera: SwiftyCamViewController.CameraSelection) {
print("Camera did change to \(camera.rawValue)")
print(camera)
}
func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFailToRecordVideo error: Error) {
print(error)
}
@IBAction func cameraSwitchTapped(_ sender: Any) {
switchCamera()
}
@IBAction func toggleFlashTapped(_ sender: Any) {
//flashEnabled = !flashEnabled
toggleFlashAnimation()
}
}
// UI Animations
extension ViewController {
fileprivate func hideButtons() {
UIView.animate(withDuration: 0.25) {
self.flashButton.alpha = 0.0
self.flipCameraButton.alpha = 0.0
}
}
fileprivate func showButtons() {
UIView.animate(withDuration: 0.25) {
self.flashButton.alpha = 1.0
self.flipCameraButton.alpha = 1.0
}
}
fileprivate func focusAnimationAt(_ point: CGPoint) {
let focusView = UIImageView(image: #imageLiteral(resourceName: "focus"))
focusView.center = point
focusView.alpha = 0.0
view.addSubview(focusView)
UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: {
focusView.alpha = 1.0
focusView.transform = CGAffineTransform(scaleX: 1.25, y: 1.25)
}) { (success) in
UIView.animate(withDuration: 0.15, delay: 0.5, options: .curveEaseInOut, animations: {
focusView.alpha = 0.0
focusView.transform = CGAffineTransform(translationX: 0.6, y: 0.6)
}) { (success) in
focusView.removeFromSuperview()
}
}
}
fileprivate func toggleFlashAnimation() {
//flashEnabled = !flashEnabled
if flashMode == .auto{
flashMode = .on
flashButton.setImage(#imageLiteral(resourceName: "flash"), for: UIControl.State())
}else if flashMode == .on{
flashMode = .off
flashButton.setImage(#imageLiteral(resourceName: "flashOutline"), for: UIControl.State())
}else if flashMode == .off{
flashMode = .auto
flashButton.setImage(#imageLiteral(resourceName: "flashauto"), for: UIControl.State())
}
}
}
|
bsd-2-clause
|
b43072758a25292c85be4a6c169e1a41
| 38.345238 | 160 | 0.700908 | 4.907201 | false | false | false | false |
jevy-wangfei/FeedMeIOS
|
LoginViewController.swift
|
1
|
3712
|
//
// LoginViewController.swift
// FeedMeIOS
//
// Created by Jun Chen on 9/04/2016.
// Copyright © 2016 FeedMe. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func displayMessage(message: String) {
let alert = UIAlertController(title: "Message", message: message, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
@IBAction func closeButtonClicked(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func signInButtonClicked(sender: UIButton) {
NSLog("username: %@, password: %@", usernameTextField.text!, passwordTextField.text!)
let verifyUserLoginResult = verifyUserLogin(usernameTextField.text, inputPassword: passwordTextField.text)
if verifyUserLoginResult.statusCode == 0 {
usernameTextField.text = ""
passwordTextField.text = ""
usernameTextField.becomeFirstResponder()
displayMessage(verifyUserLoginResult.description)
} else {
dismissViewControllerAnimated(true, completion: nil)
}
}
func verifyUsername(inputUsername: String?) -> (statusCode: Int, description: String) {
var statusCode = 0
var description = "Invalid username. Username does not exist."
// MARK: TODO HTTP POST (use main thread).
// if username exists, return (statusCode = 1, description = password).
return (statusCode, description)
}
func verifyUserLogin(inputUsername: String?, inputPassword: String?) -> (statusCode: Int, description: String) {
var statusCode = 0
var description = ""
// (1) verify username:
let verifyUsernameResult = verifyUsername(inputUsername)
if verifyUsernameResult.statusCode == 0 {
usernameTextField.text = ""
passwordTextField.text = ""
usernameTextField.becomeFirstResponder()
statusCode = 0
description = verifyUsernameResult.description
}
// (2) verify password:
else if passwordTextField.text! != verifyUsernameResult.description{
passwordTextField.text = ""
usernameTextField.becomeFirstResponder()
statusCode = 0
description = "Wrong username or wrong password. Try again."
} else {
statusCode = 1
description = ""
}
return (statusCode, description)
}
@IBAction func forgetPasswordButtonClicked(sender: UIButton) {
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
258cf8f7a34bd9a01b8b6205a02c41fa
| 31.269565 | 119 | 0.627863 | 5.691718 | false | false | false | false |
prettyxw/BingPaper
|
BingPaper/BingPictureManager.swift
|
2
|
5850
|
//
// BingPictureManager.swift
// BingPaper
//
// Created by Jingwen Peng on 2015-07-12.
// Copyright (c) 2015 Jingwen Peng. All rights reserved.
//
import Cocoa
class BingPictureManager {
let netRequest = NSMutableURLRequest()
let fileManager = FileManager.default
var pastWallpapersRange = 15
init() {
netRequest.cachePolicy = NSURLRequest.CachePolicy.useProtocolCachePolicy
netRequest.timeoutInterval = 15
netRequest.httpMethod = "GET"
}
fileprivate func buildInfoPath(workDir: String, onDate: String, atRegion: String) -> String {
if atRegion == "" {
return "\(workDir)/\(onDate).json"
}
return "\(workDir)/\(onDate)_\(atRegion).json"
}
fileprivate func buildImagePath(workDir: String, onDate: String, atRegion: String) -> String {
if atRegion == "" {
return "\(workDir)/\(onDate).jpg"
}
return "\(workDir)/\(onDate)_\(atRegion).jpg"
}
fileprivate func checkAndCreateWorkDirectory(workDir: String) {
try? fileManager.createDirectory(atPath: workDir, withIntermediateDirectories: true, attributes: nil)
}
fileprivate func obtainWallpaper(workDir: String, atIndex: Int, atRegion: String) {
let baseURL = "http://www.bing.com/HpImageArchive.aspx"
netRequest.url = URL(string: "\(baseURL)?format=js&n=1&idx=\(atIndex)&cc=\(atRegion)")
let reponseData = try? NSURLConnection.sendSynchronousRequest(netRequest as URLRequest, returning: nil)
if let dataValue = reponseData {
let data = try? JSONSerialization.jsonObject(with: dataValue, options: []) as AnyObject
if let objects = data?.value(forKey: "images") as? [NSObject] {
if let startDateString = objects[0].value(forKey: "startdate") as? String,
let urlString = objects[0].value(forKey: "url") as? String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd"
if let startDate = formatter.date(from: startDateString) {
formatter.dateFormat = "yyyy-MM-dd"
let dateString = formatter.string(from: startDate)
let infoPath = buildInfoPath(workDir: workDir, onDate: dateString, atRegion: atRegion)
let imagePath = buildImagePath(workDir: workDir, onDate: dateString, atRegion: atRegion)
if !fileManager.fileExists(atPath: infoPath) {
checkAndCreateWorkDirectory(workDir: workDir)
try? dataValue.write(to: URL(fileURLWithPath: infoPath), options: [.atomic])
}
if !fileManager.fileExists(atPath: imagePath) {
checkAndCreateWorkDirectory(workDir: workDir)
if urlString.contains("http://") || urlString.contains("https://") {
netRequest.url = URL.init(string: urlString)
} else {
netRequest.url = URL.init(string: "https://www.bing.com\(urlString)")
}
let imageResponData = try? NSURLConnection.sendSynchronousRequest(netRequest as URLRequest, returning: nil)
try? imageResponData?.write(to: URL(fileURLWithPath: imagePath), options: [.atomic])
}
}
}
}
}
}
func fetchWallpapers(workDir: String, atRegin: String) {
for index in -1...pastWallpapersRange {
obtainWallpaper(workDir: workDir, atIndex: index, atRegion: atRegin)
}
}
func fetchLastWallpaper(workDir: String, atRegin: String) {
for index in -1...0 {
obtainWallpaper(workDir: workDir, atIndex: index, atRegion: atRegin)
}
}
func checkWallpaperExist(workDir: String, onDate: String, atRegion: String) -> Bool {
if fileManager.fileExists(atPath: buildImagePath(workDir: workDir, onDate: onDate, atRegion: atRegion)) {
return true
}
return false
}
func getWallpaperInfo(workDir: String, onDate: String, atRegion: String) -> (copyright: String, copyrightLink: String) {
let jsonString = try? String.init(contentsOfFile: buildInfoPath(workDir: workDir, onDate: onDate, atRegion: atRegion))
if let jsonData = jsonString?.data(using: String.Encoding.utf8) {
let data = try? JSONSerialization.jsonObject(with: jsonData, options: []) as AnyObject
if let objects = data?.value(forKey: "images") as? [NSObject] {
if let copyrightString = objects[0].value(forKey: "copyright") as? String,
let copyrightLinkString = objects[0].value(forKey: "copyrightlink") as? String {
return (copyrightString, copyrightLinkString)
}
}
}
return ("", "")
}
func setWallpaper(workDir: String, onDate: String, atRegion: String) {
if checkWallpaperExist(workDir: workDir, onDate: onDate, atRegion: atRegion) {
NSScreen.screens.forEach({ (screen) in
try? NSWorkspace.shared.setDesktopImageURL(
URL(fileURLWithPath: buildImagePath(workDir: workDir, onDate: onDate, atRegion: atRegion)),
for: screen,
options: [:]
)
})
}
}
}
|
gpl-3.0
|
54d3bf2944258c861e7cf16ec6cedf85
| 42.984962 | 135 | 0.559145 | 4.842715 | false | false | false | false |
wilmarvh/Bounce
|
Hooops/Home/HomeListTypeViewController.swift
|
1
|
3914
|
import UIKit
import NothingButNet
enum HomeList: String {
case popular = "Popular"
case teams = "Teams"
case playoffs = "Playoffs"
case debuts = "Debuts"
case rebounds = "Rebounds"
case gifs = "GIFs"
case attachments = "Attachments"
static func allNames() -> [String] {
return [HomeList.popular.rawValue,
HomeList.teams.rawValue,
HomeList.playoffs.rawValue,
HomeList.debuts.rawValue,
HomeList.rebounds.rawValue,
HomeList.gifs.rawValue,
HomeList.attachments.rawValue
]
}
func asList() -> Shot.List {
switch self {
case .popular:
return .popular
case .teams:
return .teams
case .playoffs:
return .playoffs
case .debuts:
return .debuts
case .rebounds:
return .rebounds
case .gifs:
return .animated
case .attachments:
return .attachments
}
}
func buttonWidth() -> CGFloat {
switch self {
case .popular:
return 130
case .teams:
return 115
case .playoffs:
return 140
case .debuts:
return 125
case .rebounds:
return 165
case .gifs:
return 90
case .attachments:
return 200
}
}
}
class HomeListTypeViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var selectedList: HomeList = .popular
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureCollectionView()
}
// MARK: Configure view
func configureCollectionView() {
// cells and other
collectionView?.backgroundColor = UIColor.white
collectionView?.register(HomeFilterCell.self, forCellWithReuseIdentifier: "Cell")
// layout
if let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
layout.sectionInset = UIEdgeInsetsMake(25, 20, 25, 20)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 15
collectionView?.collectionViewLayout = layout
}
}
// MARK: UICollectionView DataSource / Delegate
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return HomeList.allNames().count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: HomeFilterCell.width, height: HomeFilterCell.height)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! HomeFilterCell
let item = HomeList.allNames()[indexPath.row]
cell.button.setTitle(item, for: .normal)
cell.button.isHighlighted = selectedList.rawValue == item
cell.button.action = { [weak self] in
let item = HomeList.allNames()[indexPath.row]
if let filter = HomeList(rawValue: item) {
self?.selectedList = filter
self?.collectionView?.reloadData()
_ = self?.popoverPresentationController?.delegate?.popoverPresentationControllerShouldDismissPopover!((self?.popoverPresentationController)!)
self?.dismiss(animated: true, completion: nil)
}
}
return cell
}
}
|
mit
|
11f69ea206c3707113424d1d054d5511
| 30.821138 | 160 | 0.603986 | 5.406077 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
WordPress/Classes/ViewRelated/Blog/Blog Details/Detail Header/NewBlogDetailHeaderView.swift
|
1
|
14825
|
import Gridicons
class NewBlogDetailHeaderView: UIView, BlogDetailHeader {
// MARK: - Child Views
private let actionRow: ActionRow
private let titleView: TitleView
// MARK: - Delegate
@objc weak var delegate: BlogDetailHeaderViewDelegate?
// Temporary method for migrating to NewBlogDetailHeaderView
@objc
var asView: UIView {
return self
}
@objc var updatingIcon: Bool = false {
didSet {
if updatingIcon {
titleView.siteIconView.activityIndicator.startAnimating()
} else {
titleView.siteIconView.activityIndicator.stopAnimating()
}
}
}
@objc var blavatarImageView: UIImageView {
return titleView.siteIconView.imageView
}
@objc var blog: Blog? {
didSet {
refreshIconImage()
toggleSpotlightOnSiteTitle()
refreshSiteTitle()
if let displayURL = blog?.displayURL as String? {
titleView.set(url: displayURL)
}
titleView.siteIconView.allowsDropInteraction = delegate?.siteIconShouldAllowDroppedImages() == true
}
}
@objc func refreshIconImage() {
if let blog = blog,
blog.hasIcon == true {
titleView.siteIconView.imageView.downloadSiteIcon(for: blog)
} else if let blog = blog,
blog.isWPForTeams() {
titleView.siteIconView.imageView.tintColor = UIColor.listIcon
titleView.siteIconView.imageView.image = UIImage.gridicon(.p2)
} else {
titleView.siteIconView.imageView.image = UIImage.siteIconPlaceholder
}
toggleSpotlightOnSiteIcon()
}
func setTitleLoading(_ isLoading: Bool) {
isLoading ? titleView.titleButton.startLoading() : titleView.titleButton.stopLoading()
}
func refreshSiteTitle() {
let blogName = blog?.settings?.name
let title = blogName != nil && blogName?.isEmpty == false ? blogName : blog?.displayURL as String?
titleView.titleButton.setTitle(title, for: .normal)
}
@objc func toggleSpotlightOnSiteTitle() {
titleView.titleButton.shouldShowSpotlight = QuickStartTourGuide.shared.isCurrentElement(.siteTitle)
}
@objc func toggleSpotlightOnSiteIcon() {
titleView.siteIconView.spotlightIsShown = QuickStartTourGuide.shared.isCurrentElement(.siteIcon)
}
private enum LayoutSpacing {
static let atSides: CGFloat = 16
static let top: CGFloat = 16
static let belowActionRow: CGFloat = 24
static func betweenTitleViewAndActionRow(_ showsActionRow: Bool) -> CGFloat {
return showsActionRow ? 32 : 0
}
static let spacingBelowIcon: CGFloat = 16
static let spacingBelowTitle: CGFloat = 8
static let minimumSideSpacing: CGFloat = 8
static let interSectionSpacing: CGFloat = 32
static let buttonsBottomPadding: CGFloat = 40
static let buttonsSidePadding: CGFloat = 40
static let maxButtonWidth: CGFloat = 390
static let siteIconSize = CGSize(width: 48, height: 48)
}
// MARK: - Initializers
required init(items: [ActionRow.Item]) {
actionRow = ActionRow(items: items)
titleView = TitleView(frame: .zero)
super.init(frame: .zero)
backgroundColor = .appBarBackground
setupChildViews(items: items)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Child View Initialization
private func setupChildViews(items: [ActionRow.Item]) {
titleView.siteIconView.tapped = { [weak self] in
QuickStartTourGuide.shared.visited(.siteIcon)
self?.titleView.siteIconView.spotlightIsShown = false
self?.delegate?.siteIconTapped()
}
titleView.siteIconView.dropped = { [weak self] images in
self?.delegate?.siteIconReceivedDroppedImage(images.first)
}
titleView.translatesAutoresizingMaskIntoConstraints = false
addSubview(titleView)
addSubview(actionRow)
addBottomBorder(withColor: .separator)
let showsActionRow = items.count > 0
setupConstraintsForChildViews(showsActionRow)
}
// MARK: - Constraints
private var topActionRowConstraint: NSLayoutConstraint?
private func setupConstraintsForChildViews(_ showsActionRow: Bool) {
let actionRowConstraints = constraintsForActionRow(showsActionRow)
let titleViewContraints = constraintsForTitleView()
NSLayoutConstraint.activate(actionRowConstraints + titleViewContraints)
}
private func constraintsForActionRow(_ showsActionRow: Bool) -> [NSLayoutConstraint] {
let widthConstraint = actionRow.widthAnchor.constraint(equalToConstant: LayoutSpacing.maxButtonWidth)
widthConstraint.priority = .defaultHigh
let topActionRowConstraint = actionRow.topAnchor.constraint(equalTo: titleView.bottomAnchor, constant: LayoutSpacing.betweenTitleViewAndActionRow(showsActionRow))
self.topActionRowConstraint = topActionRowConstraint
return [
topActionRowConstraint,
actionRow.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -LayoutSpacing.belowActionRow),
actionRow.leadingAnchor.constraint(greaterThanOrEqualTo: titleView.leadingAnchor),
actionRow.trailingAnchor.constraint(lessThanOrEqualTo: titleView.trailingAnchor),
actionRow.centerXAnchor.constraint(equalTo: centerXAnchor),
widthConstraint
]
}
private func constraintsForTitleView() -> [NSLayoutConstraint] {
[
titleView.topAnchor.constraint(equalTo: topAnchor, constant: LayoutSpacing.top),
titleView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: LayoutSpacing.atSides),
titleView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -LayoutSpacing.atSides)
]
}
// MARK: - User Action Handlers
@objc
private func siteSwitcherTapped() {
delegate?.siteSwitcherTapped()
}
@objc
private func titleButtonTapped() {
QuickStartTourGuide.shared.visited(.siteTitle)
titleView.titleButton.shouldShowSpotlight = false
delegate?.siteTitleTapped()
}
@objc
private func subtitleButtonTapped() {
delegate?.visitSiteTapped()
}
// MARK: - Accessibility
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
refreshStackViewVisibility()
}
private func refreshStackViewVisibility() {
let showsActionRow = !traitCollection.preferredContentSizeCategory.isAccessibilityCategory
topActionRowConstraint?.constant = LayoutSpacing.betweenTitleViewAndActionRow(showsActionRow)
}
}
fileprivate extension NewBlogDetailHeaderView {
class TitleView: UIView {
private enum LabelMinimumScaleFactor {
static let regular: CGFloat = 0.75
static let accessibility: CGFloat = 0.5
}
private enum Dimensions {
static let siteIconHeight: CGFloat = 64
static let siteIconWidth: CGFloat = 64
static let siteSwitcherHeight: CGFloat = 36
static let siteSwitcherWidth: CGFloat = 36
}
private enum LayoutSpacing {
static let betweenTitleAndSubtitleButtons: CGFloat = 8
static let betweenSiteIconAndTitle: CGFloat = 16
static let betweenTitleAndSiteSwitcher: CGFloat = 16
static let betweenSiteSwitcherAndRightPadding: CGFloat = 4
static let subtitleButtonImageInsets = UIEdgeInsets(top: 1, left: 4, bottom: 0, right: 0)
static let rtlSubtitleButtonImageInsets = UIEdgeInsets(top: 1, left: -4, bottom: 0, right: 4)
}
// MARK: - Child Views
private lazy var mainStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [
siteIconView,
titleStackView,
siteSwitcherButton
])
stackView.alignment = .center
stackView.spacing = LayoutSpacing.betweenSiteIconAndTitle
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
let siteIconView: SiteIconView = {
let siteIconView = SiteIconView(frame: .zero)
siteIconView.translatesAutoresizingMaskIntoConstraints = false
return siteIconView
}()
let subtitleButton: UIButton = {
let button = UIButton()
button.titleLabel?.font = WPStyleGuide.fontForTextStyle(.footnote)
button.titleLabel?.adjustsFontForContentSizeCategory = true
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.minimumScaleFactor = LabelMinimumScaleFactor.regular
button.titleLabel?.lineBreakMode = .byTruncatingTail
button.setTitleColor(.primary, for: .normal)
button.accessibilityHint = NSLocalizedString("Tap to view your site", comment: "Accessibility hint for button used to view the user's site")
if let pointSize = button.titleLabel?.font.pointSize {
button.setImage(UIImage.gridicon(.external, size: CGSize(width: pointSize, height: pointSize)), for: .normal)
}
// Align the image to the right
if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft {
button.semanticContentAttribute = .forceLeftToRight
button.imageEdgeInsets = LayoutSpacing.rtlSubtitleButtonImageInsets
} else {
button.semanticContentAttribute = .forceRightToLeft
button.imageEdgeInsets = LayoutSpacing.subtitleButtonImageInsets
}
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(subtitleButtonTapped), for: .touchUpInside)
return button
}()
let titleButton: SpotlightableButton = {
let button = SpotlightableButton(type: .custom)
button.contentHorizontalAlignment = .leading
button.titleLabel?.font = AppStyleGuide.blogDetailHeaderTitleFont
button.titleLabel?.adjustsFontForContentSizeCategory = true
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.minimumScaleFactor = LabelMinimumScaleFactor.regular
button.titleLabel?.lineBreakMode = .byTruncatingTail
button.titleLabel?.numberOfLines = 1
button.accessibilityHint = NSLocalizedString("Tap to change the site's title", comment: "Accessibility hint for button used to change site title")
// I don't understand why this is needed, but without it the button has additional
// vertical padding, so it's more difficult to get the spacing we want.
button.setImage(UIImage(), for: .normal)
button.setTitleColor(.text, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(titleButtonTapped), for: .touchUpInside)
return button
}()
let siteSwitcherButton: UIButton = {
let button = UIButton(frame: .zero)
let image = UIImage.gridicon(.chevronDown)
button.setImage(image, for: .normal)
button.contentMode = .center
button.translatesAutoresizingMaskIntoConstraints = false
button.tintColor = .gray
button.accessibilityLabel = NSLocalizedString("Switch Site", comment: "Button used to switch site")
button.accessibilityHint = NSLocalizedString("Tap to switch to another site, or add a new site", comment: "Accessibility hint for button used to switch site")
button.accessibilityIdentifier = "SwitchSiteButton"
button.addTarget(self, action: #selector(siteSwitcherTapped), for: .touchUpInside)
return button
}()
private(set) lazy var titleStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [
titleButton,
subtitleButton
])
stackView.alignment = .leading
stackView.distribution = .equalSpacing
stackView.axis = .vertical
stackView.spacing = LayoutSpacing.betweenTitleAndSubtitleButtons
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
setupChildViews()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Configuration
func set(url: String) {
subtitleButton.setTitle(url, for: .normal)
}
// MARK: - Accessibility
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
refreshMainStackViewAxis()
}
// MARK: - Child View Setup
private func setupChildViews() {
refreshMainStackViewAxis()
addSubview(mainStackView)
pinSubviewToAllEdges(mainStackView)
setupConstraintsForSiteSwitcher()
}
private func refreshMainStackViewAxis() {
if traitCollection.preferredContentSizeCategory.isAccessibilityCategory {
mainStackView.axis = .vertical
titleButton.titleLabel?.minimumScaleFactor = LabelMinimumScaleFactor.accessibility
subtitleButton.titleLabel?.minimumScaleFactor = LabelMinimumScaleFactor.accessibility
} else {
mainStackView.axis = .horizontal
titleButton.titleLabel?.minimumScaleFactor = LabelMinimumScaleFactor.regular
subtitleButton.titleLabel?.minimumScaleFactor = LabelMinimumScaleFactor.regular
}
}
// MARK: - Constraints
private func setupConstraintsForSiteSwitcher() {
NSLayoutConstraint.activate([
siteSwitcherButton.heightAnchor.constraint(equalToConstant: Dimensions.siteSwitcherHeight),
siteSwitcherButton.widthAnchor.constraint(equalToConstant: Dimensions.siteSwitcherWidth)
])
}
}
}
|
gpl-2.0
|
939f3c29687dc551a422490b6b5c8314
| 35.970075 | 170 | 0.659696 | 5.669216 | false | false | false | false |
FlexMonkey/Filterpedia
|
Filterpedia/customFilters/RefractedTextFilter.swift
|
1
|
8693
|
//
// RefractedTextFilter.swift
// Filterpedia
//
// Created by Simon Gladman on 07/02/2016.
// Copyright © 2016 Simon Gladman. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
import UIKit
import CoreImage
class RefractedTextFilter: CIFilter
{
var inputImage: CIImage?
{
didSet
{
if inputImage?.extent != refractingImage?.extent
{
refractingImage = nil
}
}
}
var inputText: NSString = "Filterpedia"
{
didSet
{
refractingImage = nil
}
}
var inputRefractiveIndex: CGFloat = 4.0
var inputLensScale: CGFloat = 50
var inputLightingAmount: CGFloat = 1.5
var inputLensBlur: CGFloat = 0
var inputBackgroundBlur: CGFloat = 2
var inputRadius: CGFloat = 15
{
didSet
{
if oldValue != inputRadius
{
refractingImage = nil
}
}
}
private var refractingImage: CIImage?
private var rawTextImage: CIImage?
override var attributes: [String : AnyObject]
{
return [
kCIAttributeFilterDisplayName: "Refracted Text",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputText": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSString",
kCIAttributeDisplayName: "Text",
kCIAttributeDefault: "Filterpedia",
kCIAttributeType: kCIAttributeTypeScalar],
"inputRefractiveIndex": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 4.0,
kCIAttributeDisplayName: "Refractive Index",
kCIAttributeMin: -4.0,
kCIAttributeSliderMin: -10.0,
kCIAttributeSliderMax: 10,
kCIAttributeType: kCIAttributeTypeScalar],
"inputLensScale": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 50,
kCIAttributeDisplayName: "Lens Scale",
kCIAttributeMin: 1,
kCIAttributeSliderMin: 1,
kCIAttributeSliderMax: 100,
kCIAttributeType: kCIAttributeTypeScalar],
"inputLightingAmount": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1.5,
kCIAttributeDisplayName: "Lighting Amount",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 5,
kCIAttributeType: kCIAttributeTypeScalar],
"inputRadius": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 15,
kCIAttributeDisplayName: "Edge Radius",
kCIAttributeMin: 5,
kCIAttributeSliderMin: 5,
kCIAttributeSliderMax: 50,
kCIAttributeType: kCIAttributeTypeScalar],
"inputLensBlur": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0,
kCIAttributeDisplayName: "Lens Blur",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 20,
kCIAttributeType: kCIAttributeTypeScalar],
"inputBackgroundBlur": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 2,
kCIAttributeDisplayName: "Background Blur",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 20,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
override func setDefaults()
{
inputText = "Filterpedia"
inputRefractiveIndex = 4.0
inputLensScale = 50
inputLightingAmount = 1.5
inputRadius = 15
inputLensBlur = 0
inputBackgroundBlur = 2
}
override var outputImage: CIImage!
{
guard let inputImage = inputImage,
refractingKernel = refractingKernel else
{
return nil
}
if refractingImage == nil
{
generateRefractingImage()
}
let extent = inputImage.extent
let arguments = [inputImage,
refractingImage!,
inputRefractiveIndex,
inputLensScale,
inputLightingAmount]
let blurMask = rawTextImage?.imageByApplyingFilter("CIColorInvert", withInputParameters: nil)
return refractingKernel.applyWithExtent(extent,
roiCallback:
{
(index, rect) in
return rect
},
arguments: arguments)!
.imageByApplyingFilter("CIMaskedVariableBlur", withInputParameters: [
kCIInputRadiusKey: inputBackgroundBlur,
"inputMask": blurMask!])
.imageByApplyingFilter("CIMaskedVariableBlur", withInputParameters: [
kCIInputRadiusKey: inputLensBlur,
"inputMask": rawTextImage!])
}
func generateRefractingImage()
{
let label = UILabel(frame: inputImage!.extent)
label.text = String(inputText)
label.textAlignment = .Center
label.font = UIFont.boldSystemFontOfSize(300)
label.adjustsFontSizeToFitWidth = true
label.numberOfLines = 0
label.textColor = UIColor.whiteColor()
UIGraphicsBeginImageContextWithOptions(
CGSize(width: label.frame.width,
height: label.frame.height), true, 1)
label.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let textImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
rawTextImage = CIImage(image: textImage)!
refractingImage = CIFilter(name: "CIHeightFieldFromMask",
withInputParameters: [
kCIInputRadiusKey: inputRadius,
kCIInputImageKey: rawTextImage!])?.outputImage?
.imageByCroppingToRect(inputImage!.extent)
}
let refractingKernel = CIKernel(string:
"float lumaAtOffset(sampler source, vec2 origin, vec2 offset)" +
"{" +
" vec3 pixel = sample(source, samplerTransform(source, origin + offset)).rgb;" +
" float luma = dot(pixel, vec3(0.2126, 0.7152, 0.0722));" +
" return luma;" +
"}" +
"kernel vec4 lumaBasedRefract(sampler image, sampler refractingImage, float refractiveIndex, float lensScale, float lightingAmount) \n" +
"{ " +
" vec2 d = destCoord();" +
" float northLuma = lumaAtOffset(refractingImage, d, vec2(0.0, -1.0));" +
" float southLuma = lumaAtOffset(refractingImage, d, vec2(0.0, 1.0));" +
" float westLuma = lumaAtOffset(refractingImage, d, vec2(-1.0, 0.0));" +
" float eastLuma = lumaAtOffset(refractingImage, d, vec2(1.0, 0.0));" +
" vec3 lensNormal = normalize(vec3((eastLuma - westLuma), (southLuma - northLuma), 1.0));" +
" vec3 refractVector = refract(vec3(0.0, 0.0, 1.0), lensNormal, refractiveIndex) * lensScale; " +
" vec3 outputPixel = sample(image, samplerTransform(image, d + refractVector.xy)).rgb;" +
" outputPixel += (northLuma - southLuma) * lightingAmount ;" +
" outputPixel += (eastLuma - westLuma) * lightingAmount ;" +
" return vec4(outputPixel, 1.0);" +
"}"
)
}
|
gpl-3.0
|
136d480516faed3a0345d8be797bd221
| 34.190283 | 145 | 0.574896 | 5.332515 | false | false | false | false |
Coderian/SwiftedKML
|
SwiftedKML/Elements/Orientation.swift
|
1
|
2556
|
//
// Orientation.swift
// SwiftedKML
//
// Created by 佐々木 均 on 2016/02/02.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// KML Orientation
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <element name="Orientation" type="kml:OrientationType" substitutionGroup="kml:AbstractObjectGroup"/>
public class Orientation :SPXMLElement, AbstractObjectGroup, HasXMLElementValue {
public static var elementName: String = "Orientation"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as Model: v.value.orientation = self
default: break
}
}
}
}
public var value: OrientationType
public required init(attributes:[String:String]){
self.value = OrientationType(attributes: attributes)
super.init(attributes: attributes)
}
public var abstractObject : AbstractObjectType { return self.value }
public func makeRelation(parent: SPXMLElement) -> SPXMLElement {
self.parent = parent
return parent
}
}
/// KML OrientationType
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <complexType name="OrientationType" final="#all">
/// <complexContent>
/// <extension base="kml:AbstractObjectType">
/// <sequence>
/// <element ref="kml:heading" minOccurs="0"/>
/// <element ref="kml:tilt" minOccurs="0"/>
/// <element ref="kml:roll" minOccurs="0"/>
/// <element ref="kml:OrientationSimpleExtensionGroup" minOccurs="0" maxOccurs="unbounded"/>
/// <element ref="kml:OrientationObjectExtensionGroup" minOccurs="0" maxOccurs="unbounded"/>
/// </sequence>
/// </extension>
/// </complexContent>
/// </complexType>
/// <element name="OrientationSimpleExtensionGroup" abstract="true" type="anySimpleType"/>
/// <element name="OrientationObjectExtensionGroup" abstract="true" substitutionGroup="kml:AbstractObjectGroup"/>
public class OrientationType: AbstractObjectType {
public var heading: Heading! // = 0.0
public var tilt: Tilt! // = 0.0
public var roll: Roll! // = 0.0
public var orientationSimpleExtensionGroup: [AnyObject] = []
public var orientationObjectExtensionGroup: [AbstractObjectGroup] = []
}
|
mit
|
1f9743835d1aba2e307528e086bb34e5
| 36.863636 | 117 | 0.654262 | 4.030645 | false | false | false | false |
bangslosan/SwiftOverlays
|
SwiftOverlays/SwiftOverlays.swift
|
1
|
8774
|
//
// SwiftOverlays.swift
// SwiftTest
//
// Created by Peter Prokop on 15/10/14.
// Copyright (c) 2014 Peter Prokop. All rights reserved.
//
import Foundation
import UIKit
// For convenience methods
public extension UIViewController {
func showWaitOverlay() -> UIView {
return SwiftOverlays.showCenteredWaitOverlay(self.view)
}
func showWaitOverlayWithText(text: NSString) -> UIView {
return SwiftOverlays.showCenteredWaitOverlayWithText(self.view, text: text)
}
func showTextOverlay(text: NSString) -> UIView {
return SwiftOverlays.showTextOverlay(self.view, text: text)
}
func showImageAndTextOverlay(image: UIImage, text: NSString) -> UIView {
return SwiftOverlays.showImageAndTextOverlay(self.view, image: image, text: text)
}
class func showNotificationOnTopOfStatusBar(notificationView: UIView, duration: NSTimeInterval) {
SwiftOverlays.showAnnoyingNotificationOnTopOfStatusBar(notificationView, duration: duration)
}
func removeAllOverlays() -> Void {
SwiftOverlays.removeAllOverlaysFromView(self.view)
}
}
public class SwiftOverlays: NSObject {
// Workaround for "Class variables not yet supported"
// You can customize these values
struct Statics {
// Some random number
static let containerViewTag = 456987123
static let cornerRadius = CGFloat(10)
static let padding = CGFloat(10)
static let backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)
static let textColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
static let font = UIFont(name: "HelveticaNeue", size: 14)!
// Annoying notifications on top of status bar
static let bannerDissapearAnimationDuration = 0.5
}
private struct PrivateStaticVars {
static var bannerWindow : UIWindow?
}
// MARK: Public class methods
public class func showCenteredWaitOverlay(parentView: UIView) -> UIView {
let ai = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
ai.startAnimating()
let containerViewRect = CGRectMake(0,
0,
ai.frame.size.width * 2,
ai.frame.size.height * 2)
let containerView = UIView(frame: containerViewRect)
containerView.tag = Statics.containerViewTag
containerView.layer.cornerRadius = Statics.cornerRadius
containerView.backgroundColor = Statics.backgroundColor
containerView.center = CGPointMake(parentView.bounds.size.width/2,
parentView.bounds.size.height/2);
ai.center = CGPointMake(containerView.bounds.size.width/2,
containerView.bounds.size.height/2);
containerView.addSubview(ai)
parentView.addSubview(containerView)
return containerView
}
public class func showCenteredWaitOverlayWithText(parentView: UIView, text: NSString) -> UIView {
let ai = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
ai.startAnimating()
return showGenericOverlay(parentView, text: text, accessoryView: ai)
}
public class func showImageAndTextOverlay(parentView: UIView, image: UIImage, text: NSString) -> UIView {
let imageView = UIImageView(image: image)
return showGenericOverlay(parentView, text: text, accessoryView: imageView)
}
public class func showGenericOverlay(parentView: UIView, text: NSString, accessoryView: UIView) -> UIView {
let label = labelForText(text)
label.frame = CGRectOffset(label.frame, accessoryView.frame.size.width + Statics.padding * 2, Statics.padding)
let actualSize = CGSizeMake(accessoryView.frame.size.width + label.frame.size.width + Statics.padding * 3,
max(label.frame.size.height, accessoryView.frame.size.height) + Statics.padding * 2)
// Container view
let containerViewRect = CGRectMake(0,
0,
actualSize.width,
actualSize.height)
let containerView = UIView(frame: containerViewRect)
containerView.tag = Statics.containerViewTag
containerView.layer.cornerRadius = Statics.cornerRadius
containerView.backgroundColor = Statics.backgroundColor
containerView.center = CGPointMake(parentView.bounds.size.width/2,
parentView.bounds.size.height/2);
accessoryView.frame = CGRectOffset(accessoryView.frame, Statics.padding, (actualSize.height - accessoryView.frame.size.height)/2)
containerView.addSubview(accessoryView)
containerView.addSubview(label)
parentView.addSubview(containerView)
return containerView
}
public class func showTextOverlay(parentView: UIView, text: NSString) -> UIView {
let label = labelForText(text)
label.frame = CGRectOffset(label.frame, Statics.padding, Statics.padding)
let actualSize = CGSizeMake(label.frame.size.width + Statics.padding * 2,
label.frame.size.height + Statics.padding * 2)
// Container view
let containerViewRect = CGRectMake(0,
0,
actualSize.width,
actualSize.height)
let containerView = UIView(frame: containerViewRect)
containerView.tag = Statics.containerViewTag
containerView.layer.cornerRadius = Statics.cornerRadius
containerView.backgroundColor = Statics.backgroundColor
containerView.center = CGPointMake(parentView.bounds.size.width/2,
parentView.bounds.size.height/2);
containerView.addSubview(label)
parentView.addSubview(containerView)
return containerView
}
public class func removeAllOverlaysFromView(parentView: UIView) {
var overlay: UIView?
while true {
overlay = parentView.viewWithTag(Statics.containerViewTag)
if overlay == nil {
break
}
overlay!.removeFromSuperview()
}
}
public class func showAnnoyingNotificationOnTopOfStatusBar(notificationView: UIView, duration: NSTimeInterval) {
if PrivateStaticVars.bannerWindow == nil {
PrivateStaticVars.bannerWindow = UIWindow()
PrivateStaticVars.bannerWindow!.windowLevel = UIWindowLevelStatusBar + 1
}
PrivateStaticVars.bannerWindow!.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, notificationView.frame.size.height)
PrivateStaticVars.bannerWindow!.hidden = false
let selector = Selector("closeAnnoyingNotificationOnTopOfStatusBar:")
let gestureRecognizer = UITapGestureRecognizer(target: self, action: selector)
notificationView.addGestureRecognizer(gestureRecognizer)
PrivateStaticVars.bannerWindow!.addSubview(notificationView)
self.performSelector(selector, withObject: notificationView, afterDelay: duration)
}
public class func closeAnnoyingNotificationOnTopOfStatusBar(sender: AnyObject) {
NSObject.cancelPreviousPerformRequestsWithTarget(self)
var notificationView: UIView?
if sender.isKindOfClass(UITapGestureRecognizer) {
notificationView = (sender as! UITapGestureRecognizer).view!
} else if sender.isKindOfClass(UIView) {
notificationView = (sender as! UIView)
}
UIView.animateWithDuration(Statics.bannerDissapearAnimationDuration,
animations: { () -> Void in
let frame = notificationView!.frame
notificationView!.frame = frame.rectByOffsetting(dx: 0, dy: -frame.size.height)
},
completion: { (finished) -> Void in
notificationView!.removeFromSuperview()
PrivateStaticVars.bannerWindow!.hidden = true
}
)
}
// MARK: Private class methods
private class func labelForText(text: NSString) -> UILabel {
let textSize = text.sizeWithAttributes([NSFontAttributeName: Statics.font])
let labelRect = CGRectMake(0,
0,
textSize.width,
textSize.height)
let label = UILabel(frame: labelRect)
label.font = Statics.font
label.textColor = Statics.textColor
label.text = text as String
label.numberOfLines = 0
return label;
}
}
|
mit
|
0ab7498ab60c96a3fd68526a780909bd
| 36.340426 | 141 | 0.652268 | 5.197867 | false | false | false | false |
kaishin/gifu
|
Sources/Gifu/Classes/Animator.swift
|
1
|
7321
|
#if os(iOS) || os(tvOS)
import UIKit
/// Responsible for parsing GIF data and decoding the individual frames.
public class Animator {
/// Total duration of one animation loop
var loopDuration: TimeInterval {
return frameStore?.loopDuration ?? 0
}
/// Number of frame to buffer.
var frameBufferCount = 50
/// Specifies whether GIF frames should be resized.
var shouldResizeFrames = false
/// Responsible for loading individual frames and resizing them if necessary.
var frameStore: FrameStore?
/// Tracks whether the display link is initialized.
private var displayLinkInitialized: Bool = false
/// A delegate responsible for displaying the GIF frames.
private weak var delegate: GIFAnimatable!
private var animationBlock: (() -> Void)? = nil
/// Responsible for starting and stopping the animation.
private lazy var displayLink: CADisplayLink = { [unowned self] in
self.displayLinkInitialized = true
let display = CADisplayLink(target: DisplayLinkProxy(target: self), selector: #selector(DisplayLinkProxy.onScreenUpdate))
display.isPaused = true
return display
}()
/// Introspect whether the `displayLink` is paused.
var isAnimating: Bool {
return !displayLink.isPaused
}
/// Total frame count of the GIF.
var frameCount: Int {
return frameStore?.frameCount ?? 0
}
/// Creates a new animator with a delegate.
///
/// - parameter view: A view object that implements the `GIFAnimatable` protocol.
///
/// - returns: A new animator instance.
public init(withDelegate delegate: GIFAnimatable) {
self.delegate = delegate
}
/// Checks if there is a new frame to display.
fileprivate func updateFrameIfNeeded() {
guard let store = frameStore else { return }
if store.isFinished {
stopAnimating()
if let animationBlock = animationBlock {
animationBlock()
}
return
}
store.shouldChangeFrame(with: displayLink.duration) {
if $0 { delegate.animatorHasNewFrame() }
}
}
/// Prepares the animator instance for animation.
///
/// - parameter imageName: The file name of the GIF in the specified bundle.
/// - parameter bundle: The bundle where the GIF is located (default Bundle.main).
/// - parameter size: The target size of the individual frames.
/// - parameter contentMode: The view content mode to use for the individual frames.
/// - parameter loopCount: Desired number of loops, <= 0 for infinite loop.
/// - parameter completionHandler: Completion callback function
func prepareForAnimation(withGIFNamed imageName: String, inBundle bundle: Bundle = .main, size: CGSize, contentMode: UIView.ContentMode, loopCount: Int = 0, completionHandler: (() -> Void)? = nil) {
guard let extensionRemoved = imageName.components(separatedBy: ".")[safe: 0],
let imagePath = bundle.url(forResource: extensionRemoved, withExtension: "gif"),
let data = try? Data(contentsOf: imagePath) else { return }
prepareForAnimation(withGIFData: data,
size: size,
contentMode: contentMode,
loopCount: loopCount,
completionHandler: completionHandler)
}
/// Prepares the animator instance for animation.
///
/// - parameter imageData: GIF image data.
/// - parameter size: The target size of the individual frames.
/// - parameter contentMode: The view content mode to use for the individual frames.
/// - parameter loopCount: Desired number of loops, <= 0 for infinite loop.
/// - parameter completionHandler: Completion callback function
func prepareForAnimation(withGIFData imageData: Data, size: CGSize, contentMode: UIView.ContentMode, loopCount: Int = 0, completionHandler: (() -> Void)? = nil) {
frameStore = FrameStore(data: imageData,
size: size,
contentMode: contentMode,
framePreloadCount: frameBufferCount,
loopCount: loopCount)
frameStore!.shouldResizeFrames = shouldResizeFrames
frameStore!.prepareFrames(completionHandler)
attachDisplayLink()
}
/// Add the display link to the main run loop.
private func attachDisplayLink() {
displayLink.add(to: .main, forMode: RunLoop.Mode.common)
}
deinit {
if displayLinkInitialized {
displayLink.invalidate()
}
}
/// Start animating.
func startAnimating() {
if frameStore?.isAnimatable ?? false {
displayLink.isPaused = false
}
}
/// Stop animating.
func stopAnimating() {
displayLink.isPaused = true
}
/// Prepare for animation and start animating immediately.
///
/// - parameter imageName: The file name of the GIF in the main bundle.
/// - parameter size: The target size of the individual frames.
/// - parameter contentMode: The view content mode to use for the individual frames.
/// - parameter loopCount: Desired number of loops, <= 0 for infinite loop.
/// - parameter completionHandler: Completion callback function
func animate(withGIFNamed imageName: String, size: CGSize, contentMode: UIView.ContentMode, loopCount: Int = 0, preparationBlock: (() -> Void)? = nil, animationBlock: (() -> Void)? = nil) {
self.animationBlock = animationBlock
prepareForAnimation(withGIFNamed: imageName,
size: size,
contentMode: contentMode,
loopCount: loopCount,
completionHandler: preparationBlock)
startAnimating()
}
/// Prepare for animation and start animating immediately.
///
/// - parameter imageData: GIF image data.
/// - parameter size: The target size of the individual frames.
/// - parameter contentMode: The view content mode to use for the individual frames.
/// - parameter loopCount: Desired number of loops, <= 0 for infinite loop.
/// - parameter completionHandler: Completion callback function
func animate(withGIFData imageData: Data, size: CGSize, contentMode: UIView.ContentMode, loopCount: Int = 0, preparationBlock: (() -> Void)? = nil, animationBlock: (() -> Void)? = nil) {
self.animationBlock = animationBlock
prepareForAnimation(withGIFData: imageData,
size: size,
contentMode: contentMode,
loopCount: loopCount,
completionHandler: preparationBlock)
startAnimating()
}
/// Stop animating and nullify the frame store.
func prepareForReuse() {
stopAnimating()
frameStore = nil
}
/// Gets the current image from the frame store.
///
/// - returns: An optional frame image to display.
func activeFrame() -> UIImage? {
return frameStore?.currentFrameImage
}
}
/// A proxy class to avoid a retain cycle with the display link.
fileprivate class DisplayLinkProxy {
/// The target animator.
private weak var target: Animator?
/// Create a new proxy object with a target animator.
///
/// - parameter target: An animator instance.
///
/// - returns: A new proxy instance.
init(target: Animator) { self.target = target }
/// Lets the target update the frame if needed.
@objc func onScreenUpdate() { target?.updateFrameIfNeeded() }
}
#endif
|
mit
|
fa7e937d7abddd7545a1a04efcbdc561
| 36.162437 | 200 | 0.6704 | 5.05245 | false | false | false | false |
nalexn/ViewInspector
|
Sources/ViewInspector/Modifiers/EnvironmentModifiers.swift
|
1
|
3787
|
import SwiftUI
// MARK: - Environment Modifiers
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {
func environment<T>(_ keyPath: WritableKeyPath<EnvironmentValues, T>) throws -> T {
return try environment(keyPath, call: "environment(\(Inspector.typeName(type: T.self)))")
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension InspectableView {
func environment<T>(_ reference: WritableKeyPath<EnvironmentValues, T>, call: String) throws -> T {
return try environment(reference, call: call, valueType: T.self)
}
func environment<T, V>(_ reference: WritableKeyPath<EnvironmentValues, T>,
call: String, valueType: V.Type) throws -> V {
guard let modifier = content.medium.environmentModifiers.last(where: { modifier in
guard let keyPath = try? modifier.keyPath() as? WritableKeyPath<EnvironmentValues, T>
else { return false }
return keyPath == reference
}) else {
throw InspectionError.modifierNotFound(
parent: Inspector.typeName(value: content.view), modifier: call, index: 0)
}
return try Inspector.cast(value: try modifier.value(), type: V.self)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension Inspector {
static func environmentKeyPath<T>(_ type: T.Type, _ value: Any) throws -> WritableKeyPath<EnvironmentValues, T> {
return try Inspector.attribute(path: "modifier|keyPath", value: value,
type: WritableKeyPath<EnvironmentValues, T>.self)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal protocol EnvironmentModifier {
static func qualifiesAsEnvironmentModifier() -> Bool
func keyPath() throws -> Any
func value() throws -> Any
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension EnvironmentModifier {
func qualifiesAsEnvironmentModifier() -> Bool {
return Self.qualifiesAsEnvironmentModifier()
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ModifiedContent: EnvironmentModifier where Modifier: EnvironmentModifier {
static func qualifiesAsEnvironmentModifier() -> Bool {
return Modifier.qualifiesAsEnvironmentModifier()
}
func keyPath() throws -> Any {
return try Inspector.attribute(label: "modifier", value: self,
type: Modifier.self).keyPath()
}
func value() throws -> Any {
return try Inspector.attribute(label: "modifier", value: self,
type: Modifier.self).value()
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension _EnvironmentKeyWritingModifier: EnvironmentModifier {
static func qualifiesAsEnvironmentModifier() -> Bool {
return true
}
func keyPath() throws -> Any {
return try Inspector.attribute(label: "keyPath", value: self)
}
func value() throws -> Any {
return try Inspector.attribute(label: "value", value: self)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension _EnvironmentKeyTransformModifier: EnvironmentModifier {
static func qualifiesAsEnvironmentModifier() -> Bool {
#if !os(macOS) && !targetEnvironment(macCatalyst)
if #available(iOS 15.0, tvOS 15.0, watchOS 8.0, *),
Value.self == TextInputAutocapitalization.self {
return true
}
#endif
return false
}
func keyPath() throws -> Any {
return try Inspector.attribute(label: "keyPath", value: self)
}
func value() throws -> Any {
return try Inspector.attribute(label: "transform", value: self)
}
}
|
mit
|
ada68884731674ff20d61ae02be994f5
| 33.743119 | 117 | 0.63586 | 4.34289 | false | false | false | false |
jmkr/SimpleAssetPicker
|
Example/simple-asset-picker-example/simple-asset-picker-example/SelectedTableViewController.swift
|
1
|
1358
|
//
// SelectedTableViewController.swift
// simple-asset-picker-example
//
// Created by John Meeker on 1/31/17.
// Copyright © 2017 John Meeker. All rights reserved.
//
import UIKit
import Photos
private var SelectedTableViewCellReuseIdentifier = "SelectedTableViewCell"
class SelectedTableViewController: UITableViewController {
var selectedAssets: Array<PHAsset>?
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let selectedAssets = selectedAssets {
return selectedAssets.count
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SelectedTableViewCellReuseIdentifier, for: indexPath)
if let selectedAssets = selectedAssets {
let asset = selectedAssets[indexPath.row]
cell.textLabel?.text = asset.description
// cell.imageView.image
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
|
mit
|
ef47d92197e6372efb24355bbc6dc771
| 28.5 | 118 | 0.695652 | 5.199234 | false | false | false | false |
blinksh/blink
|
Blink/FaceCam.swift
|
1
|
15656
|
//////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Blink is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
import UIKit
fileprivate extension UIView {
func setRecursiveBg(color: UIColor) {
layer.removeAllAnimations()
if self.backgroundColor != nil {
self.backgroundColor = color
}
for v in subviews {
v.setRecursiveBg(color: color)
}
}
}
fileprivate class PhotoOverlayController: UIImagePickerController {
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
view?.setRecursiveBg(color: UIColor.clear)
}
override func viewDidLoad() {
super.viewDidLoad()
sourceType = .camera
cameraDevice = .front
allowsEditing = false
showsCameraControls = false
view?.setRecursiveBg(color: UIColor.blinkTint)
}
}
fileprivate final class FaceCamView: UIView, UIGestureRecognizerDelegate {
private let _ctrl = PhotoOverlayController()
fileprivate var controller: UIViewController { _ctrl }
private let _tapRecognizer = UITapGestureRecognizer()
private let _doubleTapRecognizer = UITapGestureRecognizer()
private let _panRecognizer = UIPanGestureRecognizer()
private let _pinchRecognizer = UIPinchGestureRecognizer()
private let _rotationRecognizer = UIRotationGestureRecognizer()
private let _longPressRecognizer = UILongPressGestureRecognizer()
private let _placeholder = UIImageView(image: UIImage(systemName: "eyes"))
private var _flipped = false
var safeFrame: CGRect = .zero {
didSet {
_positionBackInSafeFrameIfNeeded()
}
}
struct State {
var frame: CGRect
var flipped: Bool
}
var state: State {
get {
State(frame: frame, flipped: _flipped)
}
set {
self.frame = newValue.frame
self._flipped = newValue.flipped
}
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(_placeholder)
_placeholder.bounds.size = CGSize(width: 36, height: 36)
_placeholder.tintColor = .white
addSubview(_ctrl.view)
clipsToBounds = true
backgroundColor = UIColor.blinkTint
layer.masksToBounds = true
layer.borderColor = UIColor.blinkTint.cgColor
layer.borderWidth = 1.5
_doubleTapRecognizer.addTarget(self, action: #selector(_doubleTap(recognizer:)))
_tapRecognizer.addTarget(self, action: #selector(_tap(recognizer:)))
_panRecognizer.addTarget(self, action: #selector(_pan(recognizer:)))
_pinchRecognizer.addTarget(self, action: #selector(_pinch(recognizer:)))
_rotationRecognizer.addTarget(self, action: #selector(_rotation(recognizer:)))
_longPressRecognizer.addTarget(self, action: #selector(_longPress(recognizer:)))
_doubleTapRecognizer.numberOfTapsRequired = 2
_doubleTapRecognizer.delegate = self
_tapRecognizer.delegate = self
_panRecognizer.delegate = self
_pinchRecognizer.delegate = self
_rotationRecognizer.delegate = self
_longPressRecognizer.delegate = self
_tapRecognizer.shouldRequireFailure(of: _doubleTapRecognizer)
addGestureRecognizer(_doubleTapRecognizer)
addGestureRecognizer(_tapRecognizer)
addGestureRecognizer(_panRecognizer)
addGestureRecognizer(_pinchRecognizer)
addGestureRecognizer(_rotationRecognizer)
addGestureRecognizer(_longPressRecognizer)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func _positionBackInSafeFrameIfNeeded() {
var center = self.center
if safeFrame.contains(center) {
return
}
let third = bounds.width / 3.0
if center.x < safeFrame.minX {
center.x = safeFrame.minX + third
}
if center.y < safeFrame.minY {
center.y = safeFrame.minY + third
}
if center.x > safeFrame.maxX {
center.x = safeFrame.maxX - third
}
if center.y > safeFrame.maxY {
center.y = safeFrame.maxY - third
}
UIView.animate(
withDuration: 1,
delay: 0,
usingSpringWithDamping: 0.9,
initialSpringVelocity: 0,
options: [.allowUserInteraction],
animations: {
self.center = center
},
completion: nil
)
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if super.point(inside: point, with: event) {
let r = bounds.width * 0.5
return point.offsetted(by: -r).magnitude <= r
}
return false
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.width * 0.5
_placeholder.center = CGPoint(x: bounds.width * 0.5, y: bounds.height * 0.5)
#if targetEnvironment(macCatalyst)
if _flipped {
_ctrl.view.transform = CGAffineTransform(scaleX: -1, y: 1);
} else {
_ctrl.view.transform = CGAffineTransform(scaleX: 1, y: 1);
}
let width = bounds.width * 16.0/9.0
_ctrl.view.frame = CGRect(x: (bounds.width - width) * 0.5, y: 0, width: width, height: bounds.height)
#else
let isPortait = (window?.windowScene?.interfaceOrientation ?? .landscapeLeft).isPortrait
if traitCollection.userInterfaceIdiom == UIUserInterfaceIdiom.pad {
// try to center on face on ipads
var offset = bounds.width / 3.0
if isPortait {
offset = 0
}
if _flipped {
_ctrl.view.transform = CGAffineTransform(scaleX: -1, y: 1);
_placeholder.transform = CGAffineTransform(scaleX: -1, y: 1);
_ctrl.view.frame = CGRect(x: 0, y: 0, width: bounds.width + offset, height: bounds.height)
} else {
_ctrl.view.transform = CGAffineTransform(scaleX: 1, y: 1);
_placeholder.transform = CGAffineTransform(scaleX: 1, y: 1);
_ctrl.view.frame = CGRect(x: -offset, y: 0, width: bounds.width + offset, height: bounds.height)
}
} else {
if _flipped {
_ctrl.view.transform = CGAffineTransform(scaleX: -1, y: 1);
_placeholder.transform = CGAffineTransform(scaleX: -1, y: 1);
} else {
_placeholder.transform = CGAffineTransform(scaleX: 1, y: 1);
_ctrl.view.transform = CGAffineTransform(scaleX: 1, y: 1);
}
let height = bounds.width * 4.0/3.0
_ctrl.view.frame = CGRect(x: 0, y: (bounds.height - height) * 0.5, width: bounds.width, height: height)
}
#endif
}
@objc func _doubleTap(recognizer: UITapGestureRecognizer) {
switch recognizer.state {
case .recognized:
_flipped.toggle()
setNeedsLayout()
case _: break
}
}
@objc func _tap(recognizer: UITapGestureRecognizer) {
print(recognizer)
}
@objc func _pan(recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .changed:
let p = recognizer.translation(in: superview)
center.offset(by: p)
recognizer.setTranslation(.zero, in: superview)
case .ended:
let velocity = recognizer.velocity(in: superview)
let targetPoint = _targetPoint(for: center, velocity: velocity)
let distanceVector = CGPoint(x: center.x - targetPoint.x, y: center.y - targetPoint.y)
let totalDistance = distanceVector.magnitude
let magVelocity = velocity.magnitude
let animationDuration: TimeInterval = 1
let springVelocity: CGFloat = magVelocity / totalDistance / CGFloat(animationDuration)
UIView.animate(
withDuration: animationDuration,
delay: 0,
usingSpringWithDamping: 2.0,
initialSpringVelocity: springVelocity,
options: [.allowUserInteraction],
animations: { self.center = targetPoint},
completion: { _ in
self._positionBackInSafeFrameIfNeeded()
}
)
case _: break
}
}
private func _targetPoint(for location: CGPoint, velocity: CGPoint) -> CGPoint {
let m: CGFloat = 0.15
return CGPoint(x: location.x + m * velocity.x, y: location.y + m * velocity.y)
}
@objc func _pinch(recognizer: UIPinchGestureRecognizer) {
switch recognizer.state {
case .changed:
let scale = recognizer.scale
let size = bounds.size
self.bounds.size = CGSize(width: size.width * scale, height: size.height * scale)
recognizer.scale = 1.0
case .ended:
let size = bounds.size
if size.width > safeFrame.width * 1.5 || size.height > safeFrame.height * 1.5 {
let length = min(safeFrame.width * 1.5, safeFrame.height * 1.5)
UIView.animate(
withDuration: 0.3,
delay: 0,
usingSpringWithDamping: 2.0,
initialSpringVelocity: 0,
options: [.allowUserInteraction],
animations: {
self.bounds.size = CGSize(width: length, height: length)
},
completion: nil
)
} else if size.width < 80 || size.height < 80 {
UIView.animate(
withDuration: 0.3,
delay: 0,
usingSpringWithDamping: 2.0,
initialSpringVelocity: 0,
options: [.allowUserInteraction],
animations: {
self.bounds.size = CGSize(width: 80, height: 80)
},
completion: nil
)
}
case _: break
}
}
@objc func _rotation(recognizer: UIRotationGestureRecognizer) {
switch recognizer.state {
case .changed:
self.transform = self.transform.rotated(by: recognizer.rotation)
recognizer.rotation = 0
case .ended:
UIView.animate(
withDuration: 0.3,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: [.allowUserInteraction],
animations: { self.transform = .identity },
completion: nil
)
case _: break
}
}
@objc func _longPress(recognizer: UILongPressGestureRecognizer) {
print(recognizer)
}
@objc func gestureRecognizer(
_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
) -> Bool {
true
}
}
fileprivate extension CGPoint {
var magnitude: CGFloat {
sqrt(pow(x, 2) + pow(y, 2))
}
mutating func offset(by: CGPoint) {
x += by.x
y += by.y
}
func offsetted(by: CGFloat) -> CGPoint {
var result = self
result.x += by
result.y += by
return result
}
}
class FaceCamManager {
private var _view: FaceCamView?
private var _spaceCtrl: SpaceController? = nil
private var _state: FaceCamView.State = .init(frame: .zero, flipped: false)
init() {
_view = FaceCamView(frame: CGRect(origin: .zero, size: CGSize(width: 80, height: 80)))
NotificationCenter.default.addObserver(self,
selector: #selector(moveToBackground(notificationInfo:)),
name: UIWindowScene.didEnterBackgroundNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(moveToForeground(notificationInfo:)),
name: UIWindowScene.willEnterForegroundNotification,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private static var __shared: FaceCamManager? = nil
@objc func moveToBackground(notificationInfo: NSNotification) {
guard let scene = notificationInfo.object as? UIWindowScene,
scene == _spaceCtrl?.view.window?.windowScene else {
return
}
if let view = _view {
view.controller.view.removeFromSuperview()
view.controller.removeFromParent()
view.removeFromSuperview()
_state = view.state
}
_view = nil;
}
@objc func moveToForeground(notificationInfo: NSNotification) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0 ) {
guard let spaceCtrl = self._spaceCtrl,
let scene = notificationInfo.object as? UIWindowScene,
scene == spaceCtrl.view.window?.windowScene
else {
return
}
let view = FaceCamView(frame: CGRect(origin: .zero, size: CGSize(width: 80, height: 80)))
self._view = view
view.state = self._state
spaceCtrl.view.addSubview(view)
spaceCtrl.addChild(view.controller)
view.layer.opacity = 0;
UIView.animate(withDuration: 0.5, delay: 0.5, options: []) {
view.layer.opacity = 1
}
}
}
static func attach(spaceCtrl: SpaceController) {
if __shared == nil {
__shared = .init()
} else {
__shared?._view?.controller.view.removeFromSuperview()
__shared?._view?.controller.removeFromParent()
__shared?._view?.removeFromSuperview()
}
guard let shared = __shared
else {
return
}
shared._spaceCtrl = spaceCtrl
let safeFrame = spaceCtrl.safeFrame
guard let view = shared._view else {
return
}
view.center = CGPoint(
x: safeFrame.minX + safeFrame.width * 0.5,
y: safeFrame.minY + safeFrame.height * 0.5
)
view.bounds.size = .zero
spaceCtrl.view.addSubview(view)
spaceCtrl.addChild(view.controller)
UIView.animate(
withDuration: 0.3,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: [.allowUserInteraction],
animations: { view.bounds.size = CGSize(width: 140, height: 140) },
completion: nil
)
}
static func update(in spaceCtrl: SpaceController) {
guard let shared = __shared,
let ctrl = shared._spaceCtrl,
ctrl == spaceCtrl,
let view = shared._view
else {
return
}
view.safeFrame = spaceCtrl.safeFrame
spaceCtrl.view.bringSubviewToFront(view)
view.setNeedsLayout()
}
static func turnOff() {
guard let shared = __shared
else {
return
}
guard let view = shared._view else {
return
}
UIView.animate(
withDuration: 0.3,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: [.allowUserInteraction],
animations: { view.alpha = 0 },
completion: { _ in
view.alpha = 1
view.removeFromSuperview()
view.controller.removeFromParent()
__shared = nil
}
)
}
}
|
gpl-3.0
|
3a30ac3760fbe638dfe117043015da03
| 27.992593 | 109 | 0.625064 | 4.502732 | false | false | false | false |
Acidburn0zzz/firefox-ios
|
Client/Frontend/Browser/FaviconHandler.swift
|
1
|
4152
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import SDWebImage
class FaviconHandler {
private let backgroundQueue = OperationQueue()
init() {
register(self, forTabEvents: .didLoadPageMetadata, .pageMetadataNotAvailable)
}
func loadFaviconURL(_ faviconURL: String, forTab tab: Tab) -> Deferred<Maybe<(Favicon, Data?)>> {
guard let iconURL = URL(string: faviconURL), let currentURL = tab.url else {
return deferMaybe(FaviconError())
}
let deferred = Deferred<Maybe<(Favicon, Data?)>>()
let manager = SDWebImageManager.shared
let url = currentURL.absoluteString
let site = Site(url: url, title: "")
let options: SDWebImageOptions = tab.isPrivate ? [SDWebImageOptions.lowPriority, SDWebImageOptions.fromCacheOnly] : SDWebImageOptions.lowPriority
var fetch: SDWebImageOperation?
let onProgress: SDWebImageDownloaderProgressBlock = { (receivedSize, expectedSize, _) -> Void in
if receivedSize > FaviconFetcher.MaximumFaviconSize || expectedSize > FaviconFetcher.MaximumFaviconSize {
fetch?.cancel()
}
}
let onSuccess: (Favicon, Data?) -> Void = { [weak tab] (favicon, data) -> Void in
tab?.favicons.append(favicon)
guard !(tab?.isPrivate ?? true), let appDelegate = UIApplication.shared.delegate as? AppDelegate, let profile = appDelegate.profile else {
deferred.fill(Maybe(success: (favicon, data)))
return
}
profile.favicons.addFavicon(favicon, forSite: site) >>> {
deferred.fill(Maybe(success: (favicon, data)))
}
}
let onCompletedSiteFavicon: SDInternalCompletionBlock = { (img, data, _, _, _, url) -> Void in
guard let urlString = url?.absoluteString else {
deferred.fill(Maybe(failure: FaviconError()))
return
}
let favicon = Favicon(url: urlString, date: Date())
guard let img = img else {
favicon.width = 0
favicon.height = 0
onSuccess(favicon, data)
return
}
favicon.width = Int(img.size.width)
favicon.height = Int(img.size.height)
onSuccess(favicon, data)
}
let onCompletedPageFavicon: SDInternalCompletionBlock = { (img, data, _, _, _, url) -> Void in
guard let img = img, let urlString = url?.absoluteString else {
// If we failed to download a page-level icon, try getting the domain-level icon
// instead before ultimately failing.
let siteIconURL = currentURL.domainURL.appendingPathComponent("favicon.ico")
fetch = manager.loadImage(with: siteIconURL, options: options, progress: onProgress, completed: onCompletedSiteFavicon)
return
}
let favicon = Favicon(url: urlString, date: Date())
favicon.width = Int(img.size.width)
favicon.height = Int(img.size.height)
onSuccess(favicon, data)
}
fetch = manager.loadImage(with: iconURL, options: options, progress: onProgress, completed: onCompletedPageFavicon)
return deferred
}
}
extension FaviconHandler: TabEventHandler {
func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) {
tab.favicons.removeAll(keepingCapacity: false)
guard let faviconURL = metadata.faviconURL else {
return
}
loadFaviconURL(faviconURL, forTab: tab).uponQueue(.main) { result in
guard let (favicon, data) = result.successValue else { return }
TabEvent.post(.didLoadFavicon(favicon, with: data), for: tab)
}
}
func tabMetadataNotAvailable(_ tab: Tab) {
tab.favicons.removeAll(keepingCapacity: false)
}
}
|
mpl-2.0
|
63d12577829edbb806ba6b9ca9b7b02d
| 37.444444 | 153 | 0.61657 | 4.942857 | false | false | false | false |
IAskWind/IAWExtensionTool
|
Pods/Kingfisher/Sources/Image/ImageDrawing.swift
|
2
|
21419
|
//
// ImageDrawing.swift
// Kingfisher
//
// Created by onevcat on 2018/09/28.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Accelerate
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
#endif
#if canImport(UIKit)
import UIKit
#endif
// MARK: - Image Transforming
extension KingfisherWrapper where Base: KFCrossPlatformImage {
// MARK: Blend Mode
/// Create image from `base` image and apply blend mode.
///
/// - parameter blendMode: The blend mode of creating image.
/// - parameter alpha: The alpha should be used for image.
/// - parameter backgroundColor: The background color for the output image.
///
/// - returns: An image with blend mode applied.
///
/// - Note: This method only works for CG-based image.
#if !os(macOS)
public func image(withBlendMode blendMode: CGBlendMode,
alpha: CGFloat = 1.0,
backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage
{
guard let _ = cgImage else {
assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
return base
}
let rect = CGRect(origin: .zero, size: size)
return draw(to: rect.size) { _ in
if let backgroundColor = backgroundColor {
backgroundColor.setFill()
UIRectFill(rect)
}
base.draw(in: rect, blendMode: blendMode, alpha: alpha)
return false
}
}
#endif
#if os(macOS)
// MARK: Compositing
/// Creates image from `base` image and apply compositing operation.
///
/// - Parameters:
/// - compositingOperation: The compositing operation of creating image.
/// - alpha: The alpha should be used for image.
/// - backgroundColor: The background color for the output image.
/// - Returns: An image with compositing operation applied.
///
/// - Note: This method only works for CG-based image. For any non-CG-based image, `base` itself is returned.
public func image(withCompositingOperation compositingOperation: NSCompositingOperation,
alpha: CGFloat = 1.0,
backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage
{
guard let _ = cgImage else {
assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.")
return base
}
let rect = CGRect(origin: .zero, size: size)
return draw(to: rect.size) { _ in
if let backgroundColor = backgroundColor {
backgroundColor.setFill()
rect.fill()
}
base.draw(in: rect, from: .zero, operation: compositingOperation, fraction: alpha)
return false
}
}
#endif
// MARK: Round Corner
/// Creates a round corner image from on `base` image.
///
/// - Parameters:
/// - radius: The round corner radius of creating image.
/// - size: The target size of creating image.
/// - corners: The target corners which will be applied rounding.
/// - backgroundColor: The background color for the output image
/// - Returns: An image with round corner of `self`.
///
/// - Note: This method only works for CG-based image. The current image scale is kept.
/// For any non-CG-based image, `base` itself is returned.
public func image(withRoundRadius radius: CGFloat,
fit size: CGSize,
roundingCorners corners: RectCorner = .all,
backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage
{
guard let _ = cgImage else {
assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
return base
}
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
return draw(to: size) { _ in
#if os(macOS)
if let backgroundColor = backgroundColor {
let rectPath = NSBezierPath(rect: rect)
backgroundColor.setFill()
rectPath.fill()
}
let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: radius)
#if swift(>=4.2)
path.windingRule = .evenOdd
#else
path.windingRule = .evenOddWindingRule
#endif
path.addClip()
base.draw(in: rect)
#else
guard let context = UIGraphicsGetCurrentContext() else {
assertionFailure("[Kingfisher] Failed to create CG context for image.")
return false
}
if let backgroundColor = backgroundColor {
let rectPath = UIBezierPath(rect: rect)
backgroundColor.setFill()
rectPath.fill()
}
let path = UIBezierPath(
roundedRect: rect,
byRoundingCorners: corners.uiRectCorner,
cornerRadii: CGSize(width: radius, height: radius)
)
context.addPath(path.cgPath)
context.clip()
base.draw(in: rect)
#endif
return false
}
}
#if os(iOS) || os(tvOS)
func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> KFCrossPlatformImage {
switch contentMode {
case .scaleAspectFit:
return resize(to: size, for: .aspectFit)
case .scaleAspectFill:
return resize(to: size, for: .aspectFill)
default:
return resize(to: size)
}
}
#endif
// MARK: Resizing
/// Resizes `base` image to an image with new size.
///
/// - Parameter size: The target size in point.
/// - Returns: An image with new size.
/// - Note: This method only works for CG-based image. The current image scale is kept.
/// For any non-CG-based image, `base` itself is returned.
public func resize(to size: CGSize) -> KFCrossPlatformImage {
guard let _ = cgImage else {
assertionFailure("[Kingfisher] Resize only works for CG-based image.")
return base
}
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
return draw(to: size) { _ in
#if os(macOS)
base.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
#else
base.draw(in: rect)
#endif
return false
}
}
/// Resizes `base` image to an image of new size, respecting the given content mode.
///
/// - Parameters:
/// - targetSize: The target size in point.
/// - contentMode: Content mode of output image should be.
/// - Returns: An image with new size.
///
/// - Note: This method only works for CG-based image. The current image scale is kept.
/// For any non-CG-based image, `base` itself is returned.
public func resize(to targetSize: CGSize, for contentMode: ContentMode) -> KFCrossPlatformImage {
let newSize = size.kf.resize(to: targetSize, for: contentMode)
return resize(to: newSize)
}
// MARK: Cropping
/// Crops `base` image to a new size with a given anchor.
///
/// - Parameters:
/// - size: The target size.
/// - anchor: The anchor point from which the size should be calculated.
/// - Returns: An image with new size.
///
/// - Note: This method only works for CG-based image. The current image scale is kept.
/// For any non-CG-based image, `base` itself is returned.
public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> KFCrossPlatformImage {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Crop only works for CG-based image.")
return base
}
let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
assertionFailure("[Kingfisher] Cropping image failed.")
return base
}
return KingfisherWrapper.image(cgImage: image, scale: scale, refImage: base)
}
// MARK: Blur
/// Creates an image with blur effect based on `base` image.
///
/// - Parameter radius: The blur radius should be used when creating blur effect.
/// - Returns: An image with blur effect applied.
///
/// - Note: This method only works for CG-based image. The current image scale is kept.
/// For any non-CG-based image, `base` itself is returned.
public func blurred(withRadius radius: CGFloat) -> KFCrossPlatformImage {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Blur only works for CG-based image.")
return base
}
// http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
// let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
// if d is odd, use three box-blurs of size 'd', centered on the output pixel.
let s = max(radius, 2.0)
// We will do blur on a resized image (*0.5), so the blur radius could be half as well.
// Fix the slow compiling time for Swift 3.
// See https://github.com/onevcat/Kingfisher/issues/611
let pi2 = 2 * CGFloat.pi
let sqrtPi2 = sqrt(pi2)
var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
if targetRadius.isEven { targetRadius += 1 }
// Determine necessary iteration count by blur radius.
let iterations: Int
if radius < 0.5 {
iterations = 1
} else if radius < 1.5 {
iterations = 2
} else {
iterations = 3
}
let w = Int(size.width)
let h = Int(size.height)
func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
let data = context.data
let width = vImagePixelCount(context.width)
let height = vImagePixelCount(context.height)
let rowBytes = context.bytesPerRow
return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
}
guard let context = beginContext(size: size, scale: scale, inverting: true) else {
assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
return base
}
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
endContext()
var inBuffer = createEffectBuffer(context)
guard let outContext = beginContext(size: size, scale: scale, inverting: true) else {
assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
return base
}
defer { endContext() }
var outBuffer = createEffectBuffer(outContext)
for _ in 0 ..< iterations {
let flag = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(
&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag)
// Next inBuffer should be the outButter of current iteration
(inBuffer, outBuffer) = (outBuffer, inBuffer)
}
#if os(macOS)
let result = outContext.makeImage().flatMap {
fixedForRetinaPixel(cgImage: $0, to: size)
}
#else
let result = outContext.makeImage().flatMap {
KFCrossPlatformImage(cgImage: $0, scale: base.scale, orientation: base.imageOrientation)
}
#endif
guard let blurredImage = result else {
assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
return base
}
return blurredImage
}
// MARK: Overlay
/// Creates an image from `base` image with a color overlay layer.
///
/// - Parameters:
/// - color: The color should be use to overlay.
/// - fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color,
/// 1.0 means transparent overlay.
/// - Returns: An image with a color overlay applied.
///
/// - Note: This method only works for CG-based image. The current image scale is kept.
/// For any non-CG-based image, `base` itself is returned.
public func overlaying(with color: KFCrossPlatformColor, fraction: CGFloat) -> KFCrossPlatformImage {
guard let _ = cgImage else {
assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
return base
}
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
return draw(to: rect.size) { context in
#if os(macOS)
base.draw(in: rect)
if fraction > 0 {
color.withAlphaComponent(1 - fraction).set()
rect.fill(using: .sourceAtop)
}
#else
color.set()
UIRectFill(rect)
base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
if fraction > 0 {
base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
}
#endif
return false
}
}
// MARK: Tint
/// Creates an image from `base` image with a color tint.
///
/// - Parameter color: The color should be used to tint `base`
/// - Returns: An image with a color tint applied.
public func tinted(with color: KFCrossPlatformColor) -> KFCrossPlatformImage {
#if os(watchOS)
return base
#else
return apply(.tint(color))
#endif
}
// MARK: Color Control
/// Create an image from `self` with color control.
///
/// - Parameters:
/// - brightness: Brightness changing to image.
/// - contrast: Contrast changing to image.
/// - saturation: Saturation changing to image.
/// - inputEV: InputEV changing to image.
/// - Returns: An image with color control applied.
public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> KFCrossPlatformImage {
#if os(watchOS)
return base
#else
return apply(.colorControl((brightness, contrast, saturation, inputEV)))
#endif
}
/// Return an image with given scale.
///
/// - Parameter scale: Target scale factor the new image should have.
/// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
public func scaled(to scale: CGFloat) -> KFCrossPlatformImage {
guard scale != self.scale else {
return base
}
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
return base
}
return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base)
}
}
// MARK: - Decoding Image
extension KingfisherWrapper where Base: KFCrossPlatformImage {
/// Returns the decoded image of the `base` image. It will draw the image in a plain context and return the data
/// from it. This could improve the drawing performance when an image is just created from data but not yet
/// displayed for the first time.
///
/// - Note: This method only works for CG-based image. The current image scale is kept.
/// For any non-CG-based image or animated image, `base` itself is returned.
public var decoded: KFCrossPlatformImage { return decoded(scale: scale) }
/// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
/// return the data from it. This could improve the drawing performance when an image is just created from
/// data but not yet displayed for the first time.
///
/// - Parameter scale: The given scale of target image should be.
/// - Returns: The decoded image ready to be displayed.
///
/// - Note: This method only works for CG-based image. The current image scale is kept.
/// For any non-CG-based image or animated image, `base` itself is returned.
public func decoded(scale: CGFloat) -> KFCrossPlatformImage {
// Prevent animated image (GIF) losing it's images
#if os(iOS)
if imageSource != nil { return base }
#else
if images != nil { return base }
#endif
guard let imageRef = cgImage else {
assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
return base
}
let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale)
return draw(to: size, inverting: true, scale: scale) { context in
context.draw(imageRef, in: CGRect(origin: .zero, size: size))
return true
}
}
}
extension KingfisherWrapper where Base: KFCrossPlatformImage {
func beginContext(size: CGSize, scale: CGFloat, inverting: Bool = false) -> CGContext? {
#if os(macOS)
guard let rep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: cgImage?.bitsPerComponent ?? 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: .calibratedRGB,
bytesPerRow: 0,
bitsPerPixel: 0) else
{
assertionFailure("[Kingfisher] Image representation cannot be created.")
return nil
}
rep.size = size
NSGraphicsContext.saveGraphicsState()
guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
assertionFailure("[Kingfisher] Image context cannot be created.")
return nil
}
NSGraphicsContext.current = context
return context.cgContext
#else
UIGraphicsBeginImageContextWithOptions(size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
if inverting { // If drawing a CGImage, we need to make context flipped.
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: 0, y: -size.height)
}
return context
#endif
}
func endContext() {
#if os(macOS)
NSGraphicsContext.restoreGraphicsState()
#else
UIGraphicsEndImageContext()
#endif
}
func draw(
to size: CGSize,
inverting: Bool = false,
scale: CGFloat? = nil,
refImage: KFCrossPlatformImage? = nil,
draw: (CGContext) -> Bool // Whether use the refImage (`true`) or ignore image orientation (`false`)
) -> KFCrossPlatformImage
{
let targetScale = scale ?? self.scale
guard let context = beginContext(size: size, scale: targetScale, inverting: inverting) else {
assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
return base
}
defer { endContext() }
let useRefImage = draw(context)
guard let cgImage = context.makeImage() else {
return base
}
let ref = useRefImage ? (refImage ?? base) : nil
return KingfisherWrapper.image(cgImage: cgImage, scale: targetScale, refImage: ref)
}
#if os(macOS)
func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> KFCrossPlatformImage {
let image = KFCrossPlatformImage(cgImage: cgImage, size: base.size)
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
return draw(to: self.size) { context in
image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
return false
}
}
#endif
}
|
mit
|
99dedde8eb75ed70053b53fa6c4a6da2
| 38.445672 | 129 | 0.595499 | 4.749224 | false | false | false | false |
nathawes/swift
|
test/Generics/generic_types.swift
|
8
|
6003
|
// RUN: %target-typecheck-verify-swift
protocol MyFormattedPrintable {
func myFormat() -> String
}
func myPrintf(_ format: String, _ args: MyFormattedPrintable...) {}
extension Int : MyFormattedPrintable {
func myFormat() -> String { return "" }
}
struct S<T : MyFormattedPrintable> {
var c : T
static func f(_ a: T) -> T {
return a
}
func f(_ a: T, b: Int) {
return myPrintf("%v %v %v", a, b, c)
}
}
func makeSInt() -> S<Int> {}
typealias SInt = S<Int>
var a : S<Int> = makeSInt()
a.f(1,b: 2)
var b : Int = SInt.f(1)
struct S2<T> {
@discardableResult
static func f() -> T {
S2.f()
}
}
struct X { }
var d : S<X> // expected-error{{type 'X' does not conform to protocol 'MyFormattedPrintable'}}
enum Optional<T> {
case element(T)
case none
init() { self = .none }
init(_ t: T) { self = .element(t) }
}
typealias OptionalInt = Optional<Int>
var uniontest1 : (Int) -> Optional<Int> = OptionalInt.element
var uniontest2 : Optional<Int> = OptionalInt.none
var uniontest3 = OptionalInt(1)
// FIXME: Stuff that should work, but doesn't yet.
// var uniontest4 : OptInt = .none
// var uniontest5 : OptInt = .Some(1)
func formattedTest<T : MyFormattedPrintable>(_ a: T) {
myPrintf("%v", a)
}
struct formattedTestS<T : MyFormattedPrintable> {
func f(_ a: T) {
formattedTest(a)
}
}
struct GenericReq<T : IteratorProtocol, U : IteratorProtocol>
where T.Element == U.Element {
}
func getFirst<R : IteratorProtocol>(_ r: R) -> R.Element {
var r = r
return r.next()!
}
func testGetFirst(ir: Range<Int>) {
_ = getFirst(ir.makeIterator()) as Int
}
struct XT<T> {
init(t : T) {
prop = (t, t)
}
static func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
class YT<T> {
init(_ t : T) {
prop = (t, t)
}
deinit {}
class func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
struct ZT<T> {
var x : T, f : Float
}
struct Dict<K, V> {
subscript(key: K) -> V { get {} set {} }
}
class Dictionary<K, V> { // expected-note{{generic type 'Dictionary' declared here}}
subscript(key: K) -> V { get {} set {} }
}
typealias XI = XT<Int>
typealias YI = YT<Int>
typealias ZI = ZT<Int>
var xi = XI(t: 17)
var yi = YI(17)
var zi = ZI(x: 1, f: 3.0)
var i : Int = XI.f()
i = XI.f()
i = xi.g()
i = yi.f() // expected-error{{static member 'f' cannot be used on instance of type 'YI' (aka 'YT<Int>')}}
i = yi.g()
var xif : (XI) -> () -> Int = XI.g
var gif : (YI) -> () -> Int = YI.g
var ii : (Int, Int) = xi.prop
ii = yi.prop
xi.prop = ii
yi.prop = ii
var d1 : Dict<String, Int>
var d2 : Dictionary<String, Int>
d1["hello"] = d2["world"]
i = d2["blarg"]
struct RangeOfPrintables<R : Sequence>
where R.Iterator.Element : MyFormattedPrintable {
var r : R
func format() -> String {
var s : String
for e in r {
s = s + e.myFormat() + " "
}
return s
}
}
struct Y {}
struct SequenceY : Sequence, IteratorProtocol {
typealias Iterator = SequenceY
typealias Element = Y
func next() -> Element? { return Y() }
func makeIterator() -> Iterator { return self }
}
func useRangeOfPrintables(_ roi : RangeOfPrintables<[Int]>) {
var rop : RangeOfPrintables<X> // expected-error{{type 'X' does not conform to protocol 'Sequence'}}
var rox : RangeOfPrintables<SequenceY> // expected-error{{type 'SequenceY.Element' (aka 'Y') does not conform to protocol 'MyFormattedPrintable'}}
}
var dfail : Dictionary<Int> // expected-error{{generic type 'Dictionary' specialized with too few type parameters (got 1, but expected 2)}}
var notgeneric : Int<Float> // expected-error{{cannot specialize non-generic type 'Int'}}{{21-28=}}
var notgenericNested : Array<Int<Float>> // expected-error{{cannot specialize non-generic type 'Int'}}{{33-40=}}
// Make sure that redundant typealiases (that map to the same
// underlying type) don't break protocol conformance or use.
class XArray : ExpressibleByArrayLiteral {
typealias Element = Int
init() { }
required init(arrayLiteral elements: Int...) { }
}
class YArray : XArray {
typealias Element = Int
required init(arrayLiteral elements: Int...) {
super.init()
}
}
var yarray : YArray = [1, 2, 3]
var xarray : XArray = [1, 2, 3]
// Type parameters can be referenced only via unqualified name lookup
struct XParam<T> { // expected-note{{'XParam' declared here}}
func foo(_ x: T) {
_ = x as T
}
static func bar(_ x: T) {
_ = x as T
}
}
var xp : XParam<Int>.T = Int() // expected-error{{'T' is not a member type of 'XParam<Int>'}}
// Diagnose failure to meet a superclass requirement.
class X1 { }
class X2<T : X1> { } // expected-note{{requirement specified as 'T' : 'X1' [with T = X3]}}
class X3 { }
var x2 : X2<X3> // expected-error{{'X2' requires that 'X3' inherit from 'X1'}}
protocol P {
associatedtype AssocP
}
protocol Q {
associatedtype AssocQ
}
struct X4 : P, Q {
typealias AssocP = Int
typealias AssocQ = String
}
struct X5<T, U> where T: P, T: Q, T.AssocP == T.AssocQ { } // expected-note{{requirement specified as 'T.AssocP' == 'T.AssocQ' [with T = X4]}}
var y: X5<X4, Int> // expected-error{{'X5' requires the types 'X4.AssocP' (aka 'Int') and 'X4.AssocQ' (aka 'String') be equivalent}}
// Recursive generic signature validation.
class Top {}
class Bottom<T : Bottom<Top>> {}
// expected-error@-1 {{generic class 'Bottom' references itself}}
// expected-note@-2 {{type declared here}}
// expected-error@-3 {{circular reference}}
// expected-note@-4 {{while resolving type 'Bottom<Top>'}}
// expected-note@-5 {{through reference here}}
// Invalid inheritance clause
struct UnsolvableInheritance1<T : T.A> {}
// expected-error@-1 {{'A' is not a member type of 'T'}}
struct UnsolvableInheritance2<T : U.A, U : T.A> {}
// expected-error@-1 {{'A' is not a member type of 'U'}}
// expected-error@-2 {{'A' is not a member type of 'T'}}
enum X7<T> where X7.X : G { case X } // expected-error{{enum case 'X' is not a member type of 'X7<T>'}}
// expected-error@-1{{cannot find type 'G' in scope}}
|
apache-2.0
|
45f6a5905698eaea1a56460ef9e88cb3
| 23.303644 | 148 | 0.633683 | 3.051856 | false | false | false | false |
crazypoo/PTools
|
Pods/PhoneNumberKit/PhoneNumberKit/Constants.swift
|
1
|
6004
|
//
// Constants.swift
// PhoneNumberKit
//
// Created by Roy Marmelstein on 25/10/2015.
// Copyright © 2021 Roy Marmelstein. All rights reserved.
//
import Foundation
// MARK: Private Enums
enum PhoneNumberCountryCodeSource {
case numberWithPlusSign
case numberWithIDD
case numberWithoutPlusSign
case defaultCountry
}
// MARK: Public Enums
/**
Enumeration for parsing error types
- GeneralError: A general error occured.
- InvalidCountryCode: A country code could not be found or the one found was invalid
- NotANumber: The string provided is not a number
- TooLong: The string provided is too long to be a valid number
- TooShort: The string provided is too short to be a valid number
- Deprecated: The method used was deprecated
- metadataNotFound: PhoneNumberKit was unable to read the included metadata
*/
public enum PhoneNumberError: Error {
case generalError
case invalidCountryCode
case notANumber
case unknownType
case tooLong
case tooShort
case deprecated
case metadataNotFound
}
extension PhoneNumberError: LocalizedError {
public var errorDescription: String? {
switch self {
case .generalError: return NSLocalizedString("An error occured whilst validating the phone number.", comment: "")
case .invalidCountryCode: return NSLocalizedString("The country code is invalid.", comment: "")
case .notANumber: return NSLocalizedString("The number provided is invalid.", comment: "")
case .unknownType: return NSLocalizedString("Phone number type is unknown.", comment: "")
case .tooLong: return NSLocalizedString("The number provided is too long.", comment: "")
case .tooShort: return NSLocalizedString("The number provided is too short.", comment: "")
case .deprecated: return NSLocalizedString("This function is deprecated.", comment: "")
case .metadataNotFound: return NSLocalizedString("Valid metadata is missing.", comment: "")
}
}
}
public enum PhoneNumberFormat {
case e164 // +33689123456
case international // +33 6 89 12 34 56
case national // 06 89 12 34 56
}
/**
Phone number type enumeration
- fixedLine: Fixed line numbers
- mobile: Mobile numbers
- fixedOrMobile: Either fixed or mobile numbers if we can't tell conclusively.
- pager: Pager numbers
- personalNumber: Personal number numbers
- premiumRate: Premium rate numbers
- sharedCost: Shared cost numbers
- tollFree: Toll free numbers
- voicemail: Voice mail numbers
- vOIP: Voip numbers
- uan: UAN numbers
- unknown: Unknown number type
*/
public enum PhoneNumberType: String, Codable {
case fixedLine
case mobile
case fixedOrMobile
case pager
case personalNumber
case premiumRate
case sharedCost
case tollFree
case voicemail
case voip
case uan
case unknown
case notParsed
}
public enum PossibleLengthType: String, Codable {
case national
case localOnly
}
// MARK: Constants
struct PhoneNumberConstants {
static let defaultCountry = "US"
static let defaultExtnPrefix = " ext. "
static let longPhoneNumber = "999999999999999"
static let minLengthForNSN = 2
static let maxInputStringLength = 250
static let maxLengthCountryCode = 3
static let maxLengthForNSN = 16
static let nonBreakingSpace = "\u{00a0}"
static let plusChars = "++"
static let pausesAndWaitsChars = ",;"
static let operatorChars = "*#"
static let validDigitsString = "0-90-9٠-٩۰-۹"
static let digitPlaceholder = "\u{2008}"
static let separatorBeforeNationalNumber = " "
}
struct PhoneNumberPatterns {
// MARK: Patterns
static let firstGroupPattern = "(\\$\\d)"
static let fgPattern = "\\$FG"
static let npPattern = "\\$NP"
static let allNormalizationMappings = ["0":"0", "1":"1", "2":"2", "3":"3", "4":"4", "5":"5", "6":"6", "7":"7", "8":"8", "9":"9", "٠":"0", "١":"1", "٢":"2", "٣":"3", "٤":"4", "٥":"5", "٦":"6", "٧":"7", "٨":"8", "٩":"9", "۰":"0", "۱":"1", "۲":"2", "۳":"3", "۴":"4", "۵":"5", "۶":"6", "۷":"7", "۸":"8", "۹":"9", "*":"*", "#":"#", ",":",", ";":";"]
static let capturingDigitPattern = "([0-90-9٠-٩۰-۹])"
static let extnPattern = "(?:;ext=([0-90-9٠-٩۰-۹]{1,7})|[ \\t,]*(?:e?xt(?:ensi(?:ó?|ó))?n?|e?xtn?|[,xxX##~~;]|int|anexo|int)[:\\..]?[ \\t,-]*([0-90-9٠-٩۰-۹]{1,7})#?|[- ]+([0-90-9٠-٩۰-۹]{1,5})#)$"
static let iddPattern = "^(?:\\+|%@)"
static let formatPattern = "^(?:%@)$"
static let characterClassPattern = "\\[([^\\[\\]])*\\]"
static let standaloneDigitPattern = "\\d(?=[^,}][^,}])"
static let nationalPrefixParsingPattern = "^(?:%@)"
static let prefixSeparatorPattern = "[- ]"
static let eligibleAsYouTypePattern = "^[-x‐-―−ー--/ ()()[].\\[\\]/~⁓∼~]*(\\$\\d[-x‐-―−ー--/ ()()[].\\[\\]/~⁓∼~]*)+$"
static let leadingPlusCharsPattern = "^[++]+"
static let secondNumberStartPattern = "[\\\\\\/] *x"
static let unwantedEndPattern = "[^0-90-9٠-٩۰-۹A-Za-z#]+$"
static let validStartPattern = "[++0-90-9٠-٩۰-۹]"
static let validPhoneNumberPattern = "^[0-90-9٠-٩۰-۹]{2}$|^[++]*(?:[-x\u{2010}-\u{2015}\u{2212}\u{30FC}\u{FF0D}-\u{FF0F} \u{00A0}\u{00AD}\u{200B}\u{2060}\u{3000}()\u{FF08}\u{FF09}\u{FF3B}\u{FF3D}.\\[\\]/~\u{2053}\u{223C}\u{FF5E}*]*[0-9\u{FF10}-\u{FF19}\u{0660}-\u{0669}\u{06F0}-\u{06F9}]){3,}[-x\u{2010}-\u{2015}\u{2212}\u{30FC}\u{FF0D}-\u{FF0F} \u{00A0}\u{00AD}\u{200B}\u{2060}\u{3000}()\u{FF08}\u{FF09}\u{FF3B}\u{FF3D}.\\[\\]/~\u{2053}\u{223C}\u{FF5E}*A-Za-z0-9\u{FF10}-\u{FF19}\u{0660}-\u{0669}\u{06F0}-\u{06F9}]*(?:(?:;ext=([0-90-9٠-٩۰-۹]{1,7})|[ \\t,]*(?:e?xt(?:ensi(?:ó?|ó))?n?|e?xtn?|[,xxX##~~;]|int|anexo|int)[:\\..]?[ \\t,-]*([0-90-9٠-٩۰-۹]{1,7})#?|[- ]+([0-90-9٠-٩۰-۹]{1,5})#)?$)?[,;]*$"
}
|
mit
|
48167fd94f6b31455db849a6e671e6c4
| 36.245161 | 704 | 0.626711 | 2.934926 | false | false | false | false |
junyuecao/Moi
|
Moi/ViewController.swift
|
3
|
6025
|
//
// ViewController.swift
// Moi
//
// Created by Eular on 15/7/26.
// Copyright © 2015年 Eular. All rights reserved.
//
import UIKit
import CoreLocation
import AVFoundation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var jumpImg: UIButton!
let locationManager:CLLocationManager = CLLocationManager()
var avPlayer: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.jumpImg.transform = CGAffineTransformMakeScale(0, 0)
let appFile = NSBundle.mainBundle().URLForResource("app", withExtension: "html")
let localRequest = NSURLRequest(URL: appFile!)
self.webView.loadRequest(localRequest)
self.webView.scalesPageToFit = false
self.webView.scrollView.scrollEnabled = false
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
// 获取地理位置
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location:CLLocation = locations[locations.count - 1]
if location.horizontalAccuracy > 0 {
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
self.locationManager.stopUpdatingLocation()
getWeatherData(latitude, lon: longitude)
// self.webView.stringByEvaluatingJavaScriptFromString("alert(1)")
}
}
func getWeatherData(lat: CLLocationDegrees, lon: CLLocationDegrees){
let yahoo_api = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.placefinder%20where%20text%3D%22\(lat)%2C\(lon)%22%20and%20gflags%20%3D%20%22R%22)%20and%20u=%22c%22&format=json&diagnostics="
NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: NSURL(string: yahoo_api)!), queue: NSOperationQueue(), completionHandler: {
(resp: NSURLResponse?, data: NSData?, err: NSError?) -> Void in
if let e = err {
print(e)
} else if let yahooData = data {
let yahooJson = try! NSJSONSerialization.JSONObjectWithData(yahooData, options: NSJSONReadingOptions.AllowFragments)
let channel = yahooJson.objectForKey("query")?.objectForKey("results")?.objectForKey("channel")
let location = channel?.objectForKey("location")
let wind = channel?.objectForKey("wind")
let condition = channel?.objectForKey("item")?.objectForKey("condition")
let city = location?.objectForKey("city")
let country = location?.objectForKey("country")
let w_direc = wind?.objectForKey("direction")
let w_speed = wind?.objectForKey("speed")
let humidity = channel?.objectForKey("atmosphere")?.objectForKey("humidity")
let temp = condition?.objectForKey("temp")
let weatherText = condition?.objectForKey("text")
// 在主线程操作
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self.webView.stringByEvaluatingJavaScriptFromString("setCity('\(city!)','\(country!)')")
self.webView.stringByEvaluatingJavaScriptFromString("setWeather('\(temp!)','\(weatherText!)','\(w_direc!)','\(w_speed!)','\(humidity!)')")
self.soundPlay(weatherText as! String)
})
}
})
}
func soundPlay(weatherText: String){
var condition: String?
let today:NSDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH" //“HH"大写强制24小时制
let hour = NSInteger(dateFormatter.stringFromDate(today))
if weatherText.hasSuffix("Rain") || weatherText.hasSuffix("Showers") {
condition = "rain"
}
else if weatherText.hasSuffix("Cloudy") || weatherText.hasSuffix("Fog"){
condition = "wind"
}
else if weatherText.hasSuffix("Thunderstorms"){
condition = "thunder"
}
else {
// ['Fair','Clear','Sunny'] or default
if hour > 19 || hour < 5 {
condition = "night"
}
else {
condition = "day"
}
}
if let cond = condition {
self.avPlayer = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound/sound_\(cond)", ofType: "mp3")!))
self.avPlayer.play()
}
}
override func viewDidAppear(animated: Bool) {
UIView.animateWithDuration(0.3, delay: 0.8, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.jumpImg.transform = CGAffineTransformScale(self.jumpImg.transform, 0.5, 0.5)
self.jumpImg.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
}, completion: {
_ in
UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.jumpImg.transform = CGAffineTransformScale(self.jumpImg.transform, 1, 1)
self.jumpImg.transform = CGAffineTransformRotate(self.jumpImg.transform, CGFloat(M_PI))
}, completion: nil)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
apache-2.0
|
c467f34499864138d66c59d220a0c401
| 41.728571 | 284 | 0.611668 | 5.065199 | false | false | false | false |
oddnetworks/odd-sample-apps
|
apple/tvos/tvOSTemplate/Odd tvOS Template/CollectionViewSectionHeader.swift
|
1
|
1332
|
//
// CollectionViewSectionHeader.swift
// Odd-iOS
//
// Created by Patrick McConnell on 10/20/15.
// Copyright © 2015 Patrick McConnell. All rights reserved.
//
import UIKit
// the resusable section header for the search results
// used to display the section title with an underline below
class CollectionViewSectionHeader: UICollectionReusableView {
var sectionTitleLabel = UILabel(frame: CGRect.zero)
var underlineView = UIView(frame: CGRect.zero)
// func canBecomeFocused() -> Bool {
// return false
// }
override func layoutSubviews() {
let frame = self.bounds
let rect = CGRect(x: 90, y: 0, width: frame.width, height: frame.height)
sectionTitleLabel.frame = rect
sectionTitleLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
sectionTitleLabel.textColor = .white
self.backgroundColor = .black
self.addSubview(sectionTitleLabel)
let underlineWidth = frame.width - 180 // 90 pixel safe zone on each side
let underlineOffset = sectionTitleLabel.frame.height
let underlineFrame = CGRect(x: 90, y: underlineOffset, width: underlineWidth, height: 1)
underlineView.frame = underlineFrame
underlineView.backgroundColor = .white
self.addSubview(underlineView)
self.bringSubview(toFront: underlineView)
}
}
|
apache-2.0
|
128333a659940d02a4a53694abc0fbbd
| 29.953488 | 92 | 0.727273 | 4.378289 | false | false | false | false |
omaralbeik/SwifterSwift
|
Sources/Extensions/CoreGraphics/CGPointExtensions.swift
|
1
|
5082
|
//
// CGPointExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 07/12/2016.
// Copyright © 2016 SwifterSwift
//
#if canImport(CoreGraphics)
import CoreGraphics
#if canImport(UIKit)
import UIKit
#endif
#if canImport(Cocoa)
import Cocoa
#endif
// MARK: - Methods
public extension CGPoint {
/// SwifterSwift: Distance from another CGPoint.
///
/// let point1 = CGPoint(x: 10, y: 10)
/// let point2 = CGPoint(x: 30, y: 30)
/// let distance = point1.distance(from: point2)
/// //distance = 28.28
///
/// - Parameter point: CGPoint to get distance from.
/// - Returns: Distance between self and given CGPoint.
public func distance(from point: CGPoint) -> CGFloat {
return CGPoint.distance(from: self, to: point)
}
/// SwifterSwift: Distance between two CGPoints.
///
/// let point1 = CGPoint(x: 10, y: 10)
/// let point2 = CGPoint(x: 30, y: 30)
/// let distance = CGPoint.distance(from: point2, to: point1)
/// //Distance = 28.28
///
/// - Parameters:
/// - point1: first CGPoint.
/// - point2: second CGPoint.
/// - Returns: distance between the two given CGPoints.
public static func distance(from point1: CGPoint, to point2: CGPoint) -> CGFloat {
// http://stackoverflow.com/questions/6416101/calculate-the-distance-between-two-cgpoints
return sqrt(pow(point2.x - point1.x, 2) + pow(point2.y - point1.y, 2))
}
}
// MARK: - Operators
public extension CGPoint {
/// SwifterSwift: Add two CGPoints.
///
/// let point1 = CGPoint(x: 10, y: 10)
/// let point2 = CGPoint(x: 30, y: 30)
/// let point = point1 + point2
/// //point = CGPoint(x: 40, y: 40)
///
/// - Parameters:
/// - lhs: CGPoint to add to.
/// - rhs: CGPoint to add.
/// - Returns: result of addition of the two given CGPoints.
public static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
/// SwifterSwift: Add a CGPoints to self.
///
/// let point1 = CGPoint(x: 10, y: 10)
/// let point2 = CGPoint(x: 30, y: 30)
/// point1 += point2
/// //point1 = CGPoint(x: 40, y: 40)
///
/// - Parameters:
/// - lhs: self
/// - rhs: CGPoint to add.
public static func += (lhs: inout CGPoint, rhs: CGPoint) {
// swiftlint:disable next shorthand_operator
lhs = lhs + rhs
}
/// SwifterSwift: Subtract two CGPoints.
///
/// let point1 = CGPoint(x: 10, y: 10)
/// let point2 = CGPoint(x: 30, y: 30)
/// let point = point1 - point2
/// //point = CGPoint(x: -20, y: -20)
///
/// - Parameters:
/// - lhs: CGPoint to subtract from.
/// - rhs: CGPoint to subtract.
/// - Returns: result of subtract of the two given CGPoints.
public static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
/// SwifterSwift: Subtract a CGPoints from self.
///
/// let point1 = CGPoint(x: 10, y: 10)
/// let point2 = CGPoint(x: 30, y: 30)
/// point1 -= point2
/// //point1 = CGPoint(x: -20, y: -20)
///
/// - Parameters:
/// - lhs: self
/// - rhs: CGPoint to subtract.
public static func -= (lhs: inout CGPoint, rhs: CGPoint) {
// swiftlint:disable next shorthand_operator
lhs = lhs - rhs
}
/// SwifterSwift: Multiply a CGPoint with a scalar
///
/// let point1 = CGPoint(x: 10, y: 10)
/// let scalar = point1 * 5
/// //scalar = CGPoint(x: 50, y: 50)
///
/// - Parameters:
/// - point: CGPoint to multiply.
/// - scalar: scalar value.
/// - Returns: result of multiplication of the given CGPoint with the scalar.
public static func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
/// SwifterSwift: Multiply self with a scalar
///
/// let point1 = CGPoint(x: 10, y: 10)
/// point *= 5
/// //point1 = CGPoint(x: 50, y: 50)
///
/// - Parameters:
/// - point: self.
/// - scalar: scalar value.
/// - Returns: result of multiplication of the given CGPoint with the scalar.
public static func *= (point: inout CGPoint, scalar: CGFloat) {
// swiftlint:disable next shorthand_operator
point = point * scalar
}
/// SwifterSwift: Multiply a CGPoint with a scalar
///
/// let point1 = CGPoint(x: 10, y: 10)
/// let scalar = 5 * point1
/// //scalar = CGPoint(x: 50, y: 50)
///
/// - Parameters:
/// - scalar: scalar value.
/// - point: CGPoint to multiply.
/// - Returns: result of multiplication of the given CGPoint with the scalar.
public static func * (scalar: CGFloat, point: CGPoint) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
}
#endif
|
mit
|
75a8a3d6ef7620f8208e49f545b2dd31
| 30.559006 | 97 | 0.557174 | 3.61637 | false | false | false | false |
dulingkang/Camera
|
SSCamera/SSCamera/SSCamera.swift
|
1
|
4289
|
//
// SSCamera.swift
// SSCamera
//
// Created by ShawnDu on 15/12/11.
// Copyright © 2015年 Shawn. All rights reserved.
//
import UIKit
import AVFoundation
class SSCamera: NSObject{
var session: AVCaptureSession!
var previewLayer: AVCaptureVideoPreviewLayer!
var captureDevice: AVCaptureDevice!
var stillImageOutput: AVCaptureStillImageOutput!
var input: AVCaptureDeviceInput!
var isUsingFront = true
var cameraPosition: AVCaptureDevicePosition {
get {
return input.device.position
}
set {
}
}
init(sessionPreset: String, position: AVCaptureDevicePosition) {
session = AVCaptureSession.init()
session.sessionPreset = sessionPreset
previewLayer = AVCaptureVideoPreviewLayer.init(session: session)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kCameraBottomHeight - kNavigationHeight)
if kScreenHeight == kIPhone4sHeight {
previewLayer.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kCameraBottom4SHeight - kNavigationHeight)
}
let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
for device in devices {
if device.position == position {
captureDevice = device as! AVCaptureDevice
}
}
do {
input = try AVCaptureDeviceInput.init(device: captureDevice)
if session.canAddInput(input) {
session.addInput(input)
}
} catch {
print("add video input error")
}
stillImageOutput = AVCaptureStillImageOutput.init()
let outputSettings = NSDictionary.init(object: AVVideoCodecJPEG, forKey: AVVideoCodecKey)
stillImageOutput.outputSettings = outputSettings as [NSObject : AnyObject]
if session.canAddOutput(stillImageOutput) {
session.addOutput(stillImageOutput)
}
session.startRunning()
}
//MARK: - public method
func takePhoto(complete: ((UIImage?) -> Void)) {
if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) {
stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: { (sampleBuffer, error) -> Void in
self.session.stopRunning()
if sampleBuffer != nil {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let image = UIImage.init(data: imageData)
complete(image)
} else if error != nil {
print("Take photo error", error)
}
})
}
}
func startCapture() {
if !session.running {
session.startRunning()
}
}
func stopCapture() {
if session.running {
session.stopRunning()
}
}
func switchCamera() {
var currentCameraPosition = self.cameraPosition
if currentCameraPosition == AVCaptureDevicePosition.Back {
currentCameraPosition = AVCaptureDevicePosition.Front
isUsingFront = true
} else {
currentCameraPosition = AVCaptureDevicePosition.Back
isUsingFront = false
}
let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
var afterSwitchCamera: AVCaptureDevice?
var newInput: AVCaptureDeviceInput?
for device in devices {
if device.position == currentCameraPosition {
afterSwitchCamera = device as? AVCaptureDevice
}
}
do {
newInput = try AVCaptureDeviceInput.init(device: afterSwitchCamera)
session.beginConfiguration()
session.removeInput(input)
if session.canAddInput(newInput) {
input = newInput
}
session.addInput(input)
session.commitConfiguration()
captureDevice = afterSwitchCamera
} catch {
print("add new input error when switch")
}
}
}
|
mit
|
f8ce0ca3b348f7b590db068237a2511f
| 33.845528 | 145 | 0.615492 | 6.053672 | false | false | false | false |
gcharita/XMLMapper
|
XMLMapper/Classes/XMLMapper.swift
|
1
|
15128
|
//
// XMLMapper.swift
// XMLMapper
//
// Created by Giorgos Charitakis on 14/09/2017.
//
//
import Foundation
public final class XMLMapper<N: XMLBaseMappable> {
// public var shouldIncludeNilValues = false /// If this is set to true, toXML output will include null values for any variables that are not set.
public init() {
}
// MARK: Mapping functions that map to an existing object toObject
/// Maps a XML object to an existing XMLMappable object if it is a XML dictionary, or returns the passed object as is
public func map(XMLObject: Any?, toObject object: N) -> N {
if let XML = XMLObject as? [String: Any] {
return map(XML: XML, toObject: object)
}
// failed to parse XML into dictionary form
// try to parse it as a String and then wrap it in an dictionary
if let string = XMLObject as? String {
let XML = [XMLParserConstant.Key.text: string]
return map(XML: XML, toObject: object)
}
return object
}
/// Map a XML string onto an existing object
public func map(XMLString: String, toObject object: N) -> N {
if let XML = XMLMapper.parseXMLStringIntoDictionary(XMLString: XMLString) {
return map(XML: XML, toObject: object)
}
return object
}
/// Maps a XML dictionary to an existing object that conforms to XMLMappable.
/// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
public func map(XML: [String: Any], toObject object: N) -> N {
var mutableObject = object
let map = XMLMap(mappingType: .fromXML, XML: XML, toObject: true)
mutableObject.mapping(with: map)
return mutableObject
}
//MARK: Mapping functions that create an object
/// Map a XML string to an object that conforms to XMLMappable
public func map(XMLString: String) -> N? {
if let XML = XMLMapper.parseXMLStringIntoDictionary(XMLString: XMLString) {
return map(XML: XML)
}
return nil
}
/// Maps a XML object to a XMLMappable object if it is a XML dictionary or String, or returns nil.
public func map(XMLObject: Any?) -> N? {
if let XML = XMLObject as? [String: Any] {
return map(XML: XML)
}
// failed to parse XML into dictionary form
// try to parse it as a String and then wrap it in an dictionary
if let string = XMLObject as? String {
let XML = [XMLParserConstant.Key.text: string]
return map(XML: XML)
}
return nil
}
/// Maps a XML dictionary to an object that conforms to XMLMappable
public func map(XML: [String: Any]) -> N? {
let map = XMLMap(mappingType: .fromXML, XML: XML)
if let klass = N.self as? XMLStaticMappable.Type { // Check if object is XMLStaticMappable
if var object = klass.objectForMapping(map: map) as? N {
object.mapping(with: map)
return object
}
} else if let klass = N.self as? XMLMappable.Type { // Check if object is XMLMappable
if var object = klass.init(map: map) as? N {
object.mapping(with: map)
return object
}
} else {
// Ensure XMLBaseMappable is not implemented directly
assert(false, "XMLBaseMappable should not be implemented directly. Please implement XMLMappable or XMLStaticMappable")
}
return nil
}
// MARK: Mapping functions for Arrays and Dictionaries
/// Maps a XML array to an object that conforms to XMLMappable
public func mapArray(XMLString: String) -> [N]? {
let parsedXML: Any? = XMLMapper.parseXMLString(XMLString: XMLString)
return mapArray(XMLObject: parsedXML)
}
/// Maps a XML object to an array of XMLMappable objects if it is an array of XML dictionary, or returns nil.
public func mapArray(XMLObject: Any?) -> [N]? {
if let XMLArray = XMLObject as? [Any] {
return mapArray(XMLArray: XMLArray)
}
// failed to parse XML into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(XMLObject: XMLObject) {
return [object]
}
return nil
}
/// Maps an array of XML dictionary to an array of XMLMappable objects
public func mapArray(XMLArray: [Any]) -> [N] {
// map every element in XML array to type N
let result = XMLArray.compactMap(map)
return result
}
/// Maps a XML object to a dictionary of XMLMappable objects if it is a XML dictionary of dictionaries, or returns nil.
public func mapDictionary(XMLString: String) -> [String: N]? {
let parsedXML: Any? = XMLMapper.parseXMLString(XMLString: XMLString)
return mapDictionary(XMLObject: parsedXML)
}
/// Maps a XML object to a dictionary of XMLMappable objects if it is a XML dictionary of dictionaries, or returns nil.
public func mapDictionary(XMLObject: Any?) -> [String: N]? {
if let XML = (XMLObject as? [String: Any])?.childNodes {
return mapDictionary(XML: XML)
}
return nil
}
/// Maps a XML dictionary of dictionaries to a dictionary of XMLMappable objects
public func mapDictionary(XML: [String: Any]) -> [String: N]? {
// map every value in dictionary to type N
let result = XML.filterMap(map)
if !result.isEmpty {
return result
}
return nil
}
/// Maps a XML object to a dictionary of XMLMappable objects if it is a XML dictionary of dictionaries, or returns nil.
public func mapDictionary(XMLObject: Any?, toDictionary dictionary: [String: N]) -> [String: N] {
if let XML = (XMLObject as? [String: Any])?.childNodes {
return mapDictionary(XML: XML, toDictionary: dictionary)
}
return dictionary
}
/// Maps a XML dictionary of dictionaries to an existing dictionary of XMLMappable objects
public func mapDictionary(XML: [String: Any], toDictionary dictionary: [String: N]) -> [String: N] {
var mutableDictionary = dictionary
for (key, value) in XML {
if let object = dictionary[key] {
_ = map(XMLObject: value, toObject: object)
} else {
mutableDictionary[key] = map(XMLObject: value)
}
}
return mutableDictionary
}
/// Maps a XML object to a dictionary of arrays of XMLMappable objects
public func mapDictionaryOfArrays(XMLObject: Any?) -> [String: [N]]? {
if let XML = (XMLObject as? [String: Any])?.childNodes as? [String: [Any]] {
return mapDictionaryOfArrays(XML: XML)
}
// failed to parse XML into dictionary of arrays form
// try to parse it into a dictionary of dictionaries and then wrap the values in an array
if let dictionary = mapDictionary(XMLObject: XMLObject) {
return dictionary.mapValues({ [$0] })
}
return nil
}
///Maps a XML dictionary of arrays to a dictionary of arrays of XMLMappable objects
public func mapDictionaryOfArrays(XML: [String: [Any]]) -> [String: [N]]? {
// map every value in dictionary to type N
let result = XML.filterMap {
mapArray(XMLArray: $0)
}
if !result.isEmpty {
return result
}
return nil
}
/// Maps an 2 dimentional array of XML dictionaries to a 2 dimentional array of XMLMappable objects
public func mapArrayOfArrays(XMLObject: Any?) -> [[N]]? {
if let XMLArray = XMLObject as? [[[String: Any]]] {
let objectArray = XMLArray.map { innerXMLArray in
return mapArray(XMLArray: innerXMLArray)
}
if !objectArray.isEmpty {
return objectArray
}
}
return nil
}
// MARK: Utility functions for converting strings to XML objects
/// Convert a XML String into a Dictionary<String, Any> using XMLSerialization
public static func parseXMLStringIntoDictionary(XMLString: String) -> [String: Any]? {
let parsedXML: Any? = XMLMapper.parseXMLString(XMLString: XMLString)
return parsedXML as? [String: Any]
}
/// Convert a XML String into an Object using XMLSerialization
public static func parseXMLString(XMLString: String) -> Any? {
var parsedXML: Any?
do {
parsedXML = try XMLSerialization.xmlObject(withString: XMLString)
} catch let error {
print(error)
parsedXML = nil
}
return parsedXML
}
}
extension XMLMapper {
// MARK: Functions that create model from XML file
/// XML file to XMLMappable object
/// - parameter XMLfile: Filename
/// - Returns: XMLMappable object
public func map(XMLfile: String) -> N? {
if let path = Bundle.main.path(forResource: XMLfile, ofType: nil) {
do {
let XMLString = try String(contentsOfFile: path)
do {
return self.map(XMLString: XMLString)
}
} catch {
return nil
}
}
return nil
}
/// XML file to XMLMappable object array
/// - parameter XMLfile: Filename
/// - Returns: XMLMappable object array
public func mapArray(XMLfile: String) -> [N]? {
if let path = Bundle.main.path(forResource: XMLfile, ofType: nil) {
do {
let XMLString = try String(contentsOfFile: path)
do {
return self.mapArray(XMLString: XMLString)
}
} catch {
return nil
}
}
return nil
}
}
extension XMLMapper {
// MARK: Functions that create XML from objects
///Maps an object that conforms to XMLMappable to a XML dictionary <String, Any>
public func toXML(_ object: N) -> [String: Any] {
var mutableObject = object
let map = XMLMap(mappingType: .toXML, XML: [:])
mutableObject.mapping(with: map)
return map.XML
}
///Maps an array of Objects to an array of XML dictionaries [[String: Any]]
public func toXMLArray(_ array: [N]) -> [[String: Any]] {
return array.map {
// convert every element in array to XML dictionary equivalent
self.toXML($0)
}
}
///Maps a dictionary of Objects that conform to XMLMappable to a XML dictionary of dictionaries.
public func toXMLDictionary(_ dictionary: [String: N]) -> [String: [String: Any]] {
return dictionary.map { (arg: (key: String, value: N)) in
// convert every value in dictionary to its XML dictionary equivalent
return (arg.key, self.toXML(arg.value))
}
}
///Maps a dictionary of Objects that conform to XMLMappable to a XML dictionary of dictionaries.
public func toXMLDictionaryOfArrays(_ dictionary: [String: [N]]) -> [String: [[String: Any]]] {
return dictionary.map { (arg: (key: String, value: [N])) in
// convert every value (array) in dictionary to its XML dictionary equivalent
return (arg.key, self.toXMLArray(arg.value))
}
}
/// Maps an Object to a XML string with option of pretty formatting
public func toXMLString(_ object: N) -> String? {
let XMLDict = toXML(object)
return XMLMapper.toXMLString(XMLDict as Any)
}
/// Maps an array of Objects to a XML string with option of pretty formatting
public func toXMLString(_ array: [N]) -> String? {
let XMLDict = toXMLArray(array)
return XMLMapper.toXMLString(XMLDict as Any)
}
/// Converts an Object to a XML string with option of pretty formatting
public static func toXMLString(_ XMLObject: Any) -> String? {
if let xmlRepresentable = XMLObject as? XMLRepresentable {
return xmlRepresentable.xmlString
}
return nil
}
}
extension XMLMapper where N: Hashable {
/// Maps a XML array to an object that conforms to XMLMappable
public func mapSet(XMLString: String) -> Set<N>? {
let parsedXML: Any? = XMLMapper.parseXMLString(XMLString: XMLString)
if let objectArray = mapArray(XMLObject: parsedXML) {
return Set(objectArray)
}
return nil
}
/// Maps a XML object to an Set of XMLMappable objects if it is an array of XML dictionary, or returns nil.
public func mapSet(XMLObject: Any?) -> Set<N>? {
if let XMLArray = XMLObject as? [Any] {
return mapSet(XMLArray: XMLArray)
}
// failed to parse XML into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(XMLObject: XMLObject) {
return Set([object])
}
return nil
}
/// Maps an Set of XML dictionary to an array of XMLMappable objects
public func mapSet(XMLArray: [Any]) -> Set<N> {
// map every element in XML array to type N
return Set(XMLArray.compactMap(map))
}
///Maps a Set of Objects to a Set of XML dictionaries [[String : Any]]
public func toXMLSet(_ set: Set<N>) -> [[String: Any]] {
return set.map {
// convert every element in set to XML dictionary equivalent
self.toXML($0)
}
}
/// Maps a set of Objects to a XML string with option of pretty formatting
public func toXMLString(_ set: Set<N>) -> String? {
let XMLDict = toXMLSet(set)
return XMLMapper.toXMLString(XMLDict as Any)
}
}
extension Dictionary {
internal func map<K, V>(_ f: (Element) throws -> (K, V)) rethrows -> [K: V] {
var mapped = [K: V]()
for element in self {
let newElement = try f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func map<K, V>(_ f: (Element) throws -> (K, [V])) rethrows -> [K: [V]] {
var mapped = [K: [V]]()
for element in self {
let newElement = try f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func filterMap<U>(_ f: (Value) throws -> U?) rethrows -> [Key: U] {
var mapped = [Key: U]()
for (key, value) in self {
if let newValue = try f(value) {
mapped[key] = newValue
}
}
return mapped
}
}
|
mit
|
6abbe71a017c9e63e121f9eb35dbfbfc
| 34.181395 | 149 | 0.586132 | 4.582854 | false | false | false | false |
gregomni/swift
|
test/Generics/sr14510.swift
|
2
|
1560
|
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on
// RUN: %target-swift-frontend -debug-generic-signatures -typecheck %s -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s
// CHECK-LABEL: Requirement signature: <Self where Self == Self.[Adjoint]Dual.[Adjoint]Dual, Self.[Adjoint]Dual : Adjoint>
public protocol Adjoint {
associatedtype Dual: Adjoint where Self.Dual.Dual == Self
}
// CHECK-LABEL: Requirement signature: <Self>
public protocol Diffable {
associatedtype Patch
}
// CHECK-LABEL: Requirement signature: <Self where Self : Adjoint, Self : Diffable, Self.[Adjoint]Dual : AdjointDiffable, Self.[Diffable]Patch : Adjoint, Self.[Adjoint]Dual.[Diffable]Patch == Self.[Diffable]Patch.[Adjoint]Dual>
public protocol AdjointDiffable: Adjoint & Diffable
where Self.Patch: Adjoint, Self.Dual: AdjointDiffable,
Self.Patch.Dual == Self.Dual.Patch {
}
// This is another example used to hit the same problem. Any one of the three
// conformance requirements 'A : P', 'B : P' or 'C : P' can be dropped and
// proven from the other two, but dropping two or more conformance requirements
// leaves us with an invalid signature.
// CHECK-LABEL: Requirement signature: <Self where Self.[P]A : P, Self.[P]A == Self.[P]B.[P]C, Self.[P]B : P, Self.[P]B == Self.[P]A.[P]C, Self.[P]C == Self.[P]A.[P]B>
protocol P {
associatedtype A : P where A == B.C
associatedtype B : P where B == A.C
associatedtype C : P where C == A.B
// expected-warning@-1 {{redundant conformance constraint 'Self.C' : 'P'}}
}
|
apache-2.0
|
5c6ba0a5c15f23504bda2da0e7dcf469
| 49.322581 | 227 | 0.716026 | 3.421053 | false | false | false | false |
gregomni/swift
|
test/stdlib/POSIX.swift
|
9
|
6713
|
// RUN: %target-run-simple-swift %t
// REQUIRES: executable_test
// UNSUPPORTED: OS=windows-msvc
// UNSUPPORTED: OS=wasi
import StdlibUnittest
import SwiftPrivateLibcExtras
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#else
#error("Unsupported platform")
#endif
chdir(CommandLine.arguments[1])
var POSIXTests = TestSuite("POSIXTests")
let semaphoreName = "TestSem"
#if os(Android)
// In Android, the cwd is the root directory, which is not writable.
let fn: String = {
let capacity = Int(PATH_MAX)
let resolvedPath = UnsafeMutablePointer<Int8>.allocate(capacity: capacity)
resolvedPath.initialize(repeating: 0, count: capacity)
defer {
resolvedPath.deinitialize(count: capacity)
resolvedPath.deallocate()
}
guard let _ = realpath("/proc/self/exe", resolvedPath) else {
fatalError("Couldn't obtain executable path")
}
let length = strlen(resolvedPath)
precondition(length != 0, "Couldn't obtain valid executable path")
// Search backwards for the last /, and turn it into a null byte.
for idx in stride(from: length-1, through: 0, by: -1) {
if Unicode.Scalar(UInt8(resolvedPath[idx])) == Unicode.Scalar("/") {
resolvedPath[idx] = 0
break
}
precondition(idx != 0, "Couldn't obtain valid executable directory")
}
return String(cString: resolvedPath) + "/test.txt"
}()
#else
let fn = "test.txt"
#endif
POSIXTests.setUp {
sem_unlink(semaphoreName)
unlink(fn)
}
// Failed semaphore creation.
#if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS
POSIXTests.test("sem_open fail") {
let sem = sem_open(semaphoreName, 0)
expectEqual(SEM_FAILED, sem)
expectEqual(ENOENT, errno)
}
#endif
// Successful semaphore creation.
#if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS
POSIXTests.test("sem_open success") {
let sem = sem_open(semaphoreName, O_CREAT, 0o777, 1)
expectNotEqual(SEM_FAILED, sem)
let res = sem_close(sem!)
expectEqual(0, res)
let res2 = sem_unlink(semaphoreName)
expectEqual(0, res2)
}
#endif
// Successful semaphore creation with O_EXCL.
#if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS
POSIXTests.test("sem_open O_EXCL success") {
let sem = sem_open(semaphoreName, O_CREAT | O_EXCL, 0o777, 1)
expectNotEqual(SEM_FAILED, sem)
let res = sem_close(sem!)
expectEqual(0, res)
let res2 = sem_unlink(semaphoreName)
expectEqual(0, res2)
}
#endif
// Successful creation and re-obtaining of existing semaphore.
#if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS
POSIXTests.test("sem_open existing") {
let sem = sem_open(semaphoreName, O_CREAT, 0o777, 1)
expectNotEqual(SEM_FAILED, sem)
let sem2 = sem_open(semaphoreName, 0)
// Here, we'd like to test that the semaphores are the same, but it's quite
// difficult.
expectNotEqual(SEM_FAILED, sem2)
let res = sem_close(sem!)
expectEqual(0, res)
let res2 = sem_unlink(semaphoreName)
expectEqual(0, res2)
}
#endif
// Fail because the semaphore already exists.
#if !os(Android) // Android doesn’t implement sem_open and always return ENOSYS
POSIXTests.test("sem_open existing O_EXCL fail") {
let sem = sem_open(semaphoreName, O_CREAT, 0o777, 1)
expectNotEqual(SEM_FAILED, sem)
let sem2 = sem_open(semaphoreName, O_CREAT | O_EXCL, 0o777, 1)
expectEqual(SEM_FAILED, sem2)
expectEqual(EEXIST, errno)
let res = sem_close(sem!)
expectEqual(0, res)
let res2 = sem_unlink(semaphoreName)
expectEqual(0, res2)
}
#endif
// Fail because the file descriptor is invalid.
POSIXTests.test("ioctl(CInt, UInt, CInt): fail") {
let fd = open(fn, 0)
expectEqual(-1, fd)
expectEqual(ENOENT, errno)
// A simple check to verify that ioctl is available
let _ = ioctl(fd, 0, 0)
expectEqual(EBADF, errno)
}
#if os(Linux) || os(Android)
// Successful creation of a socket and listing interfaces
POSIXTests.test("ioctl(CInt, UInt, UnsafeMutableRawPointer): listing interfaces success") {
// Create a socket
let sock = socket(PF_INET, 1, 0)
expectGT(Int(sock), 0)
// List interfaces
var ic = ifconf()
let io = ioctl(sock, UInt(SIOCGIFCONF), &ic);
expectGE(io, 0)
//Cleanup
let res = close(sock)
expectEqual(0, res)
}
#endif
// Fail because file doesn't exist.
POSIXTests.test("fcntl(CInt, CInt): fail") {
let fd = open(fn, 0)
expectEqual(-1, fd)
expectEqual(ENOENT, errno)
let _ = fcntl(fd, F_GETFL)
expectEqual(EBADF, errno)
}
// Change modes on existing file.
POSIXTests.test("fcntl(CInt, CInt): F_GETFL/F_SETFL success with file") {
// Create and open file.
let fd = open(fn, O_CREAT, 0o666)
expectGT(Int(fd), 0)
var flags = fcntl(fd, F_GETFL)
expectGE(Int(flags), 0)
// Change to APPEND mode...
var rc = fcntl(fd, F_SETFL, O_APPEND)
expectEqual(0, rc)
flags = fcntl(fd, F_GETFL)
expectEqual(flags | O_APPEND, flags)
// Change back...
rc = fcntl(fd, F_SETFL, 0)
expectEqual(0, rc)
flags = fcntl(fd, F_GETFL)
expectGE(Int(flags), 0)
// Clean up...
rc = close(fd)
expectEqual(0, rc)
rc = unlink(fn)
expectEqual(0, rc)
}
POSIXTests.test("fcntl(CInt, CInt, CInt): block and unblocking sockets success") {
// Create socket, note: socket created by default in blocking mode...
let sock = socket(PF_INET, 1, 0)
expectGT(Int(sock), 0)
var flags = fcntl(sock, F_GETFL)
expectGE(Int(flags), 0)
// Change mode of socket to non-blocking...
var rc = fcntl(sock, F_SETFL, flags | O_NONBLOCK)
expectEqual(0, rc)
flags = fcntl(sock, F_GETFL)
expectEqual((flags | O_NONBLOCK), flags)
// Change back to blocking...
rc = fcntl(sock, F_SETFL, flags & ~O_NONBLOCK)
expectEqual(0, rc)
flags = fcntl(sock, F_GETFL)
expectGE(Int(flags), 0)
// Clean up...
rc = close(sock)
expectEqual(0, rc)
}
POSIXTests.test("fcntl(CInt, CInt, UnsafeMutableRawPointer): locking and unlocking success") {
// Create the file and add data to it...
var fd = open(fn, O_CREAT | O_WRONLY, 0o666)
expectGT(Int(fd), 0)
let data = "Testing 1 2 3"
let bytesWritten = write(fd, data, data.utf8.count)
expectEqual(data.utf8.count, bytesWritten)
var rc = close(fd)
expectEqual(0, rc)
// Re-open the file...
fd = open(fn, 0)
expectGT(Int(fd), 0)
// Lock for reading...
var flck = flock()
flck.l_type = Int16(F_RDLCK)
flck.l_len = off_t(data.utf8.count)
rc = fcntl(fd, F_SETLK, &flck)
expectEqual(0, rc)
// Unlock for reading...
flck = flock()
flck.l_type = Int16(F_UNLCK)
rc = fcntl(fd, F_SETLK, &flck)
expectEqual(0, rc)
// Clean up...
rc = close(fd)
expectEqual(0, rc)
rc = unlink(fn)
expectEqual(0, rc)
}
runAllTests()
|
apache-2.0
|
528514932b8bb171b1b947ed94b0c097
| 24.104869 | 94 | 0.684022 | 3.30849 | false | true | false | false |
Liujlai/DouYuD
|
DYTV/DYTV/FunnyViewController.swift
|
1
|
1118
|
//
// FunnyViewController.swift
// DYTV
//
// Created by idea on 2017/8/22.
// Copyright © 2017年 idea. All rights reserved.
//
import UIKit
private let kTopmargin: CGFloat = 8
class FunnyViewController: BaseAnchorViewController {
//MARK: -懒加载ViewModel对象
fileprivate lazy var funnyVM : FunnyViewModel = FunnyViewModel()
}
extension FunnyViewController{
override func setupUI() {
super.setupUI()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
// 将hearder设置为0
layout.headerReferenceSize = CGSize.zero
// 设置顶部间距
collectionView.contentInset = UIEdgeInsets(top: kTopmargin, left: 0, bottom: 0, right: 0)
}
}
extension FunnyViewController{
override func loadData() {
//1.给父类中的ViewModel进行赋值
baseVm = funnyVM
//2.请求数据
funnyVM.loadFunnyData {
self.collectionView.reloadData()
// 3.数据请求完成
self.loadDataFinished()
}
}
}
|
mit
|
9f735c716e79b0a8186680a2ea3fe5af
| 20.367347 | 97 | 0.625597 | 4.695067 | false | false | false | false |
DavidSkrundz/CGI
|
Sources/CGI/Method.swift
|
1
|
1450
|
//
// Method.swift
// CGI
//
public enum Method {
case Get
case Post
case Put
case Patch
case Delete
case Copy
case Head
case Options
case Link
case Unlink
case Purge
case Lock
case Unlock
case Propfind
case View
public init?(_ string: String) {
switch string.uppercased() {
case "GET": self = .Get
case "POST": self = .Post
case "PUT": self = .Put
case "PATCH": self = .Patch
case "DELETE": self = .Delete
case "COPY": self = .Copy
case "HEAD": self = .Head
case "OPTIONS": self = .Options
case "LINK": self = .Link
case "UNLINK": self = .Unlink
case "PURGE": self = .Purge
case "LOCK": self = .Lock
case "UNLOCK": self = .Unlock
case "PROPFIND": self = .Propfind
case "VIEW": self = .View
default: return nil
}
}
}
extension Method: CustomStringConvertible {
public var description: String {
switch self {
case .Get: return "GET"
case .Post: return "POST"
case .Put: return "PUT"
case .Patch: return "PATCH"
case .Delete: return "DELETE"
case .Copy: return "COPY"
case .Head: return "HEAD"
case .Options: return "OPTIONS"
case .Link: return "LINK"
case .Unlink: return "UNLINK"
case .Purge: return "PURGE"
case .Lock: return "LOCK"
case .Unlock: return "UNLOCK"
case .Propfind: return "PROPFIND"
case .View: return "VIEW"
}
}
}
|
lgpl-3.0
|
4f934bbb424ff336eab09c6356dd1fce
| 21.307692 | 43 | 0.592414 | 3.052632 | false | false | false | false |
joseph-zhong/CommuterBuddy-iOS
|
SwiftSideMenu/Utility/BlockButton.swift
|
4
|
3334
|
//
// BlockButton.swift
//
//
// Created by Cem Olcay on 12/08/15.
//
//
import UIKit
public typealias BlockButtonAction = (_ sender: BlockButton) -> Void
///Make sure you use "[weak self] (sender) in" if you are using the keyword self inside the closure or there might be a memory leak
open class BlockButton: UIButton {
// MARK: Propeties
open var highlightLayer: CALayer?
open var action: BlockButtonAction?
// MARK: Init
public init() {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
defaultInit()
}
public init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
super.init(frame: CGRect(x: x, y: y, width: w, height: h))
defaultInit()
}
public init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, action: BlockButtonAction?) {
super.init (frame: CGRect(x: x, y: y, width: w, height: h))
self.action = action
defaultInit()
}
public init(action: @escaping BlockButtonAction) {
super.init(frame: CGRect.zero)
self.action = action
defaultInit()
}
public override init(frame: CGRect) {
super.init(frame: frame)
defaultInit()
}
public init(frame: CGRect, action: @escaping BlockButtonAction) {
super.init(frame: frame)
self.action = action
defaultInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func defaultInit() {
addTarget(self, action: #selector(BlockButton.didPressed(_:)), for: UIControlEvents.touchUpInside)
addTarget(self, action: #selector(BlockButton.highlight), for: [UIControlEvents.touchDown, UIControlEvents.touchDragEnter])
addTarget(self, action: #selector(BlockButton.unhighlight), for: [
UIControlEvents.touchUpInside,
UIControlEvents.touchUpOutside,
UIControlEvents.touchCancel,
UIControlEvents.touchDragExit
])
setTitleColor(.black, for: .normal)
setTitleColor(.blue, for: .selected)
}
open func addAction(_ action: @escaping BlockButtonAction) {
self.action = action
}
// MARK: Action
open func didPressed(_ sender: BlockButton) {
action?(sender)
}
// MARK: Highlight
open func highlight() {
if action == nil {
return
}
let highlightLayer = CALayer()
highlightLayer.frame = layer.bounds
highlightLayer.backgroundColor = UIColor.black.cgColor
highlightLayer.opacity = 0.5
var maskImage: UIImage? = nil
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, false, 0)
if let context = UIGraphicsGetCurrentContext() {
layer.render(in: context)
maskImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
let maskLayer = CALayer()
maskLayer.contents = maskImage?.cgImage
maskLayer.frame = highlightLayer.frame
highlightLayer.mask = maskLayer
layer.addSublayer(highlightLayer)
self.highlightLayer = highlightLayer
}
open func unhighlight() {
if action == nil {
return
}
highlightLayer?.removeFromSuperlayer()
highlightLayer = nil
}
}
|
mit
|
0c848256ffb04375b956041ef5f1d480
| 28.504425 | 132 | 0.625975 | 4.592287 | false | false | false | false |
hyperoslo/CalendarKit
|
Source/Header/DaySelector/DaySelectorController.swift
|
1
|
1215
|
import UIKit
public final class DaySelectorController: UIViewController {
public private(set) lazy var daySelector = DaySelector()
public var delegate: DaySelectorDelegate? {
get {
return daySelector.delegate
}
set {
daySelector.delegate = newValue
}
}
public var calendar: Calendar {
get {
return daySelector.calendar
}
set(newValue) {
daySelector.calendar = newValue
}
}
public var startDate: Date {
get {
return daySelector.startDate!
}
set {
daySelector.startDate = newValue
}
}
public var selectedIndex: Int {
get {
return daySelector.selectedIndex
}
set {
daySelector.selectedIndex = newValue
}
}
public var selectedDate: Date? {
get {
return daySelector.selectedDate
}
set {
daySelector.selectedDate = newValue
}
}
override public func loadView() {
view = daySelector
}
func transitionToHorizontalSizeClass(_ sizeClass: UIUserInterfaceSizeClass) {
daySelector.transitionToHorizontalSizeClass(sizeClass)
}
public func updateStyle(_ newStyle: DaySelectorStyle) {
daySelector.updateStyle(newStyle)
}
}
|
mit
|
587f876057ef5cb0d08315977808bb59
| 18.596774 | 79 | 0.654321 | 4.709302 | false | false | false | false |
mnin/on_ruby_ios
|
onruby/User.swift
|
1
|
3348
|
//
// User.swift
// onruby
//
// Created by Martin Wilhelmi on 25.09.14.
//
import Foundation
class User {
let id: Int
let available, freelancer: Bool?
let imageURL, name, nickname: String
let github, twitter, url: String?
var image: UIImage?
init(id: Int, available: Bool?, freelancer: Bool?, github: String?, imageURL: String, name: String, nickname: String, twitter: String?, url: String?) {
self.id = id
self.available = available
self.freelancer = freelancer
self.github = github
self.imageURL = imageURL
self.name = name
self.nickname = nickname
self.twitter = twitter
self.url = url
}
func availableDescription() -> String {
if self.available != nil {
return self.available == true ? "Yes" : "No"
} else {
return "Unkown"
}
}
func freelancerDescription() -> String {
if self.freelancer != nil {
return self.freelancer == true ? "Yes" : "No"
} else {
return "Unkown"
}
}
class func loadFromJsonArray(participants: NSArray) -> [User] {
var userArray = [User]()
var user_id: Int
var user: User?
for participant in participants {
user_id = participant.objectForKey("user_id") as Int
user = User.find(user_id)?
if user != nil {
userArray.append(user!)
}
}
return userArray
}
class func find(id: Int) -> User? {
return UserGroup.current().allUserDictionary()[id]
}
class func loadUsersFromJSONDictionary(usersJsonDictionary: NSArray) -> Dictionary<Int, User> {
var userDictionary = Dictionary<Int, User>()
var id: Int
var available, freelancer: Bool?
var github, twitter, url: String?
var imageURL, name, nickname: String
for userJsonDictionary in usersJsonDictionary {
id = userJsonDictionary["id"] as Int
imageURL = userJsonDictionary["image"] as String
name = userJsonDictionary["name"] as String
nickname = userJsonDictionary["nickname"] as String
available = (userJsonDictionary["available"] == nil || userJsonDictionary["available"] is NSNull) ? nil : (userJsonDictionary["available"]! as Bool)
freelancer = (userJsonDictionary["freelancer"] == nil || userJsonDictionary["freelancer"] is NSNull) ? nil : (userJsonDictionary["freelancer"]! as Bool)
github = (userJsonDictionary["github"] == nil || userJsonDictionary["github"] is NSNull) ? nil : (userJsonDictionary["github"]! as String)
twitter = (userJsonDictionary["twitter"] == nil || userJsonDictionary["twitter"] is NSNull) ? nil : (userJsonDictionary["twitter"]! as String)
url = (userJsonDictionary["url"] == nil || userJsonDictionary["url"] is NSNull) ? nil : (userJsonDictionary["url"]! as String)
userDictionary[id] = User(id: id, available: available, freelancer: freelancer, github: github, imageURL: imageURL, name: name, nickname: nickname, twitter: twitter, url: url)
}
return userDictionary
}
}
|
gpl-3.0
|
9a0fcb32915fde831d81b50a167bee47
| 37.045455 | 187 | 0.583632 | 4.336788 | false | false | false | false |
HaloWang/WCQuick
|
WCQuick/UILabel+WCQ.swift
|
1
|
1390
|
//
// UILabel+WCQ.swift
// SuperGina
//
// Created by 王策 on 15/6/17.
// Copyright (c) 2015年 Anve. All rights reserved.
//
import UIKit
public extension UILabel {
public func text(text : String?) -> Self {
self.text = text
return self
}
public func textColor(color : UIColor) -> Self {
self.textColor = color
return self
}
public func numberOfLines(numberOfLines : Int) -> Self {
self.numberOfLines = numberOfLines
return self
}
public func font(font : UIFont) -> Self {
self.font = font
return self
}
public func textAlignment(textAlignment : NSTextAlignment) -> Self {
self.textAlignment = textAlignment
return self
}
public func text(text : String, textColor : UIColor) -> Self {
return self.text(text).textColor(textColor)
}
/// 获取该label展示当前文字所需最小size,当没有文字时,返回宽度为0,高度为font。lineHeight的size
public var displaySize: CGSize {
if let text = text {
return (text as NSString).boundingRectWithSize(CGSize(width: Double(MAXFLOAT), height: Double(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:font], context: nil).size
} else {
return CGSize(width: 0, height: font.lineHeight)
}
}
public func font(#systemFontOfSize:CGFloat) -> Self {
return font(UIFont.systemFontOfSize(systemFontOfSize))
}
}
|
mit
|
f15723500ee61a69953a0c0474ef10e6
| 23 | 223 | 0.712879 | 3.548387 | false | false | false | false |
hulab/ClusterKit
|
Examples/Example-swift/MapboxViewController.swift
|
1
|
6342
|
// MapboxViewController.swift
//
// Copyright © 2017 Hulab. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Mapbox
import ClusterKit
import ExampleData
class MapboxViewController: UIViewController, MGLMapViewDelegate {
@IBOutlet weak var mapView: MGLMapView!
override func viewDidLoad() {
super.viewDidLoad()
let algorithm = CKNonHierarchicalDistanceBasedAlgorithm()
algorithm.cellSize = 200
mapView.clusterManager.algorithm = algorithm
mapView.clusterManager.marginFactor = 1
let paris = CLLocationCoordinate2D(latitude: 48.853, longitude: 2.35)
mapView.setCenter(paris, animated: false)
loadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadData() {
let operation = CKGeoPointOperation()
operation.setCompletionBlockWithSuccess({ (_, points) in
self.mapView.clusterManager.annotations = points
})
operation.start()
}
// MARK: MGLMapViewDelegate
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
guard let cluster = annotation as? CKCluster else {
return nil
}
if cluster.count > 1 {
return mapView.dequeueReusableAnnotationView(withIdentifier: CKMapViewDefaultClusterAnnotationViewReuseIdentifier) ??
MBXClusterView(annotation: annotation, reuseIdentifier: CKMapViewDefaultClusterAnnotationViewReuseIdentifier)
}
return mapView.dequeueReusableAnnotationView(withIdentifier: CKMapViewDefaultAnnotationViewReuseIdentifier) ??
MBXAnnotationView(annotation: annotation, reuseIdentifier: CKMapViewDefaultAnnotationViewReuseIdentifier)
}
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
guard let cluster = annotation as? CKCluster else {
return true
}
return cluster.count == 1
}
// MARK: - How To Update Clusters
func mapView(_ mapView: MGLMapView, regionDidChangeAnimated animated: Bool) {
mapView.clusterManager.updateClustersIfNeeded()
}
// MARK: - How To Handle Selection/Deselection
func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {
guard let cluster = annotation as? CKCluster else {
return
}
if cluster.count > 1 {
let edgePadding = UIEdgeInsets.init(top: 40, left: 20, bottom: 44, right: 20)
let camera = mapView.cameraThatFitsCluster(cluster, edgePadding: edgePadding)
mapView.setCamera(camera, animated: true)
} else if let annotation = cluster.firstAnnotation {
mapView.clusterManager.selectAnnotation(annotation, animated: false);
}
}
func mapView(_ mapView: MGLMapView, didDeselect annotation: MGLAnnotation) {
guard let cluster = annotation as? CKCluster, cluster.count == 1 else {
return
}
mapView.clusterManager.deselectAnnotation(cluster.firstAnnotation, animated: false);
}
}
// MARK: - Custom annotation view
class MBXAnnotationView: MGLAnnotationView {
var imageView: UIImageView!
override init(annotation: MGLAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
let image = UIImage(named: "marker")
imageView = UIImageView(image: image)
addSubview(imageView)
frame = imageView.frame
isDraggable = true
centerOffset = CGVector(dx: 0.5, dy: 1)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Not implemented")
}
override func setDragState(_ dragState: MGLAnnotationViewDragState, animated: Bool) {
super.setDragState(dragState, animated: animated)
switch dragState {
case .starting:
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.5, options: [.curveLinear], animations: {
self.transform = self.transform.scaledBy(x: 2, y: 2)
})
case .ending:
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.5, options: [.curveLinear], animations: {
self.transform = CGAffineTransform.identity
})
default:
break
}
}
}
class MBXClusterView: MGLAnnotationView {
var imageView: UIImageView!
override init(annotation: MGLAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
let image = UIImage(named: "cluster")
imageView = UIImageView(image: image)
addSubview(imageView)
frame = imageView.frame
centerOffset = CGVector(dx: 0.5, dy: 1)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Not implemented")
}
}
|
mit
|
af608092529d37dbe767d5afef5758bd
| 34.623596 | 151 | 0.664249 | 5.223229 | false | false | false | false |
AnarchoApp/Anarcho-Cocoa
|
Anarcho-Cocoa/Source/Network/AnarchoAPI.swift
|
1
|
5223
|
import UIKit
import Alamofire
import JsonSwiftson
public struct Application {
let app_key : NSString
let app_type : NSString
let icon_url : NSString
let package : NSString
let name : NSString
}
public struct Build {
let id : NSInteger
let created_on : NSTimeInterval
let release_notes : NSString
let version_code : NSString
let version_name : NSString
}
public typealias completion = () -> Void
public let kAuthorization = "http://anarcho.pp.ciklum.com/api/login"
public let kApps = "http://anarcho.pp.ciklum.com/api/apps"
public class AnarchoAPI{
public func authorization(email: NSString!, password: NSString!, completionBlock: completion? = nil) -> Self{
Alamofire.request(.POST, kAuthorization,
parameters: ["email" : email, "password" : password], encoding: .JSON)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseString(encoding: NSUTF8StringEncoding) { (_, _, string, _) -> Void in
if let json = string{
var mapper = JsonSwiftson(json: json)
let token : NSString = mapper["authToken"].map()!
Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["x-auth-token" :token]
}
if let block = completionBlock {
block()
}
}
return self
}
public func getApps(completion: (applications: [Application]) -> Void) -> Self{
Alamofire.request(.GET, kApps)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseString(encoding: NSUTF8StringEncoding) { (_, _, string, _) -> Void in
if let json = string{
var mapper = JsonSwiftson(json: json)
let applications : [Application] = mapper["list"].mapArrayOfObjects { j in
Application(
app_key: j["app_key"].map()!,
app_type: j["app_type"].map()!,
icon_url: j["icon_url"].map()!,
package: j["package"].map()!,
name: j["name"].map()!)
} ?? []
completion(applications: applications)
}else{
completion(applications: [])
}
}
return self
}
public func getBuilds(appKey: NSString, completion: (builds: [Build]) -> Void) -> Self{
Alamofire.request(.GET, "\(kApps)\(appKey)/builds")
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseString(encoding: NSUTF8StringEncoding) { (_, _, string, _) -> Void in
if let json = string{
var mapper = JsonSwiftson(json: json)
let builds : [Build] = mapper["list"].mapArrayOfObjects { j in
Build(
id: j["id"].map()!,
created_on: j["created_on"].map()!,
release_notes: j["release_notes"].map()!,
version_code: j["version_code"].map()!,
version_name: j["version_name"].map()!)
} ?? []
completion(builds: builds)
}else{
completion(builds: [])
}
}
return self
}
}
class ImageLoader {
var cache = NSCache()
class var sharedLoader : ImageLoader {
struct Static {
static let instance : ImageLoader = ImageLoader()
}
return Static.instance
}
func imageForUrl(urlString: String, completionHandler:(image: UIImage?, url: String) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {()in
var data: NSData? = self.cache.objectForKey(urlString) as? NSData
if let goodData = data {
let image = UIImage(data: goodData)
dispatch_async(dispatch_get_main_queue(), {() in
completionHandler(image: image, url: urlString)
})
return
}
var downloadTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if (error != nil) {
completionHandler(image: nil, url: urlString)
return
}
if data != nil {
let image = UIImage(data: data)
self.cache.setObject(data, forKey: urlString)
dispatch_async(dispatch_get_main_queue(), {() in
completionHandler(image: image, url: urlString)
})
return
}
})
downloadTask.resume()
})
}
}
|
mit
|
21d8f1e14348343567116968a9e1707d
| 38.278195 | 214 | 0.507946 | 5.115573 | false | false | false | false |
Explora-codepath/explora
|
Explora/LoginViewController.swift
|
1
|
3809
|
//
// LoginViewController.swift
// Explora
//
// Created by admin on 10/21/15.
// Copyright © 2015 explora-codepath. All rights reserved.
//
import UIKit
import ParseFacebookUtilsV4
import FBSDKCoreKit
protocol LoginDelegate: class {
func handleLoginSuccess(user: PFUser)
}
class LoginViewController: UIViewController {
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
weak var delegate: LoginDelegate?;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
PFUser.logOut()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loginToFacebook() {
PFFacebookUtils.logInInBackgroundWithReadPermissions(nil) {
(user: PFUser?, error: NSError?) -> Void in
if let user = user {
user.getUserInfo()
let message = "You've successfully logged in!"
print(message)
let alertController = UIAlertController(title: "Facebook Signin", message: message, preferredStyle: UIAlertControllerStyle.Alert)
let button = UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction) -> Void in
self.dismissViewControllerAnimated(true, completion: { () -> Void in
self.delegate?.handleLoginSuccess(user)
})
})
alertController.addAction(button)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let message = "Uh oh. There was an error logging in through Facebook."
print(message)
let alertController = UIAlertController(title: "Facebook Signin", message: message, preferredStyle: UIAlertControllerStyle.Alert)
let button = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
alertController.addAction(button)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
}
@IBAction func loginButtonPressed(sender: AnyObject) {
let username = usernameField.text!;
let password = passwordField.text!;
PFUser.logInWithUsernameInBackground(username, password: password) {
(user: PFUser?, error: NSError?) -> Void in
if let user = user {
// Do stuff after successful login.
print(user)
self.dismissViewControllerAnimated(true, completion: { () -> Void in
self.delegate?.handleLoginSuccess(user)
})
} else {
// The login failed. Check error to see why.
print(error)
}
}
}
@IBAction func cancelButtonPressed(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func facebookSignInButtonPressed(sender: AnyObject) {
loginToFacebook()
}
// 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.
if segue.identifier == "SignUp" {
if let signupVC = segue.destinationViewController as? SignUpViewController {
signupVC.delegate = self.delegate
}
}
}
}
|
mit
|
343ffd0fe4f1a4e6c618fca7a861e849
| 36.333333 | 145 | 0.615546 | 5.463415 | false | false | false | false |
moysklad/ios-remap-sdk
|
Sources/MoyskladiOSRemapSDK/DataManager/DataManager.swift
|
1
|
70044
|
//
// DataManager.swift
// MoyskladNew
//
// Created by Anton Efimenko on 02.11.16.
// Copyright © 2016 Andrey Parshakov. All rights reserved.
//
import Foundation
import RxSwift
/**
Static data loaded after successful login
*/
public struct LogInInfo {
///
public let employee: MSEmployee
public let companySettings: MSCompanySettings
public let states: [MSObjectType: [MSState]]
public let documentAttributes: [MSObjectType: [MSAttributeDefinition]]
public let currencies: [String: MSCurrency]
public let counterpartyTags: [String]
public let priceTypes: [String]
public let groups: [String: MSGroup]
public let createShared: [MSObjectType: Bool]
}
struct MetadataLoadResult {
let type: MSObjectType
let states: [MSState]
let attributes: [MSAttributeDefinition]
let tags: [String]
let priceTypes: [String]
let createShared: Bool
}
/**
Container structure for loading methods' parameters
- parameter auth: Authentication information
- parameter offset: Desired data offset
- parameter expanders: Additional objects to include into request
- parameter filter: Filter for request
- parameter search: Additional string for filtering by name
- parameter orderBy: Order by instruction
- parameter urlParameters: Any other URL parameters
*/
public struct UrlRequestParameters {
public let auth: Auth
public let offset: MSOffset?
public let expanders: [Expander]
public let filter: Filter?
public let search: Search?
public let orderBy: Order?
public let urlParameters: [UrlParameter]?
public init(auth: Auth, offset: MSOffset? = nil, expanders: [Expander] = [], filter: Filter? = nil, search: Search? = nil, orderBy: Order? = nil, urlParameters: [UrlParameter] = []) {
self.auth = auth
self.offset = offset
self.expanders = expanders
self.filter = filter
self.search = search
self.orderBy = orderBy
self.urlParameters = urlParameters
}
var allParameters: [UrlParameter] {
return mergeUrlParameters(offset, search, CompositeExpander(expanders), filter, orderBy) + (urlParameters ?? [])
}
func allParametersCollection(_ parameters: UrlParameter?...) -> [UrlParameter] {
return parameters.compactMap { $0 } + allParameters
}
private func mergeUrlParameters(_ params: UrlParameter?...) -> [UrlParameter] {
var result = [UrlParameter]()
params.forEach { p in
if let p = p {
result.append(p)
}
}
return result
}
}
public struct DataManager {
/// Максимальное количество позиций для документа, при большем (при превышении возвращается ошибка)
static let documentPositionsCountLimit = 100
static func groupBy<T, K: Hashable>(data: [T], groupingKey: ((T) -> K),
withPrevious previousData: [(groupKey: K, data: [T])]? = nil) -> [(groupKey: K, data: [T])] {
var groups: [(groupKey: K, data: [T])] = previousData ?? []
var lastKroupKey = groups.last?.groupKey
data.forEach { object in
let groupingValue = groupingKey(object)
if groupingValue == lastKroupKey {
var lastGroup = groups[groups.count - 1].data
lastGroup.append(object)
groups[groups.count - 1] = (groupKey: groupingValue, data: lastGroup)
} else {
groups.append((groupKey: groupingValue, data: [object]))
lastKroupKey = groupingValue
}
}
return groups
}
static func deserializeObjectMetadata(objectType: MSObjectType, from json: [String:Any]) -> MetadataLoadResult {
let metadata = json.msValue(objectType.rawValue)
let states: [MSState] = metadata.msArray("states").compactMap { MSState.from(dict: $0)?.value() }
let attrs: [MSAttributeDefinition] = metadata.msArray("attributes").compactMap { MSAttributeDefinition.from(dict: $0) }
let priceTypes: [String] = metadata.msArray("priceTypes").compactMap { $0.value("name") }
let createShared: Bool = metadata.value("createShared") ?? false
return MetadataLoadResult(type: objectType, states: states, attributes: attrs, tags: metadata.value("groups") ?? [], priceTypes: priceTypes, createShared: createShared)
}
static func deserializeArray<T>(json: [String:Any],
incorrectJsonError: Error,
deserializer: @escaping ([String:Any]) -> MSEntity<T>?) -> Observable<[MSEntity<T>]> {
let deserialized = json.msArray("rows").map { deserializer($0) }
let withoutNills = deserialized.removeNils()
guard withoutNills.count == deserialized.count else {
return Observable.error(incorrectJsonError)
}
return Observable.just(withoutNills)
}
/**
Register new account
- parameter email: Email for new account
- returns: Registration information
*/
public static func register(email: String, phone: String?) -> Observable<MSRegistrationResult> {
return HttpClient.register(email: email, phone: phone).flatMapLatest { result -> Observable<MSRegistrationResult> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectRegistrationResponse.value))
}
guard let registration = MSRegistrationResult.from(dict: result) else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectRegistrationResponse.value))
}
return Observable.just(registration)
}
}
/**
Log in
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction,
UUID id
- returns: Login information
*/
public static func logIn(parameter: UrlRequestParameters) -> Observable<LogInInfo> {
// запрос данных по пользователю и затем настроек компании и статусов документов
let employeeRequest = HttpClient.get(.contextEmployee, auth: parameter.auth)
.flatMapLatest { result -> Observable<MSEmployee> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectLoginResponse.value))
}
guard let employee = MSEmployee.from(dict: result)?.value() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectLoginResponse.value))
}
return Observable.just(employee)
}
let settingsRequest = HttpClient.get(.companySettings, auth: parameter.auth, urlParameters: [Expander(.currency)])
.flatMapLatest { result -> Observable<MSCompanySettings> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectCompanySettingsResponse.value))
}
guard let settings = MSCompanySettings.from(dict: result)?.value() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectCompanySettingsResponse.value))
}
return Observable.just(settings)
}
let currenciesRequest = HttpClient.get(.currency, auth: parameter.auth, urlParameters: [MSOffset(size: 100, limit: 100, offset: 0)])
.flatMapLatest { result -> Observable<[MSCurrency]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectCurrencyResponse.value)) }
let deserialized = result.msArray("rows").map { MSCurrency.from(dict: $0) }
return Observable.just(deserialized.map { $0?.value() }.removeNils())
}.catchError { error in
switch error {
case MSError.errors(let e):
guard let first = e.first, first == MSErrorStruct.accessDenied() else { return Observable.error(error) }
return Observable.error(MSError.errors([MSErrorStruct.accessDeniedRate()]))
default: return Observable.error(error)
}
}
let groupsRequest = HttpClient.get(.group, auth: parameter.auth, urlParameters: [MSOffset(size: 100, limit: 100, offset: 0)])
.flatMapLatest { result -> Observable<[MSGroup]> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectGroupResponse.value))
}
let deserialized = result.msArray("rows").map { MSGroup.from(dict: $0)?.value() }.removeNils()
return Observable.just(deserialized)
}
// комбинируем все ответы от запросов и возвращаем LogInInfo
return employeeRequest.flatMapLatest { employee -> Observable<LogInInfo> in
return Observable.combineLatest(settingsRequest, currenciesRequest, loadMetadata(parameter: parameter), groupsRequest) { settings, currencies, metadata, groups -> LogInInfo in
let states = metadata.toDictionary(key: { $0.type }, element: { $0.states })
let attributes = metadata.toDictionary(key: { $0.type }, element: { $0.attributes })
let createShared = metadata.toDictionary(key: { $0.type }, element: { $0.createShared })
let counterpartyTags = metadata.first(where: { $0.type == .counterparty })?.tags ?? []
let assortmentPrices = metadata.first(where: { $0.type == .product })?.priceTypes ?? []
return LogInInfo(employee: employee,
companySettings: settings,
states: states,
documentAttributes: attributes,
currencies: currencies.toDictionary { $0.meta.href.withoutParameters() },
counterpartyTags: counterpartyTags,
priceTypes: assortmentPrices,
groups: groups.toDictionary({ $0.meta.href.withoutParameters() }),
createShared: createShared)
}
}
}
static func loadMetadata(parameter: UrlRequestParameters) -> Observable<[MetadataLoadResult]> {
return HttpClient.get(.entityMetadata, auth: parameter.auth, urlParameters: [MSOffset(size: 0, limit: 100, offset: 0)])
.flatMapLatest { result -> Observable<[MetadataLoadResult]> in
guard let json = result?.toDictionary() else { return.just([]) }
let metadata: [MetadataLoadResult] = [deserializeObjectMetadata(objectType: .customerorder, from: json),
deserializeObjectMetadata(objectType: .demand, from: json),
deserializeObjectMetadata(objectType: .invoicein, from: json),
deserializeObjectMetadata(objectType: .cashin, from: json),
deserializeObjectMetadata(objectType: .cashout, from: json),
deserializeObjectMetadata(objectType: .paymentin, from: json),
deserializeObjectMetadata(objectType: .paymentout, from: json),
deserializeObjectMetadata(objectType: .supply, from: json),
deserializeObjectMetadata(objectType: .invoicein, from: json),
deserializeObjectMetadata(objectType: .invoiceout, from: json),
deserializeObjectMetadata(objectType: .purchaseorder, from: json),
deserializeObjectMetadata(objectType: .counterparty, from: json),
deserializeObjectMetadata(objectType: .move, from: json),
deserializeObjectMetadata(objectType: .inventory, from: json),
deserializeObjectMetadata(objectType: .product, from: json),
deserializeObjectMetadata(objectType: .store, from: json),
deserializeObjectMetadata(objectType: .project, from: json),
deserializeObjectMetadata(objectType: .contract, from: json),
deserializeObjectMetadata(objectType: .employee, from: json),
deserializeObjectMetadata(objectType: .organization, from: json)]
return .just(metadata)
}
}
/**
Load dashboard data for current day
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction,
UUID id
- returns: Dashboard
*/
public static func dashboardDay(parameter: UrlRequestParameters) -> Observable<MSDashboard> {
return HttpClient.get(.dashboardDay, auth: parameter.auth)
.flatMapLatest { result -> Observable<MSDashboard> in
guard let result = result?.toDictionary() else { return Observable.empty() }
guard let dash = MSDashboard.from(dict: result) else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectDashboardResponse.value))
}
return Observable.just(dash)
}
}
/**
Load dashboard data for current week
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction,
UUID id
- returns: Dashboard
*/
public static func dashboardWeek(parameter: UrlRequestParameters) -> Observable<MSDashboard> {
return HttpClient.get(.dashboardWeek, auth: parameter.auth)
.flatMapLatest { result -> Observable<MSDashboard> in
guard let result = result?.toDictionary() else { return Observable.empty() }
guard let dash = MSDashboard.from(dict: result) else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectDashboardResponse.value))
}
return Observable.just(dash)
}
}
/**
Load dashboard data for current month
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction,
UUID id
- returns: Dashboard
*/
public static func dashboardMonth(parameter: UrlRequestParameters) -> Observable<MSDashboard> {
return HttpClient.get(.dashboardMonth, auth: parameter.auth)
.flatMapLatest { result -> Observable<MSDashboard> in
guard let result = result?.toDictionary() else { return Observable.empty() }
guard let dash = MSDashboard.from(dict: result) else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectDashboardResponse.value))
}
return Observable.just(dash)
}
}
/**
Load Assortment.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#ассортимент)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction
- parameter stockStore: Specifies specific Store for filtering
- parameter scope: Filter data for scope. For example if product specified, query will not return variants for product
- returns: Collection of Assortment
*/
public static func assortment(parameters: UrlRequestParameters,
stockStore: StockStore? = nil,
scope: AssortmentScope? = nil)
-> Observable<[MSEntity<MSAssortment>]> {
return HttpClient.get(.assortment, auth: parameters.auth, urlParameters: parameters.allParametersCollection(stockStore, scope, StockMomentAssortment(value: Date())))
.flatMapLatest { result -> Observable<[MSEntity<MSAssortment>]> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectAssortmentResponse.value))
}
let deserialized = result.msArray("rows").map { MSAssortment.from(dict: $0) }
let withoutNills = deserialized.removeNils()
guard withoutNills.count == deserialized.count else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectAssortmentResponse.value))
}
return Observable.just(withoutNills)
}
}
/**
Load organizations.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#юрлицо)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction,
UUID id
*/
public static func organizations(parameters: UrlRequestParameters)
-> Observable<[MSEntity<MSAgent>]> {
return HttpClient.get(.organization, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSAgent>]> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectOrganizationResponse.value))
}
let deserialized = result.msArray("rows").map { MSAgent.from(dict: $0) }
let withoutNills = deserialized.removeNils()
guard withoutNills.count == deserialized.count else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectOrganizationResponse.value))
}
return Observable.just(withoutNills)
}
}
/**
Load counterparties.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#контрагент)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction
*/
public static func counterparties(parameters: UrlRequestParameters)
-> Observable<[MSEntity<MSAgent>]> {
return HttpClient.get(.counterparty, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSAgent>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectCounterpartyResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectCounterpartyResponse.value),
deserializer: { MSAgent.from(dict: $0) })
}
}
/**
Load counterparties with report.
Also see API reference [ for counterparties](https://online.moysklad.ru/api/remap/1.1/doc/index.html#контрагент) and [ counterparty reports](https://online.moysklad.ru/api/remap/1.1/doc/index.html#отчёт-показатели-контрагентов-показатели-контрагентов)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction
*/
public static func counterpartiesWithReport(parameters: UrlRequestParameters)
-> Observable<[MSEntity<MSAgent>]> {
return HttpClient.get(.counterparty, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSAgent>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectCounterpartyResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectCounterpartyResponse.value),
deserializer: { MSAgent.from(dict: $0) })
}
.flatMapLatest { counterparties -> Observable<[MSEntity<MSAgent>]> in
return loadReportsForCounterparties(parameters: parameters, counterparties: counterparties)
.catchError { e in
guard MSError.isCrmAccessDenied(from: e) else { throw e }
return .just([])
}
.flatMapLatest { reports -> Observable<[MSEntity<MSAgent>]> in
let new = counterparties.toDictionary({ $0.objectMeta().objectId })
reports.forEach {
new[$0.value()?.agent.objectMeta().objectId ?? ""]?.value()?.report = $0
}
return .just(counterparties.compactMap { new[$0.objectMeta().objectId] })
}
}
}
/**
Load Assortment and group result by product folder
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction
- parameter stockStore: Specifies specific Store for filtering
- parameter scope: Filter data for scope. For example if product specified, query will not return variants for product
- parameter withPrevious: Grouped data returned by previous invocation of assortmentGroupedByProductFolder (useful for paged loading)
- returns: Collection of grouped Assortment
*/
public static func assortmentGroupedByProductFolder(parameters: UrlRequestParameters,
stockStore: StockStore? = nil,
scope: AssortmentScope? = nil,
urlParameters otherParameters: [UrlParameter] = [],
withPrevious: [(groupKey: String, data: [MSEntity<MSAssortment>])]? = nil)
-> Observable<[(groupKey: String, data: [MSEntity<MSAssortment>])]> {
let parameters = UrlRequestParameters(auth: parameters.auth, offset: parameters.offset, expanders: parameters.expanders, filter: parameters.filter, search: parameters.search, urlParameters: otherParameters)
return assortment(parameters: parameters, stockStore: stockStore, scope: scope)
.flatMapLatest { result -> Observable<[(groupKey: String, data: [MSEntity<MSAssortment>])]> in
let grouped = DataManager.groupBy(data: result, groupingKey: { $0.value()?.getFolderName() ?? "" }, withPrevious: withPrevious)
return Observable.just(grouped)
}
}
/**
Load stock data.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#отчёт-остатки-все-остатки-get)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction,
UUID id
- parameter assortments: Collection of assortments. If specified, stock data will be returned only for this assortment objects
- parameter store: Stock data will be returned for specific Store, if specified
- parameter stockMode: Mode for stock data
- parameter moment: The time point for stock data
*/
public static func productStockAll(parameters: UrlRequestParameters,
assortments: [MSEntity<MSAssortment>],
store: MSStore? = nil,
stockMode: StockMode = .all,
moment: Date? = nil) -> Observable<[MSEntity<MSProductStockAll>]> {
var urlParameters: [UrlParameter] = assortments.map { StockProductId(value: $0.objectMeta().objectId) }
if let storeId = store?.id.msID?.uuidString {
urlParameters.append(StockStoretId(value: storeId))
}
if let moment = moment {
urlParameters.append(StockMoment(value: moment))
}
urlParameters.append(stockMode)
urlParameters.append(MSOffset(size: 100, limit: 100, offset: 0))
return HttpClient.get(.stockAll, auth: parameters.auth, urlParameters: urlParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSProductStockAll>]> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectStockAllResponse.value))
}
let array = result.msArray("rows")
guard array.count > 0 else {
// если массив пустой, значит остатков нет
return Observable.just([])
}
let deserialized = array.map { MSProductStockAll.from(dict: $0) }.removeNils()
return Observable.just(deserialized)
}
}
/**
Load stock distributed by stores.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#отчёт-остатки-все-остатки-get)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction,
UUID id
- parameter assortment: Assortment for whick stock data should be loaded
*/
public static func productStockByStore(parameters: UrlRequestParameters, assortment: MSAssortment) -> Observable<[MSEntity<MSProductStockStore>]> {
let urlParameters: [UrlParameter] = [MSOffset(size: 100, limit: 100, offset: 0),
StockProductId(value: assortment.id.msID?.uuidString ?? "")]
return HttpClient.get(.stockByStore, auth: parameters.auth, urlParameters: urlParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSProductStockStore>]> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectStockByStoreResponse.value))
}
guard let array = result.msArray("rows").first?.msArray("stockByStore"),
array.count > 0 else {
// если массив пустой, значит остатков нет
// возвращаем пустой массив
return Observable.just([])
}
let deserialized = array.map { MSProductStockStore.from(dict: $0) }
let withoutNills = deserialized.removeNils()
guard withoutNills.count == deserialized.count else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectStockByStoreResponse.value))
}
return Observable.just(withoutNills)
}
}
/**
Returns combined data from productStockAll and productStockByStore requests
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction,
UUID id
- parameter assortment: Assortment for whick stock data should be loaded
*/
public static func productCombinedStock(parameters: UrlRequestParameters, assortment: MSAssortment) -> Observable<MSProductStock?> {
return productStockAll(parameters: parameters, assortments: [MSEntity.entity(assortment)]).flatMapLatest { allStock -> Observable<MSProductStock?> in
let prodStockAll: MSProductStockAll? = {
guard let allStock = allStock.first else {
// если остатки не пришли вообще, значит там пусто, возвращаем пустую структуру
return MSProductStockAll.empty()
}
return allStock.value()
}()
guard let all = prodStockAll else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectStockAllResponse.value))
}
return productStockByStore(parameters: parameters, assortment: assortment)
.flatMapLatest { byStore -> Observable<MSProductStock?> in
let withoutNils = byStore.map { $0.value() }.removeNils()
guard withoutNils.count == byStore.count else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectStockAllResponse.value))
}
return Observable.just(MSProductStock(all: all, store: withoutNils))
}
}
}
/**
Load Product folders.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#группа-товаров)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
*/
public static func productFolders(parameters: UrlRequestParameters) -> Observable<[MSEntity<MSProductFolder>]> {
return HttpClient.get(.productFolder, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSProductFolder>]> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectProductFolderResponse.value))
}
let deserialized = result.msArray("rows").map { MSProductFolder.from(dict: $0) }
let withoutNills = deserialized.removeNils()
guard withoutNills.count == deserialized.count else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectProductFolderResponse.value))
}
return Observable.just(withoutNills)
}
}
/**
Load stores.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#склад)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
*/
public static func stores(parameters: UrlRequestParameters) -> Observable<[MSEntity<MSStore>]> {
return HttpClient.get(.store, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSStore>]> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectStoreResponse.value))
}
let deserialized = result.msArray("rows").map { MSStore.from(dict: $0) }
let withoutNills = deserialized.removeNils()
guard withoutNills.count == deserialized.count else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectStoreResponse.value))
}
return Observable.just(withoutNills)
}
}
/**
Load projects.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#проект)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction
*/
public static func projects(parameters: UrlRequestParameters) -> Observable<[MSEntity<MSProject>]> {
return HttpClient.get(.project, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSProject>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectProjectResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectProjectResponse.value),
deserializer: { MSProject.from(dict: $0) })
}
}
/**
Load groups.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#отдел)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction
*/
public static func groups(parameters: UrlRequestParameters)
-> Observable<[MSEntity<MSGroup>]> {
return HttpClient.get(.group, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSGroup>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectGroupResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectGroupResponse.value),
deserializer: { MSGroup.from(dict: $0) })
}
}
/**
Load currencies.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#валюта)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction
*/
public static func currencies(parameters: UrlRequestParameters) -> Observable<[MSEntity<MSCurrency>]> {
return HttpClient.get(.currency, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSCurrency>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectCurrencyResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectCurrencyResponse.value),
deserializer: { MSCurrency.from(dict: $0) })
}
}
/**
Load contracts.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#договор)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction
*/
public static func contracts(parameters: UrlRequestParameters) -> Observable<[MSEntity<MSContract>]> {
return HttpClient.get(.contract, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSContract>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectContractResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectContractResponse.value),
deserializer: { MSContract.from(dict: $0) })
}
}
/**
Load employees.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#сотрудник)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction
*/
public static func employees(parameters: UrlRequestParameters) -> Observable<[MSEntity<MSEmployee>]> {
return HttpClient.get(.employee, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSEmployee>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectEmployeeResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectEmployeeResponse.value),
deserializer: { MSEmployee.from(dict: $0) })
}
}
/**
Load employees to agent
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#сотрудник)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction
Реализовано для возможности совмещать на одном экране контрагентов и сотрудников. Релизовано на экране выбора контрагента
*/
public static func employeesForAgents(parameters: UrlRequestParameters) -> Observable<[MSEntity<MSAgent>]> {
return HttpClient.get(.employee, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSAgent>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectEmployeeResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectEmployeeResponse.value),
deserializer: { MSAgent.from(dict: $0) })
}
}
/**
Load accounts for specified agent.
Also see API reference for [ counterparty](https://online.moysklad.ru/api/remap/1.1/doc/index.html#контрагент-счета-контрагента-get)
and [ organizaiton](https://online.moysklad.ru/api/remap/1.1/doc/index.html#юрлицо-счета-юрлица-get)
- parameter agent: Agent for which accounts will be loaded
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction,
UUID id
*/
public static func agentAccounts(agent: MSAgent, parameters: UrlRequestParameters) -> Observable<[MSEntity<MSAccount>]> {
let urlParameters: [UrlParameter] = parameters.allParameters
let pathComponents = [agent.id.msID?.uuidString ?? "", "accounts"]
let request: Observable<JSONType?> = {
switch agent.meta.type {
case MSObjectType.counterparty: return HttpClient.get(.counterparty, auth: parameters.auth,
urlPathComponents: pathComponents, urlParameters: urlParameters)
case MSObjectType.organization: return HttpClient.get(.organization, auth: parameters.auth,
urlPathComponents: pathComponents, urlParameters: urlParameters)
default: return Observable.empty() // MSAgent бывает только двух типов
}
}()
return request.flatMapLatest { result -> Observable<[MSEntity<MSAccount>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectEmployeeResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectEmployeeResponse.value),
deserializer: { MSAccount.from(dict: $0) })
}
}
/**
Load product info by product id
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#товар-товар-get)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
*/
public static func productAssortmentById(parameters: UrlRequestParameters, id : UUID) -> Observable<MSEntity<MSAssortment>> {
return HttpClient.get(.product, auth: parameters.auth, urlPathComponents: [id.uuidString], urlParameters: [CompositeExpander(parameters.expanders)])
.flatMapLatest { result -> Observable<MSEntity<MSAssortment>> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectProductResponse.value)) }
guard let deserialized = MSAssortment.from(dict: result) else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectProductResponse.value))
}
return Observable.just(deserialized)
}
}
/**
Load product info by bundle id.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#комплект-комплект-get)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
*/
public static func bundleAssortmentById(parameters: UrlRequestParameters, id : UUID) -> Observable<MSEntity<MSAssortment>> {
return HttpClient.get(.bundle, auth: parameters.auth, urlPathComponents: [id.uuidString], urlParameters: [CompositeExpander(parameters.expanders)])
.flatMapLatest { result -> Observable<MSEntity<MSAssortment>> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectBundleResponse.value)) }
guard let deserialized = MSAssortment.from(dict: result) else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectBundleResponse.value))
}
return Observable.just(deserialized)
}
}
/**
Load product info by variant id.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#модификация-модификация-get)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
*/
public static func variantAssortmentById(parameters: UrlRequestParameters, id : UUID) -> Observable<MSEntity<MSAssortment>> {
return HttpClient.get(.variant, auth: parameters.auth, urlPathComponents: [id.uuidString], urlParameters: [CompositeExpander(parameters.expanders)])
.flatMapLatest { result -> Observable<MSEntity<MSAssortment>> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectVariantResponse.value)) }
guard let deserialized = MSAssortment.from(dict: result) else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectVariantResponse.value))
}
return Observable.just(deserialized)
}
}
/**
Load custom entities
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#пользовательский-справочник)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
*/
public static func customEntities(parameters: UrlRequestParameters, metadataId: String) -> Observable<[MSEntity<MSCustomEntity>]> {
return HttpClient.get(.customEntity, auth: parameters.auth, urlPathComponents: [metadataId], urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSCustomEntity>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectCustomEntityResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectCustomEntityResponse.value),
deserializer: { MSCustomEntity.from(dict: $0) })
}
}
/**
Load product info by service id.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#услуга-услуга-get)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
*/
public static func serviceAssortmentById(parameters: UrlRequestParameters, id : UUID) -> Observable<MSEntity<MSAssortment>> {
return HttpClient.get(.service, auth: parameters.auth, urlPathComponents: [id.uuidString], urlParameters: [CompositeExpander(parameters.expanders)])
.flatMapLatest { result -> Observable<MSEntity<MSAssortment>> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectServiceResponse.value)) }
guard let deserialized = MSAssortment.from(dict: result) else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectServiceResponse.value))
}
return Observable.just(deserialized)
}
}
/**
Load SalesByModification report for current day.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#отчёт-прибыльность-прибыльность-по-модификациям-get)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
*/
public static func salesByModificationDay(parameters: UrlRequestParameters) -> Observable<[MSSaleByModification]> {
return salesByModification(parameters: parameters, from: Date().beginningOfDay(), to: Date().endOfDay())
}
/**
Load SalesByModification report for current week.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#отчёт-прибыльность-прибыльность-по-модификациям-get)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
*/
public static func salesByModificationWeek(parameters: UrlRequestParameters) -> Observable<[MSSaleByModification]> {
return salesByModification(parameters: parameters, from: Date().startOfWeek(), to: Date().endOfWeek())
}
/**
Load SalesByModification report for current month.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#отчёт-прибыльность-прибыльность-по-модификациям-get)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
*/
public static func salesByModificationMonth(parameters: UrlRequestParameters) -> Observable<[MSSaleByModification]> {
return salesByModification(parameters: parameters, from: Date().startOfMonth(), to: Date().endOfMonth())
}
/**
Load SalesByModification report for period.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#отчёт-прибыльность-прибыльность-по-модификациям-get)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
- parameter period: Desired period
*/
public static func salesByModificationPeriod(parameters: UrlRequestParameters, period: StatisticsMoment) -> Observable<[MSSaleByModification]> {
return salesByModification(parameters: parameters, from: period.from, to: period.to)
}
/**
Load SalesByModification report.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#отчёт-прибыльность-прибыльность-по-модификациям-get)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
- parameter from: Start date for report
- parameter to: End date for report
*/
public static func salesByModification(parameters: UrlRequestParameters,
from: Date,
to: Date) -> Observable<[MSSaleByModification]> {
let momentFrom = GenericUrlParameter(name: "momentFrom", value: from.toCurrentLocaleLongDate())
let momentTo = GenericUrlParameter(name: "momentTo", value: to.toCurrentLocaleLongDate())
return HttpClient.get(.salesByModification, auth: parameters.auth, urlParameters: parameters.allParametersCollection(momentFrom, momentTo)).flatMapLatest { result -> Observable<[MSSaleByModification]> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectSalesByProductResponse.value))
}
let deserialized = result.msArray("rows").map { MSSaleByModification.from(dict: $0) }
let withoutNills = deserialized.removeNils()
guard withoutNills.count == deserialized.count else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectSalesByProductResponse.value))
}
return Observable.just(withoutNills)
}
}
/**
Load counterparty contacts.
Also see [ API refere`nce](https://online.moysklad.ru/api/remap/1.1/doc#контрагент-контактное-лицо-get)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
- id has to be added to parameters container as stringData
- returns: Observable sequence with contacts
*/
public static func counterpartyContacts(parameters: UrlRequestParameters, id: String) -> Observable<[MSEntity<MSContactPerson>]> {
let urlPathComponents: [String] = [id, "contactpersons"]
return HttpClient.get(.counterparty, auth: parameters.auth, urlPathComponents: urlPathComponents, urlParameters: [])
.flatMapLatest { result -> Observable<[MSEntity<MSContactPerson>]> in
guard let results = result?.toDictionary()?.msArray("rows") else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrecContactPersonsResponse.value))
}
return Observable.just(results.compactMap({ (contact) -> MSEntity<MSContactPerson>? in
return MSContactPerson.from(dict: contact)
}))
}
}
/**
Searches counterparty data by INN.
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
- inn has to be added to parameters container as stringData
- returns: Observable sequence with counterparty info
*/
public static func searchCounterpartyByInn(parameters: UrlRequestParameters, inn: String) -> Observable<[MSCounterpartySearchResult]> {
return HttpClient.get(.suggestCounterparty, auth: parameters.auth, urlParameters: [GenericUrlParameter(name: "search", value: inn)])
.flatMapLatest { result -> Observable<[MSCounterpartySearchResult]> in
guard let results = result?.toDictionary()?.msArray("rows") else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectCounterpartySearchResponse.value))
}
return Observable.just(results.map { MSCounterpartySearchResult.from(dict: $0) }.removeNils())
}
}
/**
Searches bank data by BIC.
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
- returns: Observable sequence with bank info
*/
public static func searchBankByBic(parameters: UrlRequestParameters, bic: String) -> Observable<[MSBankSearchResult]> {
return HttpClient.get(.suggestBank, auth: parameters.auth, urlParameters: [GenericUrlParameter(name: "search", value: bic)])
.flatMapLatest { result -> Observable<[MSBankSearchResult]> in
guard let results = result?.toDictionary()?.msArray("rows") else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectBankSearchResponse.value))
}
return Observable.just(results.map { MSBankSearchResult.from(dict: $0) })
}
}
/**
Load tasks.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#задача)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction
*/
public static func tasks(parameters: UrlRequestParameters) -> Observable<[MSEntity<MSTask>]> {
return HttpClient.get(.task, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSTask>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectTasksResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectEmployeeResponse.value),
deserializer: { MSTask.from(dict: $0) })
}
}
/**
Load task by id.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#задача)
- parameter parameters: container for parameters like auth, offset, search, expanders, filter, orderBy, urlParameters
- id has to be added to parameters container
*/
public static func loadById(parameters: UrlRequestParameters, taskId: UUID) -> Observable<MSEntity<MSTask>> {
return HttpClient.get(.task, auth: parameters.auth, urlPathComponents: [taskId.uuidString], urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<MSEntity<MSTask>> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectTasksResponse.value)) }
guard let deserialized = MSTask.from(dict: result) else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectTasksResponse.value))
}
return Observable.just(deserialized)
}
}
public static func loadExpenseitems(parameters: UrlRequestParameters) -> Observable<[MSEntity<MSExpenseItem>]> {
return HttpClient.get(.expenseitem, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSExpenseItem>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectExpenseItemResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectExpenseItemResponse.value),
deserializer: { MSExpenseItem.from(dict: $0) })
}
}
public static func loadCountries(parameters: UrlRequestParameters) -> Observable<[MSEntity<MSCountry>]> {
let urlParameters: [UrlParameter] = parameters.allParameters
return HttpClient.get(.country, auth: parameters.auth, urlParameters: urlParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSCountry>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectCountiesResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectCountiesResponse.value),
deserializer: { MSCountry.from(dict: $0) })
}
}
public static func loadUom(parameters: UrlRequestParameters) -> Observable<[MSEntity<MSUOM>]> {
return HttpClient.get(.uom, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSUOM>]> in
guard let result = result?.toDictionary() else { return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectUomResponse.value)) }
return deserializeArray(json: result,
incorrectJsonError: MSError.genericError(errorText: LocalizedStrings.incorrectUomResponse.value),
deserializer: { MSUOM.from(dict: $0) })
}
}
/**
Load Variant metadata
- parameter auth: Authentication information
- returns: Metadata for object
*/
public static func variantMetadata(parameters: UrlRequestParameters) -> Observable<[MSEntity<MSVariantAttribute>]> {
return HttpClient.get(.variantMetadata, auth: parameters.auth)
.flatMapLatest { result -> Observable<[MSEntity<MSVariantAttribute>]> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectVariantMetadataResponse.value))
}
let deserialized = result.msArray("characteristics").map { MSVariantAttribute.from(dict: $0) }
let withoutNills = deserialized.removeNils()
return .just(withoutNills)
}
}
/**
Load Variants.
Also see [ API reference](https://online.moysklad.ru/api/remap/1.1/doc/index.html#модификация-модификации)
- parameter parameters: container for parameters like:
authentication information,
desired data offset,
filter for request,
Additional objects to include into request,
Order by instruction
- returns: Collection of Variant
*/
public static func variants(parameters: UrlRequestParameters)
-> Observable<[MSEntity<MSAssortment>]> {
return HttpClient.get(.variant, auth: parameters.auth, urlParameters: parameters.allParameters)
.flatMapLatest { result -> Observable<[MSEntity<MSAssortment>]> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectVariantResponse.value))
}
let deserialized = result.msArray("rows").map { MSAssortment.from(dict: $0) }
let withoutNills = deserialized.removeNils()
guard withoutNills.count == deserialized.count else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectVariantResponse.value))
}
return Observable.just(withoutNills)
}
}
public static func downloadFile(auth: Auth, url: URL) -> Observable<URL> {
var request = URLRequest(url: url)
request.addValue(auth.header.values.first!, forHTTPHeaderField: auth.header.keys.first!)
return HttpClient.resultCreateForDownloadFile(request)
}
public static func sendToken(auth: Auth, fcmToken: String, deviceId: String) -> Observable<Void> {
let body = ["deviceId": deviceId, "token": fcmToken].toJSONType()
return HttpClient.create(.token, auth: auth, urlPathComponents: [], urlParameters: [], body: body)
.flatMap { _ -> Observable<Void> in
return .empty()
}
}
public static func readAllNotifications(auth: Auth) -> Observable<Void> {
return HttpClient.update(.notificationsReadAll, auth: auth)
.flatMap { _ -> Observable<Void> in
return .empty()
}
}
public static func sendNotificationsSettings(auth: Auth, settings: [String: Any]) -> Observable<Void> {
return HttpClient.update(.notificationSubscription, auth: auth, body: settings.toJSONType())
.flatMap { _ -> Observable<Void> in
return .empty()
}
}
public static func getAllNotificationsSettings(auth: Auth) -> Observable<[MSNotificationSettings]> {
return HttpClient.get(.notificationSubscription, auth: auth)
.flatMapLatest { result -> Observable<[MSNotificationSettings]> in
guard let result = result?.toDictionary() else {
return Observable.error(MSError.genericError(errorText: LocalizedStrings.incorrectNotificationResponse.value))
}
var deserialized = result.msValue("groups").map { MSNotificationSettings(key: $0.key, settings: MSEnabledChannels.from(dict: $0.value as? [String : Any]))}
deserialized = deserialized.filter { $0.key == "task" || $0.key == "customer_order" || $0.key == "retail" || $0.key == "stock" || $0.key == "data_exchange" || $0.key == "invoice" }
return Observable.just(deserialized.sorted(by: { $0.keyOrder < $1.keyOrder }))
}
}
}
|
mit
|
5a249011984d5a6acb250f2e0bc1ad58
| 56.057072 | 256 | 0.596953 | 5.261785 | false | false | false | false |
CSStickyHeaderFlowLayout/CSStickyHeaderFlowLayout
|
Project/SwiftDemo/SwiftDemo/AppDelegate.swift
|
2
|
869
|
//
// AppDelegate.swift
// SwiftDemo
//
// Created by James Tang on 16/7/15.
// Copyright (c) 2015 James Tang. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// Override point for customization after application launch.
let stickyHeaderFlowLayout = CSStickyHeaderFlowLayout()
let collectionViewController = CollectionViewController(collectionViewLayout: stickyHeaderFlowLayout)
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = collectionViewController
window.makeKeyAndVisible()
self.window = window
return true
}
}
|
mit
|
55b2406fc0629122c483e72a092419ce
| 28.965517 | 152 | 0.728423 | 5.364198 | false | false | false | false |
dreamsxin/swift
|
validation-test/compiler_crashers_fixed/00119-swift-dependentmembertype-get.swift
|
11
|
1483
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
func sr<ml>() -> (ml, ml -> ml) -> ml {
a sr a.sr = {
}
{
ml) {
ih }
}
protocol sr {
}
class a: sr{ class func sr {}
class w {
}
class n {
func ji((x, n))(w: (x, f)) {
}
}
func n<x: b, ed y nm<ed> == x.x.n>(rq : x) -> ed? {
fe (w : ed?) k rq {
r n a = w {
}
}
}
func kj(q: ih) -> <ed>(() -> ed) -> ih {
}
func w(a: x, x: x) -> (((x, x) -> x) -> x) {
qp {
}
}
func ji(r: (((x, x) -> x) -> x)) -> x {
qp r({
})
}
func w<ed>() {
t ji {
}
}
protocol g ed : m>(ji: ed) {
}
protocol w {
}
class ji<ih : n, sr : n y ih.ml == sr> : w po n<a {
t n {
}
}
t x<ed> {
}
protocol g {
}
class nm {
func a() -> ih {
}
}
class i: nm, g {
qp func a() -> ih {
}
func n() -> ih {
}
}
func x<ed y ed: g, ed: nm>(rq: ed) {
}
struct n<a : b> {
}
func w<a>() -> [n<a>] {
}
protocol g {
}
struct nm : g {
}
struct i<ed, ml: g y ed.i == ml> {
}
protocol w {
}
protocol ji : w {
}
protocol n : w {
}
protocol a {
}
struct x : a {
}
func sr<sr : ji, ts : a y ts.sr == sr> (sr: ts) {
}
func ji {
}
struct n<ih : ji
|
apache-2.0
|
c74e8e84d11e2961d55179275fc6c3f8
| 14.946237 | 78 | 0.489548 | 2.467554 | false | false | false | false |
miroslavkovac/Lingo
|
Sources/Lingo/Pluralization/Concrete/lt.swift
|
1
|
589
|
import Foundation
final class lt: PluralizationRule {
let locale: LocaleIdentifier = "lt"
var availablePluralCategories: [PluralCategory] = [.one, .few, .other]
func pluralCategory(forNumericValue n: UInt) -> PluralCategory {
let mod10 = n % 10
let mod100 = n % 100
if mod10 == 1 && !(11...19).contains(mod100) {
return .one
} else if (2...9).contains(mod10) && !(11...19).contains(mod100) {
return .few
} else {
return .other
}
}
}
|
mit
|
44a3bb66784048e888adde9bdcd265b3
| 23.541667 | 74 | 0.50764 | 4.23741 | false | false | false | false |
vgatto/protobuf-swift
|
src/ProtocolBuffers/runtime-pb-swift/CodedOutputStream.swift
|
3
|
11763
|
// Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google 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 Foundation
var DEFAULT_BUFFER_SIZE:Int32 = 4 * 1024
public class CodedOutputStream
{
private var output:NSOutputStream!
internal var buffer:RingBuffer
public init (output aOutput:NSOutputStream!, data:NSMutableData)
{
output = aOutput
buffer = RingBuffer(data:data)
}
public init(output aOutput:NSOutputStream!, bufferSize:Int32)
{
var data = NSMutableData(length: Int(bufferSize))!
output = aOutput
buffer = RingBuffer(data: data)
}
public init(output:NSOutputStream)
{
var data = NSMutableData(length: Int(DEFAULT_BUFFER_SIZE))!
self.output = output
buffer = RingBuffer(data: data)
}
public init(data aData:NSMutableData)
{
buffer = RingBuffer(data: aData)
}
public func flush()
{
if output == nil
{
NSException(name:"OutOfSpace", reason:"", userInfo: nil).raise()
}
var size = buffer.flushToOutputStream(output!)
}
public func writeRawByte(byte aByte:UInt8)
{
while (!buffer.appendByte(byte: aByte))
{
flush()
}
}
public func writeRawData(data:NSData)
{
writeRawData(data, offset:0, length: Int32(data.length))
}
public func writeRawData(data:NSData, offset:Int32, length:Int32)
{
var aLength = length
var aOffset = offset
while (aLength > 0)
{
var written:Int32 = buffer.appendData(data, offset: aOffset, length: aLength)
aOffset += Int32(written)
aLength -= Int32(written)
if (written == 0 || aLength > 0)
{
flush()
}
}
}
public func writeDoubleNoTag(value:Double)
{
var convertValue = value
var returnValue:Int64 = 0
WireFormat.convertTypes(convertValue: value, retValue: &returnValue)
writeRawLittleEndian64(returnValue)
}
public func writeDouble(fieldNumber:Int32, value aValue:Double)
{
writeTag(fieldNumber, format: WireFormat.WireFormatFixed64)
writeDoubleNoTag(aValue)
}
public func writeFloatNoTag(value:Float)
{
var convertValue = value
var returnValue:Int32 = 0
WireFormat.convertTypes(convertValue: convertValue, retValue: &returnValue)
writeRawLittleEndian32(returnValue)
}
public func writeFloat(fieldNumber:Int32, value aValue:Float)
{
writeTag(fieldNumber, format: WireFormat.WireFormatFixed32)
writeFloatNoTag(aValue)
}
public func writeUInt64NoTag(value:UInt64)
{
var retvalue:Int64 = 0
WireFormat.convertTypes(convertValue: value, retValue: &retvalue)
writeRawVarint64(retvalue)
}
public func writeUInt64(fieldNumber:Int32, value:UInt64)
{
writeTag(fieldNumber, format:WireFormat.WireFormatVarint)
writeUInt64NoTag(value)
}
public func writeInt64NoTag(value:Int64)
{
writeRawVarint64(value)
}
public func writeInt64(fieldNumber:Int32, value aValue:Int64)
{
writeTag(fieldNumber, format: WireFormat.WireFormatVarint)
writeInt64NoTag(aValue)
}
public func writeInt32NoTag(value:Int32)
{
if (value >= 0) {
writeRawVarint32(value)
} else {
writeRawVarint64(Int64(value))
}
}
public func writeInt32(fieldNumber:Int32, value:Int32)
{
writeTag(fieldNumber, format: WireFormat.WireFormatVarint)
writeInt32NoTag(value)
}
public func writeFixed64NoTag(value:UInt64)
{
var retvalue:Int64 = 0
WireFormat.convertTypes(convertValue: value, retValue: &retvalue)
writeRawLittleEndian64(retvalue)
}
public func writeFixed64(fieldNumber:Int32, value:UInt64)
{
writeTag(fieldNumber, format: WireFormat.WireFormatFixed64)
writeFixed64NoTag(value)
}
public func writeFixed32NoTag(value:UInt32)
{
var retvalue:Int32 = 0
WireFormat.convertTypes(convertValue: value, retValue: &retvalue)
writeRawLittleEndian32(retvalue)
}
public func writeFixed32(fieldNumber:Int32, value:UInt32)
{
writeTag(fieldNumber, format:WireFormat.WireFormatFixed32)
writeFixed32NoTag(value)
}
public func writeBoolNoTag(value:Bool)
{
writeRawByte(byte: value ? 1 : 0)
}
public func writeBool(fieldNumber:Int32, value:Bool)
{
writeTag(fieldNumber, format:WireFormat.WireFormatVarint)
writeBoolNoTag(value)
}
public func writeStringNoTag(value:String)
{
let data = value.utf8ToNSData()
writeRawVarint32(Int32(data.length))
writeRawData(data)
}
public func writeString(fieldNumber:Int32, value:String)
{
writeTag(fieldNumber, format: WireFormat.WireFormatLengthDelimited)
writeStringNoTag(value)
}
public func writeGroupNoTag(fieldNumber:Int32, value:Message)
{
value.writeToCodedOutputStream(self)
writeTag(fieldNumber, format: WireFormat.WireFormatEndGroup)
}
public func writeGroup(fieldNumber:Int32, value:Message)
{
writeTag(fieldNumber, format: WireFormat.WireFormatStartGroup)
writeGroupNoTag(fieldNumber, value: value)
}
public func writeUnknownGroupNoTag(fieldNumber:Int32, value:UnknownFieldSet) {
value.writeToCodedOutputStream(self)
writeTag(fieldNumber, format:WireFormat.WireFormatEndGroup)
}
public func writeUnknownGroup(fieldNumber:Int32, value:UnknownFieldSet)
{
writeTag(fieldNumber, format:WireFormat.WireFormatStartGroup)
writeUnknownGroupNoTag(fieldNumber, value:value)
}
public func writeMessageNoTag(value:Message)
{
writeRawVarint32(value.serializedSize())
value.writeToCodedOutputStream(self)
}
public func writeMessage(fieldNumber:Int32, value:Message)
{
writeTag(fieldNumber, format: WireFormat.WireFormatLengthDelimited)
writeMessageNoTag(value)
}
public func writeDataNoTag(data:NSData)
{
writeRawVarint32(Int32(data.length))
writeRawData(data)
}
public func writeData(fieldNumber:Int32, value:NSData)
{
writeTag(fieldNumber, format: WireFormat.WireFormatLengthDelimited)
writeDataNoTag(value)
}
public func writeUInt32NoTag(value:UInt32)
{
var retvalue:Int32 = 0
WireFormat.convertTypes(convertValue: value, retValue: &retvalue)
writeRawVarint32(retvalue)
}
public func writeUInt32(fieldNumber:Int32, value:UInt32)
{
writeTag(fieldNumber, format: WireFormat.WireFormatVarint)
writeUInt32NoTag(value)
}
public func writeEnumNoTag(value:Int32)
{
writeRawVarint32(value)
}
public func writeEnum(fieldNumber:Int32, value:Int32)
{
writeTag(fieldNumber, format:WireFormat.WireFormatVarint)
writeEnumNoTag(value)
}
public func writeSFixed32NoTag(value:Int32)
{
writeRawLittleEndian32(value)
}
public func writeSFixed32(fieldNumber:Int32, value:Int32)
{
writeTag(fieldNumber, format:WireFormat.WireFormatFixed32)
writeSFixed32NoTag(value)
}
public func writeSFixed64NoTag(value:Int64)
{
writeRawLittleEndian64(value)
}
public func writeSFixed64(fieldNumber:Int32, value:Int64)
{
writeTag(fieldNumber, format:WireFormat.WireFormatFixed64)
writeSFixed64NoTag(value)
}
public func writeSInt32NoTag(value:Int32) {
writeRawVarint32(WireFormat.encodeZigZag32(value))
}
public func writeSInt32(fieldNumber:Int32, value:Int32)
{
writeTag(fieldNumber, format:WireFormat.WireFormatVarint)
writeSInt32NoTag(value)
}
public func writeSInt64NoTag(value:Int64) {
writeRawVarint64(WireFormat.encodeZigZag64(value))
}
public func writeSInt64(fieldNumber:Int32, value:Int64)
{
writeTag(fieldNumber, format:WireFormat.WireFormatVarint)
writeSInt64NoTag(value)
}
public func writeMessageSetExtension(fieldNumber:Int32, value:Message)
{
writeTag(WireFormatMessage.WireFormatMessageSetItem.rawValue, format:WireFormat.WireFormatStartGroup)
writeUInt32(WireFormatMessage.WireFormatMessageSetTypeId.rawValue, value:UInt32(fieldNumber))
writeMessage(WireFormatMessage.WireFormatMessageSetMessage.rawValue, value: value)
writeTag(WireFormatMessage.WireFormatMessageSetItem.rawValue, format:WireFormat.WireFormatEndGroup)
}
public func writeRawMessageSetExtension(fieldNumber:Int32, value:NSData)
{
writeTag(WireFormatMessage.WireFormatMessageSetItem.rawValue, format:WireFormat.WireFormatStartGroup)
writeUInt32(WireFormatMessage.WireFormatMessageSetTypeId.rawValue, value:UInt32(fieldNumber))
writeData( WireFormatMessage.WireFormatMessageSetMessage.rawValue, value: value)
writeTag(WireFormatMessage.WireFormatMessageSetItem.rawValue, format:WireFormat.WireFormatEndGroup)
}
public func writeTag(fieldNumber:Int32, format:WireFormat)
{
writeRawVarint32(format.wireFormatMakeTag(fieldNumber))
}
public func writeRawLittleEndian32(value:Int32)
{
writeRawByte(byte:UInt8(value & 0xFF))
writeRawByte(byte:UInt8((value >> 8) & 0xFF))
writeRawByte(byte:UInt8((value >> 16) & 0xFF))
writeRawByte(byte:UInt8((value >> 24) & 0xFF))
}
public func writeRawLittleEndian64(value:Int64)
{
writeRawByte(byte:UInt8(value & 0xFF))
writeRawByte(byte:UInt8((value >> 8) & 0xFF))
writeRawByte(byte:UInt8((value >> 16) & 0xFF))
writeRawByte(byte:UInt8((value >> 24) & 0xFF))
writeRawByte(byte:UInt8((value >> 32) & 0xFF))
writeRawByte(byte:UInt8((value >> 40) & 0xFF))
writeRawByte(byte:UInt8((value >> 48) & 0xFF))
writeRawByte(byte:UInt8((value >> 56) & 0xFF))
}
public func writeRawVarint32(var value:Int32) {
while (true) {
if ((value & ~0x7F) == 0) {
writeRawByte(byte:UInt8(value))
break
} else
{
writeRawByte(byte: UInt8((value & 0x7F) | 0x80))
value = WireFormat.logicalRightShift32(value:value,spaces: 7)
}
}
}
public func writeRawVarint64(var value:Int64) {
while (true) {
if ((value & ~0x7F) == 0) {
writeRawByte(byte:UInt8(value))
break
} else {
writeRawByte(byte: UInt8((value & 0x7F) | 0x80))
value = WireFormat.logicalRightShift64(value:value, spaces: 7)
}
}
}
}
|
apache-2.0
|
de7eb87a0386c7f545db5693da590a62
| 29.164103 | 109 | 0.649239 | 4.297771 | false | false | false | false |
dreamsxin/swift
|
validation-test/stdlib/Hashing.swift
|
3
|
5335
|
// RUN: %target-run-stdlib-swift
// REQUIRES: executable_test
import Swift
import SwiftPrivate
import StdlibUnittest
var HashingTestSuite = TestSuite("Hashing")
HashingTestSuite.test("_mixUInt32/GoldenValues") {
expectEqual(0x11b882c9, _mixUInt32(0x0))
expectEqual(0x60d0aafb, _mixUInt32(0x1))
expectEqual(0x636847b5, _mixUInt32(0xffff))
expectEqual(0x203f5350, _mixUInt32(0xffff_ffff))
expectEqual(0xb8747ef6, _mixUInt32(0xa62301f9))
expectEqual(0xef4eeeb2, _mixUInt32(0xfe1b46c6))
expectEqual(0xd44c9cf1, _mixUInt32(0xe4daf7ca))
expectEqual(0xfc1eb1de, _mixUInt32(0x33ff6f5c))
expectEqual(0x5605f0c0, _mixUInt32(0x13c2a2b8))
expectEqual(0xd9c48026, _mixUInt32(0xf3ad1745))
expectEqual(0x471ab8d0, _mixUInt32(0x656eff5a))
expectEqual(0xfe265934, _mixUInt32(0xfd2268c9))
}
HashingTestSuite.test("_mixInt32/GoldenValues") {
expectEqual(Int32(bitPattern: 0x11b882c9), _mixInt32(0x0))
}
HashingTestSuite.test("_mixUInt64/GoldenValues") {
expectEqual(0xb2b2_4f68_8dc4_164d, _mixUInt64(0x0))
expectEqual(0x792e_33eb_0685_57de, _mixUInt64(0x1))
expectEqual(0x9ec4_3423_1b42_3dab, _mixUInt64(0xffff))
expectEqual(0x4cec_e9c9_01fa_9a84, _mixUInt64(0xffff_ffff))
expectEqual(0xcba5_b650_bed5_b87c, _mixUInt64(0xffff_ffff_ffff))
expectEqual(0xe583_5646_3fb8_ac99, _mixUInt64(0xffff_ffff_ffff_ffff))
expectEqual(0xf5d0079f828d43a5, _mixUInt64(0x94ce7d9319f8d233))
expectEqual(0x61900a6be9db9c3f, _mixUInt64(0x2728821e8c5b1f7))
expectEqual(0xf2fd34b1b7d4b46e, _mixUInt64(0xe7f67ec98c64f482))
expectEqual(0x216199ed628c821, _mixUInt64(0xd7c277b5438873ac))
expectEqual(0xb1b486ff5f2e0e53, _mixUInt64(0x8399f1d563c42f82))
expectEqual(0x61acc92bd91c030, _mixUInt64(0x488cefd48a2c4bfd))
expectEqual(0xa7a52d6e4a8e3ddf, _mixUInt64(0x270a15116c351f95))
expectEqual(0x98ceedc363c4e56a, _mixUInt64(0xe5fb9b5f6c426a84))
}
HashingTestSuite.test("_mixUInt64/GoldenValues") {
expectEqual(Int64(bitPattern: 0xb2b2_4f68_8dc4_164d), _mixInt64(0x0))
}
HashingTestSuite.test("_mixUInt/GoldenValues") {
#if arch(i386) || arch(arm)
expectEqual(0x11b8_82c9, _mixUInt(0x0))
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
expectEqual(0xb2b2_4f68_8dc4_164d, _mixUInt(0x0))
#else
fatalError("unimplemented")
#endif
}
HashingTestSuite.test("_mixInt/GoldenValues") {
#if arch(i386) || arch(arm)
expectEqual(Int(bitPattern: 0x11b8_82c9), _mixInt(0x0))
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
expectEqual(Int(bitPattern: 0xb2b2_4f68_8dc4_164d), _mixInt(0x0))
#else
fatalError("unimplemented")
#endif
}
HashingTestSuite.test("_squeezeHashValue/Int") {
// Check that the function can return values that cover the whole range.
func checkRange(_ r: Range<Int>) {
var results = [Int : Void]()
for _ in 0..<(14 * (r.upperBound - r.lowerBound)) {
let v = _squeezeHashValue(randInt(), r)
expectTrue(r ~= v)
if results[v] == nil {
results[v] = Void()
}
}
expectEqual(r.upperBound - r.lowerBound, results.count)
}
checkRange(Int.min..<(Int.min+10))
checkRange(0..<4)
checkRange(0..<8)
checkRange(-5..<5)
checkRange((Int.max-10)..<(Int.max-1))
// Check that we can handle ranges that span more than `Int.max`.
#if arch(i386) || arch(arm)
expectEqual(-0x6e477d37, _squeezeHashValue(0, Int.min..<(Int.max - 1)))
expectEqual(0x38a3ea26, _squeezeHashValue(2, Int.min..<(Int.max - 1)))
#elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x)
expectEqual(0x32b24f688dc4164d, _squeezeHashValue(0, Int.min..<(Int.max - 1)))
expectEqual(-0x6d1cc14f97aa822, _squeezeHashValue(1, Int.min..<(Int.max - 1)))
#else
fatalError("unimplemented")
#endif
}
HashingTestSuite.test("_squeezeHashValue/UInt") {
// Check that the function can return values that cover the whole range.
func checkRange(_ r: Range<UInt>) {
var results = [UInt : Void]()
let cardinality = r.upperBound - r.lowerBound
for _ in 0..<(10*cardinality) {
let v = _squeezeHashValue(randInt(), r)
expectTrue(r ~= v)
if results[v] == nil {
results[v] = Void()
}
}
expectEqual(Int(cardinality), results.count)
}
checkRange(0..<4)
checkRange(0..<8)
checkRange(0..<10)
checkRange(10..<20)
checkRange((UInt.max-10)..<(UInt.max-1))
}
HashingTestSuite.test("String/hashValue/topBitsSet") {
#if _runtime(_ObjC)
#if arch(x86_64) || arch(arm64)
// Make sure that we don't accidentally throw away bits by storing the result
// of NSString.hash into an int in the runtime.
// This is the bit pattern that we xor to NSString's hash value.
let hashOffset = UInt(bitPattern: 0x429b_1266_0000_0000)
let hash = "efghijkl".hashValue
// When we are not equal to the top bit of the xor'ed hashOffset pattern
// there where some bits set.
let topHashBits = UInt(bitPattern: hash) & 0xffff_ffff_0000_0000
expectTrue(hash > 0)
expectTrue(topHashBits != hashOffset)
#endif
#endif
}
HashingTestSuite.test("overridePerExecutionHashSeed/overflow") {
// Test that we don't use checked arithmetic on the seed.
_HashingDetail.fixedSeedOverride = UInt64.max
expectEqual(0x4344_dc3a_239c_3e81, _mixUInt64(0xffff_ffff_ffff_ffff))
_HashingDetail.fixedSeedOverride = 0
}
runAllTests()
|
apache-2.0
|
a8eb186ee4fe60af8ef34fe7bfabf02f
| 34.331126 | 90 | 0.724461 | 2.785901 | false | true | false | false |
chengxianghe/MissGe
|
MissGe/MissGe/Class/Helper/KeychainTool.swift
|
1
|
774
|
//
// KeychainTool.swift
// MissGe
//
// Created by chengxianghe on 2017/4/12.
// Copyright © 2017年 cn. All rights reserved.
//
import Foundation
import KeychainAccess
class KeychainTool {
static func save(service: String, data: String?) {
let keychain = Keychain(service: service)
keychain[service] = data
}
static func load(_ service: String) -> String? {
let keychain = Keychain(service: service)
let token = keychain[service]
return token
}
static func delete(service: String) {
let keychain = Keychain(service: service)
do {
try keychain.remove(service)
} catch let error {
print("keychain delete error: \(error)")
}
}
}
|
mit
|
a85baae2c36c5ae1017b1a4a17ba96b6
| 22.363636 | 54 | 0.594034 | 4.236264 | false | false | false | false |
davidbjames/Unilib
|
Unilib/Sources/PropertyWrappers.swift
|
1
|
10662
|
//
// PropertyWrappers.swift
// Unilib
//
// Created by David James on 2019-10-01.
// Copyright © 2019-2021 David B James. All rights reserved.
//
import Foundation
/// Property that is guaranteed to never be less than 0
/// with a projected boolean value to indicate when
/// the value is greater than 0.
@propertyWrapper
public struct MinZero {
private var number = 0
public var projectedValue = false
public var wrappedValue:Int {
get { return number }
set {
if newValue < 0 {
number = 0
} else {
number = newValue
}
projectedValue = number > 0
}
}
public init(wrappedValue:Int) {
// NOTE: This specific initializer is necessary in case
// you must create this property with an initial value.
// Example: @MinZero var test = 3
// On the other hand, to create this property with any
// other value you must create another initializer for
// that value. Example: @Min(min:2) var test.
// To combine both a custom initial value and the initial
// value of the wrapped value, you must create yet another
// initializer that does both, with wrappedValue first:
// init(wrappedValue:Int, min:Int) and call it like
// @Min(min:2) var test = 5
// which synthesizes to: Min(wrappedValue:5, min:2).
number = wrappedValue
}
}
// DEV NOTE: @Cycled may only be used in a SwiftUI context
// because SwiftUI manages its state (with updates) within a View.
// To get the same functionality (but without updates) use @CycledRaw.
// This has been tested on a UIViewController.
// @Cycled does not work there, @CycledRaw does (but without updates).
// MAINTENANCE: Sync the two blocks with and without SwiftUI
#if canImport(SwiftUI)
import SwiftUI
/// Property that cycles through numbers
/// resetting to 0 when `max` is reached.
///
/// Alternatively, pass `min` to reset to
/// a number other than 0 and/or decrement
/// the number instead of incrementing.
/// You may also pass an initial starting
/// number from where to begin in the cycle.
///
/// @Cycled(min:1, max:5) var counter:Int = 2
/// ..
/// counter = 1 // increment
/// counter = -1 // decrement
/// Optionally, make the cycling `reversible`
/// in either direction, so instead of starting
/// again, it reverses when it reaches min/max.
/// Alternatively, make this `finite` so that
/// it stops when its bound is reached.
@propertyWrapper
public struct Cycled<T:SignedNumeric & Comparable> : DynamicProperty {
/// Type of cycling behavior
public enum Mode {
/// Cycle numbers from beginning and when
/// reaching the end, start at the beginning.
/// Default cycling behavior.
case repeatable
/// Cycle numbers from beginning and when
/// reaching the end, go back to the beginning
/// and vice versa.
case reversible
/// Cycle numbers from beginning and when
/// reaching the end, stop.
case finite
}
private let min:T
private let max:T
private let mode:Mode
private var reversible:Bool {
mode == .reversible
}
private var finite:Bool {
mode == .finite
}
@State private var number:T = 0
@State private var shouldReverse:Bool = false
public var wrappedValue:T {
get { return number }
nonmutating set {
guard newValue != T.zero else { return }
let value = shouldReverse ? -newValue : newValue
let newNumber = number + value
if value < T.zero { // decrementing
if newNumber < min {
if reversible || finite {
// Past min value, clamp to min.
// It will either start going back the opposite way
// for "reversible" or just stay there for "finite".
number = min
} else {
// Past min, start again at max. "repeatable"
number = max
}
} else {
number = newNumber
}
} else { // incrementing
if newNumber > max {
if reversible || finite {
number = max
} else {
number = min
}
} else {
number = newNumber
}
}
if reversible && (number == min || number == max) {
shouldReverse.toggle()
}
}
}
public var projectedValue:Binding<T> {
Binding(
get: { wrappedValue },
set: { wrappedValue = $0 }
)
}
public init(min:T = T.zero, max:T, mode:Mode? = nil) {
guard min < max else {
preconditionFailure("Attempt to initialize @Cycled property wrapper with min value that is greater than or equal to max value.")
}
self.min = min
self.max = max
self.mode = mode ?? .repeatable
self._number = State(wrappedValue:min)
}
public init(wrappedValue startingAt:T, min:T = T.zero, max:T, mode:Mode? = nil) {
guard min < max else {
preconditionFailure("Attempt to initialize @Cycled property wrapper with min value that is greater than or equal to max value.")
}
guard startingAt >= min && startingAt <= max else {
preconditionFailure("Attempt to initialize @Cycled property wrapper with initial start value (\(startingAt)) that is not within min (\(min)) and max (\(max)) values inclusive.")
}
self.min = min
self.max = max
self.mode = mode ?? .repeatable
self._number = State(wrappedValue:startingAt)
}
public var atMin:Bool {
wrappedValue <= min
}
public var atMax:Bool {
wrappedValue >= max
}
// Couldn't get this to work.. would just hit Int +=
// Wanted syntax like: counter += 1
// public static func +=(cycled:inout Self, value:Int) {
// cycled.wrappedValue = value
// }
}
#endif
/// Property that cycles through numbers
/// resetting to 0 when `max` is reached.
///
/// Alternatively, pass `min` to reset to
/// a number other than 0 and/or decrement
/// the number instead of incrementing.
/// You may also pass an initial starting
/// number from where to begin in the cycle.
///
/// @CycledRaw(min:1, max:5) var counter:Int = 2
/// ..
/// counter = 1 // increment
/// counter = -1 // decrement
/// Optionally, make the cycling `reversible`
/// in either direction, so instead of starting
/// again, it reverses when it reaches min/max.
/// Alternatively, make this `finite` so that
/// it stops when its bound is reached.
/// See also @Cycled if this is used in SwiftUI.
@propertyWrapper
public struct CycledRaw<T:SignedNumeric & Comparable> {
public enum Mode {
case repeatable, reversible, finite
}
private let min:T
private let max:T
private let mode:Mode
private var reversible:Bool {
mode == .reversible
}
private var finite:Bool {
mode == .finite
}
private var shouldReverse:Bool = false
private var number:T
public var wrappedValue:T {
get { return number }
set {
guard newValue != T.zero else { return }
let value = shouldReverse ? -newValue : newValue
let newNumber = number + value
if newValue < T.zero { // decrementing
if newNumber < min {
if reversible || finite {
number = min
} else {
number = max
}
} else {
number = newNumber
}
} else { // incrementing
if newNumber > max {
if reversible || finite {
number = max
} else {
number = min
}
} else {
number = newNumber
}
}
if reversible && (number == min || number == max) {
shouldReverse.toggle()
}
}
}
public init(min:T = T.zero, max:T, mode:Mode? = nil) {
guard min < max else {
preconditionFailure("Attempt to initialize @Cycled property wrapper with min value that is greater than or equal to max value.")
}
self.min = min
self.max = max
self.mode = mode ?? .repeatable
self.number = min
}
public init(wrappedValue startingAt:T, min:T = T.zero, max:T, mode:Mode? = nil) {
guard min < max else {
preconditionFailure("Attempt to initialize @Cycled property wrapper with min value that is greater than or equal to max value.")
}
guard startingAt >= min && startingAt <= max else {
preconditionFailure("Attempt to initialize @Cycled property wrapper with initial start value (\(startingAt)) that is not within min (\(min)) and max (\(max)) values inclusive.")
}
self.min = min
self.max = max
self.mode = mode ?? .repeatable
self.number = startingAt
}
public var atMin:Bool {
wrappedValue <= min
}
public var atMax:Bool {
wrappedValue >= max
}
}
/// Property that stores a closure, initially running
/// that closure and storing the return value as the
/// projected value of that type. This supports both
/// immediate use of the returned "projected" value
/// (e.g. "$foo") and the ability to rerun/refresh the
/// closure (e.g. "foo()"). The result of refreshing
/// may be used in a local variable (keeping the original
/// projected value intact) or assigned directly back to
/// the projected value, to update it (e.g. "$foo = foo()").
/// Alternatively, assign a new closure to this property
/// to update both the refreshable closure and projected value.
@propertyWrapper
public struct Refreshable<T> {
public typealias Closure = ()->T
private var closure:Closure
public var projectedValue:T
public var wrappedValue:Closure {
get { return closure }
set {
closure = newValue
projectedValue = self.closure()
}
}
public init(wrappedValue closure:@escaping Closure) {
self.closure = closure
self.projectedValue = closure()
}
}
|
mit
|
cec548cc8ea741621c4323dfef264c36
| 34.301325 | 189 | 0.574149 | 4.655459 | false | false | false | false |
josve05a/wikipedia-ios
|
Wikipedia/Code/DiffHeaderExtendedView.swift
|
2
|
3953
|
import UIKit
protocol DiffHeaderActionDelegate: class {
func tappedUsername(username: String)
func tappedRevision(revisionID: Int)
}
class DiffHeaderExtendedView: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet var stackView: UIStackView!
@IBOutlet var summaryView: DiffHeaderSummaryView!
@IBOutlet var editorView: DiffHeaderEditorView!
@IBOutlet var compareView: DiffHeaderCompareView!
@IBOutlet var divViews: [UIView]!
@IBOutlet var summaryDivView: UIView!
@IBOutlet var editorDivView: UIView!
@IBOutlet var compareDivView: UIView!
private var viewModel: DiffHeaderViewModel?
weak var delegate: DiffHeaderActionDelegate? {
get {
return editorView.delegate
}
set {
editorView.delegate = newValue
compareView.delegate = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
Bundle.main.loadNibNamed(DiffHeaderExtendedView.wmf_nibName(), owner: self, options: nil)
addSubview(contentView)
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
func configureHeight(beginSquishYOffset: CGFloat, scrollYOffset: CGFloat) {
guard let viewModel = viewModel else {
return
}
switch viewModel.headerType {
case .compare:
compareView.configureHeight(beginSquishYOffset: beginSquishYOffset, scrollYOffset: scrollYOffset)
default: break
}
}
func update(_ new: DiffHeaderViewModel) {
self.viewModel = new
switch new.headerType {
case .compare(let compareViewModel, _):
summaryView.isHidden = true
summaryDivView.isHidden = true
editorView.isHidden = true
editorDivView.isHidden = true
compareView.isHidden = false
compareDivView.isHidden = false
compareView.update(compareViewModel)
case .single(let editorViewModel, let summaryViewModel):
editorView.isHidden = false
editorDivView.isHidden = false
compareView.isHidden = true
compareDivView.isHidden = true
if let summary = summaryViewModel.summary, summary.wmf_hasNonWhitespaceText {
summaryView.isHidden = false
summaryDivView.isHidden = false
summaryView.update(summaryViewModel)
} else {
summaryView.isHidden = true
summaryDivView.isHidden = true
}
editorView.update(editorViewModel)
}
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let summaryConvertedPoint = self.convert(point, to: summaryView)
if summaryView.point(inside: summaryConvertedPoint, with: event) {
return true
}
let editorConvertedPoint = self.convert(point, to: editorView)
if editorView.point(inside: editorConvertedPoint, with: event) {
return true
}
let compareConvertedPoint = self.convert(point, to: compareView)
if compareView.point(inside: compareConvertedPoint, with: event) {
return true
}
return false
}
}
extension DiffHeaderExtendedView: Themeable {
func apply(theme: Theme) {
backgroundColor = theme.colors.paperBackground
summaryView.apply(theme: theme)
editorView.apply(theme: theme)
compareView.apply(theme: theme)
for view in divViews {
view.backgroundColor = theme.colors.chromeShadow
}
}
}
|
mit
|
407ab9fcefc651a75181d25746084bec
| 30.624 | 109 | 0.619024 | 5.437414 | false | false | false | false |
abitofalchemy/auralML
|
Sandbox/STBlueMS_iOS/W2STApp/MainApp/Demo/BlueVoice/ASREngine/Google/BlueVoiceGoogleASREngine.swift
|
1
|
11078
|
/*
* Copyright (c) 2017 STMicroelectronics – All rights reserved
* The STMicroelectronics corporate logo is a trademark of STMicroelectronics
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name nor trademarks of STMicroelectronics International N.V. nor any other
* STMicroelectronics company nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* - All of the icons, pictures, logos and other images that are provided with the source code
* in a directory whose title begins with st_images may only be used for internal purposes and
* shall not be redistributed to any third party or modified in any way.
*
* - Any redistributions in binary form shall not include the capability to display any of the
* icons, pictures, logos and other images that are provided with the source code in a directory
* whose title begins with st_images.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*/
import Foundation
import UIKit
/// Use the Google speech API to translate the voice to text
public class BlueVoiceGoogleASREngine: BlueVoiceASREngine,
BlueVoiceGoogleKeyDelegate{
private static let ASR_KEY_PREFERENCE = "BlueVoiceGoogleASREngine.ASR_KEY";
private static let ASR_KEY_LENGHT = 39;
/// result with a confidence lower that this value will be discarded
private static let MIN_CONFIDENCE = Float(0.75);
public let needAuthKey = true;
public let hasContinuousRecognizer = false;
public let name = "Google™";
private let mSamplingRateHz:UInt;
/// string key to use during the google request
private var mAsrKey:String?;
/// voice language
private let mLanguage:BlueVoiceLangauge;
/// Check that the string has a valid format to be an api key,
/// it return the valid key string or nil if the string is not a valid key
///
/// - Parameter asrKey: key to test
/// - Returns: nil if is not a valid key, otherwise the valid key
private static func synitizeAsrKey(_ asrKey:String?) -> String?{
if(asrKey?.characters.count==ASR_KEY_LENGHT){
return asrKey;
}else{
return nil;
}//if let
}
/// convert the language in the url string parameter, if the language is
/// unknow the english will be used
///
/// - Parameter lang: voice language
/// - Returns: string to use in the request url
private static func getLanguageParamiter(lang: BlueVoiceLangauge)-> String{
switch lang {
case .ENGLISH:
return "en-US";
case .ITALIAN:
return "it-IT";
case .FRENCH:
return "fr-FR"
case .SPANISH:
return "es-ES";
case .GERMAN:
return "de-DE";
case .PORTUGUESE:
return "pr-PR";
// default:
// return "en-EN"
}
}
/// build the request url
///
/// - Parameters:
/// - language: voice language
/// - key: user key
/// - Returns: url where send the audio data
private static func getRequestUrl(_ language:BlueVoiceLangauge, _ key:String)->URL?{
let langStr = getLanguageParamiter(lang: language);
return URL(string:"https://www.google.com/speech-api/v2/recognize?xjerr=1&client=chromium&lang="+langStr+"&key="+key);
}
init(language:BlueVoiceLangauge, samplingRateHz:UInt){
mLanguage=language;
mSamplingRateHz=samplingRateHz;
mAsrKey=loadAsrKey()
}
func hasLoadedAuthKey() ->Bool{
if(mAsrKey==nil){
mAsrKey = loadAsrKey();
}
return mAsrKey != nil;
}
public func getAuthKeyDialog()->UIViewController?{
let storyBoard = UIStoryboard(name: "BlueVoice", bundle:nil )
let viewController = storyBoard.instantiateViewController(withIdentifier: "GoogleAsrKeyViewController") as! BlueVoiceGoogleASRKeyViewController;
viewController.delegate=self;
return viewController;
}
func startListener(){}
func stopListener(){}
func destroyListener(){}
/// conver the audio to text
///
/// - Parameters:
/// - audio: audio to send
/// - callback: object to notify when the answer is ready
/// - Returns: true if the request is send correctly
func sendASRRequest(audio:Data, callback: BlueVoiceAsrRequestCallback) -> Bool{
guard mAsrKey != nil else{
return false;
}
let url = BlueVoiceGoogleASREngine.getRequestUrl(mLanguage,mAsrKey!);
if(url == nil){
return false;
}
var request = URLRequest(url: url!,
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 10.0);
request.httpMethod="POST";
request.setValue("audio/l16; rate=\(mSamplingRateHz)", forHTTPHeaderField: "Content-Type");
let session = URLSession(configuration: URLSessionConfiguration.default);
//start the request and call parseResponseData when it is ready
let task = session.uploadTask(with: request, from: audio, completionHandler:
{(responseData:Data?,response:URLResponse?,error:Error?) in
self.parseResponseData(responseData: responseData, respose: response, error: error, callback: callback);
})
task.resume();
return true;
}
/// function call when the http response is ready
///
/// - Parameters:
/// - responseData: response data
/// - respose: response header
/// - error: response error
/// - callback: object where notify the response results
private func parseResponseData(responseData:Data?,respose:URLResponse?,error:Error?,callback: BlueVoiceAsrRequestCallback){
guard error==nil else{
print(error!.localizedDescription);
callback.onAsrRequestFail(error: .NETWORK_PROBLEM);
return;
}
if let resp = (respose as! HTTPURLResponse?){
if(resp.statusCode != 200){
callback.onAsrRequestFail(error: .REQUEST_FAILED);
return;
}
}
guard responseData != nil else{
callback.onAsrRequestFail(error: .REQUEST_FAILED);
return;
}
let results = extractResults(data: responseData);
let bestResults = getBestConfidenceResults(results);
if let (confidence,text) = bestResults{
print("BestResult: \(text) conf: \(confidence)")
if(confidence>=BlueVoiceGoogleASREngine.MIN_CONFIDENCE){
callback.onAsrRequestSuccess(withText: text);
}else{
callback.onAsrRequestFail(error: .LOW_CONFIDENCE)
}
}else{
callback.onAsrRequestFail(error: .NOT_RECOGNIZED)
}
}
/// function that parse the json response and extract a list of confidence and strings
///
/// - Parameter data: json response
/// - Returns: list of confidence and string or nil if the parse fail
private func extractResults(data:Data?)->[(Float,String)]?{
var retValue:[(Float,String)] = Array();
do{
var respStr = String(data: data!, encoding: .utf8);
//the fist line of the response is an empty json.. remove it to parse
//the real response
respStr = respStr?.replacingOccurrences(of: "{\"result\":[]}", with:"")
respStr = respStr?.trimmingCharacters(in: .controlCharacters);
print(respStr!)
let respStrData = respStr?.data(using: .utf8);
if(respStr == nil){
return nil;
}
let json = try JSONSerialization.jsonObject(with: respStrData!) as? [String: Any];
let retult = json?["result"] as? [[String:Any]];
let alternative = retult?.first?["alternative"] as? [[String:Any]];
if(alternative == nil){
return nil;
}
for transcript in alternative!{
let text = transcript["transcript"] as! String;
let confidence = transcript["confidence"] as! Float;
retValue.append((confidence,text));
}
}catch let error as NSError{
print (error.debugDescription)
print (error.description);
return nil;
}
return retValue;
}
/// sort the result in decreasing order using the float component ->
/// in first position the value with the best confidence
///
/// - Parameter results: list to sort
/// - Returns: sorted list, with the best confidece value as the first paramiters
func getBestConfidenceResults(_ results:[(Float,String)]?)->(Float,String)?{
let sortResults = results?.sorted(by: {$0.0 > $1.0});
return sortResults?.first;
}
//////////////////BlueVoiceGoogleKeyDelegate///////////////////////////////
public func loadAsrKey()->String?{
let userPref = UserDefaults.standard;
let langString = userPref.string(forKey: BlueVoiceGoogleASREngine.ASR_KEY_PREFERENCE);
return BlueVoiceGoogleASREngine.synitizeAsrKey(langString);
}
public func storeAsrKey(_ asrKey:String){
let userPref = UserDefaults.standard;
if let checkedKey = BlueVoiceGoogleASREngine.synitizeAsrKey(asrKey){
mAsrKey=checkedKey;
userPref.setValue(checkedKey, forKey:BlueVoiceGoogleASREngine.ASR_KEY_PREFERENCE);
}
}
}
|
bsd-3-clause
|
c416781276d8c86915a56dbe7370337b
| 37.72028 | 152 | 0.628951 | 4.606489 | false | false | false | false |
adrfer/swift
|
test/SILGen/generic_closures.swift
|
1
|
5346
|
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | FileCheck %s
import Swift
var zero: Int
// CHECK-LABEL: sil hidden @_TF16generic_closures28generic_nondependent_context{{.*}}
func generic_nondependent_context<T>(x: T, y: Int) -> Int {
var y = y
func foo() -> Int { return y }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures28generic_nondependent_context{{.*}} : $@convention(thin) (@owned @box Int) -> Int
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo()
}
// CHECK-LABEL: sil hidden @_TF16generic_closures15generic_capture{{.*}}
func generic_capture<T>(x: T) -> Any.Type {
func foo() -> Any.Type { return T.self }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures15generic_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick protocol<>.Type
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo()
}
// CHECK-LABEL: sil hidden @_TF16generic_closures20generic_capture_cast{{.*}}
func generic_capture_cast<T>(x: T, y: Any) -> Bool {
func foo(a: Any) -> Bool { return a is T }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures20generic_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in protocol<>) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo(y)
}
protocol Concept {
var sensical: Bool { get }
}
// CHECK-LABEL: sil hidden @_TF16generic_closures29generic_nocapture_existential{{.*}}
func generic_nocapture_existential<T>(x: T, y: Concept) -> Bool {
func foo(a: Concept) -> Bool { return a.sensical }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures29generic_nocapture_existential{{.*}} : $@convention(thin) (@in Concept) -> Bool
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]
return foo(y)
}
// CHECK-LABEL: sil hidden @_TF16generic_closures25generic_dependent_context{{.*}}
func generic_dependent_context<T>(x: T, y: Int) -> T {
func foo() -> T { return x }
// CHECK: [[FOO:%.*]] = function_ref @_TFF16generic_closures25generic_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@out τ_0_0, @owned @box τ_0_0) -> ()
// CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>
return foo()
}
enum Optionable<T> {
case Some(T)
case None
}
class NestedGeneric<U> {
class func generic_nondependent_context<T>(x: T, y: Int, z: U) -> Int {
func foo() -> Int { return y }
return foo()
}
class func generic_dependent_inner_context<T>(x: T, y: Int, z: U) -> T {
func foo() -> T { return x }
return foo()
}
class func generic_dependent_outer_context<T>(x: T, y: Int, z: U) -> U {
func foo() -> U { return z }
return foo()
}
class func generic_dependent_both_contexts<T>(x: T, y: Int, z: U) -> (T, U) {
func foo() -> (T, U) { return (x, z) }
return foo()
}
// CHECK-LABEL: sil hidden @_TFC16generic_closures13NestedGeneric20nested_reabstraction{{.*}}
// CHECK: [[REABSTRACT:%.*]] = function_ref @_TTRG__rXFo__dT__XFo_iT__iT__
// CHECK: partial_apply [[REABSTRACT]]<U, T>
func nested_reabstraction<T>(x: T) -> Optionable<() -> ()> {
return .Some({})
}
}
// <rdar://problem/15417773>
// Ensure that nested closures capture the generic parameters of their nested
// context.
// CHECK: sil hidden @_TF16generic_closures25nested_closure_in_generic{{.*}} : $@convention(thin) <T> (@out T, @in T) -> ()
// CHECK: function_ref [[OUTER_CLOSURE:@_TFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_]]
// CHECK: sil shared [[OUTER_CLOSURE]] : $@convention(thin) <T> (@out T, @inout_aliasable T) -> ()
// CHECK: function_ref [[INNER_CLOSURE:@_TFFF16generic_closures25nested_closure_in_genericurFxxU_FT_Q_U_FT_Q_]]
// CHECK: sil shared [[INNER_CLOSURE]] : $@convention(thin) <T> (@out T, @inout_aliasable T) -> () {
func nested_closure_in_generic<T>(x:T) -> T {
return { { x }() }()
}
// CHECK-LABEL: sil hidden @_TF16generic_closures16local_properties
func local_properties<T>(inout t: T) {
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $T
var prop: T {
get {
return t
}
set {
t = newValue
}
}
// CHECK: [[GETTER_REF:%[0-9]+]] = function_ref [[GETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@out τ_0_0, @owned @box τ_0_0) -> ()
// CHECK: apply [[GETTER_REF]]
t = prop
// CHECK: [[SETTER_REF:%[0-9]+]] = function_ref [[SETTER_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0, @owned @box τ_0_0) -> ()
// CHECK: apply [[SETTER_REF]]
prop = t
var prop2: T {
get {
return t
}
set {
// doesn't capture anything
}
}
// CHECK: [[GETTER2_REF:%[0-9]+]] = function_ref [[GETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@out τ_0_0, @owned @box τ_0_0) -> ()
// CHECK: apply [[GETTER2_REF]]
t = prop2
// CHECK: [[SETTER2_REF:%[0-9]+]] = function_ref [[SETTER2_CLOSURE:@_TFF16generic_closures16local_properties.*]] : $@convention(thin) <τ_0_0> (@in τ_0_0) -> ()
// CHECK: apply [[SETTER2_REF]]
prop2 = t
}
protocol Fooable {
static func foo() -> Bool
}
// <rdar://problem/16399018>
func shmassert(@autoclosure f: () -> Bool) {}
// CHECK-LABEL: sil hidden @_TF16generic_closures21capture_generic_param
func capture_generic_param<A: Fooable>(x: A) {
shmassert(A.foo())
}
|
apache-2.0
|
4d10f807b8aa330e9470572507d00658
| 35.258503 | 181 | 0.613508 | 3.113318 | false | false | false | false |
mcomisso/hellokiwi
|
kiwi/AppDelegate.swift
|
1
|
11828
|
//
// AppDelegate.swift
// kiwi
//
// Created by Matteo Comisso on 03/01/15.
// Copyright (c) 2015 Blue-Mate. All rights reserved.
//
import UIKit
import Fabric
import Crashlytics
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var window: UIWindow?
var locationManager: CLLocationManager?
var beaconRegion: CLBeaconRegion?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let applicationID = "appId"
let clientKey = "clientKey"
Fabric.with([Crashlytics()])
Parse.setApplicationId(applicationID, clientKey: clientKey)
PFAnalytics.trackAppOpenedWithLaunchOptionsInBackground(launchOptions, block: nil)
PFFacebookUtils.initializeFacebook()
//Register for notifications
if((UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8.0) {
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))
} else {
// iOS7 compatibility
application.registerForRemoteNotificationTypes(UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound)
}
//MARK:- CoreLocation
let uuidString = "96A1736B-11FC-85C3-1762-80DF658F0B29"
let beaconIdentifier = "com.kiwi.beaconRegion"
let beaconUUID:NSUUID? = NSUUID(UUIDString: uuidString)
beaconRegion = CLBeaconRegion(proximityUUID: beaconUUID, identifier: beaconIdentifier)
locationManager = CLLocationManager()
locationManager!.delegate = self
if CLLocationManager.locationServicesEnabled() {
if(locationManager!.respondsToSelector("requestAlwaysAuthorization")) {
locationManager!.requestAlwaysAuthorization()
}
}
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
return FBAppCall.handleOpenURL(url, sourceApplication: sourceApplication)
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
locationManager!.startRangingBeaconsInRegion(beaconRegion)
FBAppEvents.activateApp()
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
locationManager!.stopRangingBeaconsInRegion(beaconRegion)
}
}
//BEACON EXTENSION
extension AppDelegate: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case CLAuthorizationStatus.Authorized:
locationManager!.startMonitoringForRegion(beaconRegion)
case CLAuthorizationStatus.NotDetermined, CLAuthorizationStatus.Denied:
println("not determined or denied")
case CLAuthorizationStatus.AuthorizedWhenInUse:
println("CLAuthorizationStatus.AuthorizedWhenInUse")
locationManager!.startMonitoringForRegion(beaconRegion)
case CLAuthorizationStatus.Restricted:
println("CLAuthorizationStatus.Restricted")
}
}
func locationManager(manager: CLLocationManager!, didDetermineState state: CLRegionState, forRegion region: CLRegion!) {
switch state {
case CLRegionState.Inside:
self.locationManager?.startRangingBeaconsInRegion(beaconRegion)
self.locationManager?.startMonitoringVisits()
case CLRegionState.Outside:
self.locationManager?.stopRangingBeaconsInRegion(beaconRegion)
self.locationManager?.stopMonitoringVisits()
case CLRegionState.Unknown:
self.locationManager?.stopMonitoringForRegion(beaconRegion)
self.locationManager?.stopRangingBeaconsInRegion(beaconRegion)
self.locationManager?.startMonitoringForRegion(beaconRegion)
self.locationManager?.startMonitoringVisits()
default:
self.locationManager?.startMonitoringForRegion(beaconRegion)
self.locationManager?.startMonitoringVisits()
}
}
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
if (region.identifier == "com.kiwi.beaconRegion") {
let notification = UILocalNotification()
let userDefaults = NSUserDefaults.standardUserDefaults()
var alertBody: String?
if !userDefaults.boolForKey("firstNotification") {
alertBody = "Benvenuto in H-Farm"
userDefaults.setBool(true, forKey: "firstNotification")
userDefaults.synchronize()
} else {
alertBody = "Sei entrato in un'altra area del progetto Kiwi"
}
notification.alertBody = alertBody
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().presentLocalNotificationNow(notification)
}
println("Entered in zone \(region.description), Start ranging beacons...")
locationManager!.startRangingBeaconsInRegion(region as CLBeaconRegion)
}
func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) {
println("Stopping ranging...")
locationManager!.stopRangingBeaconsInRegion(region as CLBeaconRegion)
}
func locationManager(manager: CLLocationManager!, didVisit visit: CLVisit!) {
//Save on parse
//var visitPFObject = PFObject(className: "")?
println(visit.description)
}
//Ranged beacons: Switch and send signals if the found beacon is correct
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {
var closestBeacon: CLBeacon?
let knownBeacons = beacons.filter{$0.proximity != CLProximity.Unknown}
if (PFUser.currentUser() != nil) {
if (knownBeacons.count > 0) {
closestBeacon = beacons.first as? CLBeacon
//println("ClosestBeacon \(closestBeacon?.description)")
let closestTupleMajMin = (closestBeacon?.major as Int, closestBeacon?.minor as Int)
switch closestTupleMajMin {
case (158, 23524):
//major:158, minor:23524
let alertBody = "Hai trovato Marco"
//self.sendLocalNotification(alertBody)
NSNotificationCenter.defaultCenter().postNotificationName("BMFoundPOI", object: nil, userInfo: ["poi":"marco", "alertBody":alertBody])
case (150, 47059):
//major:150, minor:47059
let alertBody = "Hai trovato Edoardo"
// self.sendLocalNotification(alertBody)
NSNotificationCenter.defaultCenter().postNotificationName("BMFoundPOI", object: nil, userInfo: ["poi":"edoardo", "alertBody":alertBody])
case (406, 65259):
//major:406, minor:65259
let alertBody = "Hai trovato Ennio"
// self.sendLocalNotification(alertBody)
NSNotificationCenter.defaultCenter().postNotificationName("BMFoundPOI", object: nil, userInfo: ["poi":"ennio", "alertBody":alertBody])
case (333, 24796), (14, 32380):
//major:333, minor:24796
let alertBody = "Benvenuto in H-Farm"
// self.sendLocalNotification(alertBody)
NSNotificationCenter.defaultCenter().postNotificationName("BMFoundPOI", object: nil, userInfo: ["poi":"hfarm", "alertBody":alertBody])
case (126, 43175):
//major:126, minor:43175
let alertBody = "Ti va un caffè?"
// self.sendLocalNotification(alertBody)
NSNotificationCenter.defaultCenter().postNotificationName("BMFoundPOI", object: nil, userInfo: ["poi":"serra", "alertBody":alertBody])
case (401, 15780):
//major:401, minor:15780
let alertBody = "Le presentazioni saranno svolte qui"
// self.sendLocalNotification(alertBody)
NSNotificationCenter.defaultCenter().postNotificationName("BMFoundPOI", object: nil, userInfo: ["poi":"convivium", "alertBody":alertBody])
case (189, 41487):
//major:189, minor:41487
let alertBody = "La sede di Life"
// self.sendLocalNotification(alertBody)
NSNotificationCenter.defaultCenter().postNotificationName("BMFoundPOI", object: nil, userInfo: ["poi":"life", "alertBody":alertBody])
default:
println("Not the correct beacon")
}
}
}
}
//ERROR HANDLING
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("FAIL \(error.localizedDescription, error.localizedFailureReason)")
}
func locationManager(manager: CLLocationManager!, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!) {
println("FAIL \(error.localizedDescription, error.localizedFailureReason, region.description)")
}
func locationManager(manager: CLLocationManager!, rangingBeaconsDidFailForRegion region: CLBeaconRegion!, withError error: NSError!) {
println("FAIL \(error.localizedDescription, error.localizedFailureReason, region.description)")
}
}
|
apache-2.0
|
56d02f369ba97b2ac6260c10e60664e1
| 47.871901 | 285 | 0.651983 | 6.049616 | false | false | false | false |
ArsalanWahid/yemekye
|
yemekye/singleton/resturantData.swift
|
1
|
2197
|
//
// resturantData.swift
// yemekye
//
// Created by Arsalan Wahid Asghar on 12/9/17.
// Copyright © 2017 Arsalan Wahid Asghar. All rights reserved.
//
import UIKit
//MARK:- Singleton
class RData{
static let Rdata = RData()
var resturants:[Resturant]
let kfc1 = UIImage(named: "krunchburger")
let kfc2 = UIImage(named:"mightyzinger")
let kfc3 = UIImage(named:"zinger")
let kfclogo = UIImage(named: "kfc")
init() {
guard let mealKFC1 = Meal(name: "Mighty Burger", photo: kfc1, rating: 2) else{
fatalError("Something bad happened while making meal object")}
guard let mealKFC2 = Meal(name: "Zinger Love", photo: kfc2, rating: 4) else{
fatalError("Something bad happened while making meal object")
}
guard let mealKFC3 = Meal(name: "Random Stuff", photo: kfc3, rating: 5) else{
fatalError("Something bad happened while presenting tasty salad")
}
let macdonalslogo = UIImage(named: "mcdonalds")
let kfcMenu = Menu(meals: [mealKFC1,mealKFC2,mealKFC3])
let KFC = Resturant(name: "Kfc", menu: kfcMenu, timings: [("11am","11pm"),("12am","3am")], resturantImage: kfclogo!, status: "open", address: "karachi Pakistan", phonenumber: "0511555113",rating: 5)
let KFC1 = Resturant(name: "McDonalds", menu: kfcMenu, timings: [("6am","9pm")], resturantImage: macdonalslogo!, status: "open", address: "karachi Pakistan", phonenumber: "0511555113",rating: 4)
let KFC2 = Resturant(name: "Dominos", menu: kfcMenu, timings: [("1am","3pm")], resturantImage: kfclogo!, status: "open", address: "karachi Pakistan", phonenumber: "0511555113", rating: 4)
let KFC3 = Resturant(name: "Subway", menu: kfcMenu, timings: [("12am","11pm")], resturantImage: kfclogo!, status: "open", address: "karachi Pakistan", phonenumber: "0511555113",rating: 3)
let karachi = City(name: "karachi", resturants: [KFC!])
_ = Country(name: "pakistan", cities: [karachi])
self.resturants = [KFC!,KFC1!,KFC2!,KFC3!]
}
}
|
apache-2.0
|
792e5d1026fab13ec263f666bd3e7327
| 36.862069 | 206 | 0.6102 | 3.368098 | false | false | false | false |
auth0/Lock.iOS-OSX
|
LockTests/PasswordPolicyValidatorSpec.swift
|
2
|
3460
|
// PasswordPolicyValidatorSpec.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.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 Quick
import Nimble
@testable import Lock
class PasswordPolicyValidatorSpec: QuickSpec {
override func spec() {
it("should return no error when password is allowed by policy") {
let policy = passingPolicy(withConditionCount: 1)
let validator = PasswordPolicyValidator(policy: policy)
expect(validator.validate(password)).to(beNil())
}
it("should return no error when password is allowed by policy") {
let policy = failingPolicy(withConditionCount: 1)
let validator = PasswordPolicyValidator(policy: policy)
expect(validator.validate(password)).toNot(beNil())
}
it("should return policy output on error") {
let policy = failingPolicy(withConditionCount: 1)
let validator = PasswordPolicyValidator(policy: policy)
let error = validator.validate(password) as? InputValidationError
expect(error).toNot(beNil())
if case .passwordPolicyViolation(let result) = error! {
expect(result.first?.valid) == false
expect(result.first?.message) == "MOCK"
} else {
fail("Invalid error. Expected PasswordPolicyViolation")
}
}
it("should return all policy output on error") {
let policy = failingPolicy(withConditionCount: 2)
let validator = PasswordPolicyValidator(policy: policy)
let error = validator.validate(password) as? InputValidationError
expect(error).toNot(beNil())
if case .passwordPolicyViolation(let result) = error! {
expect(result).to(haveCount(2))
} else {
fail("Invalid error. Expected PasswordPolicyViolation")
}
}
}
}
private func failingPolicy(withConditionCount count: Int) -> PasswordPolicy {
var rules: [Rule] = []
(1...count).forEach { _ in rules.append(MockRule(valid: false)) }
return PasswordPolicy(name: "custom", rules: rules)
}
private func passingPolicy(withConditionCount count: Int) -> PasswordPolicy {
var rules: [Rule] = []
(1...count).forEach { _ in rules.append(MockRule(valid: true)) }
return PasswordPolicy(name: "custom", rules: rules)
}
|
mit
|
c52a05b3ae24f740920501e9084a6958
| 42.25 | 80 | 0.671965 | 4.613333 | false | false | false | false |
lenglengiOS/BuDeJie
|
百思不得姐/Pods/Charts/Charts/Classes/Data/CandleChartDataSet.swift
|
20
|
3145
|
//
// CandleChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class CandleChartDataSet: LineScatterCandleChartDataSet
{
/// the width of the candle-shadow-line in pixels.
///
/// **default**: 3.0
public var shadowWidth = CGFloat(1.5)
/// the space between the candle entries
///
/// **default**: 0.1 (10%)
private var _bodySpace = CGFloat(0.1)
/// the color of the shadow line
public var shadowColor: UIColor?
/// use candle color for the shadow
public var shadowColorSameAsCandle = false
/// color for open <= close
public var decreasingColor: UIColor?
/// color for open > close
public var increasingColor: UIColor?
/// Are decreasing values drawn as filled?
public var decreasingFilled = false
/// Are increasing values drawn as filled?
public var increasingFilled = true
public required init()
{
super.init()
}
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
}
internal override func calcMinMax(start start: Int, end: Int)
{
if (yVals.count == 0)
{
return
}
var entries = yVals as! [CandleChartDataEntry]
var endValue : Int
if end == 0 || end >= entries.count
{
endValue = entries.count - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = end
_yMin = DBL_MAX
_yMax = -DBL_MAX
for (var i = start; i <= endValue; i++)
{
let e = entries[i]
if (e.low < _yMin)
{
_yMin = e.low
}
if (e.high > _yMax)
{
_yMax = e.high
}
}
}
/// the space that is left out on the left and right side of each candle,
/// **default**: 0.1 (10%), max 0.45, min 0.0
public var bodySpace: CGFloat
{
set
{
if (newValue < 0.0)
{
_bodySpace = 0.0
}
else if (newValue > 0.45)
{
_bodySpace = 0.45
}
else
{
_bodySpace = newValue
}
}
get
{
return _bodySpace
}
}
/// Is the shadow color same as the candle color?
public var isShadowColorSameAsCandle: Bool { return shadowColorSameAsCandle }
/// Are increasing values drawn as filled?
public var isIncreasingFilled: Bool { return increasingFilled; }
/// Are decreasing values drawn as filled?
public var isDecreasingFilled: Bool { return decreasingFilled; }
}
|
apache-2.0
|
90617c11a98fd89200e4bf4c688cd5b8
| 22.654135 | 81 | 0.519873 | 4.638643 | false | false | false | false |
aamays/Twitter
|
Twitter/Utilities/AppUtils.swift
|
1
|
2421
|
//
// AppUtils.swift
// Twitter
//
// Created by Amay Singhal on 10/2/15.
// Copyright © 2015 ple. All rights reserved.
//
import Foundation
import UIKit
struct AppUtils {
static func getUserDirectory() -> String {
let userDir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
return userDir[0]
}
static func getUserInfoArchiveFilePathForUserId(id: Int) -> String {
return "\(AppUtils.getUserDirectory())/\(id)"
}
static func updateTextAndTintColorForNavBar(navController: UINavigationController, tintColor: UIColor?, textColor: UIColor?) {
navController.navigationBar.barTintColor = tintColor ?? AppConstants.TwitterBlueColor
navController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: textColor ?? AppConstants.ApplicationBarTintColor]
}
static func getAttributedStringForActionButtons(message: String, icon: FontasticIconType, iconTextColor: UIColor = UIColor.darkGrayColor(), withIconSize size: CGFloat = 15, andBaseLine baseline: CGFloat = -3) -> NSAttributedString {
let attributedString = NSMutableAttributedString()
if let font = UIFont(name: FontasticIcons.FontName, size: size) {
let attrs = [NSFontAttributeName : font,
NSBaselineOffsetAttributeName: baseline,
NSForegroundColorAttributeName: iconTextColor]
let cautionSign = NSMutableAttributedString(string: icon.rawValue, attributes: attrs)
attributedString.appendAttributedString(cautionSign)
message.characters.count > 0 ? attributedString.appendAttributedString(NSAttributedString(string: " ")) : ()
}
attributedString.appendAttributedString(NSAttributedString(string: message))
return attributedString
}
static func shakeUIView(targetView: UIView, withOffset offset: CGFloat = 5) {
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.07
animation.repeatCount = 1
animation.autoreverses = true
animation.fromValue = NSValue(CGPoint: CGPointMake(targetView.center.x - offset, targetView.center.y))
animation.toValue = NSValue(CGPoint: CGPointMake(targetView.center.x + offset, targetView.center.y))
targetView.layer.addAnimation(animation, forKey: "position")
}
}
|
mit
|
01a85b4e54159a1b96a7dd1e9272d087
| 45.538462 | 236 | 0.724793 | 5.365854 | false | false | false | false |
MetalheadSanya/GtkSwift
|
src/Application.swift
|
1
|
4383
|
import CGTK
import gobjectswift
#if os(Linux)
import Glibc
#endif
public typealias ApplicationActivateCallback = (Application) -> Void
public typealias ApplicationWindowAddedCallback = (Application, Window!) -> Void
public typealias ApplicationWindowRemovedCallback = (Application, Window!) -> Void
public class Application: Object {
internal var n_App: UnsafeMutablePointer<GtkApplication>
internal var _windows = [Window]()
var windows: [Window] {
return _windows
}
public init?(applicationId: String, flags: [ApplicationFlag]) {
let totalFlag = flags.reduce(0) { $0 | $1.rawValue }
n_App = gtk_application_new(applicationId, GApplicationFlags(totalFlag))
super.init(n_Object: unsafeBitCast(n_App, to: UnsafeMutablePointer<GObject>.self))
}
deinit {
g_object_unref (n_App)
}
// MARK: - GApplication
public func run(_ arguments: [String]) -> Int {
return Int(g_application_run (UnsafeMutablePointer<GApplication> (n_App), Int32(arguments.count), arguments.withUnsafeBufferPointer {
let buffer = UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>(allocatingCapacity: $0.count + 1)
buffer.initializeFrom($0.map { $0.withCString(strdup) })
buffer[$0.count] = nil
return buffer
}))
}
public typealias ApplicationActivateNative = @convention(c)(UnsafeMutablePointer<GtkApplication>, gpointer) -> Void
public lazy var activateSignal: Signal<ApplicationActivateCallback, Application, ApplicationActivateNative>
= Signal(obj: self, signal: "activate", c_handler: {
(_, user_data) in
let data = unsafeBitCast(user_data, to: SignalData<Application, ApplicationActivateCallback>.self)
let application = data.obj
let action = data.function
action(application)
})
public typealias ApplicationWindowAddedNative = @convention(c)(UnsafeMutablePointer<GtkApplication>,
UnsafeMutablePointer<GtkWindow>, gpointer) -> Void
/// Emitted when a Window is added to application through Application.addWindow(_:).
public lazy var windowAddedSignal: Signal<ApplicationWindowAddedCallback, Application, ApplicationWindowAddedNative>
= Signal(obj: self, signal: "window-added", c_handler: {
(_, n_Window, user_data) in
let data = unsafeBitCast(user_data, to: SignalData<Application, ApplicationWindowAddedCallback>.self)
let application = data.obj
let window = application._getWindowForNativeWindow(n_Window)
let action = data.function
action(application, window)
})
public typealias ApplicationWindowRemovedNative = @convention(c)(UnsafeMutablePointer<GtkApplication>,
UnsafeMutablePointer<GtkWindow>, gpointer) -> Void
public lazy var windowRemovedSignal: Signal<ApplicationWindowRemovedCallback, Application, ApplicationWindowRemovedNative>
= Signal(obj: self, signal: "window-removed", c_handler: {
(_, n_Window, user_data) in
let data = unsafeBitCast(user_data, to: SignalData<Application, ApplicationWindowRemovedCallback>.self)
let application = data.obj
let window = application._getWindowForNativeWindow(n_Window)
let action = data.function
action(application, window)
})
}
// MARK: - Windows
extension Application {
internal func _getWindowForNativeWindow(_ n_Window: UnsafeMutablePointer<GtkWindow>) -> Window! {
for window in _windows {
if window.n_Window == n_Window {
return window
}
}
return nil
}
internal func _addWindowToApplicationStack(_ window: Window) {
_windows.append(window)
}
public func addWindow(_ window: Window) {
_windows.append(window)
gtk_application_add_window(n_App, window.n_Window)
}
public func removeWindow(_ window: Window) {
if let index = _windows.index(of: window) {
_windows.remove(at: index)
}
gtk_application_remove_window(n_App, window.n_Window)
}
public var activeWindow: Window! {
let n_Window = gtk_application_get_active_window(n_App)
return _getWindowForNativeWindow(n_Window)
}
// TODO: in future
// func windowWithId(id: Int) -> Window? {
// }
}
extension Application: Equatable { }
public func ==(lhs: Application, rhs: Application) -> Bool {
return lhs.n_App == rhs.n_App
}
public enum ApplicationFlag: UInt32 {
case None = 0b00000001
case IsService = 0b00000010
case IsLauncher = 0b00000100
case HandlesOpen = 0b00001000
case HandlesCommandLine = 0b00010000
case SendEnvironent = 0000100000
case NonUnique = 0b01000000
}
|
bsd-3-clause
|
ebcec38e152effdbcbd86f4896308880
| 29.4375 | 135 | 0.74036 | 3.686291 | false | false | false | false |
tectijuana/iOS
|
VargasJuan/Ejercicios/6-27.swift
|
2
|
2625
|
/*
27. Hacer un programa para imprimir la suma, diferencia, producto y
cociente de dos números complejos a + ib y c + id. Usar los siguientes
números complejos como datos:
a) 2 + 3i y 3 + 4i
b) 5 + 7i y 1 + 4i
c) -21 + 3i y 14 + 107i
Vargas Bañuelos Juan Samuel
*/
class NumComplejo {
var R: Double
var I: Double
init(R: Double, I: Double) {
self.R = R
self.I = I
}
func to_string() -> String {
var s: String = ""
s += String(R)
s += (I < 0 ? " - " : " + ")
s += String(abs(I))
s += "i"
return s
}
}
func +(left: NumComplejo, right: NumComplejo) -> NumComplejo {
return NumComplejo(R:(left.R + right.R), I:(left.I + right.I))
}
func -(left: NumComplejo, right: NumComplejo) -> NumComplejo {
return NumComplejo(R:(left.R - right.R), I:(left.I - right.I))
}
func *(left: NumComplejo, right: NumComplejo) -> NumComplejo {
let r = left.R * right.R
let i = (left.R * right.I) + (left.I * right.R)
let i2 = -(left.I * right.I)
return NumComplejo(R:(r + i2), I:i)
}
func /(left: NumComplejo, right: NumComplejo) -> NumComplejo {
let r_u = (left.R * right.R) + (left.I * right.I)
let r_d = (right.R * right.R) + (right.I * right.I)
let r = r_u / r_d
let i_u = (left.I * right.R) - (left.R * right.I)
let i_d = (right.R * right.R) + (right.I * right.I)
let i = i_u / i_d
return NumComplejo(R:r, I:i)
}
let pares_de_numeros = [
[NumComplejo(R:2, I:3), NumComplejo(R:3, I:4)],
[NumComplejo(R:5, I:7), NumComplejo(R:1, I:4)],
[NumComplejo(R:-21, I:3), NumComplejo(R:14, I:107)]
]
for numeros in pares_de_numeros {
// Suma
print("(", terminator:"")
print(numeros[0].to_string(), terminator:"")
print(") + (", terminator:"")
print(numeros[1].to_string(), terminator:"")
print(") = ", terminator:"")
print((numeros[0] + numeros[1]).to_string())
// Diferencia
print("(", terminator:"")
print(numeros[0].to_string(), terminator:"")
print(") - (", terminator:"")
print(numeros[1].to_string(), terminator:"")
print(") = ", terminator:"")
print((numeros[0] - numeros[1]).to_string())
// Producto
print("(", terminator:"")
print(numeros[0].to_string(), terminator:"")
print(") * (", terminator:"")
print(numeros[1].to_string(), terminator:"")
print(") = ", terminator:"")
print((numeros[0] * numeros[1]).to_string())
// Cociente
print("(", terminator:"")
print(numeros[0].to_string(), terminator:"")
print(") / (", terminator:"")
print(numeros[1].to_string(), terminator:"")
print(") = ", terminator:"")
print((numeros[0] / numeros[1]).to_string())
print()
}
|
mit
|
6532476faaaacbe82ef5907d5e4a2868
| 24.960396 | 74 | 0.57971 | 2.686475 | false | false | false | false |
prebid/prebid-mobile-ios
|
InternalTestApp/PrebidMobileDemoRendering/Utilities/IABConsentHelper.swift
|
1
|
4445
|
/* 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 Foundation
import UIKit
class IABConsentHelper {
private var settingUpdates: [NSDictionary]?
private var timer: Timer?
private var nextUpdate = 0
static var isGDPREnabled: Bool {
get {
let userDefaults = UserDefaults.standard
return userDefaults.string(forKey: IABConsentSettingKey.TCF.v2.cmpSdkId) == nil ||
userDefaults.string(forKey: IABConsentSettingKey.TCF.v2.subjectToGDPR) == "1";
}
set {
let userDefaults = UserDefaults.standard
if (newValue) {
userDefaults.removeObject(forKey: IABConsentSettingKey.TCF.v2.cmpSdkId)
userDefaults.removeObject(forKey: IABConsentSettingKey.TCF.v2.subjectToGDPR)
} else {
//just set fake params to disable DGPR
userDefaults.set("123", forKey: IABConsentSettingKey.TCF.v2.cmpSdkId)
userDefaults.set("0", forKey: IABConsentSettingKey.TCF.v2.subjectToGDPR)
}
}
}
func eraseIrrelevantUserDefaults() {
let userDefaults = UserDefaults.standard
if userDefaults.bool(forKey: IABConsentSettingKey.keepSettings) == false {
userDefaults.removeObject(forKey: IABConsentSettingKey.TCF.v1.cmpPresent)
userDefaults.removeObject(forKey: IABConsentSettingKey.TCF.v1.subjectToGDPR)
userDefaults.removeObject(forKey: IABConsentSettingKey.TCF.v1.consentString)
userDefaults.removeObject(forKey: IABConsentSettingKey.TCF.v2.cmpSdkId)
userDefaults.removeObject(forKey: IABConsentSettingKey.TCF.v2.subjectToGDPR)
userDefaults.removeObject(forKey: IABConsentSettingKey.TCF.v2.consentString)
userDefaults.removeObject(forKey: IABConsentSettingKey.usPrivacyString)
}
}
func parseAndApply(consentSettingsString: String) {
guard let iabSettings = try? JSONSerialization.jsonObject(with: consentSettingsString.data(using: .utf8)!, options: []) as? NSDictionary else {
return
}
if let launchOptions = iabSettings["launchOptions"] as? NSDictionary {
apply(iabSettings: launchOptions)
}
if let delay = (iabSettings["updateInterval"] as? NSNumber)?.floatValue,
let updatedOptions = iabSettings["updatedOptions"] as? [NSDictionary],
updatedOptions.count > 0
{
settingUpdates = updatedOptions
timer = Timer.scheduledTimer(timeInterval: TimeInterval(delay), target: self, selector: #selector(onTimerTicked), userInfo: nil, repeats: true)
}
}
@objc private func onTimerTicked(timer: Timer) {
guard let settingUpdates = self.settingUpdates else {
return
}
self.apply(iabSettings: settingUpdates[self.nextUpdate])
self.nextUpdate += 1
if self.nextUpdate >= self.settingUpdates?.count ?? 0 {
self.timer?.invalidate()
self.timer = nil
self.settingUpdates = nil
self.nextUpdate = 0
}
}
func apply(iabSettings: NSDictionary) {
let userDefaults = UserDefaults.standard
let isWithAllowedPrefix: (String) -> Bool = { s in
for prefix in IABConsentSettingKey.allowedPrefixes {
if s.starts(with: prefix) {
return true
}
}
return false
}
for (key, obj) in iabSettings as? [String: NSObject] ?? [:] {
guard isWithAllowedPrefix(key) else {
continue
}
if obj is NSNull {
userDefaults.removeObject(forKey: key)
} else {
userDefaults.set(obj, forKey: key)
}
}
}
}
|
apache-2.0
|
ba75ee416e01f71927256938b956f200
| 38.589286 | 155 | 0.632612 | 4.460765 | false | false | false | false |
justin999/gitap
|
gitap/IssuesTableViewDataSource.swift
|
1
|
1183
|
//
// IssuesTableViewDataSource.swift
// gitap
//
// Created by Koichi Sato on 12/30/16.
// Copyright © 2016 Koichi Sato. All rights reserved.
//
import UIKit
let issesIndexId = "IssuesTableViewCell"
class IssuesTableViewDataSource: NSObject {
var stateController: StateController
init(tableView: UITableView, stateController: StateController) {
self.stateController = stateController
super.init()
tableView.dataSource = self
Utils.registerCell(tableView, nibName: String(describing: FeedsTableViewCell.self), cellId: issesIndexId)
}
}
extension IssuesTableViewDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCell(withIdentifier: issesIndexId, for: indexPath as IndexPath)
let cell = UITableViewCell()
cell.textLabel?.text = "issue name"
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
}
|
mit
|
cfbe312e582716fad3ebd7902dbadfe1
| 29.307692 | 113 | 0.700508 | 4.864198 | false | false | false | false |
shorlander/firefox-ios
|
Client/Frontend/Home/HistoryPanel.swift
|
1
|
25068
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
import XCGLogger
import Deferred
private let log = Logger.browserLogger
private typealias SectionNumber = Int
private typealias CategoryNumber = Int
private typealias CategorySpec = (section: SectionNumber?, rows: Int, offset: Int)
private struct HistoryPanelUX {
static let WelcomeScreenItemTextColor = UIColor.gray
static let WelcomeScreenItemWidth = 170
static let IconSize = 23
static let IconBorderColor = UIColor(white: 0, alpha: 0.1)
static let IconBorderWidth: CGFloat = 0.5
}
private func getDate(_ dayOffset: Int) -> Date {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let nowComponents = (calendar as NSCalendar).components([.year, .month, .day], from: Date())
let today = calendar.date(from: nowComponents)!
return (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.day, value: dayOffset, to: today, options: [])!
}
class HistoryPanel: SiteTableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate?
private var currentSyncedDevicesCount: Int?
var events = [NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged]
var refreshControl: UIRefreshControl?
fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: #selector(HistoryPanel.longPress(_:)))
}()
private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverlayView()
private let QueryLimit = 100
private let NumSections = 5
private let Today = getDate(0)
private let Yesterday = getDate(-1)
private let ThisWeek = getDate(-7)
private var categories: [CategorySpec] = [CategorySpec]() // Category number (index) -> (UI section, row count, cursor offset).
private var sectionLookup = [SectionNumber: CategoryNumber]() // Reverse lookup from UI section to data category.
var syncDetailText = ""
var hasRecentlyClosed: Bool {
return self.profile.recentlyClosedTabs.tabs.count > 0
}
// MARK: - Lifecycle
init() {
super.init(nibName: nil, bundle: nil)
events.forEach { NotificationCenter.default.addObserver(self, selector: #selector(HistoryPanel.notificationReceived(_:)), name: $0, object: nil) }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
events.forEach { NotificationCenter.default.removeObserver(self, name: $0, object: nil) }
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.addGestureRecognizer(longPressRecognizer)
tableView.accessibilityIdentifier = "History List"
updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in
self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Add a refresh control if the user is logged in and the control was not added before. If the user is not
// logged in, remove any existing control but only when it is not currently refreshing. Otherwise, wait for
// the refresh to finish before removing the control.
if profile.hasSyncableAccount() && refreshControl == nil {
addRefreshControl()
} else if refreshControl?.isRefreshing == false {
removeRefreshControl()
}
updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in
self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount)
}
}
@objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return }
let touchPoint = longPressGestureRecognizer.location(in: tableView)
guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return }
if indexPath.section != 0 {
presentContextMenu(for: indexPath)
}
}
// MARK: - History Data Store
func updateNumberOfSyncedDevices(_ count: Int?) {
if let count = count, count > 0 {
syncDetailText = String.localizedStringWithFormat(Strings.SyncedTabsTableViewCellDescription, count)
} else {
syncDetailText = ""
}
self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .automatic)
}
func updateSyncedDevicesCount() -> Success {
return chainDeferred(self.profile.getCachedClientsAndTabs()) { tabsAndClients in
self.currentSyncedDevicesCount = tabsAndClients.count
return succeed()
}
}
func notificationReceived(_ notification: Notification) {
switch notification.name {
case NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory:
if self.profile.hasSyncableAccount() {
resyncHistory()
}
break
case NotificationDynamicFontChanged:
if emptyStateOverlayView.superview != nil {
emptyStateOverlayView.removeFromSuperview()
}
emptyStateOverlayView = createEmptyStateOverlayView()
resyncHistory()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
private func fetchData() -> Deferred<Maybe<Cursor<Site>>> {
return profile.history.getSitesByLastVisit(QueryLimit)
}
private func setData(_ data: Cursor<Site>) {
self.data = data
self.computeSectionOffsets()
}
func resyncHistory() {
profile.syncManager.syncHistory().uponQueue(DispatchQueue.main) { result in
if result.isSuccess {
self.reloadData()
} else {
self.endRefreshing()
}
self.updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in
self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount)
}
}
}
// MARK: - Refreshing TableView
func addRefreshControl() {
let refresh = UIRefreshControl()
refresh.addTarget(self, action: #selector(HistoryPanel.refresh), for: UIControlEvents.valueChanged)
self.refreshControl = refresh
self.tableView.addSubview(refresh)
}
func removeRefreshControl() {
self.refreshControl?.removeFromSuperview()
self.refreshControl = nil
}
func endRefreshing() {
// Always end refreshing, even if we failed!
self.refreshControl?.endRefreshing()
// Remove the refresh control if the user has logged out in the meantime
if !self.profile.hasSyncableAccount() {
self.removeRefreshControl()
}
}
@objc func refresh() {
self.refreshControl?.beginRefreshing()
resyncHistory()
}
override func reloadData() {
self.fetchData().uponQueue(DispatchQueue.main) { result in
if let data = result.successValue {
self.setData(data)
self.tableView.reloadData()
self.updateEmptyPanelState()
}
self.endRefreshing()
}
}
// MARK: - Empty State
private func updateEmptyPanelState() {
if data.count == 0 {
if self.emptyStateOverlayView.superview == nil {
self.tableView.addSubview(self.emptyStateOverlayView)
self.emptyStateOverlayView.snp.makeConstraints { make -> Void in
make.left.right.bottom.equalTo(self.view)
make.top.equalTo(self.view).offset(100)
}
}
} else {
self.tableView.alwaysBounceVertical = true
self.emptyStateOverlayView.removeFromSuperview()
}
}
private func createEmptyStateOverlayView() -> UIView {
let overlayView = UIView()
overlayView.backgroundColor = UIColor.white
let welcomeLabel = UILabel()
overlayView.addSubview(welcomeLabel)
welcomeLabel.text = Strings.HistoryPanelEmptyStateTitle
welcomeLabel.textAlignment = NSTextAlignment.center
welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight
welcomeLabel.textColor = HistoryPanelUX.WelcomeScreenItemTextColor
welcomeLabel.numberOfLines = 0
welcomeLabel.adjustsFontSizeToFitWidth = true
welcomeLabel.snp.makeConstraints { make in
make.centerX.equalTo(overlayView)
// Sets proper top constraint for iPhone 6 in portait and for iPad.
make.centerY.equalTo(overlayView).offset(HomePanelUX.EmptyTabContentOffset).priority(100)
// Sets proper top constraint for iPhone 4, 5 in portrait.
make.top.greaterThanOrEqualTo(overlayView).offset(50)
make.width.equalTo(HistoryPanelUX.WelcomeScreenItemWidth)
}
return overlayView
}
// MARK: - TableView Row Helpers
func computeSectionOffsets() {
var counts = [Int](repeating: 0, count: NumSections)
// Loop over all the data. Record the start of each "section" of our list.
for i in 0..<data.count {
if let site = data[i] {
counts[categoryForDate(site.latestVisit!.date) + 1] += 1
}
}
var section = 0
var offset = 0
self.categories = [CategorySpec]()
for i in 0..<NumSections {
let count = counts[i]
if i == 0 {
sectionLookup[section] = i
section += 1
}
if count > 0 {
log.debug("Category \(i) has \(count) rows, and thus is section \(section).")
self.categories.append((section: section, rows: count, offset: offset))
sectionLookup[section] = i
offset += count
section += 1
} else {
log.debug("Category \(i) has 0 rows, and thus has no section.")
self.categories.append((section: nil, rows: 0, offset: offset))
}
}
}
fileprivate func siteForIndexPath(_ indexPath: IndexPath) -> Site? {
let offset = self.categories[sectionLookup[indexPath.section]!].offset
return data[indexPath.row + offset]
}
private func categoryForDate(_ date: MicrosecondTimestamp) -> Int {
let date = Double(date)
if date > (1000000 * Today.timeIntervalSince1970) {
return 0
}
if date > (1000000 * Yesterday.timeIntervalSince1970) {
return 1
}
if date > (1000000 * ThisWeek.timeIntervalSince1970) {
return 2
}
return 3
}
private func isInCategory(_ date: MicrosecondTimestamp, category: Int) -> Bool {
return self.categoryForDate(date) == category
}
// UI sections disappear as categories empty. We need to translate back and forth.
private func uiSectionToCategory(_ section: SectionNumber) -> CategoryNumber {
for i in 0..<self.categories.count {
if let s = self.categories[i].section, s == section {
return i
}
}
return 0
}
private func categoryToUISection(_ category: CategoryNumber) -> SectionNumber? {
return self.categories[category].section
}
// MARK: - TableView Delegate / DataSource
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.accessoryType = UITableViewCellAccessoryType.none
if indexPath.section == 0 {
cell.imageView!.layer.borderWidth = 0
return indexPath.row == 0 ? configureRecentlyClosed(cell, for: indexPath) : configureSyncedTabs(cell, for: indexPath)
} else {
return configureSite(cell, for: indexPath)
}
}
func configureRecentlyClosed(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell {
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell.textLabel!.text = Strings.RecentlyClosedTabsButtonTitle
cell.detailTextLabel!.text = ""
cell.imageView!.image = UIImage(named: "recently_closed")
cell.imageView?.backgroundColor = UIColor.white
if !hasRecentlyClosed {
cell.textLabel?.alpha = 0.5
cell.imageView!.alpha = 0.5
cell.selectionStyle = .none
}
cell.accessibilityIdentifier = "HistoryPanel.recentlyClosedCell"
return cell
}
func configureSyncedTabs(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell {
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell.textLabel!.text = Strings.SyncedTabsTableViewCellTitle
cell.detailTextLabel!.text = self.syncDetailText
cell.imageView!.image = UIImage(named: "synced_devices")
cell.imageView?.backgroundColor = UIColor.white
cell.accessibilityIdentifier = "HistoryPanel.syncedDevicesCell"
return cell
}
func configureSite(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell {
if let site = siteForIndexPath(indexPath), let cell = cell as? TwoLineTableViewCell {
cell.setLines(site.title, detailText: site.url)
cell.imageView!.layer.borderColor = HistoryPanelUX.IconBorderColor.cgColor
cell.imageView!.layer.borderWidth = HistoryPanelUX.IconBorderWidth
cell.imageView?.setIcon(site.icon, forURL: site.tileURL, completed: { (color, url) in
if site.tileURL == url {
cell.imageView?.image = cell.imageView?.image?.createScaled(CGSize(width: HistoryPanelUX.IconSize, height: HistoryPanelUX.IconSize))
cell.imageView?.backgroundColor = color
cell.imageView?.contentMode = .center
}
})
}
return cell
}
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
var count = 1
for category in self.categories where category.rows > 0 {
count += 1
}
return count
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
if indexPath.section == 0 {
self.tableView.deselectRow(at: indexPath, animated: true)
return indexPath.row == 0 ? self.showRecentlyClosed() : self.showSyncedTabs()
}
if let site = self.siteForIndexPath(indexPath), let url = URL(string: site.url) {
let visitType = VisitType.typed // Means History, too.
if let homePanelDelegate = homePanelDelegate {
homePanelDelegate.homePanel(self, didSelectURL: url, visitType: visitType)
}
return
}
log.warning("No site or no URL when selecting row.")
}
func pinTopSite(_ site: Site) {
_ = profile.history.addPinnedTopSite(site).value
}
func showSyncedTabs() {
let nextController = RemoteTabsPanel()
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
self.refreshControl?.endRefreshing()
self.navigationController?.pushViewController(nextController, animated: true)
}
func showRecentlyClosed() {
guard hasRecentlyClosed else {
return
}
let nextController = RecentlyClosedTabsPanel()
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
self.refreshControl?.endRefreshing()
self.navigationController?.pushViewController(nextController, animated: true)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = String()
switch sectionLookup[section]! {
case 0: return nil
case 1: title = NSLocalizedString("Today", comment: "History tableview section header")
case 2: title = NSLocalizedString("Yesterday", comment: "History tableview section header")
case 3: title = NSLocalizedString("Last week", comment: "History tableview section header")
case 4: title = NSLocalizedString("Last month", comment: "History tableview section header")
default:
assertionFailure("Invalid history section \(section)")
}
return title
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
return nil
}
return super.tableView(tableView, viewForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 0
}
return super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
}
return self.categories[uiSectionToCategory(section)].rows
}
func tableView(_ tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: IndexPath) {
// Intentionally blank. Required to use UITableViewRowActions
}
fileprivate func removeHistoryForURLAtIndexPath(indexPath: IndexPath) {
if let site = self.siteForIndexPath(indexPath) {
// Why the dispatches? Because we call success and failure on the DB
// queue, and so calling anything else that calls through to the DB will
// deadlock. This problem will go away when the history API switches to
// Deferred instead of using callbacks.
self.profile.history.removeHistoryForURL(site.url)
.upon { res in
self.fetchData().uponQueue(DispatchQueue.main) { result in
// If a section will be empty after removal, we must remove the section itself.
if let data = result.successValue {
let oldCategories = self.categories
self.data = data
self.computeSectionOffsets()
let sectionsToDelete = NSMutableIndexSet()
var rowsToDelete = [IndexPath]()
let sectionsToAdd = NSMutableIndexSet()
var rowsToAdd = [IndexPath]()
for (index, category) in self.categories.enumerated() {
let oldCategory = oldCategories[index]
// don't bother if we're not displaying this category
if oldCategory.section == nil && category.section == nil {
continue
}
// 1. add a new section if the section didn't previously exist
if oldCategory.section == nil && category.section != oldCategory.section {
log.debug("adding section \(category.section ?? 0)")
sectionsToAdd.add(category.section!)
}
// 2. add a new row if there are more rows now than there were before
if oldCategory.rows < category.rows {
log.debug("adding row to \(category.section ?? 0) at \(category.rows-1)")
rowsToAdd.append(IndexPath(row: category.rows-1, section: category.section!))
}
// if we're dealing with the section where the row was deleted:
// 1. if the category no longer has a section, then we need to delete the entire section
// 2. delete a row if the number of rows has been reduced
// 3. delete the selected row and add a new one on the bottom of the section if the number of rows has stayed the same
if oldCategory.section == indexPath.section {
if category.section == nil {
log.debug("deleting section \(indexPath.section)")
sectionsToDelete.add(indexPath.section)
} else if oldCategory.section == category.section {
if oldCategory.rows > category.rows {
log.debug("deleting row from \(category.section ?? 0) at \(indexPath.row)")
rowsToDelete.append(indexPath)
} else if category.rows == oldCategory.rows {
log.debug("in section \(category.section ?? 0), removing row at \(indexPath.row) and inserting row at \(category.rows-1)")
rowsToDelete.append(indexPath)
rowsToAdd.append(IndexPath(row: category.rows-1, section: indexPath.section))
}
}
}
}
self.tableView.beginUpdates()
if sectionsToAdd.count > 0 {
self.tableView.insertSections(sectionsToAdd as IndexSet, with: UITableViewRowAnimation.left)
}
if sectionsToDelete.count > 0 {
self.tableView.deleteSections(sectionsToDelete as IndexSet, with: UITableViewRowAnimation.right)
}
if !rowsToDelete.isEmpty {
self.tableView.deleteRows(at: rowsToDelete, with: UITableViewRowAnimation.right)
}
if !rowsToAdd.isEmpty {
self.tableView.insertRows(at: rowsToAdd, with: UITableViewRowAnimation.right)
}
self.tableView.endUpdates()
self.updateEmptyPanelState()
}
}
}
}
}
func tableView(_ tableView: UITableView, editActionsForRowAtIndexPath indexPath: IndexPath) -> [AnyObject]? {
if indexPath.section == 0 {
return []
}
let title = NSLocalizedString("Delete", tableName: "HistoryPanel", comment: "Action button for deleting history entries in the history panel.")
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: title, handler: { (action, indexPath) in
self.removeHistoryForURLAtIndexPath(indexPath: indexPath)
})
return [delete]
}
}
extension HistoryPanel: HomePanelContextMenu {
func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) {
guard let contextMenu = completionHandler() else { return }
self.present(contextMenu, animated: true, completion: nil)
}
func getSiteDetails(for indexPath: IndexPath) -> Site? {
return siteForIndexPath(indexPath)
}
func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? {
guard var actions = getDefaultContextMenuActions(for: site, homePanelDelegate: homePanelDelegate) else { return nil }
let removeAction = PhotonActionSheetItem(title: Strings.DeleteFromHistoryContextMenuTitle, iconString: "action_delete", handler: { action in
self.removeHistoryForURLAtIndexPath(indexPath: indexPath)
})
let pinTopSite = PhotonActionSheetItem(title: Strings.PinTopsiteActionTitle, iconString: "action_pin", handler: { action in
self.pinTopSite(site)
})
if FeatureSwitches.activityStream.isMember(profile.prefs) {
actions.append(pinTopSite)
}
actions.append(removeAction)
return actions
}
}
|
mpl-2.0
|
b998d7425c15699fc98bfe46590e38f5
| 41.998285 | 166 | 0.610858 | 5.711552 | false | false | false | false |
Shopify/mobile-buy-sdk-ios
|
Buy/Generated/Storefront/CartLineUpdateInput.swift
|
1
|
5369
|
//
// CartLineUpdateInput.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// Specifies the input fields to update a line item on a cart.
open class CartLineUpdateInput {
/// The identifier of the merchandise line.
open var id: GraphQL.ID
/// The quantity of the line item.
open var quantity: Input<Int32>
/// The identifier of the merchandise for the line item.
open var merchandiseId: Input<GraphQL.ID>
/// An array of key-value pairs that contains additional information about the
/// merchandise line.
open var attributes: Input<[AttributeInput]>
/// The identifier of the selling plan that the merchandise is being purchased
/// with.
open var sellingPlanId: Input<GraphQL.ID>
/// Creates the input object.
///
/// - parameters:
/// - id: The identifier of the merchandise line.
/// - quantity: The quantity of the line item.
/// - merchandiseId: The identifier of the merchandise for the line item.
/// - attributes: An array of key-value pairs that contains additional information about the merchandise line.
/// - sellingPlanId: The identifier of the selling plan that the merchandise is being purchased with.
///
public static func create(id: GraphQL.ID, quantity: Input<Int32> = .undefined, merchandiseId: Input<GraphQL.ID> = .undefined, attributes: Input<[AttributeInput]> = .undefined, sellingPlanId: Input<GraphQL.ID> = .undefined) -> CartLineUpdateInput {
return CartLineUpdateInput(id: id, quantity: quantity, merchandiseId: merchandiseId, attributes: attributes, sellingPlanId: sellingPlanId)
}
private init(id: GraphQL.ID, quantity: Input<Int32> = .undefined, merchandiseId: Input<GraphQL.ID> = .undefined, attributes: Input<[AttributeInput]> = .undefined, sellingPlanId: Input<GraphQL.ID> = .undefined) {
self.id = id
self.quantity = quantity
self.merchandiseId = merchandiseId
self.attributes = attributes
self.sellingPlanId = sellingPlanId
}
/// Creates the input object.
///
/// - parameters:
/// - id: The identifier of the merchandise line.
/// - quantity: The quantity of the line item.
/// - merchandiseId: The identifier of the merchandise for the line item.
/// - attributes: An array of key-value pairs that contains additional information about the merchandise line.
/// - sellingPlanId: The identifier of the selling plan that the merchandise is being purchased with.
///
@available(*, deprecated, message: "Use the static create() method instead.")
public convenience init(id: GraphQL.ID, quantity: Int32? = nil, merchandiseId: GraphQL.ID? = nil, attributes: [AttributeInput]? = nil, sellingPlanId: GraphQL.ID? = nil) {
self.init(id: id, quantity: quantity.orUndefined, merchandiseId: merchandiseId.orUndefined, attributes: attributes.orUndefined, sellingPlanId: sellingPlanId.orUndefined)
}
internal func serialize() -> String {
var fields: [String] = []
fields.append("id:\(GraphQL.quoteString(input: "\(id.rawValue)"))")
switch quantity {
case .value(let quantity):
guard let quantity = quantity else {
fields.append("quantity:null")
break
}
fields.append("quantity:\(quantity)")
case .undefined: break
}
switch merchandiseId {
case .value(let merchandiseId):
guard let merchandiseId = merchandiseId else {
fields.append("merchandiseId:null")
break
}
fields.append("merchandiseId:\(GraphQL.quoteString(input: "\(merchandiseId.rawValue)"))")
case .undefined: break
}
switch attributes {
case .value(let attributes):
guard let attributes = attributes else {
fields.append("attributes:null")
break
}
fields.append("attributes:[\(attributes.map{ "\($0.serialize())" }.joined(separator: ","))]")
case .undefined: break
}
switch sellingPlanId {
case .value(let sellingPlanId):
guard let sellingPlanId = sellingPlanId else {
fields.append("sellingPlanId:null")
break
}
fields.append("sellingPlanId:\(GraphQL.quoteString(input: "\(sellingPlanId.rawValue)"))")
case .undefined: break
}
return "{\(fields.joined(separator: ","))}"
}
}
}
|
mit
|
e797d23d688af53833fec83fd27922c7
| 39.674242 | 249 | 0.707208 | 3.720721 | false | false | false | false |
nheagy/WordPress-iOS
|
WordPress/Classes/Utility/Migrations/AccountToAccount22to23.swift
|
1
|
7533
|
import UIKit
import Foundation
import WordPressComAnalytics
/**
Note:
This migration policy handles database migration from WPiOS 4.4 to 4.5.
WPiOS 4.5 introduces two extra data models (22 and 23).
*/
class AccountToAccount22to23: NSEntityMigrationPolicy {
private let defaultDotcomUsernameKey = "AccountDefaultUsername"
private let defaultDotcomKey = "AccountDefaultDotcom"
private let defaultDotcomUUIDKey = "AccountDefaultDotcomUUID"
override func beginEntityMapping(mapping: NSEntityMapping, manager: NSMigrationManager) throws {
// Note:
// NSEntityMigrationPolicy instance might not be the same all over. Let's use NSUserDefaults
let defaultAccount = legacyDefaultWordPressAccount(manager.sourceContext)
if defaultAccount == nil {
DDLogSwift.logError(">> Migration process couldn't locate a default WordPress.com account")
return
}
let unwrappedAccount = defaultAccount!
let username = unwrappedAccount.valueForKey("username") as? String
let isDotCom = unwrappedAccount.valueForKey("isWpcom") as? Bool
if username == nil || isDotCom == nil {
DDLogSwift.logError(">> Migration process found an invalid default DotCom account")
}
if isDotCom! == true {
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setValue(username!, forKey: defaultDotcomUsernameKey)
userDefaults.synchronize()
DDLogSwift.logWarn(">> Migration process matched [\(username!)] as the default WordPress.com account")
} else {
DDLogSwift.logError(">> Migration process found [\(username!)] as an invalid Default Account (Non DotCom!)")
}
}
override func endEntityMapping(mapping: NSEntityMapping, manager: NSMigrationManager) throws {
// Load every WPAccount instance
let context = manager.destinationContext
let request = NSFetchRequest(entityName: "Account")
let accounts = try context.executeFetchRequest(request) as! [NSManagedObject]
if accounts.count == 0 {
return
}
// Assign the UUID's + Find the old defaultAccount (if any)
let defaultUsername: String = NSUserDefaults.standardUserDefaults().stringForKey(defaultDotcomUsernameKey) ?? String()
var defaultAccount: NSManagedObject?
for account in accounts {
let uuid = NSUUID().UUIDString
account.setValue(uuid, forKey: "uuid")
let username = account.valueForKey("username") as? String
let isDotCom = account.valueForKey("isWpcom") as? Bool
if username == nil || isDotCom == nil {
continue
}
if defaultUsername == username! && isDotCom! == true {
defaultAccount = account
DDLogSwift.logWarn(">> Assigned UUID [\(uuid)] to DEFAULT account [\(username!)]. IsDotCom [\(isDotCom!)]")
} else {
DDLogSwift.logWarn(">> Assigned UUID [\(uuid)] to account [\(username!)]. IsDotCom [\(isDotCom!)]")
}
}
// Set the defaultAccount (if any)
let userDefaults = NSUserDefaults.standardUserDefaults()
if defaultAccount != nil {
let uuid = defaultAccount!.valueForKey("uuid") as! String
userDefaults.setObject(uuid, forKey: defaultDotcomUUIDKey)
}
userDefaults.removeObjectForKey(defaultDotcomKey)
userDefaults.removeObjectForKey(defaultDotcomUsernameKey)
userDefaults.synchronize()
// At last: Execute the Default Account Fix (if needed)
fixDefaultAccountIfNeeded(context)
}
// MARK: - Private Helpers
private func legacyDefaultWordPressAccount(context: NSManagedObjectContext) -> NSManagedObject? {
let objectURL = NSUserDefaults.standardUserDefaults().URLForKey(defaultDotcomKey)
if objectURL == nil {
return nil
}
let objectID = context.persistentStoreCoordinator!.managedObjectIDForURIRepresentation(objectURL!)
if objectID == nil {
return nil
}
var defaultAccount:NSManagedObject
do {
defaultAccount = try context.existingObjectWithID(objectID!)
} catch {
DDLogSwift.logError("\(error)")
return nil
}
return defaultAccount
}
private func defaultWordPressAccount(context: NSManagedObjectContext) -> NSManagedObject? {
let objectUUID = NSUserDefaults.standardUserDefaults().stringForKey(defaultDotcomUUIDKey)
if objectUUID == nil {
return nil
}
let request = NSFetchRequest(entityName: "Account")
request.predicate = NSPredicate(format: "uuid == %@", objectUUID!)
var accounts:[NSManagedObject]
do {
accounts = try context.executeFetchRequest(request) as! [NSManagedObject]
} catch {
DDLogSwift.logError("\(error)")
return nil
}
return accounts.first
}
private func setDefaultWordPressAccount(account: NSManagedObject) {
let uuid = account.valueForKey("uuid") as? String
if uuid == nil {
DDLogSwift.logError(">> Error setting the default WordPressDotCom Account")
return
}
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(uuid, forKey: defaultDotcomUUIDKey)
defaults.synchronize()
}
// MARK: Invalid Default WordPress Account Fix
private func fixDefaultAccountIfNeeded(context: NSManagedObjectContext) {
let oldDefaultAccount = defaultWordPressAccount(context)
if oldDefaultAccount?.valueForKey("isWpcom")?.boolValue == true {
DDLogSwift.logWarn("<< Default Account Fix not required!")
return
}
DDLogSwift.logInfo(">> Proceeding with Default Account Fix")
// Load all of the WPAccount instances
let request = NSFetchRequest(entityName: "Account")
request.predicate = NSPredicate(format: "isWpcom == true")
var results:[NSManagedObject]
do {
results = try context.executeFetchRequest(request) as! [NSManagedObject]
} catch {
DDLogSwift.logError(">> Error while executing accounts fix: couldn't locate any WPAccount instances")
return
}
// Attempt to infer the right default WordPress.com account
let unwrappedAccounts = NSMutableArray(array: results)
unwrappedAccounts.sortUsingDescriptors([
NSSortDescriptor(key: "blogs.@count", ascending: false),
NSSortDescriptor(key: "jetpackBlogs.@count", ascending: true)
])
// Pick up the first account!
if let defaultAccount = unwrappedAccounts.firstObject as? NSManagedObject {
DDLogSwift.logInfo(">> Updating defaultAccount \(defaultAccount)")
setDefaultWordPressAccount(defaultAccount)
WPAnalytics.track(.PerformedCoreDataMigrationFixFor45)
} else {
DDLogSwift.logError(">> Error: couldn't update the Default WordPress.com account")
}
}
}
|
gpl-2.0
|
9a0e46fe463471b696bbaaf6839f778e
| 37.433673 | 126 | 0.625647 | 5.62584 | false | false | false | false |
algolia/algoliasearch-client-swift
|
Sources/AlgoliaSearchClient/Command/Command+Advanced.swift
|
1
|
1689
|
//
// Command+Advanced.swift
//
//
// Created by Vladislav Fitc on 10.03.2020.
//
import Foundation
extension Command {
enum Advanced {
struct TaskStatus: AlgoliaCommand {
let method: HTTPMethod = .get
let callType: CallType = .read
let path: URL
let requestOptions: RequestOptions?
init(indexName: IndexName, taskID: TaskID, requestOptions: RequestOptions?) {
self.requestOptions = requestOptions
self.path = URL
.indexesV1
.appending(indexName)
.appending(.task)
.appending(taskID)
}
}
struct AppTaskStatus: AlgoliaCommand {
let method: HTTPMethod = .get
let callType: CallType = .read
let path: URL
let requestOptions: RequestOptions?
init(taskID: AppTaskID, requestOptions: RequestOptions?) {
self.requestOptions = requestOptions
self.path = URL
.task
.appending(taskID)
}
}
struct GetLogs: AlgoliaCommand {
let method: HTTPMethod = .get
let callType: CallType = .read
let path = URL.logs
let requestOptions: RequestOptions?
init(indexName: IndexName?, offset: Int?, length: Int?, logType: LogType, requestOptions: RequestOptions?) {
let requestOptions = requestOptions.updateOrCreate(
[:]
.merging(indexName.flatMap { [.indexName: $0.rawValue] } ?? [:])
.merging(offset.flatMap { [.offset: String($0)] } ?? [:])
.merging(length.flatMap { [.length: String($0)] } ?? [:])
.merging([.type: logType.rawValue])
)
self.requestOptions = requestOptions
}
}
}
}
|
mit
|
9560fc7d60b319c45898e6cdb241ae28
| 23.128571 | 114 | 0.597395 | 4.589674 | false | false | false | false |
ArchimboldiMao/remotex-iOS
|
remotex-iOS/View/JobTableNodeCell.swift
|
2
|
5287
|
//
// JobTableNodeCell.swift
// remotex-iOS
//
// Created by archimboldi on 10/05/2017.
// Copyright © 2017 me.archimboldi. All rights reserved.
//
import Foundation
import AsyncDisplayKit
class JobTableNodeCell: ASCellNode {
let jobTitleLabel = ASTextNode()
let priceLabel = ASTextNode()
let cityLabel = ASTextNode()
var tagLabels: [ASTextNode] = []
let abstractTextLabel = ASTextNode()
let releaseAtLabel = ASTextNode()
let expireAtLabel = ASTextNode()
let viewCountLabel = ASTextNode()
init(jobModel: JobModel) {
super.init()
self.jobTitleLabel.attributedText = jobModel.attrStringForTitle(withSize: Constants.CellLayout.TitleFontSize)
self.priceLabel.attributedText = jobModel.attrStringForPrice(withSize: Constants.CellLayout.PriceFontSize)
self.abstractTextLabel.attributedText = jobModel.attrStringForAbstractText(withSize: Constants.CellLayout.AbstractFontSize)
if jobModel.cityName != nil && jobModel.cityName != "" {
self.cityLabel.attributedText = jobModel.attrStringForCityName(withSize: Constants.CellLayout.TagFontSize)
tagLabels.append(self.cityLabel)
}
if jobModel.categories != nil && (jobModel.categories?.count)! >= 1 {
for category: CategoryModel in jobModel.categories! {
let label = ASTextNode()
label.attributedText = category.attrStringForCategoryName(withSize: Constants.CellLayout.TagFontSize)
tagLabels.append(label)
}
}
if jobModel.roles != nil && (jobModel.roles?.count)! >= 1 {
for role: RoleModel in jobModel.roles! {
let label = ASTextNode()
label.attributedText = role.attrStringForRoleName(withSize: Constants.CellLayout.TagFontSize)
tagLabels.append(label)
}
}
if jobModel.skills != nil && (jobModel.skills?.count)! >= 1 {
for skill: SkillModel in jobModel.skills! {
let label = ASTextNode()
label.attributedText = skill.attrStringForSkillName(withSize: Constants.CellLayout.TagFontSize)
tagLabels.append(label)
}
}
self.viewCountLabel.attributedText = jobModel.attrStringForViewCount(withSize: Constants.CellLayout.DateFontSize)
self.releaseAtLabel.attributedText = jobModel.attrStringForReleaseAt(withSize: Constants.CellLayout.DateFontSize)
self.expireAtLabel.attributedText = jobModel.attrStringForExpireAt(withSize: Constants.CellLayout.DateFontSize)
self.automaticallyManagesSubnodes = true
// Solutions to eliminate flashes caused by reloadData
// https://github.com/facebookarchive/AsyncDisplayKit/issues/2536
// http://texturegroup.org/docs/synchronous-concurrency.html
self.neverShowPlaceholders = true
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
self.backgroundColor = UIColor.white
let titleStack = ASStackLayoutSpec.horizontal()
titleStack.justifyContent = ASStackLayoutJustifyContent.spaceBetween
self.jobTitleLabel.style.alignSelf = .start
self.jobTitleLabel.style.maxWidth = ASDimensionMakeWithFraction(0.85)
self.jobTitleLabel.maximumNumberOfLines = 2
self.priceLabel.style.alignSelf = .end
self.priceLabel.style.minWidth = ASDimensionMakeWithFraction(0.15)
titleStack.children = [self.jobTitleLabel, self.priceLabel]
let tagStack = ASStackLayoutSpec.horizontal()
tagStack.alignItems = .start
tagStack.spacing = 8.0
tagStack.flexWrap = .wrap // allow multi lines
tagStack.alignContent = .spaceAround
for tagLabel in self.tagLabels {
tagLabel.backgroundColor = Constants.CellLayout.TagBackgroundColor
tagLabel.style.alignSelf = .center
tagLabel.textContainerInset = UIEdgeInsets.init(top: 4, left: 8, bottom: 4, right: 8)
tagLabel.cornerRadius = 8.0
tagLabel.clipsToBounds = true
// use UIEdgeInsets set line space
// Thanks @jeffdav (Texture team member in Slack)
let insetStack = ASInsetLayoutSpec.init(insets: UIEdgeInsets.init(top: 6, left: 0, bottom: 0, right: 0), child: tagLabel)
tagStack.children?.append(insetStack)
}
self.abstractTextLabel.style.spacingBefore = 6.0
self.abstractTextLabel.style.spacingAfter = 6.0
self.abstractTextLabel.style.alignSelf = .start
self.abstractTextLabel.maximumNumberOfLines = 12
let footerStack = ASStackLayoutSpec.horizontal()
footerStack.alignItems = .center
footerStack.justifyContent = ASStackLayoutJustifyContent.spaceBetween
footerStack.children = [self.releaseAtLabel, self.viewCountLabel]
let verticalStack = ASStackLayoutSpec.vertical()
verticalStack.children = [titleStack, tagStack, self.abstractTextLabel, footerStack]
return ASInsetLayoutSpec(insets:UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16), child: verticalStack)
}
}
|
apache-2.0
|
8f9de6eaf2e4e766576ef0a655f8511a
| 45.368421 | 133 | 0.673099 | 4.805455 | false | false | false | false |
stephentyrone/swift
|
stdlib/public/core/CTypes.swift
|
1
|
9594
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// C Primitive Types
//===----------------------------------------------------------------------===//
/// The C 'char' type.
///
/// This will be the same as either `CSignedChar` (in the common
/// case) or `CUnsignedChar`, depending on the platform.
public typealias CChar = Int8
/// The C 'unsigned char' type.
public typealias CUnsignedChar = UInt8
/// The C 'unsigned short' type.
public typealias CUnsignedShort = UInt16
/// The C 'unsigned int' type.
public typealias CUnsignedInt = UInt32
/// The C 'unsigned long' type.
#if os(Windows) && arch(x86_64)
public typealias CUnsignedLong = UInt32
#else
public typealias CUnsignedLong = UInt
#endif
/// The C 'unsigned long long' type.
public typealias CUnsignedLongLong = UInt64
/// The C 'signed char' type.
public typealias CSignedChar = Int8
/// The C 'short' type.
public typealias CShort = Int16
/// The C 'int' type.
public typealias CInt = Int32
/// The C 'long' type.
#if os(Windows) && arch(x86_64)
public typealias CLong = Int32
#else
public typealias CLong = Int
#endif
/// The C 'long long' type.
public typealias CLongLong = Int64
/// The C '_Float16' type.
@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
public typealias CFloat16 = Float16
/// The C 'float' type.
public typealias CFloat = Float
/// The C 'double' type.
public typealias CDouble = Double
/// The C 'long double' type.
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// On Darwin, long double is Float80 on x86, and Double otherwise.
#if arch(x86_64) || arch(i386)
public typealias CLongDouble = Float80
#else
public typealias CLongDouble = Double
#endif
#elseif os(Windows)
// On Windows, long double is always Double.
public typealias CLongDouble = Double
#elseif os(Linux)
// On Linux/x86, long double is Float80.
// TODO: Fill in definitions for additional architectures as needed. IIRC
// armv7 should map to Double, but arm64 and ppc64le should map to Float128,
// which we don't yet have in Swift.
#if arch(x86_64) || arch(i386)
public typealias CLongDouble = Float80
#endif
// TODO: Fill in definitions for other OSes.
#if arch(s390x)
// On s390x '-mlong-double-64' option with size of 64-bits makes the
// Long Double type equivalent to Double type.
public typealias CLongDouble = Double
#endif
#elseif os(Android)
// On Android, long double is Float128 for AAPCS64, which we don't have yet in
// Swift (SR-9072); and Double for ARMv7.
#if arch(arm)
public typealias CLongDouble = Double
#endif
#elseif os(OpenBSD)
public typealias CLongDouble = Float80
#endif
// FIXME: Is it actually UTF-32 on Darwin?
//
/// The C++ 'wchar_t' type.
public typealias CWideChar = Unicode.Scalar
// FIXME: Swift should probably have a UTF-16 type other than UInt16.
//
/// The C++11 'char16_t' type, which has UTF-16 encoding.
public typealias CChar16 = UInt16
/// The C++11 'char32_t' type, which has UTF-32 encoding.
public typealias CChar32 = Unicode.Scalar
/// The C '_Bool' and C++ 'bool' type.
public typealias CBool = Bool
/// A wrapper around an opaque C pointer.
///
/// Opaque pointers are used to represent C pointers to types that
/// cannot be represented in Swift, such as incomplete struct types.
@frozen
public struct OpaquePointer {
@usableFromInline
internal var _rawValue: Builtin.RawPointer
@usableFromInline @_transparent
internal init(_ v: Builtin.RawPointer) {
self._rawValue = v
}
/// Creates an `OpaquePointer` from a given address in memory.
@_transparent
public init?(bitPattern: Int) {
if bitPattern == 0 { return nil }
self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)
}
/// Creates an `OpaquePointer` from a given address in memory.
@_transparent
public init?(bitPattern: UInt) {
if bitPattern == 0 { return nil }
self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)
}
/// Converts a typed `UnsafePointer` to an opaque C pointer.
@_transparent
public init<T>(@_nonEphemeral _ from: UnsafePointer<T>) {
self._rawValue = from._rawValue
}
/// Converts a typed `UnsafePointer` to an opaque C pointer.
///
/// The result is `nil` if `from` is `nil`.
@_transparent
public init?<T>(@_nonEphemeral _ from: UnsafePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.
@_transparent
public init<T>(@_nonEphemeral _ from: UnsafeMutablePointer<T>) {
self._rawValue = from._rawValue
}
/// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.
///
/// The result is `nil` if `from` is `nil`.
@_transparent
public init?<T>(@_nonEphemeral _ from: UnsafeMutablePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
}
extension OpaquePointer: Equatable {
@inlinable // unsafe-performance
public static func == (lhs: OpaquePointer, rhs: OpaquePointer) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))
}
}
extension OpaquePointer: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(Int(Builtin.ptrtoint_Word(_rawValue)))
}
}
extension OpaquePointer: CustomDebugStringConvertible {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return _rawPointerToString(_rawValue)
}
}
extension Int {
/// Creates a new value with the bit pattern of the given pointer.
///
/// The new value represents the address of the pointer passed as `pointer`.
/// If `pointer` is `nil`, the result is `0`.
///
/// - Parameter pointer: The pointer to use as the source for the new
/// integer.
@inlinable // unsafe-performance
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
extension UInt {
/// Creates a new value with the bit pattern of the given pointer.
///
/// The new value represents the address of the pointer passed as `pointer`.
/// If `pointer` is `nil`, the result is `0`.
///
/// - Parameter pointer: The pointer to use as the source for the new
/// integer.
@inlinable // unsafe-performance
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
/// A wrapper around a C `va_list` pointer.
#if arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows))
@frozen
public struct CVaListPointer {
@usableFromInline // unsafe-performance
internal var _value: (__stack: UnsafeMutablePointer<Int>?,
__gr_top: UnsafeMutablePointer<Int>?,
__vr_top: UnsafeMutablePointer<Int>?,
__gr_off: Int32,
__vr_off: Int32)
@inlinable // unsafe-performance
public // @testable
init(__stack: UnsafeMutablePointer<Int>?,
__gr_top: UnsafeMutablePointer<Int>?,
__vr_top: UnsafeMutablePointer<Int>?,
__gr_off: Int32,
__vr_off: Int32) {
_value = (__stack, __gr_top, __vr_top, __gr_off, __vr_off)
}
}
extension CVaListPointer: CustomDebugStringConvertible {
public var debugDescription: String {
return "(\(_value.__stack.debugDescription), " +
"\(_value.__gr_top.debugDescription), " +
"\(_value.__vr_top.debugDescription), " +
"\(_value.__gr_off), " +
"\(_value.__vr_off))"
}
}
#else
@frozen
public struct CVaListPointer {
@usableFromInline // unsafe-performance
internal var _value: UnsafeMutableRawPointer
@inlinable // unsafe-performance
public // @testable
init(_fromUnsafeMutablePointer from: UnsafeMutableRawPointer) {
_value = from
}
}
extension CVaListPointer: CustomDebugStringConvertible {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return _value.debugDescription
}
}
#endif
/// Copy `size` bytes of memory from `src` into `dest`.
///
/// The memory regions `src..<src + size` and
/// `dest..<dest + size` should not overlap.
@inlinable
internal func _memcpy(
dest destination: UnsafeMutableRawPointer,
src: UnsafeRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
dest, src, size,
/*volatile:*/ false._value)
}
/// Copy `size` bytes of memory from `src` into `dest`.
///
/// The memory regions `src..<src + size` and
/// `dest..<dest + size` may overlap.
@inlinable
internal func _memmove(
dest destination: UnsafeMutableRawPointer,
src: UnsafeRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memmove_RawPointer_RawPointer_Int64(
dest, src, size,
/*volatile:*/ false._value)
}
|
apache-2.0
|
fe60c3d56dc8b0a49c26102d7233abe3
| 28.795031 | 84 | 0.67094 | 4.002503 | false | false | false | false |
milseman/swift
|
benchmark/single-source/DropLast.swift
|
11
|
4963
|
//===--- DropLast.swift ---------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
////////////////////////////////////////////////////////////////////////////////
// WARNING: This file is manually generated from .gyb template and should not
// be directly modified. Instead, make changes to DropLast.swift.gyb and run
// scripts/generate_harness/generate_harness.py to regenerate this file.
////////////////////////////////////////////////////////////////////////////////
import TestsUtils
let sequenceCount = 4096
let prefixCount = 1024
let dropCount = sequenceCount - prefixCount
let sumCount = prefixCount * (prefixCount - 1) / 2
@inline(never)
public func run_DropLastCountableRange(_ N: Int) {
let s = 0..<sequenceCount
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastSequence(_ N: Int) {
let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnySequence(_ N: Int) {
let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnySeqCntRange(_ N: Int) {
let s = AnySequence(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnySeqCRangeIter(_ N: Int) {
let s = AnySequence((0..<sequenceCount).makeIterator())
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnyCollection(_ N: Int) {
let s = AnyCollection(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastArray(_ N: Int) {
let s = Array(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastCountableRangeLazy(_ N: Int) {
let s = (0..<sequenceCount).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastSequenceLazy(_ N: Int) {
let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnySequenceLazy(_ N: Int) {
let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnySeqCntRangeLazy(_ N: Int) {
let s = (AnySequence(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnySeqCRangeIterLazy(_ N: Int) {
let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastAnyCollectionLazy(_ N: Int) {
let s = (AnyCollection(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
@inline(never)
public func run_DropLastArrayLazy(_ N: Int) {
let s = (Array(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount)
}
}
|
apache-2.0
|
644fd24a6f54574c7cb0bc8878788a5d
| 26.726257 | 91 | 0.604675 | 3.794343 | false | false | false | false |
skedgo/tripkit-ios
|
Tests/TripKitTests/routing/TKRouterTest.swift
|
1
|
8237
|
//
// TKRouterTest.swift
// TripKitTests
//
// Created by Adrian Schoenig on 24.09.17.
// Copyright © 2017 SkedGo. All rights reserved.
//
import Foundation
import CoreLocation
import XCTest
@testable import TripKit
class TKRouterTest: TKTestCase {
override func setUpWithError() throws {
try super.setUpWithError()
let env = ProcessInfo.processInfo.environment
if let apiKey = env["TRIPGO_API_KEY"], !apiKey.isEmpty {
TripKit.apiKey = apiKey
} else {
try XCTSkipIf(true, "No TripGo API key supplied")
}
}
func testParsingOldPTResult() throws {
let request = try self.request(fromFilename: "routing-pt-oldish")
// Evaluating the returned response
XCTAssertEqual(request.tripGroups.count, 3)
XCTAssertEqual(request.trips.count, 4 + 4 + 4)
for trip in request.trips {
XCTAssertGreaterThan(trip.segments.count, 0)
}
// Evaluating what's in Core Data
XCTAssertEqual(self.tripKitContext.fetchObjects(TripGroup.self).count, 3)
XCTAssertEqual(self.tripKitContext.fetchObjects(Trip.self).count, 4 + 4 + 4)
XCTAssertEqual(self.tripKitContext.fetchObjects(SegmentTemplate.self).count, 20, "Each segment that's not hidden should be parsed and added just once.")
// Make sure CoreData is happy
try self.tripKitContext.save()
}
func testParsingPerformance() throws {
let data = try dataFromJSON(named: "routing-pt-oldish")
let response = try JSONDecoder().decode(TKAPI.RoutingResponse.self, from: data)
measure {
do {
let request = try TKRoutingParser.addBlocking(response, into: self.tripKitContext)
XCTAssertNotNil(request)
} catch {
XCTFail("Parsing failed with \(error)")
}
}
}
func testParsingGoGetResult() throws {
let request = try self.request(fromFilename: "routing-goget")
XCTAssertNotNil(request)
XCTAssertEqual(request.tripGroups.count, 1)
XCTAssertEqual(request.tripGroups.first?.sources.count, 3)
XCTAssertEqual(request.trips.count, 1)
let trip = try XCTUnwrap(request.trips.first)
XCTAssertEqual(trip.segments.count, 5)
XCTAssertNil(trip.segments[1].bookingInternalURL)
XCTAssertNotNil(trip.segments[1].bookingExternalActions)
XCTAssertEqual(trip.segments[2].alerts.count, 4)
XCTAssertEqual(trip.segments[2].alertsWithAction.count, 0)
XCTAssertEqual(trip.segments[2].alertsWithContent.count, 4)
XCTAssertEqual(trip.segments[2].alertsWithLocation.count, 4)
XCTAssertEqual(trip.segments[2].timesAreRealTime, true)
XCTAssertEqual(trip.segments[2].isSharedVehicle, true)
XCTAssertEqual(trip.segments[3].hasCarParks, true)
// wording should be the regular variant (not 'near')
let startSegment = try XCTUnwrap(trip.segments.first)
let endSegment = try XCTUnwrap(trip.segments.last)
XCTAssertEqual(startSegment.title, Loc.LeaveFromLocation("Mount Street & Little Walker Street"))
XCTAssertEqual(endSegment.title, Loc.ArriveAtLocation("2A Bligh Street, 2000 Sydney, Australia"))
// Make sure CoreData is happy
try self.tripKitContext.save()
}
func testParsingCycleTrainCycleResult() throws {
let request = try self.request(fromFilename: "routing-cycle-train-cycle")
XCTAssertNotNil(request)
XCTAssertEqual(request.tripGroups.count, 5)
XCTAssertEqual(request.trips.count, 33)
let cycleGroup = try XCTUnwrap(request.tripGroups.first { $0.trips.contains(where: { $0.usedModeIdentifiers.contains("cy_bic") }) })
XCTAssertEqual(cycleGroup.sources.count, 3)
let cycleTrip = try XCTUnwrap(cycleGroup.trips.min { $0.totalScore < $1.totalScore })
XCTAssertEqual(cycleTrip.segments.count, 9)
XCTAssertEqual(cycleTrip.segments[0].alerts.count, 0)
// Make sure CoreData is happy
try self.tripKitContext.save()
}
func testParsingPublicTransportWithStops() throws {
let request = try self.request(fromFilename: "routing-with-stops")
XCTAssertNotNil(request)
XCTAssertEqual(request.tripGroups.count, 1)
XCTAssertEqual(request.trips.count, 16)
for trip in request.trips {
let services = trip.segments.compactMap(\.service)
XCTAssertEqual(services.count, 1)
for service in services {
XCTAssertTrue(service.hasServiceData)
XCTAssertEqual(service.shape?.routeIsTravelled, true)
for visit in service.visits ?? [] {
XCTAssertNotNil(visit.departure ?? visit.arrival, "No time for visit to stop \(visit.stop.stopCode) - service \(service.code)")
}
}
}
if let best = request.tripGroups.first?.visibleTrip, let bestService = best.segments[2].service {
XCTAssertEqual(best.totalScore, 29.8, accuracy: 0.1)
XCTAssertEqual(bestService.code, "847016")
XCTAssertEqual(bestService.visits?.count, 27)
XCTAssertEqual(bestService.sortedVisits.count, 27)
XCTAssertEqual(bestService.sortedVisits.map { $0.index }, (0...26).map { $0 })
XCTAssertEqual(bestService.sortedVisits.map { $0.stop.stopCode },
["202634",
"202635",
"202637",
"202653",
"202654",
"202656",
"202659",
"202661",
"202663",
"202255",
"202257",
"202268",
"202281",
"202258",
"202260",
"202151",
"202152",
"202153",
"202155",
"201060",
"201051",
"201056",
"200055",
"200057",
"2000421",
"200059",
"200065",
])
} else {
XCTFail("Couldn't find best trip")
}
// Make sure CoreData is happy
try self.tripKitContext.save()
}
func testParsingRouteGetsWalks() throws {
let request = try self.request(fromFilename: "routing-walk")
XCTAssertNotNil(request)
XCTAssertEqual(request.tripGroups.count, 1)
XCTAssertEqual(request.trips.count, 1)
let walkGroup = try XCTUnwrap(request.tripGroups.first)
let walkTrip = try XCTUnwrap(walkGroup.trips.first)
XCTAssertEqual(walkTrip.segments.count, 3)
XCTAssertNotNil(walkTrip.segments[1].shapes)
XCTAssertEqual(walkTrip.segments[1].shapes.count, 4)
// Make sure CoreData is happy
try self.tripKitContext.save()
}
func testParsingTripWithSharedScooter() throws {
let request = try self.request(fromFilename: "routing-scooter-vehicle")
XCTAssertNotNil(request)
XCTAssertEqual(request.tripGroups.count, 1)
XCTAssertEqual(request.trips.count, 2)
let sharedSegments = request.trips.flatMap(\.segments).filter(\.isSharedVehicle).filter(\.isStationary)
XCTAssertEqual(sharedSegments.count, 2)
for segment in sharedSegments {
XCTAssertNotNil(segment.sharedVehicle)
}
// Make sure CoreData is happy
try self.tripKitContext.save()
}
func testTripCache() throws {
let identifier = "Test"
let directory = TKFileCacheDirectory.documents // where TKRouter keeps its trips
let json: [String: Any] = try contentFromJSON(named: "routing-pt-oldish")
// 0. Clear
TKJSONCache.remove(identifier, directory: directory)
XCTAssertNil(TKJSONCache.read(identifier, directory: directory))
// 1. Save the trip to the cache
TKJSONCache.save(identifier, dictionary: json, directory: directory)
XCTAssertNotNil(TKJSONCache.read(identifier, directory: directory))
// 2. Retrieve from cache
let expectation = self.expectation(description: "Trip downloaded from cache")
TKTripFetcher.downloadTrip(URL(string: "http://example.com/")!, identifier: identifier, into: self.tripKitContext) { trip in
XCTAssertNotNil(trip)
expectation.fulfill()
}
waitForExpectations(timeout: 5) { error in
XCTAssertNil(error)
}
}
}
|
apache-2.0
|
1ed0704314dc1145538beffd67c31364
| 33.460251 | 156 | 0.651287 | 4.318825 | false | true | false | false |
gb-6k-house/YsSwift
|
Sources/Peacock/Extenstion/UIImage+Swift.swift
|
1
|
4626
|
/******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: 说明
** Copyright © 2017年 尧尚信息科技(wwww.yourshares.cn). All rights reserved
******************************************************************************/
import UIKit
import YsSwift
public extension UIImage {
public static func colorImage(_ color: UIColor, size: CGSize = CGSize(width: 4, height: 4)) -> UIImage {
let rect = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
extension YSSwift where Base: UIImage {
public func subImage(_ rect: CGRect) -> UIImage {
//
let subImageRef = self.base.cgImage?.cropping(to: rect)
let ysallBounds = CGRect(x: 0, y: 0, width: (subImageRef?.width)!, height: (subImageRef?.height)!)
UIGraphicsBeginImageContext(ysallBounds.size)
let context = UIGraphicsGetCurrentContext()
context?.draw(subImageRef!, in: ysallBounds)
let ysallImage = UIImage(cgImage: subImageRef!)
UIGraphicsEndImageContext()
return ysallImage
}
public func subImage() -> UIImage {
// 裁取正方形
let rawWidth = self.base.size.width
let rawHeight = self.base.size.height
if rawWidth > rawHeight {
let rect = CGRect(x: (rawWidth - rawHeight) / 2.0, y: 0, width: rawHeight, height: rawHeight)
return self.subImage(rect)
} else {
let rect = CGRect(x: 0, y: (rawHeight - rawWidth) / 2.0, width: rawWidth, height: rawWidth)
return self.subImage(rect)
}
}
/**
图片压缩,异步处理
- parameter size: 最终分辨率
- parameter maxDataSize: 图片大小kb
- parameter handler: 成功回调
*/
public func compressImage(_ size: CGSize, maxDataSize: Int, handler: ((_ imageData: Data?) -> Void)?) {
DispatchQueue.global(qos: .default).async {
let image = self.scaleImage(size)
let data = image.ys.resetSizeToData(maxDataSize)
DispatchQueue.main.async(execute: {
handler?(data)
})
}
}
/**
图片质量压缩到指定大小,二分
- parameter maxSize: 大小kb
- returns: NSData
*/
public func resetSizeToData(_ maxSize: Int) -> Data? {
// 先判断当前大小是否满足要求,不满足再进行压缩
let data = UIImageJPEGRepresentation(self.base, 1)!
if data.size() <= maxSize {
return data
}
var maxQuality: CGFloat = 1
var minQuelity: CGFloat = 0
while maxQuality - minQuelity >= 0.01 { // 精度
let midQuality = (maxQuality + minQuelity) / 2
let data = UIImageJPEGRepresentation(self.base, midQuality)!
if data.size() > maxSize {
maxQuality = midQuality
} else {
minQuelity = midQuality
}
}
return UIImageJPEGRepresentation(self.base, minQuelity)
}
/**
更改分辨率
- parameter size: 分辨率
- returns: UIImage
*/
public func scaleImage(_ size: CGSize) -> UIImage {
UIGraphicsBeginImageContext(size)
self.base.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
/**
获取圆形的图片
*/
public func circleImage(_ radius: CGFloat) -> UIImage {
UIGraphicsBeginImageContext(self.base.size)
let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: radius*2, height: radius*2))
path.addClip()
self.base.draw(in: CGRect(x: 0, y: 0, width: radius*2, height: radius*2))
let cImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return cImage!
}
}
extension Data {
/**
获取data size
- returns: kb
*/
func size() -> Int {
let sizeOrigin = Int64(self.count)
let sizeOriginKB = Int(sizeOrigin / 1024)
return sizeOriginKB
}
}
|
mit
|
036c5fe939b15c479863a81c181f857a
| 28.993243 | 107 | 0.560261 | 4.479314 | false | false | false | false |
damizhou/Leetcode
|
LeetCode/LeetCode/Easy/IntersectionofTwoArrays_349.swift
|
1
|
1788
|
//
// Day9_MoveZeroes_283.swift
// LeetCode
//
// Created by 潘传洲 on 16/11/3.
// Copyright © 2016年 pcz. All rights reserved.
//
import Foundation
class IntersectionofTwoArrays_349: NSObject {
/// Given two arrays, write a function to compute their intersection.给出两个数组,求两个数组的交集
/// Example:
/// Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
/// Note:
/// Each element in the result must be unique.结果中每个元素必须是唯一的.
/// The result can be in any order.结果可以无序
/// 解法1:哈希表存储.遍历其中一个数组,判断其中的元素是否在另一个数组和哈希表中,如果该元素在另一个数组且不在哈希表中,该元素则为目标元素.
///
/// - parameter nums1: 第一个数组
/// - parameter nums2: 第二个数组
///
/// - returns: 交集数组
static func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
var result = [Int]()
var hash : [Int:Int] = [Int:Int]()
for i in nums2 {
if nums1.contains(i) && hash[i] == nil{
result.append(i)
hash[i] = 1
}
}
return result
}
/// 解法2:利用集合可以删除特定元素的特性
static func intersection2(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
var result = [Int]()
var nums1Set = Set(nums1)
for i in nums2 {
if nums1Set.contains(i) {
result.append(i)
nums1Set.remove(i)
print(nums1Set)
if nums1Set.count == 0 {
break
}
}
}
return result
}
}
|
apache-2.0
|
88a11b128b8a957cce646c29629560d0
| 25.327586 | 88 | 0.502292 | 3.385809 | false | false | false | false |
groue/GRDB.swift
|
GRDB/Record/TableRecord.swift
|
1
|
20609
|
import Foundation
/// A type that builds database queries with the Swift language instead of SQL.
///
/// A `TableRecord` type is tied to one database table, and can build SQL
/// queries on that table.
///
/// To build SQL queries that involve several tables, define some ``Association``
/// between two `TableRecord` types.
///
/// Most of the time, your record types will get `TableRecord` conformance
/// through the ``MutablePersistableRecord`` or ``PersistableRecord`` protocols,
/// which provide persistence methods.
///
/// ## Topics
///
/// ### Configuring the Generated SQL
///
/// - ``databaseTableName-3tcw2``
/// - ``databaseSelection-7iphs``
/// - ``numberOfSelectedColumns(_:)``
///
/// ### Counting Records
///
/// - ``fetchCount(_:)``
///
/// ### Testing for Record Existence
///
/// - ``exists(_:id:)``
/// - ``exists(_:key:)-60hf2``
/// - ``exists(_:key:)-6ha6``
///
/// ### Deleting Records
///
/// - ``deleteAll(_:)``
/// - ``deleteAll(_:ids:)``
/// - ``deleteAll(_:keys:)-jbkm``
/// - ``deleteAll(_:keys:)-5s1jg``
/// - ``deleteOne(_:id:)``
/// - ``deleteOne(_:key:)-413u8``
/// - ``deleteOne(_:key:)-5pdh5``
///
/// ### Updating Records
///
/// - ``updateAll(_:onConflict:_:)-7vv9x``
/// - ``updateAll(_:onConflict:_:)-7atfw``
///
/// ### Building Query Interface Requests
///
/// `TableRecord` provide convenience access to most ``DerivableRequest`` and
/// ``QueryInterfaceRequest`` methods as static methods on the type itself.
///
/// - ``aliased(_:)``
/// - ``all()``
/// - ``annotated(with:)-3zi1n``
/// - ``annotated(with:)-4xoen``
/// - ``annotated(with:)-8ce7u``
/// - ``annotated(with:)-79389``
/// - ``annotated(withOptional:)``
/// - ``annotated(withRequired:)``
/// - ``filter(_:)``
/// - ``filter(id:)``
/// - ``filter(ids:)``
/// - ``filter(key:)-9ey53``
/// - ``filter(key:)-34lau``
/// - ``filter(keys:)-4hq8y``
/// - ``filter(keys:)-7skw1``
/// - ``filter(literal:)``
/// - ``filter(sql:arguments:)``
/// - ``having(_:)``
/// - ``including(all:)``
/// - ``including(optional:)``
/// - ``including(required:)``
/// - ``joining(optional:)``
/// - ``joining(required:)``
/// - ``limit(_:offset:)``
/// - ``matching(_:)``
/// - ``none()``
/// - ``order(_:)-9rc11``
/// - ``order(_:)-2033k``
/// - ``order(literal:)``
/// - ``order(sql:arguments:)``
/// - ``orderByPrimaryKey()``
/// - ``request(for:)``
/// - ``select(_:)-1gvtj``
/// - ``select(_:)-5oylt``
/// - ``select(_:as:)-1puz3``
/// - ``select(_:as:)-tjh0``
/// - ``select(literal:)``
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectPrimaryKey(as:)``
/// - ``with(_:)``
///
/// ### Defining Associations
///
/// - ``association(to:)``
/// - ``association(to:on:)``
/// - ``belongsTo(_:key:using:)-13t5r``
/// - ``belongsTo(_:key:using:)-81six``
/// - ``hasMany(_:key:using:)-45axo``
/// - ``hasMany(_:key:using:)-10d4k``
/// - ``hasMany(_:through:using:key:)``
/// - ``hasOne(_:key:using:)-4g9tm``
/// - ``hasOne(_:key:using:)-4v5xa``
/// - ``hasOne(_:through:using:key:)``
public protocol TableRecord {
/// The name of the database table used to build SQL queries.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// static var databaseTableName = "player"
/// }
///
/// // SELECT * FROM player
/// try Player.fetchAll(db)
/// ```
static var databaseTableName: String { get }
/// The columns selected by the record.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// static let databaseSelection = [AllColumns()]
/// }
///
/// struct PartialPlayer: TableRecord {
/// static let databaseTableName = "player"
/// static let databaseSelection = [Column("id"), Column("name")]
/// }
///
/// // SELECT * FROM player
/// try Player.fetchAll(db)
///
/// // SELECT id, name FROM player
/// try PartialPlayer.fetchAll(db)
/// ```
static var databaseSelection: [any SQLSelectable] { get }
}
extension TableRecord {
/// The default name of the database table used to build requests.
///
/// - Player -> "player"
/// - Place -> "place"
/// - PostalAddress -> "postalAddress"
/// - HTTPRequest -> "httpRequest"
/// - TOEFL -> "toefl"
static var defaultDatabaseTableName: String {
if let cached = defaultDatabaseTableNameCache.object(forKey: "\(Self.self)" as NSString) {
return cached as String
}
let typeName = "\(Self.self)".replacingOccurrences(of: "(.)\\b.*$", with: "$1", options: [.regularExpression])
let initial = typeName.replacingOccurrences(of: "^([A-Z]+).*$", with: "$1", options: [.regularExpression])
let tableName: String
switch initial.count {
case typeName.count:
tableName = initial.lowercased()
case 0:
tableName = typeName
case 1:
tableName = initial.lowercased() + typeName.dropFirst()
default:
tableName = initial.dropLast().lowercased() + typeName.dropFirst(initial.count - 1)
}
defaultDatabaseTableNameCache.setObject(tableName as NSString, forKey: "\(Self.self)" as NSString)
return tableName
}
/// The default name of the database table is derived from the name of
/// the type.
///
/// - `Player` -> "player"
/// - `Place` -> "place"
/// - `PostalAddress` -> "postalAddress"
/// - `HTTPRequest` -> "httpRequest"
/// - `TOEFL` -> "toefl"
public static var databaseTableName: String {
defaultDatabaseTableName
}
/// The default selection is all columns: `[AllColumns()]`.
public static var databaseSelection: [any SQLSelectable] {
[AllColumns()]
}
}
extension TableRecord {
// MARK: - Counting All
/// Returns the number of records in the database table.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// try dbQueue.read { db in
/// // SELECT COUNT(*) FROM player
/// let count = try Player.fetchCount(db)
/// }
/// ```
///
/// - parameter db: A database connection.
public static func fetchCount(_ db: Database) throws -> Int {
try all().fetchCount(db)
}
}
extension TableRecord {
// MARK: - SQL Generation
/// Returns the number of selected columns.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// struct PartialPlayer: TableRecord {
/// static let databaseTableName = "player"
/// static let databaseSelection = [Column("id"), Column("name")]
/// }
///
/// try dbQueue.write { db in
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text)
/// t.column("score", .integer)
/// }
///
/// try Player.numberOfSelectedColumns(db) // 3
/// try PartialPlayer.numberOfSelectedColumns(db) // 2
/// }
/// ```
public static func numberOfSelectedColumns(_ db: Database) throws -> Int {
// The alias makes it possible to count the columns in `SELECT *`:
let alias = TableAlias(tableName: databaseTableName)
let context = SQLGenerationContext(db)
return try databaseSelection
.map { $0.sqlSelection.qualified(with: alias) }
.columnCount(context)
}
}
// MARK: - Batch Delete
extension TableRecord {
/// Deletes all records, and returns the number of deleted records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// try dbQueue.write { db in
/// // DELETE FROM player
/// let count = try Player.deleteAll(db)
/// }
/// ```
///
/// - parameter db: A database connection.
/// - returns: The number of deleted records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public static func deleteAll(_ db: Database) throws -> Int {
try all().deleteAll(db)
}
}
// MARK: - Check Existence by Single-Column Primary Key
extension TableRecord {
/// Returns whether a record exists for this primary key.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// struct Player: TableRecord { }
/// struct Country: TableRecord { }
///
/// try dbQueue.read { db in
/// let playerExists = try Player.exists(db, key: 1)
/// let countryExists = try Country.exists(db, key: "FR")
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - key: A primary key value.
/// - returns: Whether a record exists for this primary key.
public static func exists(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool {
try !filter(key: key).isEmpty(db)
}
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// Returns whether a record exists for this primary key.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// struct Player: TableRecord, Identifiable {
/// var id: Int64
/// }
/// struct Country: TableRecord, Identifiable {
/// var id: String
/// }
///
/// try dbQueue.read { db in
/// let playerExists = try Player.exists(db, id: 1)
/// let countryExists = try Country.exists(db, id: "FR")
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - id: A primary key value.
/// - returns: Whether a record exists for this primary key.
public static func exists(_ db: Database, id: ID) throws -> Bool {
if id.databaseValue.isNull {
// Don't hit the database
return false
}
return try !filter(id: id).isEmpty(db)
}
}
// MARK: - Check Existence by Key
extension TableRecord {
/// Returns whether a record exists for this primary or unique key.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
/// struct Citizenship: TableRecord { }
///
/// try dbQueue.read { db in
/// let playerExists = Player.exists(db, key: ["id": 1])
/// let playerExists = Player.exists(db, key: ["email": "[email protected]"])
/// let citizenshipExists = Citizenship.exists(db, key: [
/// "citizenId": 1,
/// "countryCode": "FR",
/// ])
/// }
/// ```
///
/// A fatal error is raised if no unique index exists on a subset of the
/// key columns.
///
/// - parameters:
/// - db: A database connection.
/// - key: A unique key.
/// - returns: Whether a record exists for this key.
public static func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool {
try !filter(key: key).isEmpty(db)
}
}
// MARK: - Deleting by Single-Column Primary Key
extension TableRecord {
/// Deletes records identified by their primary keys, and returns the number
/// of deleted records.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// struct Player: TableRecord { }
/// struct Country: TableRecord { }
///
/// try dbQueue.write { db in
/// // DELETE FROM player WHERE id IN (1, 2, 3)
/// try Player.deleteAll(db, keys: [1, 2, 3])
///
/// // DELETE FROM country WHERE code IN ('FR', 'US')
/// try Country.deleteAll(db, keys: ["FR", "US"])
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - keys: A sequence of primary keys.
/// - returns: The number of deleted records.
@discardableResult
public static func deleteAll<Keys>(_ db: Database, keys: Keys)
throws -> Int
where Keys: Sequence, Keys.Element: DatabaseValueConvertible
{
let keys = Array(keys)
if keys.isEmpty {
// Avoid hitting the database
return 0
}
return try filter(keys: keys).deleteAll(db)
}
/// Deletes the record identified by its primary key, and returns whether a
/// record was deleted.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// struct Player: TableRecord { }
/// struct Country: TableRecord { }
///
/// try dbQueue.write { db in
/// // DELETE FROM player WHERE id = 1
/// try Player.deleteOne(db, key: 1)
///
/// // DELETE FROM country WHERE code = 'FR'
/// try Country.deleteOne(db, key: "FR")
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - key: A primary key value.
/// - returns: Whether a record was deleted.
@discardableResult
public static func deleteOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool {
if key.databaseValue.isNull {
// Don't hit the database
return false
}
return try deleteAll(db, keys: [key]) > 0
}
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
/// Deletes records identified by their primary keys, and returns the number
/// of deleted records.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// struct Player: TableRecord, Identifiable {
/// var id: Int64
/// }
/// struct Country: TableRecord, Identifiable {
/// var id: String
/// }
///
/// try dbQueue.write { db in
/// // DELETE FROM player WHERE id IN (1, 2, 3)
/// try Player.deleteAll(db, ids: [1, 2, 3])
///
/// // DELETE FROM country WHERE code IN ('FR', 'US')
/// try Country.deleteAll(db, ids: ["FR", "US"])
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - ids: A collection of primary keys.
/// - returns: The number of deleted records.
@discardableResult
public static func deleteAll<IDS>(_ db: Database, ids: IDS) throws -> Int
where IDS: Collection, IDS.Element == ID
{
if ids.isEmpty {
// Avoid hitting the database
return 0
}
return try filter(ids: ids).deleteAll(db)
}
/// Deletes the record identified by its primary key, and returns whether a
/// record was deleted.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// struct Player: TableRecord, Identifiable {
/// var id: Int64
/// }
/// struct Country: TableRecord, Identifiable {
/// var id: String
/// }
///
/// try dbQueue.write { db in
/// // DELETE FROM player WHERE id = 1
/// try Player.deleteOne(db, id: 1)
///
/// // DELETE FROM country WHERE code = 'FR'
/// try Country.deleteOne(db, id: "FR")
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - id: A primary key value.
/// - returns: Whether a record was deleted.
@discardableResult
public static func deleteOne(_ db: Database, id: ID) throws -> Bool {
try deleteAll(db, ids: [id]) > 0
}
}
// MARK: - Deleting by Key
extension TableRecord {
/// Deletes records identified by their primary or unique keys, and returns
/// the number of deleted records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
/// struct Citizenship: TableRecord { }
///
/// try dbQueue.write { db in
/// // DELETE FROM player WHERE id = 1
/// try Player.deleteAll(db, keys: [["id": 1]])
///
/// // DELETE FROM player WHERE email = '[email protected]'
/// try Player.deleteAll(db, keys: [["email": "[email protected]"]])
///
/// // DELETE FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
/// try Citizenship.deleteAll(db, keys: [
/// ["citizenId": 1, "countryCode": "FR"],
/// ])
/// }
/// ```
///
/// A fatal error is raised if no unique index exists on a subset of the
/// key columns.
///
/// - parameters:
/// - db: A database connection.
/// - keys: An array of key dictionaries.
/// - returns: The number of deleted records.
@discardableResult
public static func deleteAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int {
if keys.isEmpty {
// Avoid hitting the database
return 0
}
return try filter(keys: keys).deleteAll(db)
}
/// Deletes the record identified by its primary or unique keys, and returns
/// whether a record was deleted.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
/// struct Citizenship: TableRecord { }
///
/// try dbQueue.write { db in
/// // DELETE FROM player WHERE id = 1
/// try Player.deleteOne(db, key: ["id": 1])
///
/// // DELETE FROM player WHERE email = '[email protected]'
/// try Player.deleteOne(db, key: ["email": "[email protected]"])
///
/// // DELETE FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
/// try Citizenship.deleteOne(db, key: [
/// "citizenId": 1,
/// "countryCode": "FR",
/// ])
/// }
/// ```
///
/// A fatal error is raised if no unique index exists on a subset of the
/// key columns.
/// - parameters:
/// - db: A database connection.
/// - key: A dictionary of values.
/// - returns: Whether a record was deleted.
@discardableResult
public static func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool {
try deleteAll(db, keys: [key]) > 0
}
}
// MARK: - Batch Update
extension TableRecord {
/// Updates all records, and returns the number of updated records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try Player.updateAll(db, [Column("score").set(to: 0)])
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution,
/// defaulting to the record's persistenceConflictPolicy.
/// - parameter assignments: An array of column assignments.
/// - returns: The number of updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public static func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> Int
{
try all().updateAll(db, onConflict: conflictResolution, assignments)
}
/// Updates all records, and returns the number of updated records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord { }
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try Player.updateAll(db, Column("score").set(to: 0))
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution,
/// defaulting to the record's persistenceConflictPolicy.
/// - parameter assignments: Column assignments.
/// - returns: The number of updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public static func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: ColumnAssignment...)
throws -> Int
{
try updateAll(db, onConflict: conflictResolution, assignments)
}
}
/// Calculating `defaultDatabaseTableName` is somewhat expensive due to the regular expression evaluation
///
/// This cache mitigates the cost of the calculation by storing the name for later retrieval
private let defaultDatabaseTableNameCache = NSCache<NSString, NSString>()
|
mit
|
7c491300dda16d6de75f69006d62b9da
| 30.368341 | 118 | 0.561842 | 4.171862 | false | false | false | false |
bradhowes/SynthInC
|
Pods/SwiftyUserDefaults/Sources/DefaultsSerializable+BuiltIns.swift
|
1
|
10352
|
//
// SwiftyUserDefaults
//
// Copyright (c) 2015-2018 Radosław Pietruszewski, Łukasz Mróz
//
// 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
extension String: DefaultsSerializable, DefaultsDefaultArrayValueType, DefaultsDefaultValueType {
public static var defaultValue: String = ""
public static var defaultArrayValue: [String] = []
public static func get(key: String, userDefaults: UserDefaults) -> String? {
return userDefaults.string(forKey: key)
}
public static func getArray(key: String, userDefaults: UserDefaults) -> [String]? {
return userDefaults.array(forKey: key) as? [String]
}
public static func save(key: String, value: String?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
public static func saveArray(key: String, value: [String], userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
}
extension Int: DefaultsSerializable, DefaultsDefaultArrayValueType, DefaultsDefaultValueType {
public static var defaultValue: Int = 0
public static var defaultArrayValue: [Int] = []
public static func get(key: String, userDefaults: UserDefaults) -> Int? {
return userDefaults.number(forKey: key)?.intValue
}
public static func getArray(key: String, userDefaults: UserDefaults) -> [Int]? {
return userDefaults.array(forKey: key) as? [Int]
}
public static func save(key: String, value: Int?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
public static func saveArray(key: String, value: [Int], userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
}
extension Double: DefaultsSerializable, DefaultsDefaultArrayValueType, DefaultsDefaultValueType {
public static var defaultValue: Double = 0.0
public static var defaultArrayValue: [Double] = []
public static func get(key: String, userDefaults: UserDefaults) -> Double? {
return userDefaults.number(forKey: key)?.doubleValue
}
public static func getArray(key: String, userDefaults: UserDefaults) -> [Double]? {
return userDefaults.array(forKey: key) as? [Double]
}
public static func save(key: String, value: Double?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
public static func saveArray(key: String, value: [Double], userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
}
extension Bool: DefaultsSerializable, DefaultsDefaultArrayValueType, DefaultsDefaultValueType {
public static var defaultValue: Bool = false
public static var defaultArrayValue: [Bool] = []
public static func get(key: String, userDefaults: UserDefaults) -> Bool? {
// @warning we use number(forKey:) instead of bool(forKey:), because
// bool(forKey:) will always return value, even if it's not set
// and it does a little bit of magic under the hood as well
// e.g. transforming strings like "YES" or "true" to true
return userDefaults.number(forKey: key)?.boolValue
}
public static func getArray(key: String, userDefaults: UserDefaults) -> [Bool]? {
return userDefaults.array(forKey: key) as? [Bool]
}
public static func save(key: String, value: Bool?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
public static func saveArray(key: String, value: [Bool], userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
}
extension Data: DefaultsSerializable, DefaultsDefaultArrayValueType, DefaultsDefaultValueType {
public static var defaultValue: Data = Data()
public static var defaultArrayValue: [Data] = []
public static func get(key: String, userDefaults: UserDefaults) -> Data? {
return userDefaults.data(forKey: key)
}
public static func getArray(key: String, userDefaults: UserDefaults) -> [Data]? {
return userDefaults.array(forKey: key) as? [Data]
}
public static func save(key: String, value: Data?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
public static func saveArray(key: String, value: [Data], userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
}
extension Date: DefaultsSerializable {
public static func get(key: String, userDefaults: UserDefaults) -> Date? {
return userDefaults.object(forKey: key) as? Date
}
public static func getArray(key: String, userDefaults: UserDefaults) -> [Date]? {
return userDefaults.array(forKey: key) as? [Date]
}
public static func save(key: String, value: Date?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
public static func saveArray(key: String, value: [Date], userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
}
extension URL: DefaultsSerializable {
public static func get(key: String, userDefaults: UserDefaults) -> URL? {
return userDefaults.url(forKey: key)
}
public static func getArray(key: String, userDefaults: UserDefaults) -> [URL]? {
return userDefaults.data(forKey: key).flatMap(NSKeyedUnarchiver.unarchiveObject) as? [URL]
}
public static func save(key: String, value: URL?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
public static func saveArray(key: String, value: [URL], userDefaults: UserDefaults) {
userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)
}
}
//extension Array: DefaultsSerializable where Element: DefaultsSerializable {
//
// public static func get(key: String, userDefaults: UserDefaults) -> [Element]? {
// return Element.getArray(key: key, userDefaults: userDefaults)
// }
//
// public static func getArray(key: String, userDefaults: UserDefaults) -> [[Element]]? {
// return [Element].getArray(key: key, userDefaults: userDefaults)
// }
//
// public static func save(key: String, value: [Element]?, userDefaults: UserDefaults) {
// guard let value = value else {
// userDefaults.removeObject(forKey: key)
// return
// }
//
// Element.saveArray(key: key, value: value, userDefaults: userDefaults)
// }
//
// public static func saveArray(key: String, value: [[Element]], userDefaults: UserDefaults) {
// [Element].saveArray(key: key, value: value, userDefaults: userDefaults)
// }
//}
extension DefaultsStoreable where Self: Encodable {
public static func saveArray(key: String, value: [Self], userDefaults: UserDefaults) {
userDefaults.set(encodable: value, forKey: key)
}
public static func save(key: String, value: Self?, userDefaults: UserDefaults) {
guard let value = value else {
userDefaults.removeObject(forKey: key)
return
}
userDefaults.set(encodable: value, forKey: key)
}
}
extension DefaultsGettable where Self: Decodable {
public static func getArray(key: String, userDefaults: UserDefaults) -> [Self]? {
return userDefaults.decodable(forKey: key) as [Self]?
}
public static func get(key: String, userDefaults: UserDefaults) -> Self? {
return userDefaults.decodable(forKey: key) as Self?
}
}
extension DefaultsGettable where Self: NSCoding {
public static func get(key: String, userDefaults: UserDefaults) -> Self? {
return userDefaults.data(forKey: key).flatMap(NSKeyedUnarchiver.unarchiveObject) as? Self
}
public static func getArray(key: String, userDefaults: UserDefaults) -> [Self]? {
return userDefaults.data(forKey: key).flatMap(NSKeyedUnarchiver.unarchiveObject) as? [Self]
}
}
extension DefaultsStoreable where Self: NSCoding {
public static func save(key: String, value: Self?, userDefaults: UserDefaults) {
guard let value = value else {
userDefaults.removeObject(forKey: key)
return
}
userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)
}
public static func saveArray(key: String, value: [Self], userDefaults: UserDefaults) {
userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)
}
}
extension DefaultsGettable where Self: RawRepresentable {
public static func get(key: String, userDefaults: UserDefaults) -> Self? {
return userDefaults.object(forKey: key).flatMap { Self(rawValue: $0 as! Self.RawValue) }
}
public static func getArray(key: String, userDefaults: UserDefaults) -> [Self]? {
return userDefaults.array(forKey: key)?.compactMap { Self(rawValue: $0 as! Self.RawValue) }
}
}
extension DefaultsStoreable where Self: RawRepresentable {
public static func save(key: String, value: Self?, userDefaults: UserDefaults) {
guard let value = value?.rawValue else {
userDefaults.removeObject(forKey: key)
return
}
userDefaults.set(value, forKey: key)
}
public static func saveArray(key: String, value: [Self], userDefaults: UserDefaults) {
let raw = value.map { $0.rawValue }
userDefaults.set(raw, forKey: key)
}
}
|
mit
|
170edd3c62eb4e78fb138551326891a5
| 35.568905 | 99 | 0.690985 | 4.435919 | false | false | false | false |
CodingGirl1208/FlowerField
|
FlowerField/FlowerField/AppDelegate.swift
|
1
|
6517
|
//
// AppDelegate.swift
// FlowerField
//
// Created by 易屋之家 on 16/7/21.
// Copyright © 2016年 xuping. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//设置全局的UINavigationBar属性
let bar = UINavigationBar.appearance()
bar.tintColor = UIColor.blackColor()
bar.titleTextAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(15),NSForegroundColorAttributeName: UIColor.blackColor()]
window = UIWindow.init(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = MainViewController()
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "xuping.FlowerField" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("FlowerField", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
|
mit
|
bc3b8646302b37060ba9440474ecda0b
| 51.780488 | 291 | 0.713494 | 5.907188 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureOnboarding/Sources/FeatureOnboardingUI/OnboardingChecklist/OnboardingChecklistReducer+Analytics.swift
|
1
|
3146
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import ComposableArchitecture
private typealias AnalyticsEvent = AnalyticsEvents.New.OnboardingChecklist
extension Reducer where State == OnboardingChecklist.State,
Action == OnboardingChecklist.Action,
Environment == OnboardingChecklist.Environment
{
func analytics() -> Reducer<State, Action, Environment> {
combined(
with: Reducer { state, action, environment in
switch action {
case .didSelectItem(let item, let selectionSource):
let completedItems = state.completedItems
return .fireAndForget {
if let peeksheetItem = AnalyticsEvent.PeeksheetItem(item: item) {
environment.analyticsRecorder.record(
event: AnalyticsEvent.peeksheetSelectionClicked(
buttonClicked: selectionSource == .callToActionButton,
currentStepCompleted: completedItems.count,
item: peeksheetItem
)
)
}
}
case .dismissFullScreenChecklist:
guard let firstPendingStep = state.firstPendingStep else {
return .none
}
return .fireAndForget {
environment.analyticsRecorder.record(
event: AnalyticsEvent.peeksheetDismissed(currentStepCompleted: firstPendingStep)
)
}
case .presentFullScreenChecklist:
guard let firstPendingStep = state.firstPendingStep else {
return .none
}
return .merge(
.fireAndForget {
environment.analyticsRecorder.record(
event: AnalyticsEvent.peeksheetViewed(
currentStepCompleted: firstPendingStep
)
)
},
.fireAndForget {
environment.analyticsRecorder.record(
event: AnalyticsEvent.peeksheetProcessClicked(
currentStepCompleted: firstPendingStep
)
)
}
)
default:
return .none
}
}
)
}
}
extension OnboardingChecklist.State {
fileprivate var firstPendingStep: AnalyticsEvent.PendingStep? {
guard let firstIncompleteItem = firstIncompleteItem else {
return nil
}
guard let firstPendingStep = AnalyticsEvent.PendingStep(firstIncompleteItem.id) else {
return nil
}
return firstPendingStep
}
}
|
lgpl-3.0
|
fc2a389f9b0c1a6f8243865d4aaaaa73
| 37.82716 | 108 | 0.488394 | 7.213303 | false | false | false | false |
iandundas/Loca
|
Loca/Classes/LocationAuthorizationProvider.swift
|
1
|
3898
|
//
// LocationAuthorizationProvider.swift
// Tacks
//
// Created by Ian Dundas on 27/05/2016.
// Copyright © 2016 Ian Dundas. All rights reserved.
//
import Foundation
import CoreLocation
import ReactiveKit
public enum LocationAuthorizationState{
case noDecisionYet
case userNotPermitted
case userDisabled
case authorized(always: Bool)
public static func fromClAuthorizationStatus(_ status: CLAuthorizationStatus) -> LocationAuthorizationState{
switch(status){
case .authorizedAlways: return .authorized(always: true)
case .authorizedWhenInUse: return .authorized(always: false)
case .restricted: return .userNotPermitted
case .denied: return .userDisabled
case .notDetermined: fallthrough
default: return .noDecisionYet
}
}
public static var currentState: LocationAuthorizationState{
return fromClAuthorizationStatus(CLLocationManager.authorizationStatus())
}
}
public enum LocationAuthorizationError: Error{
case denied, restricted
}
public protocol LocationAuthorizationProviderType{
var state: Property<LocationAuthorizationState> {get}
static var stateStream: Signal1<LocationAuthorizationState> {get}
func authorize() -> Signal<LocationAuthorizationState, LocationAuthorizationError>
}
public final class LocationAuthorizationProvider: LocationAuthorizationProviderType{
public let state = Property<LocationAuthorizationState>(LocationAuthorizationState.currentState)
fileprivate let bag = DisposeBag()
public init(){
LocationAuthorizationProvider.stateStream
.bind(to:state)
.dispose(in: bag)
}
public static var stateStream: Signal1<LocationAuthorizationState>{
return CLLocationManager.statusStream().map { LocationAuthorizationState.fromClAuthorizationStatus($0) }
}
public func authorize() -> Signal<LocationAuthorizationState, LocationAuthorizationError>{
return Signal { observer in
let startingState = LocationAuthorizationState.currentState
guard case .noDecisionYet = startingState else {
switch(startingState){
case .authorized(always: _):
observer.next(startingState)
observer.completed()
case .userNotPermitted:
observer.failed(LocationAuthorizationError.restricted)
case .userDisabled:fallthrough
default:
observer.failed(LocationAuthorizationError.denied)
}
return SimpleDisposable()
}
let bag = DisposeBag()
let locationManager = CLLocationManager()
locationManager.reactive.authorizationStatus
.map {LocationAuthorizationState.fromClAuthorizationStatus($0)}
.observeNext { status in
switch(status){
case .authorized(_):
observer.next(status)
observer.completed()
case .userNotPermitted:
observer.failed(LocationAuthorizationError.restricted)
case .userDisabled:
observer.failed(LocationAuthorizationError.denied)
default:
observer.next(.noDecisionYet)
}
}.dispose(in: bag)
locationManager.requestWhenInUseAuthorization()
BlockDisposable{
_ = locationManager // hold reference to it in the disposable block otherwise it's deallocated.
}.dispose(in: bag)
return bag
}
}
}
|
apache-2.0
|
8233dd83997b01b6d0ead5f2f3f2303a
| 33.486726 | 112 | 0.617655 | 6.146688 | false | false | false | false |
jifusheng/MyDouYuTV
|
DouYuTV/DouYuTV/Classes/Home/View/CateCollectionCell.swift
|
1
|
2057
|
//
// CateCollectionCell.swift
// DouYuTV
//
// Created by 王建伟 on 2016/11/23.
// Copyright © 2016年 jifusheng. All rights reserved.
// 分类item
import UIKit
private let cellIdentifier = "GameCollectionCell"
class CateCollectionCell: UICollectionViewCell {
@IBOutlet fileprivate weak var collectionView: UICollectionView!
var itemArray : [BaseGroupModel]? {
didSet {
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = .init(rawValue: 0)
//设置collectionView的数据源和代理
collectionView.dataSource = self
collectionView.delegate = self;
//注册cell
collectionView.register(UINib(nibName: "GameCollectionCell", bundle: nil), forCellWithReuseIdentifier: cellIdentifier)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: collectionView.bounds.width / 4, height: collectionView.bounds.height / 2)
}
}
// MARK: - 实现collectionView的数据源方法
extension CateCollectionCell : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemArray?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! GameCollectionCell
cell.placeholderImageName = "home_column_more"
cell.baseModel = itemArray![indexPath.item]
return cell
}
}
// MARK: - 实现collectionView的代理方法
extension CateCollectionCell : UICollectionViewDelegate {
// MARK: - 监听item的点击
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
|
mit
|
56bb42f9516d2db1fe48cdc1d4e5d4b1
| 32.59322 | 129 | 0.706357 | 5.215789 | false | false | false | false |
faimin/ZDOpenSourceDemo
|
ZDOpenSourceSwiftDemo/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift
|
7
|
1761
|
import Foundation
#if !PMKCocoaPods
import PromiseKit
#endif
/**
To import the `NSObject` category:
use_frameworks!
pod "PromiseKit/Foundation"
Or `NSObject` is one of the categories imported by the umbrella pod:
use_frameworks!
pod "PromiseKit"
And then in your sources:
import PromiseKit
*/
extension NSObject {
/**
- Returns: A promise that resolves when the provided keyPath changes.
- Warning: *Important* The promise must not outlive the object under observation.
- SeeAlso: Apple’s KVO documentation.
*/
public func observe(_: PMKNamespacer, keyPath: String) -> Guarantee<Any?> {
return Guarantee { KVOProxy(observee: self, keyPath: keyPath, resolve: $0) }
}
}
private class KVOProxy: NSObject {
var retainCycle: KVOProxy?
let fulfill: (Any?) -> Void
@discardableResult
init(observee: NSObject, keyPath: String, resolve: @escaping (Any?) -> Void) {
fulfill = resolve
super.init()
observee.addObserver(self, forKeyPath: keyPath, options: NSKeyValueObservingOptions.new, context: pointer)
retainCycle = self
}
fileprivate override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let change = change, context == pointer {
defer { retainCycle = nil }
fulfill(change[NSKeyValueChangeKey.newKey])
if let object = object as? NSObject, let keyPath = keyPath {
object.removeObserver(self, forKeyPath: keyPath)
}
}
}
private lazy var pointer: UnsafeMutableRawPointer = {
return Unmanaged<KVOProxy>.passUnretained(self).toOpaque()
}()
}
|
mit
|
d0d39278b60203d1c0de534117d0b654
| 29.859649 | 163 | 0.664582 | 4.703209 | false | false | false | false |
tomesm/ShinyWeather
|
ShinyWeather/CurrentWeather.swift
|
1
|
2126
|
//
// CurrentWeather.swift
// ShinyWeather
//
// Created by martin on 27/09/2017.
// Copyright © 2017 Martin Tomes. All rights reserved.
//
import UIKit
import Alamofire
class CurrentWeather {
var _cityName: String!
var _date: String!
var _weatherType: String!
var _currentTemp: Int!
var cityName: String {
if _cityName == nil {
_cityName = "default city"
}
return _cityName
}
var date: String {
if _date == nil {
_date = ""
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
let currentDate = dateFormatter.string(from: Date())
self._date = "Today, \(currentDate)"
return _date
}
var weatherType: String {
if _weatherType == nil {
_weatherType = ""
}
return _weatherType
}
var currentTemp: Int {
if _currentTemp == nil {
_currentTemp = 0
}
return _currentTemp
}
// alamofire downloads
func downloadWeatherDetails(completed: @escaping DownloadComplete) {
//let currentWeatherUrl = URL(string: CURRENT_WEATHER_URL)
Alamofire.request(CURRENT_WEATHER_URL).responseJSON { response in
let result = response.result
// lets start parsing JSON
guard let dict = result.value as? Dictionary<String, AnyObject>,
let name = dict["name"] as? String,
let weather = dict["weather"] as? [Dictionary<String, AnyObject>],
let weatherType = weather[0]["main"] as? String,
let main = dict["main"] as? Dictionary<String, AnyObject>,
let temp = main["temp"] as? Double
else { return }
let kelvinToCelsius = temp - 273.15
self._currentTemp = Int(kelvinToCelsius)
self._cityName = name.capitalized
self._weatherType = weatherType.capitalized
completed()
}
}
}
|
mit
|
c0833607a966bf5415cac6849f5c745f
| 22.611111 | 84 | 0.548706 | 4.829545 | false | false | false | false |
chrisballinger/OpenCallBlock
|
OpenCallBlock/ViewController.swift
|
1
|
10272
|
//
// ViewController.swift
// OpenCallBlock
//
// Created by Chris Ballinger on 10/27/17.
// Copyright © 2017 Chris Ballinger. All rights reserved.
//
import UIKit
import CallDataKit
import PhoneNumberKit
import CocoaLumberjackSwift
import CallKit
import Contacts
class ViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var numberField: PhoneNumberTextField!
@IBOutlet weak var prefixLabel: UILabel!
@IBOutlet weak var extensionActiveLabel: UILabel!
@IBOutlet weak var blockedLabel: UILabel!
@IBOutlet weak var whitelistLabel: UILabel!
@IBOutlet weak var extraBlockingSwitch: UISwitch!
let numberKit = PhoneNumberKit()
private let database = DatabaseManager.shared
private var user: User? {
get {
return database.user
}
set {
database.user = newValue
}
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
numberField.delegate = self
numberField.maxDigits = 10
numberField.withPrefix = false
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
refreshExtensionState()
refreshUserState(user)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: animated)
}
// MARK: - Data Refresh
/// Check whether or not extension is active
private func refreshExtensionState() {
CXCallDirectoryManager.sharedInstance.reloadExtension(withIdentifier: Constants.CallDirectoryExtensionIdentifier) { (reloadError) in
if let error = reloadError as? CXErrorCodeCallDirectoryManagerError {
DDLogError("Error reloading CXCallDirectoryManager extension: \(error.localizedDescription) \"\(error.code)\"")
} else {
DDLogError("Reloaded CXCallDirectoryManager extension.")
}
CXCallDirectoryManager.sharedInstance.getEnabledStatusForExtension(withIdentifier: Constants.CallDirectoryExtensionIdentifier) { (status, statusError) in
if let error = statusError {
DDLogError("Error getting status for CXCallDirectoryManager extension: \(error.localizedDescription)")
} else {
DDLogError("Got status for CXCallDirectoryManager extension: \(status)")
}
DispatchQueue.main.async {
// show warning if enabled with error
if status != .disabled,
reloadError != nil || statusError != nil {
self.setExtensionLabelActive(nil)
} else {
self.setExtensionLabelActive(status == .enabled)
}
}
}
}
}
/// true=working&enabled, false=user disabled, nil=error
private func setExtensionLabelActive(_ active: Bool?) {
guard let active = active else {
self.extensionActiveLabel.text = "\(UIStrings.ExtensionActive): ⚠️"
return
}
if active {
self.extensionActiveLabel.text = "\(UIStrings.ExtensionActive): ✅"
} else {
self.extensionActiveLabel.text = "\(UIStrings.ExtensionActive): ❌"
}
}
/// Refresh UI from User data
private func refreshUserState(_ user: User?) {
if let number = user?.me.rawNumber {
numberField.text = "\(number)"
refreshNpaNxx(numberString: "\(number)")
} else {
numberField.text = ""
}
whitelistLabel.text = "\(UIStrings.Whitelist): \(user?.whitelist.count ?? 0) \(UIStrings.Numbers)"
blockedLabel.text = "\(UIStrings.Blocked): \(user?.blocklist.count ?? 0) \(UIStrings.Numbers)"
extraBlockingSwitch.isOn = user?.extraBlocking ?? false
refreshExtensionState()
}
/// Refreshes NPA-NXX field, optionally saving User data
func refreshNpaNxx(numberString: String, shouldSave: Bool = false) {
var _number: PhoneNumber? = nil
do {
_number = try numberKit.parse(numberString, withRegion: "us", ignoreType: true)
} catch {
//DDLogWarn("Bad number \(error)")
}
guard let number = _number,
let npaNxx = number.npaNxxString else { return }
// valid number found
numberField.resignFirstResponder()
prefixLabel.text = "\(UIStrings.NpaNxxPrefix): \(npaNxx)"
if shouldSave {
var user = self.user
user?.me = Contact(phoneNumber: number)
if user == nil {
user = User(phoneNumber: number)
}
user?.extraBlocking = extraBlockingSwitch.isOn
// TODO: move this
user?.refreshBlocklist()
if let user = user {
self.user = user
}
refreshUserState(user)
}
}
// MARK: - UI Actions
@IBAction func refreshWhitelist(_ sender: Any) {
guard var user = self.user else {
DDLogError("Must create a user first")
return
}
let store = CNContactStore()
store.requestAccess(for: .contacts) { (success, error) in
if let error = error {
DDLogError("Contacts permission error: \(error)")
return
}
var whitelist: Set<Contact> = []
do {
let request = CNContactFetchRequest(keysToFetch: [CNContactPhoneNumbersKey as CNKeyDescriptor])
try store.enumerateContacts(with: request, usingBlock: { (contact, stop) in
for number in contact.phoneNumbers {
do {
let numberString = number.value.stringValue
let phoneNumber = try self.numberKit.parse(numberString, withRegion: "us", ignoreType: true)
let contact = Contact(phoneNumber: phoneNumber)
whitelist.insert(contact)
} catch {
DDLogError("Error parsing phone number: \(error)")
}
}
})
} catch {
DDLogError("Could not enumerate contacts \(error)")
}
user.whitelist = whitelist.sorted()
user.refreshBlocklist()
self.user = user
DispatchQueue.main.async {
self.refreshUserState(user)
}
}
}
@IBAction func extraBlockingValueChanged(_ sender: Any) {
if var user = self.user {
user.extraBlocking = extraBlockingSwitch.isOn
user.refreshBlocklist()
self.user = user
}
refreshUserState(self.user)
}
@IBAction func numberFieldEditingChanged(_ sender: Any) {
guard let numberString = numberField.text else {
return
}
refreshNpaNxx(numberString: numberString, shouldSave: true)
}
@IBAction func enableExtensionPressed(_ sender: Any) {
// TODO: Show alert view explaining how to enable
// Settings => Phone => Call Blocking & Identification => Enable OpenCallBlock
refreshExtensionState()
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Show List editor for white/block list
guard let user = self.user,
let listEditor = segue.destination as? ListEditorViewController,
let identifier = segue.identifier,
let listEditorSegue = ListEditorSegue(rawValue: identifier) else {
return
}
listEditor.setupWithUser(user, editorType: listEditorSegue.editorType)
}
}
// MARK: - Constants
private struct Constants {
static let CallDirectoryExtensionIdentifier = "io.ballinger.OpenCallBlock.CallDirectoryExtension"
static let EditBlocklistSegue = "editBlocklist"
static let EditWhitelistSegue = "editWhitelist"
}
private struct UIStrings {
static let ExtensionActive = "Extension Active"
static let NpaNxxPrefix = "NPA-NXX Prefix"
static let Whitelist = "Whitelist"
static let Blocked = "Blocked"
static let Numbers = "numbers"
}
// MARK: - Extensions
extension ViewController: UITextFieldDelegate {
}
private extension PhoneNumber {
/// Returns NPA-NXX prefix of US number e.g. 800-555-5555 returns 800-555
var npaNxx: UInt64? {
guard countryCode == 1 else { return nil }
return nationalNumber/10_000
}
var npaNxxString: String? {
guard let npaNxx = self.npaNxx else { return nil }
return "\(npaNxx / 1000)-\(npaNxx % 1000)"
}
}
extension CXErrorCodeCallDirectoryManagerError.Code: CustomStringConvertible {
public var description: String {
switch self {
case .unknown:
return "An unknown error occurred."
case .noExtensionFound:
return "The call directory manager could not find a corresponding app extension."
case .loadingInterrupted:
return "The call directory manager was interrupted while loading the app extension."
case .entriesOutOfOrder:
return "The entries in the call directory are out of order."
case .duplicateEntries:
return "There are duplicate entries in the call directory."
case .maximumEntriesExceeded:
return "There are too many entries in the call directory."
case .extensionDisabled:
return "The call directory extension isn’t enabled by the system."
case .currentlyLoading:
return "currentlyLoading"
case .unexpectedIncrementalRemoval:
return "expectedIncrementalRemoval"
}
}
}
|
mpl-2.0
|
967bd2c5db161ab39786e47ec737c313
| 34.752613 | 165 | 0.599649 | 5.125375 | false | false | false | false |
sgr-ksmt/i18nSwift
|
i18nSwiftTests/LanguageTests.swift
|
1
|
2742
|
//
// LanguageTests.swift
// i18nSwift
//
// Created by Suguru Kishimoto on 3/30/17.
// Copyright © 2017 Suguru Kishimoto. All rights reserved.
//
import XCTest
@testable import i18nSwift
class LanguageTests: XCTestCase {
override func setUp() {
super.setUp()
i18n.Language.dataStore = MockLanguageDataStore()
i18n.Language.languageBundle = Bundle(for: LanguageTests.self)
}
override func tearDown() {
super.tearDown()
i18n.Language.dataStore.reset(forKey: i18n.Language.Constant.currentLanguageKey)
}
func testAvailableLanguages() {
do {
let availableLanguages = i18n.Language.availableLanguages()
XCTAssertTrue(availableLanguages.contains("Base"))
XCTAssertTrue(availableLanguages.contains("en"))
XCTAssertTrue(availableLanguages.contains("ja"))
XCTAssertTrue(availableLanguages.contains("fr"))
XCTAssertEqual(availableLanguages.count, 4)
}
do {
let availableLanguages = i18n.Language.availableLanguages(includeBase: false)
XCTAssertFalse(availableLanguages.contains("Base"))
XCTAssertTrue(availableLanguages.contains("en"))
XCTAssertTrue(availableLanguages.contains("ja"))
XCTAssertTrue(availableLanguages.contains("fr"))
XCTAssertEqual(availableLanguages.count, 3)
}
}
func testCurrentLanguage() {
XCTAssertNotNil(i18n.Language.Constant())
let defaultLanguage = i18n.Language.default
XCTAssertEqual(defaultLanguage, i18n.Language.current)
i18n.Language.current = "fr"
XCTAssertNotEqual(defaultLanguage, i18n.Language.current)
XCTAssertEqual(i18n.Language.current, "fr")
i18n.Language.reset()
XCTAssertNotEqual("fr", i18n.Language.current)
XCTAssertEqual(defaultLanguage, i18n.Language.current)
i18n.Language.current = "unavailable_language"
XCTAssertNotEqual("unavailable_language", i18n.Language.current)
XCTAssertEqual(defaultLanguage, i18n.Language.current)
}
func testDisplayName() {
XCTAssertEqual(i18n.Language.displayName(), "English")
XCTAssertEqual(i18n.Language.displayName(), i18n.Language.displayName(for: "en"))
i18n.Language.current = "ja"
XCTAssertEqual(i18n.Language.displayName(), "日本語")
XCTAssertEqual(i18n.Language.displayName(), i18n.Language.displayName(for: "ja"))
i18n.Language.current = "Base"
XCTAssertNil(i18n.Language.displayName())
XCTAssertEqual(i18n.Language.displayName(), i18n.Language.displayName(for: "Base"))
}
}
|
mit
|
36182abffcbf2368ecacc42ddb1051ac
| 36.465753 | 91 | 0.665448 | 4.490969 | false | true | false | false |
hoanganh6491/BrightFutures
|
BrightFuturesTests/InvalidationTokenTests.swift
|
2
|
4178
|
//
// InvalidationTokenTests.swift
// BrightFutures
//
// Created by Thomas Visser on 19/01/15.
// Copyright (c) 2015 Thomas Visser. All rights reserved.
//
import XCTest
import BrightFutures
class InvalidationTokenTests: XCTestCase {
func testInvalidationTokenInit() {
let token = InvalidationToken()
XCTAssert(!token.isInvalid, "a token is valid by default")
}
func testInvalidateToken() {
let token = InvalidationToken()
token.invalidate()
XCTAssert(token.isInvalid, "a token should become invalid after invalidating")
}
func testInvalidationTokenFuture() {
let token = InvalidationToken()
XCTAssertNotNil(token.future, "token should have a future")
XCTAssert(!token.future.isCompleted, "token should have a future and not be complete")
token.invalidate()
XCTAssert(token.future.error != nil, "future should have an error")
if let error = token.future.error?.nsError {
XCTAssertEqual(error.domain, BrightFuturesErrorDomain)
XCTAssertEqual(error.code, InvalidationTokenInvalid)
}
}
func testCompletionAfterInvalidation() {
let token = InvalidationToken()
let p = Promise<Int, NSError>()
p.future.onSuccess(token: token) { val in
XCTAssert(false, "onSuccess should not get called")
}.onFailure(token: token) { error in
XCTAssert(false, "onSuccess should not get called")
}
let e = self.expectation()
Queue.global.async {
token.invalidate()
p.success(2)
NSThread.sleepForTimeInterval(0.2); // make sure onSuccess is not called
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testNonInvalidatedSucceededFutureOnSuccess() {
let token = InvalidationToken()
let e = self.expectation()
Future<Int, NoError>.succeeded(3).onSuccess(token: token) { val in
XCTAssertEqual(val, 3)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testNonInvalidatedSucceededFutureOnComplete() {
let token = InvalidationToken()
let e = self.expectation()
Future<Int, NoError>.succeeded(3).onComplete(token: token) { res in
XCTAssertEqual(res.value!, 3)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testNonInvalidatedFailedFutureOnFailure() {
let token = InvalidationToken()
let e = self.expectation()
Future<Int, TestError>.failed(TestError.JustAnError).onFailure(token: token) { err in
XCTAssertEqual(err, TestError.JustAnError)
e.fulfill()
}
self.waitForExpectationsWithTimeout(2, handler: nil)
}
func testStress() {
class Counter {
var i = 0
}
var token: InvalidationToken!
let counter = Counter()
for _ in 1...100 {
token = InvalidationToken()
let currentI = counter.i
let e = self.expectation()
future { () -> Bool in
let sleep: NSTimeInterval = NSTimeInterval(arc4random() % 100) / 100000.0
NSThread.sleepForTimeInterval(sleep)
return true
}.onSuccess(context: Queue.global.context, token: token) { _ in
XCTAssert(!token.isInvalid)
XCTAssertEqual(currentI, counter.i, "onSuccess should only get called if the counter did not increment")
}.onComplete(context: Queue.global.context) { _ in
NSThread.sleepForTimeInterval(0.0001);
e.fulfill()
}
NSThread.sleepForTimeInterval(0.0005)
token.context {
counter.i++
token.invalidate()
}
}
self.waitForExpectationsWithTimeout(5, handler: nil)
}
}
|
mit
|
a056b16066f6a1b0155e7ddb99ea8c99
| 31.387597 | 120 | 0.583293 | 5.170792 | false | true | false | false |
TarangKhanna/Inspirator
|
WorkoutMotivation/FriendController.swift
|
2
|
5826
|
//
// FriendController.swift
// WorkoutMotivation
//
// Created by Tarang khanna on 6/19/15.
// Copyright (c) 2015 Tarang khanna. All rights reserved.
//
import UIKit
let reuseIdentifier3 = "CellFriend"
class FriendController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UIPopoverPresentationControllerDelegate {
var name2 : String = "" // passed from parent
//var profileImageFile = PFFile()
var downloadedImage2 = UIImage()
var messages = [String]()
var createdAt = [Int]()
var duration : Int = 0
var currentMessage = String()
var imageFiles = [PFFile]()
override func viewWillAppear(animated: Bool) {
retrieve()
// var queryUser = PFUser.query() as PFQuery?
// queryUser!.findObjectsInBackgroundWithBlock {
// (users: [AnyObject]?, error: NSError?) -> Void in
// queryUser!.whereKey("username", equalTo: self.name2)
// if error == nil {
// // The find succeeded.
// // Do something with the found users
// if let users = users as? [PFObject] {
// for user in users {
// var user2:PFUser = user as! PFUser
// self.profileImageFile = user2["ProfilePicture"] as! PFFile
// self.profileImageFile.getDataInBackgroundWithBlock { (data, error) -> Void in
//
// if let downloadedImage = UIImage(data: data!) {
//
// self.downloadedImage2 = downloadedImage
// //self.avatarImage.image = downloadedImage
//
// }
//
// }
//
//
// }
// //self.tableView.reloadData()
// }
// } else {
// // Log details of the failure
// println("Error: \(error!) \(error!.userInfo!)")
// }
// }
}
func retrieve() {
self.imageFiles.removeAll(keepCapacity: false)
let queryUser = PFUser.query() as PFQuery?
queryUser!.findObjectsInBackgroundWithBlock {
(users: [AnyObject]?, error: NSError?) -> Void in
//queryUser!.orderByDescending("createdAt")
//queryUser!.whereKey("username", equalTo: self.userArray[indexPath.row])
if error == nil {
//println("Successfully retrieved \(users!.count) users.")
// Do something with the found users
if let users = users as? [PFObject] {
for user in users {
let user2:PFUser = user as! PFUser
self.imageFiles.append(user2["ProfilePicture"] as! PFFile)
//self.imageFiles.append(user2["ProfilePictue"] as! PFFile)
}
}
self.collectionView?.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
//println(name2)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//#warning Incomplete method implementation -- Return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return imageFiles.count
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// currentMessage = messages[indexPath.row]
// go to profile
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier3, forIndexPath: indexPath) as! CollectionViewCell2
// //cell.title.sizeToFit()
// cell.Image.clipsToBounds = true
// cell.Image.layer.masksToBounds = true
// cell.Image.layer.cornerRadius = cell.Image.layer.frame.size.width/2
// let image42 = self.imageFiles[indexPath.row]
// image42.getDataInBackgroundWithBlock { (data, error) -> Void in
// if let downloadedImage2 = UIImage(data: data!) {
// cell.Image.image = downloadedImage2
// }
// }
// //cell.title.text = messages[indexPath.row]
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
print(self.view.frame.size)
return CGSizeMake(100, (self.view.frame.size.height - 10))
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(5, 0, 5, 0)
}
func adaptivePresentationStyleForPresentationController(PC: UIPresentationController) -> UIModalPresentationStyle {
// This *forces* a popover to be displayed on the iPhone
return .None
}
}
|
apache-2.0
|
81c5e4c8c793534aa7783563af02aa30
| 38.910959 | 169 | 0.567971 | 5.517045 | false | false | false | false |
LQJJ/demo
|
125-iOSTips-master/Demo/9.使用面向协议实现app的主题功能/DCTheme/Theme/LightTheme.swift
|
1
|
962
|
//
// LightTheme.swift
// DCTheme
//
// Created by Dariel on 2018/10/9.
// Copyright © 2018年 Dariel. All rights reserved.
//
import UIKit
struct LightTheme: Theme {
let tint: UIColor = .white
let barStyle: UIBarStyle = .default
let labelColor: UIColor = UIColor.darkText
let labelSelectedColor: UIColor = UIColor.lightText
let backgroundColor: UIColor = .white
let separatorColor: UIColor = .lightGray
let selectedColor: UIColor = UIColor(236, 236, 236)
}
extension LightTheme {
// 需要自定义的部分写在这边
func extend() {
UISegmentedControl.appearance().with {
$0.tintColor = UIColor.darkText
$0.setTitleTextAttributes([.foregroundColor : labelColor], for: .normal)
$0.setTitleTextAttributes([.foregroundColor : UIColor.white], for: .selected)
}
UISlider.appearance().tintColor = UIColor.darkText
}
}
|
apache-2.0
|
ad8fa6e58e8fc8291444eb5fd6f3dbe8
| 23.605263 | 89 | 0.642781 | 4.516908 | false | false | false | false |
GraphKit/MaterialKit
|
Sources/iOS/BottomNavigationController.swift
|
2
|
6042
|
/*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public class BottomNavigationFadeAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromView : UIView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
let toView : UIView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
toView.alpha = 0
transitionContext.containerView.addSubview(fromView)
transitionContext.containerView.addSubview(toView)
UIView.animate(withDuration: transitionDuration(using: transitionContext),
animations: { _ in
toView.alpha = 1
fromView.alpha = 0
}) { _ in
transitionContext.completeTransition(true)
}
}
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.35
}
}
@objc(BottomNavigationTransitionAnimation)
public enum BottomNavigationTransitionAnimation: Int {
case none
case fade
}
open class BottomNavigationController: UITabBarController, UITabBarControllerDelegate {
/// The transition animation to use when selecting a new tab.
open var transitionAnimation = BottomNavigationTransitionAnimation.fade
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
An initializer that initializes the object with an Optional nib and bundle.
- Parameter nibNameOrNil: An Optional String for the nib.
- Parameter bundle: An Optional NSBundle where the nib is located.
*/
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/// An initializer that accepts no parameters.
public init() {
super.init(nibName: nil, bundle: nil)
}
/**
An initializer that initializes the object an Array of UIViewControllers.
- Parameter viewControllers: An Array of UIViewControllers.
*/
public init(viewControllers: [UIViewController]) {
super.init(nibName: nil, bundle: nil)
self.viewControllers = viewControllers
}
open override func viewDidLoad() {
super.viewDidLoad()
prepare()
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
layoutSubviews()
}
open func layoutSubviews() {
if let v = tabBar.items {
for item in v {
if .phone == Device.userInterfaceIdiom {
if nil == item.title {
let inset: CGFloat = 7
item.imageInsets = UIEdgeInsetsMake(inset, 0, -inset, 0)
} else {
let inset: CGFloat = 6
item.titlePositionAdjustment.vertical = -inset
}
} else {
if nil == item.title {
let inset: CGFloat = 9
item.imageInsets = UIEdgeInsetsMake(inset, 0, -inset, 0)
} else {
let inset: CGFloat = 3
item.imageInsets = UIEdgeInsetsMake(inset, 0, -inset, 0)
item.titlePositionAdjustment.vertical = -inset
}
}
}
}
tabBar.divider.reload()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open func prepare() {
view.clipsToBounds = true
view.contentScaleFactor = Screen.scale
view.backgroundColor = .white
delegate = self
prepareTabBar()
}
/// Handles transitions when tabBarItems are pressed.
open func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let fVC: UIViewController? = fromVC
let tVC: UIViewController? = toVC
if nil == fVC || nil == tVC {
return nil
}
return .fade == transitionAnimation ? BottomNavigationFadeAnimatedTransitioning() : nil
}
/// Prepares the tabBar.
private func prepareTabBar() {
tabBar.heightPreset = .normal
tabBar.depthPreset = .depth1
tabBar.dividerAlignment = .top
let image = UIImage.image(with: Color.clear, size: CGSize(width: 1, height: 1))
tabBar.shadowImage = image
tabBar.backgroundImage = image
tabBar.backgroundColor = .white
}
}
|
agpl-3.0
|
fa74d0e3f224e8b44e026e579a883e17
| 34.751479 | 201 | 0.732042 | 4.56 | false | false | false | false |
NoryCao/zhuishushenqi
|
zhuishushenqi/Extension/String+QSExtension.swift
|
1
|
10196
|
//
// String+crypto.swift
// zhuishushenqi
//
// Created by Nory Cao on 2017/3/6.
// Copyright © 2017年 QS. All rights reserved.
//
import Foundation
import CommonCrypto
extension String {
//MARK: - crypto
func md5() ->String{
let str = self.cString(using: String.Encoding.utf8)
let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_MD5(str!, strLen, result)
let hash = NSMutableString()
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i])
}
result.deinitialize(count: digestLen)
return String(format: hash as String)
}
//由于移动设备的内存有限,以下代码实现是将文件分块读出并且计算md5值的方法
func fileMD5()->String? {
let handler = FileHandle(forReadingAtPath: self)
if handler == nil {
return nil
}
let ctx = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: MemoryLayout<CC_MD5_CTX>.size)
CC_MD5_Init(ctx)
var done = false
while !done {
let fileData = handler?.readData(ofLength: 256)
fileData?.withUnsafeBytes({ (bytes) -> Void in
CC_MD5_Update(ctx, bytes, CC_LONG(fileData!.count))
})
if fileData?.count == 0 {
done = true
}
}
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let digest = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_MD5_Final(digest, ctx)
var hash = ""
for i in 0..<digestLen {
hash += String(format:"%02x",(digest[i]))
}
// digest.deinitialize()
// ctx.deinitialize()
return hash
}
//MARK: - Sub string Half open
func qs_subStr(start:Int,end:Int)->String{
if self == "" {
return self
}
var ends = end
if self.count < ends {
ends = self.count
}
let startIndex = self.index(self.startIndex, offsetBy: start)
let endIndex = self.index(self.startIndex, offsetBy: ends)
let range = startIndex..<endIndex
let sub = self[range]
return String(sub)
}
func qs_subStr(start:Int,length:Int)->String{
if self == "" {
return self
}
let startIndex = self.index(self.startIndex, offsetBy: start)
let endIndex = self.index(self.startIndex, offsetBy: start + length)
let range = startIndex..<endIndex
let sub = self[range]
return String(sub)
}
func qs_subStr(from:Int)->String{
if self == "" {
return self
}
let startIndex = self.index(self.startIndex, offsetBy: from)
let endIndex = self.endIndex
let range = startIndex..<endIndex
let sub = self[range]
return String(sub)
}
func qs_subStr(to:Int)->String{
if self == "" {
return self
}
let startIndex = self.startIndex
let endIndex = self.index(self.startIndex, offsetBy: to)
let range = startIndex..<endIndex
let sub = self[range]
return String(sub)
}
func qs_subStr(range:CountableRange<Int>)->String{
if self == "" {
return self
}
let startIndex = range.startIndex
let endIndex = range.endIndex
let sub = self.qs_subStr(start: startIndex, end: endIndex)
return sub
}
func qs_subStr(range:NSRange)->String{
if self == "" {
return self
}
let start = range.location
let end = range.location + range.length
return self.qs_subStr(start: start, end: end)
}
//MARK:- count
func qs_width(_ font:UIFont,height:CGFloat) ->CGFloat
{
let dict = [NSAttributedString.Key.font:font]
let sttt:NSString = self as NSString
let rect:CGRect = sttt.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: CGFloat(height)), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: dict, context: nil)
return rect.size.width
}
func qs_height(_ font:UIFont,width:CGFloat) ->CGFloat
{
let dict = [NSAttributedString.Key.font:font]
let sttt:NSString = self as NSString
let rect:CGRect = sttt.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: dict, context: nil)
return rect.size.height
}
func qs_width(_ fontSize:CGFloat,height:CGFloat) -> CGFloat{
let dict = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: fontSize)]
let sttt:NSString = self as NSString
let rect:CGRect = sttt.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: CGFloat(height)), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: dict, context: nil)
return rect.size.width
}
func qs_height(_ fontSize:CGFloat,width:CGFloat) ->CGFloat
{
let dict = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: fontSize)]
let sttt:NSString = self as NSString
let rect:CGRect = sttt.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: dict, context: nil)
return rect.size.height
}
//获取子字符串
func substingInRange(_ r: Range<Int>) -> String? {
if r.lowerBound < 0 || r.upperBound > self.count {
return nil
}
let startIndex = self.index(self.startIndex, offsetBy:r.lowerBound)
let endIndex = self.index(self.startIndex, offsetBy:r.upperBound)
return String(self[startIndex..<endIndex])
}
//MARK: - equal
func isEqual(to string:String) ->Bool {
if self == string {
return true
}
return false
}
//MARK: - string
func asNSString() ->NSString {
return (self as NSString)
}
var ocString:NSString {
return (self as NSString)
}
var nsString:NSString {
return (self as NSString)
}
func isEmpty() ->Bool {
if self == "" || self.count == 0 {
return true
}
return false
}
func schemeURLString(_ host:String = "") ->String {
var urlString:String = self
if !urlString.hasPrefix("http") {
if urlString.hasPrefix("/") && host.hasSuffix("/") {
let host = host.qs_subStr(start: 0, length: host.length - 1)
urlString = "\(host)\(urlString)"
} else {
urlString = "\(host)\(urlString)"
}
}
return urlString
}
func httpScheme()->String {
var icon = self
if icon.hasPrefix("//") {
icon = icon.replacingOccurrences(of: "//", with: "http://")
}
return icon
}
func httpsScheme()->String {
var icon = self
if icon.hasPrefix("//") {
icon = icon.replacingOccurrences(of: "//", with: "https://")
}
return icon
}
//MARK: - transform
var length:Int {
return self.lengthOfBytes(using: .utf8)
}
var oc_length:Int {
return self.asNSString().length
}
var toArray:Array<[String:Any]>? {
var json = self
if json.contains("\\") {
json = json.components(separatedBy: "\\").joined()
}
if let data = json.data(using: .utf8) {
do {
let arr = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.init(rawValue: 0)) as? Array<[String:Any]>
return arr
} catch let error {
QSLog(error)
}
}
return nil
}
var toDict:Dictionary<String,Any>? {
var json = self
if json.contains("\\") {
json = json.components(separatedBy: "\\").joined()
}
if let data = json.data(using: .utf8) {
do {
let dict = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.init(rawValue: 0)) as? Dictionary<String,Any>
guard let _ = dict?.first else {
return nil
}
return dict
} catch let error {
QSLog(error)
}
}
return nil
}
static func stringFromDataDetectingEncoding(data: Data, suggestedEncodings: [String.Encoding] = []) -> (string: String, encoding: String.Encoding, lossy: Bool)? {
var outString: NSString? = nil
var lossyConversion: ObjCBool = false
var suggestedEncodingsValues:[NSNumber] = []
suggestedEncodingsValues = suggestedEncodings.map { (encode) -> NSNumber in
return NSNumber.init(value: encode.rawValue)
}
let encoding = NSString.stringEncoding(for: data as Data, encodingOptions: [StringEncodingDetectionOptionsKey.suggestedEncodingsKey:suggestedEncodingsValues], convertedString: &outString, usedLossyConversion: &lossyConversion)
guard let foundString = outString else { return nil }
return (string: foundString as String, encoding: String.Encoding.init(rawValue: encoding), lossy: lossyConversion.boolValue)
}
}
extension Optional {
}
extension String.Encoding {
static var gbk:String.Encoding {
let encode = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue))
return String.Encoding(rawValue: encode)
}
static func zs_encoding(str:String)->String.Encoding {
switch str {
case ".utf8":
return .utf8
case ".gbk":
return gbk
default:
return .utf8
}
}
}
|
mit
|
686afc7476ae449dea9ca843fc96adaf
| 31.734628 | 234 | 0.57736 | 4.483599 | false | false | false | false |
calosth/bussper
|
Buspper/ListRoutesView.swift
|
1
|
3789
|
//
// ListRoutesViewViewController.swift
// Buspper
//
// Created by Carlos Linares on 2/10/16.
// Copyright © 2016 Carlos Linares. All rights reserved.
//
import UIKit
class ListRoutesView: UIView, UITableViewDataSource, UITableViewDelegate {
private let headerHeight: CGFloat = 40.0
private let margin: CGFloat = 16
var stopName: String?
var routesNames = [["24 de Diciembre", "Plaza Mirage"], ["Av. España", "Plaza Mirage"]]
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = UIColor.clearColor()
// Add UILabel
let containerHeader = UIView(frame: CGRectMake(0, 0, self.frame.width, headerHeight))
let stopNameLabel = UILabel()
stopNameLabel.font = UIFont(name: "HelveticaNeue-Light", size: 22)
stopNameLabel.text = "Plaza Edison"
stopNameLabel.sizeToFit()
stopNameLabel.center.y = containerHeader.bounds.height / 2 // Maybe a constrain is better
stopNameLabel.frame.origin.x = 16 // Maybe a constrain is better
stopNameLabel.textColor = UIColor.whiteColor()
// Blur
let blurEffect = UIBlurEffect(style: .ExtraLight)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.backgroundColor = UIColor.clearColor()
// blurView.backgroundColor = UIColor.blueBuspper()
// containerHeader.addSubview(blurView)
containerHeader.backgroundColor = UIColor.blueBuspper()
containerHeader.alpha = 0.75
containerHeader.addSubview(stopNameLabel)
addSubview(containerHeader)
// Background table view
let busLogo = UIImageView(image: UIImage(named: "bus"))
busLogo.contentMode = UIViewContentMode.Center
busLogo.center.y = UIScreen.mainScreen().bounds.width / 2
busLogo.center.x = UIScreen.mainScreen().bounds.height - 100
// Add UITableView
let tableView = UITableView(frame: CGRectMake(0, headerHeight, self.frame.width, self.frame.height - headerHeight))
blurView.frame = tableView.frame
tableView.delegate = self
tableView.dataSource = self
tableView.alpha = 0.85
tableView.addSubview(busLogo)
addSubview(tableView)
self.frame.origin.y -= UIScreen.mainScreen().bounds.height
}
// MARK: About UITableViewDelegate and UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return routesNames.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "")
cell.textLabel!.text = routesNames[indexPath.row][0]
cell.textLabel!.font = UIFont(name: "HelveticaNeue-Regular", size: 14)
cell.textLabel!.frame.origin.x = self.margin
cell.textLabel!.frame.origin.y = 10
cell.detailTextLabel?.text = "Próxima parada: \(routesNames[indexPath.row][1])"
cell.detailTextLabel?.font = UIFont(name: "HelveticaNeue-Light", size: 14)
cell.detailTextLabel?.textColor = UIColor.hexToUIColor("#575757")
return cell
}
// MARK: UI things
func show() {
UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseOut, animations: {
self.frame.origin.y += UIScreen.mainScreen().bounds.height
}, completion: nil)
}
func hide() {
UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseIn, animations: {
self.frame.origin.y -= UIScreen.mainScreen().bounds.height
}, completion: nil)
}
}
|
apache-2.0
|
2542e06d1236528eff7497a946571fb1
| 36.117647 | 123 | 0.651083 | 4.651106 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.