repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bitboylabs/selluv-ios | refs/heads/master | selluv-ios/selluv-ios/Classes/Base/Vender/RoundedSwitch/Switch.swift | mit | 1 | //
// Switch.swift
//
// Created by Thanh Pham on 8/24/16.
//
import UIKit
/// A switch control
@IBDesignable open class Switch: UIControl {
let backgroundLayer = RoundLayer()
let switchLayer = RoundLayer()
let selectedColor: UIColor = text_color_bl51
let deselectedColor: UIColor = text_color_g153
var previousPoint: CGPoint?
var switchLayerLeftPosition: CGPoint?
var switchLayerRightPosition: CGPoint?
static let labelFactory: () -> UILabel = {
let label = UILabel()
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 12, weight: UIFontWeightRegular)
return label
}
/// The label on the left. Don't set the `textColor` and `text` properties on this label. Set them on the `leftText`, `tintColor` and `disabledColor` properties of the switch instead.
open let leftLabel = labelFactory()
/// The label on the right. Don't set the `textColor` and `text` properties on this label. Set them on the `rightText`, `tintColor` and `disabledColor` properties of the switch instead.
open let rightLabel = labelFactory()
/// Text for the label on the left. Setting this property instead of the `text` property of the `leftLabel` to trigger Auto Layout automatically.
@IBInspectable open var leftText: String? {
get {
return leftLabel.text
}
set {
leftLabel.text = newValue
invalidateIntrinsicContentSize()
}
}
/// Text for the label on the right. Setting this property instead of the `text` property of the `rightLabel` to trigger Auto Layout automatically.
@IBInspectable open var rightText: String? {
get {
return rightLabel.text
}
set {
rightLabel.text = newValue
invalidateIntrinsicContentSize()
}
}
/// True when the right value is selected, false when the left value is selected. When this property is changed, the UIControlEvents.ValueChanged is fired.
@IBInspectable open var rightSelected: Bool = false {
didSet {
reloadSwitchLayerPosition()
reloadLabelsTextColor()
sendActions(for: .valueChanged)
}
}
/// The color used for the unselected text and the background border.
@IBInspectable open var disabledColor: UIColor = UIColor.lightGray {
didSet {
backgroundLayer.borderColor = disabledColor.cgColor
switchLayer.borderColor = disabledColor.cgColor
reloadLabelsTextColor()
}
}
/// The color used for the selected text and the switch border.
override open var tintColor: UIColor! {
didSet {
reloadLabelsTextColor()
}
}
var touchBegan = false
var touchBeganInSwitchLayer = false
var touchMoved = false
/// Init with coder.
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
backgroundLayer.backgroundColor = UIColor.init(colorLiteralRed: 245/255, green: 245/255, blue: 250/255, alpha: 1).cgColor
backgroundLayer.borderColor = disabledColor.cgColor
backgroundLayer.borderWidth = 1
layer.addSublayer(backgroundLayer)
switchLayer.backgroundColor = UIColor.white.cgColor
switchLayer.borderColor = disabledColor.cgColor
switchLayer.borderWidth = 1
layer.addSublayer(switchLayer)
addSubview(leftLabel)
addSubview(rightLabel)
reloadLabelsTextColor()
}
/// Layouts subviews. Should not be called directly.
override open func layoutSubviews() {
super.layoutSubviews()
leftLabel.frame = CGRect(x: 0, y: 0, width: bounds.size.width / 2, height: bounds.size.height)
rightLabel.frame = CGRect(x: bounds.size.width / 2, y: 0, width: bounds.size.width / 2, height: bounds.size.height)
}
/// Layouts sublayers of a layer. Should not be called directly.
override open func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
guard layer == self.layer else {
return
}
backgroundLayer.frame = layer.bounds
switchLayer.bounds = CGRect(x: 0, y: 0, width: layer.bounds.size.width / 2, height: layer.bounds.size.height)
switchLayerLeftPosition = layer.convert(layer.position, from: layer.superlayer).applying(CGAffineTransform(translationX: -switchLayer.bounds.size.width / 2, y: 0))
switchLayerRightPosition = switchLayerLeftPosition!.applying(CGAffineTransform(translationX: switchLayer.bounds.size.width, y: 0))
touchBegan = false
touchBeganInSwitchLayer = false
touchMoved = false
previousPoint = nil
reloadSwitchLayerPosition()
}
/// Touches began event handler. Should not be called directly.
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
touchBegan = true
previousPoint = touches.first!.location(in: self)
touchBeganInSwitchLayer = switchLayer.contains(switchLayer.convert(previousPoint!, from: layer))
}
/// Touches moved event handler. Should not be called directly.
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
touchMoved = true
guard touchBeganInSwitchLayer else {
return
}
let point = touches.first!.location(in: self)
var position = switchLayer.position.applying(CGAffineTransform(translationX: point.x - previousPoint!.x, y: 0))
position.x = max(switchLayer.bounds.size.width / 2, min(layer.bounds.size.width - switchLayer.bounds.size.width / 2, position.x))
switchLayer.position = position
previousPoint = point
}
/// Touches ended event handler. Should not be called directly.
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
guard touchBegan else {
return
}
previousPoint = nil
if touchMoved && touchBeganInSwitchLayer {
rightSelected = abs(switchLayerLeftPosition!.x - switchLayer.position.x) > abs(switchLayerRightPosition!.x - switchLayer.position.x)
} else if !touchMoved && !touchBeganInSwitchLayer {
rightSelected = !rightSelected
}
touchBegan = false
touchBeganInSwitchLayer = false
touchMoved = false
}
/// Touches cancelled event handler. Should not be called directly.
override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
previousPoint = nil
reloadSwitchLayerPosition()
touchBegan = false
touchBeganInSwitchLayer = false
touchMoved = false
}
/// Returns the minimum size that fits a given size.
override open func sizeThatFits(_ size: CGSize) -> CGSize {
let labelSize = CGSize(width: (size.width - 3 * size.height / 2) / 2, height: size.height)
return desiredSizeForLeftSize(leftLabel.sizeThatFits(labelSize), rightSize: rightLabel.sizeThatFits(labelSize))
}
/// The minimum size used for Auto Layout.
override open var intrinsicContentSize : CGSize {
return desiredSizeForLeftSize(leftLabel.intrinsicContentSize, rightSize: rightLabel.intrinsicContentSize)
}
func desiredSizeForLeftSize(_ leftSize: CGSize, rightSize: CGSize) -> CGSize {
let height = max(leftSize.height, rightSize.height)
return CGSize(width: max(leftSize.width, rightSize.width) * 2 + 3 * height / 2, height: height)
}
func reloadLabelsTextColor() {
leftLabel.textColor = rightSelected ? deselectedColor : selectedColor
rightLabel.textColor = rightSelected ? selectedColor : deselectedColor
}
func reloadSwitchLayerPosition() {
guard let switchLayerLeftPosition = switchLayerLeftPosition, let switchLayerRightPosition = switchLayerRightPosition else {
return
}
switchLayer.position = rightSelected ? switchLayerRightPosition : switchLayerLeftPosition
}
}
class RoundLayer: CALayer {
override func layoutSublayers() {
super.layoutSublayers()
cornerRadius = bounds.size.height / 2
}
}
| c621ab93a5d953ce9dbb236e85a502ee | 37.778281 | 189 | 0.669545 | false | false | false | false |
rafaelcpalmeida/UFP-iOS | refs/heads/master | UFP/UFP/PageViewController.swift | mit | 1 | //
// PageViewController.swift
// UFP
//
// Created by Rafael Almeida on 29/03/17.
// Copyright © 2016 Vladimir Romanov. All rights reserved.
// https://github.com/VRomanov89/EEEnthusiast---iOS-Dev
//
import Foundation
import UIKit
class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
let pageControl = UIPageControl.appearance()
public lazy var VCArr: [UIViewController] = {
return [self.VCInstance(name: "schedule"),
self.VCInstance(name: "queue"),
self.VCInstance(name: "finalGrades"),
self.VCInstance(name: "partialGrades"),
self.VCInstance(name: "atm"),
self.VCInstance(name: "assiduity"),
self.VCInstance(name: "teachers")]
}()
private func VCInstance(name: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: name)
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
if let firstVC = VCArr.first {
setViewControllers([firstVC], direction: .forward, animated: true, completion: nil)
}
self.pageControl.pageIndicatorTintColor = UIColor(red:0.40, green:0.40, blue:0.40, alpha:1.0)
self.pageControl.currentPageIndicatorTintColor = UIColor(red:0.34, green:0.62, blue:0.17, alpha:1.0)
self.pageControl.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 150)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
for view in self.view.subviews {
if view is UIScrollView {
view.frame = UIScreen.main.bounds
} else if view is UIPageControl {
view.backgroundColor = UIColor.clear
}
}
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = VCArr.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return VCArr.last
}
guard VCArr.count > previousIndex else {
return nil
}
return VCArr[previousIndex]
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = VCArr.index(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
guard nextIndex < VCArr.count else {
return VCArr.first
}
guard VCArr.count > nextIndex else {
return nil
}
return VCArr[nextIndex]
}
public func presentationCount(for pageViewController: UIPageViewController) -> Int {
return VCArr.count
}
public func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let firstViewController = viewControllers?.first,
let firstViewControllerIndex = VCArr.index(of: firstViewController) else {
return 0
}
return firstViewControllerIndex
}
public func getToHome() {
if let firstVC = VCArr.first {
setViewControllers([firstVC], direction: .forward, animated: true, completion: nil)
}
}
}
| 5b8ef491824eb44ad891da4d21963b2e | 31.877193 | 156 | 0.611259 | false | false | false | false |
gang544043963/swift-LGSelectButtonView | refs/heads/master | SwiftStudy/LGSelectButtonView.swift | mit | 1 | //
// LGSelectButtonView.swift
// SwiftStudy
//
// Created by ligang on 15/11/8.
// Copyright © 2015年 L&G. All rights reserved.
//
import UIKit
protocol LGSelectButtonViewDelegate {
func didSelectRowAtIndexPath(indexPath:NSIndexPath)
}
class LGSelectButtonView: UIView, UITableViewDataSource, UITableViewDelegate {
var btnHeight:CGFloat = 30.0
var button:UIButton?
var tableView:UITableView?
var origFrame:CGRect?
var delegate:LGSelectButtonViewDelegate?
var imageName:NSString {
get{
return self.button!.selected ? "class_up_arrow_iPhone.png" : "class_down_arrow_iPhone.png"
}
}
var tableViewTextLableArray: NSMutableArray? {
didSet {
setupButton()
setupTableView()
}
}
func setupButton() {
let button = UIButton.init(frame: CGRectMake(0, 0 , frame.size.width, btnHeight));
button.setBackgroundImage(UIImage(named: "preference_button_iphone.png"), forState: UIControlState.Normal)
button.addTarget(self, action: "btnTouchd:", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(button)
self.button = button
button.setImage(UIImage(named: imageName as String), forState: UIControlState.Normal)
}
func setupTableView() {
let tableView = UITableView.init(frame: CGRectMake(0, btnHeight, frame.size.width, frame.size.height - btnHeight))
tableView.delegate = self
tableView.dataSource = self
tableView.layer.cornerRadius = 4
tableView.backgroundColor = UIColor.clearColor()
self.addSubview(tableView)
self.tableView = tableView
}
override init(frame: CGRect) {
super.init(frame: frame)
self.origFrame = frame
self.backgroundColor = UIColor(white: 255, alpha: 0.8)
self.layer.cornerRadius = 4
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func btnTouchd(sender:UIButton) {
self.button!.setImage(UIImage(named: imageName as String), forState: UIControlState.Normal)
(self.button!.selected == true) ? (self.button!.selected = false) : (self.button!.selected = true)
if self.button!.selected == true {
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.btnHeight)
self.tableView!.frame = CGRectMake(0, self.btnHeight, self.frame.size.width, 0)
})
} else {
[UIView .animateWithDuration(0.5, animations: { () -> Void in
self.frame = self.origFrame!
self.tableView!.frame = CGRectMake(0, self.btnHeight, self.frame.size.width, self.frame.size.height - self.btnHeight)
})]
}
}
//UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (tableViewTextLableArray?.count)!
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell.init(style: UITableViewCellStyle.Default , reuseIdentifier:nil)
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.text = tableViewTextLableArray?[indexPath.row] as? String
return cell
}
//UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.cellForRowAtIndexPath(indexPath)?.selected = false
let labelStr = self.tableViewTextLableArray?[indexPath.row] as? String
button!.setTitle(labelStr, forState: UIControlState.Normal)
delegate?.didSelectRowAtIndexPath(indexPath)
btnTouchd(self.button!)
}
}
| ecc2c3abb693cd5b6286d3ca2ac427af | 37.257143 | 133 | 0.658701 | false | false | false | false |
mountainvat/google-maps-ios-utils | refs/heads/master | samples/SwiftDemoApp/SwiftDemoApp/HeatmapViewController.swift | apache-2.0 | 1 | /* Copyright (c) 2017 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
import GoogleMaps
import UIKit
class HeatmapViewController: UIViewController, GMSMapViewDelegate {
private var mapView: GMSMapView!
private var heatmapLayer: GMUHeatmapTileLayer!
private var button: UIButton!
private var gradientColors = [UIColor.green, UIColor.red]
private var gradientStartPoints = [0.2, 1.0] as? [NSNumber]
override func loadView() {
let camera = GMSCameraPosition.camera(withLatitude: -37.848, longitude: 145.001, zoom: 10)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.delegate = self
self.view = mapView
makeButton()
}
override func viewDidLoad() {
// Set heatmap options.
heatmapLayer = GMUHeatmapTileLayer()
heatmapLayer.radius = 80
heatmapLayer.opacity = 0.8
heatmapLayer.gradient = GMUGradient(colors: gradientColors,
startPoints: gradientStartPoints!,
colorMapSize: 256)
addHeatmap()
// Set the heatmap to the mapview.
heatmapLayer.map = mapView
}
// Parse JSON data and add it to the heatmap layer.
func addHeatmap() {
var list = [GMUWeightedLatLng]()
do {
// Get the data: latitude/longitude positions of police stations.
if let path = Bundle.main.url(forResource: "police_stations", withExtension: "json") {
let data = try Data(contentsOf: path)
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let object = json as? [[String: Any]] {
for item in object {
let lat = item["lat"]
let lng = item["lng"]
let coords = GMUWeightedLatLng(coordinate: CLLocationCoordinate2DMake(lat as! CLLocationDegrees, lng as! CLLocationDegrees), intensity: 1.0)
list.append(coords)
}
} else {
print("Could not read the JSON.")
}
}
} catch {
print(error.localizedDescription)
}
// Add the latlngs to the heatmap layer.
heatmapLayer.weightedData = list
}
func removeHeatmap() {
heatmapLayer.map = nil
heatmapLayer = nil
// Disable the button to prevent subsequent calls, since heatmapLayer is now nil.
button.isEnabled = false
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
}
// Add a button to the view.
func makeButton() {
// A button to test removing the heatmap.
button = UIButton(frame: CGRect(x: 5, y: 150, width: 200, height: 35))
button.backgroundColor = .blue
button.alpha = 0.5
button.setTitle("Remove heatmap", for: .normal)
button.addTarget(self, action: #selector(removeHeatmap), for: .touchUpInside)
self.mapView.addSubview(button)
}
}
| 789d5187e28a7e86999680799cb6198c | 34.319588 | 152 | 0.670753 | false | false | false | false |
apple/swift-lldb | refs/heads/stable | packages/Python/lldbsuite/test/lang/swift/swiftieformatting/main.swift | apache-2.0 | 1 | // main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
import Foundation
class SwiftClass {
var ns_a: NSString
var sw_a: String
var ns_d: NSData
var sw_i: Int
var ns_n: NSNumber
var ns_u: NSURL
init() {
ns_a = "Hello Swift" as NSString
sw_a = "Hello Swift"
ns_d = NSData()
sw_i = 30
ns_n = 30 as NSNumber
ns_u = NSURL(string: "http://www.apple.com")!
}
}
func main() {
var swcla = SwiftClass()
var nsarr: NSArray = [2 as NSNumber,3 as NSNumber,"Hello",5 as NSNumber,["One","Two","Three"],[1 as NSNumber,2 as NSNumber,3 as NSNumber] as NSArray]
print("hello world") // Set breakpoint here
}
main()
| 22d34006e16bc215f209b866f97b5348 | 25.25641 | 151 | 0.628906 | false | false | false | false |
cxpyear/ZSZQApp | refs/heads/master | spdbapp/spdbapp/AppDelegate.swift | bsd-3-clause | 1 | //
// AppDelegate.swift
// spdbapp
//
// Created by tommy on 15/5/7.
// Copyright (c) 2015年 shgbit. All rights reserved.
//
import UIKit
var server = Server()
var current = GBCurrent()
var totalMembers = NSArray()
var member = GBMember()
var bNeedLogin = true
var appManager = AppManager()
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var backgroundTransferCompletionHandler:(() -> Void)?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIApplication.sharedApplication().idleTimerDisabled = true
return true
}
func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) {
self.backgroundTransferCompletionHandler = completionHandler
}
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.
// NSNotificationCenter.defaultCenter().addObserver(self, selector: "defaultsSettingsChanged", name: NSUserDefaultsDidChangeNotification, object: nil)
}
func applicationWillEnterForeground(application: UIApplication) {
// var defaults = NSUserDefaults.standardUserDefaults()
// defaults.synchronize()
// 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:.
UIApplication.sharedApplication().idleTimerDisabled = false
}
}
| 910a9d901c3c05291306d5b07a324888 | 39.777778 | 285 | 0.739101 | false | false | false | false |
segmentio/analytics-swift | refs/heads/main | Examples/apps/SegmentExtensionsExample/SegmentExtensionsExample/ResultViewController.swift | mit | 1 | //
// ResultViewController.swift
// SegmentExtensionsExample
//
// Created by Alan Charles on 8/10/21.
//
import UIKit
import AuthenticationServices
class ResultViewController: UIViewController {
var analytics = UIApplication.shared.delegate?.analytics
@IBOutlet weak var userIdentifierLabel: UILabel!
@IBOutlet weak var givenNameLabel: UILabel!
@IBOutlet weak var familyNameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var signOutButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
userIdentifierLabel.text = KeychainItem.currentUserIdentifier
}
@IBAction func signOutButtonPressed(_ sender: UIButton!) {
KeychainItem.deleteUserIdentifierFromKeychain()
userIdentifierLabel.text = ""
givenNameLabel.text = ""
familyNameLabel.text = ""
emailLabel.text = ""
DispatchQueue.main.async {
self.showLoginViewController()
}
analytics?.track(name: "Logged Out")
}
}
| c696aa41c3a57d1aa90f509ad5213876 | 25.975 | 69 | 0.668211 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/SourceKit/CodeComplete/complete_filter_rules.swift | apache-2.0 | 27 | // The top of this file is very sensitive to modification as we're using raw
// offsets for code-completion locations.
import Foo
struct TestHideName {
func hideThis1() {}
func hideThis2(_ x: Int, namedParam2: Int) {}
func hideThis3(namedParam1: Int, _ unnamedParam: Int) {}
func hideThis4(namedParam1 x: Int, namedParam2: Int) {}
func dontHideThisByName() {}
// REQUIRES: objc_interop
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideNames.json -tok=HIDE_NAMES_1 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_NAMES
func testHideName01() {
#^HIDE_NAMES_1,hidethis^#
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideNames.json -tok=HIDE_NAMES_2 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_NAMES
func testHideName02() {
self.#^HIDE_NAMES_2,hidethis^#
}
// HIDE_NAMES-LABEL: Results for filterText: hidethis [
// HIDE_NAMES-NEXT: dontHideThisByName()
// HIDE_NAMES-NEXT: ]
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideKeywords.json -tok=HIDE_KEYWORDS_1 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_LET
func testHideKeyword01() {
#^HIDE_KEYWORDS_1^#
// HIDE_LET-NOT: let
// HIDE_LET: var
// HIDE_LET-NOT: let
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showKeywords.json -tok=HIDE_KEYWORDS_2 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=SHOW_FUNC
func testHideKeyword02() {
#^HIDE_KEYWORDS_2^#
// SHOW_FUNC-NOT: let
// SHOW_FUNC-NOT: var
// SHOW_FUNC: func
// SHOW_FUNC-NOT: var
// SHOW_FUNC-NOT: let
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideLiterals.json -tok=HIDE_LITERALS_1 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_NIL
func testHideLiteral01() {
let x = #^HIDE_LITERALS_1^#
// HIDE_NIL-NOT: nil
// HIDE_NIL: 0
// HIDE_NIL-NOT: nil
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showLiterals.json -tok=HIDE_LITERALS_2 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=SHOW_STRING
func testHideLiteral02() {
let x = #^HIDE_LITERALS_2^#
// SHOW_STRING-NOT: [
// SHOW_STRING-NOT: nil
// SHOW_STRING: "abc"
// SHOW_STRING-NOT: nil
// SHOW_STRING-NOT: [
}
// FIXME: custom completions
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideModules.json -tok=HIDE_MODULES_1 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_FOO
func testHideModule01() {
let x: #^HIDE_MODULES_1^#
// FIXME: submodules
// HIDE_FOO-NOT: FooStruct1
// HIDE_FOO-NOT: FooClassBase
// HIDE_FOO: FooStruct2
// HIDE_FOO: FooHelperSubEnum1
// HIDE_FOO-NOT: FooStruct1
// HIDE_FOO-NOT: FooClassBase
}
func myFunFunction1() {}
func myFunFunction2() {}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showSpecific.json -tok=SHOW_SPECIFIC_1 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=SHOW_SPECIFIC_1
func testShowSpecific01() {
#^SHOW_SPECIFIC_1,fun^#
// SHOW_SPECIFIC_1-LABEL: Results for filterText: fun [
// SHOW_SPECIFIC_1-NEXT: func
// SHOW_SPECIFIC_1-NEXT: myFunFunction1()
// SHOW_SPECIFIC_1-NEXT: ]
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showSpecific.json -tok=HIDE_OP_1 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_OP
func testHideOp1() {
var local = 1
#^HIDE_OP_1,local^#
}
// HIDE_OP-NOT: .
// HIDE_OP-NOT: =
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showSpecific.json -tok=HIDE_OP_2 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_OP -allow-empty
func testHideOp2() {
var local = 1
local#^HIDE_OP_2^#
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showOp.json -tok=SHOW_OP_1 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=SHOW_OP_1
func testShowOp1() {
var local = 1
#^SHOW_OP_1,local^#
}
// SHOW_OP_1: local.{{$}}
// SHOW_OP_1: local={{$}}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showOp.json -tok=SHOW_OP_2 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=SHOW_OP_2
func testShowOp2() {
var local = 1
local#^SHOW_OP_2^#
}
// SHOW_OP_2: {{^}}.{{$}}
// SHOW_OP_2: {{^}}={{$}}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showOp.json -tok=HIDE_OP_3 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_OP
func testHideOp3() {
let local = TestHideName()
// Implicitly hidden because we hide all the members.
#^HIDE_OP_3,local^#
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showOp.json -tok=HIDE_OP_4 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_OP -allow-empty
func testHideOp4() {
let local = TestHideName()
// Implicitly hidden because we hide all the members.
local#^HIDE_OP_4^#
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showOp.json -tok=SHOW_OP_3 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=SHOW_OP_1
func testShowOp3() {
var local = 1
#^SHOW_OP_3,local^#
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showOp.json -tok=SHOW_OP_4 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=SHOW_OP_2
func testShowOp4() {
var local = 1
local#^SHOW_OP_4^#
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideInnerOp.json -tok=HIDE_OP_5 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_OP_5 -allow-empty
func testHideOp5() {
var local = 1
#^HIDE_OP_5,local^#
}
// HIDE_OP_5-NOT: local.{{$}}
// HIDE_OP_5-NOT: local?.
// HIDE_OP_5-NOT: local(
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideInnerOp.json -tok=HIDE_OP_6 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_OP_5 -allow-empty
func testHideOp6() {
var local: Int? = 1
#^HIDE_OP_6,local^#
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideInnerOp.json -tok=HIDE_OP_7 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_OP_5 -allow-empty
func testHideOp7() {
struct local {}
#^HIDE_OP_7,local^#
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideInnerOp.json -tok=HIDE_OP_8 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_OP_8 -allow-empty
func testHideOp8() {
var local = 1
local#^HIDE_OP_8^#
}
// HIDE_OP_8-NOT: {{^}}.{{$}}
// HIDE_OP_8-NOT: {{^}}?.
// HIDE_OP_8-NOT: {{^}}(
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideInnerOp.json -tok=HIDE_OP_9 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_OP_8 -allow-empty
func testHideOp9() {
var local: Int? = 1
local#^HIDE_OP_9^#
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideInnerOp.json -tok=HIDE_OP_10 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_OP_8 -allow-empty
func testHideOp10() {
struct local {}
local#^HIDE_OP_10^#
}
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideDesc.json -tok=HIDE_DESC_1 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_DESC_1
func testHideDesc1() {
struct Local {
func over(_: Int) {}
func over(_: Float) {}
}
Local().#^HIDE_DESC_1^#
}
// HIDE_DESC_1-NOT: over
// HIDE_DESC_1: over(Float)
// HIDE_DESC_1-NOT: over
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideDesc.json -tok=HIDE_DESC_2 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_DESC_2
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/hideDesc.json -tok=HIDE_DESC_3 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=HIDE_DESC_2
func testHideDesc2() {
struct Local {
subscript(_: Int) -> Int { return 0 }
subscript(_: Float) -> Float { return 0.0 }
}
Local()#^HIDE_DESC_2^#
let local = Local()
#^HIDE_DESC_3,local^#
}
// HIDE_DESC_2-NOT: [Int]
// HIDE_DESC_2: [Float]
// HIDE_DESC_2-NOT: [Int]
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showDesc.json -tok=SHOW_DESC_2 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=SHOW_DESC_2
// RUN: %complete-test -filter-rules=%S/Inputs/filter-rules/showDesc.json -tok=SHOW_DESC_3 %s -- -F %S/../Inputs/libIDE-mock-sdk | %FileCheck %s -check-prefix=SHOW_DESC_2
func testHideDesc2() {
struct Local {
subscript(_: Int) -> Int { return 0 }
subscript(_: Float) -> Float { return 0.0 }
}
Local()#^SHOW_DESC_2^#
let local = Local()
#^SHOW_DESC_3,local^#
}
// SHOW_DESC_2-NOT: [Int]
// SHOW_DESC_2: [Float]
// SHOW_DESC_2-NOT: [Int]
| d2ebb1d2f84f3faab3508c72adce2314 | 35.905172 | 183 | 0.665849 | false | true | false | false |
networkextension/SFSocket | refs/heads/master | SFSocket/tcp/DirectConnector.swift | bsd-3-clause | 1 | //
// DirectConnector.swift
// SimpleTunnel
//
// Created by yarshure on 15/11/11.
// Copyright © 2015年 Apple Inc. All rights reserved.
//
import Foundation
import AxLogger
//import CocoaAsyncSocket
public class DirectConnector:NWTCPSocket{
var interfaceName:String?
var targetHost:String = ""
var targetPort:Int = 0
//var ipAddress:String?
override public func start() {
autoreleasepool { do {
try super.connectTo(self.targetHost, port: Int(self.targetPort), enableTLS: false, tlsSettings: nil)
}catch let e as NSError {
//throw e
AxLogger.log("connectTo error \(e.localizedDescription)", level: .Error)
}
}
}
public override func connectTo(_ host: String, port: Int, enableTLS: Bool, tlsSettings: [NSObject : AnyObject]?) throws {
do {
try super.connectTo(host, port: port, enableTLS: false, tlsSettings: nil)
}catch let e {
throw e
}
}
public static func connectorWithHost(targetHost:String,targetPort:Int) ->DirectConnector{
//public func
let c = DirectConnector()
c.targetPort = targetPort
c.targetHost = targetHost
return c
}
}
| 3632878000cbfe10adb85428e4ed07a4 | 26.673913 | 126 | 0.613511 | false | false | false | false |
CodaFi/swift | refs/heads/master | test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-enum-1argument-1distinct_use.swift | apache-2.0 | 2 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main9NamespaceO5ValueVySS_SiGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32{{(, \[4 x i8\])?}},
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// i8** @"$sB[[INT]]_WV",
// i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main9NamespaceO5ValueVySS_SiGWV", i32 0, i32 0)
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main9NamespaceO5ValueVMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSSN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
enum Namespace<Arg> {
struct Value<First> {
let first: First
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32{{(, \[4 x i8\])?}},
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main9NamespaceO5ValueVySS_SiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Namespace<String>.Value(first: 13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceO5ValueVMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE_1]],
// CHECK-SAME: i8* [[ERASED_TYPE_2]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.+}}$s4main9NamespaceO5ValueVMn{{.+}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| 411efdcf09cec12ad40063864d659b36 | 37.421687 | 157 | 0.578551 | false | false | false | false |
bitrise-io/sample-apps-ios-xcode7 | refs/heads/master | BitriseXcode7Sample/AppDelegate.swift | mit | 2 | //
// AppDelegate.swift
// BitriseXcode7Sample
//
// Created by Viktor Benei on 9/16/15.
// Copyright © 2015 Bitrise. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let controller = masterNavigationController.topViewController as! MasterViewController
controller.managedObjectContext = self.managedObjectContext
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: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
// 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 "com.bitrise.BitriseXcode7Sample" 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("BitriseXcode7Sample", 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()
}
}
}
}
| 98b56bdf02d10b4a77aaef51915719a1 | 57.284615 | 291 | 0.734196 | false | false | false | false |
aleufms/JeraUtils | refs/heads/master | JeraUtils/Messages/Views/MessageView.swift | mit | 1 | //
// MessageView.swift
// beblueapp
//
// Created by Alessandro Nakamuta on 8/27/15.
// Copyright (c) 2015 Jera. All rights reserved.
//
import UIKit
import FontAwesome_swift
public enum MessageViewType {
case EmptyError
case ConnectionError
case GenericError
case GenericMessage
}
public class MessageView: UIView {
@IBOutlet private weak var imageView: UIImageView!
@IBOutlet private weak var textLabel: UILabel!
@IBOutlet private weak var retryButton: UIButton!
private var reloadBlock:(()->Void)?
public class func instantiateFromNib() -> MessageView {
let podBundle = NSBundle(forClass: self)
if let bundleURL = podBundle.URLForResource("JeraUtils", withExtension: "bundle") {
if let bundle = NSBundle(URL: bundleURL) {
return bundle.loadNibNamed("MessageView", owner: nil, options: nil)!.first as! MessageView
}else {
assertionFailure("Could not load the bundle")
}
}
assertionFailure("Could not create a path to the bundle")
return MessageView()
// return NSBundle.mainBundle().loadNibNamed("MessageView", owner: nil, options: nil).first as! MessageView
}
public var color: UIColor? {
didSet {
refreshAppearence()
}
}
private func refreshAppearence() {
textLabel.textColor = color
imageView.tintColor = color
}
public func populateWith(text: String, messageViewType: MessageViewType, reloadBlock: (()->Void)? = nil ) {
switch messageViewType {
case .EmptyError:
imageView.image = UIImage.fontAwesomeIconWithName(FontAwesome.List, textColor: UIColor.blackColor(), size: CGSize(width: 41, height: 41)).imageWithRenderingMode(.AlwaysTemplate)
imageView.tintColor = color
case .ConnectionError:
imageView.image = UIImage.fontAwesomeIconWithName(FontAwesome.Globe, textColor: UIColor.blackColor(), size: CGSize(width: 41, height: 41)).imageWithRenderingMode(.AlwaysTemplate)
imageView.tintColor = color
case .GenericError:
imageView.image = UIImage.fontAwesomeIconWithName(FontAwesome.ExclamationCircle, textColor: UIColor.blackColor(), size: CGSize(width: 41, height: 41)).imageWithRenderingMode(.AlwaysTemplate)
imageView.tintColor = color
case .GenericMessage:
imageView.image = nil
}
textLabel.text = text
self.reloadBlock = reloadBlock
retryButton.hidden = (reloadBlock == nil)
}
@IBAction func retryButtonAction(sender: AnyObject) {
if let reloadBlock = reloadBlock {
reloadBlock()
}
}
}
| 88ae736f7e885927cdef8015615ce5be | 32.716049 | 202 | 0.660198 | false | false | false | false |
xsunsmile/zentivity | refs/heads/master | zentivity/Photo.swift | apache-2.0 | 1 | ////
//// Photo.swift
//// zentivity
////
//// Created by Eric Huang on 3/7/15.
//// Copyright (c) 2015 Zendesk. All rights reserved.
////
class Photo : PFObject, PFSubclassing {
@NSManaged var user: PFUser
@NSManaged var file: PFFile
override class func initialize() {
var onceToken : dispatch_once_t = 0;
dispatch_once(&onceToken) {
self.registerSubclass()
println("INITING PHOTO")
}
}
class func parseClassName() -> String {
return "Photo"
}
// Use for creating only!!
// Sets each photo's user to to current user
class func photosFromImages(images: [UIImage]) -> NSMutableArray {
var photos = NSMutableArray()
for image in images {
var photo = Photo()
photo.file = PFFile(name:"image.png", data: UIImagePNGRepresentation(image))
photo.user = User.currentUser()!
photos.addObject(photo as Photo)
}
return photos
}
} | 567f780e6929e938ff7f3b61d1604115 | 25.282051 | 88 | 0.573242 | false | false | false | false |
mozilla-mobile/firefox-ios | refs/heads/main | Client/Frontend/Settings/ContentBlockerSettingViewController.swift | mpl-2.0 | 1 | // 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
extension BlockingStrength {
var settingTitle: String {
switch self {
case .basic:
return .TrackingProtectionOptionBlockListLevelStandard
case .strict:
return .TrackingProtectionOptionBlockListLevelStrict
}
}
var settingSubtitle: String {
switch self {
case .basic:
return .TrackingProtectionStandardLevelDescription
case .strict:
return .TrackingProtectionStrictLevelDescription
}
}
static func accessibilityId(for strength: BlockingStrength) -> String {
switch strength {
case .basic:
return "Settings.TrackingProtectionOption.BlockListBasic"
case .strict:
return "Settings.TrackingProtectionOption.BlockListStrict"
}
}
}
// Additional information shown when the info accessory button is tapped.
class TPAccessoryInfo: ThemedTableViewController {
var isStrictMode = false
override func viewDidLoad() {
tableView.dataSource = self
tableView.delegate = self
tableView.estimatedRowHeight = 130
tableView.rowHeight = UITableView.automaticDimension
tableView.separatorStyle = .none
tableView.sectionHeaderHeight = 0
tableView.sectionFooterHeight = 0
applyTheme()
listenForThemeChange()
}
func headerView() -> UIView {
let stack = UIStackView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 10))
stack.axis = .vertical
let header = UILabel()
header.text = .TPAccessoryInfoBlocksTitle
header.font = DynamicFontHelper.defaultHelper.DefaultMediumBoldFont
header.textColor = themeManager.currentTheme.colors.textSecondary
stack.addArrangedSubview(UIView())
stack.addArrangedSubview(header)
stack.layoutMargins = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
stack.isLayoutMarginsRelativeArrangement = true
let topStack = UIStackView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 40))
topStack.axis = .vertical
let sep = UIView()
topStack.addArrangedSubview(stack)
topStack.addArrangedSubview(sep)
topStack.spacing = 10
topStack.layoutMargins = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0)
topStack.isLayoutMarginsRelativeArrangement = true
sep.backgroundColor = themeManager.currentTheme.colors.borderPrimary
sep.snp.makeConstraints { make in
make.height.equalTo(0.5)
make.width.equalToSuperview()
}
return topStack
}
override func applyTheme() {
super.applyTheme()
tableView.tableHeaderView = headerView()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func numberOfSections(in tableView: UITableView) -> Int {
return isStrictMode ? 5 : 4
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ThemedTableViewCell(style: .subtitle, reuseIdentifier: nil)
cell.applyTheme(theme: themeManager.currentTheme)
if indexPath.section == 0 {
if indexPath.row == 0 {
cell.textLabel?.text = .TPSocialBlocked
} else {
cell.textLabel?.text = .TPCategoryDescriptionSocial
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
cell.textLabel?.text = .TPCrossSiteBlocked
} else {
cell.textLabel?.text = .TPCategoryDescriptionCrossSite
}
} else if indexPath.section == 2 {
if indexPath.row == 0 {
cell.textLabel?.text = .TPCryptominersBlocked
} else {
cell.textLabel?.text = .TPCategoryDescriptionCryptominers
}
} else if indexPath.section == 3 {
if indexPath.row == 0 {
cell.textLabel?.text = .TPFingerprintersBlocked
} else {
cell.textLabel?.text = .TPCategoryDescriptionFingerprinters
}
} else if indexPath.section == 4 {
if indexPath.row == 0 {
cell.textLabel?.text = .TPContentBlocked
} else {
cell.textLabel?.text = .TPCategoryDescriptionContentTrackers
}
}
cell.imageView?.tintColor = themeManager.currentTheme.colors.iconPrimary
if indexPath.row == 1 {
cell.textLabel?.font = DynamicFontHelper.defaultHelper.DefaultMediumFont
}
cell.textLabel?.numberOfLines = 0
cell.detailTextLabel?.numberOfLines = 0
cell.backgroundColor = .clear
cell.textLabel?.textColor = themeManager.currentTheme.colors.textPrimary
cell.selectionStyle = .none
return cell
}
}
class ContentBlockerSettingViewController: SettingsTableViewController {
private let button = UIButton()
let prefs: Prefs
var currentBlockingStrength: BlockingStrength
init(prefs: Prefs) {
self.prefs = prefs
currentBlockingStrength = prefs.stringForKey(ContentBlockingConfig.Prefs.StrengthKey).flatMap({BlockingStrength(rawValue: $0)}) ?? .basic
super.init(style: .grouped)
self.title = .SettingsTrackingProtectionSectionName
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
tableView.reloadData()
}
override func generateSettings() -> [SettingSection] {
let strengthSetting: [CheckmarkSetting] = BlockingStrength.allOptions.map { option in
let id = BlockingStrength.accessibilityId(for: option)
let setting = CheckmarkSetting(
title: NSAttributedString(string: option.settingTitle),
style: .leftSide,
subtitle: NSAttributedString(string: option.settingSubtitle),
accessibilityIdentifier: id,
isChecked: { return option == self.currentBlockingStrength },
onChecked: {
self.currentBlockingStrength = option
self.prefs.setString(self.currentBlockingStrength.rawValue,
forKey: ContentBlockingConfig.Prefs.StrengthKey)
TabContentBlocker.prefsChanged()
self.tableView.reloadData()
let extras = [TelemetryWrapper.EventExtraKey.preference.rawValue: "ETP-strength",
TelemetryWrapper.EventExtraKey.preferenceChanged.rawValue: option.rawValue]
TelemetryWrapper.recordEvent(category: .action,
method: .change,
object: .setting,
extras: extras)
if option == .strict {
self.button.isHidden = true
let alert = UIAlertController(title: .TrackerProtectionAlertTitle,
message: .TrackerProtectionAlertDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: .TrackerProtectionAlertButton,
style: .default,
handler: nil))
self.present(alert, animated: true)
}
})
setting.onAccessoryButtonTapped = {
let vc = TPAccessoryInfo()
vc.isStrictMode = option == .strict
self.navigationController?.pushViewController(vc, animated: true)
}
return setting
}
let enabledSetting = BoolSetting(
prefs: profile.prefs,
prefKey: ContentBlockingConfig.Prefs.EnabledKey,
defaultValue: ContentBlockingConfig.Defaults.NormalBrowsing,
attributedTitleText: NSAttributedString(string: .TrackingProtectionEnableTitle)) { [weak self] enabled in
TabContentBlocker.prefsChanged()
strengthSetting.forEach { item in
item.enabled = enabled
}
self?.tableView.reloadData()
}
let firstSection = SettingSection(title: nil, footerTitle: NSAttributedString(string: .TrackingProtectionCellFooter), children: [enabledSetting])
let optionalFooterTitle = NSAttributedString(string: .TrackingProtectionLevelFooter)
// The bottom of the block lists section has a More Info button, implemented as a custom footer view,
// SettingSection needs footerTitle set to create a footer, which we then override the view for.
let blockListsTitle: String = .TrackingProtectionOptionProtectionLevelTitle
let secondSection = SettingSection(title: NSAttributedString(string: blockListsTitle), footerTitle: optionalFooterTitle, children: strengthSetting)
return [firstSection, secondSection]
}
// The first section header gets a More Info link
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let _defaultFooter = super.tableView(tableView, viewForFooterInSection: section) as? ThemedTableSectionHeaderFooterView
guard let defaultFooter = _defaultFooter else { return nil }
if section == 0 {
// TODO: Get a dedicated string for this.
let title: String = .TrackerProtectionLearnMore
let font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .subheadline, size: 12.0)
var attributes = [NSAttributedString.Key: AnyObject]()
attributes[NSAttributedString.Key.foregroundColor] = themeManager.currentTheme.colors.actionPrimary
attributes[NSAttributedString.Key.font] = font
button.setAttributedTitle(NSAttributedString(string: title, attributes: attributes), for: .normal)
button.addTarget(self, action: #selector(moreInfoTapped), for: .touchUpInside)
button.isHidden = false
defaultFooter.addSubview(button)
button.snp.makeConstraints { (make) in
make.top.equalTo(defaultFooter.titleLabel.snp.bottom)
make.leading.equalTo(defaultFooter.titleLabel)
}
return defaultFooter
}
if currentBlockingStrength == .basic {
return nil
}
return defaultFooter
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return UITableView.automaticDimension
}
@objc func moreInfoTapped() {
let viewController = SettingsContentViewController()
viewController.url = SupportUtils.URLForTopic("tracking-protection-ios")
navigationController?.pushViewController(viewController, animated: true)
}
}
| 37e3caffa07e3888421e2f775a28e723 | 40.15 | 155 | 0.624631 | false | false | false | false |
qinting513/WeiBo-Swift | refs/heads/master | WeiBo_V3/WeiBo/Classes/View[视图跟控制器]/Main/WBBaseViewController.swift | apache-2.0 | 1 | //
// WBBaseViewController.swift
// WeiBo
//
// Created by Qinting on 16/9/6.
// Copyright © 2016年 Qinting. All rights reserved.
//
import UIKit
//面试题 OC中支持多继承吗 如果不支持,如何替代 答案: 使用协议替代
//class WBBaseViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate{
//swift 中,利用‘extension’可以把函数按照功能分类管理,便于阅读跟维护
//注意:
//1. extension中不能有属性
//2.extension中不能重写父类方法,重写父类方法,是子类的职责,扩展是对类的扩展,使类的功能更强大
//主控制机器基类
class WBBaseViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate {
// 如果用户没有登录 则不创建
var tableView : UITableView?
// 添加刷新控件
var refreshControl : UIRefreshControl?
// 上拉刷新标记
var isPullup = false
//// 用户登录标记
// var userLogon = true
// 设置访客视图信息的字典
var visitorInfoDictionary : [String:String]?
// MARK:- 隐藏系统的后,自定义导航栏
lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main().bounds.size.width, height: 64))
// MARK: - 自定义的导航项
lazy var naviItem = UINavigationItem()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
// 如果我想每次都加载,那就放在viewWillAppear方法里,用户登录了才刷新数据
WBNetworkManager.shared.userLogon ? loadData() : ()
//新浪登录成功的通知
NotificationCenter.default().addObserver(
self,
selector: #selector(loginSuccess),
name: WBUserLoginSuccessNotification,
object: nil)
}
//MARK: - 重写title 的 setter方法
override var title: String? {
didSet{
naviItem.title = title
}
}
// 加载数据 具体的实现由子类负责
func loadData() {
// 如果不实现任何方法,则默认关闭
refreshControl?.endRefreshing()
}
deinit {
NotificationCenter.default().removeObserver(self)
}
}
//MARK:- 登录注册
extension WBBaseViewController{
@objc private func registerBtnClick(){
}
//通知用户登录
@objc private func loginBtnClick() {
NotificationCenter.default().post(name: NSNotification.Name(rawValue:WBUserShouldLoginNotification) ,
object: nil)
}
@objc private func loginSuccess(n : Notification){
// print("登录成功: \(n)")
WBNetworkManager.shared.userLoging = true
naviItem.leftBarButtonItem = nil
naviItem.rightBarButtonItem = nil
//更新UI -- >将访客视图替换为表格视图
//需要重新设置View
//在访问view的getter时,如果view == nil 会去调用loadView方法 -> viewDidLoad方法
view = nil
//关键代码:注销通知,重新执行viewDidLoad 会再次注册通知!避免通知重复注册
NotificationCenter.default().removeObserver(self)
}
func logout(){
WBNetworkManager.shared.userLoging = false
}
}
//设置界面
extension WBBaseViewController {
private func setupUI() {
view.backgroundColor = UIColor.randomColor()
setupNavi()
WBNetworkManager.shared.userLogon ? setupTableView() : setupVisitView()
}
// MARK: - 设置tableView
func setupTableView(){
tableView = UITableView(frame: view.bounds, style: .plain)
view.insertSubview(tableView!, belowSubview: navigationBar)
tableView?.dataSource = self
tableView?.delegate = self
// 取消自动缩进 如果隐藏了导航栏会缩进 20 个点
automaticallyAdjustsScrollViewInsets = false
// 设置内容缩进
tableView?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height,
left: 0,
bottom: tabBarController?.tabBar.bounds.height ?? 49 ,
right: 0)
//修改指示器的缩进
tableView?.scrollIndicatorInsets = (tableView?.contentInset)!
// 设置刷新控件
refreshControl = UIRefreshControl()
tableView?.addSubview(refreshControl!)
// 添加监听方法
refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
}
// MARK: - 设置访客视图
private func setupVisitView(){
let visitorView = WBVisitorView(frame: view.bounds)
visitorView.backgroundColor = UIColor.white()
view.insertSubview(visitorView, belowSubview: navigationBar)
// 1.设置导航视图信息
visitorView.visitorInfo = visitorInfoDictionary
//2.添加监听方法
visitorView.loginBtn.addTarget(self, action: #selector(loginBtnClick), for: .touchUpInside)
visitorView.registerBtn.addTarget(self, action: #selector(registerBtnClick), for: .touchUpInside)
//3.设置导航条按钮
naviItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(registerBtnClick))
naviItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(loginBtnClick))
}
// MARK: - 设置导航条
private func setupNavi(){
// 添加一个导航栏
view.addSubview(navigationBar)
// 设置导航项
navigationBar.items = [naviItem]
// 设置naviBar的 背景 渲染颜色
navigationBar.barTintColor = UIColor(white: 0xF6F6F6, alpha: 1.0)
// 设置naviBar的 barButton 文字渲染颜色
navigationBar.tintColor = UIColor.orange()
// 设置naviBar的 标题字体颜色
navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray()]
}
}
extension WBBaseViewController {
@objc(numberOfSectionsInTableView:) func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
// 基类只是准备方法,子类负责具体实现,子类的数据源方法不需要super
@objc(tableView:cellForRowAtIndexPath:) func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 只是保证没有语法错误
return UITableViewCell()
}
/// 在显示最后一行的时候做上拉刷新
@objc(tableView:willDisplayCell:forRowAtIndexPath:) func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// 判断是最后分区 最后一行
let row = indexPath.row
let section = tableView.numberOfSections - 1
if row < 0 || section < 0 {
return
}
let count = tableView.numberOfRows(inSection: section)
// 判断最后一行,同时没有上拉刷新
if row == (count - 1) && !isPullup {
// print("上拉刷新")
self.isPullup = true
self.loadData()
}
}
}
| 0f6fd0e257b3c82e9cc95ed745c0cf52 | 30.595122 | 164 | 0.619423 | false | false | false | false |
xiabob/ZhiHuDaily | refs/heads/master | ZhiHuDaily/ZhiHuDaily/DataSource/GetBeforeNews.swift | mit | 1 | //
// GetBeforeNews.swift
// ZhiHuDaily
//
// Created by xiabob on 17/3/21.
// Copyright © 2017年 xiabob. All rights reserved.
//
import UIKit
import SwiftyJSON
import SwiftDate
class GetBeforeNews: XBAPIBaseManager, ManagerProtocol, XBAPILocalCache {
var normalNewsModel: [NewsModel] = []
var beforeDate = ""
var currentDate = ""
var path: String {
return "/news/before/" + beforeDate
}
var shouldCache: Bool {return true}
func customLoadFromLocal() {
guard let realm = RealmManager.shared.defaultRealm else {return}
var resultDate = Date()
do {
let date = try beforeDate.date(format: .custom("yyyyMMdd"))
resultDate = date.absoluteDate - 1.day
} catch {}
currentDate = resultDate.string(format: .custom("yyyyMMdd"))
let normalNews = News.fetchNews(from: realm, withDate: currentDate)
normalNewsModel = normalNews.map({ (news) -> NewsModel in
return NewsModel(from: news)
})
}
func getDataFromLocal(from key: String) -> Data? {
customLoadFromLocal()
return nil
}
func parseResponseData(_ data: AnyObject) {
let json = JSON(data)
let date = json["date"].stringValue
let normalStories = json["stories"].arrayValue
var normalNews: [News] = []
let realm = RealmManager.shared.defaultRealm
try? realm?.write({
for newsDic in normalStories {
let newsID = newsDic["id"].intValue
let existNews = realm?.object(ofType: News.self, forPrimaryKey: newsID)
if let existNews = existNews { //存在则更新
existNews.update(from: newsDic, dateString: date)
normalNews.append(existNews)
} else { //否则创建新的实体
let news = News(from: newsDic, dateString: date)
realm?.add(news)
normalNews.append(news)
}
}
normalNewsModel = normalNews.map({ (news) -> NewsModel in
return NewsModel(from: news)
})
})
}
}
| a06785b60bd9af3df622f7d6f32a1fe2 | 29.861111 | 87 | 0.560756 | false | false | false | false |
acumenrev/CANNavApp | refs/heads/master | CANNavApp/CANNavApp/Classes/ViewControllers/MainViewController.swift | apache-2.0 | 1 | //
// MainViewController.swift
// CANNavApp
//
// Created by Tri Vo on 7/15/16.
// Copyright © 2016 acumenvn. All rights reserved.
//
import UIKit
import QuartzCore
import CoreLocation
import PKHUD
class MainViewController: UIViewController, SearchViewControllerDelegate {
enum MovingMode : String {
case Driving = "driving"
case Walking = "walking"
}
// MARK: - Variables
let kTAG_TXT_FROM = 101
let kTAG_TXT_TO = 102
let kTAG_BTN_MOVING_MODE_CAR = 101
let kTAG_BTN_MOVING_MODE_WALKING = 104
var mLocationManager : CLLocationManager?
var mCurrentUserLocation : CLLocation?
var bDidGetUserLocationFirstTime : Bool = false
var mMarkerFrom : GMSMarker?
var mMarkerTo : GMSMarker?
var mMarkerUserLocation : GMSMarker?
var mLocationFrom : MyLocation?
var mLocationTo : MyLocation?
var mSearchViewControllerFrom : SearchViewController?
var mSearchViewControllerTo : SearchViewController?
var mCurrentMovingMode : MovingMode = .Driving
var mCurrentDirection : DirectionModel?
var mDirectionDictionary : NSMutableDictionary = NSMutableDictionary()
var mCurrentPolyline : GMSPolyline?
let mSelectedColor : UIColor = UIColor(red: 255/255, green: 214/255, blue: 92/255, alpha: 1)
// MARK: - IBOutlets
@IBOutlet var mMapView: GMSMapView!
@IBOutlet var mViewFrom: UIView!
@IBOutlet var mViewTo: UIView!
@IBOutlet var mTxtFrom: UITextField!
@IBOutlet var mTxtTo: UITextField!
@IBOutlet var mViewCurrentLocation: UIView!
@IBOutlet var mViewMovingModeCar: UIView!
@IBOutlet var mViewMovingModeWalking: UIView!
@IBOutlet var mLblDistance: UILabel!
@IBOutlet var mLblDuration: UILabel!
@IBOutlet var mViewDistanceAndDuration: UIView!
@IBOutlet var mViewVehicleBottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupUI()
if CLLocationManager.locationServicesEnabled() {
setupLocationManager()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Other methods
/**
Setup UI on view
*/
func setupUI() -> Void {
mViewTo.layer.cornerRadius = 8.0;
mViewTo.clipsToBounds = true;
mViewFrom.layer.cornerRadius = 8.0;
mViewFrom.clipsToBounds = true;
mViewCurrentLocation.layer.cornerRadius = 16.0;
mViewCurrentLocation.clipsToBounds = true;
mViewDistanceAndDuration.layer.cornerRadius = 8.0
mViewDistanceAndDuration.clipsToBounds = true
mTxtTo.tag = kTAG_TXT_TO
mTxtFrom.tag = kTAG_TXT_FROM
mViewDistanceAndDuration.hidden = true
// setup map view
self.setupMapView()
// set constraint for vehicle view
mViewVehicleBottomConstraint.constant = -50
}
/**
Setup location manager
*/
func setupLocationManager() -> Void {
if mLocationManager == nil {
mLocationManager = CLLocationManager()
mLocationManager?.delegate = self
mLocationManager?.desiredAccuracy = kCLLocationAccuracyKilometer
mLocationManager?.requestWhenInUseAuthorization()
}
mLocationManager?.startUpdatingLocation()
}
/**
Setup Google Map View
*/
func setupMapView() -> Void {
// config Google Maps
mMapView.userInteractionEnabled = true
mMapView.mapType = kGMSTypeNormal
mMapView.settings.myLocationButton = false
mMapView.myLocationEnabled = false
mMapView.settings.compassButton = true
mMapView.settings.zoomGestures = true
mMapView.settings.scrollGestures = true
mMapView.settings.indoorPicker = false
mMapView.settings.tiltGestures = false
mMapView.settings.rotateGestures = true
}
/**
Show message for location service permission
*/
func showMessageForLocationServicesPermission() -> Void {
let alert = self.showAlert(Constants.AlertTitle.NoLocationService.rawValue, message: Constants.AlertMessage.NoLocationService.rawValue, delegate: nil, tag: 101, cancelButton: "no, thanks", ok: "settings", okHandler: {
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}, cancelhandler: {})
self.presentViewController(alert, animated: true, completion: nil)
}
/**
Draw paths on Google Maps
*/
func drawPaths() -> Void {
if mMarkerTo != nil && mMarkerFrom != nil {
var direction : DirectionModel?
if mDirectionDictionary.objectForKey(mCurrentMovingMode.rawValue) != nil {
direction = mDirectionDictionary.objectForKey(mCurrentMovingMode.rawValue) as? DirectionModel
}
if direction != nil {
// draw paths
drawPaths(direction!)
} else {
// request directions from google
// get directions
NetworkManager.sharedInstance.getDirectionPath(mMarkerFrom!.position, destination: mMarkerTo!.position, movingMode: mCurrentMovingMode.rawValue, completion: { (direction) in
// cache in NSDictionary
self.mDirectionDictionary.setObject(direction, forKey: self.mCurrentMovingMode.rawValue)
// draw paths
self.drawPaths(direction)
}, fail: { (failError) in
})
}
}
}
/**
Draw paths on Map
- parameter direction: DirectionModel
*/
func drawPaths(direction : DirectionModel) -> Void {
if direction.routes?.count > 0 {
let route = direction.routes?.first
let path = GMSPath(fromEncodedPath: (route?.paths)!)
if mCurrentPolyline == nil {
mCurrentPolyline = GMSPolyline()
mCurrentPolyline!.strokeColor = UIColor.blueColor()
mCurrentPolyline!.strokeWidth = 2.0
}
mCurrentPolyline?.path = path
mCurrentPolyline?.map = mMapView
// enable moving mode bar
self.mViewVehicleBottomConstraint.constant = 0
// update duration and distance
self.refreshDistanceAndDurationValues(direction)
}
}
/**
Refresh moving mode bar
*/
func refreshMovingModeBar() -> Void {
mViewMovingModeCar.backgroundColor = UIColor.clearColor()
mViewMovingModeWalking.backgroundColor = UIColor.clearColor()
switch mCurrentMovingMode {
case .Driving:
mViewMovingModeCar.backgroundColor = mSelectedColor
break
case .Walking:
mViewMovingModeWalking.backgroundColor = mSelectedColor
break
default:
break
}
}
/**
Refresh distance and duration values
- parameter direction: DirectionModel
*/
func refreshDistanceAndDurationValues(direction : DirectionModel) -> Void {
if direction.routes?.count > 0 {
if direction.routes?.first?.legs?.count > 0 {
mViewDistanceAndDuration.hidden = false
mLblDuration.text = direction.routes?.first?.legs?.first?.duration
mLblDistance.text = direction.routes?.first?.legs?.first?.distance
}
}
}
// MARK: - Actions
@IBAction func btnCurrentLocation_Touched(sender: AnyObject) {
if (mCurrentUserLocation != nil) {
let camera = GMSCameraPosition.cameraWithLatitude((mCurrentUserLocation?.coordinate.latitude)!, longitude: (mCurrentUserLocation?.coordinate.longitude)!, zoom: mMapView.camera.zoom)
mMapView.animateToCameraPosition(camera)
} else {
self.showMessageForLocationServicesPermission()
}
}
@IBAction func btnTo_Touched(sender: AnyObject) {
if mSearchViewControllerTo == nil {
mSearchViewControllerTo = SearchViewController(nibName: "SearchViewController", bundle: nil, delegate: self, locationInfo: mLocationTo, searchForFromAddress: false)
}
mSearchViewControllerTo?.mMyLocation = mLocationTo
self.presentViewController(mSearchViewControllerTo!, animated: true, completion: nil)
}
@IBAction func btnFrom_Touched(sender: AnyObject) {
if mSearchViewControllerFrom == nil {
mSearchViewControllerFrom = SearchViewController(nibName: "SearchViewController", bundle: nil, delegate: self, locationInfo: mLocationFrom, searchForFromAddress: true)
}
mSearchViewControllerFrom?.mMyLocation = mLocationFrom
self.presentViewController(mSearchViewControllerFrom!, animated: true, completion: nil)
}
@IBAction func changeMovingMode(sender: AnyObject) {
let btn = sender as! UIButton
var movingMode = MovingMode.Driving
switch btn.tag {
case kTAG_BTN_MOVING_MODE_CAR:
movingMode = MovingMode.Driving
break
case kTAG_BTN_MOVING_MODE_WALKING:
movingMode = MovingMode.Walking
break
default:
break
}
if mCurrentMovingMode == movingMode {
return
}
mCurrentMovingMode = movingMode
self.refreshMovingModeBar()
self.drawPaths()
}
// MARK: - SearchViewController Delegate
func searchViewController(viewController: SearchViewController, choseLocation location: MyLocation, forFromAddress boolValue: Bool) {
// remove direction cache
mDirectionDictionary.removeAllObjects()
if boolValue == true {
// from address
mLocationFrom = location
// relocate marker
if mMarkerFrom == nil {
// init marker to
mMarkerFrom = GMSMarker()
mMarkerFrom?.icon = UIImage(named: "default_marker")
mMarkerFrom?.zIndex = 2
} else {
mMarkerFrom?.map = nil
}
mMarkerFrom?.position = location.mLocationCoordinate!
mTxtFrom.text = location.mLocationName
mMarkerFrom?.map = mMapView
mMarkerFrom?.title = location.mLocationName
} else {
// to address
mLocationTo = location
// relocate marker
if mMarkerTo == nil {
// init marker to
mMarkerTo = GMSMarker()
mMarkerTo?.icon = UIImage(named: "default_marker")
mMarkerTo?.zIndex = 2
} else {
mMarkerTo?.map = nil
}
mMarkerTo?.position = location.mLocationCoordinate!
mMarkerTo?.title = location.mLocationName
mMarkerTo?.map = mMapView
mTxtTo.text = location.mLocationName
}
self.drawPaths()
// move camera
mMapView.camera = GMSCameraPosition.cameraWithTarget(location.mLocationCoordinate!, zoom: (mMapView.camera.zoom==4 ? 16 : mMapView.camera.zoom))
}
}
// MARK: - Location Manager Delegate
extension MainViewController : CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.first
mCurrentUserLocation = location
if mCurrentUserLocation != nil && bDidGetUserLocationFirstTime == false {
bDidGetUserLocationFirstTime = true
// current location marker
mMarkerUserLocation = GMSMarker()
mMarkerUserLocation?.map = mMapView
mMarkerUserLocation?.icon = UIImage(named: "img_default_marker")
mMarkerUserLocation?.title = ""
mMarkerUserLocation?.zIndex = 1
// animate map move to user location
mMapView.camera = GMSCameraPosition.cameraWithTarget((mCurrentUserLocation?.coordinate)!, zoom: 16)
// setup marker from
mMarkerFrom = GMSMarker()
mMarkerFrom?.map = mMapView
mMarkerFrom?.icon = UIImage(named: "default_marker")
mMarkerFrom?.position = (location?.coordinate)!
mMarkerFrom?.zIndex = 2
// init from location & to location
mLocationFrom = MyLocation(location: (location?.coordinate)!, name: "")
mLocationTo = MyLocation(location: (location?.coordinate)!, name: "")
// request location
if TUtilsSwift.appDelegate().bCanReachInternet {
NetworkManager.sharedInstance.queryAddressBasedOnLatLng((location?.coordinate.latitude)!, lngValue: (location?.coordinate.longitude)!, completion: { (locationResult) in
self.mTxtFrom.text = locationResult?.formattedAddress
}, fail: { (failError) in
})
}
}
// update marker user location position
mMarkerUserLocation?.position = (location?.coordinate)!
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
TUtilsSwift.log(error.localizedDescription, logLevel: TUtilsSwift.TLogLevel.DEBUG)
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .AuthorizedWhenInUse:
mLocationManager?.startUpdatingLocation()
break
case .Denied:
self.showMessageForLocationServicesPermission()
break
case .NotDetermined:
self.setupLocationManager()
break
case .Restricted:
self.showMessageForLocationServicesPermission()
break
default:
break
}
}
}
| 3c8d95fbc52eae82a3272fc57602dcb6 | 33.643026 | 226 | 0.604681 | false | false | false | false |
ben-ng/swift | refs/heads/master | stdlib/public/core/CTypes.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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 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.
public typealias CUnsignedLong = UInt
/// 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.
public typealias CLong = Int
/// The C 'long long' type.
public typealias CLongLong = Int64
/// The C 'float' type.
public typealias CFloat = Float
/// The C 'double' type.
public typealias CDouble = Double
// FIXME: long double
// FIXME: Is it actually UTF-32 on Darwin?
//
/// The C++ 'wchar_t' type.
public typealias CWideChar = UnicodeScalar
// 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 = UnicodeScalar
/// 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.
@_fixed_layout
public struct OpaquePointer : Hashable {
internal var _rawValue: Builtin.RawPointer
@_versioned
@_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>(_ 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>(_ 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>(_ 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>(_ from: UnsafeMutablePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// The pointer's hash value.
///
/// The hash value is not guaranteed to be stable across different
/// invocations of the same program. Do not persist the hash value across
/// program runs.
public var hashValue: Int {
return 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 {
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
extension UInt {
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
extension OpaquePointer : Equatable {
public static func == (lhs: OpaquePointer, rhs: OpaquePointer) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))
}
}
/// The corresponding Swift type to `va_list` in imported C APIs.
@_fixed_layout
public struct CVaListPointer {
var value: UnsafeMutableRawPointer
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
}
}
func _memcpy(
dest destination: UnsafeMutableRawPointer,
src: UnsafeMutableRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
dest, src, size,
/*alignment:*/ Int32()._value,
/*volatile:*/ false._value)
}
/// Copy `count` bytes of memory from `src` into `dest`.
///
/// The memory regions `source..<source + count` and
/// `dest..<dest + count` may overlap.
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,
/*alignment:*/ Int32()._value,
/*volatile:*/ false._value)
}
@available(*, unavailable, renamed: "OpaquePointer")
public struct COpaquePointer {}
extension OpaquePointer {
@available(*, unavailable,
message:"use 'Unmanaged.toOpaque()' instead")
public init<T>(bitPattern bits: Unmanaged<T>) {
Builtin.unreachable()
}
}
| 90fa7ccc01f0d050179e4871cc0a76e4 | 26.85022 | 80 | 0.674628 | false | false | false | false |
arbitur/Func | refs/heads/master | source/Core/TextFormatter.swift | mit | 1 | //
// TextFormatter.swift
// Pods
//
// Created by Philip Fryklund on 17/Feb/17.
//
//
import Foundation
public class TextFormatter {
public static func percent(_ percent: Double, decimals: Int = 1) -> String {
let f = NumberFormatter()
f.numberStyle = .percent
f.maximumFractionDigits = decimals
return f.string(from: NSNumber(value: percent))!
}
public static func currency(_ amount: Double, currencyCode: CurrencyCode) -> String {
let f = NumberFormatter()
f.locale = Locale.current
f.numberStyle = .currency
f.maximumFractionDigits = (amount.remainder(dividingBy: 1) == 0) ? 0 : 2
f.currencyCode = currencyCode.rawValue
return f.string(from: NSNumber(value: amount))!
}
public static func timeComponents(_ time: Number, maximumComponents: Int = 1) -> String {
let f = DateComponentsFormatter()
f.allowedUnits = [.year, .month, .day, .hour, .minute, .second]
f.maximumUnitCount = maximumComponents
f.allowsFractionalUnits = false
f.collapsesLargestUnit = false
f.unitsStyle = .full
f.zeroFormattingBehavior = .dropAll
return f.string(from: time.toDouble()) ?? "NaN"
}
@available(iOS, deprecated: 1.0, message: "This only works for very specific situations")
public static func phoneNumber(_ phoneNumber: String) -> String {
let p = phoneNumber.extracted(characters: CharacterSet.decimalDigits)
let format: String
switch p.count {
case 1+9: format = "xxx-xxx xx xx"
case 1+8: format = "xxxx-xxx xx"
case 1+7: format = "xxx-xxx xx"
default: return p
}
var formattedNumber = ""
var index = 0
for char in format.map({ String($0) }) {
if char == "x" {
formattedNumber += String(p[p.index(p.startIndex, offsetBy: index)])
index += 1
}
else {
formattedNumber += char
}
}
return formattedNumber
}
}
// https://www.iban.com/currency-codes.html
public struct CurrencyCode: RawRepresentable {
public var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public static let sek: CurrencyCode = "SEK"
public static let usd: CurrencyCode = "USD"
public static let eur: CurrencyCode = "EUR"
}
extension CurrencyCode: ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
self.init(rawValue: value)
}
}
| 6d3d0ea4100eeccce82b732651edf3c4 | 19.208696 | 90 | 0.684596 | false | false | false | false |
zekunyan/TTGEmojiRate | refs/heads/master | Pod/Classes/EmojiRateView.swift | mit | 1 | //
// EmojiRateView.swift
// EmojiRate
//
// Created by zorro on 15/10/17.
// Copyright © 2015年 tutuge. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
open class EmojiRateView: UIView {
/// Rate default color for rateValue = 5
fileprivate static let rateLineColorBest: UIColor = UIColor.init(hue: 165 / 360, saturation: 0.8, brightness: 0.9, alpha: 1.0)
/// Rate default color for rateValue = 0
fileprivate static let rateLineColorWorst: UIColor = UIColor.init(hue: 1, saturation: 0.8, brightness: 0.9, alpha: 1.0)
// MARK: -
// MARK: Private property.
fileprivate var shapeLayer: CAShapeLayer = CAShapeLayer.init()
fileprivate var shapePath: UIBezierPath = UIBezierPath.init()
fileprivate var rateFaceMargin: CGFloat = 1
fileprivate var touchPoint: CGPoint? = nil
fileprivate var hueFrom: CGFloat = 0, saturationFrom: CGFloat = 0, brightnessFrom: CGFloat = 0, alphaFrom: CGFloat = 0
fileprivate var hueDelta: CGFloat = 0, saturationDelta: CGFloat = 0, brightnessDelta: CGFloat = 0, alphaDelta: CGFloat = 0
// MARK: -
// MARK: Public property.
/// Line width.
@IBInspectable open var rateLineWidth: CGFloat = 14 {
didSet {
if rateLineWidth > 20 {
rateLineWidth = 20
}
if rateLineWidth < 0.5 {
rateLineWidth = 0.5
}
self.rateFaceMargin = rateLineWidth / 2
redraw()
}
}
/// Current line color.
@IBInspectable open var rateColor: UIColor = UIColor.init(red: 55 / 256, green: 46 / 256, blue: 229 / 256, alpha: 1.0) {
didSet {
redraw()
}
}
/// Color range
open var rateColorRange: (from: UIColor, to: UIColor) = (EmojiRateView.rateLineColorWorst, EmojiRateView.rateLineColorBest) {
didSet {
// Get begin color
rateColorRange.from.getHue(&hueFrom, saturation: &saturationFrom, brightness: &brightnessFrom, alpha: &alphaFrom)
// Get end color
var hueTo: CGFloat = 1, saturationTo: CGFloat = 1, brightnessTo: CGFloat = 1, alphaTo: CGFloat = 1
rateColorRange.to.getHue(&hueTo, saturation: &saturationTo, brightness: &brightnessTo, alpha: &alphaTo)
// Update property
hueDelta = hueTo - hueFrom
saturationDelta = saturationTo - saturationFrom
brightnessDelta = brightnessTo - brightnessFrom
alphaDelta = alphaTo - alphaFrom
// Force to refresh current color
let currentRateValue = rateValue
rateValue = currentRateValue
}
}
/// If line color changes with rateValue.
@IBInspectable open var rateDynamicColor: Bool = true {
didSet {
redraw()
}
}
/// Mouth width. From 0.2 to 0.7.
@IBInspectable open var rateMouthWidth: CGFloat = 0.6 {
didSet {
if rateMouthWidth > 0.7 {
rateMouthWidth = 0.7
}
if rateMouthWidth < 0.2 {
rateMouthWidth = 0.2
}
redraw()
}
}
/// Mouth lip width. From 0.2 to 0.9
@IBInspectable open var rateLipWidth: CGFloat = 0.7 {
didSet {
if rateLipWidth > 0.9 {
rateLipWidth = 0.9
}
if rateLipWidth < 0.2 {
rateLipWidth = 0.2
}
redraw()
}
}
/// Mouth vertical position. From 0.1 to 0.5.
@IBInspectable open var rateMouthVerticalPosition: CGFloat = 0.35 {
didSet {
if rateMouthVerticalPosition > 0.5 {
rateMouthVerticalPosition = 0.5
}
if rateMouthVerticalPosition < 0.1 {
rateMouthVerticalPosition = 0.1
}
redraw()
}
}
/// If show eyes.
@IBInspectable open var rateShowEyes: Bool = true {
didSet {
redraw()
}
}
/// Eye width. From 0.1 to 0.3.
@IBInspectable open var rateEyeWidth: CGFloat = 0.2 {
didSet {
if rateEyeWidth > 0.3 {
rateEyeWidth = 0.3
}
if rateEyeWidth < 0.1 {
rateEyeWidth = 0.1
}
redraw()
}
}
/// Eye vertical position. From 0.6 to 0.8.
@IBInspectable open var rateEyeVerticalPosition: CGFloat = 0.6 {
didSet {
if rateEyeVerticalPosition > 0.8 {
rateEyeVerticalPosition = 0.8
}
if rateEyeVerticalPosition < 0.6 {
rateEyeVerticalPosition = 0.6
}
redraw()
}
}
/// Rate value. From 0 to 5.
@IBInspectable open var rateValue: Float = 2.5 {
didSet {
if rateValue > 5 {
rateValue = 5
}
if rateValue < 0 {
rateValue = 0
}
// Update color
if rateDynamicColor {
let rate: CGFloat = CGFloat(rateValue / 5)
// Calculate new color
self.rateColor = UIColor.init(
hue: hueFrom + hueDelta * rate,
saturation: saturationFrom + saturationDelta * rate,
brightness: brightnessFrom + brightnessDelta * rate,
alpha: alphaFrom + alphaDelta * rate)
}
// Callback
self.rateValueChangeCallback?(rateValue)
redraw()
}
}
/// If you are using this with a scroll view, for example, this allows the scroll view to recognize pan gestures at the same time.
@IBInspectable open var recognizeSimultanousGestures: Bool = false
/// Callback when rateValue changes.
open var rateValueChangeCallback: ((_ newRateValue: Float) -> Void)? = nil
/// Sensitivity when drag. From 1 to 10.
open var rateDragSensitivity: CGFloat = 5 {
didSet {
if rateDragSensitivity > 10 {
rateDragSensitivity = 10
}
if rateDragSensitivity < 1 {
rateDragSensitivity = 1
}
}
}
// MARK: -
// MARK: Public methods.
public override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
/**
Override layoutSubviews
*/
open override func layoutSubviews() {
super.layoutSubviews()
redraw()
}
// MARK: -
// MARK: Private methods.
/**
Init configure.
*/
fileprivate func configure() {
let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGestureAction))
addGestureRecognizer(panRecognizer)
panRecognizer.delegate = self
self.backgroundColor = self.backgroundColor ?? UIColor.white
self.clearsContextBeforeDrawing = true
self.isMultipleTouchEnabled = false
shapeLayer.fillColor = UIColor.clear.cgColor
rateColorRange = (EmojiRateView.rateLineColorWorst, EmojiRateView.rateLineColorBest)
self.layer.addSublayer(shapeLayer)
redraw()
}
/**
Redraw all lines.
*/
fileprivate func redraw() {
shapeLayer.frame = self.bounds
shapeLayer.strokeColor = rateColor.cgColor;
shapeLayer.lineCap = "round"
shapeLayer.lineWidth = rateLineWidth
shapePath.removeAllPoints()
shapePath.append(facePathWithRect(self.bounds))
shapePath.append(mouthPathWithRect(self.bounds))
shapePath.append(eyePathWithRect(self.bounds, isLeftEye: true))
shapePath.append(eyePathWithRect(self.bounds, isLeftEye: false))
shapeLayer.path = shapePath.cgPath
self.setNeedsDisplay()
}
/**
Generate face UIBezierPath
- parameter rect: rect
- returns: face UIBezierPath
*/
fileprivate func facePathWithRect(_ rect: CGRect) -> UIBezierPath {
let margin = rateFaceMargin + 2
let facePath = UIBezierPath(ovalIn: UIEdgeInsetsInsetRect(rect, UIEdgeInsetsMake(margin, margin, margin, margin)))
return facePath
}
/**
Generate mouth UIBezierPath
- parameter rect: rect
- returns: mouth UIBezierPath
*/
fileprivate func mouthPathWithRect(_ rect: CGRect) -> UIBezierPath {
let width = rect.width
let height = rect.width
let leftPoint = CGPoint(
x: width * (1 - rateMouthWidth) / 2,
y: height * (1 - rateMouthVerticalPosition))
let rightPoint = CGPoint(
x: width - leftPoint.x,
y: leftPoint.y)
let centerPoint = CGPoint(
x: width / 2,
y: leftPoint.y + height * 0.3 * (CGFloat(rateValue) - 2.5) / 5)
let halfLipWidth = width * rateMouthWidth * rateLipWidth / 2
let mouthPath = UIBezierPath()
mouthPath.move(to: leftPoint)
mouthPath.addCurve(
to: centerPoint,
controlPoint1: leftPoint,
controlPoint2: CGPoint(x: centerPoint.x - halfLipWidth, y: centerPoint.y))
mouthPath.addCurve(
to: rightPoint,
controlPoint1: CGPoint(x: centerPoint.x + halfLipWidth, y: centerPoint.y),
controlPoint2: rightPoint)
return mouthPath
}
/**
Generate eye UIBezierPath
- parameter rect: rect
- parameter isLeftEye: is left eye
- returns: eye UIBezierPath
*/
fileprivate func eyePathWithRect(_ rect: CGRect, isLeftEye: Bool) -> UIBezierPath {
if !rateShowEyes {
return UIBezierPath.init()
}
let width = rect.width
let height = rect.width
let centerPoint = CGPoint(
x: width * (isLeftEye ? 0.30 : 0.70),
y: height * (1 - rateEyeVerticalPosition) - height * 0.1 * (CGFloat(rateValue > 2.5 ? rateValue : 2.5) - 2.5) / 5)
let leftPoint = CGPoint(
x: centerPoint.x - rateEyeWidth / 2 * width,
y: height * (1 - rateEyeVerticalPosition))
let rightPoint = CGPoint(
x: centerPoint.x + rateEyeWidth / 2 * width,
y: leftPoint.y)
let eyePath = UIBezierPath()
eyePath.move(to: leftPoint)
eyePath.addCurve(
to: centerPoint,
controlPoint1: leftPoint,
controlPoint2: CGPoint(x: centerPoint.x - width * 0.06, y: centerPoint.y))
eyePath.addCurve(
to: rightPoint,
controlPoint1: CGPoint(x: centerPoint.x + width * 0.06, y: centerPoint.y),
controlPoint2: rightPoint)
return eyePath;
}
// MARK: Handling pan gestures.
@objc fileprivate func panGestureAction(_ sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
touchPoint = sender.location(in: self)
case .changed:
let currentPoint = sender.location(in: self)
// Change rate value
rateValue = rateValue + Float((currentPoint.y - touchPoint!.y) / self.bounds.height * rateDragSensitivity)
// Save current point
touchPoint = currentPoint
case .ended:
touchPoint = nil
default:
break
}
}
}
extension EmojiRateView : UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return recognizeSimultanousGestures
}
}
| c07205f2a8098dbc62c1470295f46ad0 | 30.033248 | 164 | 0.558019 | false | false | false | false |
lbkchen/wake-up-world | refs/heads/master | wakeupworld/wakeupworld/ListViewViewController.swift | mit | 1 | //
// ListViewViewController.swift
// wakeupworld
//
// Created by Ken Chen on 4/9/16.
// Copyright © 2016 wakeup. All rights reserved.
//
import UIKit
import SwiftyJSON
class ListViewViewController: UITableViewController {
var numberOfRows = 0
var photoArrays: [String] = [String]()
var nameArrays: [String] = [String]()
var storyArrays: [String] = [String]()
var clicks = [Bool]()
var numClicks = 0
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// let navVC = segue.destinationViewController as! UINavigationController
// let tableVC = navVC.viewControllers.first as! SecondViewController
// tableVC.receivedPhotoArrays = photoArrays
// tableVC.receivednameArrays = nameArrays
// tableVC.receivedclicks = clicks
// tableVC.receivedNumClicks = numClicks
//
// }
override func viewDidLoad() {
super.viewDidLoad()
parseJSON()
// Do any additional setup after loading the view.
}
func parseJSON() {
let path : String = NSBundle.mainBundle().pathForResource("watsi", ofType: "json") as String!
let jsonData = NSData(contentsOfFile: path) as NSData!
let readableJSON = JSON(data: jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil)
numberOfRows = readableJSON["profiles"].count
for i in 0...numberOfRows-1 {
var name = readableJSON["profiles"][i]["name"].string as String!
var photo = readableJSON["profiles"][i]["photo_url"].string as String!
var story = readableJSON["profiles"][i]["header"].string as String!
nameArrays.append(name)
photoArrays.append(photo)
storyArrays.append(story)
clicks.append(false)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfRows
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell!
if nameArrays.count != 0 {
var url = NSURL(string: photoArrays[indexPath.row])
var data = NSData(contentsOfURL: url!)
var imageHere = UIImage(data: data!)
cell.imageView?.image = imageHere!
cell.imageView?.transform = CGAffineTransformMakeScale(0.9, 1.1);
if (clicks[indexPath.row]) {
cell.backgroundColor = UIColor(hue: 0.0583, saturation: 0.4, brightness: 0.82, alpha: 1.0)
} else {
cell.backgroundColor = UIColor(hue: 0.5306, saturation: 0.31, brightness: 0.93, alpha: 1.0)
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell!
var name = nameArrays[indexPath.row]
var story = storyArrays[indexPath.row]
var string = "This is " + name + "." + "\r\n"
string += story
cell!.textLabel?.text = string
cell!.imageView?.image = nil
cell!.textLabel?.textAlignment = NSTextAlignment.Center
clicks[indexPath.row] = !clicks[indexPath.row]
if (clicks[indexPath.row]) {
cell!.backgroundColor = UIColor(hue: 0.0583, saturation: 0.4, brightness: 0.82, alpha: 1.0)
numClicks += 1
} else {
cell!.backgroundColor = UIColor(hue: 0.5306, saturation: 0.31, brightness: 0.93, alpha: 1.0)
numClicks -= 1
}
cell!.textLabel?.textColor = UIColor.blackColor()
cell!.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell!.textLabel?.numberOfLines = 0
NSLog("Patient: " + name + " Donate?: " + clicks[indexPath.row].description)
}
// /*
// FILL IN METHOD FOR ACTION CALL WHEN RANDOM IS PRESSED
// */
// @IBAction func pressedRandom(sender: UIButton) {
//
// }
//
// /*
// FILL IN METHOD FOR ACTION CALL WHEN GOODNIGHT IS PRESSED
// */
// @IBAction func pressedGoodNight(sender: UIButton) {
//
// }
//
@IBAction func cancelToListViewViewController(segue:UIStoryboardSegue) {
}
//
// /*
// // 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.
// }
// */
}
| 42c1fa6104038df88d48f588146f8b74 | 33.863014 | 118 | 0.622397 | false | false | false | false |
biohazardlover/ROer | refs/heads/master | DataImporter/Item.swift | mit | 1 |
import Foundation
import CoreData
class Item: NSManagedObject {
/// Item id
@NSManaged var id: NSNumber?
/// Server name to reference the item in scripts and lookups,
/// should use no spaces.
@NSManaged var aegisName: String?
/// Name in English for displaying as output for @ and script commands.
@NSManaged var name: String?
/// 0 Healing item.
/// 2 Usable item.
/// 3 Etc item
/// 4 Armor/Garment/Boots/Headgear/Accessory
/// 5 Weapon
/// 6 Card
/// 7 Pet egg
/// 8 Pet equipment
/// 10 Ammo (Arrows/Bullets/etc)
/// 11 Usable with delayed consumption (intended for 'itemskill')
/// Items using the 'itemskill' script command are consumed after
/// selecting a target. Any other command will NOT consume the item.
/// 12 Shadow Equipment
/// 18 Another delayed consume that requires user confirmation before
/// using item.
@NSManaged var type: NSNumber?
/// Default buying price. When not specified, becomes double the sell price.
@NSManaged var buy: NSNumber?
/// Default selling price. When not specified, becomes half the buy price.
@NSManaged var sell: NSNumber?
/// Item's weight. Each 10 is 1 weight.
@NSManaged var weight: NSNumber?
/// Weapon's attack
@NSManaged var atk: NSNumber?
/// Weapon's magic attack (Renewal only)
@NSManaged var matk: NSNumber?
/// Armor's defense
@NSManaged var def: NSNumber?
/// Weapon's attack range
@NSManaged var range: NSNumber?
/// Amount of slots the item possesses.
@NSManaged var slots: NSNumber?
/// Equippable jobs. Uses the following bitmask table:
/// (S.) Novice (2^00): 0x00000001 初学者/超级初学者
/// Swordman (2^01): 0x00000002 剑士
/// Magician (2^02): 0x00000004 魔法师
/// Archer (2^03): 0x00000008 弓箭手
/// Acolyte (2^04): 0x00000010 服事
/// Merchant (2^05): 0x00000020 商人
/// Thief (2^06): 0x00000040 盗贼
/// Knight (2^07): 0x00000080 骑士
/// Priest (2^08): 0x00000100 牧师
/// Wizard (2^09): 0x00000200 巫师
/// Blacksmith (2^10): 0x00000400 铁匠
/// Hunter (2^11): 0x00000800 猎人
/// Assassin (2^12): 0x00001000 刺客
/// Unused (2^13): 0x00002000
/// Crusader (2^14): 0x00004000 十字军
/// Monk (2^15): 0x00008000 武僧
/// Sage (2^16): 0x00010000 贤者
/// Rogue (2^17): 0x00020000 流氓
/// Alchemist (2^18): 0x00040000 炼金术师
/// Bard/Dancer (2^19): 0x00080000 诗人/舞娘
/// Unused (2^20): 0x00100000
/// Taekwon (2^21): 0x00200000 跆拳少年
/// Star Gladiator (2^22): 0x00400000 拳圣
/// Soul Linker (2^23): 0x00800000 灵媒
/// Gunslinger (2^24): 0x01000000 枪手
/// Ninja (2^25): 0x02000000 忍者
/// Gangsi (2^26): 0x04000000 国内没这职业,不知道是啥
/// Death Knight (2^27): 0x08000000 国内没这职业,直译是死亡骑士
/// Dark Collector (2^28): 0x10000000 国内没这职业,直译是黑暗收集者
/// Kagerou/Oboro (2^29): 0x20000000 日影忍者/月影忍者(影牙/胧,忍者的二转职业)
/// Rebellion (2^30): 0x40000000 反叛者/变革者(枪手的二转职业)
///
/// Novice + Swordman + Magician + Archer = 0x0000000F, why?
/// Because: 10 = A, 11 = B, 12 = C, 13 = D, 14 = E, and 15 = F
/// It's using hexadecimal.
@NSManaged var job: NSNumber?
/// Equippable upper-types. Uses the following bitmasks:
/// 1: Normal classes (no Baby/Transcendent/Third classes) 普通职业 (不含 宝宝职业/进阶职业/三转职业)
/// 2: Transcedent classes (no Transcedent-Third classes) 进阶职业 (不含 进阶三转职业)
/// 4: Baby classes (no Third-Baby classes) 宝宝职业 (不含 三转宝宝职业)
/// 8: Third classes (no Transcedent-Third or Third-Baby classes) 三转职业 (不含 进阶三转职业和三转宝宝职业)
/// 16: Transcedent-Third classes 进阶三转职业
/// 32: Third-Baby classes 三转宝宝职业
///
/// 注:这个原来叫class,但是class不用被用来当变量名,所以改成了category
@NSManaged var category: NSNumber?
/// Gender restriction. 0 is female, 1 is male, 2 for both.
@NSManaged var gender: NSNumber?
/// Equipment's placement. Values are:
/// 2^8 256 = Upper Headgear 头饰上
/// 2^9 512 = Middle Headgear 头饰中
/// 2^0 001 = Lower Headgear 头饰下
/// 2^4 016 = Armor 盔甲
/// 2^1 002 = Weapon 武器
/// 2^5 032 = Shield 盾牌
/// 2^2 004 = Garment 披肩
/// 2^6 064 = Footgear 鞋子
/// 2^3 008 = Accessory Right 右侧饰品
/// 2^7 128 = Accessory Left 左侧饰品
/// 2^10 1024 = Costume Top Headgear 时装-头饰上
/// 2^11 2048 = Costume Mid Headgear 时装-头饰中
/// 2^12 4096 = Costume Low Headgear 时装-头饰下
/// 2^13 8192 = Costume Garment/Robe 时装-披肩
/// 2^15 32768 = Ammo 弹药/弓箭
/// 2^16 65536 = Shadow Armor 影子装备 – 盔甲
/// 2^17 131072 = Shadow Weapon 影子装备 – 武器
/// 2^18 262144 = Shadow Shield 影子装备 – 盾牌
/// 2^19 524288 = Shadow Shoes 影子装备 – 鞋子
/// 2^20 1048576 = Shadow Accessory Right (Earring) 影子装备 – 右侧饰品(耳环)
/// 2^21 2097152 = Shadow Accessory Left (Pendant) 影子装备 – 左侧饰品(吊坠)
@NSManaged var loc: NSNumber?
/// Weapon level.
@NSManaged var wLV: NSNumber?
/// Base level required to be able to equip.
@NSManaged var eLV: NSNumber?
/// Only able to equip if base level is lower than this.
@NSManaged var maxLevel: NSNumber?
/// 1 if the item can be refined, 0 otherwise.
@NSManaged var refineable: NSNumber?
/// For normal items, defines a replacement view-sprite for the item (eg:
/// Making apples look like apple juice). The special case are weapons
/// and ammo where this value indicates the weapon-class of the item.
///
/// For weapons, the types are:
/// 0: bare fist 空手
/// 1: Daggers 短剑
/// 2: One-handed swords 单手剑
/// 3: Two-handed swords 双手剑
/// 4: One-handed spears 单手矛
/// 5: Two-handed spears 双手矛
/// 6: One-handed axes 单手斧
/// 7: Two-handed axes 双手斧
/// 8: Maces 锤子
/// 9: Unused
/// 10: Staves 单手杖
/// 11: Bows 猎弓
/// 12: Knuckles 拳套
/// 13: Musical Instruments 乐器
/// 14: Whips 鞭子
/// 15: Books 书籍
/// 16: Katars 拳刃
/// 17: Revolvers 左轮手枪
/// 18: Rifles 来复枪/来福枪
/// 19: Gatling guns 格林机枪
/// 20: Shotguns 霰弹枪/散弹枪
/// 21: Grenade launchers 榴弹枪/榴弹发射器
/// 22: Fuuma Shurikens 风魔飞镖
/// 23: Two-handed staves 双手杖
/// 24: Max Type
/// 25: Dual-wield Daggers 双刀流-短剑(左手右手都是1把短剑)
/// 26: Dual-wield Swords 双刀流-剑(左手右手都是1把单手剑)
/// 27: Dual-wield Axes 双刀流-斧头(左手右手欧式1把单手斧)
/// 28: Dagger + Sword 短剑 + 单手剑
/// 29: Dagger + Axe 短剑 + 单手斧
/// 30: Sword + Axe 单手剑 + 单手斧
///
/// For ammo, the types are:
/// 1: Arrows 箭矢
/// 2: Throwable daggers 投掷用短剑
/// 3: Bullets 子弹
/// 4: Shells 炮弹
/// 5: Grenades 榴弹
/// 6: Shuriken 飞镖
/// 7: Kunai 苦无/飞刀
/// 8: Cannonballs 加农炮弹
/// 9: Throwable Items (Sling Item) 投掷用物品 (三转基因学者丢香蕉的香蕉就是这类物品)
@NSManaged var view: NSNumber?
/// Script to execute when the item is used/equipped.
@NSManaged var script: String?
/// Script to execute when the item is equipped.
/// Warning, not all item bonuses will work here as expected.
@NSManaged var onEquipScript: String?
/// Script to execute when the item is unequipped.
/// Warning, not all item bonuses will work here as expected.
@NSManaged var onUnequipScript: String?
}
| 046f30b63f25de1ec66cb0ff9652c117 | 41.970874 | 96 | 0.49808 | false | false | false | false |
ryuichis/swift-ast | refs/heads/master | Sources/AST/Declaration/PrecedenceGroupDeclaration.swift | apache-2.0 | 2 | /*
Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors
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.
*/
public class PrecedenceGroupDeclaration : ASTNode, Declaration {
public enum Attribute {
case higherThan(IdentifierList)
case lowerThan(IdentifierList)
case assignment(Bool)
case associativityLeft
case associativityRight
case associativityNone
}
public let name: Identifier
public let attributes: [Attribute]
public init(name: Identifier, attributes: [Attribute] = []) {
self.name = name
self.attributes = attributes
}
// MARK: - ASTTextRepresentable
override public var textDescription: String {
let attrsText = attributes.map({ $0.textDescription }).joined(separator: "\n")
let attrsBlockText = attributes.isEmpty ? "{}" : "{\n\(attrsText)\n}"
return "precedencegroup \(name) \(attrsBlockText)"
}
}
extension PrecedenceGroupDeclaration.Attribute : ASTTextRepresentable {
public var textDescription: String {
switch self {
case .higherThan(let ids):
return "higherThan: \(ids.textDescription)"
case .lowerThan(let ids):
return "lowerThan: \(ids.textDescription)"
case .assignment(let b):
let boolText = b ? "true" : "false"
return "assignment: \(boolText)"
case .associativityLeft:
return "associativity: left"
case .associativityRight:
return "associativity: right"
case .associativityNone:
return "associativity: none"
}
}
}
| 3cf50f39cad039f1922a91bac3340bce | 31.548387 | 85 | 0.713578 | false | false | false | false |
anirudh24seven/wikipedia-ios | refs/heads/develop | Wikipedia/Code/WMFWelcomeAnalyticsAnimationView.swift | mit | 1 | import Foundation
public class WMFWelcomeAnalyticsAnimationView : WMFWelcomeAnimationView {
lazy var fileImgView: UIImageView = {
let imgView = UIImageView(frame: self.bounds)
imgView.image = UIImage(named: "ftux-file")
imgView.contentMode = UIViewContentMode.ScaleAspectFit
imgView.layer.zPosition = 101
imgView.layer.opacity = 0
imgView.layer.transform = self.wmf_leftTransform
return imgView
}()
var squashedHeightBarTransform: CATransform3D{
return CATransform3DMakeScale(1, 0, 1)
}
var fullHeightBarTransform: CATransform3D{
return CATransform3DMakeScale(1, -1, 1) // -1 to flip Y so bars grow from bottom up.
}
var barOddColor: CGColor{
return UIColor.wmf_colorWithHex(0x4A90E2, alpha: 1.0).CGColor
}
var barEvenColor: CGColor{
return UIColor.wmf_colorWithHex(0x2A4B8D, alpha: 1.0).CGColor
}
lazy var bar1: WelcomeBarShapeLayer = {
let bar = WelcomeBarShapeLayer(
unitRect: CGRectMake(0.313, 0.64, 0.039, 0.18),
referenceSize:self.frame.size,
transform: self.squashedHeightBarTransform
)
bar.fillColor = self.barOddColor
return bar
}()
lazy var bar2: WelcomeBarShapeLayer = {
let bar = WelcomeBarShapeLayer(
unitRect: CGRectMake(0.383, 0.64, 0.039, 0.23),
referenceSize:self.frame.size,
transform: self.squashedHeightBarTransform
)
bar.fillColor = self.barEvenColor
return bar
}()
lazy var bar3: WelcomeBarShapeLayer = {
let bar = WelcomeBarShapeLayer(
unitRect: CGRectMake(0.453, 0.64, 0.039, 0.06),
referenceSize:self.frame.size,
transform: self.squashedHeightBarTransform
)
bar.fillColor = self.barOddColor
return bar
}()
lazy var bar4: WelcomeBarShapeLayer = {
let bar = WelcomeBarShapeLayer(
unitRect: CGRectMake(0.523, 0.64, 0.039, 0.12),
referenceSize:self.frame.size,
transform: self.squashedHeightBarTransform
)
bar.fillColor = self.barEvenColor
return bar
}()
lazy var bar5: WelcomeBarShapeLayer = {
let bar = WelcomeBarShapeLayer(
unitRect: CGRectMake(0.593, 0.64, 0.039, 0.15),
referenceSize:self.frame.size,
transform: self.squashedHeightBarTransform
)
bar.fillColor = self.barOddColor
return bar
}()
lazy var dashedCircle: WelcomeCircleShapeLayer = {
return WelcomeCircleShapeLayer(
unitRadius: 0.258,
unitOrigin: CGPointMake(0.61, 0.44),
referenceSize: self.frame.size,
isDashed: true,
transform: self.wmf_scaleZeroTransform,
opacity:0.0
)
}()
lazy var solidCircle: WelcomeCircleShapeLayer = {
return WelcomeCircleShapeLayer(
unitRadius: 0.235,
unitOrigin: CGPointMake(0.654, 0.41),
referenceSize: self.frame.size,
isDashed: false,
transform: self.wmf_scaleZeroTransform,
opacity:0.0
)
}()
lazy var plus1: WelcomePlusShapeLayer = {
return WelcomePlusShapeLayer(
unitOrigin: CGPointMake(0.9, 0.222),
unitWidth: 0.05,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroTransform,
opacity: 0.0
)
}()
lazy var plus2: WelcomePlusShapeLayer = {
return WelcomePlusShapeLayer(
unitOrigin: CGPointMake(0.832, 0.167),
unitWidth: 0.05,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroTransform,
opacity: 0.0
)
}()
lazy var line1: WelcomeLineShapeLayer = {
return WelcomeLineShapeLayer(
unitOrigin: CGPointMake(0.82, 0.778),
unitWidth: 0.125,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroAndRightTransform,
opacity: 0.0
)
}()
lazy var line2: WelcomeLineShapeLayer = {
return WelcomeLineShapeLayer(
unitOrigin: CGPointMake(0.775, 0.736),
unitWidth: 0.127,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroAndRightTransform,
opacity: 0.0
)
}()
lazy var line3: WelcomeLineShapeLayer = {
return WelcomeLineShapeLayer(
unitOrigin: CGPointMake(0.233, 0.385),
unitWidth: 0.043,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroAndLeftTransform,
opacity: 0.0
)
}()
lazy var line4: WelcomeLineShapeLayer = {
return WelcomeLineShapeLayer(
unitOrigin: CGPointMake(0.17, 0.385),
unitWidth: 0.015,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroAndLeftTransform,
opacity: 0.0
)
}()
lazy var line5: WelcomeLineShapeLayer = {
return WelcomeLineShapeLayer(
unitOrigin: CGPointMake(0.11, 0.427),
unitWidth: 0.043,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroAndLeftTransform,
opacity: 0.0
)
}()
lazy var line6: WelcomeLineShapeLayer = {
return WelcomeLineShapeLayer(
unitOrigin: CGPointMake(0.173, 0.427),
unitWidth: 0.015,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroAndLeftTransform,
opacity: 0.0
)
}()
override public func addAnimationElementsScaledToCurrentFrameSize(){
removeExistingSubviewsAndSublayers()
self.addSubview(self.fileImgView)
_ = [
self.bar1,
self.bar2,
self.bar3,
self.bar4,
self.bar5
].map({ (layer: CALayer) -> () in
fileImgView.layer.addSublayer(layer)
})
_ = [
self.solidCircle,
self.dashedCircle,
self.plus1,
self.plus2,
self.line1,
self.line2,
self.line3,
self.line4,
self.line5,
self.line6
].map({ (layer: CALayer) -> () in
self.layer.addSublayer(layer)
})
}
override public func beginAnimations() {
CATransaction.begin()
fileImgView.layer.wmf_animateToOpacity(1.0,
transform: CATransform3DIdentity,
delay: 0.1,
duration: 1.0
)
self.solidCircle.wmf_animateToOpacity(0.04,
transform: CATransform3DIdentity,
delay: 0.3,
duration: 1.0
)
var barIndex = 0
let animateBarGrowingUp = { (layer: CALayer) -> () in
layer.wmf_animateToOpacity(1.0,
transform: self.fullHeightBarTransform,
delay: (0.3 + (Double(barIndex) * 0.1)),
duration: 0.3
)
barIndex+=1
}
_ = [
self.bar1,
self.bar2,
self.bar3,
self.bar4,
self.bar5
].map(animateBarGrowingUp)
let animate = { (layer: CALayer) -> () in
layer.wmf_animateToOpacity(0.15,
transform: CATransform3DIdentity,
delay: 0.3,
duration: 1.0
)
}
_ = [
self.dashedCircle,
self.plus1,
self.plus2,
self.line1,
self.line2,
self.line3,
self.line4,
self.line5,
self.line6
].map(animate)
CATransaction.commit()
}
}
| b9d9c319013ba305d922c56d346ed58d | 28.899628 | 92 | 0.545941 | false | false | false | false |
mirego/PinLayout | refs/heads/master | Example/PinLayoutSample/UI/Examples/IntroRTL/IntroRTLView.swift | mit | 1 | // Copyright (c) 2017 Luc Dion
// 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 PinLayout
class IntroRTLView: UIView {
private let logo = UIImageView(image: UIImage(named: "PinLayout-logo"))
private let segmented = UISegmentedControl(items: ["Intro", "1", "2"])
private let textLabel = UILabel()
private let separatorView = UIView()
init() {
super.init(frame: .zero)
backgroundColor = .white
// PinLayout will detect automatically the layout direction based on
// `UIView.userInterfaceLayoutDirection(for: semanticContentAttribute)` (>= iOS 9) or
// `UIApplication.shared.userInterfaceLayoutDirection` (< iOS 9)
Pin.layoutDirection(.auto)
logo.contentMode = .scaleAspectFit
addSubview(logo)
segmented.selectedSegmentIndex = 0
segmented.tintColor = .pinLayoutColor
addSubview(segmented)
if isLTR() {
textLabel.text = "Swift manual views layouting without auto layout, no magic, pure code, full control. Concise syntax, readable & chainable.\n\nSwift manual views layouting without auto layout, no magic, pure code, full control. Concise syntax, readable & chainable."
} else {
textLabel.text = "ان هذا وكسبت وقدّموا التاريخ،, قد مكن ووصف يعبأ واُسدل. لإنعدام الأبرياء أسر ان. فقد و أراض إتفاقية, حدى و غضون وبولندا الأوروبيّون, لم العصبة معاملة مما. بـ يكن أمّا واُسدل مهمّات. بأيدي الفرنسي بـ نفس, تصفح لفرنسا بها في. لان قد الأوروبي الأوروبية, قد جُل أحدث وحرمان اليميني."
}
textLabel.font = .systemFont(ofSize: 14)
textLabel.numberOfLines = 0
textLabel.lineBreakMode = .byWordWrapping
addSubview(textLabel)
separatorView.pin.height(1)
separatorView.backgroundColor = .pinLayoutColor
addSubview(separatorView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
Pin.layoutDirection(.ltr)
}
override func layoutSubviews() {
super.layoutSubviews()
let padding: CGFloat = 10
logo.pin.top(pin.safeArea).start(pin.safeArea).width(100).aspectRatio().margin(padding)
segmented.pin.after(of: logo, aligned: .top).end(pin.safeArea).marginHorizontal(padding)
textLabel.pin.below(of: segmented, aligned: .start).width(of: segmented).pinEdges().marginTop(10).sizeToFit(.width)
separatorView.pin.below(of: [logo, textLabel], aligned: .start).end(to: segmented.edge.end).marginTop(10)
}
}
| cd52362636fff16141e5b6d3180db512 | 45.628205 | 309 | 0.691229 | false | false | false | false |
ebaker355/IBOutletScanner | refs/heads/master | src/FileScanner.swift | mit | 1 | /*
MIT License
Copyright (c) 2017 DuneParkSoftware, 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.
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
enum FileScannerError: Error {
case noPath
case fileSystemError(path: String)
}
extension FileScannerError: CustomStringConvertible {
var description: String {
switch self {
case .noPath:
return "No search path specified"
case .fileSystemError(let path):
return "Can't access path: " + String(describing: path)
}
}
}
public struct FileScanner {
typealias FileScannerProcessor = (_ file: URL) throws -> Void
func processFiles(ofTypes fileTypes: [String], inPath path: String, _ processor: FileScannerProcessor) throws {
guard path.count > 0 else {
throw FileScannerError.noPath
}
guard let enumerator = FileManager.default.enumerator(atPath: path) else {
throw FileScannerError.fileSystemError(path: path)
}
let rootURL = URL(fileURLWithPath: path)
while let dir = enumerator.nextObject() as? String {
let fileURL = rootURL.appendingPathComponent(dir)
if fileTypes.contains(fileURL.pathExtension) {
try processor(fileURL)
}
}
}
}
| 26705b1dee02f27ad606ba108b234ae7 | 34.5 | 115 | 0.708187 | false | false | false | false |
algolia/algoliasearch-client-swift | refs/heads/master | Sources/AlgoliaSearchClient/Helpers/DisjunctiveFacetingHelper.swift | mit | 1 | //
// DisjunctiveFacetingHelper.swift
//
//
// Created by Vladislav Fitc on 19/10/2022.
//
import Foundation
/// Helper making multiple queries for disjunctive faceting
/// and merging the multiple search responses into a single one with
/// combined facets information
struct DisjunctiveFacetingHelper {
let query: Query
let refinements: [Attribute: [String]]
let disjunctiveFacets: Set<Attribute>
init(query: Query,
refinements: [Attribute: [String]],
disjunctiveFacets: Set<Attribute>) {
self.query = query
self.refinements = refinements
self.disjunctiveFacets = disjunctiveFacets
}
/// Build filters SQL string from the provided refinements and disjunctive facets set
func buildFilters(excluding excludedAttribute: Attribute?) -> String {
String(
refinements
.sorted(by: { $0.key.rawValue < $1.key.rawValue })
.filter { (name: Attribute, values: [String]) in
name != excludedAttribute && !values.isEmpty
}.map { (name: Attribute, values: [String]) in
let facetOperator = disjunctiveFacets.contains(name) ? " OR " : " AND "
let expression = values
.map { value in """
"\(name)":"\(value)"
"""
}
.joined(separator: facetOperator)
return "(\(expression))"
}.joined(separator: " AND ")
)
}
/// Get applied disjunctive facet values for provided attribute
func appliedDisjunctiveFacetValues(for attribute: Attribute) -> Set<String> {
guard disjunctiveFacets.contains(attribute) else {
return []
}
return refinements[attribute].flatMap(Set.init) ?? []
}
/// Build search queries to fetch the necessary facets information for disjunctive faceting
/// If the disjunctive facets set is empty, makes a single request with applied conjunctive filters
func makeQueries() -> [Query] {
var queries = [Query]()
var mainQuery = query
mainQuery.filters = buildFilters(excluding: .none)
queries.append(mainQuery)
disjunctiveFacets
.sorted(by: { $0.rawValue < $1.rawValue })
.forEach { disjunctiveFacet in
var disjunctiveQuery = query
disjunctiveQuery.facets = [disjunctiveFacet]
disjunctiveQuery.filters = buildFilters(excluding: disjunctiveFacet)
disjunctiveQuery.hitsPerPage = 0
disjunctiveQuery.attributesToRetrieve = []
disjunctiveQuery.attributesToHighlight = []
disjunctiveQuery.attributesToSnippet = []
disjunctiveQuery.analytics = false
queries.append(disjunctiveQuery)
}
return queries
}
/// Merge received search responses into single one with combined facets information
func mergeResponses(_ responses: [SearchResponse], keepSelectedEmptyFacets: Bool = true) throws -> SearchResponse {
guard var mainResponse = responses.first else {
throw DisjunctiveFacetingError.emptyResponses
}
let responsesForDisjunctiveFaceting = responses.dropFirst()
var mergedDisjunctiveFacets = [Attribute: [Facet]]()
var mergedFacetStats = mainResponse.facetStats ?? [:]
var mergedExhaustiveFacetsCount = mainResponse.exhaustiveFacetsCount ?? true
for result in responsesForDisjunctiveFaceting {
// Merge facet values
if let facetsPerAttribute = result.facets {
for (attribute, facets) in facetsPerAttribute {
// Complete facet values applied in the filters
// but missed in the search response
let missingFacets = appliedDisjunctiveFacetValues(for: attribute)
.subtracting(facets.map(\.value))
.map { Facet(value: $0, count: 0) }
mergedDisjunctiveFacets[attribute] = facets + missingFacets
}
}
// Merge facets stats
if let facetStats = result.facetStats {
mergedFacetStats.merge(facetStats) { _, last in last }
}
// If facet counts are not exhaustive, propagate this information to the main results.
// Because disjunctive queries are less restrictive than the main query, it can happen that the main query
// returns exhaustive facet counts, while the disjunctive queries do not.
if let exhaustiveFacetsCount = result.exhaustiveFacetsCount {
mergedExhaustiveFacetsCount = mergedExhaustiveFacetsCount && exhaustiveFacetsCount
}
}
mainResponse.disjunctiveFacets = mergedDisjunctiveFacets
mainResponse.facetStats = mergedFacetStats
mainResponse.exhaustiveFacetsCount = mergedExhaustiveFacetsCount
return mainResponse
}
}
public enum DisjunctiveFacetingError: LocalizedError {
case emptyResponses
var localizedDescription: String {
switch self {
case .emptyResponses:
return "Unexpected empty search responses list. At least one search responses might be present."
}
}
}
| cef8db361aa81ccf09efe4dd5c992025 | 34.087591 | 117 | 0.696276 | false | false | false | false |
steelwheels/Coconut | refs/heads/master | CoconutData/Source/Graphics/CNPoint.swift | lgpl-2.1 | 1 | /**
* @file CNPoint.swift
* @brief Extend CGPoint class
* @par Copyright
* Copyright (C) 2016-2021 Steel Wheels Project
*/
import CoreGraphics
import Foundation
public extension CGPoint
{
static let ClassName = "point"
static func fromValue(value val: CNValue) -> CGPoint? {
if let dict = val.toDictionary() {
return fromValue(value: dict)
} else {
return nil
}
}
static func fromValue(value val: Dictionary<String, CNValue>) -> CGPoint? {
if let xval = val["x"], let yval = val["y"] {
if let xnum = xval.toNumber(), let ynum = yval.toNumber() {
let x:CGFloat = CGFloat(xnum.floatValue)
let y:CGFloat = CGFloat(ynum.floatValue)
return CGPoint(x: x, y: y)
}
}
return nil
}
func toValue() -> Dictionary<String, CNValue> {
let xnum = NSNumber(floatLiteral: Double(self.x))
let ynum = NSNumber(floatLiteral: Double(self.y))
let result: Dictionary<String, CNValue> = [
"class" : .stringValue(CGPoint.ClassName),
"x" : .numberValue(xnum),
"y" : .numberValue(ynum)
]
return result
}
func moving(dx x: CGFloat, dy y: CGFloat) -> CGPoint {
let newx = self.x + x
let newy = self.y + y
return CGPoint(x: newx, y: newy)
}
func subtracting(_ p: CGPoint) -> CGPoint {
return CGPoint(x: self.x - p.x, y: self.y - p.y)
}
var description: String {
get {
let xstr = NSString(format: "%.2lf", Double(self.x))
let ystr = NSString(format: "%.2lf", Double(self.y))
return "{x:\(xstr), y:\(ystr)}"
}
}
static func center(_ pt0: CGPoint, _ pt1: CGPoint) -> CGPoint {
let x = (pt0.x + pt1.x) / 2.0
let y = (pt0.y + pt1.y) / 2.0
return CGPoint(x: x, y: y)
}
}
| 0e24e326c729bfe9c1c09731f30f710d | 22.671429 | 76 | 0.627037 | false | false | false | false |
HasanEdain/NPCColorPicker | refs/heads/master | NPCColorPicker/NPCColorUtility.swift | mit | 1 | //
// NPCColorUtility.swift
// NPCColorPicker
//
// Created by Hasan D Edain and Andrew Bush on 12/6/15.
// Copyright © 2015-2017 NPC Unlimited. All rights reserved.
//
import UIKit
open class NPCColorUtility {
open static func colorWithRGBA(_ rgbaString: String)->UIColor {
let colorString = cleanRGBAString(rgbaString)
if colorString.length != 6 && colorString.length != 8 {
return UIColor.white
}
let redPercent = NPCColorUtility.redPercentForRGBAString(colorString)
let greenPercent = NPCColorUtility.greenPercentForRGBAString(colorString)
let bluePercent = NPCColorUtility.bluePercentForRGBAString(colorString)
let alphaPercent = NPCColorUtility.alphaPercentForRGBAString(colorString)
let color = UIColor(red: redPercent, green: greenPercent, blue: bluePercent, alpha: alphaPercent)
return color
}
open static func colorWithHex(_ hexString: String)->UIColor {
let colorString = cleanHexString(hexString)
if colorString.length != 6 && colorString.length != 8 {
return UIColor.white
}
let alphaPercent:CGFloat = NPCColorUtility.alphaPercentForHexString(colorString)
let redPercent = NPCColorUtility.redPercentForHexString(colorString)
let greenPercent = NPCColorUtility.greenPercentForHexString(colorString)
let bluePercent = NPCColorUtility.bluePercentForHexString(colorString)
let color = UIColor(red: redPercent, green: greenPercent, blue: bluePercent, alpha: alphaPercent)
return color
}
// MARK: - RGBA methods
static func cleanRGBAString(_ rgbaString: String) -> NSString {
var cString:NSString = rgbaString.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased() as NSString
if cString.length != 6 && cString.length != 8 {
cString = "";
}
return cString
}
open static func redPercentForRGBAString(_ colorString: NSString) -> CGFloat {
let redString = colorString.substring(to: 2)
let redPercent = NPCColorUtility.rgbaPercentForString(redString)
return redPercent
}
open static func greenPercentForRGBAString(_ colorString: NSString) -> CGFloat {
let greenRange = NSMakeRange(2, 2)
let greenString = colorString.substring(with: greenRange)
let greenPercent = NPCColorUtility.rgbaPercentForString(greenString)
return greenPercent
}
open static func bluePercentForRGBAString(_ colorString: NSString) -> CGFloat {
let blueRange = NSMakeRange(4, 2)
let blueString = colorString.substring(with: blueRange)
let bluePercent = NPCColorUtility.rgbaPercentForString(blueString)
return bluePercent
}
open static func alphaPercentForRGBAString(_ colorString: NSString) -> CGFloat {
var alphaPercent:CGFloat = 1.0
if colorString.length == 8 {
let alphaRange = NSMakeRange(6, 2)
let alphaString = colorString.substring(with: alphaRange)
alphaPercent = NPCColorUtility.rgbaPercentForString(alphaString)
}
return alphaPercent
}
open static func rgbaPercentForString(_ string: String)->CGFloat {
var percentNumerator:Int = 0
Scanner(string: string).scanInt(&percentNumerator)
let percent = CGFloat(percentNumerator) / CGFloat(255.0)
return percent
}
// MARK: - Hex methods
static func cleanHexString(_ hexString: String) -> NSString {
var cString:NSString = hexString.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased() as NSString
if (cString.hasPrefix("#")) {
cString = cString.substring(from: 1) as NSString
}
if cString.length != 6 && cString.length != 8 {
cString = "";
}
return cString
}
open static func redPercentForHexString(_ colorString: NSString) -> CGFloat {
let redString = colorString.substring(to: 2)
let redPercent = NPCColorUtility.hexPercentForString(redString)
return redPercent
}
open static func greenPercentForHexString(_ colorString: NSString) -> CGFloat {
let greenRange = NSMakeRange(2, 2)
let greenString = colorString.substring(with: greenRange)
let greenPercent = NPCColorUtility.hexPercentForString(greenString)
return greenPercent
}
open static func bluePercentForHexString(_ colorString: NSString) -> CGFloat {
let blueRange = NSMakeRange(4, 2)
let blueString = colorString.substring(with: blueRange)
let bluePercent = NPCColorUtility.hexPercentForString(blueString)
return bluePercent
}
open static func alphaPercentForHexString(_ colorString: NSString) -> CGFloat {
var alphaPercent:CGFloat = 1.0
if colorString.length == 8 {
let alphaRange = NSMakeRange(6, 2)
let alphaString = colorString.substring(with: alphaRange)
alphaPercent = NPCColorUtility.hexPercentForString(alphaString)
}
return alphaPercent
}
open static func hexPercentForString(_ string: String)->CGFloat {
var percentNumerator:CUnsignedInt = 0
Scanner(string: string).scanHexInt32(&percentNumerator)
let percent = CGFloat(percentNumerator) / CGFloat(255.0)
return percent
}
}
| 0545dd09ee1c70b075ca1189559ce94a | 31.795181 | 128 | 0.679096 | false | false | false | false |
slimane-swift/WS | refs/heads/master | Tests/WebSocketTests/WebSocketTests.swift | mit | 1 | import XCTest
@testable import WebSocket
class WebSocketTests: XCTestCase {
func testReality() {
XCTAssert(2 + 2 == 4, "Something is severely wrong here.")
}
}
extension WebSocketTests {
<<<<<<< HEAD
static var allTests: [(String, WebSocketTests -> () throws -> Void)] {
=======
static var allTests: [(String, (WebSocketTests) -> () throws -> Void)] {
>>>>>>> upstream/master
return [
("testReality", testReality),
]
}
}
| 37c131957b93ad693a38c8a338d92a7c | 22.9 | 76 | 0.589958 | false | true | false | false |
Friend-LGA/LGSideMenuController | refs/heads/master | LGSideMenuController/Extensions/Validators/LGSideMenuController+ValidatingViewsVisibility.swift | mit | 1 | //
// LGSideMenuController+ValidatingViewsVisibility.swift
// LGSideMenuController
//
//
// The MIT License (MIT)
//
// Copyright © 2015 Grigorii Lutkov <[email protected]>
// (https://github.com/Friend-LGA/LGSideMenuController)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import UIKit
internal extension LGSideMenuController {
func validateViewsVisibility() {
self.validateRootViewsVisibility()
self.validateLeftViewsVisibility()
self.validateRightViewsVisibility()
}
func validateRootViewsVisibility() {
guard self.shouldUpdateVisibility == true,
let backgroundDecorationView = self.rootViewBackgroundDecorationView,
let coverView = self.rootViewCoverView else { return }
backgroundDecorationView.isHidden = self.isRootViewShowing && !self.isLeftViewAlwaysVisible && !self.isRightViewAlwaysVisible
coverView.isHidden = self.isRootViewShowing
}
func validateLeftViewsVisibility() {
guard self.shouldUpdateVisibility == true,
let containerView = self.leftContainerView,
let coverView = self.leftViewCoverView,
let statusBarBackgroundView = self.leftViewStatusBarBackgroundView else { return }
containerView.isHidden = !self.isLeftViewVisibleToUser
coverView.isHidden = self.isLeftViewShowing || (self.isLeftViewAlwaysVisible && !self.isRightViewVisible)
statusBarBackgroundView.isHidden =
self.isLeftViewStatusBarBackgroundHidden ||
self.isLeftViewStatusBarHidden ||
self.isNavigationBarVisible() ||
!self.isViewLocatedUnderStatusBar
}
func validateRightViewsVisibility() {
guard self.shouldUpdateVisibility == true,
let containerView = self.rightContainerView,
let coverView = self.rightViewCoverView,
let statusBarBackgroundView = self.rightViewStatusBarBackgroundView else { return }
containerView.isHidden = !self.isRightViewVisibleToUser
coverView.isHidden = self.isRightViewShowing || (self.isRightViewAlwaysVisible && !self.isLeftViewVisible)
statusBarBackgroundView.isHidden =
self.isRightViewStatusBarBackgroundHidden ||
self.isRightViewStatusBarHidden ||
self.isNavigationBarVisible() ||
!self.isViewLocatedUnderStatusBar
}
private func isNavigationBarVisible() -> Bool {
guard let navigationController = navigationController else { return false }
return !navigationController.isNavigationBarHidden
}
}
| d2c93a519ab1810a10934422f59aeda6 | 41.264368 | 133 | 0.721512 | false | false | false | false |
csnu17/My-Swift-learning | refs/heads/master | Love In A Snap/Love In A Snap Starter/Love In A Snap/ViewController.swift | mit | 1 | /// Copyright (c) 2019 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 MobileCoreServices
import TesseractOCR
import GPUImage
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
}
// IBAction methods
@IBAction func backgroundTapped(_ sender: Any) {
view.endEditing(true)
}
@IBAction func takePhoto(_ sender: Any) {
let imagePickerActionSheet = UIAlertController(title: "Snap/Upload Image", message: nil, preferredStyle: .actionSheet)
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let cameraButton = UIAlertAction(title: "Take Photo", style: .default) { (alert) in
self.activityIndicator.startAnimating()
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.mediaTypes = [kUTTypeImage as String]
self.present(imagePicker, animated: true, completion: {
self.activityIndicator.stopAnimating()
})
}
imagePickerActionSheet.addAction(cameraButton)
}
let libraryButton = UIAlertAction(title: "Choose Existing", style: .default) { (alert) in
self.activityIndicator.startAnimating()
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
self.present(imagePicker, animated: true, completion: {
self.activityIndicator.stopAnimating()
})
}
imagePickerActionSheet.addAction(libraryButton)
let cancelButton = UIAlertAction(title: "Cancel", style: .cancel)
imagePickerActionSheet.addAction(cancelButton)
present(imagePickerActionSheet, animated: true)
}
// Tesseract Image Recognition
func performImageRecognition(_ image: UIImage) {
if let tesseract = G8Tesseract(language: "eng+fra") {
tesseract.engineMode = .tesseractCubeCombined
tesseract.pageSegmentationMode = .auto
let scaledImage = image.scaledImage(1000) ?? image
let preprocessedImage = scaledImage.preprocessedImage() ?? scaledImage
tesseract.image = preprocessedImage
tesseract.recognize()
textView.text = tesseract.recognizedText
}
activityIndicator.stopAnimating()
}
}
// MARK: - UINavigationControllerDelegate
extension ViewController: UINavigationControllerDelegate {
}
// MARK: - UIImagePickerControllerDelegate
extension ViewController: UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let selectedPhoto = info[.originalImage] as? UIImage else {
dismiss(animated: true)
return
}
activityIndicator.startAnimating()
dismiss(animated: true) {
self.performImageRecognition(selectedPhoto)
}
}
}
// MARK: - UIImage extension
extension UIImage {
func scaledImage(_ maxDimension: CGFloat) -> UIImage? {
var scaledSize = CGSize(width: maxDimension, height: maxDimension)
if size.width > size.height {
scaledSize.height = size.height / size.width * scaledSize.width
} else {
scaledSize.width = size.width / size.height * scaledSize.height
}
UIGraphicsBeginImageContext(scaledSize)
draw(in: CGRect(origin: .zero, size: scaledSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
func preprocessedImage() -> UIImage? {
let stillImageFilter = GPUImageAdaptiveThresholdFilter()
stillImageFilter.blurRadiusInPixels = 15.0
let filteredImage = stillImageFilter.image(byFilteringImage: self)
return filteredImage
}
}
| cbb39b0cb33f2e9888eca4ccefcbe4ad | 41.442857 | 126 | 0.680242 | false | false | false | false |
Benoitcn/Upli | refs/heads/master | Upli/Upli/Session.swift | apache-2.0 | 1 | //
// Session.swift
// Upli
//
// Created by 王毅 on 15/5/11.
// Copyright (c) 2015年 Ted. All rights reserved.
//
import UIKit
class Session {
var title: String
var titleico:UIImage
class func allSessions() -> [Session] {
var sessions = [Session]()
if let URL = NSBundle.mainBundle().URLForResource("Sessions", withExtension: "plist") {
if let sessionsFromPlist = NSArray(contentsOfURL: URL) {
for dictionary in sessionsFromPlist {
let session = Session(dictionary: dictionary as! NSDictionary)
sessions.append(session)
}
}
}
return sessions
}
init(title: String,titleico:UIImage) {
self.title = title
self.titleico=titleico
//self.speaker = speaker
//self.room = room
//self.time = time
}
convenience init(dictionary: NSDictionary) {
let title = dictionary["Title"] as? String
let _titleico=dictionary["Ico"]as? String
let titleico=UIImage(named: _titleico!)?.decompressedImage
//let speaker//dictionary["Speaker"] as? String
//let room //'dictionary["Room"] as? String
//let time //'dictionary["Time"] as? String
self.init(title: title!,titleico:titleico!)
}
}
| 32513fc9ed80f8fdfe22fe8cc683c035 | 27.104167 | 95 | 0.577465 | false | false | false | false |
diatrevolo/GameplaykitPDA | refs/heads/master | GameplaykitPDA/GameplaykitPDA_iosTests/GameplaykitPDA_iosTests.swift | apache-2.0 | 1 | //
// GameplaykitPDATests.swift
// GameplaykitPDATests
//
// Created by Roberto Osorio Goenaga on 8/13/15.
// Copyright © 2015 Roberto Osorio Goenaga. All rights reserved.
//
import XCTest
class GameplaykitPDA_iosTests: XCTestCase {
var pushdownAutomaton: PushdownAutomaton?
override func setUp() {
super.setUp()
self.pushdownAutomaton = PushdownAutomaton(states: [OneState(), TwoState()], firstElement: StackElement())
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testStack() {
let currentElement = self.pushdownAutomaton!.currentElement
self.pushdownAutomaton?.pushToStack(currentElement!)
self.pushdownAutomaton?.enterState(TwoState)
XCTAssertTrue(currentElement?.currentState != self.pushdownAutomaton?.currentElement?.currentState)
self.pushdownAutomaton?.popAndPush()
XCTAssertTrue(currentElement?.currentState == self.pushdownAutomaton?.currentElement?.currentState)
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| c9a97baf0526d65068f199d90eca9ef9 | 31.634146 | 114 | 0.680867 | false | true | false | false |
Jerry0523/JWIntent | refs/heads/master | IntentDemo/ModalViewController.swift | mit | 1 | //
// ModalViewController.swift
// JWIntentDemo
//
// Created by Jerry on 2017/11/8.
// Copyright © 2017年 Jerry Wong. All rights reserved.
//
import UIKit
import Intent
class ModalViewController: UIViewController, AssociatedTransitionDataSource {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if presentTransition != nil {
let ges = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
imageView.addGestureRecognizer(ges)
}
}
func manipulateAssociatedFromView(with work: (UIView) -> ()) {
guard let associatedTransition = (presentTransition as? AssociatedTransition) else {
return
}
associatedTransition.associatedFromViews.forEach {
work($0)
}
}
@objc private func handlePanGesture(_ sender: UIPanGestureRecognizer) {
let point = sender.translation(in: view)
let progress = 2.0 * CGFloat(fabsf(Float(point.y))) / view.bounds.height
let percent = 1 - progress
switch sender.state {
case .began:
manipulateAssociatedFromView {
$0.isHidden = true
}
case .changed:
imageView.transform = CGAffineTransform(translationX: point.x, y: point.y).scaledBy(x: max(0.5, percent), y: max(0.5, percent))
view.backgroundColor = UIColor.white.withAlphaComponent(percent)
titleLabel.alpha = percent
default:
manipulateAssociatedFromView {
$0.isHidden = true
}
if progress > 0.3 {
dismiss(animated: true)
} else {
UIView.animate(withDuration: 0.25) {
self.imageView.transform = .identity
self.view.backgroundColor = .white
self.titleLabel.alpha = 1.0
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc func viewsForTransition() -> [UIView]? {
return [imageView]
}
}
| a428a0b8b3b6f5764a09146f67f3f2e2 | 29.972222 | 140 | 0.585202 | false | false | false | false |
jberkman/Balsa | refs/heads/master | Balsa/Balsa.swift | mit | 1 | //
// Balsa.swift
// Balsa
//
// Created by jacob berkman on 2015-10-02.
// Copyright © 2015 jacob berkman. All rights reserved.
//
import CoreData
import Foundation
public let errorDomain = "Balsa.errorDomain"
public let entityNotFoundError = 1
public protocol ModelNaming {
static var modelName: String { get }
}
public protocol ModelControlling {
typealias Model
var model: Model? { get }
}
public protocol MutableModelControlling: ModelControlling {
typealias Model
var model: Model? { get set }
}
public protocol ModelSelecting {
typealias Model
var selectedModel: Model? { get }
}
public protocol MutableModelSelecting: ModelSelecting {
var selectedModel: Model? { get set }
}
public protocol ModelMultipleSelecting {
typealias Model: Hashable
var maximumSelectionCount: Int { get }
var selectedModels: Set<Model> { get }
}
public protocol MutableModelMultipleSelecting: ModelMultipleSelecting {
var maximumSelectionCount: Int { get set }
var selectedModels: Set<Model> { get set }
}
public protocol Predicating {
var predicate: NSPredicate? { get set }
}
public protocol MutablePredicating: Predicating {
var predicate: NSPredicate? { get set }
}
extension ModelNaming {
public var modelName: String { return self.dynamicType.modelName }
}
extension ModelNaming where Self: NSManagedObject {
public init(insertIntoManagedObjectContext managedObjectContext: NSManagedObjectContext) throws {
guard let entity = NSEntityDescription.entityForName(Self.modelName, inManagedObjectContext: managedObjectContext) else {
throw NSError(domain: errorDomain, code: entityNotFoundError, userInfo: nil)
}
self.init(entity: entity, insertIntoManagedObjectContext: managedObjectContext)
}
public static func countInContext(managedObjectContext: NSManagedObjectContext, predicate: NSPredicate? = nil) -> Int {
let fetchRequest = NSFetchRequest(entityName: modelName)
fetchRequest.predicate = predicate
let result = managedObjectContext.countForFetchRequest(fetchRequest, error: nil)
return result == NSNotFound ? 0 : result
}
public static func existsInContext(managedObjectContext: NSManagedObjectContext, predicate: NSPredicate? = nil) -> Bool {
return countInContext(managedObjectContext, predicate: predicate) > 1
}
}
| 8b7953cdde57d691842c9d98126982e5 | 28.292683 | 129 | 0.737302 | false | false | false | false |
Kratos28/KPageView | refs/heads/master | KPageViewSwift/KPageView/HYPageView/KPageStyle.swift | mit | 1 | //
// KPageStyle.swift
// KPageView
//
// Created by Kratos on 17/4/8.
// Copyright © 2017年 Kratos. All rights reserved.
// NSObject --> KVC
import UIKit
class KPageStyle {
// 是否可以滚动
var isScrollEnable : Bool = false
// Label的一些属性
var titleHeight : CGFloat = 44
var normalColor : UIColor = UIColor.white
var selectColor : UIColor = UIColor.orange
var fontSize : CGFloat = 15
var titleMargin : CGFloat = 30
// 是否显示滚动条
var isShowBottomLine : Bool = false
var bottomLineColor : UIColor = UIColor.orange
var bottomLineHeight : CGFloat = 2
// 是否需要缩放功能
var isScaleEnable : Bool = false
var maxScale : CGFloat = 1.2
// 是否需要显示的coverView
var isShowCoverView : Bool = false
var coverBgColor : UIColor = UIColor.black
var coverAlpha : CGFloat = 0.4
var coverMargin : CGFloat = 8
var coverHeight : CGFloat = 25
var coverRadius : CGFloat = 12
// pageControl的高度
var pageControlHeight : CGFloat = 20
}
| 8936e7719069e9115a12e0a4bed6e3ec | 22.837209 | 50 | 0.640976 | false | false | false | false |
roecrew/AudioKit | refs/heads/master | AudioKit/Common/Nodes/Generators/Oscillators/Oscillator/AKOscillator.swift | mit | 1 | //
// AKOscillator.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// Reads from the table sequentially and repeatedly at given frequency. Linear
/// interpolation is applied for table look up from internal phase values.
///
/// - Parameters:
/// - frequency: Frequency in cycles per second
/// - amplitude: Output Amplitude.
/// - detuningOffset: Frequency offset in Hz.
/// - detuningMultiplier: Frequency detuning multiplier
///
public class AKOscillator: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKOscillatorAudioUnit?
internal var token: AUParameterObserverToken?
private var waveform: AKTable?
private var frequencyParameter: AUParameter?
private var amplitudeParameter: AUParameter?
private var detuningOffsetParameter: AUParameter?
private var detuningMultiplierParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// In cycles per second, or Hz.
public var frequency: Double = 440 {
willSet {
if frequency != newValue {
if internalAU!.isSetUp() {
frequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.frequency = Float(newValue)
}
}
}
}
/// Output Amplitude.
public var amplitude: Double = 1 {
willSet {
if amplitude != newValue {
if internalAU!.isSetUp() {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.amplitude = Float(newValue)
}
}
}
}
/// Frequency offset in Hz.
public var detuningOffset: Double = 0 {
willSet {
if detuningOffset != newValue {
if internalAU!.isSetUp() {
detuningOffsetParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.detuningOffset = Float(newValue)
}
}
}
}
/// Frequency detuning multiplier
public var detuningMultiplier: Double = 1 {
willSet {
if detuningMultiplier != newValue {
if internalAU!.isSetUp() {
detuningMultiplierParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.detuningMultiplier = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize the oscillator with defaults
public convenience override init() {
self.init(waveform: AKTable(.Sine))
}
/// Initialize this oscillator node
///
/// - Parameters:
/// - waveform: The waveform of oscillation
/// - frequency: Frequency in cycles per second
/// - amplitude: Output Amplitude.
/// - detuningOffset: Frequency offset in Hz.
/// - detuningMultiplier: Frequency detuning multiplier
///
public init(
waveform: AKTable,
frequency: Double = 440,
amplitude: Double = 1,
detuningOffset: Double = 0,
detuningMultiplier: Double = 1) {
self.waveform = waveform
self.frequency = frequency
self.amplitude = amplitude
self.detuningOffset = detuningOffset
self.detuningMultiplier = detuningMultiplier
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = fourCC("oscl")
description.componentManufacturer = fourCC("AuKt")
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKOscillatorAudioUnit.self,
asComponentDescription: description,
name: "Local AKOscillator",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKOscillatorAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
self.internalAU?.setupWaveform(Int32(waveform.size))
for i in 0 ..< waveform.size {
self.internalAU?.setWaveformValue(waveform.values[i], atIndex: UInt32(i))
}
}
guard let tree = internalAU?.parameterTree else { return }
frequencyParameter = tree.valueForKey("frequency") as? AUParameter
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
detuningOffsetParameter = tree.valueForKey("detuningOffset") as? AUParameter
detuningMultiplierParameter = tree.valueForKey("detuningMultiplier") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.frequencyParameter!.address {
self.frequency = Double(value)
} else if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
} else if address == self.detuningOffsetParameter!.address {
self.detuningOffset = Double(value)
} else if address == self.detuningMultiplierParameter!.address {
self.detuningMultiplier = Double(value)
}
}
}
internalAU?.frequency = Float(frequency)
internalAU?.amplitude = Float(amplitude)
internalAU?.detuningOffset = Float(detuningOffset)
internalAU?.detuningMultiplier = Float(detuningMultiplier)
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| d2530ee48b81a768e206b92888ac5238 | 33.454545 | 94 | 0.601143 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | Riot/Modules/Room/TimelineCells/RoomCreationIntro/RoomCreationIntroCell.swift | apache-2.0 | 1 | //
// Copyright 2020 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
@objcMembers
class RoomCreationIntroCell: MXKRoomBubbleTableViewCell {
// MARK: - Constants
private enum Sizing {
static var sizes = Set<SizingViewHeight>()
static let view: RoomCreationIntroCell = RoomCreationIntroCell(style: .default, reuseIdentifier: nil)
}
static let tapOnAvatarView = "RoomCreationIntroCellTapOnAvatarView"
static let tapOnAddTopic = "RoomCreationIntroCellTapOnAddTopic"
static let tapOnAddParticipants = "RoomCreationIntroCellTapOnAddParticipants"
// MARK: - Properties
private weak var roomCellContentView: RoomCreationIntroCellContentView?
// MARK: - Setup
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func commonInit() {
self.selectionStyle = .none
self.setupContentView()
self.update(theme: ThemeService.shared().theme)
super.setupViews()
}
// MARK: - Public
func update(theme: Theme) {
self.roomCellContentView?.update(theme: theme)
}
// MARK: - Overrides
override class func defaultReuseIdentifier() -> String! {
return String(describing: self)
}
override class func height(for cellData: MXKCellData!, withMaximumWidth maxWidth: CGFloat) -> CGFloat {
guard let cellData = cellData else {
return 0
}
guard let roomBubbleCellData = cellData as? MXKRoomBubbleCellData else {
return 0
}
let height: CGFloat
let sizingViewHeight = self.findOrCreateSizingViewHeight(from: roomBubbleCellData)
if let cachedHeight = sizingViewHeight.heights[maxWidth] {
height = cachedHeight
} else {
height = self.contentViewHeight(for: roomBubbleCellData, fitting: maxWidth)
sizingViewHeight.heights[maxWidth] = height
}
return height
}
override func render(_ cellData: MXKCellData!) {
super.render(cellData)
guard let roomCellContentView = self.roomCellContentView else {
MXLog.debug("[RoomCreationIntroCell] Fail to load content view")
return
}
guard let bubbleData = self.bubbleData,
let viewData = self.viewData(from: bubbleData) else {
MXLog.debug("[RoomCreationIntroCell] Fail to render \(String(describing: cellData))")
return
}
roomCellContentView.fill(with: viewData)
}
// MARK: - Private
private static func findOrCreateSizingViewHeight(from bubbleData: MXKRoomBubbleCellData) -> SizingViewHeight {
let sizingViewHeight: SizingViewHeight
let bubbleDataHashValue = bubbleData.hashValue
if let foundSizingViewHeight = self.Sizing.sizes.first(where: { (sizingViewHeight) -> Bool in
return sizingViewHeight.uniqueIdentifier == bubbleDataHashValue
}) {
sizingViewHeight = foundSizingViewHeight
} else {
sizingViewHeight = SizingViewHeight(uniqueIdentifier: bubbleDataHashValue)
}
return sizingViewHeight
}
private class func sizingView() -> RoomCreationIntroCell {
return self.Sizing.view
}
private static func contentViewHeight(for cellData: MXKCellData, fitting width: CGFloat) -> CGFloat {
let sizingView = self.sizingView()
sizingView.render(cellData)
sizingView.layoutIfNeeded()
let fittingSize = CGSize(width: width, height: UIView.layoutFittingCompressedSize.height)
return sizingView.systemLayoutSizeFitting(fittingSize).height
}
private func setupContentView() {
guard self.roomCellContentView == nil else {
return
}
let roomCellContentView = RoomCreationIntroCellContentView.instantiate()
self.contentView.vc_addSubViewMatchingParent(roomCellContentView)
self.roomCellContentView = roomCellContentView
roomCellContentView.roomAvatarView?.action = { [weak self] in
self?.notifyDelegate(with: RoomCreationIntroCell.tapOnAvatarView)
}
roomCellContentView.didTapTopic = { [weak self] in
self?.notifyDelegate(with: RoomCreationIntroCell.tapOnAddTopic)
}
roomCellContentView.didTapAddParticipants = { [weak self] in
self?.notifyDelegate(with: RoomCreationIntroCell.tapOnAddParticipants)
}
}
private func viewData(from bubbleData: MXKRoomBubbleCellData) -> RoomCreationIntroViewData? {
guard let session = bubbleData.mxSession, let roomId = bubbleData.roomId, let room = session.room(withRoomId: roomId) else {
return nil
}
guard let roomSummary = room.summary else {
return nil
}
let discussionType: DiscussionType
if roomSummary.isDirect {
if roomSummary.membersCount.members > 2 {
discussionType = .directMessage
} else {
discussionType = .multipleDirectMessage
}
} else {
discussionType = .room(topic: roomSummary.topic)
}
let displayName = roomSummary.displayname ?? ""
let roomAvatarViewData = RoomAvatarViewData(roomId: roomId,
displayName: displayName,
avatarUrl: room.summary.avatar, mediaManager: session.mediaManager)
return RoomCreationIntroViewData(dicussionType: discussionType, roomDisplayName: displayName, avatarViewData: roomAvatarViewData)
}
private func notifyDelegate(with actionIdentifier: String) {
self.delegate.cell(self, didRecognizeAction: actionIdentifier, userInfo: nil)
}
}
| c7a13da0bf51b38980580733e88e8b0d | 33.658291 | 137 | 0.634769 | false | false | false | false |
dasdom/DHTweak | refs/heads/master | Tweaks/ShakeableWindow.swift | mit | 2 | //
// ShakeableWindow.swift
// TweaksDemo
//
// Created by dasdom on 29.09.14.
// Copyright (c) 2014 Dominik Hauser. All rights reserved.
//
import UIKit
public class ShakeableWindow: UIWindow {
var isShaking = false
override public func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {
if motion == UIEventSubtype.MotionShake {
isShaking = true
let sec = 0.4 * Float(NSEC_PER_SEC)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(sec)), dispatch_get_main_queue(), {
if self.shouldPresentTweaksController() {
self.presentTweaks()
}
})
}
}
override public func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
isShaking = false
}
func shouldPresentTweaksController() -> Bool {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return true
#else
return self.isShaking && UIApplication.sharedApplication().applicationState == .Active
#endif
}
func presentTweaks() {
var visibleViewController = self.rootViewController
while let presentingViewController = visibleViewController?.presentingViewController {
visibleViewController = presentingViewController
}
if (visibleViewController is CategoriesTableViewController) == false {
visibleViewController?.presentViewController(UINavigationController(rootViewController: CategoriesTableViewController()), animated: true, completion: nil)
}
}
}
| 087e1f4ca3d864880b4d397e0577ea18 | 32.102041 | 166 | 0.636868 | false | false | false | false |
Constantine-Fry/wunderlist.swift | refs/heads/master | Source/Shared/Endpoints/Files.swift | bsd-2-clause | 1 | //
// Files.swift
// Wunderlist
//
// Created by Constantine Fry on 05/12/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
/**
Represents Files endpoint on Wunderilst.
https://developer.wunderlist.com/documentation/endpoints/file
*/
public class Files: Endpoint {
override var endpoint: String {
return "files"
}
public func getFilesForList(listId: Int,
completionHandler: (files: [File]?, error: NSError?) -> Void) -> SessionTask {
var parameters = [
"list_id" : listId,
] as [String: AnyObject]
return taskWithPath(nil, parameters: parameters, HTTPMethod: "GET", transformClosure: { File(JSON: $0) }) {
(result, error) -> Void in
completionHandler(files: result as [File]?, error: error)
}
}
public func getFilesForTask(taskId: Int,
completionHandler: (files: [File]?, error: NSError?) -> Void) -> SessionTask {
var parameters = [
"task_id" : taskId,
] as [String: AnyObject]
return taskWithPath(nil, parameters: parameters, HTTPMethod: "GET", transformClosure: { File(JSON: $0) }) {
(result, error) -> Void in
completionHandler(files: result as [File]?, error: error)
}
}
public func getFile(fileId: Int,
completionHandler: (file: File?, error: NSError?) -> Void) -> SessionTask {
let path = String(fileId)
return taskWithPath(path, parameters: nil, HTTPMethod: "GET", transformClosure: { File(JSON: $0) }) {
(result, error) -> Void in
completionHandler(file: result as File?, error: error)
}
}
public func createFile(uploadId: Int, taskId: Int, creationDate:NSDate?,
completionHandler: (file: File?, error: NSError?) -> Void) -> SessionTask {
var parameters = [
"upload_id" : uploadId,
"task_id" : taskId
] as [String: AnyObject]
if creationDate != nil {
parameters["local_created_at"] = creationDate
}
return taskWithPath(nil, parameters: parameters, HTTPMethod: "POST", transformClosure: { File(JSON: $0) }) {
(result, error) -> Void in
completionHandler(file: result as File?, error: error)
}
}
public func deleteFile(fileId: Int, revision: Int,
completionHandler: (result: Bool, error: NSError?) -> Void) -> SessionTask {
var parameters = [
"revision" : String(revision),
] as [String: AnyObject]
let path = String(fileId)
return taskWithPath(path, parameters: parameters, HTTPMethod: "DELETE", transformClosure: nil) {
(result, error) -> Void in
completionHandler(result: error == nil, error: error)
}
}
}
| 9b182e4795892be354ff1a14519cf7da | 34.841463 | 116 | 0.574685 | false | false | false | false |
Crowdmix/Buildasaur | refs/heads/master | Buildasaur/StatusProjectViewController.swift | mit | 2 | //
// StatusProjectViewController.swift
// Buildasaur
//
// Created by Honza Dvorsky on 07/03/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import AppKit
import BuildaUtils
import XcodeServerSDK
import BuildaKit
let kBuildTemplateAddNewString = "Create New..."
class StatusProjectViewController: StatusViewController, NSComboBoxDelegate, SetupViewControllerDelegate {
//no project yet
@IBOutlet weak var addProjectButton: NSButton!
//we have a project
@IBOutlet weak var statusContentView: NSView!
@IBOutlet weak var projectNameLabel: NSTextField!
@IBOutlet weak var projectPathLabel: NSTextField!
@IBOutlet weak var projectURLLabel: NSTextField!
@IBOutlet weak var buildTemplateComboBox: NSComboBox!
@IBOutlet weak var selectSSHPrivateKeyButton: NSButton!
@IBOutlet weak var selectSSHPublicKeyButton: NSButton!
@IBOutlet weak var sshPassphraseTextField: NSSecureTextField!
//GitHub.com: Settings -> Applications -> Personal access tokens - create one for Buildasaur and put it in this text field
@IBOutlet weak var tokenTextField: NSTextField!
override func availabilityChanged(state: AvailabilityCheckState) {
if let project = self.project() {
project.availabilityState = state
}
super.availabilityChanged(state)
}
override func viewWillAppear() {
super.viewWillAppear()
self.buildTemplateComboBox.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
self.tokenTextField.delegate = self
self.lastAvailabilityCheckStatus = .Unchecked
}
func project() -> Project? {
return self.storageManager.projects.first
}
func buildTemplates() -> [BuildTemplate] {
return self.storageManager.buildTemplates.filter { (template: BuildTemplate) -> Bool in
if
let projectName = template.projectName,
let project = self.project()
{
return projectName == project.projectName ?? ""
} else {
//if it doesn't yet have a project name associated, assume we have to show it
return true
}
}
}
override func reloadStatus() {
//if there is a local project, show status. otherwise show button to add one.
if let project = self.project() {
self.statusContentView.hidden = false
self.addProjectButton.hidden = true
self.buildTemplateComboBox.enabled = self.editing
self.deleteButton.hidden = !self.editing
self.editButton.title = self.editing ? "Done" : "Edit"
self.selectSSHPrivateKeyButton.enabled = self.editing
self.selectSSHPublicKeyButton.enabled = self.editing
self.sshPassphraseTextField.enabled = self.editing
self.selectSSHPublicKeyButton.title = project.publicSSHKeyUrl?.lastPathComponent ?? "Select SSH Public Key"
self.selectSSHPrivateKeyButton.title = project.privateSSHKeyUrl?.lastPathComponent ?? "Select SSH Private Key"
self.sshPassphraseTextField.stringValue = project.sshPassphrase ?? ""
//fill data in
self.projectNameLabel.stringValue = project.projectName ?? "<NO NAME>"
self.projectURLLabel.stringValue = project.projectURL?.absoluteString ?? "<NO URL>"
self.projectPathLabel.stringValue = project.url.path ?? "<NO PATH>"
if let githubToken = project.githubToken {
self.tokenTextField.stringValue = githubToken
}
self.tokenTextField.enabled = self.editing
let selectedBefore = self.buildTemplateComboBox.objectValueOfSelectedItem as? String
self.buildTemplateComboBox.removeAllItems()
let buildTemplateNames = self.buildTemplates().map { $0.name! }
self.buildTemplateComboBox.addItemsWithObjectValues(buildTemplateNames + [kBuildTemplateAddNewString])
self.buildTemplateComboBox.selectItemWithObjectValue(selectedBefore)
if
let preferredTemplateId = project.preferredTemplateId,
let template = self.buildTemplates().filter({ $0.uniqueId == preferredTemplateId }).first
{
self.buildTemplateComboBox.selectItemWithObjectValue(template.name!)
}
} else {
self.statusContentView.hidden = true
self.addProjectButton.hidden = false
self.tokenTextField.stringValue = ""
self.buildTemplateComboBox.removeAllItems()
}
}
override func checkAvailability(statusChanged: ((status: AvailabilityCheckState, done: Bool) -> ())?) {
let statusChangedPersist: (status: AvailabilityCheckState, done: Bool) -> () = {
(status: AvailabilityCheckState, done: Bool) -> () in
self.lastAvailabilityCheckStatus = status
statusChanged?(status: status, done: done)
}
if let _ = self.project() {
statusChangedPersist(status: .Checking, done: false)
NetworkUtils.checkAvailabilityOfGitHubWithCurrentSettingsOfProject(self.project()!, completion: { (success, error) -> () in
let status: AvailabilityCheckState
if success {
status = .Succeeded
} else {
Log.error("Checking github availability error: " + (error?.description ?? "Unknown error"))
status = AvailabilityCheckState.Failed(error)
}
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
statusChangedPersist(status: status, done: true)
})
})
} else {
statusChangedPersist(status: .Unchecked, done: true)
}
}
@IBAction func addProjectButtonTapped(sender: AnyObject) {
if let url = StorageUtils.openWorkspaceOrProject() {
do {
try self.storageManager.addProjectAtURL(url)
//we have just added a local source, good stuff!
//check if we have everything, if so, enable the "start syncing" button
self.editing = true
} catch {
//local source is malformed, something terrible must have happened, inform the user this can't be used (log should tell why exactly)
UIUtils.showAlertWithText("Couldn't add Xcode project at path \(url.absoluteString), error: \((error as NSError).localizedDescription).", style: NSAlertStyle.CriticalAlertStyle, completion: { (resp) -> () in
//
})
}
self.reloadStatus()
} else {
//user cancelled
}
}
//Combo Box Delegate
func comboBoxWillDismiss(notification: NSNotification) {
if let templatePulled = self.buildTemplateComboBox.objectValueOfSelectedItem as? String {
//it's string
var buildTemplate: BuildTemplate?
if templatePulled != kBuildTemplateAddNewString {
buildTemplate = self.buildTemplates().filter({ $0.name == templatePulled }).first
}
if buildTemplate == nil {
buildTemplate = BuildTemplate(projectName: self.project()!.projectName!)
}
self.delegate.showBuildTemplateViewControllerForTemplate(buildTemplate, project: self.project()!, sender: self)
}
}
func pullTemplateFromUI() -> Bool {
if let _ = self.project() {
let selectedIndex = self.buildTemplateComboBox.indexOfSelectedItem
if selectedIndex == -1 {
//not yet selected
UIUtils.showAlertWithText("You need to select a Build Template first")
return false
}
let template = self.buildTemplates()[selectedIndex]
if let project = self.project() {
project.preferredTemplateId = template.uniqueId
return true
}
return false
}
return false
}
override func pullDataFromUI() -> Bool {
if super.pullDataFromUI() {
let successCreds = self.pullCredentialsFromUI()
let template = self.pullTemplateFromUI()
return successCreds && template
}
return false
}
func pullCredentialsFromUI() -> Bool {
if let project = self.project() {
_ = self.pullTokenFromUI()
let privateUrl = project.privateSSHKeyUrl
let publicUrl = project.publicSSHKeyUrl
_ = self.pullSSHPassphraseFromUI() //can't fail
let githubToken = project.githubToken
let tokenPresent = githubToken != nil
let sshValid = privateUrl != nil && publicUrl != nil
let success = tokenPresent && sshValid
if success {
return true
}
UIUtils.showAlertWithText("Credentials error - you need to specify a valid personal GitHub token and valid SSH keys - SSH keys are used by Git and the token is used for talking to the API (Pulling Pull Requests, updating commit statuses etc). Please, also make sure all are added correctly.")
}
return false
}
func pullSSHPassphraseFromUI() -> Bool {
let string = self.sshPassphraseTextField.stringValue
if let project = self.project() {
if !string.isEmpty {
project.sshPassphrase = string
} else {
project.sshPassphrase = nil
}
}
return true
}
func pullTokenFromUI() -> Bool {
let string = self.tokenTextField.stringValue
if let project = self.project() {
if !string.isEmpty {
project.githubToken = string
} else {
project.githubToken = nil
}
}
return true
}
func control(control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
if control == self.tokenTextField {
self.pullTokenFromUI()
}
if control == self.sshPassphraseTextField {
self.pullSSHPassphraseFromUI()
}
return true
}
override func removeCurrentConfig() {
if let project = self.project() {
//also cleanup comboBoxes
self.buildTemplateComboBox.stringValue = ""
self.storageManager.removeProject(project)
self.storageManager.saveProjects()
self.reloadStatus()
}
}
func selectKey(type: String) {
if let url = StorageUtils.openSSHKey(type) {
do {
_ = try NSString(contentsOfURL: url, encoding: NSASCIIStringEncoding)
let project = self.project()!
if type == "public" {
project.publicSSHKeyUrl = url
} else {
project.privateSSHKeyUrl = url
}
} catch {
UIUtils.showAlertWithError(error as NSError)
}
}
self.reloadStatus()
}
@IBAction func selectPublicKeyTapped(sender: AnyObject) {
self.selectKey("public")
}
@IBAction func selectPrivateKeyTapped(sender: AnyObject) {
self.selectKey("private")
}
func setupViewControllerDidSave(viewController: SetupViewController) {
if let templateViewController = viewController as? BuildTemplateViewController {
//select the passed in template
var foundIdx: Int? = nil
let template = templateViewController.buildTemplate
for (idx, obj) in self.buildTemplates().enumerate() {
if obj.uniqueId == template.uniqueId {
foundIdx = idx
break
}
}
if let project = self.project() {
project.preferredTemplateId = template.uniqueId
}
if let foundIdx = foundIdx {
self.buildTemplateComboBox.selectItemAtIndex(foundIdx)
} else {
UIUtils.showAlertWithText("Couldn't find saved template, please report this error!")
}
self.reloadStatus()
}
}
func setupViewControllerDidCancel(viewController: SetupViewController) {
if let _ = viewController as? BuildTemplateViewController {
//nothing to do really, reset the selection of the combo box to nothing
self.buildTemplateComboBox.deselectItemAtIndex(self.buildTemplateComboBox.indexOfSelectedItem)
self.reloadStatus()
}
}
}
| 6a737d287e7549b59c204e52cacdaf05 | 35.863014 | 304 | 0.580305 | false | false | false | false |
ishaan1995/susi_iOS | refs/heads/master | Susi/Convenience.swift | apache-2.0 | 1 | //
// Convenience.swift
// Susi
//
// Created by Chashmeet Singh on 31/01/17.
// Copyright © 2017 FOSSAsia. All rights reserved.
//
import Foundation
import Alamofire
extension Client {
// MARK: - Auth Methods
func loginUser(_ params: [String : AnyObject], _ completion: @escaping(_ user: User?, _ success: Bool, _ error: String) -> Void) {
_ = makeRequest(.post, [:], Methods.Login, parameters: params, completion: { (results, message) in
if let error = message {
print(error.localizedDescription)
completion(nil, false, ResponseMessages.InvalidParams)
return
} else if let results = results as? [String : AnyObject] {
let user = User(dictionary: results)
UserDefaults.standard.set(results, forKey: "user")
completion(user, true, user.message)
return
}
})
}
func registerUser(_ params: [String : AnyObject], _ completion: @escaping(_ success: Bool, _ error: String) -> Void) {
_ = makeRequest(.post, [:], Methods.Register, parameters: params, completion: { (results, message) in
if let error = message {
print(error.localizedDescription)
completion(false, ResponseMessages.ServerError)
return
} else if let results = results {
guard let successMessage = results[UserKeys.Message] as? String else {
completion(false, ResponseMessages.InvalidParams)
return
}
completion(true, successMessage)
return
}
})
}
func logoutUser(_ completion: @escaping(_ success: Bool, _ error: String) -> Void) {
UserDefaults.standard.removeObject(forKey: "user")
completion(true, ResponseMessages.SignedOut)
}
// MARK: - Chat Methods
func queryResponse(_ params: [String : AnyObject], _ completion: @escaping(_ response: Message?, _ success: Bool, _ error: String?) -> Void) {
_ = makeRequest(.get, [:], Methods.Chat, parameters: params, completion: { (results, message) in
if let error = message {
print(error.localizedDescription)
completion(nil, false, ResponseMessages.ServerError)
return
} else if let results = results {
guard let response = results as? [String : AnyObject] else {
completion(nil, false, ResponseMessages.InvalidParams)
return
}
let message = Message.getMessageFromResponse(response, isBot: true)
completion(message, true, nil)
return
}
})
}
func websearch(_ params: [String : AnyObject], _ completion: @escaping(_ response: WebsearchResult?, _ success: Bool, _ error: String?) -> Void) {
_ = customRequest(.get, [:], CustomURLs.DuckDuckGo, params, completion: { (results, message) in
if let error = message {
print(error.localizedDescription)
completion(nil, false, ResponseMessages.ServerError)
return
} else if let results = results {
guard let response = results as? [String : AnyObject] else {
completion(nil, false, ResponseMessages.InvalidParams)
return
}
let searchResult = WebsearchResult(dictionary: response)
completion(searchResult, true, nil)
return
}
})
}
func searchYotubeVideos(_ query: String, _ completion: @escaping(_ response: String?, _ success: Bool, _ error: String?) -> Void) {
let params = [
YoutubeParamKeys.Key: YoutubeParamValues.Key,
YoutubeParamKeys.Part: YoutubeParamValues.Part,
YoutubeParamKeys.Query: query.replacingOccurrences(of: " ", with: "+")
]
_ = customRequest(.get, [:], CustomURLs.YoutubeSearch, params as [String : AnyObject], completion: { (results, message) in
if let error = message {
print(error.localizedDescription)
completion(nil, false, ResponseMessages.ServerError)
return
} else if let results = results {
guard let response = results as? [String : AnyObject] else {
completion(nil, false, ResponseMessages.InvalidParams)
return
}
if let itemsObject = response[Client.YoutubeResponseKeys.Items] as? [[String : AnyObject]] {
if let items = itemsObject[0][Client.YoutubeResponseKeys.ID] as? [String : AnyObject] {
let videoID = items[Client.YoutubeResponseKeys.VideoID] as? String
completion(videoID, true, nil)
}
}
return
}
})
}
}
| 423c07ca71ad0f09eaadbcfd9df5f9a6 | 31.551282 | 150 | 0.553958 | false | false | false | false |
myfreeweb/SwiftCBOR | refs/heads/master | Sources/SwiftCBOR/Encoder/CodableCBOREncoder.swift | unlicense | 1 | import Foundation
public class CodableCBOREncoder {
public init() {}
public func encode(_ value: Encodable) throws -> Data {
let encoder = _CBOREncoder()
if let dateVal = value as? Date {
return Data(CBOR.encodeDate(dateVal))
} else if let dataVal = value as? Data {
return Data(CBOR.encodeData(dataVal))
}
try value.encode(to: encoder)
return encoder.data
}
}
final class _CBOREncoder {
var codingPath: [CodingKey] = []
var userInfo: [CodingUserInfoKey : Any] = [:]
fileprivate var container: CBOREncodingContainer? {
willSet {
precondition(self.container == nil)
}
}
var data: Data {
return container?.data ?? Data()
}
}
extension _CBOREncoder: Encoder {
fileprivate func assertCanCreateContainer() {
precondition(self.container == nil)
}
func container<Key: CodingKey>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
assertCanCreateContainer()
let container = KeyedContainer<Key>(codingPath: self.codingPath, userInfo: self.userInfo)
self.container = container
return KeyedEncodingContainer(container)
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
assertCanCreateContainer()
let container = UnkeyedContainer(codingPath: self.codingPath, userInfo: self.userInfo)
self.container = container
return container
}
func singleValueContainer() -> SingleValueEncodingContainer {
assertCanCreateContainer()
let container = SingleValueContainer(codingPath: self.codingPath, userInfo: self.userInfo)
self.container = container
return container
}
}
protocol CBOREncodingContainer: class {
var data: Data { get }
}
| 1b4141a10d7e236323ca3e33fb848cec | 25.434783 | 98 | 0.650768 | false | false | false | false |
velvetroom/columbus | refs/heads/master | Source/View/Settings/VSettingsListCellDetailLevelList+Factory.swift | mit | 1 | import UIKit
extension VSettingsListCellDetailLevelList
{
//MARK: internal
func factoryViews()
{
let selectorMargin2:CGFloat = VSettingsListCellDetailLevelList.Constants.selectorLeft * 2
let selectorWidth:CGFloat = VSettingsListCellDetailLevelList.Constants.cellWidth - selectorMargin2
let viewSelector:VSettingsListCellDetailLevelListSelector = VSettingsListCellDetailLevelListSelector()
self.viewSelector = viewSelector
let viewRail:VSettingsListCellDetailLevelListRail = VSettingsListCellDetailLevelListRail()
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.backgroundColor = UIColor.clear
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
self.label = label
insertSubview(
viewRail,
belowSubview:collectionView)
insertSubview(
viewSelector,
belowSubview:collectionView)
addSubview(label)
layoutSelectorTop = NSLayoutConstraint.topToTop(
view:viewSelector,
toView:self)
NSLayoutConstraint.height(
view:viewSelector,
constant:VSettingsListCellDetailLevelList.Constants.selectorHeight)
NSLayoutConstraint.leftToLeft(
view:viewSelector,
toView:self,
constant:VSettingsListCellDetailLevelList.Constants.selectorLeft)
NSLayoutConstraint.width(
view:viewSelector,
constant:selectorWidth)
NSLayoutConstraint.equalsVertical(
view:viewRail,
toView:self)
NSLayoutConstraint.leftToLeft(
view:viewRail,
toView:self,
constant:VSettingsListCellDetailLevelList.Constants.railLeft)
NSLayoutConstraint.width(
view:viewRail,
constant:VSettingsListCellDetailLevelList.Constants.railWidth)
NSLayoutConstraint.topToTop(
view:label,
toView:self)
layoutLabelHeight = NSLayoutConstraint.height(
view:label)
NSLayoutConstraint.leftToLeft(
view:label,
toView:self,
constant:VSettingsListCellDetailLevelList.Constants.cellWidth)
NSLayoutConstraint.rightToRight(
view:label,
toView:self,
constant:VSettingsListCellDetailLevelList.Constants.labelRight)
}
}
| d00c5a6f61137da31910d6e823549cf6 | 33.780822 | 110 | 0.648681 | false | false | false | false |
nrlnishan/ViewPager-Swift | refs/heads/master | ViewPager-Swift/ItemViewController.swift | mit | 1 | //
// ItemViewController.swift
// ViewPager-Swift
//
// Created by Nishan on 2/9/16.
// Copyright © 2016 Nishan. All rights reserved.
//
import UIKit
class ItemViewController: UIViewController {
override func loadView() {
let newView = UIView()
newView.backgroundColor = UIColor.white
view = newView
}
var itemText: String?
override func viewDidLoad() {
super.viewDidLoad()
let itemLabel = UILabel()
itemLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(itemLabel)
itemLabel.textAlignment = .center
itemLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
itemLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
itemLabel.text = itemText
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Access the navigation controller if you want from child
if let parentPageViewController = self.parent {
parentPageViewController.parent?.navigationItem.title = itemText
}
}
}
| d223219b936610f074bd1b3563a4542e | 24.913043 | 87 | 0.646812 | false | false | false | false |
vsqweHCL/DouYuZB | refs/heads/master | DouYuZB/DouYuZB/Classs/Main/Controller/BaseViewController.swift | mit | 1 | //
// BaseViewController.swift
// DouYuZB
//
// Created by HCL黄 on 2016/12/25.
// Copyright © 2016年 HCL黄. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
var contentView : UIView?
// MARK:- 懒加载属性
fileprivate lazy var animImageView : UIImageView = { [unowned self] in
let imageView = UIImageView(image: UIImage(named: "img_loading_1"))
imageView.center = self.view.center
imageView.animationImages = [UIImage(named: "img_loading_1")!, UIImage(named: "img_loading_2")!]
imageView.animationDuration = 0.5
imageView.animationRepeatCount = LONG_MAX
imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin]
return imageView
}()
// MARK:- 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
extension BaseViewController {
func setupUI() {
// 1.先隐藏内容的view
contentView?.isHidden = true
// 2.添加执行动画的UIImageView
view.addSubview(animImageView)
animImageView.startAnimating()
view.backgroundColor = UIColor(r: 250, g: 250, b: 250)
}
func loadDataFinshed() {
animImageView.stopAnimating()
animImageView.isHidden = true
contentView?.isHidden = false
}
}
| 8a751bda52292dab199a345e7f05ac08 | 23.8 | 104 | 0.618768 | false | false | false | false |
objecthub/swift-lispkit | refs/heads/master | Sources/LispKit/Primitives/InternalLibrary.swift | apache-2.0 | 1 | //
// InternalLibrary.swift
// LispKit
//
// Created by Matthias Zenger on 25/08/2019.
// Copyright © 2019 ObjectHub. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
///
/// Internal library
///
public final class InternalLibrary: NativeLibrary {
public static let deconstructionTag = Symbol(uninterned: "deconstruct-datatype")
/// Name of the library.
public override class var name: [String] {
return ["lispkit", "internal"]
}
/// Declarations of the library.
public override func declarations() {
self.define(Procedure("datatype-deconstruction?", self.isDatatypeDeconstruction))
self.define(Procedure("deconstruct-datatype", self.deconstructDatatype))
self.define(Procedure("make-nan", self.makeNan))
self.define(Procedure("nan-negative?", self.nanNegative))
self.define(Procedure("nan-quiet?", self.nanQuiet))
self.define(Procedure("nan-payload", self.nanPayload))
self.define(Procedure("flbits=?", self.doubleBitsEquals))
}
private func isDatatypeDeconstruction(args: Expr) -> Expr {
guard case .pair(.symbol(InternalLibrary.deconstructionTag), .pair(_, .null)) = args else {
return .false
}
return .true
}
private func deconstructDatatype(args: Arguments) throws -> (Procedure, Exprs) {
guard args.count == 2 else {
throw RuntimeError.argumentCount(num: 2, args: .makeList(args))
}
guard case .procedure(let proc) = args.first! else {
throw RuntimeError.type(args.first!, expected: [.procedureType])
}
return (proc, [.symbol(InternalLibrary.deconstructionTag), args[args.startIndex + 1]])
}
private func makeNan(neg: Expr, quiet: Expr, payload: Expr) throws -> Expr {
// This is not portable code; I couldn't figure out a different way to implement this
// function
let pload = try payload.asInt64()
guard pload >= 0 && pload <= (Int64(1) << 50) else {
return .false
}
let num = Double(nan: UInt64(bitPattern: pload), signaling: quiet.isFalse)
if neg.isTrue {
return .makeNumber(Double(bitPattern: num.bitPattern | (UInt64(1) << 63)))
} else {
return .makeNumber(num)
}
}
private func nanNegative(expr: Expr) throws -> Expr {
switch expr {
case .flonum(let num):
return .makeBoolean(num.isNaN && (num.sign == .minus))
default:
return .false
}
}
private func nanQuiet(expr: Expr) throws -> Expr {
let num = try expr.asDouble(coerce: true)
return .makeBoolean(num.isNaN && !num.isSignalingNaN)
}
private func nanPayload(expr: Expr) throws -> Expr {
let num = try expr.asDouble(coerce: true)
return .makeNumber(num.bitPattern & ((UInt64(1) << 50) - 1))
}
private func doubleBitsEquals(fst: Expr, snd: Expr) throws -> Expr {
let num1 = try fst.asDouble(coerce: true)
let num2 = try snd.asDouble(coerce: true)
return .makeBoolean(num1.bitPattern == num2.bitPattern)
}
}
| 16976419a295646746ccde02a34c20cd | 33.333333 | 95 | 0.679041 | false | false | false | false |
Fenrikur/ef-app_ios | refs/heads/master | Eurofurence/Views/Controls/StarRatingControl.swift | mit | 1 | import UIKit
class StarRatingControl: UIControl {
private let stackView = UIStackView(frame: .zero)
private let numberOfStars = 5
private var selectionChangedFeedback: UISelectionFeedbackGenerator?
private var previousValueWhileTouchesMoving: Int?
override var isEnabled: Bool {
didSet {
updateCurrentTintColor()
}
}
var value: Int = 3 {
didSet {
switch validate(value: value) {
case .valid:
valueDidChange()
case .invalid(let suggestion):
value = suggestion
}
}
}
var percentageValue: Float {
return Float(value) / Float(numberOfStars)
}
var enabledTintColor: UIColor = UIColor(red: 1, green: 0.8, blue: 0, alpha: 1) {
didSet {
if isEnabled {
tintColor = enabledTintColor
}
}
}
var disabledTintColor: UIColor = .lightGray {
didSet {
if !isEnabled {
tintColor = disabledTintColor
}
}
}
private enum ValidationResult {
case valid
case invalid(suggestion: Int)
}
private func validate(value: Int) -> ValidationResult {
guard value > 1 else { return .invalid(suggestion: 1) }
guard value <= numberOfStars else { return .invalid(suggestion: numberOfStars) }
return .valid
}
private func valueDidChange() {
sendActions(for: .valueChanged)
updateAccessibilityValue()
repaintStars(value: value)
}
private func repaintStars(value: Int) {
let asStarView: (UIView) -> StarView? = { $0 as? StarView }
let filled = stackView.arrangedSubviews[0..<value].compactMap(asStarView)
let empty = stackView.arrangedSubviews[value..<numberOfStars].compactMap(asStarView)
filled.forEach({ $0.isFilled = true })
empty.forEach({ $0.isFilled = false })
}
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
private func setUp() {
setUpStackView()
insertStarViews()
updateCurrentTintColor()
setUpAccessibility()
repaintStars(value: value)
}
private func setUpStackView() {
insertStackViewIntoViewHiearchy()
adjustStackViewForHorizontalStarLayout()
}
private func insertStackViewIntoViewHiearchy() {
addSubview(stackView)
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor),
stackView.topAnchor.constraint(equalTo: topAnchor),
stackView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
private func adjustStackViewForHorizontalStarLayout() {
stackView.alignment = .center
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.translatesAutoresizingMaskIntoConstraints = false
}
private func insertStarViews() {
for _ in 0..<numberOfStars {
let starView = StarView(frame: .zero)
stackView.addArrangedSubview(starView)
}
}
private func updateCurrentTintColor() {
if isEnabled {
applyDefaultStarTintColor()
} else {
applyDisabledStarTintColor()
}
}
private func applyDefaultStarTintColor() {
tintColor = enabledTintColor
}
private func applyDisabledStarTintColor() {
tintColor = disabledTintColor
}
private func setUpAccessibility() {
isAccessibilityElement = true
accessibilityTraits.formUnion(.adjustable)
accessibilityLabel = "Star Rating"
}
private func updateAccessibilityValue() {
accessibilityValue = "\(value) of \(numberOfStars)"
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard isEnabled else { return }
guard touches.count == 1 else { return }
guard let touch = touches.first else { return }
selectionChangedFeedback = UISelectionFeedbackGenerator()
playSelectionChangedFeedback()
let point = touch.location(in: self)
let valueForLocation = calculateControlValue(for: point)
previousValueWhileTouchesMoving = valueForLocation
repaintStars(value: valueForLocation)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard isEnabled else { return }
guard touches.count == 1 else { return }
guard let touch = touches.first else { return }
let point = touch.location(in: self)
let valueForLocation = calculateControlValue(for: point)
if previousValueWhileTouchesMoving != valueForLocation {
playSelectionChangedFeedback()
previousValueWhileTouchesMoving = valueForLocation
}
repaintStars(value: valueForLocation)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
guard isEnabled else { return }
teardownTouchTrackingFields()
repaintStars(value: value)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard isEnabled else { return }
guard touches.count == 1 else { return }
guard let touch = touches.first else { return }
teardownTouchTrackingFields()
let point = touch.location(in: self)
value = calculateControlValue(for: point)
}
private func calculateControlValue(for point: CGPoint) -> Int {
let widthRatio = point.x / bounds.width
let estimatedValue = ceil(widthRatio * CGFloat(numberOfStars))
return max(1, min(numberOfStars, Int(estimatedValue)))
}
private func playSelectionChangedFeedback() {
selectionChangedFeedback?.selectionChanged()
selectionChangedFeedback?.prepare()
}
private func teardownTouchTrackingFields() {
selectionChangedFeedback = nil
previousValueWhileTouchesMoving = nil
}
override var intrinsicContentSize: CGSize {
return stackView.intrinsicContentSize
}
override func accessibilityIncrement() {
value += 1
}
override func accessibilityDecrement() {
value -= 1
}
private class StarView: UIImageView {
var isFilled: Bool = true {
didSet {
updateStarGraphic()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
private func setUp() {
adjustImageViewForPresentingStar()
updateStarGraphic()
}
private func adjustImageViewForPresentingStar() {
contentMode = .center
}
private func updateStarGraphic() {
if isFilled {
image = UIImage(named: "Star_Filled")
} else {
image = UIImage(named: "Star_Empty")
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: 44, height: 44)
}
}
}
| e40ef3ef14be628f345e725cd0721472 | 28.225564 | 92 | 0.589915 | false | false | false | false |
mattadatta/sulfur | refs/heads/master | Sulfur/Gradient.swift | mit | 1 | /*
This file is subject to the terms and conditions defined in
file 'LICENSE.txt', which is part of this source code package.
*/
import UIKit
// MARK: - Gradient
public struct Gradient {
fileprivate struct Constants {
static let defaultStops = [
Stop(color: .black, percent: 0.0),
Stop(color: .white, percent: 1.0),
]
}
public struct Stop: Hashable {
public var color: UIColor
public var percent: Double
public init(color: UIColor, percent: Double) {
self.color = color
self.percent = max(0.0, min(1.0, percent))
}
public var hashValue: Int {
return Hasher()
.adding(hashable: self.color)
.adding(part: self.percent)
.hashValue
}
public static func ==(lhs: Stop, rhs: Stop) -> Bool {
return lhs.color == rhs.color && lhs.percent == rhs.percent
}
}
public var stops: [Stop] {
didSet {
if self.stops.count < 2 {
self.stops = Constants.defaultStops
}
self.stops.sort(by: { $0.percent <= $1.percent })
}
}
public var colors: [UIColor] {
get { return self.stops.map({ $0.color }) }
set {
guard newValue.count > 1 else {
self.stops = Constants.defaultStops
return
}
let increment = 1.0 / Double(newValue.count - 1)
self.stops = newValue.mapPass(0.0) { color, percentage in
return (Stop(color: color, percent: percentage), percentage + increment)
}
}
}
public init() {
self.init(stops: Constants.defaultStops)
}
public init(stops: [Stop]) {
self.stops = (stops.count > 2) ? stops : Constants.defaultStops
}
public init(colors: [UIColor]) {
self.stops = Constants.defaultStops
self.colors = colors
}
public func interpolatedColorForPercentage(_ percent: Double) -> UIColor {
let percent = max(self.stops.first!.percent, min(self.stops.last!.percent, percent))
var firstIndex = 0, lastIndex = 1
while !(self.stops[firstIndex].percent <= percent &&
self.stops[lastIndex].percent >= percent) &&
lastIndex < self.stops.count
{
firstIndex = firstIndex + 1
lastIndex = lastIndex + 1
}
let stop1 = self.stops[firstIndex]
let stop2 = self.stops[lastIndex]
let interpolatedPercent = CGFloat((percent - stop1.percent) / (stop2.percent - stop1.percent))
let color1 = stop1.color
let color2 = stop2.color
let resultRed = color1.red + (interpolatedPercent * (color2.red - color1.red))
let resultGreen = color1.green + (interpolatedPercent * (color2.green - color1.green))
let resultBlue = color1.blue + (interpolatedPercent * (color2.blue - color1.blue))
let resultAlpha = color1.alpha + (interpolatedPercent * (color2.alpha - color1.alpha))
return UIColor(red: resultRed, green: resultGreen, blue: resultBlue, alpha: resultAlpha)
}
}
// MARK: - GradientView
public final class GradientView: UIView {
override public class var layerClass: AnyClass {
return CAGradientLayer.self
}
public var gradientLayer: CAGradientLayer {
return self.layer as! CAGradientLayer
}
public var gradient: Gradient = Gradient() {
didSet {
self.gradientLayer.colors = self.gradient.colors.map({ $0.cgColor })
self.gradientLayer.locations = self.gradient.stops.map({ NSNumber(value: $0.percent) })
}
}
public var startPoint: CGPoint {
get { return self.gradientLayer.startPoint }
set { self.gradientLayer.startPoint = newValue }
}
public var endPoint: CGPoint {
get { return self.gradientLayer.endPoint }
set { self.gradientLayer.endPoint = newValue }
}
override public init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
fileprivate func commonInit() {
self.gradient = Gradient() // Trigger didSet
}
}
| 353665b04c7c294d28cb2275c24a2a50 | 28.687075 | 102 | 0.586618 | false | false | false | false |
johnno1962/GitDiff | refs/heads/master | SharedXPC/LNScriptImpl.swift | mit | 2 | //
// LNScriptImpl.swift
// LNProvider
//
// Created by John Holdsworth on 31/03/2017.
// Copyright © 2017 John Holdsworth. All rights reserved.
//
import Foundation
let implementationFactory = LNScriptImpl.self
open class LNScriptImpl: LNExtensionBase, LNExtensionService {
open var scriptExt: String {
return "py"
}
open func requestHighlights(forFile filepath: String, callback: @escaping LNHighlightCallback) {
guard let script = Bundle.main.path(forResource: EXTENSION_IMPL_SCRIPT, ofType: scriptExt) else {
callback(nil, error(description: "script \(EXTENSION_IMPL_SCRIPT).\(scriptExt) not in XPC bundle"))
return
}
DispatchQueue.global().async {
let url = URL(fileURLWithPath: filepath)
let task = Process()
task.launchPath = script
task.arguments = [url.lastPathComponent]
task.currentDirectoryPath = url.deletingLastPathComponent().path
let pipe = Pipe()
task.standardOutput = pipe.fileHandleForWriting
task.standardError = pipe.fileHandleForWriting
task.launch()
pipe.fileHandleForWriting.closeFile()
let json = pipe.fileHandleForReading.readDataToEndOfFile()
task.waitUntilExit()
if task.terminationStatus != 0 {
let alert = "Script \(EXTENSION_IMPL_SCRIPT).\(self.scriptExt) exit status " +
"\(task.terminationStatus):\n" + (String(data: json, encoding: .utf8) ?? "No output")
callback(json, self.error(description: alert))
} else {
callback(json, nil)
}
}
}
}
| d2e1a0ff397f2105df9c3ab70f15660b | 32.076923 | 111 | 0.615116 | false | false | false | false |
Azoy/Sword | refs/heads/rewrite | Sources/Sword/Gateway/DispatchHandler.swift | mit | 1 | //
// DispatchHandler.swift
// Sword
//
// Created by Alejandro Alonso
// Copyright © 2018 Alejandro Alonso. All rights reserved.
//
import Foundation
extension Shard {
/// Operates on a given dispatch payload
///
/// - parameter payload: Payload received from gateway
/// - parameter data: Full payload data to decode after we figure out type
func handleDispatch(
_ payload: PayloadSinData,
_ data: Data
) {
// Make sure we got an event name
guard let t = payload.t else {
Sword.log(.warning, .dispatchName(id))
return
}
// Make sure we can handle this event
guard let event = Event(rawValue: t) else {
Sword.log(.warning, .unknownEvent(t))
return
}
// Handle the event
switch event {
// CHANNEL_CREATE
case .channelCreate:
guard let channelDecoding
= decode(ChannelDecoding.self, from: data) else {
Sword.log(.warning, "Could not decode channel")
return
}
let channel: Channel
switch channelDecoding.type {
case .guildCategory:
guard let tmp = decode(Guild.Channel.Category.self, from: data) else {
Sword.log(.warning, "Could not decode channel")
return
}
channel = tmp
case .guildText:
guard let tmp = decode(Guild.Channel.Text.self, from: data) else {
Sword.log(.warning, "Could not decode channel")
return
}
channel = tmp
case .guildVoice:
guard let tmp = decode(Guild.Channel.Voice.self, from: data) else {
Sword.log(.warning, "Could not decode channel")
return
}
channel = tmp
default:
// FIXME: When I implement the other channel types decode them here
return
}
sword.emit.channelCreate(channel)
// GUILD_CREATE
case .guildCreate:
Sword.decoder.dateDecodingStrategy = .custom(decodeISO8601)
guard let guild = decode(Guild.self, from: data) else {
Sword.log(.warning, "Could not decode guild")
return
}
sword.guilds[guild.id] = guild
if sword.unavailableGuilds.keys.contains(guild.id) {
sword.unavailableGuilds.removeValue(forKey: guild.id)
sword.emit.guildAvailable(guild)
} else {
sword.emit.guildCreate(guild)
}
// PRESENCE_UPDATE
case .presenceUpdate:
Sword.decoder.dateDecodingStrategy = .millisecondsSince1970
guard let presence = decode(Presence.self, from: data) else {
Sword.log(.warning, "Invalid presence structure received")
return
}
sword.emit.presenceUpdate(presence)
// READY
case .ready:
guard let ready = decode(GatewayReady.self, from: data) else {
Sword.log(.warning, "Unable to handle ready, disconnect")
disconnect()
return
}
// Make sure version we're connected to is the same as the version we requested
guard ready.version == Sword.gatewayVersion else {
Sword.log(.error, .invalidVersion(id))
disconnect()
return
}
sessionId = ready.sessionId
sword.user = ready.user
// Append unavailable guilds
for ug in ready.unavailableGuilds {
sword.unavailableGuilds[ug.id] = ug
}
sword.emit.ready(ready.user)
// RESUMED
case .resumed:
isReconnecting = false
// TYPING_START
case .typingStart:
Sword.decoder.dateDecodingStrategy = .secondsSince1970
guard let typing = decode(Typing.self, from: data) else {
Sword.log(.warning, "Unable to handle TYPING_START")
return
}
sword.emit.typingStart(typing)
default:
break
}
}
}
| aa38cf05a7d9a61fbb41d04c44c34373 | 25.671233 | 85 | 0.592964 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | Riot/Modules/Room/ParticipantsInviteModal/OptionList/OptionListItemViewData.swift | apache-2.0 | 1 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class OptionListItemViewData {
let title: String?
let detail: String?
let image: UIImage?
let accessoryImage: UIImage?
let enabled: Bool
init(title: String? = nil,
detail: String? = nil,
image: UIImage? = nil,
accessoryImage: UIImage? = Asset.Images.chevron.image,
enabled: Bool = true) {
self.title = title
self.detail = detail
self.image = image
self.accessoryImage = accessoryImage
self.enabled = enabled
}
}
| db519c97a5f18f7b679465507ae11fbc | 29.540541 | 75 | 0.674336 | false | false | false | false |
tjw/swift | refs/heads/master | test/SILGen/availability_query.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -emit-sil %s -target x86_64-apple-macosx10.50 -verify
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s -target x86_64-apple-macosx10.50 | %FileCheck %s
// REQUIRES: OS=macosx
// CHECK-LABEL: sil{{.+}}@main{{.*}} {
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 53
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 8
// CHECK: [[FUNC:%.*]] = function_ref @$Ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10.53.8, iOS 7.1, *) {
}
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_br [[TRUE]]
// Since we are compiling for an unmentioned platform (OS X), we check against the minimum
// deployment target, which is 10.50
if #available(iOS 7.1, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @$Ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10.52, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @$Ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(macOS 10.52, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @$Ss26_stdlib_isOSVersionAtLeastyBi1_Bw_BwBwtF : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10, *) {
}
// CHECK: }
func doThing() {}
func testUnreachableVersionAvailable(condition: Bool) {
if #available(OSX 10.0, *) {
doThing() // no-warning
return
} else {
doThing() // FIXME-warning {{will never be executed}}
}
if true {
doThing() // no-warning
}
if false { // expected-note {{condition always evaluates to false}}
doThing() // expected-warning {{will never be executed}}
}
}
func testUnreachablePlatformAvailable(condition: Bool) {
if #available(iOS 7.1, *) {
doThing() // no-warning
return
} else {
doThing() // no-warning
}
if true {
doThing() // no-warning
}
if false { // expected-note {{condition always evaluates to false}}
doThing() // expected-warning {{will never be executed}}
}
}
func testUnreachablePlatformAvailableGuard() {
guard #available(iOS 7.1, *) else {
doThing() // no-warning
return
}
doThing() // no-warning
}
| a86e6c2e1e91e837aa6138f6c9f0c49e | 38.934066 | 170 | 0.642818 | false | false | false | false |
Harada753/ARToolKitWithSwift | refs/heads/master | examples/ARApp/ViewController.swift | gpl-3.0 | 1 | //
// ViewController.swift
// ARToolKitWithSwift
//
// Created by 藤澤研究室 on 2016/07/11.
// Copyright © 2016年 藤澤研究室. All rights reserved.
//
import UIKit
import QuartzCore
class ARViewController: UIViewController, UIAlertViewDelegate, CameraVideoTookPictureDelegate, EAGLViewTookSnapshotDelegate {
var runLoopInterval: Int = 0
var runLoopTimePrevious: NSTimeInterval = 0.0
var videoPaused: Bool = false
// Video acquisition
var gVid: UnsafeMutablePointer<AR2VideoParamT> = nil
// Marker detection.
var gARHandle: UnsafeMutablePointer<ARHandle> = nil
var gARPattHandle: UnsafeMutablePointer<ARPattHandle> = nil
var gCallCountMarkerDetect: Int = 0
// Transformation matrix retrieval.
var gAR3DHandle: UnsafeMutablePointer<AR3DHandle> = nil
var gPatt_width: ARdouble = 0.0
var gPatt_trans34: UnsafeMutablePointer<(ARdouble, ARdouble, ARdouble, ARdouble)> = nil
var gPatt_found: Int32 = 0
var gPatt_id: Int32 = 0
var useContPoseEstimation: Bool = false
var gCparamLT: UnsafeMutablePointer<ARParamLT> = nil
private(set) var glView: UnsafeMutablePointer<ARView> = nil
private(set) var arglContextSettings: ARGL_CONTEXT_SETTINGS_REF = nil
private(set) var running: Bool = false
var paused: Bool = false
var markersHaveWhiteBorders: Bool = false
let VIEW_DISTANCE_MIN: Float = 5.0
let VIEW_DISTANCE_MAX: Float = 2000.0
// ロード画面の描画
override func loadView() {
// This will be overlaid with the actual AR view.
var irisImage : String? = nil
if (UIDevice.currentDevice().userInterfaceIdiom == .Pad) {
irisImage = "Iris-iPad.png"
} else { // UIDevice.current.userInterfaceIdiom == .Phone
let result = UIScreen.mainScreen().bounds.size
if (result.height == 568) {
irisImage = "Iris-568h.png" // iPhone 5, iPod touch 5th Gen, etc.
} else { // result.height == 480
irisImage = "Iris.png"
}
}
let myImage: UIImage = UIImage(named: irisImage!)!
let irisView = UIImageView(image: myImage)
irisView.userInteractionEnabled = true // タッチの検知を行う
view = irisView
}
// Viewが初めて呼び出されるとき一回呼ばれる
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// 変数の初期化
gCallCountMarkerDetect = 0
useContPoseEstimation = false
running = false
videoPaused = false
runLoopTimePrevious = CFAbsoluteTimeGetCurrent()
}
// 画面が表示された直後に実行される
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
start2()
}
// On iOS 6.0 and later, we must explicitly report which orientations this view controller supports.
func supportedInterfaceOrientationsBySwift() -> UIInterfaceOrientationMask { // change func name
return UIInterfaceOrientationMask.Portrait
}
func startRunLoop() {
if (!running) {
// After starting the video, new frames will invoke cameraVideoTookPicture:userData:.
if (ar2VideoCapStart(gVid) != 0) {
print("Error: Unable to begin camera data capture.\n")
stop()
return
}
running = true
}
}
func stopRunLoop() {
if (running) {
ar2VideoCapStop(gVid)
running = false
}
}
private func setRunLoopInterval(interval: Int) {
if (interval >= 1) {
runLoopInterval = interval
if (running) {
stopRunLoop()
startRunLoop()
}
}
}
func isPaused() -> Bool {
if (!running) {
return(false)
}
return (videoPaused)
}
private func setPaused(paused: Bool) {
if (!running) {
return
}
if (videoPaused != paused) {
if (paused) {
ar2VideoCapStop(gVid)
}
else {
ar2VideoCapStart(gVid)
}
videoPaused = paused
}
}
@IBAction func start() {
let vconf: UnsafePointer<Int8> = nil
let ref: UnsafeMutablePointer<Void> = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
gVid = ar2VideoOpenAsync(vconf, startCallback, ref)
if (gVid != nil) {
print("Error: Unable to open connection to camera.\n")
stop()
return
}
}
/*
static func startCallback(userData: UnsafeMutablePointer<Void>){
let vc: UnsafeMutablePointer<ARViewController> = unsafeBitCast(userData,UnsafeMutablePointer<ARViewController>.self)
vc.memory.start2()
}
*/
let startCallback: @convention(c) (UnsafeMutablePointer<Void>) -> Void = {
(userData) in
let vc: UnsafeMutablePointer<ARViewController> = unsafeBitCast(userData,
UnsafeMutablePointer<ARViewController>.self)
vc.memory.start2()
}
func start2() {
// Find the size of the window.
let xsize: UnsafeMutablePointer<Int32> = nil
let ysize: UnsafeMutablePointer<Int32> = nil
if (ar2VideoGetSize(gVid, xsize, ysize) < 0) {
print("Error: ar2VideoGetSize.")
stop()
return
}
// Get the format in which the camera is returning pixels.
let pixFormat = ar2VideoGetPixelFormat(gVid)
if (pixFormat == AR_PIXEL_FORMAT_INVALID) {
print("Error: Camera is using unsupported pixel format.")
stop()
return
}
// Work out if the front camera is being used. If it is, flip the viewing frustum for
// 3D drawing.
var flipV: Bool = false
let frontCamera: UnsafeMutablePointer<Int32> = nil
if (ar2VideoGetParami(gVid, Int32(AR_VIDEO_PARAM_IOS_CAMERA_POSITION), frontCamera) >= 0) {
if (frontCamera[0] == AR_VIDEO_IOS_CAMERA_POSITION_FRONT.rawValue) {
flipV = true
}
}
// Tell arVideo what the typical focal distance will be. Note that this does NOT
// change the actual focus, but on devices with non-fixed focus, it lets arVideo
// choose a better set of camera parameters.
ar2VideoSetParami(gVid, Int32(AR_VIDEO_PARAM_IOS_FOCUS), Int32(AR_VIDEO_IOS_FOCUS_0_3M.rawValue))
// Default is 0.3 metres. See <AR/sys/videoiPhone.h> for allowable values.
// Load the camera parameters, resize for the window and init.
let cparam: UnsafeMutablePointer<ARParam> = nil
if (ar2VideoGetCParam(gVid, cparam) < 0) {
let cparam_name: String? = "Data2/camera_para.dat"
print("Unable to automatically determine camera parameters. Using default.\n")
if (arParamLoadFromBuffer(cparam_name!, 1, cparam) < 0) {
print("Error: Unable to load parameter file %s for camera.\n", cparam_name)
stop()
return
}
}
if (cparam[0].xsize != xsize[0] || cparam[0].ysize != ysize[0]) {
arParamChangeSize(cparam, xsize[0], ysize[0], cparam)
}
gCparamLT = arParamLTCreate(cparam, AR_PARAM_LT_DEFAULT_OFFSET)
if (gCparamLT == nil) {
print("Error: arParamLTCreate.\n")
stop()
return
}
// AR init.
gARHandle = arCreateHandle(gCparamLT)
if (gARHandle == nil) {
print("Error: arCreateHandle.\n")
stop()
return
}
if (arSetPixelFormat(gARHandle, pixFormat) < 0) {
print("Error: arSetPixelFormat.\n")
stop()
return
}
gAR3DHandle = ar3DCreateHandle(&gCparamLT[0].param)
if (gAR3DHandle == nil) {
print("Error: ar3DCreateHandle.\n")
stop()
return
}
// libARvideo on iPhone uses an underlying class called CameraVideo. Here, we
// access the instance of this class to get/set some special types of information.
// let cameraVideo: CameraVideo? = ar2VideoGetNativeVideoInstanceiPhone(gVid[0].device.iPhone)
let iphone = gVid[0].device.iPhone
let tmp = ar2VideoGetNativeVideoInstanceiPhone(iphone)
let cameraVideo: UnsafeMutablePointer<CameraVideo> = unsafeBitCast(tmp, UnsafeMutablePointer<CameraVideo>.self)
if (cameraVideo == nil) {
print("Error: Unable to set up AR camera: missing CameraVideo instance.\n")
stop()
return
}
// The camera will be started by -startRunLoop.
cameraVideo[0].tookPictureDelegate = self
cameraVideo[0].tookPictureDelegateUserData = nil
// Other ARToolKit setup.
arSetMarkerExtractionMode(gARHandle, AR_USE_TRACKING_HISTORY_V2)
//arSetMarkerExtractionMode(gARHandle, AR_NOUSE_TRACKING_HISTORY)
//arSetLabelingThreshMode(gARHandle, AR_LABELING_THRESH_MODE_MANUAL) // Uncomment to use manual thresholding.
// Allocate the OpenGL view.
glView.memory = ARView.init(frame: UIScreen.mainScreen().bounds, pixelFormat: kEAGLColorFormatRGBA8, depthFormat: kEAGLDepth16, withStencil: false, preserveBackbuffer: false) // Don't retain it, as it will be retained when added to self.view.
glView.memory.arViewController = self
view.addSubview(glView.memory)
// Create the OpenGL projection from the calibrated camera parameters.
// If flipV is set, flip.
let frustum: UnsafeMutablePointer<Float> = nil
arglCameraFrustumRHf(&gCparamLT[0].param, VIEW_DISTANCE_MIN, VIEW_DISTANCE_MAX, frustum)
glView.memory.cameraLens = frustum
glView.memory.contentFlipV = flipV
// Set up content positioning.
glView.memory.contentScaleMode = ARViewContentScaleModeFill
glView.memory.contentAlignMode = ARViewContentAlignModeCenter
glView.memory.contentWidth = gARHandle[0].xsize
glView.memory.contentHeight = gARHandle[0].ysize
let isBackingTallerThanWide: Bool = glView.memory.surfaceSize.height > glView.memory.surfaceSize.width
if (glView.memory.contentWidth > glView.memory.contentHeight) {
glView.memory.contentRotate90 = isBackingTallerThanWide
}
else {
glView.memory.contentRotate90 = !isBackingTallerThanWide
}
// Setup ARGL to draw the background video.
arglContextSettings = arglSetupForCurrentContext(&gCparamLT[0].param, pixFormat)
let temp = { () -> Int8 in
if (self.glView.memory.contentWidth > self.glView.memory.contentHeight) {
return isBackingTallerThanWide ? 1 : 0
}
else {
return isBackingTallerThanWide ? 0 : 1
}
}
arglSetRotate90(arglContextSettings, temp())
if (flipV) {
arglSetFlipV(arglContextSettings, 1/*Objc: 1, Swift: true*/)
}
let width: UnsafeMutablePointer<Int32> = nil
let height: UnsafeMutablePointer<Int32> = nil
ar2VideoGetBufferSize(gVid, width, height)
arglPixelBufferSizeSet(arglContextSettings, width[0], height[0])
gARPattHandle = arPattCreateHandle()
// Prepare ARToolKit to load patterns.
if gARPattHandle == nil {
print("Error: arPattCreateHandle.\n")
stop()
return
}
arPattAttach(gARHandle, gARPattHandle)
// Load marker(s).
// Loading only 1 pattern in this example.
let patt_name: String = "Data2/hiro.patt"
gPatt_id = arPattLoad(gARPattHandle, patt_name)
if gPatt_id < 0 {
print("Error loading pattern file \(patt_name).\n")
stop()
return
}
gPatt_width = 40.0
gPatt_found = 0
// For FPS statistics.
arUtilTimerReset()
gCallCountMarkerDetect = 0
//Create our runloop timer
setRunLoopInterval(2) // Target 30 fps on a 60 fps device.
startRunLoop()
}
func cameraVideoTookPicture(sender: AnyObject, userData data: UnsafeMutablePointer<Void>) {
let buffer: UnsafeMutablePointer<AR2VideoBufferT> = ar2VideoGetImage(gVid)
if (buffer != nil) {
processFrame(buffer)
}
}
func processFrame(buffer: UnsafeMutablePointer<AR2VideoBufferT>) {
var err : ARdouble
var j : Int = 0
var k : Int = -1
if (buffer != nil)
{
let bufPlanes0 = buffer.memory.bufPlanes[0]
let bufPlanes1 = buffer.memory.bufPlanes[1]
// Upload the frame to OpenGL.
if (buffer.memory.bufPlaneCount == 2)
{
arglPixelBufferDataUploadBiPlanar(arglContextSettings, bufPlanes0, bufPlanes1)
}
else
{
arglPixelBufferDataUploadBiPlanar(arglContextSettings, buffer.memory.buff, nil)
}
gCallCountMarkerDetect += 1 // Increment ARToolKit FPS counter.
// Detect the markers in the video frame.
if (arDetectMarker(gARHandle, buffer.memory.buff) < 0)
{
return
}
// Check through the marker_info array for highest confidence
// visible marker matching our preferred pattern.
while (j < Int(gARHandle.memory.marker_num)) {
let markInfoId_j = withUnsafeMutablePointer(&gARHandle.memory.markerInfo.0) { (markerInfoPtr) -> Int32 in
return markerInfoPtr[0+j].id
}
let markInfoCf_j = withUnsafeMutablePointer(&gARHandle.memory.markerInfo.0) { (markerInfoPtr) -> ARdouble in
return markerInfoPtr[0+j].cf
}
let markInfoCf_k = withUnsafeMutablePointer(&gARHandle.memory.markerInfo.0) { (markerinfoPtr) -> ARdouble in
return markerinfoPtr[0+k].cf
}
if (markInfoId_j == gPatt_id) {
if (k == -1)
{
k = j // First marker detected.
}
else if (markInfoCf_j > markInfoCf_k)
{
k = j // Higher confidence marker detected.
}
}
}
j += 1
}
if (k != -1)
{
var markInfo_k = withUnsafeMutablePointer(&gARHandle.memory.markerInfo.0) { (markerinfoPtr) -> ARMarkerInfo in
return markerinfoPtr[0+k]
}
// Get the transformation between the marker and the real camera into gPatt_trans.
if ((gPatt_found != 0) && useContPoseEstimation)
{
err = arGetTransMatSquareCont(gAR3DHandle, &markInfo_k, gPatt_trans34, gPatt_width, gPatt_trans34)
}
else
{
err = arGetTransMatSquare(gAR3DHandle, &markInfo_k, gPatt_width, gPatt_trans34)
}
let modelview: [Float] = []
gPatt_found = 1
glView.memory.cameraPose = UnsafeMutablePointer<Float>(modelview)
} else {
gPatt_found = 0
glView.memory.cameraPose = nil
}
// Get current time (units = seconds).
var runLoopTimeNow: NSTimeInterval
runLoopTimeNow = CFAbsoluteTimeGetCurrent()
glView.memory.updateWithTimeDelta(runLoopTimeNow - runLoopTimePrevious)
// The display has changed.
glView.memory.drawView(self)
// Save timestamp for next loop.
runLoopTimePrevious = runLoopTimeNow
}
@IBAction func stop() {
stopRunLoop()
if (arglContextSettings != nil) {
arglCleanup(arglContextSettings)
arglContextSettings = nil
}
glView.memory.removeFromSuperview()
glView = nil
if (gARHandle != nil){
arPattDetach(gARHandle)
}
if (gARPattHandle != nil) {
arPattDeleteHandle(gARPattHandle)
gARHandle = nil
}
arParamLTFree(&gCparamLT)
if (gVid != nil) {
ar2VideoClose(gVid)
gVid = nil
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Viewが画面から消える直前に呼び出される
override func viewWillDisappear(animated:Bool) {
stop()
super.viewWillDisappear(animated)
}
// 解放のタイミングで呼ばれる
deinit {
// super.dealloc()
}
// ARToolKit-specific methods.
func markersHaveWhiteBordersBySwift() -> Bool { // change method name
let mode: UnsafeMutablePointer<Int32> = nil
arGetLabelingMode(gARHandle, mode)
return (mode[0] == AR_LABELING_WHITE_REGION)
}
func setMarkersHaveWhiteBordersBySwift(markersHaveWhiteBorders:Bool) {
arSetLabelingMode(gARHandle, (markersHaveWhiteBorders ? AR_LABELING_WHITE_REGION : AR_LABELING_BLACK_REGION))
}
// Call this method to take a snapshot of the ARView.
// Once the image is ready, tookSnapshot:forview: will be called.
func takeSnapshot() {
// We will need to wait for OpenGL rendering to complete.
glView.memory.tookSnapshotDelegate = self
glView.memory.takeSnapshot()
}
//- (void) tookSnapshot:(UIImage *)image forView:(EAGLView *)view;
// Here you can choose what to do with the image.
// We will save it to the iOS camera roll.
func tookSnapshot(image: UIImage, forView view: EAGLView) {
// First though, unset ourselves as delegate.
glView.memory.tookSnapshotDelegate = nil
// Write image to camera roll.
UIImageWriteToSavedPhotosAlbum(image, self, #selector(ARViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
// Let the user know that the image was saved by playing a shutter sound,
// or if there was an error, put up an alert.
func image(image:UnsafeMutablePointer<UIImage>, didFinishSavingWithError error:UnsafeMutablePointer<NSError>, contextInfo: UnsafeMutablePointer<Void>) {
if (error != nil) {
var shutterSound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(NSBundle.mainBundle().URLForResource("slr_camera_shutter", withExtension: "wav") as! CFURLRef, &shutterSound)
AudioServicesPlaySystemSound(shutterSound)
} else {
let titleString: String? = "Error saving screenshot"
var messageString: String? = error.debugDescription
let moreString: String = (error[0].localizedFailureReason != nil) ? error[0].localizedFailureReason! : NSLocalizedString("Please try again.", comment: "")
messageString = NSString.init(format: "%@. %@", messageString!, moreString) as String
// iOS 8.0以上
if #available(iOS 8.0, *) {
let alertView: UIAlertController = UIAlertController.init(title: titleString!, message: messageString!, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction: UIAlertAction = UIAlertAction.init(title: "OK", style: UIAlertActionStyle.Cancel, handler: {
(action: UIAlertAction!) -> Void in
print("OK")
})
alertView.addAction(cancelAction)
presentViewController(alertView, animated: true, completion: nil)
// iOS 8.0未満
} else {
let alertView: UIAlertView = UIAlertView.init(title: titleString!, message: messageString!, delegate: self, cancelButtonTitle: "OK")
alertView.show()
}
}
}
}
| a7fe7f4bffe3978aaef3c70e158dda82 | 37.791985 | 250 | 0.593447 | false | false | false | false |
Caiflower/SwiftWeiBo | refs/heads/master | 花菜微博/花菜微博/Classes/Tools(工具)/Other/CFCommon.swift | apache-2.0 | 1 | //
// CFCommon.swift
// 花菜微博
//
// Created by 花菜ChrisCai on 2016/12/18.
// Copyright © 2016年 花菜ChrisCai. All rights reserved.
//
import Foundation
// MARK: - 全局通知
/// 用户是否登录通知
let kUserShoudLoginNotification = "userShoudLoginNotification"
/// 用户登录成功通知
let kUserLoginSuccessNotification = "kUserLoginSuccessNotification"
/// 用户token过期通知
let kUserTokenDidExpireNotification = "kUserTokenDidExpireNotification"
// MARK: - 应用程序信息
/// 新浪微博Appkey
let SinaAppKey = "941749531"
/// 应用程序加密信息
let SinaAppSecret = "96e15facd4e5d81626e66dd4a41bb5b7"
/// 回到地址 - 登录成功完成跳转的URL
let SinaRedirectURI = "http://caiflower.com"
// MARK: - 各种key
let CFBoundelVersionKey = "CFBoundelVersionKey"
// MARK: - 微博常数
/// 头像高度
let CFStatusIconViewHeight: CGFloat = 34
/// 底部工具条高度
let CFStatusToolbarHeight: CGFloat = 36
/// 通用间距
let CFCommonMargin: CGFloat = 12
/// 微博配图外部间距
let CFStatusPictureViewOutterMargin: CGFloat = CFCommonMargin
/// 微博配图内部间距
let CFStatusPictureViewInnerMargin: CGFloat = 3
/// 微博配图视图宽度
let CFStatusPictureViewWidth: CGFloat = UIScreen.main.cf_screenWidth - 2 * CFStatusPictureViewOutterMargin
/// 微博配图单个配图宽高
let CFStatusPictureItemWidth: CGFloat = (CFStatusPictureViewWidth - 2 * CFStatusPictureViewInnerMargin) / 3
| 82656d97a71b7f858df7a139da2eaaf3 | 23.56 | 107 | 0.769544 | false | false | false | false |
IBAnimatable/IBAnimatable | refs/heads/master | Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationHeartBeat.swift | mit | 2 | //
// ActivityIndicatorAnimationHeartBeat.swift
// IBAnimatable
//
// Created by phimage on 02/05/2018.
// Copyright © 2018 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationHeartBeat: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 0.8
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let circle = ActivityIndicatorShape.mask(type: .heart).makeLayer(size: size, color: color)
circle.frame = CGRect(x: x, y: y, width: size.width, height: size.height)
circle.add(defaultAnimation, forKey: "animation")
layer.addSublayer(circle)
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationHeartBeat {
var defaultAnimation: CABasicAnimation {
let scaleAnimation = CABasicAnimation(keyPath: .scale)
scaleAnimation.timingFunctionType = .easeOutBack
scaleAnimation.duration = duration
scaleAnimation.repeatCount = .infinity
scaleAnimation.autoreverses = true
scaleAnimation.fromValue = 1
scaleAnimation.toValue = 0.8
scaleAnimation.isRemovedOnCompletion = false
return scaleAnimation
}
}
| e7f680c6f8a74f14732ddc174743729f | 27.978261 | 94 | 0.739685 | false | false | false | false |
xlexi/Textual-Inline-Media | refs/heads/master | Textual Inline Media/Extensions.swift | bsd-3-clause | 1 | /*
Copyright (c) 2015, Alex S. Glomsaas
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
extension String {
subscript(index: Int) -> Character {
return self[startIndex.advancedBy(index)]
}
subscript(range: Range<Int>) -> String {
return self[startIndex.advancedBy(range.startIndex)..<startIndex.advancedBy(range.endIndex)]
}
func trim() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
}
extension DOMElement {
var classList: [String] {
get {
return self.className.componentsSeparatedByString(" ")
} set(classes) {
self.className = classes.joinWithSeparator(" ")
}
}
}
extension NSFileManager {
func getTemporaryDirectory(name: String) -> NSURL? {
let tempDirURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(name)
if NSFileManager.defaultManager().fileExistsAtPath(tempDirURL.absoluteString) == false {
do {
try NSFileManager.defaultManager().createDirectoryAtURL(tempDirURL, withIntermediateDirectories: true, attributes: nil)
} catch {
return nil
}
}
return tempDirURL
}
}
extension NSImage {
static func fromAssetCatalogue(name: String) -> NSImage? {
let mainBundle = NSBundle(forClass: InlineMedia.self)
return mainBundle.imageForResource(name)
}
}
extension NSTimeInterval {
init?(iso8601String: String) {
if iso8601String.hasPrefix("P") && iso8601String.containsString("T") {
var seconds: NSTimeInterval = 0
var isTimeSegment = false
let iso8601duration = NSScanner(string: iso8601String)
if iso8601String.hasPrefix("PT") {
iso8601duration.charactersToBeSkipped = NSCharacterSet(charactersInString: "PT")
isTimeSegment = true
} else {
iso8601duration.charactersToBeSkipped = NSCharacterSet(charactersInString: "P")
}
while iso8601duration.atEnd == false {
var value = 0.0
var units: NSString?
if iso8601duration.scanDouble(&value) {
if iso8601duration.scanCharactersFromSet(NSCharacterSet.uppercaseLetterCharacterSet(), intoString: &units) {
if let unitString = units as? String {
for unit in unitString.characters {
switch unit {
case "Y":
seconds += 31557600*value
case "M":
if isTimeSegment {
seconds += 60*value
} else {
seconds += 2629800*value
}
case "W":
seconds += 604800*value
case "D":
seconds += 86400*value
case "H":
seconds += 3600*value
case "S":
seconds += value
case "T":
isTimeSegment = true
default:
return nil
}
}
}
}
} else {
break
}
}
self.init(seconds)
return
}
return nil
}
}
| 6a3d5dfba4f4e048a44f7ce23148cf06 | 37.236111 | 135 | 0.545042 | false | false | false | false |
kingslay/KSRearrangeableCollectionView | refs/heads/master | KDRearrangeableCollectionViewFlowLayout/InteractiveMovement.swift | mit | 1 | //
// InteractiveMovement.swift
// KDRearrangeableCollectionViewFlowLayout
//
// Created by kingslay on 15/10/29.
// Copyright © 2015年 Karmadust. All rights reserved.
//
import UIKit
import ObjectiveC
private var xoAssociationKey: UInt8 = 0
extension UICollectionView: UIGestureRecognizerDelegate {
class Bundle {
var offset : CGPoint = CGPointZero
var sourceCell : UICollectionViewCell
var representationImageView : UIView
var currentIndexPath : NSIndexPath
init(offset: CGPoint, sourceCell: UICollectionViewCell, representationImageView:UIView, currentIndexPath: NSIndexPath)
{
self.offset = offset
self.sourceCell = sourceCell
self.representationImageView = representationImageView
self.currentIndexPath = currentIndexPath
}
}
var bundle : Bundle? {
get {
return objc_getAssociatedObject(self, &xoAssociationKey) as? Bundle
}
set(newValue) {
objc_setAssociatedObject(self, &xoAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
public func addMoveGestureRecognizerForPan(){
let panGestureRecogniser = UIPanGestureRecognizer(target: self, action: "handleGesture:")
panGestureRecogniser.delegate = self
self.addGestureRecognizer(panGestureRecogniser)
}
public func addMoveGestureRecognizerForLongPress(){
let longPressGestureRecogniser = UILongPressGestureRecognizer(target: self, action: "handleGesture:")
longPressGestureRecogniser.delegate = self
self.addGestureRecognizer(longPressGestureRecogniser)
}
// MARK: - UIGestureRecognizerDelegate
public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
let pointPressedPoint = gestureRecognizer.locationInView(self)
if let indexPath = self.indexPathForItemAtPoint(pointPressedPoint),cell = self.cellForItemAtIndexPath(indexPath) {
let representationImage = cell.snapshotViewAfterScreenUpdates(true)
representationImage.frame = cell.frame
let offset = CGPointMake(pointPressedPoint.x - representationImage.frame.origin.x, pointPressedPoint.y - representationImage.frame.origin.y)
self.bundle = Bundle(offset: offset, sourceCell: cell, representationImageView:representationImage, currentIndexPath: indexPath)
}
return (self.bundle != nil)
}
public func handleGesture(gesture: UIGestureRecognizer) -> Void {
if let bundle = self.bundle {
let dragPointOnCollectionView = gesture.locationInView(self)
if gesture.state == UIGestureRecognizerState.Began {
bundle.sourceCell.hidden = true
self.addSubview(bundle.representationImageView)
UIView.animateWithDuration(0.5, animations: { () -> Void in
bundle.representationImageView.alpha = 0.8
});
}
if gesture.state == UIGestureRecognizerState.Changed {
// Update the representation image
var imageViewFrame = bundle.representationImageView.frame
var point = CGPointZero
point.x = dragPointOnCollectionView.x - bundle.offset.x
point.y = dragPointOnCollectionView.y - bundle.offset.y
imageViewFrame.origin = point
bundle.representationImageView.frame = imageViewFrame
if let indexPath : NSIndexPath = self.indexPathForItemAtPoint(dragPointOnCollectionView) {
if indexPath.isEqual(bundle.currentIndexPath) == false {
// If we have a collection view controller that implements the delegate we call the method first
if let delegate = self.delegate as? KDRearrangeableCollectionViewDelegate {
delegate.moveDataItem(bundle.currentIndexPath, toIndexPath: indexPath)
}
self.moveItemAtIndexPath(bundle.currentIndexPath, toIndexPath: indexPath)
self.bundle!.currentIndexPath = indexPath
}
}
}
if gesture.state == UIGestureRecognizerState.Ended {
bundle.sourceCell.hidden = false
bundle.representationImageView.removeFromSuperview()
if let _ = self.delegate as? KDRearrangeableCollectionViewDelegate { // if we have a proper data source then we can reload and have the data displayed correctly
self.reloadData()
}
self.bundle = nil
}
}
}
} | a46ca448b04d343ca7bdc030830c666b | 42.769912 | 176 | 0.626896 | false | false | false | false |
justinhester/hacking-with-swift | refs/heads/master | src/Project33/Project33/AppDelegate.swift | gpl-3.0 | 1 | //
// AppDelegate.swift
// Project33
//
// Created by Justin Lawrence Hester on 2/18/16.
// Copyright © 2016 Justin Lawrence Hester. All rights reserved.
//
import CloudKit
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let notificationSettings = UIUserNotificationSettings(
forTypes: [.Alert, .Sound],
categories: nil
)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
UIApplication.sharedApplication().registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if let pushInfo = userInfo as? [String: NSObject] {
let notification = CKNotification(fromRemoteNotificationDictionary: pushInfo)
let ac = UIAlertController(
title: "What's that Whistle?",
message: notification.alertBody,
preferredStyle: .Alert
)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
if let nc = window?.rootViewController as? UINavigationController {
if let vc = nc.visibleViewController {
vc.presentViewController(ac, animated: true, completion: nil)
}
}
}
}
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:.
}
}
| 1d32668edc7489dad94483f044263355 | 43.608108 | 285 | 0.710997 | false | false | false | false |
qutheory/vapor | refs/heads/master | Sources/Vapor/Middleware/ErrorMiddleware.swift | mit | 1 | /// Captures all errors and transforms them into an internal server error HTTP response.
public final class ErrorMiddleware: Middleware {
/// Structure of `ErrorMiddleware` default response.
internal struct ErrorResponse: Codable {
/// Always `true` to indicate this is a non-typical JSON response.
var error: Bool
/// The reason for the error.
var reason: String
}
/// Create a default `ErrorMiddleware`. Logs errors to a `Logger` based on `Environment`
/// and converts `Error` to `Response` based on conformance to `AbortError` and `Debuggable`.
///
/// - parameters:
/// - environment: The environment to respect when presenting errors.
public static func `default`(environment: Environment) -> ErrorMiddleware {
return .init { req, error in
// variables to determine
let status: HTTPResponseStatus
let reason: String
let headers: HTTPHeaders
// inspect the error type
switch error {
case let abort as AbortError:
// this is an abort error, we should use its status, reason, and headers
reason = abort.reason
status = abort.status
headers = abort.headers
default:
// if not release mode, and error is debuggable, provide debug info
// otherwise, deliver a generic 500 to avoid exposing any sensitive error info
reason = environment.isRelease
? "Something went wrong."
: String(describing: error)
status = .internalServerError
headers = [:]
}
// Report the error to logger.
req.logger.report(error: error)
// create a Response with appropriate status
let response = Response(status: status, headers: headers)
// attempt to serialize the error to json
do {
let errorResponse = ErrorResponse(error: true, reason: reason)
response.body = try .init(data: JSONEncoder().encode(errorResponse))
response.headers.replaceOrAdd(name: .contentType, value: "application/json; charset=utf-8")
} catch {
response.body = .init(string: "Oops: \(error)")
response.headers.replaceOrAdd(name: .contentType, value: "text/plain; charset=utf-8")
}
return response
}
}
/// Error-handling closure.
private let closure: (Request, Error) -> (Response)
/// Create a new `ErrorMiddleware`.
///
/// - parameters:
/// - closure: Error-handling closure. Converts `Error` to `Response`.
public init(_ closure: @escaping (Request, Error) -> (Response)) {
self.closure = closure
}
/// See `Middleware`.
public func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
return next.respond(to: request).flatMapErrorThrowing { error in
return self.closure(request, error)
}
}
}
| 9bf6f2d45645fb738ffc85bc97e9922c | 40.298701 | 107 | 0.584591 | false | false | false | false |
zevwings/ZVRefreshing | refs/heads/master | ZVRefreshing/Footer/AutoFooter/ZVRefreshAutoNativeFooter.swift | mit | 1 | //
// ZVRefreshAutoDIYFooter.swift
// ZVRefreshing
//
// Created by zevwings on 2017/7/17.
// Copyright © 2017年 zevwings. All rights reserved.
//
import UIKit
public class ZVRefreshAutoNativeFooter: ZVRefreshAutoStateFooter {
// MARK: - Property
private var activityIndicator: UIActivityIndicatorView?
public var activityIndicatorViewStyle: UIActivityIndicatorView.Style = .gray {
didSet {
activityIndicator?.style = activityIndicatorViewStyle
setNeedsLayout()
}
}
// MARK: - Subviews
override public func prepare() {
super.prepare()
self.labelInsetLeft = 24.0
if activityIndicator == nil {
activityIndicator = UIActivityIndicatorView()
activityIndicator?.style = activityIndicatorViewStyle
activityIndicator?.hidesWhenStopped = true
activityIndicator?.color = .lightGray
addSubview(activityIndicator!)
}
}
override public func placeSubViews() {
super.placeSubViews()
if let activityIndicator = activityIndicator, activityIndicator.constraints.isEmpty {
var activityIndicatorCenterX = frame.width * 0.5
if let stateLabel = stateLabel, !stateLabel.isHidden {
let leftPadding = stateLabel.textWidth * 0.5 +
labelInsetLeft +
activityIndicator.frame.width * 0.5
activityIndicatorCenterX -= leftPadding
}
let activityIndicatorCenterY = frame.height * 0.5
activityIndicator.center = CGPoint(x: activityIndicatorCenterX, y: activityIndicatorCenterY)
}
}
// MARK: - State Update
open override func refreshStateUpdate(
_ state: ZVRefreshControl.RefreshState,
oldState: ZVRefreshControl.RefreshState
) {
super.refreshStateUpdate(state, oldState: oldState)
switch state {
case .idle, .noMoreData:
activityIndicator?.stopAnimating()
case .refreshing:
activityIndicator?.startAnimating()
default:
break
}
}
}
| 8ba7587e59b1844350d4fcfc9dad5886 | 28.76 | 104 | 0.610663 | false | false | false | false |
beneiltis/SwiftCharts | refs/heads/master | Examples/Examples/Examples/MultipleLabelsExample.swift | apache-2.0 | 4 | //
// MultipleLabelsExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
class MultipleLabelsExample: UIViewController {
private var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let cp1 = ChartPoint(x: MyMultiLabelAxisValue(myVal: 2), y: ChartAxisValueFloat(2))
let cp2 = ChartPoint(x: MyMultiLabelAxisValue(myVal: 4), y: ChartAxisValueFloat(6))
let cp3 = ChartPoint(x: MyMultiLabelAxisValue(myVal: 5), y: ChartAxisValueFloat(12))
let cp4 = ChartPoint(x: MyMultiLabelAxisValue(myVal: 8), y: ChartAxisValueFloat(4))
let chartPoints = [cp1, cp2, cp3, cp4]
let xValues = chartPoints.map{$0.x}
let yValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueFloat($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
let chartSettings = ExamplesDefaults.chartSettings
chartSettings.trailing = 20
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.redColor(), lineWidth: 1, animDuration: 1, animDelay: 0)
let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel])
var settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings)
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
chartPointsLineLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
private class MyMultiLabelAxisValue: ChartAxisValue {
private let myVal: Int
private let derivedVal: Double
init(myVal: Int) {
self.myVal = myVal
self.derivedVal = Double(myVal) / 5.0
super.init(scalar: Double(myVal))
}
override var labels:[ChartAxisLabel] {
return [
ChartAxisLabel(text: "\(self.myVal)", settings: ChartLabelSettings(font: UIFont.systemFontOfSize(18), fontColor: UIColor.blackColor())),
ChartAxisLabel(text: "blabla", settings: ChartLabelSettings(font: UIFont.systemFontOfSize(10), fontColor: UIColor.blueColor())),
ChartAxisLabel(text: "\(self.derivedVal)", settings: ChartLabelSettings(font: UIFont.systemFontOfSize(14), fontColor: UIColor.purpleColor()))
]
}
}
| e001a26deecce8f78d32b52e6f844140 | 44.153846 | 258 | 0.68711 | false | false | false | false |
sarvex/SwiftRecepies | refs/heads/master | CalendarsEvents/Constructing Date Objects/Constructing Date Objects/AppDelegate.swift | isc | 1 | //
// AppDelegate.swift
// Constructing Date Objects
//
// Created by Vandad Nahavandipoor on 6/23/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
enum GregorianEra: Int{
case BC = 0
case AD
}
func example1(){
let date = NSCalendar.currentCalendar().dateWithEra(GregorianEra.AD.rawValue,
year: 2014,
month: 12,
day: 25,
hour: 10,
minute: 20,
second: 30,
nanosecond: 40)
if date != nil{
println("The date is \(date)")
} else {
println("Could not construct the date")
}
}
func example2(){
let now = NSDate()
println(now)
let newDate = NSCalendar.currentCalendar().dateByAddingUnit(
.CalendarUnitHour,
value: 10,
toDate: now,
options:.MatchNextTime)
println(newDate)
}
func example3(){
let now = NSDate()
let components = NSCalendar.currentCalendar().componentsInTimeZone(
NSTimeZone.localTimeZone(), fromDate: now)
dump(components)
}
func example4(){
var components = NSDateComponents()
components.year = 2015
components.month = 3
components.day = 20
components.hour = 10
components.minute = 20
components.second = 30
let date = NSCalendar.currentCalendar().dateFromComponents(components)
println(date)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
example4()
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
// Override point for customization after application launch.
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
}
| 41f21d26da06acac50a921b76312a76f | 24.466667 | 126 | 0.668661 | false | false | false | false |
denrase/TimeTracking-iOS | refs/heads/master | TimeTracking/EndpointSelectionViewController.swift | mit | 1 | //
// EndpointSelectionViewController.swift
// TimeTracking
//
// Created by Denis Andrasec on 27.06.15.
// Copyright (c) 2015 Bytepoets. All rights reserved.
//
import UIKit
class EndpointSelectionViewController: UITableViewController {
var didSelectEndpoint: ((endpoint: String) -> Void)?
var endpoints = [Endpoint]()
override func viewDidLoad() {
super.viewDidLoad()
endpoints = Configuration.endpoints()
preferredContentSize = CGSizeMake(CGFloat(280), min(CGFloat(endpoints.count * 44), CGFloat(6*44 + 22)))
tableView.reloadData()
}
// MARK: UITableViewDelegate
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return endpoints.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let endpoint = endpoints[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("EndpointCell") as! UITableViewCell
cell.textLabel?.text = endpoint.name
cell.detailTextLabel?.text = endpoint.url
return cell
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let endpoint = endpoints[indexPath.row]
didSelectEndpoint?(endpoint: endpoint.url)
dismissViewControllerAnimated(true, completion: nil)
}
}
| 62d88114d0a93e04e29c579ee3e8debe | 30.705882 | 118 | 0.679654 | false | false | false | false |
tluquet3/MonTennis | refs/heads/master | MonTennis/Profile/ClassementTableViewController.swift | apache-2.0 | 1 | //
// ClassementTableViewController.swift
// MonTennis
//
// Created by Thomas Luquet on 30/06/2015.
// Copyright (c) 2015 Thomas Luquet. All rights reserved.
//
import UIKit
class ClassementTableViewController: UITableViewController{
private var selectedClassement : String!
private let pickerData = ["NC","40","30/5","30/4","30/3","30/2","30/1","30","15/5","15/4","15/3","15/2","15/1","15","5/6","4/6","3/6","2/6","1/6","0","-2/6","-4/6","-15","N°60-100","N°40-60","1ère Serie"]
override func viewDidLoad() {
super.viewDidLoad()
self.selectedClassement = barCtrl.user.classement.string
let indexPath = NSIndexPath(forRow: barCtrl.user.classement.value, inSection: 0)
self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Middle, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "saveDetails"{
if let cell = sender as? UITableViewCell {
selectedClassement = cell.textLabel?.text
barCtrl.getNSuserDefaults().setInteger(Classement(stringValue: selectedClassement).value, forKey: "classement")
barCtrl.user.classement = Classement(stringValue: selectedClassement)
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return pickerData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("classementCell", forIndexPath: indexPath)
cell.textLabel?.text = pickerData[indexPath.row]
if(indexPath.row == barCtrl.user.classement.value){
cell.textLabel?.textColor = UIColor.orangeColor()
cell.accessoryType = .Checkmark
}else{
cell.accessoryType = .None
cell.textLabel?.textColor = UIColor.blackColor()
}
return cell
}
}
| 2178bea77e38ae35ba19821b854edc7b | 37.38806 | 208 | 0.633359 | false | false | false | false |
liuweicode/LinkimFoundation | refs/heads/master | Example/LinkimFoundation/Foundation/UI/UIImageView/UIImageView+Cache.swift | mit | 1 | //
// UIImageView+Cache.swift
// Pods
//
// Created by Vic on 16/7/4.
//
//
import Foundation
import UIKit
import AlamofireImage
import Alamofire
typealias CacheImageCompletedBlock = (image: UIImage?, error: NSError?) -> Void
typealias CacheImageProgressBlock = (receivedSize: Int, expectedSize: Int) -> Void
public enum LoadImageAnimationType: Int {
case AnimationNone
case AnimationFadeIn
}
extension UIImageView {
/**
异步加载一张图片
- parameter URL: 图片URL
- parameter placeholderImage: 默认图片
- parameter filter: 过滤器
- parameter progress: 下载进度
- parameter progressQueue: 处理队列
- parameter imageTransition: 动画
- parameter runImageTransitionIfCached: 如果图片被缓存是否执行过渡动画
- parameter completion: 完成回调
*/
public func cacheWith(
URL: NSURL,
placeholderImage: UIImage? = nil,
filter: ImageFilter? = nil,
progress: ImageDownloader.ProgressHandler? = nil,
progressQueue: dispatch_queue_t = dispatch_get_main_queue(),
imageTransition: ImageTransition = .None,
runImageTransitionIfCached: Bool = false,
completion: (Response<UIImage, NSError> -> Void)? = nil)
{
self.af_setImageWithURL(URL, placeholderImage: placeholderImage, filter: filter, progress: progress, progressQueue: progressQueue, imageTransition: imageTransition, runImageTransitionIfCached: runImageTransitionIfCached, completion: completion)
}
} | a5f20d99cbf0869e980be21d506ffc69 | 31.645833 | 252 | 0.652618 | false | false | false | false |
amujic5/iVictim | refs/heads/master | iVictim/Application/AppDelegate.swift | gpl-3.0 | 1 | //
// AppDelegate.swift
// iVictim
//
// Created by Azzaro Mujic on 5/31/16
// Copyright (c) 2016 . All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let imageView = UIImageView()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
imageView.image = UIImage(named: "screen_image")
window = UIWindow()
let navigationController = UINavigationController()
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
let mainWireframe = MainWireframe(navigationController: navigationController)
mainWireframe.showHomeScreen()
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
if let value = UserDefaults.standard.object(forKey: "hideWindow") as? Bool, value {
if let window = window {
window.addSubview(imageView)
imageView.frame = window.bounds
}
}
}
func applicationWillEnterForeground(_ application: UIApplication) {
imageView.removeFromSuperview()
}
// 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 "com.infinum.a" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1] as NSURL
}()
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 = Bundle.main.url(forResource: "CoreDataSensitiveModel", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: 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.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject
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()
}
}
}}
| 194c15080739ea4a95ee9e74916a4691 | 46.163636 | 291 | 0.680224 | false | false | false | false |
BlackSourceLabs/BlackNectar-iOS | refs/heads/develop | BlackNectar/BlackNectar/GlobalLocationManager.swift | apache-2.0 | 1 | //
// GlobalLocationManager.swift
// BlackNectar
//
// Created by Cordero Hernandez on 11/28/16.
// Copyright © 2017 BlackSource. All rights reserved.
//
import Archeota
import AromaSwiftClient
import CoreLocation
import Foundation
import MapKit
import UIKit
class UserLocation: NSObject, CLLocationManagerDelegate, MKMapViewDelegate {
static let instance = UserLocation()
private override init() {}
private var alreadyInitialized = false
private var onLocation: ((CLLocationCoordinate2D) -> Void)?
var locationManager: CLLocationManager!
var currentLocation: CLLocation?
var currentRegion: MKCoordinateRegion?
var currentStatus: CLAuthorizationStatus?
var currentCoordinate: CLLocationCoordinate2D? {
return currentLocation?.coordinate
}
func initialize() {
if alreadyInitialized {
LOG.info("Location Manager already initialized")
return
}
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
alreadyInitialized = true
}
func requestLocation(callback: @escaping ((CLLocationCoordinate2D) -> Void)) {
if !alreadyInitialized {
initialize()
}
self.onLocation = callback
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location: CLLocation = locations.first else {
makeNoteThatFailedToGetLocation()
return
}
defer {
locationManager.stopUpdatingLocation()
}
self.currentLocation = location
let region = calculateRegion(for: location.coordinate)
self.currentRegion = region
onLocation?(location.coordinate)
onLocation = nil
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
makeNoteThatAccessIsRestricted()
case .denied:
makeNoteThatAccessIsDenied()
case .authorizedWhenInUse, .authorizedAlways:
makeNoteThatAccessGranted(status)
default:
makeNoteThatAccessIsUndetermined()
}
self.currentStatus = status
}
internal func calculateRegion(for location: CLLocationCoordinate2D) -> MKCoordinateRegion {
let latitude = location.latitude
let longitude = location.longitude
let latDelta: CLLocationDegrees = 0.05
let longDelta: CLLocationDegrees = 0.05
let span = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: longDelta)
let location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let region = MKCoordinateRegion(center: location, span: span)
return region
}
}
fileprivate extension UserLocation {
func makeNoteThatFailedToGetLocation() {
LOG.error("Failed to load the user's location")
AromaClient.beginMessage(withTitle: "Failed To Load Location")
.addBody("Failed to load the user's location")
.withPriority(.high)
.send()
}
func makeNoteThatAccessIsRestricted() {
LOG.warn("User restricted access to Location")
AromaClient.beginMessage(withTitle: "User Location Access Restricted")
.addBody("The User has restricted access to their locaiton")
.withPriority(.high)
.send()
}
func makeNoteThatAccessIsDenied() {
LOG.warn("User denied access to location")
AromaClient.beginMessage(withTitle: "User Location Access Denied")
.addBody("User denied permission to access their location")
.withPriority(.medium)
.send()
}
func makeNoteThatAccessGranted(_ status: CLAuthorizationStatus) {
LOG.warn("User allowed access to location: \(status.name)")
AromaClient.beginMessage(withTitle: "User Location Access Granted")
.addBody("User granted authorization to use their location: \(status)")
.withPriority(.low)
.send()
}
func makeNoteThatAccessIsUndetermined() {
LOG.warn("User status not determined")
AromaClient.beginMessage(withTitle: "User Location Access Undetermined")
.addBody("The user has not yet made a choice regarding whether this app can use location services")
.withPriority(.medium)
.send()
}
}
fileprivate extension CLAuthorizationStatus {
var name: String {
switch self {
case .authorizedAlways : return "(authorizedAlways)"
case .authorizedWhenInUse : return "(authorizedWhenInUse)"
case .denied : return "(denied)"
case .notDetermined : return "(notDetermined)"
case .restricted : return "(restricted)"
}
}
}
| bccfefdeb85fcaa6b14dc3379a17ec56 | 28.546875 | 111 | 0.60832 | false | false | false | false |
microeditionbiz/ML-client | refs/heads/master | ML-client/Model/Installments.swift | mit | 1 | //
// Installments.swift
//
// Created by Pablo Romero on 8/13/17
// Copyright (c) . All rights reserved.
//
import Foundation
import ObjectMapper
public class Installments: Mappable {
public class Issuer: Mappable {
private struct SerializationKeys {
static let name = "name"
static let id = "id"
static let thumbnail = "thumbnail"
static let secureThumbnail = "secure_thumbnail"
}
public var name: String?
public var id: String?
public var thumbnail: String?
public var secureThumbnail: String?
public required init?(map: Map) {
}
public func mapping(map: Map) {
name <- map[SerializationKeys.name]
id <- map[SerializationKeys.id]
thumbnail <- map[SerializationKeys.thumbnail]
secureThumbnail <- map[SerializationKeys.secureThumbnail]
}
}
public class PayerCost: Mappable {
private struct SerializationKeys {
static let discountRate = "discount_rate"
static let labels = "labels"
static let installmentRate = "installment_rate"
static let installmentAmount = "installment_amount"
static let minAllowedAmount = "min_allowed_amount"
static let installmentRateCollector = "installment_rate_collector"
static let totalAmount = "total_amount"
static let maxAllowedAmount = "max_allowed_amount"
static let recommendedMessage = "recommended_message"
static let installments = "installments"
}
public var discountRate: Int?
public var labels: [String]?
public var installmentRate: Float?
public var installmentAmount: Float?
public var minAllowedAmount: Int?
public var installmentRateCollector: [String]?
public var totalAmount: Float?
public var maxAllowedAmount: Int?
public var recommendedMessage: String?
public var installments: Int?
public required init?(map: Map) {
}
public func mapping(map: Map) {
discountRate <- map[SerializationKeys.discountRate]
labels <- map[SerializationKeys.labels]
installmentRate <- map[SerializationKeys.installmentRate]
installmentAmount <- map[SerializationKeys.installmentAmount]
minAllowedAmount <- map[SerializationKeys.minAllowedAmount]
installmentRateCollector <- map[SerializationKeys.installmentRateCollector]
totalAmount <- map[SerializationKeys.totalAmount]
maxAllowedAmount <- map[SerializationKeys.maxAllowedAmount]
recommendedMessage <- map[SerializationKeys.recommendedMessage]
installments <- map[SerializationKeys.installments]
}
}
private struct SerializationKeys {
static let issuer = "issuer"
static let paymentMethodId = "payment_method_id"
static let paymentTypeId = "payment_type_id"
static let processingMode = "processing_mode"
static let payerCosts = "payer_costs"
}
public var issuer: Issuer?
public var paymentMethodId: String?
public var paymentTypeId: String?
public var processingMode: String?
public var payerCosts: [PayerCost]?
public required init?(map: Map) {
}
public func mapping(map: Map) {
issuer <- map[SerializationKeys.issuer]
paymentMethodId <- map[SerializationKeys.paymentMethodId]
paymentTypeId <- map[SerializationKeys.paymentTypeId]
processingMode <- map[SerializationKeys.processingMode]
payerCosts <- map[SerializationKeys.payerCosts]
}
}
| d78eca4e71b287f58544cc6fa7801599 | 33.783784 | 87 | 0.626522 | false | false | false | false |
yeziahehe/Gank | refs/heads/master | Gank/Helpers/GankLogger.swift | gpl-3.0 | 1 | //
// GankLogger.swift
// Gank
//
// Created by 叶帆 on 2016/11/1.
// Copyright © 2016年 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
import Foundation
import XCGLogger
let gankLog: XCGLogger = {
let gankLog = XCGLogger(identifier: "gank", includeDefaultDestinations: false)
// Create a console log destination
let consoleDestination = ConsoleDestination(identifier: "gank.consoleDestination")
consoleDestination.haveLoggedAppDetails = true
// Create a file log destination
let logPath: URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("gank.log")
let fileDestination = FileDestination(writeToFile: logPath, identifier: "gank.fileDestination")
fileDestination.haveLoggedAppDetails = true
fileDestination.logQueue = XCGLogger.logQueue
gankLog.add(destination: consoleDestination)
gankLog.add(destination: fileDestination)
return gankLog
}()
| 1b63f7b4c1dcab9f5b2632fd77e5fd56 | 32.233333 | 133 | 0.74323 | false | false | false | false |
Pluto-Y/SwiftyEcharts | refs/heads/master | SwiftyEcharts/Tools/Echarts.swift | mit | 1 | //
// Echarts.swift
// SwiftyEcharts
//
// Created by Pluto Y on 09/09/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
import JavaScriptCore
/// 用于封装一些通用的Echarts提供的工具
public final class Echarts {
/// SwiftyEcharts.framework的位置
public static let frameworkBundle: Bundle? = {
if let bundlePath = Bundle.main.path(forResource: "SwiftyEcharts", ofType: "framework", inDirectory: "Frameworks") {
return Bundle(path: bundlePath)!
}
// 避免不在Frameworks目录下的情况, 例如在unit test中就不出现在Framework下
for bundle in Bundle.allBundles {
if let bundlePath = bundle.path(forResource: "SwiftyEcharts", ofType: "framework") {
return Bundle(path: bundlePath)!
}
}
return nil
}()
/// 加载echart.min.js的内容到JSContext中
///
/// - Parameter context: 需要加载到的JSContext
public static func loadEcharts(_ context: JSContext) {
guard let echartScriptPath = frameworkBundle?.path(forResource: "echarts.min", ofType: "js", inDirectory: "js"), let echartsScripts = try? String(contentsOfFile: echartScriptPath) else {
return
}
context.evaluateScript(echartsScripts)
}
}
// MARK: DataTool
extension Echarts {
/// 针对DataTool模块的封装
public class DataTool {
/// 加载dataTool.js模块到JSContext中
///
/// - Parameter context: 需要加载到的JSContext
public static func loadDataTool(_ context: JSContext) {
guard let scriptPath = frameworkBundle?.path(forResource: "dataTool", ofType: "js", inDirectory: "js"), let scripts = try? String(contentsOfFile: scriptPath) else {
return
}
Echarts.loadEcharts(context)
context.evaluateScript(scripts)
}
/// 执行echarts.dataTool.prepareBoxplotData的方法,并将返回值获得用于给业务层用
///
/// - Parameters:
/// - datas: 需要执行该方法的数据
/// - option: 可以配置的项目,可以配置为选项有'boundIQR'的选项以及'layout'选项
/// 其中 `layout` 可以配置为 'horizontal' 或 'vertical' 用于 Boxplot 的布局
/// 其中 `boundIQR` 用来配置小于该值的是 outlier 的值,默认是1.5, 意思是: Q1 - 1.5 * (Q3 - Q1),
/// - Notes: 虽然 `boundIQR` 配置的是数值,但是应该以字符串传入
/// - Returns: 转换后的数据
public static func prepareBoxplotData(_ datas: [[Float]], _ option: [String: String] = [:]) -> [String: [Jsonable]] {
guard let context = JSContext(virtualMachine: JSVirtualMachine()) else {
return [:]
}
self.loadDataTool(context)
let scriptResult = context.evaluateScript("echarts.dataTool.prepareBoxplotData(\(datas), \(option.jsonString))")
guard let sr = scriptResult, !sr.isUndefined , sr.isObject else {
return [:]
}
let scriptResultDic = scriptResult?.toDictionary() as! [String: NSArray]
var result: [String: [Jsonable]] = [:]
var outliers: [[Jsonable]] = []
for outer in scriptResultDic["outliers"]! {
var innerArr: [Jsonable] = []
for inner in outer as! NSArray {
innerArr.append(inner as! Float)
}
outliers.append(innerArr)
}
result["outliers"] = outliers.map { $0 as Jsonable }
var axisDatas: [String] = []
for axisData in scriptResultDic["axisData"]! {
axisDatas.append(axisData as! String)
}
result["axisData"] = axisDatas.map { $0 as Jsonable }
var boxDatas: [[Jsonable]] = []
for outer in scriptResultDic["boxData"]! {
var innerArr: [Jsonable] = []
for inner in outer as! NSArray {
innerArr.append(inner as! Float)
}
boxDatas.append(innerArr)
}
result["boxData"] = boxDatas.map { $0 as Jsonable }
return result
}
}
}
| 2a80e669c9e21e370427f7f2675420c4 | 37.836538 | 194 | 0.560535 | false | false | false | false |
HabitRPG/habitrpg-ios | refs/heads/develop | HabitRPG/Extensions/UIApplication-Extensions.swift | gpl-3.0 | 1 | //
// UIApplication-Extensions.swift
// Habitica
//
// Created by Phillip on 29.08.17.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import UIKit
extension UIApplication {
class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(base: selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base
}
}
| 9bb707e18d691d7020de40ef07b8f578 | 29.807692 | 133 | 0.650437 | false | false | false | false |
vernon99/Gamp | refs/heads/master | Gamp/GACardView.swift | gpl-3.0 | 1 | //
// GACardView.swift
// Gamp
//
// Created by Mikhail Larionov on 7/19/14.
// Copyright (c) 2014 Mikhail Larionov. All rights reserved.
//
import UIKit
class GACardView: UIView {
var loadingStarted = false
var buildString: String? = nil {
didSet{
if let build = buildString
{
labelBuild.text = labelBuild.text + build
}
}
}
var startDate: NSDate = NSDate()
var endDate: NSDate = NSDate()
{
didSet{
}
}
@IBOutlet weak var labelLifetime: UILabel!
@IBOutlet weak var labelARPDAU: UILabel!
@IBOutlet weak var labelLTV: UILabel!
@IBOutlet weak var lineChart: PNLineChart!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var labelBuild: UILabel!
@IBOutlet weak var labelStatus: UILabel!
class func instanceFromNib() -> GACardView {
var result:UINib = UINib(nibName: "GACardView", bundle: NSBundle.mainBundle())
var array = result.instantiateWithOwner(nil, options: nil)
return array[0] as GACardView
}
func prepare()
{
// Setup chart
lineChart.setDefaultValues()
lineChart.yLabelFormat = "%1.2f"
lineChart.showLabel = true
lineChart.yValueStartsFromZero = true
lineChart.showCoordinateAxis = false
lineChart.yLabelMaxCount = 10
lineChart.clipsToBounds = false
}
func load() {
loadingStarted = true
// Start animating
activityIndicator.startAnimating()
// Fetch data
var collection = GACohortDataCollection(build:buildString, start:startDate, end:endDate)
collection.startLoading({
// Stop animating
dispatch_async(dispatch_get_main_queue(), {
self.activityIndicator.stopAnimating()
})
// Check if the params were set up
if gameId == "NUMBER_HERE"
{
self.labelStatus.hidden = false;
self.labelStatus.text = "You haven't set game id and secret, check Config.swift file"
return
}
// Check data
var retentionArray = collection.averageRetentionByDay
if retentionArray.count < 2
{
self.labelStatus.hidden = false
self.labelStatus.text = "Insufficient data, need at least two days from build launch"
return
}
// Add estimated data to historical if needed
var estimation:Array<Float> = []
if let retentionDecay = collection.retentionDecay
{
estimation = retentionDecay.dataForDaysTill(maximumRetentionDays)
for var n = retentionArray.count; n < estimation.count; n++
{
retentionArray.append(estimation[n])
}
}
// Create charts
var arrayDays:[String] = [];
var counter:Int = 0
for point in retentionArray
{
if counter % 5 == 0 {
arrayDays.append(String(counter))
}
else {
arrayDays.append("")
}
counter++
}
// Historical chart
var historicalData = PNLineChartData()
historicalData.inflexionPointStyle = PNLineChartData.PNLineChartPointStyle.PNLineChartPointStyleNone
historicalData.color = PNGreenColor
historicalData.itemCount = retentionArray.count
historicalData.getData = ({(index: Int) -> PNLineChartDataItem in
var item = PNLineChartDataItem()
item.y = CGFloat(retentionArray[index] as NSNumber)
return item
})
// Estimated chart
var estimatedData = PNLineChartData()
estimatedData.inflexionPointStyle = PNLineChartData.PNLineChartPointStyle.PNLineChartPointStyleNone
estimatedData.color = PNGreyColor
estimatedData.itemCount = estimation.count
estimatedData.getData = ({(index: Int) -> PNLineChartDataItem in
var item = PNLineChartDataItem()
item.y = CGFloat(estimation[index] as Float)
return item
})
// Redraw in the main thread
dispatch_async(dispatch_get_main_queue(), {
// Key numbers
self.labelLifetime.text = NSString(format:"%.2f d", collection.userLifetime)
self.labelARPDAU.text = NSString(format:"$%.3f", collection.averageARPDAU)
self.labelLTV.text = NSString(format:"$%.3f", collection.lifetimeValue)
// Chart
self.lineChart.xLabels = arrayDays
self.lineChart.chartData = [estimatedData, historicalData]
self.lineChart.strokeChart()
})
})
}
}
| 2374834dfacd38fef47a768bcf61ebf9 | 33.207792 | 112 | 0.54385 | false | false | false | false |
HPE-Haven-OnDemand/havenondemand-ios-swift | refs/heads/master | HODClient/lib/HODResponseParser.swift | mit | 1 | //
// HODResponseParser.swift
// Parse HOD API Responses
//
// Created by MAC_USER on 9/25/15.
// Copyright (c) 2015 PhongVu. All rights reserved.
//
import Foundation
public struct HODErrorCode {
static let IN_PROGRESS = 1610
static let QUEUED = 1620
static let NONSTANDARD_RESPONSE = 1630
static let INVALID_PARAM = 1640
static let INVALID_HOD_RESPONSE = 1650
static let UNKNOWN_ERROR = 1660
}
public class HODResponseParser
{
var hodErrors : NSMutableArray = []
public init() {
}
public func GetLastError() -> NSMutableArray
{
return hodErrors
}
private func resetErrors()
{
hodErrors.removeAllObjects()
}
private func addError(error : HODErrorObject)
{
hodErrors.addObject(error)
}
public func ParseJobID(jsonStr:String) -> String?
{
var jobID : String?
if (jsonStr.characters.count != 0) {
let resStr = jsonStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let data = (resStr as NSString).dataUsingEncoding(NSUTF8StringEncoding)
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
guard let _ :NSDictionary = json as? NSDictionary else {
return jobID
}
jobID = json.valueForKey("jobID") as? String
}
catch {
return jobID
}
}
return jobID
}
public func getResult(inout jsonStr:String) -> String?
{
resetErrors()
var result = jsonStr
if (jsonStr.characters.count == 0) {
let err = String(format: "%@%d%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"Empty response.\"}"])
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let jsonObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: jsonObj)
addError(hodError)
return nil
}
let resStr = jsonStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let data = (resStr as NSString).dataUsingEncoding(NSUTF8StringEncoding)
do {
let jsonObj = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
guard let _ :NSDictionary = jsonObj as? NSDictionary else {
let err = String(format: "%@%d%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"Invalid json response.\"}"])
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let jsonObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: jsonObj)
addError(hodError)
return nil
}
if let actions = jsonObj["actions"] as? NSArray {
let status = actions[0].valueForKey("status") as? String
if status == "finished" || status == "FINISHED" {
let jsonData: NSData?
do {
jsonData = try NSJSONSerialization.dataWithJSONObject((actions[0].valueForKey("result") as? NSDictionary)!, options: [])
result = NSString(data: jsonData!, encoding: NSUTF8StringEncoding)! as String
} catch let error as NSError {
let err = String(format: "%@%d%@%@%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"", error.localizedDescription, "\"}"])
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: errorObj)
addError(hodError)
return nil
}
} else if status == "failed" {
let errors = actions[0].valueForKey("errors") as! NSArray
for item in errors {
let hodError = HODErrorObject(json: item as! NSDictionary)
addError(hodError)
}
return nil
} else if status == "queued" {
var jobID = jsonObj.valueForKey("jobID") as? String
jobID = jobID!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let err = String(format: "%@%d%@%@%@", "{\"error\":", HODErrorCode.QUEUED,",\"reason\":\"Task is in queue\",\"jobID\":\"", jobID!, "\"}")
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: errorObj)
addError(hodError)
return nil
} else if status == "in progress" {
var jobID = jsonObj.valueForKey("jobID") as? String
jobID = jobID!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let err = String(format: "%@%d%@%@%@", "{\"error\":",HODErrorCode.IN_PROGRESS,",\"reason\":\"Task is in progress\",\"jobID\":\"", jobID!, "\"}")
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: errorObj)
addError(hodError)
return nil
} else {
let err = String(format: "%@%d%@%@", "{\"error\":",HODErrorCode.UNKNOWN_ERROR,",\"reason\":\"", status!, "\"}")
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: errorObj)
addError(hodError)
return nil
}
} else {
// handle error for sync mode
var isError = false
for (key, _) in jsonObj as! NSDictionary {
if key as! String == "error" {
let hodError = HODErrorObject(json: jsonObj as! NSDictionary)
addError(hodError)
isError = true
}
}
if isError == true {
return nil
}
}
}
catch {
let err = String(format: "%@%d%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"Invalid json response\"}"])
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: errorObj)
addError(hodError)
return nil
}
return result
}
private func logParserError(error:NSError) {
let err = String(format: "%@%d%@%@", "{\"error\":",HODErrorCode.INVALID_HOD_RESPONSE,",\"reason\":\"", error.localizedDescription, "\"}")
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: errorObj)
addError(hodError)
}
public func ParseSpeechRecognitionResponse(inout jsonStr:String) -> SpeechRecognitionResponse?
{
var obj : SpeechRecognitionResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = SpeechRecognitionResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseCancelConnectorScheduleResponse(inout jsonStr:String) -> CancelConnectorScheduleResponse?
{
var obj : CancelConnectorScheduleResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = CancelConnectorScheduleResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseConnectorHistoryResponse(inout jsonStr:String) -> ConnectorHistoryResponse?
{
var obj : ConnectorHistoryResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = ConnectorHistoryResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseConnectorStatusResponse(inout jsonStr:String) -> ConnectorStatusResponse?
{
var obj : ConnectorStatusResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = ConnectorStatusResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseCreateConnectorResponse(inout jsonStr:String) -> CreateConnectorResponse?
{
var obj : CreateConnectorResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = CreateConnectorResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseDeleteConnectorResponse(inout jsonStr:String) -> DeleteConnectorResponse?
{
var obj : DeleteConnectorResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = DeleteConnectorResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseRetrieveConnectorConfigurationAttrResponse(inout jsonStr:String) -> RetrieveConnectorConfigurationAttrResponse?
{
var obj : RetrieveConnectorConfigurationAttrResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = RetrieveConnectorConfigurationAttrResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseRetrieveConnectorConfigurationFileResponse(inout jsonStr:String) -> RetrieveConnectorConfigurationFileResponse?
{
var obj : RetrieveConnectorConfigurationFileResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = RetrieveConnectorConfigurationFileResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseStartConnectorResponse(inout jsonStr:String) -> StartConnectorResponse?
{
var obj : StartConnectorResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = StartConnectorResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseStopConnectorResponse(inout jsonStr:String) -> StopConnectorResponse?
{
var obj : StopConnectorResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = StopConnectorResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseUpdateConnectorResponse(inout jsonStr:String) -> UpdateConnectorResponse?
{
var obj : UpdateConnectorResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = UpdateConnectorResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseExpandContainerResponse(inout jsonStr:String) -> ExpandContainerResponse?
{
var obj : ExpandContainerResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = ExpandContainerResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseStoreObjectResponse(inout jsonStr:String) -> StoreObjectResponse?
{
var obj : StoreObjectResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = StoreObjectResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseViewDocumentResponse(inout jsonStr:String) -> ViewDocumentResponse?
{
var obj : ViewDocumentResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = ViewDocumentResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseGetCommonNeighborsResponse(inout jsonStr:String) -> GetCommonNeighborsResponse?
{
var obj : GetCommonNeighborsResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = GetCommonNeighborsResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseGetNeighborsResponse(inout jsonStr:String) -> GetNeighborsResponse?
{
var obj : GetNeighborsResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = GetNeighborsResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseGetNodesResponse(inout jsonStr:String) -> GetNodesResponse?
{
var obj : GetNodesResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = GetNodesResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseGetShortestPathResponse(inout jsonStr:String) -> GetShortestPathResponse?
{
var obj : GetShortestPathResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = GetShortestPathResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseGetSubgraphResponse(inout jsonStr:String) -> GetSubgraphResponse?
{
var obj : GetSubgraphResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = GetSubgraphResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseSuggestLinksResponse(inout jsonStr:String) -> SuggestLinksResponse?
{
var obj : SuggestLinksResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = SuggestLinksResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseSummarizeGraphResponse(inout jsonStr:String) -> SummarizeGraphResponse?
{
var obj : SummarizeGraphResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = SummarizeGraphResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseOCRDocumentResponse(inout jsonStr:String) -> OCRDocumentResponse?
{
var obj : OCRDocumentResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = OCRDocumentResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseRecognizeBarcodesResponse(inout jsonStr:String) -> RecognizeBarcodesResponse?
{
var obj : RecognizeBarcodesResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = RecognizeBarcodesResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseDetectFacesResponse(inout jsonStr:String) -> DetectFacesResponse?
{
var obj : DetectFacesResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = DetectFacesResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseRecognizeImagesResponse(inout jsonStr:String) -> RecognizeImagesResponse?
{
var obj : RecognizeImagesResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = RecognizeImagesResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParsePredictResponse(inout jsonStr:String) -> PredictResponse?
{
var obj : PredictResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = PredictResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseRecommendResponse(inout jsonStr:String) -> RecommendResponse?
{
var obj : RecommendResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = RecommendResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseTrainPredictorResponse(inout jsonStr:String) -> TrainPredictorResponse?
{
var obj : TrainPredictorResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = TrainPredictorResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseCreateQueryProfileResponse(inout jsonStr:String) -> CreateQueryProfileResponse?
{
var obj : CreateQueryProfileResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = CreateQueryProfileResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseDeleteQueryProfileResponse(inout jsonStr:String) -> DeleteQueryProfileResponse?
{
var obj : DeleteQueryProfileResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = DeleteQueryProfileResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseRetrieveQueryProfileResponse(inout jsonStr:String) -> RetrieveQueryProfileResponse?
{
var obj : RetrieveQueryProfileResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = RetrieveQueryProfileResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseUpdateQueryProfileResponse(inout jsonStr:String) -> UpdateQueryProfileResponse?
{
var obj : UpdateQueryProfileResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = UpdateQueryProfileResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseFindRelatedConceptsResponse(inout jsonStr:String) -> FindRelatedConceptsResponse?
{
var obj : FindRelatedConceptsResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = FindRelatedConceptsResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseAutoCompleteResponse(inout jsonStr:String) -> AutoCompleteResponse?
{
var obj : AutoCompleteResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = AutoCompleteResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseExtractConceptsResponse(inout jsonStr:String) -> ExtractConceptsResponse?
{
var obj : ExtractConceptsResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = ExtractConceptsResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseExpandTermsResponse(inout jsonStr:String) -> ExpandTermsResponse?
{
var obj : ExpandTermsResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = ExpandTermsResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseHighlightTextResponse(inout jsonStr:String) -> HighlightTextResponse?
{
var obj : HighlightTextResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = HighlightTextResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseIdentifyLanguageResponse(inout jsonStr:String) -> IdentifyLanguageResponse?
{
var obj : IdentifyLanguageResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = IdentifyLanguageResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseSentimentAnalysisResponse(inout jsonStr:String) -> SentimentAnalysisResponse?
{
var obj : SentimentAnalysisResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = SentimentAnalysisResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseTokenizeTextResponse(inout jsonStr:String) -> TokenizeTextResponse?
{
var obj : TokenizeTextResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = TokenizeTextResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseAddToTextIndexResponse(inout jsonStr:String) -> AddToTextIndexResponse?
{
var obj : AddToTextIndexResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = AddToTextIndexResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseCreateTextIndexResponse(inout jsonStr:String) -> CreateTextIndexResponse?
{
var obj : CreateTextIndexResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = CreateTextIndexResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseDeleteTextIndexResponse(inout jsonStr:String) -> DeleteTextIndexResponse?
{
var obj : DeleteTextIndexResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = DeleteTextIndexResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseDeleteFromTextIndexResponse(inout jsonStr:String) -> DeleteFromTextIndexResponse?
{
var obj : DeleteFromTextIndexResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = DeleteFromTextIndexResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseIndexStatusResponse(inout jsonStr:String) -> IndexStatusResponse?
{
var obj : IndexStatusResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = IndexStatusResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseListResourcesResponse(inout jsonStr:String) -> ListResourcesResponse?
{
var obj : ListResourcesResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = ListResourcesResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseRestoreTextIndexResponse(inout jsonStr:String) -> RestoreTextIndexResponse?
{
var obj : RestoreTextIndexResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = RestoreTextIndexResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseAnomalyDetectionResponse(inout jsonStr:String) -> AnomalyDetectionResponse?
{
var obj : AnomalyDetectionResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = AnomalyDetectionResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseTrendAnalysisResponse(inout jsonStr:String) -> TrendAnalysisResponse?
{
var obj : TrendAnalysisResponse!
if let result = getResult(&jsonStr) {
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let dic = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
obj = TrendAnalysisResponse(json:dic)
} catch let error as NSError {
logParserError(error)
}
}
return obj
}
public func ParseCustomResponse(inout jsonStr:String) -> NSDictionary?
{
resetErrors()
var obj : NSDictionary!
if (jsonStr.characters.count == 0) {
let err = String(format: "%@%d%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"Empty response.\"}"])
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let jsonObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: jsonObj)
addError(hodError)
return nil
}
let resStr = jsonStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let data = (resStr as NSString).dataUsingEncoding(NSUTF8StringEncoding)
do {
let jsonObj = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
guard let _ :NSDictionary = jsonObj as? NSDictionary else {
let err = String(format: "%@%d%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"Invalid json response.\"}"])
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let jsonObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: jsonObj)
addError(hodError)
return nil
}
var result = jsonStr
if let actions = jsonObj["actions"] as? NSArray {
let status = actions[0].valueForKey("status") as? String
if status == "finished" || status == "FINISHED" {
let jsonData: NSData?
do {
jsonData = try NSJSONSerialization.dataWithJSONObject((actions[0].valueForKey("result") as? NSDictionary)!, options: [])
result = NSString(data: jsonData!, encoding: NSUTF8StringEncoding)! as String
} catch let error as NSError {
let err = String(format: "%@%d%@%@%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"", error.localizedDescription, "\"}"])
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: errorObj)
addError(hodError)
return nil
}
} else if status == "failed" {
let errors = actions[0].valueForKey("errors") as! NSArray
for item in errors {
let hodError = HODErrorObject(json: item as! NSDictionary)
addError(hodError)
}
return nil
} else if status == "queued" {
var jobID = jsonObj.valueForKey("jobID") as? String
jobID = jobID!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let err = String(format: "%@%d%@%@%@", "{\"error\":", HODErrorCode.QUEUED,",\"reason\":\"Task is in queue\",\"jobID\":\"", jobID!, "\"}")
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: errorObj)
addError(hodError)
return nil
} else if status == "in progress" {
var jobID = jsonObj.valueForKey("jobID") as? String
jobID = jobID!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let err = String(format: "%@%d%@%@%@", "{\"error\":",HODErrorCode.IN_PROGRESS,",\"reason\":\"Task is in progress\",\"jobID\":\"", jobID!, "\"}")
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: errorObj)
addError(hodError)
return nil
} else {
let err = String(format: "%@%d%@%@", "{\"error\":",HODErrorCode.UNKNOWN_ERROR,",\"reason\":\"", status!, "\"}")
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: errorObj)
addError(hodError)
return nil
}
} else {
// handle error for sync mode
var isError = false
for (key, _) in jsonObj as! NSDictionary {
if key as! String == "error" {
let hodError = HODErrorObject(json: jsonObj as! NSDictionary)
addError(hodError)
isError = true
}
}
if isError {
return nil
}
}
do {
let data1 = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding)
obj = try NSJSONSerialization.JSONObjectWithData(data1!, options: []) as! NSDictionary
} catch let error as NSError {
let err = String(format: "%@%d%@%@", "{\"error\":",HODErrorCode.INVALID_HOD_RESPONSE,",\"reason\":\"", error.localizedDescription, "\"}")
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: errorObj)
addError(hodError)
return nil
}
}
catch {
let err = String(format: "%@%d%@", arguments: ["{\"error\":", HODErrorCode.INVALID_HOD_RESPONSE, ",\"reason\":\"Invalid json response\"}"])
let errData = (err as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let errorObj = (try! NSJSONSerialization.JSONObjectWithData(errData!, options: [])) as! NSDictionary
let hodError = HODErrorObject(json: errorObj)
addError(hodError)
return nil
}
return obj
}
} | f8a0f0c2ac80bdcd9814a7e252952334 | 44.425466 | 178 | 0.582065 | false | false | false | false |
subangstrom/Ronchi | refs/heads/master | MathFramework/Matrix.swift | gpl-3.0 | 1 |
//
// Matrix.swift
// Ronchigram
//
// Created by James LeBeau on 5/19/17.
// Copyright © 2017 The Handsome Microscopist. All rights reserved.
//
import Foundation
import Cocoa
import Accelerate
//MARK: - Constants
struct MatrixConstant {
static let elementwise = "element-wise"
static let product = "product"
}
struct MatrixOutput {
static let uint16 = 16
static let uint8 = 8
static let float = 32
}
infix operator .*
class Matrix: CustomStringConvertible, CustomPlaygroundQuickLookable{
//MARK: - Properties
let rows:Int
let columns:Int
let type:String
var real:Array<Float>
var imag:Array<Float>?
var count: Int {
return rows*columns
}
var complex: Bool {
if (imag as [Float]?) != nil{
return true
}else{
return false
}
}
var max:Complex {
var maxValue = Complex(0,0)
let length = vDSP_Length(count)
if type == "real"{
vDSP_maxv(real, 1, &maxValue.a, length)
}else {
vDSP_maxv(real, 1, &maxValue.a, length)
vDSP_maxv(imag!, 1, &maxValue.b, length)
}
return maxValue
}
var min:Complex {
var minValue = Complex(0,0)
let length = vDSP_Length(count)
if type == "real"{
vDSP_minv(real, 1, &minValue.a, length)
}else {
vDSP_minv(real, 1, &minValue.a, length)
vDSP_minv(imag!, 1, &minValue.b, length)
}
return minValue
}
// this currently doesn't really make sense
//MARK: - Initializers
init(_ rows:Int, _ columns:Int, _ type:String? = nil){
self.rows = rows
self.columns = columns
if let newType = type{
if(newType == "real"){
self.type = newType
real = Array(repeating: Float(0), count: rows*columns)
imag = nil
}else if (newType == "complex"){
self.type = newType
real = Array(repeating: Float(0), count: rows*columns)
imag = Array(repeating: Float(0), count: rows*columns)
}else{
self.type = "real"
real = Array(repeating: Float(0), count: rows*columns)
imag = nil
}
}else{
self.type = "real"
real = Array(repeating: Float(0), count: rows*columns)
imag = nil
}
}
class func identity(size:Int)->Matrix{
let newMat = Matrix(size, size)
for i in 0..<size{
newMat.set(i, i, 1.0)
}
return newMat
}
//MARK: - Matrix setters
// mutating func setRange(range:Range<Int>, values:[Any]){
//
// switch values {
// case let complexValue as [Complex]:
//
// real[index] = complexValue.a
// imag?[index] = complexValue.b
//
// case let floatValue as [Float]:
// real[index] = floatValue
// case let intValue as [Int]:
// real[index] = Float(intValue)
// case let doubleValue as [Double]:
// real[index] = Float(doubleValue)
// default:
// print("not a valid type")
// }
//
// }
func set(_ i:Int,_ j:Int,_ value:Any){
let index = columns*i+j
switch value {
case let complexValue as Complex:
real[index] = complexValue.a
imag?[index] = complexValue.b
case let floatValue as Float:
real[index] = floatValue
case let intValue as Int:
real[index] = Float(intValue)
case let doubleValue as Double:
real[index] = Float(doubleValue)
default:
print("not a valid type")
}
}
// TODO: Add capability to set a range with an array
func set(array:[Float], type:String ){
if(type == "real" && count == array.count){
self.real = array
}
}
func convert()->Matrix{
let newMat:Matrix
if complex{
newMat = Matrix(rows, columns)
newMat.real = real
newMat.imag = imag!
}else{
newMat = Matrix(rows, columns, "complex")
newMat.real = real
}
return newMat
}
//MARK: - Operations (replace values in this matrix)
func add(_ addMatrix:Matrix) {
guard self.sameSize(addMatrix) else {
print("Matrices are not the same size for element-wise calculation")
return
}
let length:vDSP_Length = UInt(self.count)
vDSP_vadd(self.real, 1, addMatrix.real, 1, &self.real, 1, length)
}
func sub(_ subMatrix:Matrix) {
guard self.sameSize(subMatrix) else {
print("Matrices are not the same size for element-wise calculation")
return
}
let length:vDSP_Length = UInt(self.count)
vDSP_vsub(subMatrix.real, 1, self.real, 1, &self.real, 1, length)
}
func mul(_ mulMatrix:Matrix) {
guard self.sameSize(mulMatrix) else {
print("Matrices are not the same size for element-wise calculation")
return
}
let length:vDSP_Length = UInt(self.count)
vDSP_vmul(mulMatrix.real, 1, self.real, 1, &self.real, 1, length)
}
func sameSize(_ compareMatrix:Matrix)->Bool{
if self.count == compareMatrix.count {
return true
}else{
return false
}
}
var description: String{
var outString = ""
var index = 0
for i in 0..<rows{
for j in 0..<columns{
index = i*columns+j
if type == "complex"{
var sign:String;
let b = imag![index]
if(b < 0){
sign = "-"
}else{
sign = "+"
}
outString = outString + String(format: "%.3f", real[index])
outString = outString + sign + String(format: "%.3f", Swift.abs(b)) + "i \t"
}else{
outString = outString + String(format: "%.3f", real[index]) + "\t"
}
}
outString = outString + "\n"
}
return outString
}
// Scaled from max and min of the original matrix
func realUint8()->[UInt8]{
var maximum = self.max
let minimum = self.min
if maximum.a == 0 {
maximum.a = 1
}
if maximum.b == 0 {
maximum.b = 1
}
var outUint8:[UInt8] = [UInt8].init(repeating: UInt8(0), count:self.count)
for i in 0..<real.count{
outUint8[i] = UInt8((real[i]-minimum.a)/(maximum.a-minimum.a)*255)
}
return outUint8
}
func realUint16()->[UInt16]{
var maximum = self.max
let minimum = self.min
if maximum.a == 0 {
maximum.a = 1
}
var outUint16:[UInt16] = [UInt16].init(repeating: UInt16(0), count:self.count)
for i in 0..<real.count{
outUint16[i] = UInt16((real[i]-minimum.a)/(maximum.a-minimum.a)*255)
}
return outUint16
}
func imagUint8()->[UInt8]{
var maximum = self.max
let minimum = self.min
if maximum.b == 0 {
maximum.b = 1
}
var outUInt8:[UInt8] = [UInt8].init(repeating: UInt8(0), count:self.count)
if imag != nil{
for i in 0..<real.count{
outUInt8[i] = UInt8((imag![i]-minimum.b)/(maximum.b-minimum.b)*255)
}
}
return outUInt8
}
func imagUint16()->[UInt16]{
var maximum = self.max
let minimum = self.min
if maximum.b == 0 {
maximum.b = 1
}
var outUint16:[UInt16] = [UInt16].init(repeating: UInt16(0), count:self.count)
if imag != nil{
for i in 0..<imag!.count{
outUint16[i] = UInt16((imag![i]-minimum.b)/(maximum.b-minimum.b)*255)
}
}
return outUint16
}
func imageRepresentation(part:String, format:Int) -> NSImage? {
let typeSize:Int = format/8
let dataSize:Int = format*count
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue).union(CGBitmapInfo())
var providerRef:CGDataProvider?
if format == MatrixOutput.uint16 {
var out:[UInt16]
if part == "imag" {
out = self.imagUint16()
}else{
out = self.realUint16()
}
providerRef = CGDataProvider(data: NSData(bytes: &out, length: dataSize))!
}else{
var out:[UInt8]
if part == "imag" {
out = self.imagUint8()
}else{
out = self.realUint8()
}
let data = NSData(bytes: &out, length: dataSize)
providerRef = CGDataProvider(data: data)!
}
// careful of bits not bytes!
if let image = CGImage(width: columns,
height: rows,
bitsPerComponent: format,
bitsPerPixel: format,
bytesPerRow: typeSize*columns,
space: CGColorSpaceCreateDeviceGray(),
bitmapInfo: bitmapInfo,
provider: providerRef!,
decode: nil,
shouldInterpolate: true,
intent: CGColorRenderingIntent.defaultIntent){
return NSImage(cgImage: image, size: NSZeroSize)
}
return nil
}
/// A custom playground Quick Look for this instance.
///
/// If this type has value semantics, the `PlaygroundQuickLook` instance
/// should be unaffected by subsequent mutations.
var customPlaygroundQuickLook: PlaygroundQuickLook{
let realPartImage = self.imageRepresentation(part: "real", format: MatrixOutput.uint8)
var combinedImage:NSImage?
if type == "complex"{
let imagPartImage = self.imageRepresentation(part: "imag", format: MatrixOutput.uint8)
combinedImage = NSImage(size: NSSize.init(width: 2*columns, height: rows), flipped:false, drawingHandler: {rect in
let realHalfRect = NSRect(x: 0, y: 0, width: self.columns, height: self.rows)
realPartImage?.draw(in:realHalfRect)
let imagHalfRect = NSRect(x: self.columns+1, y: 0, width: self.columns, height: self.rows)
imagPartImage?.draw(in:imagHalfRect)
return true
})
}
if combinedImage != nil{
return .image(combinedImage!)
}else{
return .image(realPartImage!)
}
// else{
// return PlaygroundQuickLook.text(self.description)
// }
}
}
//MARK: - Operations (new matrix)
func +(lhs:Matrix,rhs:Matrix) -> Matrix? {
if let newMatrix = validOutputMatrix(lhs, rhs) as Matrix? {
let length:vDSP_Length = UInt(newMatrix.count)
var outReal = newMatrix.real
vDSP_vadd(lhs.real, 1, rhs.real, 1, &outReal, 1, length)
newMatrix.real = outReal;
if newMatrix.type == "complex" {
var outImag = newMatrix.imag
if let lhsImag = lhs.imag as [Float]? {
vDSP_vadd(lhsImag, 1, outImag!, 1, &outImag!, 1, length)
}
if let rhsImag = rhs.imag as [Float]? {
vDSP_vadd(rhsImag, 1, outImag!, 1, &outImag!, 1, length)
}
newMatrix.imag = outImag;
}
return newMatrix
}else{
return nil
}
}
func -(lhs:Matrix,rhs:Matrix) -> Matrix? {
if let newMatrix = validOutputMatrix(lhs, rhs) as Matrix? {
let length:vDSP_Length = UInt(newMatrix.count)
var outReal = newMatrix.real
vDSP_vsub(rhs.real, 1, lhs.real, 1, &outReal, 1, length)
newMatrix.real = outReal;
if newMatrix.type == "complex" {
var outImag = newMatrix.imag
if let lhsImag = lhs.imag as [Float]? {
vDSP_vadd(lhsImag, 1, outImag!, 1, &outImag!, 1, length)
}
if let rhsImag = rhs.imag as [Float]? {
vDSP_vsub(rhsImag, 1, outImag!, 1, &outImag!, 1, length)
}
newMatrix.imag = outImag;
}
return newMatrix
}else{
return nil
}
}
func .*(lhs:Matrix,rhs:Matrix) -> Matrix?{
if let newMatrix = validOutputMatrix(lhs, rhs) as Matrix? {
let length:vDSP_Length = UInt(newMatrix.count)
var outReal = newMatrix.real
var temp1 = [Float](repeatElement(0.0, count: newMatrix.count))
var temp2 = [Float](repeatElement(0.0, count: newMatrix.count))
if lhs.complex && rhs.complex {
var outImag = newMatrix.imag!
// Calculate the real part
vDSP_vmul(rhs.real, 1, lhs.real, 1, &temp1, 1, length)
vDSP_vmul(rhs.imag!, 1, lhs.imag!, 1, &temp2, 1, length)
vDSP_vsub(temp2, 1, temp1, 1, &outReal, 1, length)
// Calculate the imag part
vDSP_vmul(rhs.real, 1, lhs.imag!, 1, &temp1, 1, length)
vDSP_vmul(rhs.imag!, 1, lhs.real, 1, &temp2, 1, length)
vDSP_vadd(temp1, 1, temp2, 1, &outImag, 1, length)
newMatrix.imag = outImag
newMatrix.real = outReal
}else if lhs.complex{
var outImag = newMatrix.imag!
vDSP_vmul(rhs.real, 1, lhs.real, 1, &outReal, 1, length)
vDSP_vmul(rhs.real, 1, lhs.imag!, 1, &outImag, 1, length)
newMatrix.imag = outImag
newMatrix.real = outReal
}else if rhs.complex{
var outImag = newMatrix.imag!
vDSP_vmul(rhs.real, 1, lhs.real, 1, &outReal, 1, length)
vDSP_vmul(rhs.imag!, 1, lhs.real, 1, &outImag, 1, length)
newMatrix.imag = outImag
newMatrix.real = outReal
}else{
vDSP_vmul(lhs.real, 1, rhs.real, 1, &outReal, 1, length)
newMatrix.real = outReal
}
return newMatrix
}else{
return nil
}
}
//MARK: - Testing and convenience
func complexMatricies(_ mat1:Matrix, _ mat2:Matrix)->Int{
var numComplex = 0
if mat1.complex{
numComplex += 1
}
if mat2.complex{
numComplex += 1
}
return numComplex
}
func validOutputMatrix(_ mat1:Matrix, _ mat2:Matrix,_ operation:String? = "element-wise")->Matrix?{
var newMatrix:Matrix
if operation == "element-wise" {
guard mat1.sameSize(mat2) else {
print("Matrices are not the same size for element-wise calculation")
return nil
}
if complexMatricies(mat1, mat2) > 0 {
newMatrix = Matrix(mat1.rows, mat1.columns, "complex")
}else{
newMatrix = Matrix(mat1.rows, mat1.columns)
}
}else{
if complexMatricies(mat1, mat2) > 0 {
newMatrix = Matrix(mat1.columns, mat2.rows, "complex")
}else{
newMatrix = Matrix(mat1.columns, mat2.rows)
}
}
return newMatrix
}
| 012bc84e1b5b926f265f7b4d93442d37 | 23.221024 | 126 | 0.450868 | false | false | false | false |
remind101/AutoGraph | refs/heads/master | AutoGraph/SubscriptionRequest.swift | mit | 1 | import Foundation
public protocol SubscriptionRequestSerializable {
func serializedSubscriptionPayload() throws -> String
}
public struct SubscriptionRequest<R: Request>: SubscriptionRequestSerializable {
let operationName: String
let request: R
let subscriptionID: SubscriptionID
init(request: R) throws {
self.operationName = request.operationName
self.request = request
self.subscriptionID = try SubscriptionRequest.generateSubscriptionID(request: request,
operationName: operationName)
}
public func serializedSubscriptionPayload() throws -> String {
let query = try self.request.queryDocument.graphQLString()
var body: [String : Any] = [
"operationName": self.operationName,
"query": query
]
if let variables = try self.request.variables?.graphQLVariablesDictionary() {
body["variables"] = variables
}
let payload: [String : Any] = [
"payload": body,
"id": self.subscriptionID,
"type": GraphQLWSProtocol.start.rawValue
]
let serialized: Data = try {
do {
return try JSONSerialization.data(withJSONObject: payload, options: .fragmentsAllowed)
}
catch let e {
throw WebSocketError.subscriptionPayloadFailedSerialization(payload, underlyingError: e)
}
}()
// TODO: Do we need to convert this to a string?
guard let serializedString = String(data: serialized, encoding: .utf8) else {
throw WebSocketError.subscriptionPayloadFailedSerialization(payload, underlyingError: nil)
}
return serializedString
}
static func generateSubscriptionID<R: Request>(request: R, operationName: String) throws -> SubscriptionID {
guard let variablesString = try request.variables?.graphQLVariablesDictionary().reduce(into: "", { (result, arg1) in
result += "\(String(describing: arg1.key)):\(String(describing: arg1.value)),"
})
else {
return operationName
}
return "\(operationName):{\(variablesString)}"
}
}
public enum GraphQLWSProtocol: String {
case connectionInit = "connection_init" // Client -> Server
case connectionTerminate = "connection_terminate" // Client -> Server
case start = "start" // Client -> Server
case stop = "stop" // Client -> Server
case connectionAck = "connection_ack" // Server -> Client
case connectionError = "connection_error" // Server -> Client
case connectionKeepAlive = "ka" // Server -> Client
case data = "data" // Server -> Client For Subscription Payload
case error = "error" // Server -> Client For Subscription Payload
case complete = "complete" // Server -> Client
case unknownResponse // Server -> Client
public func serializedSubscriptionPayload(id: String? = nil) throws -> String {
var payload: [String : Any] = [
"type": self.rawValue
]
if let id = id {
payload["id"] = id
}
let serialized: Data = try {
do {
return try JSONSerialization.data(withJSONObject: payload, options: .fragmentsAllowed)
}
catch let e {
throw WebSocketError.subscriptionPayloadFailedSerialization(payload, underlyingError: e)
}
}()
// TODO: Do we need to convert this to a string?
guard let serializedString = String(data: serialized, encoding: .utf8) else {
throw WebSocketError.subscriptionPayloadFailedSerialization(payload, underlyingError: nil)
}
return serializedString
}
}
| 8af216c59fc563b451c8e13b3552ddf9 | 39.252427 | 124 | 0.572359 | false | false | false | false |
paulgriffiths/macplanetpos | refs/heads/master | MacAstro/AstroFunctions.swift | gpl-3.0 | 1 | //
// AstroFunctions.swift
// MacAstro
//
// Created by Paul Griffiths on 5/3/15.
// Copyright (c) 2015 Paul Griffiths. All rights reserved.
//
import Darwin
public func kepler(mAnom: Double, ecc: Double) -> Double {
let desiredAccuracy = 1e-6
precondition(ecc >= 0 && ecc <= 1, "Eccentricity must be between 0.0 and 1.0, inclusive")
var eAnom = mAnom
var diff : Double
repeat {
diff = eAnom - ecc * sin(eAnom) - mAnom
eAnom -= diff / (1 - ecc * cos(eAnom))
} while ( abs(diff) > desiredAccuracy )
return eAnom
} | 1ccdea8e9aa201b6cdf21aaf18abf4f3 | 22.32 | 93 | 0.603093 | false | false | false | false |
CoBug92/Hookah | refs/heads/master | Hookah/Source/Model/PlainObject/Articles/ArticlePlainObject+Request.swift | mit | 1 | //
// ArticlePlainObject+Request.swift
// Hookah
//
// Created by Bogdan Kostyuchenko on 25/03/2018.
// Copyright © 2018 Bogdan Kostyuchenko. All rights reserved.
//
import Foundation
extension ArticlePlainObject: PlainObjectType {
static func article(with id: String) -> [ArticleContentPlainObject] {
var articleArray = [ArticleContentPlainObject]()
ArticleStub.stub.forEach { (jsonDict) in
guard
let article = ArticlePlainObject(json: jsonDict),
article.id == id
else { return }
articleArray = article.contents
}
return articleArray
}
init?(json: JSONDictionary) {
guard
let id = json["articleId"] as? String,
let contents = json["contents"] as? [JSONDictionary]
else { return nil }
self.id = id
var contentsArray = [ArticleContentPlainObject]()
contents.forEach { (contentJSON) in
guard let plainObject = ArticleContentPlainObject(json: contentJSON) else { return }
contentsArray.append(plainObject)
}
self.contents = contentsArray
}
}
| c0e381276fa0707cad59fa1ab22b5faf | 29.153846 | 96 | 0.613946 | false | false | false | false |
zhuxietong/Eelay | refs/heads/master | run/test/Regex/MatchResult.swift | mit | 1 | import Foundation
/// A `MatchResult` encapsulates the result of a single match in a string,
/// providing access to the matched string, as well as any capture groups within
/// that string.
public struct MatchResult {
// MARK: Accessing match results
/// The entire matched string.
///
/// Example:
///
/// let pattern = Regex("a*")
///
/// if let match = pattern.firstMatch(in: "aaa") {
/// match.matchedString // "aaa"
/// }
///
/// if let match = pattern.firstMatch(in: "bbb") {
/// match.matchedString // ""
/// }
public var matchedString: String {
return _result.matchedString
}
/// The range of the matched string.
public var range: Range<String.Index> {
return _string.range(from: _result.range)
}
/// The matching string for each capture group in the regular expression
/// (if any).
///
/// **Note:** Usually if the match was successful, the captures will by
/// definition be non-nil. However if a given capture group is optional, the
/// captured string may also be nil, depending on the particular string that
/// is being matched against.
///
/// Example:
///
/// let regex = Regex("(a)?(b)")
///
/// regex.firstMatch(in: "ab")?.captures // [Optional("a"), Optional("b")]
/// regex.firstMatch(in: "b")?.captures // [nil, Optional("b")]
public var captures: [String?] {
return _result.captures
}
/// The ranges of each capture (if any).
///
/// - seealso: The discussion and example for `MatchResult.captures`.
public var captureRanges: [Range<String.Index>?] {
return _captureRanges.value
}
// MARK: Internal initialisers
internal var matchResult: NSTextCheckingResult {
return _result.result
}
private let _captureRanges: Memo<[Range<String.Index>?]>
private let _result: _MatchResult
private let _string: String
internal init(_ string: String, _ result: NSTextCheckingResult) {
self._result = _MatchResult(string, result)
self._string = string
let result = self._result
let funcAction = { () -> [Range<String.Index>?] in
let ranges = result.captureRanges
let set = ranges.map({ (range) -> Range<String.Index>? in
guard let r = range else {return nil}
return r as Range<String.Index>
})
return set
}
self._captureRanges = Memo(unevaluated: { () -> [Range<String.Index>?] in
return funcAction()
})
// self._captureRanges = Memo { [_result] in
// _result.captureRanges.map { utf16range in
// utf16range.map { string.range(from: $0) }
// }
// }
}
}
private extension String {
func range(from utf16Range: Range<UTF16View.Index>) -> Range<Index> {
#if swift(>=4.0)
return utf16Range
#else
let start = Index(utf16Range.lowerBound, within: self)!
let end = Index(utf16Range.upperBound, within: self)!
return start..<end
#endif
}
}
// Use of a private class allows for lazy vars without the need for `mutating`.
private final class _MatchResult {
#if swift(>=4.0)
private let string: String
#else
private let string: String.UTF16View
#endif
fileprivate let result: NSTextCheckingResult
fileprivate init(_ string: String, _ result: NSTextCheckingResult) {
#if swift(>=4.0)
self.string = string
#else
self.string = string.utf16
#endif
self.result = result
}
lazy var range: Range<String.UTF16View.Index> = {
return self.utf16Range(from: self.result.range)!
}()
lazy var captures: [String?] = {
return self.captureRanges.map { $0.map(self.substring(from:)) }
}()
lazy var captureRanges: [Range<String.UTF16View.Index>?] = {
return self.result.ranges.dropFirst().map(self.utf16Range(from:))
}()
lazy var matchedString: String = {
let range = self.utf16Range(from: self.result.range)!
return self.substring(from: range)
}()
private func utf16Range(from range: NSRange) -> Range<String.UTF16View.Index>? {
#if swift(>=4.0)
return Range(range, in: string)
#else
guard range.location != NSNotFound else { return nil }
let start = string.index(string.startIndex, offsetBy: range.location)
let end = string.index(start, offsetBy: range.length)
return start..<end
#endif
}
private func substring(from range: Range<String.UTF16View.Index>) -> String {
return String(describing: string[range])
}
}
| f53bdf8c54050e210e1e62d10795e741 | 26.419753 | 82 | 0.641153 | false | false | false | false |
stormpath/stormpath-swift-example | refs/heads/master | Pods/Stormpath/Stormpath/Core/Stormpath.swift | mit | 1 | //
// Stormpath.swift
// Stormpath
//
// Created by Adis on 16/11/15.
// Copyright © 2015 Stormpath. All rights reserved.
//
import Foundation
/// Callback for Stormpath API responses that respond with a success/fail.
public typealias StormpathSuccessCallback = (Bool, NSError?) -> Void
/// Callback for Stormpath API responses that respond with an account object.
public typealias StormpathAccountCallback = (Account?, NSError?) -> Void
/**
Stormpath represents the state of the application's connection to the Stormpath
Framework server. It allows you to connect to the Stormpath Framework
Integration API, register, login, and stores the current account's access and
refresh tokens securely. All callbacks to the application are handled on the
main thread.
*/
@objc(SPHStormpath)
public final class Stormpath: NSObject {
/// Singleton representing the primary Stormpath instance using the default configuration.
public static let sharedSession = Stormpath(identifier: "default")
/// Configuration parameter for the Stormpath object. Can be changed.
public var configuration = StormpathConfiguration.defaultConfiguration
/// Reference to the API Service.
var apiService: APIService!
/// Reference to the Social Login Service.
var socialLoginService: SocialLoginService!
/// Reference to the Keychain Service.
var keychain: KeychainService!
/// API Client
var apiClient: APIClient!
/**
Initializes the Stormpath object with a default configuration. The
identifier is used to namespace the current state of the object, so that on
future loads we can find the saved credentials from the right location. The
default identifier is "default".
*/
public init(identifier: String) {
super.init()
apiService = APIService(withStormpath: self)
keychain = KeychainService(withIdentifier: identifier)
socialLoginService = SocialLoginService(withStormpath: self)
apiClient = APIClient(stormpath: self)
}
/**
This method registers an account from the data provided.
- parameters:
- account: A Registration Model object with the account data you want to
register.
- callback: The completion block to be invoked after the API
request is finished. It returns an account object.
*/
public func register(account: RegistrationForm, callback: StormpathAccountCallback? = nil) {
apiService.register(newAccount: account, callback: callback)
}
/**
Logs in an account and assumes that the login path is behind the /login
relative path. This method also stores the account session tokens for later
use.
- parameters:
- username: Account's email or username.
- password: Account password.
- callback: The completion block to be invoked after the API
request is finished. If the method fails, the error will be passed in
the completion.
*/
public func login(username: String, password: String, callback: StormpathSuccessCallback? = nil) {
apiService.login(username: username, password: password, callback: callback)
}
/**
Begins a login flow with a social provider, presenting or opening up Safari
(iOS8) to handle login. This WILL NOT call back if the user clicks "cancel"
on the login screen, as they never began the login process in the first
place.
- parameters:
- socialProvider: the provider (Facebook, Google, etc) from which you
have an access token
- callback: Callback on success or failure
*/
public func login(provider: Provider, callback: StormpathSuccessCallback? = nil) {
socialLoginService.login(provider: provider, callback: callback)
}
/**
Logs in an account if you have an access token from a social provider.
- parameters:
- socialProvider: the provider (Facebook, Google, etc) from which you
have an access token
- accessToken: String containing the access token
- callback: A block of code that is called back on success or
failure.
*/
public func login(provider: Provider, accessToken: String, callback: StormpathSuccessCallback? = nil) {
apiService.login(socialProvider: provider, accessToken: accessToken, callback: callback)
}
/**
Logs in an account if you have an authorization code from a social provider.
- parameters:
- socialProvider: the provider (Facebook, Google, etc) from which you have
an access token
- authorizationCode: String containing the authorization code
- callback: A block of code that is called back on success or
failure.
*/
// Making this internal for now, since we don't support auth codes for FB /
// Google
func login(provider: Provider, authorizationCode: String, callback: StormpathSuccessCallback? = nil) {
apiService.login(socialProvider: provider, authorizationCode: authorizationCode, callback: callback)
}
/**
Fetches the account data, and returns it in the form of a dictionary.
- parameters:
- callback: Completion block invoked
*/
public func me(callback: StormpathAccountCallback? = nil) {
apiService.me(callback)
}
/**
Logs out the account and clears the sessions tokens.
*/
public func logout() {
apiService.logout()
}
// MARK: Account password reset
/**
Generates an account password reset token and sends an email to the user,
if such email exists.
- parameters:
- email: Account email. Usually from an input.
- callback: The completion block to be invoked after the API
request is finished. This will always succeed if the API call is
successful.
*/
public func resetPassword(email: String, callback: StormpathSuccessCallback? = nil) {
apiService.resetPassword(email, callback: callback)
}
/// Deep link handler (iOS9)
public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any]) -> Bool {
return socialLoginService.handleCallbackURL(url)
}
/// Deep link handler (<iOS9)
public func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return self.application(application, open: url, options: [UIApplicationOpenURLOptionsKey: Any]())
}
/**
Provides the last access token fetched by either login or
refreshAccessToken functions. The validity of the token is not verified
upon fetching!
- returns: Access token for your API calls.
*/
internal(set) public var accessToken: String? {
get {
return keychain.accessToken
}
set {
keychain.accessToken = newValue
}
}
/// Refresh token for the current account.
internal(set) public var refreshToken: String? {
get {
return keychain.refreshToken
}
set {
keychain.refreshToken = newValue
}
}
/**
Refreshes the access token and stores it to be available via accessToken
var. Call this function if your token expires.
- parameters:
- callback: Block invoked on function completion. It will have
either a new access token passed as a string, or an error if one
occurred.
*/
public func refreshAccessToken(callback: StormpathSuccessCallback? = nil) {
apiService.refreshAccessToken(callback)
}
}
| a352e76b582affa500aa481f2af02091 | 35.195349 | 127 | 0.671164 | false | false | false | false |
alexaubry/BulletinBoard | refs/heads/develop | Sources/Support/Views/Internal/ActivityIndicator.swift | mit | 1 | /**
* BulletinBoard
* Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
/**
* A view that contains an activity indicator. The indicator is centered inside the view.
*/
class ActivityIndicator: UIView {
private let activityIndicatorView = UIActivityIndicatorView()
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
addSubview(activityIndicatorView)
activityIndicatorView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
activityIndicatorView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
// MARK: - Activity Indicator
/// Starts the animation of the activity indicator.
func startAnimating() {
activityIndicatorView.startAnimating()
}
/// Stops the animation of the activity indicator.
func stopAnimating() {
activityIndicatorView.stopAnimating()
}
/// The color of the activity indicator.
var color: UIColor? {
get {
return activityIndicatorView.color
}
set {
activityIndicatorView.color = newValue
}
}
/// The style of the activity indicator.
var style: UIActivityIndicatorView.Style {
get {
return activityIndicatorView.style
}
set {
activityIndicatorView.style = newValue
}
}
}
| 983a1f1f761e15b34c72912557da53c4 | 23.085714 | 94 | 0.648873 | false | false | false | false |
square/Valet | refs/heads/master | Sources/Valet/MigratableKeyValuePair.swift | apache-2.0 | 1 | // Created by Dan Federman on 5/20/20.
// Copyright © 2020 Square, 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
/// A struct that represented a key:value pair that can be migrated.
public struct MigratableKeyValuePair<Key: Hashable>: Hashable {
// MARK: Initialization
/// Creates a migratable key:value pair with the provided inputs.
/// - Parameters:
/// - key: The key in the key:value pair.
/// - value: The value in the key:value pair.
public init(key: Key, value: Data) {
self.key = key
self.value = value
}
/// Creates a migratable key:value pair with the provided inputs.
/// - Parameters:
/// - key: The key in the key:value pair.
/// - value: The desired value in the key:value pair, represented as a String.
public init(key: Key, value: String) {
self.key = key
self.value = Data(value.utf8)
}
// MARK: Public
/// The key in the key:value pair.
public let key: Key
/// The value in the key:value pair.
public let value: Data
}
// MARK: - Objective-C Compatibility
@objc(VALMigratableKeyValuePairInput)
public final class ObjectiveCCompatibilityMigratableKeyValuePairInput: NSObject {
// MARK: Initialization
internal init(key: Any, value: Data) {
self.key = key
self.value = value
}
// MARK: Public
/// The key in the key:value pair.
@objc
public let key: Any
/// The value in the key:value pair.
@objc
public let value: Data
}
@objc(VALMigratableKeyValuePairOutput)
public class ObjectiveCCompatibilityMigratableKeyValuePairOutput: NSObject {
// MARK: Initialization
/// Creates a migratable key:value pair with the provided inputs.
/// - Parameters:
/// - key: The key in the key:value pair.
/// - value: The value in the key:value pair.
@objc
public init(key: String, value: Data) {
self.key = key
self.value = value
preventMigration = false
}
/// Creates a migratable key:value pair with the provided inputs.
/// - Parameters:
/// - key: The key in the key:value pair.
/// - stringValue: The desired value in the key:value pair, represented as a String.
@objc
public init(key: String, stringValue: String) {
self.key = key
self.value = Data(stringValue.utf8)
preventMigration = false
}
// MARK: Public Static Methods
/// A sentinal `ObjectiveCCompatibilityMigratableKeyValuePairOutput` that conveys that the migration should be prevented.
@available(swift, obsoleted: 1.0)
@objc
public static func preventMigration() -> ObjectiveCCompatibilityMigratableKeyValuePairOutput {
ObjectiveCCompatibilityPreventMigrationOutput()
}
// MARK: Public
/// The key in the key:value pair.
@objc
public let key: String
/// The value in the key:value pair.
@objc
public let value: Data
// MARK: Internal
internal fileprivate(set) var preventMigration: Bool
}
private final class ObjectiveCCompatibilityPreventMigrationOutput: ObjectiveCCompatibilityMigratableKeyValuePairOutput {
init() {
super.init(key: "", stringValue: "")
preventMigration = true
}
}
| 470b7d831acd1670883629321f3fbc7e | 28.261538 | 125 | 0.666667 | false | false | false | false |
Pluto-tv/RxSwift | refs/heads/master | Demo 2/Sequences/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift | gpl-3.0 | 27 | //
// BinaryDisposable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/12/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Represents two disposable resources that are disposed together.
*/
public final class BinaryDisposable : DisposeBase, Cancelable {
private var _disposed: Int32 = 0
// state
private var disposable1: Disposable?
private var disposable2: Disposable?
/**
- returns: Was resource disposed.
*/
public var disposed: Bool {
get {
return _disposed > 0
}
}
/**
Constructs new binary disposable from two disposables.
- parameter disposable1: First disposable
- parameter disposable2: Second disposable
*/
init(_ disposable1: Disposable, _ disposable2: Disposable) {
self.disposable1 = disposable1
self.disposable2 = disposable2
super.init()
}
/**
Calls the disposal action if and only if the current instance hasn't been disposed yet.
After invoking disposal action, disposal action will be dereferenced.
*/
public func dispose() {
if OSAtomicCompareAndSwap32(0, 1, &_disposed) {
disposable1?.dispose()
disposable2?.dispose()
disposable1 = nil
disposable2 = nil
}
}
} | fbb0a3cf6eea1d8a34ae3c4bb2803778 | 23.428571 | 91 | 0.625457 | false | false | false | false |
FandyLiu/FDDemoCollection | refs/heads/master | Swift/WidgetDemo/SnapKitUtil/UIView-Layout.swift | mit | 1 | //
// UIView-Layout.swift
// EPlus_Swift
//
// Created by QianTuFD on 2017/6/14.
// Copyright © 2017年 frontpay. All rights reserved.
// SnapKit 的可复用布局封装
import SnapKit
/****************** Layout 默认常量 ******************/
// MARK: - Layout 默认常量
/// Layout 默认常量
struct LayoutConst {
static let margin: CGFloat = 8.0
static let leftMargin: CGFloat = 8.0
static let rightMargin: CGFloat = 8.0
static let topMargin: CGFloat = 8.0
static let bottomMargin: CGFloat = 8.0
}
/****************** Layoutable 协议 ******************/
// MARK: - Layoutable 协议
/// Layoutable 的协议, 只有遵守协议的类才能在封装中使用
protocol Layoutable {
var layoutMaker: (ConstraintMaker) -> Void { get }
}
/****************** UIView 布局扩展 ******************/
// MARK: - UIView 布局扩展
extension UIView {
/// UIView 布局扩展
///
/// - Parameter layouter: 遵守 Layoutable 的自定义可 复用 布局
func makeLayout(_ layouter: Layoutable) {
snp.makeConstraints(layouter.layoutMaker)
}
}
| 3b732800cf331c8257b6d3e8d04cd339 | 21.204545 | 55 | 0.58956 | false | false | false | false |
ello/ello-ios | refs/heads/master | Specs/Controllers/Profile/ProfileScreenSpec.swift | mit | 1 | ////
/// ProfileScreenSpec.swift
//
@testable import Ello
import Quick
import Nimble
class ProfileScreenSpec: QuickSpec {
class MockDelegate: ProfileScreenDelegate {
func roleAdminTapped() {}
func mentionTapped() {}
func hireTapped() {}
func editTapped() {}
func inviteTapped() {}
func collaborateTapped() {}
}
override func spec() {
describe("ProfileScreen") {
var subject: ProfileScreen!
beforeEach {
subject = ProfileScreen()
subject.coverImage = specImage(named: "specs-cover.jpg")
}
context("snapshots") {
context("ghost - loading") {
validateAllSnapshots(named: "ProfileScreen_ghost") {
subject.hasRoleAdminButton = false
subject.coverImage = nil
subject.showNavBars(animated: false)
return subject
}
}
context("current user") {
validateAllSnapshots(named: "ProfileScreen_is_current_user") {
let user = User.stub(["username": "Archer", "relationshipPriority": "self"])
subject.hasRoleAdminButton = false
subject.configureButtonsForCurrentUser()
subject.relationshipControl.relationshipPriority = user.relationshipPriority
subject.showNavBars(animated: false)
return subject
}
}
context("not current user") {
it("current user is role admin") {
let user = User.stub([
"username": "Archer", "relationshipPriority": "friend"
])
subject.hasRoleAdminButton = true
subject.configureButtonsForNonCurrentUser(
isHireable: true,
isCollaborateable: true
)
subject.relationshipControl.relationshipPriority = user.relationshipPriority
subject.showNavBars(animated: false)
expectValidSnapshot(
subject,
named: "ProfileScreen_current_user_is_role_admin",
device: .phone6_Portrait
)
}
it("is hireable not collaborateable") {
let user = User.stub([
"username": "Archer", "relationshipPriority": "friend"
])
subject.hasRoleAdminButton = false
subject.configureButtonsForNonCurrentUser(
isHireable: true,
isCollaborateable: false
)
subject.relationshipControl.relationshipPriority = user.relationshipPriority
subject.showNavBars(animated: false)
expectValidSnapshot(
subject,
named: "ProfileScreen_not_current_user_is_hireable",
device: .phone6_Portrait
)
}
it("is collaborateable not hireable") {
let user = User.stub([
"username": "Archer", "relationshipPriority": "friend"
])
subject.hasRoleAdminButton = false
subject.configureButtonsForNonCurrentUser(
isHireable: false,
isCollaborateable: true
)
subject.relationshipControl.relationshipPriority = user.relationshipPriority
subject.showNavBars(animated: false)
expectValidSnapshot(
subject,
named: "ProfileScreen_not_current_user_is_collaborateable",
device: .phone6_Portrait
)
}
it("is hireable and collaborateable") {
let user = User.stub([
"username": "Archer", "relationshipPriority": "friend"
])
subject.hasRoleAdminButton = false
subject.configureButtonsForNonCurrentUser(
isHireable: true,
isCollaborateable: true
)
subject.relationshipControl.relationshipPriority = user.relationshipPriority
subject.showNavBars(animated: false)
expectValidSnapshot(
subject,
named: "ProfileScreen_not_current_user_hireable_and_collaborateable",
device: .phone6_Portrait
)
}
it("is mentionable") {
let user = User.stub(["username": "Archer", "relationshipPriority": "noise"]
)
subject.hasRoleAdminButton = false
subject.configureButtonsForNonCurrentUser(
isHireable: false,
isCollaborateable: false
)
subject.relationshipControl.relationshipPriority = user.relationshipPriority
subject.showNavBars(animated: false)
expectValidSnapshot(
subject,
named: "ProfileScreen_not_current_user_is_mentionable",
device: .phone6_Portrait
)
}
}
}
}
}
}
| 5895ab93d0a87130896e4e0d4927e6b4 | 39.625 | 100 | 0.447449 | false | false | false | false |
SummerHH/swift3.0WeBo | refs/heads/master | WeBo/Classes/Controller/Home(首页)/UIPopover/PopoverAnimator.swift | apache-2.0 | 1 |
//
// PopoverAnimator.swift
// WeBo
//
// Created by 叶炯 on 16/9/17.
// Copyright © 2016年 叶炯. All rights reserved.
//
import UIKit
class PopoverAnimator: NSObject {
//MARK: - 属性
fileprivate var isPersent: Bool = false
var presentedFrame: CGRect = CGRect.zero
//闭包回调
var callBack: ((_ persented: Bool) -> ())?
//MARK: - 自定义构造函数
//注意:如果自定义了一个构造函数,但是没有对默认构造函数 init()进行重写,那么自定义的构造函数会覆盖默认的 init() 构造函数
init(callBack: @escaping (_ persented: Bool) -> ()) {
self.callBack = callBack
}
}
//MARK:- 设置自定义转场动画代理方法
extension PopoverAnimator: UIViewControllerTransitioningDelegate {
//目的: 改变弹出 view 的fream
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
let presentation = YJPresentationController(presentedViewController: presented, presenting: presenting)
presentation.presentedFrame = presentedFrame
return presentation
}
//目的: 自定义弹出的动画 返回是一个协议
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPersent = true
//调用闭包
callBack!(isPersent)
return self
}
//目的: 自定义消失动画
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPersent = false
//调用闭包
callBack!(isPersent)
return self
}
}
//MARK: - 弹出和消失动画代理的方法
extension PopoverAnimator : UIViewControllerAnimatedTransitioning {
//动画持续的时间
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
//获取"转场的上下文": 可以通过转场上下文获取弹出的 View 和消失的 View
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
isPersent ? animateTransitionPersentView(transitionContext) : animateTransitionDismissView(transitionContext)
}
//自定义弹出动画
fileprivate func animateTransitionPersentView(_ transitionContext: UIViewControllerContextTransitioning) {
//1.获取弹出的 view
//UITransitionContextToViewKey 获取消失的 view
//UITransitionContextFromViewKey 获取弹出的 View
let presentedView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
//2. 将弹出的 View 添加到 containerView 中
transitionContext.containerView.addSubview(presentedView)
//3.执行动画
//执行动画的比例
presentedView.transform = CGAffineTransform(scaleX: 1.0, y: 0.0)
//设置锚点
presentedView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
//回到最初的位置
presentedView.transform = CGAffineTransform.identity
}, completion: { (_) in
//必须告诉上下文,已完成动画
transitionContext.completeTransition(true)
})
}
//自定义消失动画
fileprivate func animateTransitionDismissView(_ transitionContext: UIViewControllerContextTransitioning) {
//1.获取消失的 view
let dismissView = transitionContext.view(forKey: UITransitionContextViewKey.from)
//2.执行动画
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
dismissView?.transform = CGAffineTransform(scaleX: 1.0, y: 0.001)
}, completion: { (_) in
dismissView?.removeFromSuperview()
//必须告诉上下文,已完成动画
transitionContext.completeTransition(true)
})
}
}
| 050f6f8a90f72276e1ed9d099f362b23 | 30.163934 | 170 | 0.660179 | false | false | false | false |
wikimedia/apps-ios-wikipedia | refs/heads/twn | Wikipedia/Code/CreateNewReadingListButtonView.swift | mit | 1 | import UIKit
public class CreateNewReadingListButtonView: UIView {
@IBOutlet weak var button: AlignedImageButton!
@IBOutlet private weak var separator: UIView!
public override func awakeFromNib() {
super.awakeFromNib()
button.setImage(#imageLiteral(resourceName: "plus"), for: .normal)
button.horizontalSpacing = 7
}
public var title: String? {
didSet {
button.setTitle(title, for: .normal)
}
}
public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
button.titleLabel?.font = UIFont.wmf_font(.semiboldBody, compatibleWithTraitCollection: traitCollection)
}
}
extension CreateNewReadingListButtonView: Themeable {
public func apply(theme: Theme) {
backgroundColor = theme.colors.paperBackground
button.tintColor = theme.colors.link
separator.backgroundColor = theme.colors.border
}
}
| 48acef66818bf6a108ee879eddd1a877 | 30.78125 | 112 | 0.705998 | false | false | false | false |
SukhKalsi/TouristApp | refs/heads/master | Virtual Tourist/PhotoAlbumCollectionViewController.swift | mit | 1 | //
// PhotoAlbumCollectionViewController.swift
// Virtual Tourist
//
// Created by Sukh Kalsi on 28/12/2015.
// Copyright © 2015 Sukh Kalsi. All rights reserved.
//
import UIKit
import MapKit
import CoreData
private let reuseIdentifier = "PhotoCell"
class PhotoAlbumCollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, NSFetchedResultsControllerDelegate {
// MARK: - Properties
// Pin location object passed through via segue
var location : Pin!
// The selected indexes array keeps all of the indexPaths for cells that are "selected".
private var selectedIndexes = [NSIndexPath]()
// Keep the changes. We will keep track of insertions, deletions, and updates.
private var insertedIndexPaths: [NSIndexPath]!
private var deletedIndexPaths: [NSIndexPath]!
private var updatedIndexPaths: [NSIndexPath]!
// MARK: - Outlets
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var photoAlbumCollectionView: UICollectionView!
@IBOutlet weak var btnCollection: UIBarButtonItem!
@IBOutlet weak var collectionViewActivityIndicator: UIActivityIndicatorView!
@IBOutlet weak var collectionViewLabel: UILabel!
// MARK: - Actions
@IBAction func btnCollectionAction(sender: UIBarButtonItem) {
btnCollection.enabled = false
// clear entire collection or remove user selected items
if selectedIndexes.isEmpty {
collectionViewActivityIndicator.hidden = false
collectionViewActivityIndicator.startAnimating()
collectionViewLabel.text = "Loading photos..."
collectionViewLabel.hidden = false
if let collection = fetchedResultsController.fetchedObjects as? [Picture] {
for picture in collection {
picture.location = nil
sharedContext.deleteObject(picture)
}
}
// retrieve a new collection set...
getCollection()
} else {
for indexPath in selectedIndexes {
let picture = fetchedResultsController.objectAtIndexPath(indexPath) as! Picture
picture.location = nil
sharedContext.deleteObject(picture)
}
selectedIndexes = [NSIndexPath]()
updateButton()
}
btnCollection.enabled = true
}
// MARK: - Core Data Convenience
var sharedContext: NSManagedObjectContext {
return CoreDataStackManager.sharedInstance().managedObjectContext
}
// Mark: - Fetched Results Controller
lazy var fetchedResultsController: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest(entityName: "Picture")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "photoID", ascending: true)]
fetchRequest.predicate = NSPredicate(format: "location == %@", self.location);
let fetchedResultsController = NSFetchedResultsController(
fetchRequest: fetchRequest,
managedObjectContext: self.sharedContext,
sectionNameKeyPath: nil,
cacheName: nil
)
return fetchedResultsController
}()
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Collection view delegate, datasource and Register cell classes
photoAlbumCollectionView.delegate = self
photoAlbumCollectionView.dataSource = self
// Set the delegate to this view controller
fetchedResultsController.delegate = self
// Perform the fetch
var error: NSError?
do {
try self.fetchedResultsController.performFetch()
} catch let error1 as NSError {
error = error1
}
if let error = error {
print("Error performing initial fetch: \(error)")
}
// Set the text on the button
updateButton()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if location.pictures.isEmpty {
collectionViewActivityIndicator.startAnimating()
btnCollection.enabled = false;
getCollection()
} else {
collectionViewActivityIndicator.stopAnimating()
collectionViewActivityIndicator.hidden = true
collectionViewLabel.hidden = true
}
// load the map to the correct location, zoomed in
loadMap()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Layout the collection view
let width = floor(self.photoAlbumCollectionView.frame.size.width / 3)
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.itemSize = CGSize(width: width, height: width)
self.photoAlbumCollectionView.collectionViewLayout = layout
}
// MARK: - Private controller methods
private func getCollection() {
FlickrClient.sharedInstance().getImagesFromLocation(location.latitude, longitude: location.longitude) { result , error in
if let _ = error {
print("error.")
} else {
if let photoDictionaries = result.valueForKey("photo") as? [[String : AnyObject]] {
// Parse the array of photo dictionairies
let _ = photoDictionaries.map() { (dictionary: [String : AnyObject]) -> Picture in
let url = NSURL(string: dictionary["url_m"] as! String)!
let picture = Picture(imageURL: url, context: self.sharedContext)
picture.location = self.location
return picture
}
// update the collection view on the main thread
dispatch_async(dispatch_get_main_queue()) {
CoreDataStackManager.sharedInstance().saveContext()
self.btnCollection.enabled = true
// self.photoAlbumCollectionView.reloadData()
self.collectionViewActivityIndicator.stopAnimating()
self.collectionViewActivityIndicator.hidden = true
if photoDictionaries.isEmpty {
self.collectionViewLabel.text = "No photos found for this location."
} else {
self.collectionViewLabel.hidden = true
}
}
}
}
}
}
private func loadMap() {
// Zoom map into region, Centralise map view to coordinates and add annotation to map view
let span = MKCoordinateSpanMake(0.0025, 0.0025)
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude), span: span)
self.mapView.scrollEnabled = false
self.mapView.addAnnotation(location)
self.mapView.regionThatFits(MKCoordinateRegionMake(region.center, region.span))
self.mapView.setRegion(region, animated: true)
}
private func updateButton() {
let text: String!
if selectedIndexes.isEmpty {
text = "New Collection"
} else {
text = "Remove Selected Pictures"
}
btnCollection.title = text
}
// MARK: UICollectionView
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
let sections = self.fetchedResultsController.sections?.count ?? 0
return sections
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
let numberOfObjects = sectionInfo.numberOfObjects
return numberOfObjects
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var locationImage = UIImage()
let picture = fetchedResultsController.objectAtIndexPath(indexPath) as! Picture
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PhotoCollectionViewCell
cell.activityIndicator.hidden = true
cell.activityIndicator.stopAnimating()
// we have an image downloaded...
if picture.locationImage != nil {
locationImage = picture.locationImage!
cell.imageView.image = locationImage
return cell
}
// we don't have an image downloaded, and there appears to be no url to fetch one
else if picture.imageURL == nil || picture.imageURL == "" {
locationImage = UIImage(named: "noImage")!
cell.imageView.image = locationImage
return cell
}
// we start downloading...
else {
cell.activityIndicator.hidden = false
cell.activityIndicator.startAnimating()
let task = HttpClient.sharedInstance().httpGetImage(picture.imageURL!) { data, error in
if let error = error {
print("Image download error: ")
print(error)
} else {
// Craete the image
let image = UIImage(data: data!)
// update the cell later, on the main thread
dispatch_async(dispatch_get_main_queue()) {
// update the model, for caching
picture.locationImage = image
cell.imageView.image = image
cell.activityIndicator.stopAnimating()
cell.activityIndicator.hidden = true
// self.photoAlbumCollectionView.reloadItemsAtIndexPaths([indexPath])
}
}
}
cell.taskToCancelifCellIsReused = task
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? PhotoCollectionViewCell {
// Whenever a cell is tapped we will toggle its presence in the selectedIndexes array
if let index = selectedIndexes.indexOf(indexPath) {
selectedIndexes.removeAtIndex(index)
cell.imageView.alpha = 1.0
} else {
selectedIndexes.append(indexPath)
cell.imageView.alpha = 0.5
}
}
updateButton()
}
// MARK: - Fetched Results Controller Delegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
// We are about to handle some new changes. Start out with empty arrays for each change type
insertedIndexPaths = [NSIndexPath]()
deletedIndexPaths = [NSIndexPath]()
updatedIndexPaths = [NSIndexPath]()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
insertedIndexPaths.append(newIndexPath!)
break
case .Delete:
deletedIndexPaths.append(indexPath!)
break
case .Update:
updatedIndexPaths.append(indexPath!)
case .Move:
print("Move an item. We don't expect to see this in this app.")
break
default:
break
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
photoAlbumCollectionView.performBatchUpdates({() -> Void in
for indexPath in self.insertedIndexPaths {
self.photoAlbumCollectionView.insertItemsAtIndexPaths([indexPath])
}
for indexPath in self.deletedIndexPaths {
self.photoAlbumCollectionView.deleteItemsAtIndexPaths([indexPath])
}
for indexPath in self.updatedIndexPaths {
self.photoAlbumCollectionView.reloadItemsAtIndexPaths([indexPath])
}
}, completion: nil)
}
}
| 13a5ebe543caf09bc6c7750e0449e980 | 34.389333 | 211 | 0.587371 | false | false | false | false |
sjf0213/DingShan | refs/heads/master | DingshanSwift/DingshanSwift/GalleryDetailController.swift | mit | 1 | //
// GalleryDetailController.swift
// DingshanSwift
//
// Created by song jufeng on 15/9/6.
// Copyright (c) 2015年 song jufeng. All rights reserved.
//
import Foundation
class GalleryDetailController: DSViewController {
var container:ScrollContainerView?
var topBar:GalleryDetailTopBar?
var bottomBar:GalleryDetailBottomBar?
var titleCache:String = ""
var mask : UIButton?
var menuView : GalleryDetailMenuView?
var shareView:SNSShareView?
override func loadView(){
super.loadView()
self.view.backgroundColor = UIColor.blackColor()
container = ScrollContainerView(frame: self.view.bounds);
self.view.addSubview(container!)
// KVO
container?.addObserver(self, forKeyPath: "totalShowCount", options: NSKeyValueObservingOptions.New, context: nil)
container?.addObserver(self, forKeyPath: "currentShowNumber", options: NSKeyValueObservingOptions.New, context: nil)
topBar = GalleryDetailTopBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 64));
self.view.addSubview(self.topBar!)
topBar?.backBlock = {self.navigationController?.popViewControllerAnimated(true)}
topBar?.tapMoreBlock = {
if nil == self.menuView{
let menu = GalleryDetailMenuView(frame: CGRect(x: self.view.frame.size.width - 90, y: -120, width: 80, height: 100))
self.menuView = menu
self.menuView?.tapMenuItemHandler = {(index) -> Void in
switch index{
case 0:
let tempview = self.container?.getCurrentShowView()
if ((tempview?.respondsToSelector(Selector("SaveToAlbum:"))) == true) {
tempview?.performSelector(Selector("SaveToAlbum:"), withObject:self.view, afterDelay:0)
}
self.dismissMenuView()
self.mask?.hidden = true
break
case 1:
self.dismissMenuView()
if self.shareView == nil{
let snsView = SNSShareView(frame: CGRect(x: 0, y: self.view.frame.size.height, width: self.view.frame.size.width, height: 170))
self.shareView = snsView
self.view.addSubview(self.shareView!)
}
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options:UIViewAnimationOptions([.AllowUserInteraction, .BeginFromCurrentState]), animations: { () -> Void in
self.shareView?.frame = CGRect(x: 0, y: self.view.frame.size.height - 170, width: self.view.frame.size.width, height: 170)
}, completion: nil)
break
default:
break
}
}
self.view.addSubview(self.menuView!)
}
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options:UIViewAnimationOptions([.AllowUserInteraction, .BeginFromCurrentState]), animations: { () -> Void in
self.menuView?.frame = CGRect(x: self.view.frame.size.width - 90, y: 54, width: 80, height: 100)
}, completion: { (finished) -> Void in
})
self.mask?.hidden = false
}
bottomBar = GalleryDetailBottomBar(frame: CGRect(x: 0, y: self.view.frame.size.height - 44, width: self.view.frame.size.width, height: 44));
self.view.addSubview(self.bottomBar!)
if (titleCache.characters.count > 0){
bottomBar?.title = titleCache
}
self.mask = UIButton(frame: self.view.bounds)
self.mask?.backgroundColor = UIColor.clearColor()
self.mask?.hidden = true
self.mask?.addTarget(self, action: Selector("onTapMask"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(self.mask!)
// 单击手势
let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("onTapView"))
self.view.addGestureRecognizer(tapRecognizer)
}
override func viewDidLoad() {
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if (keyPath == "currentShowNumber" ||
keyPath == "totalShowCount"){
self.bottomBar?.pageText = String(format:"%zd / %zd", (self.container?.currentShowNumber)!, (self.container?.totalShowCount)!)
}
}
override func viewDidAppear(animated: Bool) {
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
}
// 供单图使用
func loadImageData(data:ImageInfoData){
let arr:[AnyObject] = [data.url]
dispatch_async(dispatch_get_main_queue(),{ [weak self]() -> Void in
self?.container?.addDataSourceByArray(arr)
self?.bottomBar?.title = data.desc
self?.bottomBar?.hidePageTip = true;
})
}
// 供多图使用
func loadDetailTitle(title:String){
self.titleCache = title
}
// 供多图使用
func startRequest(imageSetId:Int){
let parameter:[NSObject:AnyObject] = [ "iid" : String(imageSetId),
"json" : "1"]
let url = ServerApi.gallery_get_galary_detail(parameter)
print("\n---$$$---url = \(url)", terminator: "")
AFDSClient.sharedInstance.GET(url, parameters: nil,
success: {[weak self](task, JSON) -> Void in
// print("\n responseJSON- - - - -data = \(JSON)")
// 如果请求数据有效
if let dic = JSON as? [NSObject:AnyObject]{
// print("\n responseJSON- - - - -data:", dic)
self?.processRequestResult(dic)
}
}, failure: {( task, error) -> Void in
print("\n failure: TIP --- e:\(error)")
})
}
func processRequestResult(result:[NSObject:AnyObject]){
if (200 == result["c"]?.integerValue){
if let list = result["v"] as? [AnyObject]{
var urlArr:[AnyObject] = [AnyObject]()
for item in list{
if let dic = item as? [NSObject: AnyObject]{
let data = ImageInfoData(dic: dic)
urlArr.append(data.url)
}
}
print("urlArr = \(urlArr)")
dispatch_async(dispatch_get_main_queue(),{ () -> Void in
self.container?.addDataSourceByArray(urlArr)
})
}
}
}
func onTapView(){
print("onTapView = = = = = = = =")
}
func onTapMask(){
print("on Tap mask = = = = = = = =")
self.dismissMenuView()
self.dismissShareView()
self.mask?.hidden = true
}
func dismissShareView(){
if (self.shareView != nil){
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options:UIViewAnimationOptions([.AllowUserInteraction, .BeginFromCurrentState]), animations: { () -> Void in
self.shareView?.frame = CGRect(x: 0, y: self.view.frame.size.height, width: self.view.frame.size.width, height: 170)
}, completion: { (finished) -> Void in
self.shareView?.removeFromSuperview()
self.shareView = nil
})
}
}
func dismissMenuView(){
if (self.menuView != nil){
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options:UIViewAnimationOptions([.AllowUserInteraction, .BeginFromCurrentState]), animations: { () -> Void in
self.menuView?.frame = CGRect(x: self.view.frame.size.width - 90, y: -120, width: 80, height: 100)
}, completion: { (finished) -> Void in
self.menuView?.removeFromSuperview()
self.menuView = nil
})
}
}
} | 9fe06f3841618e3c4d8bd3306a26a4d2 | 44.106383 | 235 | 0.555254 | false | false | false | false |
fandongtongxue/Unsplash | refs/heads/master | Unsplash/ViewController.swift | mit | 1 | //
// ViewController.swift
// Unsplash
//
// Created by 范东 on 17/2/4.
// Copyright © 2017年 范东. All rights reserved.
//
import UIKit
import SDWebImage
import MBProgressHUD
import Alamofire
import MJExtension
let url = "https://api.unsplash.com/photos/?client_id=522f34661134a2300e6d94d344a7ab6424e028a51b31353363b7a8cce11d73b6&per_page=30&page="
let cellId = "UnsplashPictureCellID"
let statusBarHeight : CGFloat = 20
let screenWidth : CGFloat = UIScreen.main.bounds.size.width
let screenHeight : CGFloat = UIScreen.main.bounds.size.height
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate {
var page : NSInteger = 1
var refreshControl : UIRefreshControl!
//懒加载
lazy var dataArray:NSMutableArray = {
let dataArray = NSMutableArray.init()
return dataArray
}()
lazy var collectionView:UICollectionView = {
let layout = UICollectionViewFlowLayout.init()
layout.itemSize = CGSize.init(width: UIScreen.main.bounds.size.width / 3, height: UIScreen.main.bounds.size.height / 3)
layout.minimumLineSpacing = 0;
layout.minimumInteritemSpacing = 0;
let collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: statusBarHeight, width: screenWidth, height: screenHeight - statusBarHeight), collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.black
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UnsplashPictureCell.self, forCellWithReuseIdentifier:cellId)
return collectionView;
}()
//生命周期
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.black
self.view.addSubview(self.collectionView)
self.initRefresh()
self.requestFirstPageData(isNeedHUD: true)
}
func initRefresh() {
let refreshControl = UIRefreshControl.init()
refreshControl.tintColor = UIColor.white
refreshControl.addTarget(self, action: #selector(requestFirstPageData(isNeedHUD:)), for: UIControlEvents.valueChanged)
self.collectionView.addSubview(refreshControl)
self.refreshControl = refreshControl
self.collectionView.alwaysBounceVertical = true
}
//请求第一页数据
func requestFirstPageData(isNeedHUD : Bool) {
if isNeedHUD {
MBProgressHUD.showAdded(to: self.view, animated: true)
}
page = 1
let firstUrl = url + String.init(format: "%d", page)
log.info("请求地址:"+firstUrl)
Alamofire.request(firstUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON(queue: DispatchQueue.main, options: .mutableContainers) { (response) in
switch response.result{
case .success:
self.dataArray.removeAllObjects()
if let result = response.result.value{
let array = result as! NSMutableArray
let model = UnsplashPictureModel.mj_objectArray(withKeyValuesArray: array) as [AnyObject]
self.dataArray.addObjects(from: model)
self.collectionView.reloadData()
self.refreshControl.endRefreshing()
}
MBProgressHUD.hide(for: self.view, animated: true)
case.failure(let error):
self.refreshControl.endRefreshing()
log.error(error)
MBProgressHUD.hide(for: self.view, animated: true)
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.mode = MBProgressHUDMode.text
hud.label.text = String.init(format: "%@", error as CVarArg)
hud.label.numberOfLines = 0;
hud.hide(animated: true, afterDelay: 2)
}
}
}
func requestMorePageData(page:NSInteger) {
let firstUrl = url + String.init(format: "%d", page)
log.info("请求地址:"+firstUrl)
Alamofire.request(firstUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON(queue: DispatchQueue.main, options: .mutableContainers) { (response) in
switch response.result{
case .success:
if let result = response.result.value{
let array = result as! NSMutableArray
let model = UnsplashPictureModel.mj_objectArray(withKeyValuesArray: array) as [AnyObject]
self.dataArray.addObjects(from: model)
}
self.collectionView.reloadData()
case.failure(let error):
print(error)
}
}
}
//UICollectionViewDelegate
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! UnsplashPictureCell
let model = self.dataArray[indexPath.row] as! UnsplashPictureModel
cell.setModel(model: model)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let model = self.dataArray[indexPath.row] as! UnsplashPictureModel
let vc = PictureViewController()
vc.model = model
self.present(vc, animated: true, completion: nil)
}
//UIScrollViewDelegate
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y + (scrollView.frame.size.height) > scrollView.contentSize.height {
log.info("到底")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var preferredStatusBarStyle: UIStatusBarStyle{
return UIStatusBarStyle.lightContent
}
}
| c8ecb242fa9ed98e2616d0a54edd7cfa | 40.331169 | 196 | 0.657345 | false | false | false | false |
CYXiang/CYXSwiftDemo | refs/heads/master | CYXSwiftDemo/CYXSwiftDemo/Classes/Other/String + Extension.swift | apache-2.0 | 1 | //
// String + Extension.swift
// CYXSwiftDemo
//
// Created by apple开发 on 16/5/18.
// Copyright © 2016年 cyx. All rights reserved.
//
import UIKit
extension String {
/// 清除字符串小数点末尾的0
func cleanDecimalPointZear() -> String {
let newStr = self as NSString
var s = NSString()
var offset = newStr.length - 1
while offset > 0 {
s = newStr.substringWithRange(NSMakeRange(offset, 1))
if s.isEqualToString("0") || s.isEqualToString(".") {
offset -= 1
} else {
break
}
}
return newStr.substringToIndex(offset + 1)
}
} | 567845288b5b702246b9bc1ea5cf46db | 20.25 | 65 | 0.5243 | false | false | false | false |
d4rkl0rd3r3b05/Data_Structure_And_Algorithm | refs/heads/master | MergeSort.swift | mit | 1 | func merge<T : Comparable>(leftArray: [T], rightArray: [T]) -> [T] {
var leftIndex = 0
var rightIndex = 0
//Order Array
var orderedArray = [T]()
//Re-ordering elements and merging left and right arrays
while leftIndex < leftArray.count && rightIndex < rightArray.count {
if leftArray[leftIndex] < rightArray[rightIndex] {
orderedArray.append(leftArray[leftIndex])
leftIndex += 1
} else if leftArray[leftIndex] > rightArray[rightIndex] {
orderedArray.append(rightArray[rightIndex])
rightIndex += 1
} else {
orderedArray.append(leftArray[leftIndex])
leftIndex += 1
orderedArray.append(rightArray[rightIndex])
rightIndex += 1
}
}
//Combining array
while leftIndex < leftArray.count {
orderedArray.append(leftArray[leftIndex])
leftIndex += 1
}
while rightIndex < rightArray.count {
orderedArray.append(rightArray[rightIndex])
rightIndex += 1
}
return orderedArray
}
public func mergeSort<T : Comparable>(_ array: [T]) -> [T] {
guard array.count > 1 else { return array }
let middleIndex = array.count / 2
let leftArray = mergeSort(Array(array[0..<middleIndex]))
let rightArray = mergeSort(Array(array[middleIndex..<array.count]))
return merge(leftArray : leftArray, rightArray: rightArray)
}
| a26b0b10d2cc43df0be0dcbabfd25f32 | 29.5625 | 72 | 0.610089 | false | false | false | false |
drewag/Swiftlier | refs/heads/master | Sources/Swiftlier/Formatting/Data+Base64.swift | mit | 1 | //
// Data+Base64.swift
// file-sync-services
//
// Created by Andrew J Wagner on 4/10/17.
//
//
import Foundation
extension Data {
static let base64Characters = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
static let base64UrlCharacters = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")
public var base64: String {
return [UInt8](self).base64
}
public var base64ForUrl: String {
return [UInt8](self).base64ForUrl
}
}
extension Array where Element == UInt8 {
public var base64: String {
return self.encode(withCharacters: Data.base64Characters)
}
public var base64ForUrl: String {
return self.encode(withCharacters: Data.base64UrlCharacters)
}
private func encode(withCharacters characters: [Character]) -> String {
var output = ""
var firstByte: UInt8?
var secondByte: UInt8?
var thirdByte: UInt8?
func appendPattern() {
guard let first = firstByte else {
return
}
let second = secondByte ?? 0
let third = thirdByte ?? 0
output.append(characters[Int(first >> 2)])
output.append(characters[Int((first << 6) >> 2 + second >> 4)])
if secondByte == nil {
output.append("=")
}
else {
output.append(characters[Int((second << 4) >> 2 + third >> 6)])
}
if thirdByte == nil {
output.append("=")
}
else {
output.append(characters[Int(third & 63)])
}
}
for byte in self {
guard firstByte != nil else {
firstByte = byte
continue
}
guard secondByte != nil else {
secondByte = byte
continue
}
thirdByte = byte
appendPattern()
firstByte = nil
secondByte = nil
thirdByte = nil
}
appendPattern()
return output
}
}
| 2b6c502ad5c0930038dfaeb99ce2ad6f | 24.072289 | 110 | 0.551177 | false | false | false | false |
kysonyangs/ysbilibili | refs/heads/master | ysbilibili/Classes/Player/Base/ZHNplayerUrlLoadingBackView.swift | mit | 1 | //
// ZHNplayerUrlLoadingBackView.swift
// zhnbilibili
//
// Created by zhn on 16/12/8.
// Copyright © 2016年 zhn. All rights reserved.
//
import UIKit
@objc protocol ZHNplayerUrlLoadingbackViewDelegate {
@objc optional func popViewControllerAction()
@objc optional func fullScreenAction()
@objc optional func copyMessageAction()
}
class ZHNplayerUrlLoadingBackView: UIView {
/// 代理
weak var delegate: ZHNplayerUrlLoadingbackViewDelegate?
// MARK: - 懒加载控件
lazy var noticeTableView: playerNoticeTableView = {
let noticeTableView = playerNoticeTableView()
return noticeTableView
}()
lazy var urlLoadingBackButton: UIButton = {
let urlLoadingBackButton = UIButton()
urlLoadingBackButton.setImage(UIImage(named: "hd_icnav_back_dark"), for: .normal)
urlLoadingBackButton.setImage(UIImage(named: "hd_icnav_back_dark"), for: .highlighted)
urlLoadingBackButton.addTarget(self, action: #selector(backAction), for: .touchUpInside)
return urlLoadingBackButton
}()
lazy var urlLoadingFullScreenButon: UIButton = {
let urlLoadingFullScreenButon = UIButton()
urlLoadingFullScreenButon.setImage(UIImage(named: "player_fullScreen_iphone-1"), for: .normal)
urlLoadingFullScreenButon.setImage(UIImage(named: "player_fullScreen_iphone-1"), for: .highlighted)
urlLoadingFullScreenButon.addTarget(self, action: #selector(fullScreenAction), for: .touchUpInside)
return urlLoadingFullScreenButon
}()
lazy var urlLoadingCopyMessageButton: UIButton = {
let urlLoadingCopyMessageButton = UIButton()
urlLoadingCopyMessageButton.setTitle("复制信息", for: .normal)
urlLoadingCopyMessageButton.setTitle("复制信息", for: .highlighted)
urlLoadingCopyMessageButton.setTitleColor(UIColor.black, for: .normal)
urlLoadingCopyMessageButton.setTitleColor(UIColor.black, for: .highlighted)
urlLoadingCopyMessageButton.titleLabel?.font = UIFont.systemFont(ofSize: 13)
urlLoadingCopyMessageButton.addTarget(self, action: #selector(copyAction), for: .touchUpInside)
return urlLoadingCopyMessageButton
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(noticeTableView)
self.addSubview(urlLoadingBackButton)
self.addSubview(urlLoadingFullScreenButon)
self.addSubview(urlLoadingCopyMessageButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let gifImageView = UIImageView.createPlayLoadingGif()
self.addSubview(gifImageView)
gifImageView.startAnimating()
gifImageView.snp.makeConstraints { (make) in
make.center.equalTo(self)
make.size.equalTo(CGSize(width: 40, height: 40))
}
noticeTableView.snp.makeConstraints { (make) in
make.left.equalTo(self)
make.bottom.equalTo(self)
make.width.equalTo(200)
make.height.equalTo(60)
}
urlLoadingBackButton.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(10)
make.top.equalTo(self).offset(25)
make.size.equalTo(CGSize(width: 20, height: 20))
}
urlLoadingFullScreenButon.snp.makeConstraints { (make) in
make.bottom.right.equalTo(self).offset(-10)
make.size.equalTo(CGSize(width: 25, height: 25))
}
urlLoadingCopyMessageButton.snp.makeConstraints { (make) in
make.centerY.equalTo(urlLoadingBackButton)
make.right.equalTo(self).offset(-10)
}
}
}
//======================================================================
// MARK:- target action
//======================================================================
extension ZHNplayerUrlLoadingBackView {
@objc fileprivate func backAction() {
guard let delegate = delegate else {return}
guard let method = delegate.popViewControllerAction else {return}
method()
}
@objc fileprivate func fullScreenAction() {
guard let delegate = delegate else {return}
guard let method = delegate.fullScreenAction else {return}
method()
}
@objc fileprivate func copyAction() {
guard let delegate = delegate else {return}
guard let method = delegate.copyMessageAction else {return}
method()
}
}
//======================================================================
// MARK:- 展示信息的view
//======================================================================
class playerNoticeTableView: UIView,UITableViewDataSource,UITableViewDelegate{
var titleArray = ["ABC12345","获取视频信息...","成功...","正在初始化设置...","正在初始化弹幕...","正在初始化播放器..."]
fileprivate lazy var contentTableView: UITableView = {
let contentTableView = UITableView()
contentTableView.dataSource = self
contentTableView.delegate = self
contentTableView.separatorStyle = .none
contentTableView.backgroundColor = kHomeBackColor
contentTableView.isScrollEnabled = false
contentTableView.isUserInteractionEnabled = false
return contentTableView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(contentTableView)
self.backgroundColor = UIColor.blue
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
contentTableView.snp.makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsets.zero)
}
}
// MARK: - tableview datasource delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titleArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = titleArray[indexPath.row]
cell.textLabel?.font = UIFont.systemFont(ofSize: 12)
cell.textLabel?.textColor = UIColor.lightGray
cell.backgroundColor = kHomeBackColor
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 20
}
// MARK: - 公共方法
func scrollToBottom() {
let indexPath = IndexPath(row: titleArray.count - 1, section: 0)
contentTableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
| f1d5430daf24035204ef8921f523ae56 | 35.148936 | 107 | 0.635815 | false | false | false | false |
michael-groble/motioncapture | refs/heads/master | MotionCapture/DataManager.swift | mit | 1 | // Copyright (c) 2014 Michael Groble
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import CoreData
class DataManager : NSObject
{
let bundleName: String?
let modelName: String
let databaseName: String
init(bundleName: String?, modelName: String, databaseName: String) {
self.bundleName = bundleName
self.modelName = modelName
self.databaseName = databaseName
}
var objectContext: NSManagedObjectContext {
get {
return clearableObjectContext.getOrCreateOnMainThread()
}
}
var objectModel: NSManagedObjectModel {
get {
return clearableObjectModel.getOrCreate()
}
}
func truncateDatabase() {
let store = persistentStoreCoordinator.persistentStoreForURL(databaseUrl)
objectContext.performBlockAndWait() {
self.objectContext.rollback()
var error: NSError? = nil;
if !self.persistentStoreCoordinator.removePersistentStore(store, error:&error) {
NSLog("Error trying to truncate database %@", error!)
}
else if !NSFileManager.defaultManager().removeItemAtPath(self.databaseUrl.path, error:&error) {
NSLog("Error trying to delete file %@", error!);
}
}
clearableObjectModel.clear()
clearableObjectContext.clear()
clearablePersistentStoreCoordinator.clear()
}
var databaseBytes: CLongLong {
get {
var size: AnyObject?
var error: NSError?
self.databaseUrl.getResourceValue(&size, forKey:NSURLFileSizeKey, error:&error)
return size == nil ? 0 : (size as NSNumber).longLongValue;
}
}
private lazy
var databaseUrl: NSURL = {
let directories = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let directory = directories[directories.endIndex-1] as NSURL
return directory.URLByAppendingPathComponent(self.databaseName)
}()
private
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
get {
return clearablePersistentStoreCoordinator.getOrCreate()
}
}
// Note, we need lazy on the clearables so we can access self in the initializer closures
private lazy
var clearableObjectContext: ClearableLazy<NSManagedObjectContext> = {
return ClearableLazy<NSManagedObjectContext>() {
let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
context.persistentStoreCoordinator = self.persistentStoreCoordinator
return context
}
}()
private lazy
var clearableObjectModel: ClearableLazy<NSManagedObjectModel> = {
return ClearableLazy<NSManagedObjectModel>() {
var bundle = NSBundle.mainBundle()
if let name = self.bundleName? {
if let bundlePath = bundle.pathForResource(name, ofType:"bundle") {
bundle = NSBundle(path: bundlePath)
}
}
// TODO load specific version, e.g.
// [bundle URLForResource:@"Blah2" withExtension:@"mom" subdirectory:@"Blah.momd"];
if let modelPath = bundle.pathForResource(self.modelName, ofType:"momd") {
let modelUrl = NSURL.fileURLWithPath(modelPath)
var objectModel = NSManagedObjectModel(contentsOfURL: modelUrl)
return objectModel;
}
NSLog("Unable to read data model %@: ", self.modelName);
abort();
}
}()
private lazy
var clearablePersistentStoreCoordinator: ClearableLazy<NSPersistentStoreCoordinator> = {
return ClearableLazy<NSPersistentStoreCoordinator>() {
var error: NSError?;
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel:self.objectModel)
if nil == self.createDatabase(persistentStoreCoordinator, error: &error) {
NSLog("Fatal error while creating persistent store: %@", error!);
abort();
}
return persistentStoreCoordinator;
}
}()
private
func createDatabase(coordinator: NSPersistentStoreCoordinator, error: NSErrorPointer) -> NSPersistentStore! {
let options = [NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true]
return coordinator.addPersistentStoreWithType(NSSQLiteStoreType,
configuration: nil,
URL: self.databaseUrl,
options: options,
error: error)
}
}
| f17e6cc1009c3e95eda7d9df216f59e4 | 35.662069 | 117 | 0.718962 | false | false | false | false |
steve-holmes/music-app-2 | refs/heads/master | MusicApp/Modules/Rank/RankCoordinator.swift | mit | 1 | //
// RankCoordinator.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/29/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import RxSwift
protocol RankCoordinator {
func presentSong(country: String) -> Observable<Void>
func presentPlaylist(_ playlists: [Playlist], country: String) -> Observable<Void>
func presentVideo(_ videos: [Video], country: String) -> Observable<Void>
}
class MARankCoordinator: RankCoordinator {
weak var sourceViewController: RankViewController?
var getSongController: (() -> RankSongViewController?)?
var getPlaylistController: (() -> RankPlaylistViewController?)?
var getVideoController: (() -> RankVideoViewController?)?
func presentSong(country: String) -> Observable<Void> {
guard let sourceController = sourceViewController else { return .empty() }
guard let destinationController = getSongController?() else { return .empty() }
destinationController.country = country
sourceController.show(destinationController, sender: nil)
return .empty()
}
func presentPlaylist(_ playlists: [Playlist], country: String) -> Observable<Void> {
guard let sourceController = sourceViewController else { return .empty() }
guard let destinationController = getPlaylistController?() else { return .empty() }
destinationController.playlists = playlists
destinationController.country = country
sourceController.show(destinationController, sender: self)
return .empty()
}
func presentVideo(_ videos: [Video], country: String) -> Observable<Void> {
guard let sourceController = sourceViewController else { return .empty() }
guard let destinationController = getVideoController?() else { return .empty() }
destinationController.videos = videos
destinationController.country = country
sourceController.show(destinationController, sender: self)
return .empty()
}
}
| a6f43d8f48e5b4fef32c52ce4c3da7b3 | 32.428571 | 91 | 0.662868 | false | false | false | false |
hooman/swift | refs/heads/main | test/SILOptimizer/definite_init_failable_initializers.swift | apache-2.0 | 4 | // RUN: %target-swift-frontend -emit-sil -disable-copy-propagation %s | %FileCheck %s
// Using -disable-copy-propagation to pattern match against older SIL
// output. At least until -enable-copy-propagation has been around
// long enough in the same form to be worth rewriting CHECK lines.
// High-level tests that DI handles early returns from failable and throwing
// initializers properly. The main complication is conditional release of self
// and stored properties.
// FIXME: not all of the test cases have CHECKs. Hopefully the interesting cases
// are fully covered, though.
////
// Structs with failable initializers
////
protocol Pachyderm {
init()
}
class Canary : Pachyderm {
required init() {}
}
// <rdar://problem/20941576> SILGen crash: Failable struct init cannot delegate to another failable initializer
struct TrivialFailableStruct {
init?(blah: ()) { }
init?(wibble: ()) {
self.init(blah: wibble)
}
}
struct FailableStruct {
let x, y: Canary
init(noFail: ()) {
x = Canary()
y = Canary()
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV24failBeforeInitializationACSgyt_tcfC
// CHECK: bb0(%0 : $@thin FailableStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: return [[SELF]]
init?(failBeforeInitialization: ()) {
return nil
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV30failAfterPartialInitializationACSgyt_tcfC
// CHECK: bb0(%0 : $@thin FailableStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[CANARY:%.*]] = apply
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: store [[CANARY]] to [[X_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[X_ADDR]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: return [[SELF]]
init?(failAfterPartialInitialization: ()) {
x = Canary()
return nil
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV27failAfterFullInitializationACSgyt_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[CANARY1:%.*]] = apply
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: store [[CANARY1]] to [[X_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct
// CHECK: [[CANARY2:%.*]] = apply
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct
// CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: store [[CANARY2]] to [[Y_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: return [[NEW_SELF]]
init?(failAfterFullInitialization: ()) {
x = Canary()
y = Canary()
return nil
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV46failAfterWholeObjectInitializationByAssignmentACSgyt_tcfC :
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[CANARY:%.*]] = apply
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableStruct
// CHECK-NEXT: store [[CANARY]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableStruct
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[SELF_VALUE:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: return [[SELF_VALUE]]
init?(failAfterWholeObjectInitializationByAssignment: ()) {
self = FailableStruct(noFail: ())
return nil
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV46failAfterWholeObjectInitializationByDelegationACSgyt_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14FailableStructV6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: return [[NEW_SELF]]
init?(failAfterWholeObjectInitializationByDelegation: ()) {
self.init(noFail: ())
return nil
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers14FailableStructV20failDuringDelegationACSgyt_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14FailableStructV24failBeforeInitializationACSgyt_tcfC
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0)
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[FAIL_BB]]:
// CHECK-NEXT: release_value [[SELF_OPTIONAL]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableStruct>)
//
// CHECK: [[SUCC_BB]]:
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: retain_value [[SELF_VALUE]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.some!enumelt, [[SELF_VALUE]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableStruct>)
//
// CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableStruct>)
// CHECK-NEXT: return [[NEW_SELF]]
// Optional to optional
init?(failDuringDelegation: ()) {
self.init(failBeforeInitialization: ())
}
// IUO to optional
init!(failDuringDelegation2: ()) {
self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!'
}
// IUO to IUO
init!(failDuringDelegation3: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
// non-optional to optional
init(failDuringDelegation4: ()) {
self.init(failBeforeInitialization: ())! // necessary '!'
}
// non-optional to IUO
init(failDuringDelegation5: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
}
extension FailableStruct {
init?(failInExtension: ()) {
self.init(failInExtension: failInExtension)
}
init?(assignInExtension: ()) {
self = FailableStruct(noFail: ())
}
}
struct FailableAddrOnlyStruct<T : Pachyderm> {
var x, y: T
init(noFail: ()) {
x = T()
y = T()
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failBeforeInitialization{{.*}}tcfC
// CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T>
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK: return
init?(failBeforeInitialization: ()) {
return nil
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failAfterPartialInitialization{{.*}}tcfC
// CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T>
// CHECK: [[X_BOX:%.*]] = alloc_stack $T
// CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type
// CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator
// CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: dealloc_stack [[X_BOX]]
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[X_ADDR]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK: return
init?(failAfterPartialInitialization: ()) {
x = T()
return nil
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failAfterFullInitialization{{.*}}tcfC
// CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T>
// CHECK: [[X_BOX:%.*]] = alloc_stack $T
// CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type
// CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator
// CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: dealloc_stack [[X_BOX]]
// CHECK-NEXT: [[Y_BOX:%.*]] = alloc_stack $T
// CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type
// CHECK-NEXT: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator
// CHECK-NEXT: apply [[T_INIT_FN]]<T>([[Y_BOX]], [[T_TYPE]])
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[WRITE]]
// CHECK-NEXT: copy_addr [take] [[Y_BOX]] to [initialization] [[Y_ADDR]]
// CHECK-NEXT: end_access [[WRITE]] : $*FailableAddrOnlyStruct<T>
// CHECK-NEXT: dealloc_stack [[Y_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK: return
init?(failAfterFullInitialization: ()) {
x = T()
y = T()
return nil
}
init?(failAfterWholeObjectInitializationByAssignment: ()) {
self = FailableAddrOnlyStruct(noFail: ())
return nil
}
init?(failAfterWholeObjectInitializationByDelegation: ()) {
self.init(noFail: ())
return nil
}
// Optional to optional
init?(failDuringDelegation: ()) {
self.init(failBeforeInitialization: ())
}
// IUO to optional
init!(failDuringDelegation2: ()) {
self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!'
}
// non-optional to optional
init(failDuringDelegation3: ()) {
self.init(failBeforeInitialization: ())! // necessary '!'
}
// non-optional to IUO
init(failDuringDelegation4: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
}
extension FailableAddrOnlyStruct {
init?(failInExtension: ()) {
self.init(failBeforeInitialization: failInExtension)
}
init?(assignInExtension: ()) {
self = FailableAddrOnlyStruct(noFail: ())
}
}
////
// Structs with throwing initializers
////
func unwrap(_ x: Int) throws -> Int { return x }
struct ThrowStruct {
var x: Canary
init(fail: ()) throws { x = Canary() }
init(noFail: ()) { x = Canary() }
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV20failBeforeDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeDelegation: Int) throws {
try unwrap(failBeforeDelegation)
self.init(noFail: ())
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV28failBeforeOrDuringDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeOrDuringDelegation: Int) throws {
try unwrap(failBeforeOrDuringDelegation)
try self.init(fail: ())
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV29failBeforeOrDuringDelegation2ACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV20failBeforeDelegationACSi_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]]([[RESULT]], %1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeOrDuringDelegation2: Int) throws {
try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV20failDuringDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failDuringDelegation: Int) throws {
try self.init(fail: ())
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV19failAfterDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterDelegation: Int) throws {
self.init(noFail: ())
try unwrap(failAfterDelegation)
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV27failDuringOrAfterDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowStruct
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:.*]] : $ThrowStruct):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: release_value [[NEW_SELF]]
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failDuringOrAfterDelegation: Int) throws {
try self.init(fail: ())
try unwrap(failDuringOrAfterDelegation)
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV27failBeforeOrAfterDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowStruct
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: release_value [[NEW_SELF]]
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeOrAfterDelegation: Int) throws {
try unwrap(failBeforeOrAfterDelegation)
self.init(noFail: ())
try unwrap(failBeforeOrAfterDelegation)
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV16throwsToOptionalACSgSi_tcfC
// CHECK: bb0([[ARG1:%.*]] : $Int, [[ARG2:%.*]] : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV20failDuringDelegationACSi_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]]([[ARG1]], [[ARG2]]) : $@convention(method) (Int, @thin ThrowStruct.Type) -> (@owned ThrowStruct, @error Error), normal [[TRY_APPLY_SUCC_BB:bb[0-9]+]], error [[TRY_APPLY_FAIL_BB:bb[0-9]+]]
//
// CHECK: [[TRY_APPLY_SUCC_BB]]([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt, [[NEW_SELF]]
// CHECK-NEXT: br [[TRY_APPLY_CONT:bb[0-9]+]]([[SELF_OPTIONAL]] : $Optional<ThrowStruct>)
//
// CHECK: [[TRY_APPLY_CONT]]([[SELF_OPTIONAL:%.*]] : $Optional<ThrowStruct>):
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[FAIL_BB]]:
// CHECK: release_value [[SELF_OPTIONAL]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<ThrowStruct>)
//
// CHECK: [[SUCC_BB]]:
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: retain_value [[SELF_VALUE]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt, [[SELF_VALUE]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<ThrowStruct>)
//
// CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<ThrowStruct>):
// CHECK-NEXT: return [[NEW_SELF]] : $Optional<ThrowStruct>
//
// CHECK: [[TRY_APPLY_FAIL_BB]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: strong_release [[ERROR]] : $Error
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt
// CHECK-NEXT: br [[TRY_APPLY_CONT]]([[NEW_SELF]] : $Optional<ThrowStruct>)
init?(throwsToOptional: Int) {
try? self.init(failDuringDelegation: throwsToOptional)
}
init(throwsToIUO: Int) {
try! self.init(failDuringDelegation: throwsToIUO)
}
init?(throwsToOptionalThrows: Int) throws {
try? self.init(fail: ())
}
init(throwsOptionalToThrows: Int) throws {
self.init(throwsToOptional: throwsOptionalToThrows)!
}
init?(throwsOptionalToOptional: Int) {
try! self.init(throwsToOptionalThrows: throwsOptionalToOptional)
}
init(failBeforeSelfReplacement: Int) throws {
try unwrap(failBeforeSelfReplacement)
self = ThrowStruct(noFail: ())
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV25failDuringSelfReplacementACSi_tKcfC :
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV4failACyt_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*ThrowStruct
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*ThrowStruct
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failDuringSelfReplacement: Int) throws {
try self = ThrowStruct(fail: ())
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers11ThrowStructV24failAfterSelfReplacementACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers11ThrowStructV6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [static] [[SELF_BOX]] : $*ThrowStruct
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: release_value [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterSelfReplacement: Int) throws {
self = ThrowStruct(noFail: ())
try unwrap(failAfterSelfReplacement)
}
}
extension ThrowStruct {
init(failInExtension: ()) throws {
try self.init(fail: failInExtension)
}
init(assignInExtension: ()) throws {
try self = ThrowStruct(fail: ())
}
}
struct ThrowAddrOnlyStruct<T : Pachyderm> {
var x : T
init(fail: ()) throws { x = T() }
init(noFail: ()) { x = T() }
init(failBeforeDelegation: Int) throws {
try unwrap(failBeforeDelegation)
self.init(noFail: ())
}
init(failBeforeOrDuringDelegation: Int) throws {
try unwrap(failBeforeOrDuringDelegation)
try self.init(fail: ())
}
init(failBeforeOrDuringDelegation2: Int) throws {
try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
}
init(failDuringDelegation: Int) throws {
try self.init(fail: ())
}
init(failAfterDelegation: Int) throws {
self.init(noFail: ())
try unwrap(failAfterDelegation)
}
init(failDuringOrAfterDelegation: Int) throws {
try self.init(fail: ())
try unwrap(failDuringOrAfterDelegation)
}
init(failBeforeOrAfterDelegation: Int) throws {
try unwrap(failBeforeOrAfterDelegation)
self.init(noFail: ())
try unwrap(failBeforeOrAfterDelegation)
}
init?(throwsToOptional: Int) {
try? self.init(failDuringDelegation: throwsToOptional)
}
init(throwsToIUO: Int) {
try! self.init(failDuringDelegation: throwsToIUO)
}
init?(throwsToOptionalThrows: Int) throws {
try? self.init(fail: ())
}
init(throwsOptionalToThrows: Int) throws {
self.init(throwsToOptional: throwsOptionalToThrows)!
}
init?(throwsOptionalToOptional: Int) {
try! self.init(throwsOptionalToThrows: throwsOptionalToOptional)
}
init(failBeforeSelfReplacement: Int) throws {
try unwrap(failBeforeSelfReplacement)
self = ThrowAddrOnlyStruct(noFail: ())
}
init(failAfterSelfReplacement: Int) throws {
self = ThrowAddrOnlyStruct(noFail: ())
try unwrap(failAfterSelfReplacement)
}
}
extension ThrowAddrOnlyStruct {
init(failInExtension: ()) throws {
try self.init(fail: failInExtension)
}
init(assignInExtension: ()) throws {
self = ThrowAddrOnlyStruct(noFail: ())
}
}
////
// Classes with failable initializers
////
class FailableBaseClass {
var member: Canary
init(noFail: ()) {
member = Canary()
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC28failBeforeFullInitializationACSgyt_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK: [[METATYPE:%.*]] = metatype $@thick FailableBaseClass.Type
// CHECK: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]]
// CHECK: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK: return [[RESULT]]
init?(failBeforeFullInitialization: ()) {
return nil
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC27failAfterFullInitializationACSgyt_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK: [[CANARY:%.*]] = apply
// CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[MEMBER_ADDR]] : $*Canary
// CHECK-NEXT: store [[CANARY]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*Canary
// CHECK-NEXT: strong_release %0
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: return [[NEW_SELF]]
init?(failAfterFullInitialization: ()) {
member = Canary()
return nil
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC20failBeforeDelegationACSgyt_tcfC
// CHECK: bb0(%0 : $@thick FailableBaseClass.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: return [[RESULT]]
convenience init?(failBeforeDelegation: ()) {
return nil
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC19failAfterDelegationACSgyt_tcfC
// CHECK: bb0(%0 : $@thick FailableBaseClass.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
// CHECK: [[INIT_FN:%.*]] = class_method %0
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: return [[RESULT]]
convenience init?(failAfterDelegation: ()) {
self.init(noFail: ())
return nil
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17FailableBaseClassC20failDuringDelegationACSgyt_tcfC
// CHECK: bb0(%0 : $@thick FailableBaseClass.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
// CHECK: [[INIT_FN:%.*]] = class_method %0
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0)
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[FAIL_BB]]:
// CHECK: release_value [[SELF_OPTIONAL]]
// CHECK: br [[FAIL_TRAMPOLINE_BB:bb[0-9]+]]
//
// CHECK: [[SUCC_BB]]:
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: strong_retain [[SELF_VALUE]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt, [[SELF_VALUE]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableBaseClass>)
//
// CHECK: [[FAIL_TRAMPOLINE_BB]]:
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<FailableBaseClass>)
//
// CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableBaseClass>):
// CHECK-NEXT: return [[NEW_SELF]]
// Optional to optional
convenience init?(failDuringDelegation: ()) {
self.init(failBeforeFullInitialization: ())
}
// IUO to optional
convenience init!(failDuringDelegation2: ()) {
self.init(failBeforeFullInitialization: ())! // unnecessary-but-correct '!'
}
// IUO to IUO
convenience init!(noFailDuringDelegation: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
// non-optional to optional
convenience init(noFailDuringDelegation2: ()) {
self.init(failBeforeFullInitialization: ())! // necessary '!'
}
}
extension FailableBaseClass {
convenience init?(failInExtension: ()) throws {
self.init(failBeforeFullInitialization: failInExtension)
}
}
// Chaining to failable initializers in a superclass
class FailableDerivedClass : FailableBaseClass {
var otherMember: Canary
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers20FailableDerivedClassC27derivedFailBeforeDelegationACSgyt_tcfc
// CHECK: bb0(%0 : $FailableDerivedClass):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK-NEXT: [[RELOAD_FROM_SELF_BOX:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick FailableDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref [[RELOAD_FROM_SELF_BOX]] : $FailableDerivedClass, [[METATYPE]] : $@thick FailableDerivedClass.Type
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt
// CHECK-NEXT: return [[RESULT]]
// CHECK: } // end sil function '$s35definite_init_failable_initializers20FailableDerivedClassC27derivedFailBeforeDelegationACSgyt_tcfc'
init?(derivedFailBeforeDelegation: ()) {
return nil
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers20FailableDerivedClassC27derivedFailDuringDelegationACSgyt_tcfc
// CHECK: bb0([[SELF:%.*]] : $FailableDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass
// CHECK: store [[SELF]] to [[SELF_BOX]]
// CHECK: [[CANARY_FUN:%.*]] = function_ref @$s35definite_init_failable_initializers6CanaryCACycfC :
// CHECK: [[CANARY:%.*]] = apply [[CANARY_FUN]](
// CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr [[SELF]]
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[MEMBER_ADDR]] : $*Canary
// CHECK-NEXT: store [[CANARY]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*Canary
// CHECK-NEXT: strong_release [[SELF]]
// CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17FailableBaseClassC28failBeforeFullInitializationACSgyt_tcfc
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], [[SUCC_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]]
//
// CHECK: [[FAIL_BB]]:
// CHECK-NEXT: release_value [[SELF_OPTIONAL]]
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt
// CHECK-NEXT: br [[EPILOG_BB]]([[NEW_SELF]] : $Optional<FailableDerivedClass>)
//
// CHECK: [[SUCC_BB]]:
// CHECK-NEXT: [[BASE_SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_ref_cast [[BASE_SELF_VALUE]]
// CHECK-NEXT: strong_retain [[SELF_VALUE]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.some!enumelt, [[SELF_VALUE]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: br [[EPILOG_BB:bb[0-9]+]]([[NEW_SELF]] : $Optional<FailableDerivedClass>)
//
// CHECK: [[EPILOG_BB]]([[NEW_SELF:%.*]] : $Optional<FailableDerivedClass>):
// CHECK-NEXT: return [[NEW_SELF]] : $Optional<FailableDerivedClass>
// CHECK: } // end sil function '$s35definite_init_failable_initializers20FailableDerivedClassC27derivedFailDuringDelegationACSgyt_tcfc'
init?(derivedFailDuringDelegation: ()) {
self.otherMember = Canary()
super.init(failBeforeFullInitialization: ())
}
init?(derivedFailAfterDelegation: ()) {
self.otherMember = Canary()
super.init(noFail: ())
return nil
}
// non-optional to IUO
init(derivedNoFailDuringDelegation: ()) {
self.otherMember = Canary()
super.init(failAfterFullInitialization: ())! // necessary '!'
}
// IUO to IUO
init!(derivedFailDuringDelegation2: ()) {
self.otherMember = Canary()
super.init(failAfterFullInitialization: ())! // unnecessary-but-correct '!'
}
}
extension FailableDerivedClass {
convenience init?(derivedFailInExtension: ()) throws {
self.init(derivedFailDuringDelegation: derivedFailInExtension)
}
}
////
// Classes with throwing initializers
////
class ThrowBaseClass {
required init() throws {}
init(noFail: ()) {}
}
class ThrowDerivedClass : ThrowBaseClass {
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK: bb0([[SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store [[SELF]] to [[SELF_BOX]]
// CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
required init() throws {
try super.init()
}
override init(noFail: ()) {
try! super.init()
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitializationACSi_tKcfc
// CHECK: bb0(%0 : $Int, [[SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store [[SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]] : $ThrowDerivedClass
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref [[RELOAD_SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
super.init(noFail: ())
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h6DuringjK0ACSi_SitKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %2 to [[SELF_BOX]] : $*ThrowDerivedClass
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int)
// CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: try_apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref [[RELOAD_SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
try super.init()
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC27failAfterFullInitializationACSi_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: strong_release [[DERIVED_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterFullInitialization: Int) throws {
super.init(noFail: ())
try unwrap(failAfterFullInitialization)
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC27failAfterFullInitialization0h6DuringjK0ACSi_SitKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %2 to [[SELF_BOX]]
// CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = upcast [[RELOAD_SELF]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK: try_apply [[INIT_FN]]([[DERIVED_SELF]])
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: strong_release [[DERIVED_SELF]]
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterFullInitialization: Int, failDuringFullInitialization: Int) throws {
try super.init()
try unwrap(failAfterFullInitialization)
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h5AfterjK0ACSi_SitKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %2 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[TWO:%.*]] = integer_literal $Builtin.Int2, -2
// CHECK-NEXT: store [[TWO]] to [[BITMAP_BOX]]
// CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassC6noFailACyt_tcfc
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[ONE]] to [[BITMAP_BOX]]
// CHECK: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%1)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: strong_release [[DERIVED_SELF]]
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2) : $Builtin.Int1
// CHECK-NEXT: cond_br [[COND]], bb6, bb10
// CHECK: bb6:
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[SHIFTED:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2) : $Builtin.Int2
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[SHIFTED]] : $Builtin.Int2) : $Builtin.Int1
// CHECK-NEXT: cond_br [[COND]], bb7, bb8
// CHECK: bb7:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb9
// CHECK: bb8:
// CHECK-NEXT: br bb9
// CHECK: bb9:
// CHECK-NEXT: br bb11
// CHECK: bb10:
// CHECK-NEXT: [[BITMAP:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref [[BITMAP]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb11
// CHECK: bb11:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]] : $Error
init(failBeforeFullInitialization: Int, failAfterFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
super.init(noFail: ())
try unwrap(failAfterFullInitialization)
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeFullInitialization0h6DuringjK00h5AfterjK0ACSi_S2itKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $Int, %3 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %3 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[RELOAD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[RELOAD_SELF]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: store [[ONE]] to [[BITMAP_BOX]]
// CHECK: try_apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[NEG_ONE:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[NEG_ONE]] to [[BITMAP_BOX]]
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: strong_retain [[DERIVED_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%2)
// CHECK: bb3([[RESULT:%.*]] : $Int):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb7([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb7([[ERROR]] : $Error)
// CHECK: bb6([[ERROR:%.*]] : $Error):
// CHECK-NEXT: strong_release [[DERIVED_SELF]]
// CHECK-NEXT: br bb7([[ERROR]] : $Error)
// CHECK: bb7([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb8, bb12
// CHECK: bb8:
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb9, bb10
// CHECK: bb9:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb11
// CHECK: bb10:
// CHECK-NEXT: br bb11
// CHECK: bb11:
// CHECK-NEXT: br bb13
// CHECK: bb12:
// CHECK-NEXT: [[SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref [[SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb13
// CHECK: bb13:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int, failAfterFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
try super.init()
try unwrap(failAfterFullInitialization)
}
convenience init(noFail2: ()) {
try! self.init()
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC20failBeforeDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[ARG:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
convenience init(failBeforeDelegation: Int) throws {
try unwrap(failBeforeDelegation)
self.init(noFail: ())
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC20failDuringDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassCACyKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]] : $Error
convenience init(failDuringDelegation: Int) throws {
try self.init()
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC28failBeforeOrDuringDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[ARG:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassCACyKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR1:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR1]] : $Error)
// CHECK: bb4([[ERROR2:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR2]] : $Error)
// CHECK: bb5([[ERROR3:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR3]]
convenience init(failBeforeOrDuringDelegation: Int) throws {
try unwrap(failBeforeOrDuringDelegation)
try self.init()
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC29failBeforeOrDuringDelegation2ACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[ARG:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassC20failBeforeDelegationACSi_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]]([[ARG]], %1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR1]] : $Error)
// CHECK: bb4([[ERROR2:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR2]] : $Error)
// CHECK: bb5([[ERROR3:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR3]]
convenience init(failBeforeOrDuringDelegation2: Int) throws {
try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC19failAfterDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: strong_release [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
convenience init(failAfterDelegation: Int) throws {
self.init(noFail: ())
try unwrap(failAfterDelegation)
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC27failDuringOrAfterDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type):
// CHECK: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassCACyKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR1:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR1]] : $Error)
// CHECK: bb4([[ERROR2:%.*]] : $Error):
// CHECK-NEXT: strong_release [[NEW_SELF]]
// CHECK-NEXT: br bb5([[ERROR2]] : $Error)
// CHECK: bb5([[ERROR3:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK: cond_br {{.*}}, bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR3]]
convenience init(failDuringOrAfterDelegation: Int) throws {
try self.init()
try unwrap(failDuringOrAfterDelegation)
}
// CHECK-LABEL: sil hidden @$s35definite_init_failable_initializers17ThrowDerivedClassC27failBeforeOrAfterDelegationACSi_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thick ThrowDerivedClass.Type):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack [dynamic_lifetime] $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @$s35definite_init_failable_initializers17ThrowDerivedClassC6noFailACyt_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @$s35definite_init_failable_initializers6unwrapyS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: strong_release [[NEW_SELF]]
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK: cond_br {{.*}}, bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
convenience init(failBeforeOrAfterDelegation: Int) throws {
try unwrap(failBeforeOrAfterDelegation)
self.init(noFail: ())
try unwrap(failBeforeOrAfterDelegation)
}
}
////
// Enums with failable initializers
////
enum FailableEnum {
case A
init?(a: Int64) { self = .A }
init!(b: Int64) {
self.init(a: b)! // unnecessary-but-correct '!'
}
init(c: Int64) {
self.init(a: c)! // necessary '!'
}
init(d: Int64) {
self.init(b: d)! // unnecessary-but-correct '!'
}
}
////
// Protocols and protocol extensions
////
// Delegating to failable initializers from a protocol extension to a
// protocol.
protocol P1 {
init?(p1: Int64)
}
extension P1 {
init!(p1a: Int64) {
self.init(p1: p1a)! // unnecessary-but-correct '!'
}
init(p1b: Int64) {
self.init(p1: p1b)! // necessary '!'
}
}
protocol P2 : class {
init?(p2: Int64)
}
extension P2 {
init!(p2a: Int64) {
self.init(p2: p2a)! // unnecessary-but-correct '!'
}
init(p2b: Int64) {
self.init(p2: p2b)! // necessary '!'
}
}
// Delegating to failable initializers from a protocol extension to a
// protocol extension.
extension P1 {
init?(p1c: Int64) {
self.init(p1: p1c)
}
init!(p1d: Int64) {
self.init(p1c: p1d)! // unnecessary-but-correct '!'
}
init(p1e: Int64) {
self.init(p1c: p1e)! // necessary '!'
}
}
extension P2 {
init?(p2c: Int64) {
self.init(p2: p2c)
}
init!(p2d: Int64) {
self.init(p2c: p2d)! // unnecessary-but-correct '!'
}
init(p2e: Int64) {
self.init(p2c: p2e)! // necessary '!'
}
}
////
// type(of: self) with uninitialized self
////
func use(_ a : Any) {}
class DynamicTypeBase {
var x: Int
init() {
use(type(of: self))
x = 0
}
convenience init(a : Int) {
use(type(of: self))
self.init()
}
}
class DynamicTypeDerived : DynamicTypeBase {
override init() {
use(type(of: self))
super.init()
}
convenience init(a : Int) {
use(type(of: self))
self.init()
}
}
struct DynamicTypeStruct {
var x: Int
init() {
use(type(of: self))
x = 0
}
init(a : Int) {
use(type(of: self))
self.init()
}
}
| 35a384f482d35d2c888f1c66749d03ed | 42.480867 | 227 | 0.623412 | false | false | false | false |
juliangrosshauser/MotionActivityDisplay | refs/heads/master | MotionActivityDisplay/Source/Classes/View Controllers/MotionActivityViewController.swift | mit | 1 | //
// MotionActivityViewController.swift
// MotionActivityDisplay
//
// Created by Julian Grosshauser on 19/06/15.
// Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//
import UIKit
import CoreMotion
class MotionActivityViewController: UIViewController {
//MARK: Properties
private let motionActivityManager = CMMotionActivityManager()
private let titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
if CMMotionActivityManager.isActivityAvailable() {
titleLabel.text = "Current motion type:"
} else {
titleLabel.text = "Motion data isn't available on this device"
}
return titleLabel
}()
private let motionTypeLabel: UILabel = {
let motionTypeLabel = UILabel()
motionTypeLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
motionTypeLabel.numberOfLines = 0
motionTypeLabel.textAlignment = .Center
return motionTypeLabel
}()
//MARK: Initialization
init() {
super.init(nibName: nil, bundle: nil)
title = "Motion Activity Display"
if CMMotionActivityManager.isActivityAvailable() {
let historyButton = UIBarButtonItem(title: "History", style: .Plain, target: self, action: "showHistory:")
navigationItem.leftBarButtonItem = historyButton
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
//MARK: UIViewController
override func viewDidLoad() {
view.addSubview(titleLabel)
view.addSubview(motionTypeLabel)
let verticalTitleConstraint = NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 0.5, constant: 0)
let horizontalTitleConstraint = NSLayoutConstraint(item: titleLabel, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0)
let verticalMotionTypeConstraint = NSLayoutConstraint(item: motionTypeLabel, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0)
let horizontalMotionTypeConstraint = NSLayoutConstraint(item: motionTypeLabel, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0)
view.addConstraints([verticalTitleConstraint, horizontalTitleConstraint, verticalMotionTypeConstraint, horizontalMotionTypeConstraint])
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if CMMotionActivityManager.isActivityAvailable() {
let motionActivityHandler: CMMotionActivityHandler = { [unowned self] activity in
let motionTypes = join("\n", activity.motionTypes)
self.motionTypeLabel.text = "\(motionTypes)\n\(activity.printableDate)\n\(activity.printableConfidence)"
}
motionActivityManager.startActivityUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: motionActivityHandler)
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
if CMMotionActivityManager.isActivityAvailable() {
motionActivityManager.stopActivityUpdates()
}
}
//MARK: Button Actions
@objc
private func showHistory(sender: AnyObject) {
presentViewController(UINavigationController(rootViewController: HistoryTableViewController()), animated: true, completion: nil)
}
}
| a0ecb77dba90687838c4c4db89ceafd1 | 34.441176 | 189 | 0.702351 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/Models/Notifications/NotificationSettings.swift | gpl-2.0 | 1 | import Foundation
/// The goal of this class is to encapsulate all of the User's Notification Settings in a generic way.
/// Settings are grouped into different Channels. A Channel is considered anything that might produce
/// Notifications: a WordPress blog, Third Party Sites or WordPress.com.
/// Each channel may support different streams, such as: Email + Push Notifications + Timeline.
///
open class NotificationSettings {
/// Represents the Channel to which the current settings are associated.
///
public let channel: Channel
/// Contains an array of the available Notification Streams.
///
public let streams: [Stream]
/// Maps to the associated blog, if any.
///
public let blog: Blog?
/// The settings that are stored locally
///
static let locallyStoredKeys: [String] = [
Keys.weeklyRoundup,
]
/// Designated Initializer
///
/// - Parameters:
/// - channel: The related Notifications Channel
/// - streams: An array of all of the involved streams
/// - blog: The associated blog, if any
///
public init(channel: Channel, streams: [Stream], blog: Blog?) {
self.channel = channel
self.streams = streams
self.blog = blog
}
/// Returns the localized description for any given preference key
///
open func localizedDescription(_ preferenceKey: String) -> String {
return Keys.localizedDescriptionMap[preferenceKey] ?? String()
}
/// Returns the details for a given preference key
///
open func localizedDetails(_ preferenceKey: String) -> String? {
return Keys.localizedDetailsMap[preferenceKey]
}
static func isLocallyStored(_ preferenceKey: String) -> Bool {
return Self.locallyStoredKeys.contains(preferenceKey)
}
/// Returns an array of the sorted Preference Keys
///
open func sortedPreferenceKeys(_ stream: Stream?) -> [String] {
switch channel {
case .blog:
// Email Streams require a special treatment
return stream?.kind == .Email ? blogEmailPreferenceKeys : blogPreferenceKeys
case .other:
return otherPreferenceKeys
case .wordPressCom:
return wpcomPreferenceKeys
}
}
/// Represents a communication channel that may post notifications to the user.
///
public enum Channel: Equatable {
case blog(blogId: Int)
case other
case wordPressCom
/// Returns the localized description of the current enum value
///
func description() -> String {
switch self {
case .blog:
return NSLocalizedString("WordPress Blog", comment: "Settings for a Wordpress Blog")
case .other:
return NSLocalizedString("Comments on Other Sites", comment: "Notification Settings Channel")
case .wordPressCom:
return NSLocalizedString("Email from WordPress.com", comment: "Notification Settings Channel")
}
}
}
/// Contains the Notification Settings collection for a specific communications stream.
///
open class Stream {
open var kind: Kind
open var preferences: [String: Bool]?
/// Designated Initializer
///
/// - Parameters:
/// - kind: The Kind of stream we're currently dealing with
/// - preferences: Raw remote preferences, retrieved from the backend
///
public init(kind: String, preferences: [String: Bool]?) {
self.kind = Kind(rawValue: kind) ?? .Email
self.preferences = preferences
}
/// Enumerates all of the possible Stream Kinds
///
public enum Kind: String {
case Timeline = "timeline"
case Email = "email"
case Device = "device"
/// Returns the localized description of the current enum value
///
func description() -> String {
switch self {
case .Timeline:
return NSLocalizedString("Notifications Tab", comment: "WordPress.com Notifications Timeline")
case .Email:
return NSLocalizedString("Email", comment: "Email Notifications Channel")
case .Device:
return NSLocalizedString("Push Notifications", comment: "Mobile Push Notifications")
}
}
static let allValues = [ Timeline, Email, Device ]
}
}
// MARK: - Private Properties
fileprivate let blogPreferenceKeys: [String] = {
var keys = [Keys.commentAdded, Keys.commentLiked, Keys.postLiked, Keys.follower, Keys.achievement, Keys.mention]
if Feature.enabled(.weeklyRoundup) {
keys.append(Keys.weeklyRoundup)
}
return keys
}()
fileprivate let blogEmailPreferenceKeys = [Keys.commentAdded, Keys.commentLiked, Keys.postLiked, Keys.follower, Keys.mention]
fileprivate let otherPreferenceKeys = [Keys.commentLiked, Keys.commentReplied]
fileprivate let wpcomPreferenceKeys = [Keys.marketing, Keys.research, Keys.community]
// MARK: - Setting Keys
fileprivate struct Keys {
static let commentAdded = "new_comment"
static let commentLiked = "comment_like"
static let commentReplied = "comment_reply"
static let postLiked = "post_like"
static let follower = "follow"
static let achievement = "achievement"
static let mention = "mentions"
static let marketing = "marketing"
static let research = "research"
static let community = "community"
static let weeklyRoundup = "weekly_roundup"
static let localizedDescriptionMap = [
commentAdded: NSLocalizedString("Comments on my site",
comment: "Setting: indicates if New Comments will be notified"),
commentLiked: NSLocalizedString("Likes on my comments",
comment: "Setting: indicates if Comment Likes will be notified"),
postLiked: NSLocalizedString("Likes on my posts",
comment: "Setting: indicates if Replies to your comments will be notified"),
follower: NSLocalizedString("Site follows",
comment: "Setting: indicates if New Follows will be notified"),
achievement: NSLocalizedString("Site achievements",
comment: "Setting: indicates if Achievements will be notified"),
mention: NSLocalizedString("Username mentions",
comment: "Setting: indicates if Mentions will be notified"),
commentReplied: NSLocalizedString("Replies to your comments",
comment: "Setting: indicates if Replies to Comments will be notified"),
marketing: NSLocalizedString("Suggestions",
comment: "Setting: WordPress.com Suggestions"),
research: NSLocalizedString("Research",
comment: "Setting: WordPress.com Surveys"),
community: NSLocalizedString("Community",
comment: "Setting: WordPress.com Community"),
weeklyRoundup: NSLocalizedString("Weekly Roundup",
comment: "Setting: indicates if the site reports its Weekly Roundup"),
]
static let localizedDetailsMap = [
marketing: NSLocalizedString("Tips for getting the most out of WordPress.com.",
comment: "WordPress.com Marketing Footer Text"),
research: NSLocalizedString("Opportunities to participate in WordPress.com research & surveys.",
comment: "WordPress.com Research Footer Text"),
community: NSLocalizedString("Information on WordPress.com courses and events (online & in-person).",
comment: "WordPress.com Community Footer Text")
]
}
}
/// Swift requires this method to be implemented globally. Sorry about that!
///
public func ==(first: NotificationSettings.Channel, second: NotificationSettings.Channel) -> Bool {
switch (first, second) {
case (let .blog(firstBlogId), let .blog(secondBlogId)) where firstBlogId == secondBlogId:
return true
case (.other, .other):
return true
case (.wordPressCom, .wordPressCom):
return true
default:
return false
}
}
| 3e037eea353fce770a2f8760a79adbbe | 39.6621 | 129 | 0.594161 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.