repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ps2/rileylink_ios | MinimedKit/Messages/BolusCarelinkMessageBody.swift | 1 | 1118 | //
// BolusCarelinkMessageBody.swift
// Naterade
//
// Created by Nathan Racklyeft on 3/5/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
public class BolusCarelinkMessageBody: CarelinkLongMessageBody {
public convenience init(units: Double, insulinBitPackingScale: Int = 10) {
let length: Int
let scrollRate: Int
if insulinBitPackingScale >= 40 {
length = 2
// 40-stroke pumps scroll faster for higher unit values
switch units {
case let u where u > 10:
scrollRate = 4
case let u where u > 1:
scrollRate = 2
default:
scrollRate = 1
}
} else {
length = 1
scrollRate = 1
}
let strokes = Int(units * Double(insulinBitPackingScale / scrollRate)) * scrollRate
let data = Data(hexadecimalString: String(format: "%02x%0\(2 * length)x", length, strokes))!
self.init(rxData: data)!
}
}
| mit | f4457affe5d38b0fb84c458e2fa2adea | 24.976744 | 100 | 0.539839 | 4.793991 | false | false | false | false |
cubixlabs/SocialGIST | Pods/GISTFramework/GISTFramework/Classes/Controls/FloatingLabelTextField.swift | 1 | 18936 | //
// FloatingLabelTextField.swift
// GISTFramework
//
// Created by Shoaib Abdul on 14/03/2017.
// Copyright © 2017 Social Cubix. All rights reserved.
//
import UIKit
open class FloatingLabelTextField: ValidatedTextField {
// MARK: Animation timing
/// The value of the title appearing duration
open var titleFadeInDuration:TimeInterval = 0.2
/// The value of the title disappearing duration
open var titleFadeOutDuration:TimeInterval = 0.3
// MARK: Title
/// The String to display when the textfield is not editing and the input is not empty.
@IBInspectable open var title:String? {
didSet {
self.updateControl();
}
} //P.E.
/// The String to display when the textfield is editing and the input is not empty.
@IBInspectable open var titleSelected:String? {
didSet {
self.updateControl();
}
} //P.E.
// MARK: Font Style
/// Font size/style key from Sync Engine.
@IBInspectable open var titleFontStyle:String = GIST_CONFIG.fontStyle {
didSet {
self.titleLabel.fontStyle = self.titleFontStyle;
}
} //P.E.
// MARK: Colors
/// A UIColor value that determines the text color of the title label when in the normal state
@IBInspectable open var titleColor:String? {
didSet {
self.updateTitleColor();
}
}
/// A UIColor value that determines the text color of the title label when editing
@IBInspectable open var titleColorSelected:String? {
didSet {
self.updateTitleColor();
}
}
/// A UIColor value that determines the color of the bottom line when in the normal state
@IBInspectable open var lineColor:String? {
didSet {
self.updateLineView();
}
}
/// A UIColor value that determines the color of the line in a selected state
@IBInspectable open var lineColorSelected:String? {
didSet {
self.updateLineView();
}
} //P.E.
/// A UIColor value that determines the color used for the title label and the line when the error message is not `nil`
@IBInspectable open var errorColor:String? {
didSet {
self.updateColors();
}
} //P.E.
// MARK: Title Case
/// Flag for upper case formatting
@IBInspectable open var uppercaseTitle:Bool = false {
didSet {
self.updateControl();
}
}
// MARK: Line height
/// A CGFloat value that determines the height for the bottom line when the control is in the normal state
@IBInspectable open var lineHeight:CGFloat = 0.5 {
didSet {
self.updateLineView();
self.setNeedsDisplay();
}
} //P.E.
/// A CGFloat value that determines the height for the bottom line when the control is in a selected state
@IBInspectable open var lineHeightSelected:CGFloat = 1.0 {
didSet {
self.updateLineView();
self.setNeedsDisplay();
}
}
// MARK: View components
/// The internal `UIView` to display the line below the text input.
open var lineView:UIView!
/// The internal `UILabel` that displays the selected, deselected title or the error message based on the current state.
open var titleLabel:BaseUILabel!
// MARK: Properties
/**
Identifies whether the text object should hide the text being entered.
*/
override open var isSecureTextEntry:Bool {
set {
super.isSecureTextEntry = newValue;
self.fixCaretPosition();
}
get {
return super.isSecureTextEntry;
}
}
/// A String value for the error message to display.
private var errorMessage:String? {
didSet {
self.updateControl(true);
}
}
/// The backing property for the highlighted property
fileprivate var _highlighted = false;
/// A Boolean value that determines whether the receiver is highlighted. When changing this value, highlighting will be done with animation
override open var isHighlighted:Bool {
get {
return _highlighted
}
set {
_highlighted = newValue;
self.updateTitleColor();
self.updateLineView();
}
}
/// A Boolean value that determines whether the textfield is being edited or is selected.
open var editingOrSelected:Bool {
get {
return super.isEditing || self.isSelected;
}
}
/// A Boolean value that determines whether the receiver has an error message.
open var hasErrorMessage:Bool {
get {
return self.errorMessage != nil && self.errorMessage != "";
}
} //P.E.
fileprivate var _renderingInInterfaceBuilder:Bool = false
/// The text content of the textfield
override open var text:String? {
didSet {
self.updateControl(false);
}
}
/**
The String to display when the input field is empty.
The placeholder can also appear in the title label when both `title` `selectedTitle` and are `nil`.
*/
override open var placeholder:String? {
didSet {
self.setNeedsDisplay();
self.updateTitleLabel();
}
}
// Determines whether the field is selected. When selected, the title floats above the textbox.
open override var isSelected:Bool {
didSet {
self.updateControl(true);
}
}
override open var fontName: String {
didSet {
self.titleLabel.fontName = self.fontName;
}
} // P.E.
// MARK: - Initializers
/**
Initializes the control
- parameter frame the frame of the control
*/
override public init(frame: CGRect) {
super.init(frame: frame)
self.setupFloatingLabel();
}
/**
Intialzies the control by deserializing it
- parameter coder the object to deserialize the control from
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
self.setupFloatingLabel();
}
// MARK: - Overridden Methods
/// Overridden property to get text changes.
///
/// - Parameter textField: UITextField
open override func textFieldDidEndEditing(_ textField: UITextField) {
super.textFieldDidEndEditing(textField);
self.errorMessage = (self.isValid == false) ? self.validityMsg:nil;
} //F.E.
// MARK: - Methods
fileprivate final func setupFloatingLabel() {
self.borderStyle = .none;
self.createTitleLabel();
self.createLineView();
self.updateColors();
self.addEditingChangedObserver();
}
fileprivate func addEditingChangedObserver() {
self.addTarget(self, action: #selector(editingChanged), for: .editingChanged)
}
/**
Invoked when the editing state of the textfield changes. Override to respond to this change.
*/
open func editingChanged() {
self.updateControl(true);
self.updateTitleLabel(true);
}
/**
The formatter to use before displaying content in the title label. This can be the `title`, `selectedTitle` or the `errorMessage`.
The default implementation converts the text to uppercase.
*/
private func titleFormatter(_ txt:String) -> String {
let rtnTxt:String = SyncedText.text(forKey: txt);
return (self.uppercaseTitle == true) ? rtnTxt.uppercased():rtnTxt;
} //F.E.
// MARK: create components
private func createTitleLabel() {
let titleLabel = BaseUILabel()
titleLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight]
titleLabel.fontName = self.fontName;
titleLabel.alpha = 0.0
self.addSubview(titleLabel)
self.titleLabel = titleLabel
}
private func createLineView() {
if self.lineView == nil {
let lineView = UIView()
lineView.isUserInteractionEnabled = false;
self.lineView = lineView
self.configureDefaultLineHeight()
}
lineView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
self.addSubview(lineView)
}
private func configureDefaultLineHeight() {
let onePixel:CGFloat = 1.0 / UIScreen.main.scale
self.lineHeight = 2.0 * onePixel
self.lineHeightSelected = 2.0 * self.lineHeight
}
// MARK: Responder handling
/**
Attempt the control to become the first responder
- returns: True when successfull becoming the first responder
*/
@discardableResult
override open func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
self.updateControl(true)
return result
}
/**
Attempt the control to resign being the first responder
- returns: True when successfull resigning being the first responder
*/
@discardableResult
override open func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
self.updateControl(true)
return result
}
// MARK: - View updates
private func updateControl(_ animated:Bool = false) {
self.updateColors()
self.updateLineView()
self.updateTitleLabel(animated)
}
private func updateLineView() {
if let lineView = self.lineView {
lineView.frame = self.lineViewRectForBounds(self.bounds, editing: self.editingOrSelected)
}
self.updateLineColor()
}
// MARK: - Color updates
/// Update the colors for the control. Override to customize colors.
open func updateColors() {
self.updateLineColor()
self.updateTitleColor()
self.updateTextColor()
}
private func updateLineColor() {
if self.hasErrorMessage {
self.lineView.backgroundColor = UIColor.color(forKey: self.errorColor) ?? UIColor.red;
} else {
self.lineView.backgroundColor = UIColor.color(forKey: (self.editingOrSelected && self.lineColorSelected != nil) ? (self.lineColorSelected) : self.lineColor);
}
}
private func updateTitleColor() {
if self.hasErrorMessage {
self.titleLabel.textColor = UIColor.color(forKey: self.errorColor) ?? UIColor.red;
} else {
if ((self.editingOrSelected || self.isHighlighted) && self.titleColorSelected != nil) {
self.titleLabel.textColor = UIColor.color(forKey: self.titleColorSelected);
} else {
self.titleLabel.textColor = UIColor.color(forKey: self.titleColor);
}
}
}
private func updateTextColor() {
if self.hasErrorMessage {
super.textColor = UIColor.color(forKey: self.errorColor);
} else {
super.textColor = UIColor.color(forKey: self.fontColorStyle);
}
}
// MARK: - Title handling
private func updateTitleLabel(_ animated:Bool = false) {
var titleText:String? = nil
if self.hasErrorMessage {
titleText = self.titleFormatter(self.validityMsg!)
} else {
if self.editingOrSelected {
titleText = self.selectedTitleOrTitlePlaceholder()
if titleText == nil {
titleText = self.titleOrPlaceholder()
}
} else {
titleText = self.titleOrPlaceholder()
}
}
self.titleLabel.text = titleText
self.updateTitleVisibility(animated)
}
private var _titleVisible = false
/*
* Set this value to make the title visible
*/
open func setTitleVisible(_ titleVisible:Bool, animated:Bool = false, animationCompletion: ((_ completed: Bool) -> Void)? = nil) {
if(_titleVisible == titleVisible) {
return
}
_titleVisible = titleVisible
self.updateTitleColor()
self.updateTitleVisibility(animated, completion: animationCompletion)
}
/**
Returns whether the title is being displayed on the control.
- returns: True if the title is displayed on the control, false otherwise.
*/
open func isTitleVisible() -> Bool {
return self.hasText || self.hasErrorMessage || _titleVisible
}
fileprivate func updateTitleVisibility(_ animated:Bool = false, completion: ((_ completed: Bool) -> Void)? = nil) {
let alpha:CGFloat = self.isTitleVisible() ? 1.0 : 0.0
let frame:CGRect = self.titleLabelRectForBounds(self.bounds, editing: self.isTitleVisible())
let updateBlock = { () -> Void in
self.titleLabel.alpha = alpha
self.titleLabel.frame = frame
}
if animated {
let animationOptions:UIViewAnimationOptions = .curveEaseOut;
let duration = self.isTitleVisible() ? titleFadeInDuration : titleFadeOutDuration
UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: { () -> Void in
updateBlock()
}, completion: completion)
} else {
updateBlock()
completion?(true)
}
}
// MARK: - UITextField text/placeholder positioning overrides
/**
Calculate the rectangle for the textfield when it is not being edited
- parameter bounds: The current bounds of the field
- returns: The rectangle that the textfield should render in
*/
override open func textRect(forBounds bounds: CGRect) -> CGRect {
_ = super.textRect(forBounds: bounds);
let titleHeight = self.titleHeight()
let lineHeight = self.lineHeightSelected
let rect = CGRect(x: 0, y: titleHeight, width: bounds.size.width, height: bounds.size.height - titleHeight - lineHeight)
return rect
}
/**
Calculate the rectangle for the textfield when it is being edited
- parameter bounds: The current bounds of the field
- returns: The rectangle that the textfield should render in
*/
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
let titleHeight = self.titleHeight()
let lineHeight = self.lineHeightSelected
let rect = CGRect(x: 0, y: titleHeight, width: bounds.size.width, height: bounds.size.height - titleHeight - lineHeight)
return rect
}
/**
Calculate the rectangle for the placeholder
- parameter bounds: The current bounds of the placeholder
- returns: The rectangle that the placeholder should render in
*/
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
let titleHeight = self.titleHeight()
let lineHeight = self.lineHeightSelected
let rect = CGRect(x: 0, y: titleHeight, width: bounds.size.width, height: bounds.size.height - titleHeight - lineHeight)
return rect
}
// MARK: - Positioning Overrides
/**
Calculate the bounds for the title label. Override to create a custom size title field.
- parameter bounds: The current bounds of the title
- parameter editing: True if the control is selected or highlighted
- returns: The rectangle that the title label should render in
*/
open func titleLabelRectForBounds(_ bounds:CGRect, editing:Bool) -> CGRect {
let titleHeight = self.titleHeight()
if editing {
return CGRect(x: 0, y: 0, width: bounds.size.width, height: titleHeight)
}
return CGRect(x: 0, y: titleHeight, width: bounds.size.width, height: titleHeight)
}
/**
Calculate the bounds for the bottom line of the control. Override to create a custom size bottom line in the textbox.
- parameter bounds: The current bounds of the line
- parameter editing: True if the control is selected or highlighted
- returns: The rectangle that the line bar should render in
*/
open func lineViewRectForBounds(_ bounds:CGRect, editing:Bool) -> CGRect {
let lineHeight:CGFloat = editing ? CGFloat(self.lineHeightSelected) : CGFloat(self.lineHeight)
return CGRect(x: 0, y: bounds.size.height - lineHeight, width: bounds.size.width, height: lineHeight);
}
/**
Calculate the height of the title label.
-returns: the calculated height of the title label. Override to size the title with a different height
*/
open func titleHeight() -> CGFloat {
if let titleLabel = self.titleLabel,
let font = titleLabel.font {
return font.lineHeight
}
return 15.0
}
/**
Calcualte the height of the textfield.
-returns: the calculated height of the textfield. Override to size the textfield with a different height
*/
open func textHeight() -> CGFloat {
return self.font!.lineHeight + 7.0
}
// MARK: - Layout
/// Invoked when the interface builder renders the control
override open func prepareForInterfaceBuilder() {
if #available(iOS 8.0, *) {
super.prepareForInterfaceBuilder()
}
self.borderStyle = .none
self.isSelected = true
_renderingInInterfaceBuilder = true
self.updateControl(false)
self.invalidateIntrinsicContentSize()
}
/// Invoked by layoutIfNeeded automatically
override open func layoutSubviews() {
super.layoutSubviews()
self.titleLabel.frame = self.titleLabelRectForBounds(self.bounds, editing: self.isTitleVisible() || _renderingInInterfaceBuilder)
self.lineView.frame = self.lineViewRectForBounds(self.bounds, editing: self.editingOrSelected || _renderingInInterfaceBuilder)
}
/**
Calculate the content size for auto layout
- returns: the content size to be used for auto layout
*/
override open var intrinsicContentSize : CGSize {
return CGSize(width: self.bounds.size.width, height: self.titleHeight() + self.textHeight())
}
// MARK: - Helpers
fileprivate func titleOrPlaceholder() -> String? {
if let title = self.title ?? self.placeholder {
return self.titleFormatter(title)
}
return nil
}
fileprivate func selectedTitleOrTitlePlaceholder() -> String? {
if let title = self.titleSelected ?? self.title ?? self.placeholder {
return self.titleFormatter(title)
}
return nil
}
} //CLS END
| gpl-3.0 | 09dfdee3420259f0e8e3b2b4f29fd960 | 32.27768 | 169 | 0.61896 | 5.081857 | false | false | false | false |
gaurav1981/eidolon | KioskTests/Models/BidderPositionTests.swift | 7 | 842 | import Quick
import Nimble
@testable
import Kiosk
class BidderPositionTests: QuickSpec {
override func spec() {
it("converts from JSON") {
let id = "saf32sadasd"
let maxBidAmountCents = 123123123
let bidID = "saf32sadasd"
let bidAmount = 100000
let bidData:[String: AnyObject] = ["id": bidID, "amount_cents" : bidAmount ]
let data:[String: AnyObject] = ["id":id , "max_bid_amount_cents" : maxBidAmountCents, "highest_bid":bidData]
let position = BidderPosition.fromJSON(data) as! BidderPosition
expect(position.id) == id
expect(position.maxBidAmountCents) == maxBidAmountCents
expect(position.highestBid!.id) == bidID
expect(position.highestBid!.amountCents) == bidAmount
}
}
}
| mit | ca846d7dc50d4db113c82fca25e279bd | 29.071429 | 121 | 0.610451 | 4.385417 | false | true | false | false |
DanielOrmeno/PeriodicLocation | src/ios/DataManager.swift | 1 | 11353 | /*******************************************************************************************************************
| File: DataManager.swift
| Proyect: swiftLocations cordova plugin
|
| Description: - DataManager class. Manages the location records in memory through the NSUserDefaults. It handles
| the location updates received by the LocationManager and stores them in memory based on a set of rules.
|
| Only 32 records are stored in memory at all times (4 records per hour for 8 hours). Location records are based
| on the LocationData class, see plugin ios project setup instructions for more information.
*******************************************************************************************************************/
import CoreData
import UIKit
import CoreLocation
class DataManager {
// ===================================== INSTANCE VARIABLES / PROPERTIES =============================//
//- MaxNumber of records allowed
var MaxNoOfRecords:Int = 10
//- Date Format
let DATEFORMAT = "dd-MM-yyyy, HH:mm:ss"
//- Class keys
let LocationRecords_Key = "LOCATION_RECORDS"
let LocationData_Key = "LOCATION_DATA"
//- Array of LocationData encoded objects
var locationRecords : NSArray?
//- User Defaults
let UserDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
// ===================================== CLASS CONSTRUCTORS =========================================//
init () {}
// ===================================== Accessors & Mutators =================================================//
func setNumberOfRecords(numberOfRecords: Int){self.MaxNoOfRecords = numberOfRecords}
func getNumberOfRecords() -> Int {return self.MaxNoOfRecords}
// ===================================== CLASS METHODS ===================================================//
/********************************************************************************************************************
METHOD NAME: savelocationRecords
INPUT PARAMETERS: array of LocationData Objects
RETURNS: None
OBSERVATIONS: Saves an array of LocationData as a NSArray of NSData objects in the NSUserDefaults by deleting old
instance and saving array from argument.
********************************************************************************************************************/
func saveLocationRecords (records: [LocationData]) {
//- Create NSArray of NSData
var NSDataArray: [NSData] = []
//- Populate NSDataArray
for eachRecord in records {
//- Convert LocationData to NSData
let Data = NSKeyedArchiver.archivedDataWithRootObject(eachRecord)
NSDataArray.append(Data)
}
//- NSArray to comply with NSUserDefaults
self.locationRecords = NSArray(array: NSDataArray)
//- Update old array from UserDefaults
self.UserDefaults.removeObjectForKey(LocationRecords_Key)
self.UserDefaults.setObject(self.locationRecords, forKey: LocationRecords_Key)
self.UserDefaults.synchronize()
}
/********************************************************************************************************************
METHOD NAME: getUpdatedRecords
INPUT PARAMETERS: NONE
RETURNS: Array of LOcationData records
OBSERVATIONS: Gets NSArray of NSData objects from NSUserDefaults and returns them as an array of LocationData objects
********************************************************************************************************************/
func getUpdatedRecords () -> [LocationData]? {
// - Fetch all Records in memoryif
if let RECORDS: [NSData] = self.UserDefaults.arrayForKey(LocationRecords_Key) as? [NSData] {
//- Empty array of LocationData objects
var locationRecords = [LocationData]()
for eachRecord in RECORDS {
//- Convert from NSData back to LocationData object
let newRecord = NSKeyedUnarchiver.unarchiveObjectWithData(eachRecord) as! LocationData
//- Append Record
locationRecords.append(newRecord)
}
//- Sort Location Records
locationRecords.sortInPlace({ $0.timestamp.compare($1.timestamp) == NSComparisonResult.OrderedAscending})
//- Return records if any, if not return nil
return locationRecords
} else {
return nil
}
}
/********************************************************************************************************************
METHOD NAME: deleteOldestLocationRecord
INPUT PARAMETERS: None
RETURNS: None
OBSERVATIONS: Gets [LocationData] from NSUserDefaults through the getUpdatedRecords method, deletes oldest record and
saves array to memory through the savelocationRecords method
********************************************************************************************************************/
func deleteOldestLocationRecord() {
//- Fetch records from memory and store on mutable array
var sortedRecords = [LocationData]()
if let fetchedRecords = self.getUpdatedRecords() {
//- Array needs to be mutable
sortedRecords = fetchedRecords
//- Delete Oldest Record
sortedRecords.removeAtIndex(0)
self.saveLocationRecords(sortedRecords)
}
}
/********************************************************************************************************************
METHOD NAME: getLastRecord
INPUT PARAMETERS: None
RETURNS: LocationData object
OBSERVATIONS: Gets [LocationData] from NSUserDefaults through the getUpdatedRecords method, and returns the newest
record if any
********************************************************************************************************************/
func getLastRecord() -> LocationData? {
//- Fetch records from memory and return newest
if let fetchedRecords = self.getUpdatedRecords() {
let newestRecord = fetchedRecords.last
return newestRecord
} else {
return nil
}
}
/********************************************************************************************************************
METHOD NAME: addNewLocationRecord
INPUT PARAMETERS: CLLocation Object
RETURNS: None
OBSERVATIONS: Converts CLLocation object to LocationData object, adds new record to [LocationData] from the
getUpdatedRecords method and saves modified array to memory.
********************************************************************************************************************/
func addNewLocationRecord (newRecord: CLLocation) {
//- Get CLLocation properties
let lat:NSNumber = newRecord.coordinate.latitude
let lon: NSNumber = newRecord.coordinate.longitude
let time: NSDate = newRecord.timestamp
let newLocationDataRecord = LocationData()
newLocationDataRecord.latitude = lat
newLocationDataRecord.longitude = lon
newLocationDataRecord.timestamp = time
//- Fetch records from memory and store on mutable array
var sortedRecords = [LocationData]()
if let fetchedRecords = self.getUpdatedRecords() {
for records in fetchedRecords {
sortedRecords.append(records)
}
}
//- Append new record
sortedRecords.append(newLocationDataRecord)
//- Sort Records
sortedRecords.sortInPlace({ $0.timestamp.compare($1.timestamp) == NSComparisonResult.OrderedAscending })
//- Save new record
self.saveLocationRecords(sortedRecords)
}
/********************************************************************************************************************
METHOD NAME: updateLocationRecords
INPUT PARAMETERS: CLLocation Object
RETURNS: None
OBSERVATIONS: Manages number of records when new record is received, only 32 location records are store in memory
(4 updates per hour, for 8 hours)
********************************************************************************************************************/
func updateLocationRecords (newLocation: CLLocation) {
var numberOfRecords: Int?
//- Perform initial fetch Request
if let fetchResults = getUpdatedRecords() {
switch fetchResults.count {
case 0...(self.MaxNoOfRecords-1):
//- Adds new location record if less than 32 records exist
addNewLocationRecord(newLocation)
case self.MaxNoOfRecords...99:
//- If six or more records exist, reduce the number of records until size of five has been reached
repeat {
deleteOldestLocationRecord()
//- new fetch for updated count result
numberOfRecords = getUpdatedRecords()?.count
} while (numberOfRecords>self.MaxNoOfRecords-1)
//- Adds last knwon location to record
addNewLocationRecord(newLocation)
default:
print("Error")
}
} else { //- NO RECORDS EXIST - CONDITIONAL UNWRAPING
print("No records exist in memory, adding new record")
addNewLocationRecord(newLocation)
}
//- FOR TESTING -----------
print(":::::: updated records ::::::")
if let fetchResults = getUpdatedRecords() {
for each in fetchResults {
print(self.fixDateFormat(each.timestamp))
}
}
print("-----------")
//- FOR TESTING above -----
}
/********************************************************************************************************************
METHOD NAME: fixDateFormat
INPUT PARAMETERS: NSDate object
RETURNS: NSstring
OBSERVATIONS: Fixes date format for debuggin and parsing, adds timezone and returns as NSString
********************************************************************************************************************/
func fixDateFormat(date: NSDate) -> NSString {
let dateFormatter = NSDateFormatter()
//- Format parameters
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
//- Force date format to garantee consistency throught devices
dateFormatter.dateFormat = DATEFORMAT
dateFormatter.timeZone = NSTimeZone()
return dateFormatter.stringFromDate(date)
}
}
| mit | f40ae66b40cf88bcae3d2c387466fe75 | 41.520599 | 121 | 0.491324 | 6.635301 | false | false | false | false |
mownier/photostream | Photostream/UI/Shared/ActivityTableCell/ActivityTableCommentCell.swift | 1 | 4102 | //
// ActivityTableCommentCell.swift
// Photostream
//
// Created by Mounir Ybanez on 26/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
protocol ActivityTableCommentCellDelegate: class {
func didTapPhoto(cell: UITableViewCell)
func didTapAvatar(cell: UITableViewCell)
}
@objc protocol ActivityTableCommentCellAction: class {
func didTapPhoto()
func didTapAvatar()
}
class ActivityTableCommentCell: UITableViewCell, ActivityTableCommentCellAction {
weak var delegate: ActivityTableCommentCellDelegate?
var avatarImageView: UIImageView!
var photoImageView: UIImageView!
var contentLabel: UILabel!
convenience init() {
self.init(style: .default, reuseIdentifier: ActivityTableCommentCell.reuseId)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
initSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSetup()
}
func initSetup() {
avatarImageView = UIImageView()
avatarImageView.contentMode = .scaleAspectFill
avatarImageView.backgroundColor = UIColor.lightGray
avatarImageView.cornerRadius = avatarDimension / 2
photoImageView = UIImageView()
photoImageView.contentMode = .scaleAspectFill
photoImageView.backgroundColor = UIColor.lightGray
photoImageView.clipsToBounds = true
contentLabel = UILabel()
contentLabel.numberOfLines = 0
contentLabel.font = UIFont.systemFont(ofSize: 12)
var tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapPhoto))
tap.numberOfTapsRequired = 1
photoImageView.isUserInteractionEnabled = true
photoImageView.addGestureRecognizer(tap)
tap = UITapGestureRecognizer(target: self, action: #selector(self.didTapAvatar))
tap.numberOfTapsRequired = 1
avatarImageView.isUserInteractionEnabled = true
avatarImageView.addGestureRecognizer(tap)
addSubview(avatarImageView)
addSubview(photoImageView)
addSubview(contentLabel)
}
override func layoutSubviews() {
var rect = CGRect.zero
rect.origin.x = spacing
rect.origin.y = (frame.height - avatarDimension) / 2
rect.size.width = avatarDimension
rect.size.height = avatarDimension
avatarImageView.frame = rect
rect.origin.x = frame.width - photoDimension - spacing
rect.origin.y = (frame.height - photoDimension) / 2
rect.size.width = photoDimension
rect.size.height = photoDimension
photoImageView.frame = rect
rect.origin.x = avatarImageView.frame.maxX
rect.origin.x += spacing
rect.size.width = frame.width - rect.origin.x
rect.size.width -= photoImageView.frame.width
rect.size.width -= (spacing * 2)
rect.size.height = contentLabel.sizeThatFits(rect.size).height
rect.origin.y = (frame.height - rect.size.height) / 2
contentLabel.frame = rect
}
func didTapPhoto() {
delegate?.didTapPhoto(cell: self)
}
func didTapAvatar() {
delegate?.didTapAvatar(cell: self)
}
}
extension ActivityTableCommentCell {
var spacing: CGFloat {
return 4
}
var avatarDimension: CGFloat {
return 32
}
var photoDimension: CGFloat {
return 40
}
}
extension ActivityTableCommentCell {
static var reuseId: String {
return "ActivityTableCommentCell"
}
}
extension ActivityTableCommentCell {
class func dequeue(from view: UITableView) -> ActivityTableCommentCell? {
return view.dequeueReusableCell(withIdentifier: self.reuseId) as? ActivityTableCommentCell
}
class func register(in view: UITableView) {
view.register(self, forCellReuseIdentifier: self.reuseId)
}
}
| mit | 99afee35416be5efccaf78481051879b | 28.292857 | 98 | 0.663741 | 5.113466 | false | false | false | false |
siemensikkema/Fairness | Fairness/CostTextFieldController.swift | 1 | 1192 | import UIKit
class CostTextFieldController: NSObject {
@IBOutlet weak var costTextField: UITextField!
var costDidChangeCallbackOrNil: ((Double) -> ())?
private let notificationCenter: FairnessNotificationCenter
override convenience init() {
self.init(notificationCenter: NotificationCenter())
}
init(notificationCenter: FairnessNotificationCenter) {
self.notificationCenter = notificationCenter
super.init()
notificationCenter.observeTransactionDidStart {
self.costTextField.userInteractionEnabled = true
self.costTextField.becomeFirstResponder()
}
notificationCenter.observeTransactionDidEnd {
self.costTextField.userInteractionEnabled = false
self.costTextField.resignFirstResponder()
self.costTextField.text = ""
}
}
@IBAction func costDidChange() {
// untested
let balanceFormatter = BalanceFormatter.sharedInstance
balanceFormatter.numberFromString(costTextField.text)
let cost = balanceFormatter.numberFromString(costTextField.text)?.doubleValue
costDidChangeCallbackOrNil?(cost ?? 0)
}
} | mit | 14bfee756564f1a7c2c8584146383aea | 33.085714 | 85 | 0.701342 | 5.96 | false | false | false | false |
HarwordLiu/Ing. | Ing/Ing/Protocol/CloudKitProtocols.swift | 1 | 2228 | //
// CloudKitProtocols.swift
// Ing
//
// Created by 刘浩 on 2017/9/7.
// Copyright © 2017年 刘浩. All rights reserved.
//
import Foundation
import CloudKit
import CoreData
@objc protocol CloudKitRecordIDObject {
var recordID: NSData? { get set }
}
extension CloudKitRecordIDObject {
func cloudKitRecordID() -> CKRecordID? {
guard let recordID = recordID else {
return nil
}
return NSKeyedUnarchiver.unarchiveObject(with: recordID as Data) as? CKRecordID
}
}
@objc protocol CloudKitManagedObject: CloudKitRecordIDObject {
var lastUpdate: Date? { get set }
var recordName: String? { get set }
var recordType: String { get }
func managedObjectToRecord(_ record: CKRecord?) -> CKRecord
func updateWithRecord(_ record: CKRecord)
}
extension CloudKitManagedObject {
func cloudKitRecord(_ record: CKRecord?, parentRecordZoneID: CKRecordZoneID?) -> CKRecord {
if let record = record {
return record
}
var recordZoneID: CKRecordZoneID
if parentRecordZoneID != .none {
recordZoneID = parentRecordZoneID!
}
else {
guard let cloudKitZone = CloudKitZone(recordType: recordType) else {
fatalError("Attempted to create a CKRecord with an unknown zone")
}
recordZoneID = cloudKitZone.recordZoneID()
}
let uuid = UUID()
let recordName = recordType + "." + uuid.uuidString
let recordID = CKRecordID(recordName: recordName, zoneID: recordZoneID)
return CKRecord(recordType: recordType, recordID: recordID)
}
func addDeletedCloudKitObject() {
if let managedObject = self as? NSManagedObject,
let managedObjectContext = managedObject.managedObjectContext,
let recordID = recordID,
let deletedCloudKitObject = NSEntityDescription.insertNewObject(forEntityName: "DeletedCloudKitObject", into: managedObjectContext) as? DeletedCloudKitObject {
deletedCloudKitObject.recordID = recordID
deletedCloudKitObject.recordType = recordType
}
}
}
| mit | 27555ba9e3cd023eb5beca179ac80042 | 29.791667 | 171 | 0.644565 | 5.278571 | false | false | false | false |
LittleRockInGitHub/LLRegex | Tests/LLRegexTests/NamedCaptureGroupsTests.swift | 1 | 7487 | //
// NamedCaptureGroupsTests.swift
// LLRegex
//
// Created by Rock Yang on 2017/6/21.
// Copyright © 2017年 Rock Young. All rights reserved.
//
import XCTest
@testable import LLRegex
class NamedCaptureGroupsTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExtraction() {
XCTAssertEqual(extractNamedCaptureGroups(in: "\\d", expectedGroupsCount: 0)!, [:])
XCTAssertEqual(extractNamedCaptureGroups(in: "()", expectedGroupsCount: 1)!, [:])
XCTAssertEqual(extractNamedCaptureGroups(in: "(?<name>abc)", expectedGroupsCount: 1)!, ["name": 1])
XCTAssertEqual(extractNamedCaptureGroups(in: "(?<name>abc)-(?<number1>\\d+)", expectedGroupsCount: 2)!, ["name": 1, "number1": 2])
XCTAssertEqual(extractNamedCaptureGroups(in: "(\\d)(?<name>abc)-(?<number1>\\d+)", expectedGroupsCount: 3)!, ["name": 2, "number1": 3])
XCTAssertEqual(extractNamedCaptureGroups(in: "(\\d(?<name>abc)-(?<number1>\\d+))", expectedGroupsCount: 3)!, ["name": 2, "number1": 3])
XCTAssertEqual(extractNamedCaptureGroups(in: "(\\d(?<name>abc((?<number1>\\d+)1)))", expectedGroupsCount: 4)!, ["name": 2, "number1": 4])
XCTAssertEqual(extractNamedCaptureGroups(in: "(?:\\d)", expectedGroupsCount: 0)!, [:])
XCTAssertEqual(extractNamedCaptureGroups(in: "(?<!>)", expectedGroupsCount: 0)!, [:])
XCTAssertEqual(extractNamedCaptureGroups(in: "(?<=)", expectedGroupsCount: 0)!, [:])
XCTAssertEqual(extractNamedCaptureGroups(in: "(?!)", expectedGroupsCount: 0)!, [:])
XCTAssertEqual(extractNamedCaptureGroups(in: "(?=)", expectedGroupsCount: 0)!, [:])
XCTAssertEqual(extractNamedCaptureGroups(in: "(?#)", expectedGroupsCount: 0)!, [:])
XCTAssertEqual(extractNamedCaptureGroups(in: "(?>)", expectedGroupsCount: 0)!, [:])
XCTAssertEqual(extractNamedCaptureGroups(in: "\\(\\)", expectedGroupsCount: 0)!, [:])
XCTAssertEqual(extractNamedCaptureGroups(in: "\\\\()", expectedGroupsCount: 1)!, [:])
XCTAssertEqual(extractNamedCaptureGroups(in: "\\(?<name>\\)", expectedGroupsCount: 0)!, [:])
XCTAssertEqual(extractNamedCaptureGroups(in: "\\\\(?<name>)", expectedGroupsCount: 1)!, ["name": 1])
}
func testNamdCaptureGroupsTypes() {
guard #available(iOS 9, *) else { return }
XCTAssertEqual(Regex("\\d", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0)
XCTAssertEqual(Regex("()", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0)
XCTAssertEqual(Regex("(?<name>abc)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 1)
XCTAssertEqual(Regex("(?<name>abc)-(?<number1>\\d+)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2)
XCTAssertEqual(Regex("(\\d)(?<name>abc)-(?<number1>\\d+)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2)
XCTAssertEqual(Regex("(\\d(?<name>abc)-(?<number1>\\d+))", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2)
XCTAssertEqual(Regex("(\\d(?<name>abc((?<number1>\\d+)1)))", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2)
XCTAssertEqual(Regex("(\\d(?<name>abc((?<number1>\\d+)1)))", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2)
XCTAssertEqual(Regex("(\\d(?<name>abc((?<number1>\\d+)1)))", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2)
XCTAssertEqual(Regex("(\\d(?<name>abc((?<number1>\\d+)1)))", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2)
XCTAssertEqual(Regex("(\\d(?<name>abc((?<number1>\\d+)1)))", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 2)
XCTAssertEqual(Regex("(?:\\d)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0)
XCTAssertEqual(Regex("(?<!>)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0)
XCTAssertEqual(Regex("(?<=)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0)
XCTAssertEqual(Regex("(?!)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0)
XCTAssertEqual(Regex("(?=)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0)
XCTAssertEqual(Regex("(?#)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0)
XCTAssertEqual(Regex("(?>)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0)
XCTAssertEqual(Regex("\\(\\)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0)
XCTAssertEqual(Regex("\\\\()", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0)
XCTAssertEqual(Regex("\\(?<name>\\)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 0)
XCTAssertEqual(Regex("\\\\(?<name>)", options: [.namedCaptureGroups]).namedCaptureGroupsInfo!.count, 1)
}
func testNamdCaptureGroups() {
guard #available(iOS 9, *) else { return }
let s = "123 normal NAMED (Nested) atomic non-capture 456"
let regex = Regex("(?#comment)(?<!a)(?<=123) (?i)(NORMAL) (?<name>named) (\\((?<nested>nested)\\)) (?>atomic) (?:non-capture) (?=456)(?!a)", options: [.namedCaptureGroups])
XCTAssertEqual(regex.namedCaptureGroupsInfo!, ["name": 2, "nested": 4])
let match = regex.matches(in: s).first!
XCTAssertEqual(match.groups["name"]!.matched, "NAMED")
XCTAssertEqual(match.groups["nested"]!.matched, "Nested")
XCTAssertNil(match.groups[""])
}
func testReplacement() {
guard #available(iOS 9, *) else { return }
let date = "1978-12-24"
let named = Regex("((?<year>\\d+)-(?<month>\\d+)-(?<day>\\d+))", options: .namedCaptureGroups)
let nonNamed = Regex("((?<year>\\d+)-(?<month>\\d+)-(?<day>\\d+))")
let namedMatch = named.matches(in: date).first!
let nonNamedMatch = nonNamed.matches(in: date).first!
XCTAssertEqual(namedMatch.replacement(withTemplate: "$2$3$4"), "19781224")
XCTAssertEqual(namedMatch.replacement(withTemplate: "${year}${month}${day}"), "19781224")
XCTAssertEqual(namedMatch.replacement(withTemplate: "\\${year}${month}\\\\${day}"), "${year}12\\24")
XCTAssertEqual(namedMatch.replacement(withTemplate: "$9${unknown}!"), "!")
XCTAssertEqual(nonNamedMatch.replacement(withTemplate: "$2$3$4"), "19781224")
XCTAssertEqual(nonNamedMatch.replacement(withTemplate: "${year}${month}${day}"), "${year}${month}${day}")
XCTAssertEqual(nonNamedMatch.replacement(withTemplate: "$9${unknown}!"), "${unknown}!")
}
func testComment() {
guard #available(iOS 9, *) else { return }
let s = "1234567890"
let regex = Regex("(\\d{1,2})(?<suffix>\\d)(?x) # (\\d+)", options: .namedCaptureGroups)
XCTAssertNil(regex.namedCaptureGroupsInfo)
XCTAssertEqual(regex.matches(in: s).first!.replacement(withTemplate: "$1${suffix}"), "12")
}
}
| mit | d0e0f48910d63373a3d12742eb1638ac | 56.129771 | 180 | 0.628942 | 4.293746 | false | true | false | false |
benlangmuir/swift | test/IDE/complete_with_closure_param.swift | 13 | 1857 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=COMPLETE | %FileCheck %s
typealias FunctionTypealias = (Int, Int) -> Bool
typealias OptionalFunctionTypealias = ((Int, Int) -> Bool)?
struct FooStruct {
func instanceMethod1(_ callback: (Int, Int) -> Void) {}
func instanceMethod2(_ callback: ((Int, Int) -> Void)?) {}
func instanceMethod3(_ callback: ((Int, Int) -> Void)??) {}
func instanceMethod4(_ callback: ((Int, Int) -> Void)!) {}
func instanceMethod5(_ callback: FunctionTypealias) {}
func instanceMethod6(_ callback: FunctionTypealias?) {}
func instanceMethod7(_ callback: OptionalFunctionTypealias) {}
}
FooStruct().#^COMPLETE^#
// CHECK: Begin completions, 8 items
// CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod1({#(callback): (Int, Int) -> Void##(Int, Int) -> Void#})[#Void#]; name=instanceMethod1(:){{$}}
// CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod2({#(callback): ((Int, Int) -> Void)?##(Int, Int) -> Void#})[#Void#]{{; name=.+$}}
// CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod3({#(callback): ((Int, Int) -> Void)??##(Int, Int) -> Void#})[#Void#]{{; name=.+$}}
// CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod4({#(callback): ((Int, Int) -> Void)!##(Int, Int) -> Void#})[#Void#]{{; name=.+$}}
// CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod5({#(callback): (Int, Int) -> Bool##(Int, Int) -> Bool#})[#Void#]{{; name=.+$}}
// CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod6({#(callback): FunctionTypealias?##(Int, Int) -> Bool#})[#Void#]{{; name=.+$}}
// CHECK-DAG: Decl[InstanceMethod]/CurrNominal: instanceMethod7({#(callback): OptionalFunctionTypealias##(Int, Int) -> Bool#})[#Void#]{{; name=.+$}}
// CHECK-DAG: Keyword[self]/CurrNominal: self[#FooStruct#]; name=self
// CHECK: End completions
| apache-2.0 | 7df915cb485394953c27af8ce6f29ec0 | 67.777778 | 157 | 0.666128 | 4.0282 | false | false | false | false |
takeo-asai/math-puzzle | problems/49.swift | 1 | 4402 | struct Circle {
let n: Int
var values: [Bool]
init(_ v: [Bool]) {
self.values = v
self.n = values.count
}
func reverse(a: Int) -> Circle {
var next = self
//let m = self.n / 2
for i in 0 ..< 3 {
next[a+i] = !next[a+i]
}
return next
}
func reverses(a: [Int]) -> Circle {
var next = self
for x in a {
next = next.reverse(x)
}
return next
}
func isFinished() -> Bool {
if self.n <= 2 {
return false
}
var present = self.values[0]
for i in 1 ..< n {
let next = self.values[i]
if present == next {
return false
}
present = next
}
return true
}
subscript(i: Int) -> Bool {
get {
return self.values[i%n]
}
set(b) {
self.values[i%n] = b
}
}
}
extension Array {
// ExSwift
//
// Created by pNre on 03/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
// https://github.com/pNre/ExSwift/blob/master/ExSwift/Array.swift
// https://github.com/pNre/ExSwift/blob/master/LICENSE
/**
- parameter length: The length of each permutation
- returns: All permutations of a given length within an array
*/
func permutation (length: Int) -> [[Element]] {
if length < 0 || length > self.count {
return []
} else if length == 0 {
return [[]]
} else {
var permutations: [[Element]] = []
let combinations = combination(length)
for combination in combinations {
var endArray: [[Element]] = []
var mutableCombination = combination
permutations += self.permutationHelper(length, array: &mutableCombination, endArray: &endArray)
}
return permutations
}
}
private func permutationHelper(n: Int, inout array: [Element], inout endArray: [[Element]]) -> [[Element]] {
if n == 1 {
endArray += [array]
}
for var i = 0; i < n; i++ {
permutationHelper(n - 1, array: &array, endArray: &endArray)
let j = n % 2 == 0 ? i : 0
let temp: Element = array[j]
array[j] = array[n - 1]
array[n - 1] = temp
}
return endArray
}
func combination (length: Int) -> [[Element]] {
if length < 0 || length > self.count {
return []
}
var indexes: [Int] = (0..<length).reduce([]) {$0 + [$1]}
var combinations: [[Element]] = []
let offset = self.count - indexes.count
while true {
var combination: [Element] = []
for index in indexes {
combination.append(self[index])
}
combinations.append(combination)
var i = indexes.count - 1
while i >= 0 && indexes[i] == i + offset {
i--
}
if i < 0 {
break
}
i++
let start = indexes[i-1] + 1
for j in (i-1)..<indexes.count {
indexes[j] = start + j - i + 1
}
}
return combinations
}
/**
- parameter length: The length of each permutations
- returns: All of the permutations of this array of a given length, allowing repeats
*/
func repeatedPermutation(length: Int) -> [[Element]] {
if length < 1 {
return []
}
var indexes: [[Int]] = []
indexes.repeatedPermutationHelper([], length: length, arrayLength: self.count, indexes: &indexes)
return indexes.map({ $0.map({ i in self[i] }) })
}
private func repeatedPermutationHelper(seed: [Int], length: Int, arrayLength: Int, inout indexes: [[Int]]) {
if seed.count == length {
indexes.append(seed)
return
}
for i in (0..<arrayLength) {
var newSeed: [Int] = seed
newSeed.append(i)
self.repeatedPermutationHelper(newSeed, length: length, arrayLength: arrayLength, indexes: &indexes)
}
}
}
let n = 8
let idxes = Array(0 ..< 2*n)
let initial = Circle(Array(count: n, repeatedValue: true) + Array(count: n, repeatedValue: false))
loop: for i in 1 ..< 2*n {
for r in idxes.combination(i) {
let c = initial.reverses(r)
if c.isFinished() {
print(r)
print(i)
break loop
}
}
}
| mit | 17d3be89fc61438097fab79715f5fbe5 | 27.960526 | 112 | 0.514312 | 3.88526 | false | false | false | false |
josefdolezal/fit-cvut | BI-IOS/semester-project/What2Do/What2Do/NSDateExtension.swift | 1 | 943 | import Foundation
extension NSDate {
func timeComponent() -> NSDateComponents {
let calendar = NSCalendar.currentCalendar()
return calendar.components([.Hour, .Minute], fromDate: self)
}
func timeDelta(date: NSDate) -> (hours: Int, minutes: Int) {
let lowerTime = self.timeComponent()
let biggerTime = date.timeComponent()
// Easier difference
if lowerTime.minute > biggerTime.minute {
biggerTime.minute += 60
lowerTime.hour += 1
}
// Over midnight
if lowerTime.hour > biggerTime.hour {
biggerTime.hour += 24
}
return (biggerTime.hour - lowerTime.hour, biggerTime.minute - lowerTime.minute)
}
func timeDelta(date: NSDate, lessThan min: Int) -> Bool {
let time = self.timeDelta(date)
return (time.hours * 60 + time.minutes) < min
}
} | mit | 0b2479e51cc94a117ad8d7ccd52145d6 | 28.5 | 87 | 0.576882 | 4.533654 | false | false | false | false |
ZackKingS/Tasks | task/Classes/Others/Lib/TakePhoto/UICollectionView+Extension.swift | 3 | 730 | //
// UICollectionView+Extension.swift
// PhotoPicker
//
// Created by liangqi on 16/3/10.
// Copyright © 2016年 dailyios. All rights reserved.
//
import Foundation
import UIKit
extension UICollectionView {
func aapl_indexPathsForElementsInRect(rect: CGRect) -> [IndexPath]? {
let allLayoutAttributes = self.collectionViewLayout.layoutAttributesForElements(in: rect)
if allLayoutAttributes == nil || allLayoutAttributes!.count == 0 {
return nil
}
var indexPaths = [IndexPath]()
for layoutAttributes in allLayoutAttributes! {
let indexPath = layoutAttributes.indexPath
indexPaths.append(indexPath)
}
return indexPaths;
}
}
| apache-2.0 | 310eb916ed547c059fcb8979d07b6d1a | 28.08 | 97 | 0.668501 | 5.048611 | false | false | false | false |
fishcafe/SunnyHiddenBar | SunnyHiddenBar/Classes/UIViewController+SunnyHiddenBar.swift | 1 | 4326 | //
// UIViewController+SunnyHiddenBar.swift
// SunnyHiddenBar
//
// Created by amaker on 16/4/19.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
/** SunnyHiddenBar Extends UIViewController
*/
//定义关联的Key
let key = "keyScrollView"
let navBarBackgroundImageKey = "navBarBackgroundImage"
let isLeftAlphaKey = "isLeftAlpha"
let isRightAlphaKey = "isRightAlpha"
let isTitleAlphaKey = "isTitleAlpha"
var alpha:CGFloat = 0;
public extension UIViewController {
var keyScrollView:UIScrollView?{
set{
objc_setAssociatedObject(self, key, keyScrollView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get{
return objc_getAssociatedObject(self, key) as? UIScrollView
}
}
var navBarBackgroundImage:UIImage?{
set{
objc_setAssociatedObject(self, navBarBackgroundImageKey, navBarBackgroundImage, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get{
return objc_getAssociatedObject(self, navBarBackgroundImageKey) as? UIImage
}
}
var isLeftAlpha:Bool?{
set{
return objc_setAssociatedObject(self, isLeftAlphaKey, (isLeftAlpha), .OBJC_ASSOCIATION_ASSIGN)
}
get{
return objc_getAssociatedObject(self, isLeftAlphaKey) as? Bool
}
}
var isRightAlpha:Bool?{
set{
return objc_setAssociatedObject(self, isRightAlphaKey, (isRightAlpha), .OBJC_ASSOCIATION_ASSIGN)
}
get{
return objc_getAssociatedObject(self, isRightAlphaKey) as? Bool
}
}
var isTitleAlpha:Bool?{
set{
return objc_setAssociatedObject(self, isTitleAlphaKey, (isTitleAlpha), .OBJC_ASSOCIATION_ASSIGN)
}
get{
return objc_getAssociatedObject(self, isTitleAlphaKey) as? Bool
}
}
func scrollControlByOffsetY(offsetY:CGFloat){
if self.getScrollerView() != Optional.None{
let scrollerView = self.getScrollerView()
alpha = scrollerView.contentOffset.y/offsetY
}else {
return
}
alpha = (alpha <= 0) ? 0 : alpha
alpha = (alpha >= 1) ? 1 : alpha
//TODO: titleView alpha no fix
self.navigationItem.leftBarButtonItem?.customView?.alpha = (self.isLeftAlpha != nil) ? alpha : 1
self.navigationItem.titleView?.alpha = (self.isTitleAlpha != nil) ? alpha : 1
self.navigationItem.rightBarButtonItem?.customView?.alpha = (self.isRightAlpha != nil) ? alpha : 1
self.navigationController?.navigationBar.subviews.first?.alpha = alpha
}
func setInViewWillAppear() {
struct Static {
static var onceToken: dispatch_once_t = 0
}
dispatch_once(&Static.onceToken) {
self.navBarBackgroundImage = self.navigationController?.navigationBar.backgroundImageForBarMetrics(.Default)
}
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.subviews.first?.alpha = 0
if self.keyScrollView != nil {
self.getScrollerView().contentOffset = CGPointMake(0, self.keyScrollView!.contentOffset.y - 1)
self.getScrollerView().contentOffset = CGPointMake(0, self.keyScrollView!.contentOffset.y + 1)
}
}
func setInViewWillDisappear() {
self.navigationController?.navigationBar.subviews.first?.alpha = 1
self.navigationController?.navigationBar.setBackgroundImage(nil, forBarMetrics: .Default)
self.navigationController?.navigationBar.shadowImage = nil
}
func getScrollerView() -> UIScrollView{
if self.isKindOfClass(UITableViewController) || self.isKindOfClass(UICollectionViewController) {
return self.view as! UIScrollView
} else {
for myView in self.view.subviews {
if myView.isEqual(self.keyScrollView) && myView.isKindOfClass(UIScrollView) || myView.isEqual(self.keyScrollView) && view.isKindOfClass(UIScrollView){
return myView as! UIScrollView
}
}
}
return Optional.None!
}
}
| mit | deda142fb73e25ddc8b872e9cb866850 | 29.588652 | 166 | 0.632506 | 4.867946 | false | false | false | false |
phatblat/realm-cocoa | examples/ios/swift/Backlink/AppDelegate.swift | 2 | 2120 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm 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 UIKit
import RealmSwift
class Dog: Object {
@Persisted var name: String
@Persisted var age: Int
// Define "owners" as the inverse relationship to Person.dogs
@Persisted(originProperty: "dogs") var owners: LinkingObjects<Person>
}
class Person: Object {
@Persisted var name: String
@Persisted var dogs: List<Dog>
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UIViewController()
window?.makeKeyAndVisible()
_ = try! Realm.deleteFiles(for: Realm.Configuration.defaultConfiguration)
let realm = try! Realm()
try! realm.write {
realm.create(Person.self, value: ["John", [["Fido", 1]]])
realm.create(Person.self, value: ["Mary", [["Rex", 2]]])
}
// Log all dogs and their owners using the "owners" inverse relationship
let allDogs = realm.objects(Dog.self)
for dog in allDogs {
let ownerNames = Array(dog.owners.map(\.name))
print("\(dog.name) has \(ownerNames.count) owners (\(ownerNames))")
}
return true
}
}
| apache-2.0 | 24c874d578398cdce0e07a901cbca946 | 34.932203 | 151 | 0.629717 | 4.700665 | false | false | false | false |
00aney/Briefinsta | Briefinsta/Sources/Module/Base/BaseWireframe.swift | 1 | 1374 | //
// BaseWireframe.swift
// Briefinsta
//
// Created by aney on 2017. 10. 24..
// Copyright © 2017년 Ted Kim. All rights reserved.
//
import UIKit
class BaseWireframe {
weak var view: UIViewController!
func show(_ viewController: UIViewController, with type: TransitionType, animated: Bool = true) {
switch type {
case .push:
guard let navigationController = view.navigationController else {
fatalError("Can't push without a navigation controller")
}
navigationController.pushViewController(viewController, animated: animated)
case .present(let sender):
sender.present(viewController, animated: animated)
case .root(let window):
window.rootViewController = viewController
}
}
func pop(animated: Bool) {
if let navigationController = view.navigationController {
guard navigationController.popViewController(animated: animated) != nil else {
if let presentingView = view.presentingViewController {
return presentingView.dismiss(animated: animated)
} else {
fatalError("Can't navigate back from \(view)")
}
}
} else if let presentingView = view.presentingViewController {
presentingView.dismiss(animated: animated)
} else {
fatalError("Neither modal nor navigation! Can't navigate back from \(view)")
}
}
}
| mit | ebf5181152f2febc8656a7784dd3ae5e | 30.159091 | 99 | 0.684172 | 4.861702 | false | false | false | false |
ifels/swiftDemo | MaterialDemo/Pods/NBMaterialDialogIOS/Pod/Classes/NBMaterialDialog.swift | 1 | 19999 | //
// NBMaterialDialog.swift
// NBMaterialDialogIOS
//
// Created by Torstein Skulbru on 02/05/15.
// Copyright (c) 2015 Torstein Skulbru. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Torstein Skulbru
//
// 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 BFPaperButton
/**
Simple material dialog class
*/
@objc open class NBMaterialDialog : UIViewController {
// MARK: - Class variables
fileprivate var overlay: UIView?
fileprivate var titleLabel: UILabel?
fileprivate var containerView: UIView = UIView()
fileprivate var contentView: UIView = UIView()
fileprivate var okButton: BFPaperButton?
fileprivate var cancelButton: BFPaperButton?
fileprivate var tapGesture: UITapGestureRecognizer!
fileprivate var backgroundColor: UIColor!
fileprivate var windowView: UIView!
fileprivate var tappableView: UIView = UIView()
fileprivate var isStacked: Bool = false
fileprivate let kBackgroundTransparency: CGFloat = 0.7
fileprivate let kPadding: CGFloat = 16.0
fileprivate let kWidthMargin: CGFloat = 40.0
fileprivate let kHeightMargin: CGFloat = 24.0
internal var kMinimumHeight: CGFloat {
return 120.0
}
fileprivate var _kMaxHeight: CGFloat?
internal var kMaxHeight: CGFloat {
if _kMaxHeight == nil {
let window = UIScreen.main.bounds
_kMaxHeight = window.height - kHeightMargin - kHeightMargin
}
return _kMaxHeight!
}
internal var strongSelf: NBMaterialDialog?
internal var userAction: ((_ isOtherButton: Bool) -> Void)?
internal var constraintViews: [String: AnyObject]!
// MARK: - Constructors
public convenience init() {
self.init(color: UIColor.white)
}
public convenience init(color: UIColor) {
self.init(nibName: nil, bundle:nil)
view.frame = UIScreen.main.bounds
view.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth]
view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:kBackgroundTransparency)
tappableView.backgroundColor = UIColor.clear
tappableView.frame = view.frame
view.addSubview(tappableView)
backgroundColor = color
setupContainerView()
view.addSubview(containerView)
//Retaining itself strongly so can exist without strong refrence
strongSelf = self
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Dialog Lifecycle
/**
Hides the dialog
*/
open func hideDialog() {
hideDialog(-1)
}
/**
Hides the dialog, sending a callback if provided when dialog was shown
:params: buttonIndex The tag index of the button which was clicked
*/
internal func hideDialog(_ buttonIndex: Int) {
if buttonIndex >= 0 {
if let userAction = userAction {
userAction(buttonIndex > 0)
}
}
tappableView.removeGestureRecognizer(tapGesture)
for childView in view.subviews {
childView.removeFromSuperview()
}
view.removeFromSuperview()
strongSelf = nil
}
/**
Displays a simple dialog using a title and a view with the content you need
- parameter windowView: The window which the dialog is to be attached
- parameter title: The dialog title
- parameter content: A custom content view
*/
open func showDialog(_ windowView: UIView, title: String?, content: UIView) -> NBMaterialDialog {
return showDialog(windowView, title: title, content: content, dialogHeight: nil, okButtonTitle: nil, action: nil, cancelButtonTitle: nil, stackedButtons: false)
}
/**
Displays a simple dialog using a title and a view with the content you need
- parameter windowView: The window which the dialog is to be attached
- parameter title: The dialog title
- parameter content: A custom content view
- parameter dialogHeight: The height of the dialog
*/
open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?) -> NBMaterialDialog {
return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: nil, action: nil, cancelButtonTitle: nil, stackedButtons: false)
}
/**
Displays a simple dialog using a title and a view with the content you need
- parameter windowView: The window which the dialog is to be attached
- parameter title: The dialog title
- parameter content: A custom content view
- parameter dialogHeight: The height of the dialog
- parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response).
*/
open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?) -> NBMaterialDialog {
return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: okButtonTitle, action: nil, cancelButtonTitle: nil, stackedButtons: false)
}
/**
Displays a simple dialog using a title and a view with the content you need
- parameter windowView: The window which the dialog is to be attached
- parameter title: The dialog title
- parameter content: A custom content view
- parameter dialogHeight: The height of the dialog
- parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response).
- parameter action: The action you wish to invoke when a button is clicked
*/
open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((_ isOtherButton: Bool) -> Void)?) -> NBMaterialDialog {
return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: okButtonTitle, action: action, cancelButtonTitle: nil, stackedButtons: false)
}
/**
Displays a simple dialog using a title and a view with the content you need
- parameter windowView: The window which the dialog is to be attached
- parameter title: The dialog title
- parameter content: A custom content view
- parameter dialogHeight: The height of the dialog
- parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response).
- parameter action: The action you wish to invoke when a button is clicked
*/
open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((_ isOtherButton: Bool) -> Void)?, cancelButtonTitle: String?) -> NBMaterialDialog {
return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: okButtonTitle, action: action, cancelButtonTitle: cancelButtonTitle, stackedButtons: false)
}
/**
Displays a simple dialog using a title and a view with the content you need
- parameter windowView: The window which the dialog is to be attached
- parameter title: The dialog title
- parameter content: A custom content view
- parameter dialogHeight: The height of the dialog
- parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response).
- parameter action: The action you wish to invoke when a button is clicked
- parameter cancelButtonTitle: The title of the first button (the left button), normally CANCEL or NO (negative response)
- parameter stackedButtons: Defines if a stackd button view should be used
*/
open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((_ isOtherButton: Bool) -> Void)?, cancelButtonTitle: String?, stackedButtons: Bool) -> NBMaterialDialog {
isStacked = stackedButtons
var totalButtonTitleLength: CGFloat = 0.0
self.windowView = windowView
let windowSize = windowView.bounds
windowView.addSubview(view)
view.frame = windowView.bounds
tappableView.frame = view.frame
tapGesture = UITapGestureRecognizer(target: self, action: #selector(NBMaterialDialog.tappedBg))
tappableView.addGestureRecognizer(tapGesture)
setupContainerView()
// Add content to contentView
contentView = content
setupContentView()
if let title = title {
setupTitleLabelWithTitle(title)
}
if let okButtonTitle = okButtonTitle {
totalButtonTitleLength += (okButtonTitle.uppercased() as NSString).size(attributes: [NSFontAttributeName: UIFont.robotoMediumOfSize(14)]).width + 8
if let cancelButtonTitle = cancelButtonTitle {
totalButtonTitleLength += (cancelButtonTitle.uppercased() as NSString).size(attributes: [NSFontAttributeName: UIFont.robotoMediumOfSize(14)]).width + 8
}
// Calculate if the combined button title lengths are longer than max allowed for this dialog, if so use stacked buttons.
let buttonTotalMaxLength: CGFloat = (windowSize.width - (kWidthMargin*2)) - 16 - 16 - 8
if totalButtonTitleLength > buttonTotalMaxLength {
isStacked = true
}
}
// Always display a close/ok button, but setting a title is optional.
if let okButtonTitle = okButtonTitle {
setupButtonWithTitle(okButtonTitle, button: &okButton, isStacked: isStacked)
if let okButton = okButton {
okButton.tag = 0
okButton.addTarget(self, action: #selector(NBMaterialDialog.pressedAnyButton(_:)), for: UIControlEvents.touchUpInside)
}
}
if let cancelButtonTitle = cancelButtonTitle {
setupButtonWithTitle(cancelButtonTitle, button: &cancelButton, isStacked: isStacked)
if let cancelButton = cancelButton {
cancelButton.tag = 1
cancelButton.addTarget(self, action: #selector(NBMaterialDialog.pressedAnyButton(_:)), for: UIControlEvents.touchUpInside)
}
}
userAction = action
setupViewConstraints()
// To get dynamic width to work we need to comment this out and uncomment the stuff in setupViewConstraints. But its currently not working..
containerView.frame = CGRect(x: kWidthMargin, y: (windowSize.height - (dialogHeight ?? kMinimumHeight)) / 2, width: windowSize.width - (kWidthMargin*2), height: fmin(kMaxHeight, (dialogHeight ?? kMinimumHeight)))
containerView.clipsToBounds = true
return self
}
// MARK: - View lifecycle
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
var sz = UIScreen.main.bounds.size
let sver = UIDevice.current.systemVersion as NSString
let ver = sver.floatValue
if ver < 8.0 {
// iOS versions before 7.0 did not switch the width and height on device roration
if UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) {
let ssz = sz
sz = CGSize(width:ssz.height, height:ssz.width)
}
}
}
// MARK: - User interaction
/**
Invoked when the user taps the background (anywhere except the dialog)
*/
internal func tappedBg() {
hideDialog(-1)
}
/**
Invoked when a button is pressed
- parameter sender: The button clicked
*/
internal func pressedAnyButton(_ sender: AnyObject) {
self.hideDialog((sender as! UIButton).tag)
}
// MARK: - View Constraints
/**
Sets up the constraints which defines the dialog
*/
internal func setupViewConstraints() {
if constraintViews == nil {
constraintViews = ["content": contentView, "containerView": containerView, "window": windowView]
}
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-24-[content]-24-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
if let titleLabel = self.titleLabel {
constraintViews["title"] = titleLabel
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-24-[title]-24-[content]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-24-[title]-24-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
} else {
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-24-[content]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
}
if okButton != nil || cancelButton != nil {
if isStacked {
setupStackedButtonsConstraints()
} else {
setupButtonConstraints()
}
} else {
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[content]-24-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
}
// TODO: Fix constraints for the containerView so we can remove the dialogheight var
//
// let margins = ["kWidthMargin": kWidthMargin, "kMinimumHeight": kMinimumHeight, "kMaxHeight": kMaxHeight]
// view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=kWidthMargin)-[containerView(>=80@1000)]-(>=kWidthMargin)-|", options: NSLayoutFormatOptions(0), metrics: margins, views: constraintViews))
// view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=kWidthMargin)-[containerView(>=48@1000)]-(>=kWidthMargin)-|", options: NSLayoutFormatOptions(0), metrics: margins, views: constraintViews))
// view.addConstraint(NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
// view.addConstraint(NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
}
/**
Sets up the constraints for normal horizontal styled button layout
*/
internal func setupButtonConstraints() {
if let okButton = self.okButton {
constraintViews["okButton"] = okButton
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[content]-24-[okButton(==36)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
// The cancel button is only shown when the ok button is visible
if let cancelButton = self.cancelButton {
constraintViews["cancelButton"] = cancelButton
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[cancelButton(==36)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[cancelButton(>=64)]-8-[okButton(>=64)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
} else {
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[okButton(>=64)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
}
}
}
/**
Sets up the constraints for stacked vertical styled button layout
*/
internal func setupStackedButtonsConstraints() {
constraintViews["okButton"] = okButton!
constraintViews["cancelButton"] = cancelButton!
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[content]-24-[okButton(==48)]-[cancelButton(==48)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[okButton]-16-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[cancelButton]-16-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
}
// MARK: Private view helpers / initializers
fileprivate func setupContainerView() {
containerView.backgroundColor = backgroundColor
containerView.layer.cornerRadius = 2.0
containerView.layer.masksToBounds = true
containerView.layer.borderWidth = 0.5
containerView.layer.borderColor = UIColor(hex: 0xCCCCCC, alpha: 1.0).cgColor
view.addSubview(containerView)
}
fileprivate func setupTitleLabelWithTitle(_ title: String) {
titleLabel = UILabel()
if let titleLabel = titleLabel {
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.font = UIFont.robotoMediumOfSize(20)
titleLabel.textColor = UIColor(white: 0.13, alpha: 1.0)
titleLabel.numberOfLines = 0
titleLabel.text = title
containerView.addSubview(titleLabel)
}
}
fileprivate func setupButtonWithTitle(_ title: String, button: inout BFPaperButton?, isStacked: Bool) {
if button == nil {
button = BFPaperButton()
}
if let button = button {
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(title.uppercased(), for: UIControlState())
button.setTitleColor(NBConfig.AccentColor, for: UIControlState())
button.isRaised = false
button.titleLabel?.font = UIFont.robotoMediumOfSize(14)
if isStacked {
button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.right
button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 20)
} else {
button.contentEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 8)
}
containerView.addSubview(button)
}
}
fileprivate func setupContentView() {
contentView.backgroundColor = UIColor.clear
contentView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(contentView)
}
}
| apache-2.0 | fe8f31f8b50f63468ddb4ffd18d33afd | 46.27896 | 243 | 0.691135 | 5.13585 | false | false | false | false |
sourcebitsllc/Asset-Generator-Mac | XCAssetGenerator/StringExtension.swift | 1 | 1056 | //
// StringExtension.swift
// XCAssetGenerator
//
// Created by Bader on 4/8/15.
// Copyright (c) 2015 Bader Alabdulrazzaq. All rights reserved.
//
import Foundation
extension String {
func remove(strings: [String]) -> String {
var v = self
for s in strings {
v = v.stringByReplacingOccurrencesOfString(s, withString: "")
}
return v
}
// TODO: Swift 2.0
func replace(characters: [Character], withCharacter character: Character) -> String {
return String(map(self) { find(characters, $0) == nil ? $0 : character })
}
func contains(substring: String) -> Bool {
return self.rangeOfString(substring) != nil
}
func removeAssetSetsComponent() -> String {
return self.pathComponents.filter { !$0.isAssetSet() }
|> String.pathWithComponents
}
func removeTrailingSlash() -> String {
var v = self
if v.hasSuffix("/") {
v.removeAtIndex(v.endIndex.predecessor())
}
return v
}
}
| mit | 981e432af2e937e0aefa63ab839befa1 | 25.4 | 89 | 0.589015 | 4.190476 | false | false | false | false |
therealbnut/swift | test/PrintAsObjC/enums.swift | 2 | 5264 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-source-import -emit-module -emit-module-doc -o %t %s -import-objc-header %S/Inputs/enums.h -disable-objc-attr-requires-foundation-module
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %t/enums.swiftmodule -typecheck -emit-objc-header-path %t/enums.h -import-objc-header %S/Inputs/enums.h -disable-objc-attr-requires-foundation-module
// RUN: %FileCheck %s < %t/enums.h
// RUN: %FileCheck -check-prefix=NEGATIVE %s < %t/enums.h
// RUN: %check-in-clang %t/enums.h
// RUN: %check-in-clang -fno-modules -Qunused-arguments %t/enums.h -include Foundation.h -include ctypes.h -include CoreFoundation.h
// REQUIRES: objc_interop
import Foundation
// NEGATIVE-NOT: NSMalformedEnumMissingTypedef :
// NEGATIVE-NOT: enum EnumNamed
// CHECK-LABEL: enum FooComments : NSInteger;
// CHECK-LABEL: enum NegativeValues : int16_t;
// CHECK-LABEL: enum ObjcEnumNamed : NSInteger;
// CHECK-LABEL: @interface AnEnumMethod
// CHECK-NEXT: - (enum NegativeValues)takeAndReturnEnum:(enum FooComments)foo SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (void)acceptPlainEnum:(enum NSMalformedEnumMissingTypedef)_;
// CHECK-NEXT: - (enum ObjcEnumNamed)takeAndReturnRenamedEnum:(enum ObjcEnumNamed)foo SWIFT_WARN_UNUSED_RESULT;
// CHECK-NEXT: - (void)acceptTopLevelImportedWithA:(enum TopLevelRaw)a b:(TopLevelEnum)b c:(TopLevelOptions)c d:(TopLevelTypedef)d e:(TopLevelAnon)e;
// CHECK-NEXT: - (void)acceptMemberImportedWithA:(enum MemberRaw)a b:(enum MemberEnum)b c:(MemberOptions)c d:(enum MemberTypedef)d e:(MemberAnon)e ee:(MemberAnon2)ee;
// CHECK: @end
@objc class AnEnumMethod {
@objc func takeAndReturnEnum(_ foo: FooComments) -> NegativeValues {
return .Zung
}
@objc func acceptPlainEnum(_: NSMalformedEnumMissingTypedef) {}
@objc func takeAndReturnRenamedEnum(_ foo: EnumNamed) -> EnumNamed {
return .A
}
@objc func acceptTopLevelImported(a: TopLevelRaw, b: TopLevelEnum, c: TopLevelOptions, d: TopLevelTypedef, e: TopLevelAnon) {}
@objc func acceptMemberImported(a: Wrapper.Raw, b: Wrapper.Enum, c: Wrapper.Options, d: Wrapper.Typedef, e: Wrapper.Anon, ee: Wrapper.Anon2) {}
}
// CHECK-LABEL: typedef SWIFT_ENUM_NAMED(NSInteger, ObjcEnumNamed, "EnumNamed") {
// CHECK-NEXT: ObjcEnumNamedA = 0,
// CHECK-NEXT: ObjcEnumNamedB = 1,
// CHECK-NEXT: ObjcEnumNamedC = 2,
// CHECK-NEXT: ObjcEnumNamedD = 3,
// CHECK-NEXT: ObjcEnumNamedHelloDolly = 4,
// CHECK-NEXT: };
@objc(ObjcEnumNamed) enum EnumNamed: Int {
case A, B, C, d, helloDolly
}
// CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, EnumWithNamedConstants) {
// CHECK-NEXT: kEnumA SWIFT_COMPILE_NAME("A") = 0,
// CHECK-NEXT: kEnumB SWIFT_COMPILE_NAME("B") = 1,
// CHECK-NEXT: kEnumC SWIFT_COMPILE_NAME("C") = 2,
// CHECK-NEXT: };
@objc enum EnumWithNamedConstants: Int {
@objc(kEnumA) case A
@objc(kEnumB) case B
@objc(kEnumC) case C
}
// CHECK-LABEL: typedef SWIFT_ENUM(unsigned int, ExplicitValues) {
// CHECK-NEXT: ExplicitValuesZim = 0,
// CHECK-NEXT: ExplicitValuesZang = 219,
// CHECK-NEXT: ExplicitValuesZung = 220,
// CHECK-NEXT: };
// NEGATIVE-NOT: ExplicitValuesDomain
@objc enum ExplicitValues: CUnsignedInt {
case Zim, Zang = 219, Zung
func methodNotExportedToObjC() {}
}
// CHECK: /**
// CHECK-NEXT: Foo: A feer, a female feer.
// CHECK-NEXT: */
// CHECK-NEXT: typedef SWIFT_ENUM(NSInteger, FooComments) {
// CHECK: /**
// CHECK-NEXT: Zim: A zeer, a female zeer.
// CHECK: */
// CHECK-NEXT: FooCommentsZim = 0,
// CHECK-NEXT: FooCommentsZang = 1,
// CHECK-NEXT: FooCommentsZung = 2,
// CHECK-NEXT: };
/// Foo: A feer, a female feer.
@objc public enum FooComments: Int {
/// Zim: A zeer, a female zeer.
case Zim
case Zang, Zung
}
// CHECK-LABEL: typedef SWIFT_ENUM(int16_t, NegativeValues) {
// CHECK-NEXT: Zang = -219,
// CHECK-NEXT: Zung = -218,
// CHECK-NEXT: };
@objc enum NegativeValues: Int16 {
case Zang = -219, Zung
func methodNotExportedToObjC() {}
}
// CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, SomeError) {
// CHECK-NEXT: SomeErrorBadness = 9001,
// CHECK-NEXT: SomeErrorWorseness = 9002,
// CHECK-NEXT: };
// CHECK-NEXT: static NSString * _Nonnull const SomeErrorDomain = @"enums.SomeError";
@objc enum SomeError: Int, Error {
case Badness = 9001
case Worseness
}
// CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, SomeOtherError) {
// CHECK-NEXT: SomeOtherErrorDomain = 0,
// CHECK-NEXT: };
// NEGATIVE-NOT: NSString * _Nonnull const SomeOtherErrorDomain
@objc enum SomeOtherError: Int, Error {
case Domain // collision!
}
// CHECK-LABEL: typedef SWIFT_ENUM_NAMED(NSInteger, ObjcErrorType, "SomeRenamedErrorType") {
// CHECK-NEXT: ObjcErrorTypeBadStuff = 0,
// CHECK-NEXT: };
// CHECK-NEXT: static NSString * _Nonnull const ObjcErrorTypeDomain = @"enums.SomeRenamedErrorType";
@objc(ObjcErrorType) enum SomeRenamedErrorType: Int, Error {
case BadStuff
}
// CHECK-NOT: enum {{[A-Z]+}}
// CHECK-LABEL: @interface ZEnumMethod
// CHECK-NEXT: - (enum NegativeValues)takeAndReturnEnum:(enum FooComments)foo SWIFT_WARN_UNUSED_RESULT;
// CHECK: @end
@objc class ZEnumMethod {
@objc func takeAndReturnEnum(_ foo: FooComments) -> NegativeValues {
return .Zung
}
}
| apache-2.0 | 0b27d618fa9964e158251e058fddec21 | 36.070423 | 229 | 0.712766 | 3.205847 | false | false | false | false |
buyiyang/iosstar | iOSStar/Scenes/Discover/Controllers/VideoHistoryVC.swift | 3 | 6317 | //
// VideoHistoryVC.swift
// iOSStar
//
// Created by mu on 2017/8/19.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import SVProgressHUD
class VideoHistoryCell: OEZTableViewCell {
@IBOutlet weak var voiceCountLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet var status: UILabel!
@IBOutlet var name: UILabel!
@IBOutlet var header: UIImageView!
@IBOutlet var askBtn: UIButton!
override func awakeFromNib() {
}
override func update(_ data: Any!) {
if let response = data as? UserAskDetailList{
contentLabel.text = response.uask
timeLabel.text = Date.yt_convertDateStrWithTimestempWithSecond(Int(response.ask_t), format: "YYYY-MM-dd")
voiceCountLabel.text = "\(response.s_total)看过"
askBtn.isHidden = response.video_url == "" ? true : false
if response.isall == 1{
if response.answer_t == 0{
status.text = "明星未回复"
}else{
status.text = "已定制"
}
StartModel.getStartName(startCode: response.starcode) { [weak self](response) in
if let star = response as? StartModel {
self?.header.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + star.pic_url_tail))
self?.name.text = star.name
}
}
}
}
}
@IBAction func seeAnswer(_ sender: Any) {
didSelectRowAction(1, data: nil)
}
@IBAction func seeAsk(_ sender: Any) {
didSelectRowAction(2, data: nil)
}
}
class VideoHistoryVC: BasePageListTableViewController,OEZTableViewDelegate {
@IBOutlet weak var titlesView: UIView!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var openButton: UIButton!
var starModel: StarSortListModel = StarSortListModel()
var type = true
private var selectedButton: UIButton?
override func viewDidLoad() {
super.viewDidLoad()
title = "历史提问"
titleViewButtonAction(openButton)
}
func tableView(_ tableView: UITableView!, rowAt indexPath: IndexPath!, didAction action: Int, data: Any!){
if action == 1{
if let model = dataSource?[indexPath.row] as? UserAskDetailList{
if model.answer_t == 0{
SVProgressHUD.showErrorMessage(ErrorMessage: "明星还没回复", ForDuration: 2, completion: nil)
return
}
self.pushViewController(pushSreing: PlaySingleVC.className(), videdoUrl: (ShareDataModel.share().qiniuHeader + model.sanswer), pushModel: model, withImg: model.thumbnailS != "" ? model.thumbnailS : "1123.png", complete: { (result) in
if let vc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: "VideoAskQuestionsVC") as? VideoAskQuestionsVC{
self.navigationController?.pushViewController(vc, animated: true)
}
})
}
}
if action == 2{
if let model = dataSource?[indexPath.row] as? UserAskDetailList{
if model.video_url == ""{
SVProgressHUD.showErrorMessage(ErrorMessage: "没有提问视频问题", ForDuration: 2, completion: nil)
return
}
self.pushViewController(pushSreing: PlaySingleVC.className(), videdoUrl: (ShareDataModel.share().qiniuHeader + model.video_url), pushModel: model, withImg: model.thumbnail != "" ? model.thumbnail : "1123.png", complete: { (result) in
if let vc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: "VideoAskQuestionsVC") as? VideoAskQuestionsVC{
vc.starModel = self.starModel
self.navigationController?.pushViewController(vc, animated: true)
}
})
}
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let model = dataSource?[indexPath.row] as? UserAskDetailList{
return model.cellHeight
}
return 175
}
@IBAction func titleViewButtonAction(_ sender: UIButton) {
if self.dataSource != nil{
self.dataSource?.removeAll()
self.tableView.reloadData()
}
self.selectedButton?.isSelected = false
self.selectedButton?.backgroundColor = UIColor.clear
sender.backgroundColor = UIColor(hexString: "ffffff")
self.selectedButton = sender
if selectedButton == closeButton{
type = false
}else{
type = true
}
self.didRequest(1)
}
override func didRequest(_ pageIndex: Int) {
let model = UserAskRequestModel()
model.aType = 1
if starModel.symbol == ""{
}else{
model.starcode = starModel.symbol
}
model.pos = pageIndex == 1 ? 1 : dataSource?.count ?? 0
model.pType = type ? 1 : 0
model.pos = (pageIndex - 1) * 10
AppAPIHelper.discoverAPI().useraskQuestion(requestModel: model, complete: { [weak self](result) in
if let response = result as? UserAskList {
for model in response.circle_list!{
model.calculateCellHeight()
}
self?.didRequestComplete(response.circle_list as AnyObject )
}
}) { (error) in
self.didRequestComplete(nil)
}
}
override func tableView(_ tableView: UITableView, cellIdentifierForRowAtIndexPath indexPath: IndexPath) -> String? {
let model = dataSource?[indexPath.row] as! UserAskDetailList
if model.isall == 1{
return "VideoShowImgCell"
}
//
return VideoHistoryCell.className()
}
}
| gpl-3.0 | df4d4bf46afe4b7d233bbfdab296e875 | 36.029586 | 251 | 0.572387 | 4.870039 | false | false | false | false |
zarghol/ViewDeckSwift | CNViewDeck/CNPresentationController.swift | 1 | 1879 | //
// CNPresentationController.swift
// CNViewDeck
//
// Created by Clément NONN on 06/06/2014.
// Copyright (c) 2014 Clément NONN. All rights reserved.
//
import UIKit
class CNPresentationController: UIPresentationController {
override func presentationTransitionWillBegin(){
let containerView = self.containerView
let presentedViewController = self.presentedViewController
//a voir
let dimmingView = presentedViewController.view
presentedView().frame = containerView.bounds
presentedView().alpha = 0.0
containerView.insertSubview(presentedViewController.view, atIndex:0)
presentedViewController.transitionCoordinator().animateAlongsideTransition(test, completion:nil)
}
func test(coord : UIViewControllerTransitionCoordinatorContext!){
presentedView().alpha = 0.0
}
func test2(coord : UIViewControllerTransitionCoordinatorContext!){
presentedView().alpha = 1.0
}
override func dismissalTransitionWillBegin(){
self.presentedViewController.transitionCoordinator().animateAlongsideTransition(test2, completion:nil)
}
override func sizeForChildContentContainer(container:UIContentContainer, withParentContainerSize parentSize:CGSize) -> CGSize{
return CGSizeMake(parentSize.width/3.0, parentSize.height)
}
override func containerViewWillLayoutSubviews(){
presentedView().frame = self.containerView.bounds
}
override func frameOfPresentedViewInContainerView() -> CGRect{
let presentedViewFrame = CGRectZero
let containerBounds = self.containerView.bounds
// missing code
let bla:UIContentContainer = self.presentedView()
let size:CGSize = self.sizeForChildContentContainer(, withParentContainerSize:containerBounds.size)
}
}
| lgpl-2.1 | b73eb2f24567e99e9e1c4b70e6d410aa | 34.415094 | 130 | 0.719766 | 5.884013 | false | true | false | false |
JudoPay/JudoKit | Source/Receipt.swift | 3 | 3728 | //
// Receipt.swift
// Judo
//
// Copyright (c) 2016 Alternative Payments Ltd
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
open class Receipt {
/// the receipt ID - nil for a list of all receipts
fileprivate (set) var receiptId: String?
/// The current Session to access the Judo API
open var APISession: Session?
/**
Initialization for a Receipt Object
If you want to use the receipt function, you need to enable it in your judo Dashboard
- Parameter receiptId: the receipt ID as a String - if nil, completion function will return a list of all transactions
- Returns: a Receipt Object for reactive usage
- Throws: LuhnValidationError if the receiptId does not match
*/
init(receiptId: String? = nil) throws {
// luhn check the receipt id
self.receiptId = receiptId
}
/**
apiSession caller - this method sets the session variable and returns itself for further use
- Parameter session: the API session which is used to call the Judo endpoints
- Returns: reactive self
*/
open func apiSession(_ session: Session) -> Self {
self.APISession = session
return self
}
/**
Completion caller - this method will automatically trigger a Session Call to the judo REST API and execute the request based on the information that were set in the previous methods.
- Parameter block: a completion block that is called when the request finishes
- Returns: reactive self
*/
open func completion(_ block: @escaping JudoCompletionBlock) -> Self {
var path = "transactions"
if let rec = self.receiptId {
path += "/\(rec)"
}
self.APISession?.GET(path, parameters: nil) { (dictionary, error) -> () in
block(dictionary, error)
}
return self
}
/**
This method will return a list of receipts
See [List all transactions](<https://www.judopay.com/docs/v4_1/restful-api/api-reference/#transactions>) for more information.
- Parameter pagination: The offset, number of items and order in which to return the items
- Parameter block: a completion block that is called when the request finishes
*/
open func list(_ pagination: Pagination, block: @escaping JudoCompletionBlock) {
let path = "transactions?pageSize=\(pagination.pageSize)&offset=\(pagination.offset)&sort=\(pagination.sort.rawValue)"
self.APISession?.GET(path, parameters: nil) { (dictionary, error) -> () in
block(dictionary, error)
}
}
}
| mit | 01e00585aca084ffaa210854c9e541a6 | 36.28 | 186 | 0.677843 | 4.665832 | false | false | false | false |
AnRanScheme/magiGlobe | magi/magiGlobe/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift | 13 | 1680 | //
// BatchedCollection.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 08/01/2017.
// Copyright © 2017 Marcin Krzyzanowski. All rights reserved.
//
struct BatchedCollectionIndex<Base: Collection> {
let range: Range<Base.Index>
}
extension BatchedCollectionIndex: Comparable {
static func ==<Base: Collection>(lhs: BatchedCollectionIndex<Base>, rhs: BatchedCollectionIndex<Base>) -> Bool {
return lhs.range.lowerBound == rhs.range.lowerBound
}
static func < <Base: Collection>(lhs: BatchedCollectionIndex<Base>, rhs: BatchedCollectionIndex<Base>) -> Bool {
return lhs.range.lowerBound < rhs.range.lowerBound
}
}
protocol BatchedCollectionType: Collection {
associatedtype Base: Collection
}
struct BatchedCollection<Base: Collection>: Collection {
let base: Base
let size: Base.IndexDistance
typealias Index = BatchedCollectionIndex<Base>
private func nextBreak(after idx: Base.Index) -> Base.Index {
return base.index(idx, offsetBy: size, limitedBy: base.endIndex)
?? base.endIndex
}
var startIndex: Index {
return Index(range: base.startIndex..<nextBreak(after: base.startIndex))
}
var endIndex: Index {
return Index(range: base.endIndex..<base.endIndex)
}
func index(after idx: Index) -> Index {
return Index(range: idx.range.upperBound..<nextBreak(after: idx.range.upperBound))
}
subscript(idx: Index) -> Base.SubSequence {
return base[idx.range]
}
}
extension Collection {
func batched(by size: IndexDistance) -> BatchedCollection<Self> {
return BatchedCollection(base: self, size: size)
}
}
| mit | 03478c25cea986328582e8390941a491 | 31.288462 | 116 | 0.691483 | 4.105134 | false | false | false | false |
dreamsxin/swift | test/1_stdlib/FloatingPointIR.swift | 2 | 2645 | // RUN: %target-build-swift -emit-ir %s | FileCheck -check-prefix=%target-cpu %s
// RUN: %target-build-swift -O -emit-ir %s | FileCheck -check-prefix=%target-cpu %s
// RUN: %target-build-swift -Ounchecked -emit-ir %s | FileCheck -check-prefix=%target-cpu %s
var globalFloat32 : Float32 = 0.0
var globalFloat64 : Float64 = 0.0
#if arch(i386) || arch(x86_64)
var globalFloat80 : Float80 = 0.0
#endif
@inline(never)
func acceptFloat32(_ a: Float32) {
globalFloat32 = a
}
@inline(never)
func acceptFloat64(_ a: Float64) {
globalFloat64 = a
}
#if arch(i386) || arch(x86_64)
@inline(never)
func acceptFloat80(_ a: Float80) {
globalFloat80 = a
}
#endif
func testConstantFoldFloatLiterals() {
acceptFloat32(1.0)
acceptFloat64(1.0)
#if arch(i386) || arch(x86_64)
acceptFloat80(1.0)
#endif
}
// i386: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// i386: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// i386: call void @{{.*}}_TF15FloatingPointIR13acceptFloat80FVs7Float80T_(x86_fp80 0xK3FFF8000000000000000)
// x86_64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// x86_64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// x86_64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat80FVs7Float80T_(x86_fp80 0xK3FFF8000000000000000)
// armv7: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// armv7: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// armv7s: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// armv7s: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// armv7k: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// armv7k: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// arm64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// arm64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// powerpc64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// powerpc64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// powerpc64le: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// powerpc64le: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// s390x: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// s390x: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
| apache-2.0 | d77a0214f7e0686699a3083c4848b271 | 40.984127 | 110 | 0.73724 | 3.265432 | false | false | false | false |
bigL055/Routable | Example/Pods/BLFoundation/Sources/Tools/RunTime.swift | 1 | 4135 | //
// BLFoundation
//
// Copyright (c) 2017 linhay - https://github.com/linhay
//
// 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
import Foundation
public class RunTime {
/// 交换方法
///
/// - Parameters:
/// - target: 被交换的方法名
/// - replace: 用于交换的方法名
/// - classType: 所属类型
public class func exchangeMethod(target: String,
replace: String,
class classType: AnyClass) {
exchangeMethod(selector: Selector(target),
replace: Selector(replace),
class: classType)
}
/// 交换方法
///
/// - Parameters:
/// - selector: 被交换的方法
/// - replace: 用于交换的方法
/// - classType: 所属类型
public class func exchangeMethod(selector: Selector,
replace: Selector,
class classType: AnyClass) {
let select1 = selector
let select2 = replace
let select1Method = class_getInstanceMethod(classType, select1)
let select2Method = class_getInstanceMethod(classType, select2)
let didAddMethod = class_addMethod(classType,
select1,
method_getImplementation(select2Method!),
method_getTypeEncoding(select2Method!))
if didAddMethod {
class_replaceMethod(classType,
select2,
method_getImplementation(select1Method!),
method_getTypeEncoding(select1Method!))
}else {
method_exchangeImplementations(select1Method!, select2Method!)
}
}
/// 获取方法列表
///
/// - Parameter classType: 所属类型
/// - Returns: 方法列表
public class func methods(from classType: AnyClass) -> [Method] {
var methodNum: UInt32 = 0
var list = [Method]()
let methods = class_copyMethodList(classType, &methodNum)
for index in 0..<numericCast(methodNum) {
if let met = methods?[index] {
list.append(met)
}
}
free(methods)
return list
}
/// 获取属性列表
///
/// - Parameter classType: 所属类型
/// - Returns: 属性列表
public class func properties(from classType: AnyClass) -> [objc_property_t] {
var propNum: UInt32 = 0
let properties = class_copyPropertyList(classType, &propNum)
var list = [objc_property_t]()
for index in 0..<Int(propNum) {
if let prop = properties?[index]{
list.append(prop)
}
}
free(properties)
return list
}
/// 成员变量列表
///
/// - Parameter classType: 类型
/// - Returns: 成员变量
public class func ivars(from classType: AnyClass) -> [Ivar] {
var ivarNum: UInt32 = 0
let ivars = class_copyIvarList(classType, &ivarNum)
var list = [Ivar]()
for index in 0..<numericCast(ivarNum) {
if let ivar: objc_property_t = ivars?[index] {
list.append(ivar)
}
}
free(ivars)
return list
}
}
| mit | 3c8dae8748d4e6d394257fa128418b7b | 32.618644 | 82 | 0.616083 | 4.364136 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Extensions/Configuration+IndentationStyle.swift | 1 | 773 | public extension Configuration {
enum IndentationStyle: Equatable {
case tabs
case spaces(count: Int)
public static var `default` = spaces(count: 4)
internal init?(_ object: Any?) {
switch object {
case let value as Int: self = .spaces(count: value)
case let value as String where value == "tabs": self = .tabs
default: return nil
}
}
// MARK: Equatable
public static func == (lhs: IndentationStyle, rhs: IndentationStyle) -> Bool {
switch (lhs, rhs) {
case (.tabs, .tabs): return true
case let (.spaces(lhs), .spaces(rhs)): return lhs == rhs
case (_, _): return false
}
}
}
}
| mit | bc897bf4eb0ac48d502d01d1e276c75e | 28.730769 | 86 | 0.520052 | 4.628743 | false | false | false | false |
0xfeedface1993/Xs8-Safari-Block-Extension-Mac | Sex8BlockExtension/Sex8BlockExtension/ViewController.swift | 1 | 8551 | //
// ViewController.swift
// Sex8BlockExtension
//
// Created by virus1993 on 2017/6/13.
// Copyright © 2017年 ascp. All rights reserved.
//
import Cocoa
import WebShell
let StopFetchName = NSNotification.Name.init("stopFetching")
let ShowExtennalTextName = NSNotification.Name.init("showExtennalText")
let UploadName = NSNotification.Name.init("UploadName")
let DownloadAddressName = NSNotification.Name.init("com.ascp.dowload.address.click")
let RemoteDownloadAddressName = NSNotification.Name.init("com.ascp.remote.dowload.address.click")
var searchText : String?
class ViewController: NSViewController, UpdateProtocol {
@IBOutlet weak var save: NSButton!
@IBOutlet weak var collectionView: NSView!
@IBOutlet weak var head: TapImageView!
@IBOutlet weak var username: NSTextField!
@IBOutlet weak var userprofile: NSTextField!
@IBOutlet weak var extenalText: NSTextField!
@IBOutlet weak var searchArea: NSSearchField!
@IBOutlet weak var downloadButton: NSButton!
lazy var downloadViewController : ContentViewController = storyboard!.instantiateController(withIdentifier: "com.ascp.contenView") as! ContentViewController
lazy var popver : NSPopover = {
let popver = NSPopover()
popver.appearance = NSAppearance(named: NSAppearance.Name.aqua)
let vc = self.downloadViewController
vc.view.wantsLayer = true
vc.view.layer?.cornerRadius = 10
popver.contentViewController = vc
popver.behavior = .transient
return popver
}()
var downloadURL : URL?
let login = NSStoryboard(name: "LoginStoryboard", bundle: Bundle.main).instantiateInitialController() as! NSWindowController
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
unselect()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.select), name: SelectItemName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.unselect), name: UnSelectItemName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.stopFetch), name: StopFetchName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.showExtennalText(notification:)), name: ShowExtennalTextName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(resetSearchValue(notification:)), name: NSControl.textDidChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(changeDownloadState(notification: )), name: DownloadAddressName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(download(_:)), name: RemoteDownloadAddressName, object: nil)
head.tapBlock = {
[weak self] image in
// let app = NSApp.delegate as! AppDelegate
// if let _ = app.user {
//
// } else {
// self.login.showWindow(nil)
// }
self?.popver.show(relativeTo: image.bounds, of: image, preferredEdge: .maxY)
}
searchArea.delegate = self
upload.isHidden = true
// extract.isHidden = true
}
deinit {
NotificationCenter.default.removeObserver(self, name: SelectItemName, object: nil)
NotificationCenter.default.removeObserver(self, name: UnSelectItemName, object: nil)
NotificationCenter.default.removeObserver(self, name: StopFetchName, object: nil)
NotificationCenter.default.removeObserver(self, name: ShowExtennalTextName, object: nil)
NotificationCenter.default.removeObserver(self, name: DownloadAddressName, object: nil)
NotificationCenter.default.removeObserver(self, name: RemoteDownloadAddressName, object: nil)
NotificationCenter.default.removeObserver(self, name: NSControl.textDidChangeNotification, object: nil)
}
override func viewDidAppear() {
super.viewDidAppear()
}
@IBOutlet weak var extract: NSButton!
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func save(_ sender: Any) {
let app = NSApplication.shared.delegate as! AppDelegate
app.resetAllRecords(in: "NetDisk")
}
@IBAction func extract(_ sender: Any) {
let fetchButton = sender as! NSButton
if fetchButton.tag == 110 {
stopFetch()
} else {
fetchButton.tag = 110
fetchButton.title = "停止"
}
NotificationCenter.default.post(name: TableViewRefreshName, object: fetchButton)
}
@objc func stopFetch() {
extract.tag = 112
extract.title = "获取前十页"
self.extenalText.stringValue = "(已停止)" + self.extenalText.stringValue
}
@IBAction func deleteAction(_ sender: Any) {
NotificationCenter.default.post(name: DeleteActionName, object: nil)
}
@objc func select() {
}
@objc func unselect() {
}
@IBOutlet weak var upload: NSButton!
@IBAction func uploadAction(_ sender: Any) {
if upload.title == "上传" {
upload.title = "停止"
NotificationCenter.default.post(name: UploadName, object: nil)
} else {
upload.title = "上传"
NotificationCenter.default.post(name: UploadName, object: 444)
}
}
@objc func showExtennalText(notification: NSNotification?) {
if let text = notification?.object as? String {
self.extenalText.stringValue = text
}
}
//MARK: - 下载
@IBAction func download(_ sender: Any) {
defer {
downloadButton.isEnabled = false
}
guard let link = downloadURL else {
print("dowloadURL is nil!")
return
}
let pipline = PCPipeline.share
pipline.delegate = self
let app = NSApp.delegate as! AppDelegate
let password = "\(app.selectItem?.passwod ?? "")"
let firendName = "\(app.selectItem?.title?.replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ".", with: "-") ?? "")"
if let _ = pipline.add(url: link.absoluteString, password: password, friendName: firendName) {
// riffle.downloadStateController = downloadViewController.resultArrayContriller
view.toast("成功添加下载任务")
}
}
@objc func changeDownloadState(notification: Notification) {
guard let linkString = notification.object as? String else {
print("none string object!")
downloadButton.isEnabled = false
downloadURL = nil
return
}
guard let linkURL = URL(string: linkString) else {
print("none URL string!")
downloadButton.isEnabled = false
downloadURL = nil
return
}
downloadURL = linkURL
downloadButton.isEnabled = true
}
}
// MARK: - Login Fun
extension ViewController {
}
// MARK: - TextFieldDelegate
extension ViewController : NSSearchFieldDelegate {
func searchFieldDidStartSearching(_ sender: NSSearchField) {
print("start search!")
}
func searchFieldDidEndSearching(_ sender: NSSearchField) {
print("end search")
}
@objc func resetSearchValue(notification: NSNotification?) {
print("change text value \(searchArea.stringValue)")
}
}
extension ViewController : PCPiplineDelegate {
func pipline(didAddRiffle riffle: PCWebRiffle) {
let vc = downloadViewController
print("found \(vc)")
vc.add(riffle: riffle)
}
func pipline(didUpdateTask task: PCDownloadTask) {
let vc = downloadViewController
vc.update(task: task)
}
func pipline(didFinishedTask task: PCDownloadTask) {
let vc = downloadViewController
vc.finished(task: task)
}
func pipline(didFinishedRiffle riffle: PCWebRiffle) {
let vc = downloadViewController
if let task = PCDownloadManager.share.allTasks.first(where: { $0.request.riffle == riffle }) {
vc.finished(task: task)
} else {
vc.finished(riffle: riffle)
}
}
}
| apache-2.0 | d1a118e1649fc879c7a6d8f9592049b3 | 34.848101 | 162 | 0.645833 | 4.635025 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Extensions/UIColorExtension.swift | 1 | 5854 | //
// UIColorExtension.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 8/4/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
enum SystemMessageColor {
case warning
case danger
case good
case unknown(String)
init(rawValue: String) {
switch rawValue {
case SystemMessageColor.warning.rawValue: self = .warning
case SystemMessageColor.danger.rawValue: self = .danger
case SystemMessageColor.good.rawValue: self = .good
default:
self = .unknown(rawValue)
}
}
var rawValue: String {
return String(describing: self)
}
var color: UIColor {
switch self {
case .warning: return UIColor(rgb: 0xFCB316, alphaVal: 1)
case .danger: return UIColor(rgb: 0xD30230, alphaVal: 1)
case .good: return UIColor(rgb: 0x35AC19, alphaVal: 1)
case .unknown(let string): return UIColor(hex: string)
}
}
}
extension UIColor {
convenience init(rgb: Int, alphaVal: CGFloat) {
self.init(
red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgb & 0x0000FF) / 255.0,
alpha: CGFloat(alphaVal)
)
}
// MARK: Avatar Colors
static var avatarColors: [UIColor] {
return [
0xF44336, 0xE91E63, 0x9C27B0, 0x673AB7, 0x3F51B5,
0x2196F3, 0x03A9F4, 0x00BCD4, 0x009688, 0x4CAF50,
0x8BC34A, 0xCDDC39, 0xFFC107, 0xFF9800, 0xFF5722,
0x795548, 0x9E9E9E, 0x607D8B
].map { UIColor(rgb: $0, alphaVal: 1.0) }
}
static func forName(_ name: String) -> UIColor {
return avatarColors[name.count % avatarColors.count]
}
// MARK: Color from strings
static func normalizeColorFromString(string: String) -> UIColor {
return SystemMessageColor(rawValue: string).color
}
// MARK: Status
static func RCOnline() -> UIColor {
return UIColor(rgb: 0x2DE0A5, alphaVal: 1)
}
static func RCAway() -> UIColor {
return UIColor(rgb: 0xFFD21F, alphaVal: 1)
}
static func RCBusy() -> UIColor {
return UIColor(rgb: 0xF5455C, alphaVal: 1)
}
static func RCInvisible() -> UIColor {
return UIColor(rgb: 0xCBCED1, alphaVal: 1)
}
// MARK: Theme color
static func RCNavigationBarColor() -> UIColor {
return UIColor(rgb: 0xF8F8F8, alphaVal: 1)
}
static func RCBackgroundColor() -> UIColor {
return UIColor(rgb: 0x2F343D, alphaVal: 1)
}
static func RCEditingAvatarColor() -> UIColor {
return UIColor(rgb: 0xEAEAEA, alphaVal: 0.75)
}
static func RCTextFieldGray() -> UIColor {
return UIColor(rgb: 10396328, alphaVal: 1)
}
static func RCTextFieldBorderGray() -> UIColor {
return UIColor(rgb: 15199218, alphaVal: 1)
}
static func RCButtonBorderGray() -> UIColor {
return UIColor(rgb: 14804456, alphaVal: 1)
}
static func RCDarkGray() -> UIColor {
return UIColor(rgb: 0x333333, alphaVal: 1)
}
static func RCGray() -> UIColor {
return UIColor(rgb: 0x9EA2A8, alphaVal: 1)
}
static func RCNavBarGray() -> UIColor {
return UIColor(rgb: 3355443, alphaVal: 1)
}
static func RCLightGray() -> UIColor {
return UIColor(rgb: 0xCBCED1, alphaVal: 1)
}
static func RCSeparatorGrey() -> UIColor {
return UIColor(rgb: 0xC2C2C2, alphaVal: 0.5)
}
static func RCSkyBlue() -> UIColor {
return UIColor(rgb: 1930485, alphaVal: 1)
}
static func RCDarkBlue() -> UIColor {
return UIColor(rgb: 0x0a4469, alphaVal: 1)
}
static func RCLightBlue() -> UIColor {
return UIColor(rgb: 0x9EA2A8, alphaVal: 1)
}
static func RCBlue() -> UIColor {
return UIColor(rgb: 0x1D74F5, alphaVal: 1)
}
// MARK: Function color
static func RCFavoriteMark() -> UIColor {
return UIColor(rgb: 0xF8B62B, alphaVal: 1.0)
}
static func RCFavoriteUnmark() -> UIColor {
return UIColor.lightGray
}
// MARK: Colors from Web Version
static let primaryAction = UIColor(rgb: 0x1D74F5, alphaVal: 1)
static let secondAction = UIColor(rgb: 0xD3E3FC, alphaVal: 1)
static let attention = UIColor(rgb: 0xF5455C, alphaVal: 1)
static var code: UIColor {
return UIColor(rgb: 0x333333, alphaVal: 1.0)
}
static var codeBackground: UIColor {
return UIColor(rgb: 0xF8F8F8, alphaVal: 1.0)
}
// MARK: Mention Color
static func background(for mention: Mention) -> UIColor {
if mention.username == AuthManager.currentUser()?.username {
return .primaryAction
}
if mention.username == "all" || mention.username == "here" {
return .attention
}
return .white
}
static func font(for mention: Mention) -> UIColor {
if mention.username == AuthManager.currentUser()?.username {
return .white
}
if mention.username == "all" || mention.username == "here" {
return .white
}
return .primaryAction
}
}
// MARK: UIKit default colors
extension UIColor {
static var placeholderGray: UIColor {
return UIColor(red: 199/255, green: 199/255, blue: 205/255, alpha: 1)
}
static var backgroundWhite: UIColor {
return UIColor(red: 247/255, green: 247/255, blue: 247/255, alpha: 1)
}
}
// MARK: Utils
extension UIColor {
func isBrightColor() -> Bool {
guard let components = cgColor.components else { return false }
let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000
return brightness < 0.5 ? false : true
}
}
| mit | 092affe25687f466337d49746786b0ca | 25.013333 | 103 | 0.606014 | 3.619666 | false | false | false | false |
ThryvInc/subway-ios | SubwayMap/DatabaseLoader.swift | 2 | 3249 | //
// DatabaseLoader.swift
// SubwayMap
//
// Created by Elliot Schrock on 8/2/15.
// Copyright (c) 2015 Thryv. All rights reserved.
//
import UIKit
import GTFSStations
import SubwayStations
import ZipArchive
class DatabaseLoader: NSObject {
static var isDatabaseReady: Bool = false
static var stationManager: StationManager!
static var navManager: StationManager!
static let NYCDatabaseLoadedNotification = "NYCDatabaseLoadedNotification"
static var documentsDirectory: String {
return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
}
static var destinationPath: String {
return self.documentsDirectory + "/" + "gtfs.db"
}
static var navDbDestinationPath: String {
return self.documentsDirectory + "/" + "nav.db"
}
class func loadDb() {
unzipDBToDocDirectoryIfNeeded()
do {
stationManager = try NYCStationManager(sourceFilePath: destinationPath)
navManager = try NYCStationManager(sourceFilePath: navDbDestinationPath)
DispatchQueue.main.async (execute: { () -> Void in
self.isDatabaseReady = true
NotificationCenter.default.post(name: Notification.Name(rawValue: self.NYCDatabaseLoadedNotification), object: nil)
})
}catch let error as NSError {
print(error.debugDescription)
}
}
class func unzipDBToDocDirectoryIfNeeded(){
if shouldUnzip(defaultsKey: "version", path: destinationPath) {
unzipScheduleToDocDirectory()
}
if shouldUnzip(defaultsKey: "nav_version", path: navDbDestinationPath) {
unzipNavToDocDirectory()
}
}
class func shouldUnzip(defaultsKey: String, path: String) -> Bool {
var shouldUnzip = !FileManager.default.fileExists(atPath: path)
if let storedVersion = UserDefaults.standard.string(forKey: defaultsKey) {
shouldUnzip = shouldUnzip || VersionChecker.isNewVersion(version: storedVersion)
} else {
shouldUnzip = true
}
return shouldUnzip
}
class func unzipScheduleToDocDirectory() {
unzipDBToDocDirectory(resourceName: "gtfs.db", destination: destinationPath, defaultsKey: "version")
}
class func unzipNavToDocDirectory() {
unzipDBToDocDirectory(resourceName: "nav.db", destination: navDbDestinationPath, defaultsKey: "nav_version")
}
class func unzipDBToDocDirectory(resourceName: String, destination: String, defaultsKey: String){
let sourcePath = Bundle.main.path(forResource: resourceName, ofType: "zip")
var error: NSError?
let unzipper = ZipArchive()
unzipper.unzipOpenFile(sourcePath)
unzipper.unzipFile(to: documentsDirectory, overWrite: true)
let fileUrl = URL(fileURLWithPath: destinationPath)
do {
try (fileUrl as NSURL).setResourceValue(NSNumber(value: true as Bool), forKey: URLResourceKey.isExcludedFromBackupKey)
} catch let error1 as NSError {
error = error1
}
UserDefaults.standard.set(VersionChecker.bundleVersion(), forKey: defaultsKey)
}
}
| mit | a520659534d64d9dbdc2588df7551cc8 | 36.77907 | 131 | 0.670976 | 4.695087 | false | false | false | false |
rnystrom/GitHawk | Pods/StyledTextKit/Source/StyledText.swift | 1 | 5067 | //
// StyledTextKit.swift
// StyledTextKit
//
// Created by Ryan Nystrom on 12/12/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import UIKit
public class StyledText: Hashable, Equatable {
public struct ImageFitOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let fit = ImageFitOptions(rawValue: 1 << 0)
public static let center = ImageFitOptions(rawValue: 2 << 0)
}
public enum Storage: Hashable, Equatable {
case text(String)
case attributedText(NSAttributedString)
case image(UIImage, [ImageFitOptions])
// MARK: Hashable
public var hashValue: Int {
switch self {
case .text(let text): return text.hashValue
case .attributedText(let text): return text.hashValue
case .image(let image, _): return image.hashValue
}
}
// MARK: Equatable
public static func ==(lhs: Storage, rhs: Storage) -> Bool {
switch lhs {
case .text(let lhsText):
switch rhs {
case .text(let rhsText): return lhsText == rhsText
case .attributedText, .image: return false
}
case .attributedText(let lhsText):
switch rhs {
case .text, .image: return false
case .attributedText(let rhsText): return lhsText == rhsText
}
case .image(let lhsImage, let lhsOptions):
switch rhs {
case .text, .attributedText: return false
case .image(let rhsImage, let rhsOptions):
return lhsImage == rhsImage && lhsOptions == rhsOptions
}
}
}
}
public let storage: Storage
public let style: TextStyle
public init(storage: Storage = .text(""), style: TextStyle = TextStyle()) {
self.storage = storage
self.style = style
}
public convenience init(text: String, style: TextStyle = TextStyle()) {
self.init(storage: .text(text), style: style)
}
internal var text: String {
switch storage {
case .text(let text): return text
case .attributedText(let text): return text.string
case .image: return ""
}
}
internal func render(contentSizeCategory: UIContentSizeCategory) -> NSAttributedString {
var attributes = style.attributes
let font = style.font(contentSizeCategory: contentSizeCategory)
attributes[.font] = font
switch storage {
case .text(let text):
return NSAttributedString(string: text, attributes: attributes)
case .attributedText(let text):
guard text.length > 0 else { return text }
let mutable = text.mutableCopy() as? NSMutableAttributedString ?? NSMutableAttributedString()
let range = NSRange(location: 0, length: mutable.length)
for (k, v) in attributes {
// avoid overwriting attributes set by the stored string
if mutable.attribute(k, at: 0, effectiveRange: nil) == nil {
mutable.addAttribute(k, value: v, range: range)
}
}
return mutable
case .image(let image, let options):
let attachment = NSTextAttachment()
attachment.image = image
var bounds = attachment.bounds
let size = image.size
if options.contains(.fit) {
let ratio = size.width / size.height
let fontHeight = min(ceil(font.pointSize), size.height)
bounds.size.width = ratio * fontHeight
bounds.size.height = fontHeight
} else {
bounds.size = size
}
if options.contains(.center) {
bounds.origin.y = round((font.capHeight - bounds.height) / 2)
}
attachment.bounds = bounds
// non-breaking space so the color hack doesn't wrap
let attributedString = NSMutableAttributedString(string: "\u{00A0}")
attributedString.append(NSAttributedString(attachment: attachment))
// replace attributes to 0 size font so no actual space taken
attributes[.font] = UIFont.systemFont(ofSize: 0)
// override all attributes so color actually tints image
attributedString.addAttributes(
attributes,
range: NSRange(location: 0, length: attributedString.length)
)
return attributedString
}
}
// MARK: Hashable
public var hashValue: Int {
return storage
.combineHash(with: style)
}
// MARK: Equatable
public static func ==(lhs: StyledText, rhs: StyledText) -> Bool {
return lhs.storage == rhs.storage
&& lhs.style == rhs.style
}
}
| mit | 871b53a08305569b11801a4a644eef37 | 32.549669 | 105 | 0.571457 | 5.076152 | false | false | false | false |
kusl/swift | test/1_stdlib/SpriteKit.swift | 10 | 650 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// watchOS does not have SpriteKit.
// UNSUPPORTED: OS=watchos
import Foundation
import SpriteKit
// SKColor is NSColor on OS X and UIColor on iOS.
var r = CGFloat(0)
var g = CGFloat(0)
var b = CGFloat(0)
var a = CGFloat(0)
var color = SKColor.redColor()
color.getRed(&r, green:&g, blue:&b, alpha:&a)
print("color \(r) \(g) \(b) \(a)")
// CHECK: color 1.0 0.0 0.0 1.0
#if os(OSX)
func f(c: NSColor) {
print("colortastic")
}
#endif
#if os(iOS) || os(tvOS)
func f(c: UIColor) {
print("colortastic")
}
#endif
f(color)
// CHECK: colortastic
| apache-2.0 | f0a27a7ecba986981620d8efc2733a74 | 18.117647 | 49 | 0.661538 | 2.765957 | false | false | false | false |
mentrena/SyncKit | Example/Realm/SyncKitRealmExample/SyncKitRealmExample/Employee/Realm/RealmEmployeeWireframe.swift | 1 | 1235 | //
// RealmEmployeeWireframe.swift
// SyncKitRealmSwiftExample
//
// Created by Manuel Entrena on 26/06/2019.
// Copyright © 2019 Manuel Entrena. All rights reserved.
//
import UIKit
import Realm
class RealmEmployeeWireframe: EmployeeWireframe {
let navigationController: UINavigationController
let realm: RLMRealm
init(navigationController: UINavigationController, realm: RLMRealm) {
self.navigationController = navigationController
self.realm = realm
}
func show(company: Company, canEdit: Bool) {
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Employee") as! EmployeeViewController
let interactor = RealmEmployeeInteractor(realm: realm, company: company)
let presenter = DefaultEmployeePresenter(view: viewController,
company: company,
interactor: interactor,
canEdit: canEdit)
interactor.delegate = presenter
viewController.presenter = presenter
navigationController.pushViewController(viewController, animated: true)
}
}
| mit | e2d7ec33d7f7792d3f0f45c59f095250 | 37.5625 | 149 | 0.65235 | 5.87619 | false | false | false | false |
certificate-helper/TLS-Inspector | TLS Inspector/View Controllers/NoticeViewController.swift | 2 | 1248 | import UIKit
class NoticeViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var dismissButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
var forgroundColor = UIColor.black
if #available(iOS 13, *) {
forgroundColor = UIColor.label
}
let noticeText = NSMutableAttributedString(string: lang(key:"first_run_notice"),
attributes: [
NSAttributedString.Key.foregroundColor : forgroundColor,
NSAttributedString.Key.font : UIFont.systemFont(ofSize: 18.0)
])
let foundRange = noticeText.mutableString.range(of: lang(key: "Apple Support"))
noticeText.addAttribute(NSAttributedString.Key.link, value: "https://support.apple.com/", range: foundRange)
noticeText.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 18.0), range: foundRange)
self.textView.attributedText = noticeText
}
@IBAction func dismissButtonPressed(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
| gpl-3.0 | a7caba26dbafe8ff9254e15ad57e3881 | 42.034483 | 123 | 0.616186 | 5.243697 | false | false | false | false |
herveperoteau/TracktionProto1 | TracktionProto1/WatchConnectivityManager.swift | 1 | 2586 | //
// WatchConnectivityManager.swift
// TracktionProto1
//
// Created by Hervé PEROTEAU on 03/01/2016.
// Copyright © 2016 Hervé PEROTEAU. All rights reserved.
//
import Foundation
import WatchConnectivity
let NotificationWCsessionWatchStateDidChange = "NotificationWCsessionWatchStateDidChange"
let NotificationWCdidReceiveMessage = "NotificationWCdidReceiveMessage"
let NotificationWCdidReceiveApplicationContext = "NotificationWCdidReceiveApplicationContext"
let NotificationWCdidReceiveUserInfo = "NotificationWCdidReceiveUserInfo"
class WatchConnectivityManager: NSObject {
class var sharedInstance: WatchConnectivityManager {
struct Singleton {
static let instance = WatchConnectivityManager()
}
return Singleton.instance
}
var session: WCSession? {
didSet {
if let session = session {
session.delegate = self
session.activateSession()
}
}
}
func activateSession() {
if (WCSession.isSupported()) {
session = WCSession.defaultSession()
}
}
}
extension WatchConnectivityManager : WCSessionDelegate {
func sessionWatchStateDidChange(session: WCSession) {
print("sessionWatchStateDidChange session.paired=\(session.paired) ...")
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(NotificationWCsessionWatchStateDidChange,
object: session, userInfo: nil)
}
}
func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]){
print("didReceiveUserInfo ...")
let trackItem = TrackDataItem.fromDictionary(userInfo)
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().postNotificationName(NotificationWCdidReceiveUserInfo,
object: trackItem, userInfo: userInfo)
}
}
// func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
// print("didReceiveMessage ...")
// let trackItem = TrackDataItem.fromDictionary(message)
// dispatch_async(dispatch_get_main_queue()) {
// NSNotificationCenter.defaultCenter().postNotificationName(NotificationWCdidReceiveMessage,
// object: trackItem, userInfo: message)
// }
// }
//
// func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
// print("didReceiveApplicationContext ...")
// let trackItem = TrackDataItem.fromDictionary(applicationContext)
// dispatch_async(dispatch_get_main_queue()) {
// NSNotificationCenter.defaultCenter().postNotificationName(NotificationWCdidReceiveApplicationContext,
// object: trackItem, userInfo: applicationContext)
// }
// }
}
| mit | 64c996b1014269c80a85f8bbb3090f27 | 32.115385 | 108 | 0.772745 | 4.453448 | false | false | false | false |
YOCKOW/SwiftCGIResponder | Tests/CGIResponderTests/CGIResponderTests.swift | 1 | 6061 | /* *************************************************************************************************
CGIResponderTests.swift
© 2017-2021 YOCKOW.
Licensed under MIT License.
See "LICENSE.txt" for more information.
************************************************************************************************ */
import XCTest
@testable import CGIResponder
import Foundation
import TemporaryFile
let CRLF = "\u{0D}\u{0A}"
private extension CGIResponder {
mutating func _resetEnvironment(_ newEnvironment: Environment = .virtual(variables: .virtual([:]))) {
self._environment = newEnvironment
}
}
final class CGIResponderTests: XCTestCase {
func test_contentType() {
var responder = CGIResponder()
XCTAssertEqual(responder.contentType, ContentType(type:.application, subtype:"octet-stream"))
let text_utf8_contentType = ContentType(type:.text, subtype:"plain", parameters:["charset":"UTF-8"])!
responder.contentType = text_utf8_contentType
XCTAssertEqual(responder.contentType.type, .text)
XCTAssertEqual(responder.contentType.subtype, "plain")
XCTAssertEqual(responder.stringEncoding, .utf8)
}
func test_expectedStatus_ETag() {
let eTag: HTTPETag = .strong("ETAG")
var responder = CGIResponder()
let HTTP_IF_MATCH = "HTTP_IF_MATCH"
let HTTP_IF_NONE_MATCH = "HTTP_IF_NONE_MATCH"
responder.header.insert(HTTPHeaderField.eTag(eTag))
XCTAssertNil(responder.expectedStatus)
responder._resetEnvironment()
responder._environment.variables[HTTP_IF_MATCH] = #""ETAG""#
XCTAssertNil(responder.expectedStatus)
responder._environment.variables[HTTP_IF_MATCH] = #""OTHER""#
XCTAssertEqual(responder.expectedStatus, .preconditionFailed)
responder._resetEnvironment()
responder._environment.variables[HTTP_IF_NONE_MATCH] = #"W/"ETAG""#
XCTAssertEqual(responder.expectedStatus, .notModified)
responder._environment.variables[HTTP_IF_NONE_MATCH] = #"W/"OTHER""#
XCTAssertNil(responder.expectedStatus)
}
func test_expectedStatus_Date() {
let date_base = DateFormatter.rfc1123.date(from:"Mon, 03 Oct 1983 16:21:09 GMT")!
let date_old = date_base - 1000
let date_new = date_base + 1000
let HTTP_IF_UNMODIFIED_SINCE = "HTTP_IF_UNMODIFIED_SINCE"
let HTTP_IF_MODIFIED_SINCE = "HTTP_IF_MODIFIED_SINCE"
func date_string(_ date:Date) -> String {
return DateFormatter.rfc1123.string(from:date)
}
var responder = CGIResponder()
responder.header.insert(HTTPHeaderField.lastModified(date_base))
XCTAssertNil(responder.expectedStatus)
responder._resetEnvironment()
responder._environment.variables[HTTP_IF_UNMODIFIED_SINCE] = date_string(date_old)
XCTAssertEqual(responder.expectedStatus, .preconditionFailed)
responder._environment.variables[HTTP_IF_UNMODIFIED_SINCE] = date_string(date_base)
XCTAssertEqual(responder.expectedStatus, nil)
responder._environment.variables[HTTP_IF_UNMODIFIED_SINCE] = date_string(date_new)
XCTAssertEqual(responder.expectedStatus, nil)
responder._resetEnvironment()
responder._environment.variables[HTTP_IF_MODIFIED_SINCE] = date_string(date_old)
XCTAssertEqual(responder.expectedStatus, nil)
responder._environment.variables[HTTP_IF_MODIFIED_SINCE] = date_string(date_base)
XCTAssertEqual(responder.expectedStatus, .notModified)
responder._environment.variables[HTTP_IF_MODIFIED_SINCE] = date_string(date_new)
XCTAssertEqual(responder.expectedStatus, .notModified)
}
func test_response() throws {
var responder = CGIResponder()
func check(_ expectedOutput: String?,
expectedError: CGIResponderError? = nil,
file: StaticString = #file, line: UInt = #line) throws {
try TemporaryFile {
var output = $0
let respond: () throws -> Void = { try responder.respond(to: &output, ignoringError: { _ in false }) }
if let expectedError = expectedError {
do {
try respond()
XCTFail("No throw.", file: file, line: line)
} catch {
let error = try XCTUnwrap(error as? CGIResponderError)
XCTAssertEqual(error, expectedError, "Unexpected Error.", file: file, line: line)
XCTAssertNil(expectedOutput)
}
} else {
XCTAssertNoThrow(try respond(), file: file, line: line)
try output.seek(toOffset:0)
let data = output.availableData
XCTAssertEqual(expectedOutput, String(data:data, encoding:.utf8), file:file, line:line)
}
}
}
responder.status = .ok
responder.contentType = ContentType(type:.text, subtype:"plain")!
responder.stringEncoding = .utf8
responder.content = .init(string:"CGI")
try check(
"Status: 200 OK\(CRLF)" +
"Content-Type: text/plain; charset=utf-8\(CRLF)" +
"\(CRLF)" +
"CGI"
)
responder.stringEncoding = .ascii
try check(
nil,
expectedError: .stringEncodingInconsistency(actualEncoding: .utf8, specifiedEncoding: .ascii)
)
}
func test_fallback() throws {
struct _Fallback: CGIFallback {
var status: HTTPStatusCode
var fallbackContent: CGIContent
init(_ error: CGIError) {
self.status = error.status
self.fallbackContent = .string(error.localizedDescription, encoding: .utf8)
}
}
struct _Error: CGIError {
var status: HTTPStatusCode = .notFound
var localizedDescription: String = "Not Found."
}
let responder = CGIResponder(content: .lazy({ throw _Error() }))
var output = InMemoryFile()
responder.respond(to: &output, fallback: { _Fallback($0) })
try output.seek(toOffset: 0)
let outputString = try output.readToEnd().flatMap({ String(data: $0, encoding: .utf8) })
XCTAssertEqual(
outputString,
"Status: 404 Not Found\(CRLF)" +
"Content-Type: text/plain; charset=utf-8\(CRLF)" +
"\(CRLF)" +
"Not Found."
)
}
}
| mit | 2cdefa290ada2c58aac3babb312ce70e | 35.287425 | 110 | 0.65066 | 4.193772 | false | true | false | false |
pinterest/tulsi | src/TulsiGenerator/TulsiApplicationSupport.swift | 2 | 3997 | // Copyright 2018 The Tulsi Authors. 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
class ApplicationSupport {
private let fileManager: FileManager
let tulsiFolder: URL
init?(fileManager: FileManager = .default) {
// Fail if we are running in a test so that we don't install files to ~/Library/Application Support.
if ProcessInfo.processInfo.environment["TEST_SRCDIR"] != nil {
return nil
}
/// Fetching the appName this way will result in failure for our tests, which is intentional as
/// we don't want to install files to ~/Library/Application Support when testing.
guard let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String else { return nil }
guard let folder = fileManager.urls(for: .applicationSupportDirectory,
in: .userDomainMask).first else {
return nil
}
self.fileManager = fileManager
self.tulsiFolder = folder.appendingPathComponent(appName, isDirectory: true)
}
/// Copies Tulsi aspect files over to ~/Library/Application\ Support/Tulsi/<version>/Bazel and
/// returns the folder.
func copyTulsiAspectFiles(tulsiVersion: String) throws -> String {
let bundle = Bundle(for: type(of: self))
let aspectWorkspaceFile = bundle.url(forResource: "WORKSPACE", withExtension: nil)!
let aspectBuildFile = bundle.url(forResource: "BUILD", withExtension: nil)!
let tulsiFiles = bundle.urls(forResourcesWithExtension: nil, subdirectory: "tulsi")!
let bazelSubpath = (tulsiVersion as NSString).appendingPathComponent("Bazel")
let bazelPath = try installFiles([aspectWorkspaceFile, aspectBuildFile], toSubpath: bazelSubpath)
let tulsiAspectsSubpath = (bazelSubpath as NSString).appendingPathComponent("tulsi")
try installFiles(tulsiFiles, toSubpath: tulsiAspectsSubpath)
return bazelPath.path
}
@discardableResult
private func installFiles(_ files: [URL],
toSubpath subpath: String) throws -> URL {
let folder = tulsiFolder.appendingPathComponent(subpath, isDirectory: true)
try createDirectory(atURL: folder)
for sourceURL in files {
let filename = sourceURL.lastPathComponent
guard let targetURL = URL(string: filename, relativeTo: folder) else {
throw TulsiXcodeProjectGenerator.GeneratorError.serializationFailed(
"Unable to resolve URL for \(filename) in \(folder.path).")
}
do {
try copyFileIfNeeded(fromURL: sourceURL, toURL: targetURL)
}
}
return folder
}
private func copyFileIfNeeded(fromURL: URL, toURL: URL) throws {
do {
// Only over-write if needed.
if fileManager.fileExists(atPath: toURL.path) {
guard !fileManager.contentsEqual(atPath: fromURL.path, andPath: toURL.path) else {
return;
}
print("Overwriting \(toURL.path) as its contents changed.")
try fileManager.removeItem(at: toURL)
}
try fileManager.copyItem(at: fromURL, to: toURL)
}
}
private func createDirectory(atURL url: URL) throws {
var isDirectory: ObjCBool = false
let fileExists = fileManager.fileExists(atPath: url.path, isDirectory: &isDirectory)
guard !fileExists || !isDirectory.boolValue else { return }
try fileManager.createDirectory(at: url,
withIntermediateDirectories: true,
attributes: nil)
}
}
| apache-2.0 | 781d70160bfce1546ee2e5c2a3b35ec3 | 38.574257 | 104 | 0.69352 | 4.735782 | false | false | false | false |
allenu/SimpleLists | SimpleLists/Document.swift | 1 | 2039 | //
// Document.swift
// SimpleLists
//
// Created by Allen Ussher on 3/11/17.
// Copyright © 2017 Ussher Press. All rights reserved.
//
import Cocoa
class Document: NSDocument {
fileprivate var names: [String] = []
override init() {
super.init()
// Add your subclass-specific initialization here.
}
override class func autosavesInPlace() -> Bool {
return true
}
override func makeWindowControllers() {
// Returns the Storyboard that contains your Document window.
let storyboard = NSStoryboard(name: "Main", bundle: nil)
let windowController = storyboard.instantiateController(withIdentifier: "Document Window Controller") as! NSWindowController
self.addWindowController(windowController)
}
override func data(ofType typeName: String) throws -> Data {
let data = try JSONSerialization.data(withJSONObject: names, options: .prettyPrinted)
return data
}
override func read(from data: Data, ofType typeName: String) throws {
if let names = try JSONSerialization.jsonObject(with: data, options: .init(rawValue: 0)) as? [String] {
self.names = names
} else {
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
}
func touch() {
self.updateChangeCount(.changeDone)
}
}
//
// Public API
//
extension Document {
var numNames: Int {
return names.count
}
func name(atIndex index: Int) -> String? {
if index >= 0 && index < names.count {
return names[index]
} else {
return nil
}
}
func add(name: String) {
names.append(name)
touch()
}
func add(name: String, at index: Int) {
names.insert(name, at: index)
touch()
}
func remove(at index: Int) {
if index >= 0 && index < names.count {
names.remove(at: index)
touch()
}
}
}
| mit | 68e6bf24ae8d3e937fe30498be1ae7d4 | 24.475 | 132 | 0.589794 | 4.430435 | false | false | false | false |
liuxianghong/GreenBaby | 工程/greenbaby/greenbaby/ViewController/ImageSeeViewController.swift | 1 | 2269 | //
// ImageSeeViewController.swift
// greenbaby
//
// Created by 刘向宏 on 15/12/28.
// Copyright © 2015年 刘向宏. All rights reserved.
//
import UIKit
class ImageSeeViewController: UIViewController {
@IBOutlet weak var imageView : UIImageView!
@IBOutlet weak var downLoadButton : UIButton!
var image : UIImage!
var imageUrl : String!
var hud : MBProgressHUD!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if image != nil{
imageView.image = image
}
else if imageUrl != nil{
imageView.sd_setImageWithURL(NSURL(string: imageUrl))
}
else{
imageView.image = nil
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.dismissViewControllerAnimated(false) { () -> Void in
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .Default
}
@IBAction func downClick(sender : UIButton){
if imageView.image == nil{
return;
}
hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
UIImageWriteToSavedPhotosAlbum(imageView.image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject){
hud.mode = .Text
if error != nil {
hud.detailsLabelText = "保存失败,\(error!.localizedDescription)"
}
else{
hud.detailsLabelText = "保存成功"
}
hud.hide(true, afterDelay: 1.5)
}
/*
// 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.
}
*/
}
| lgpl-3.0 | 9be4195ddf2d016e1d67dc6b8e66c5b2 | 27.666667 | 114 | 0.620751 | 5.013453 | false | false | false | false |
Boilertalk/VaporFacebookBot | Sources/VaporFacebookBot/Send/FacebookSendAttachmentGenericTemplate.swift | 1 | 6699 | //
// FacebookSendAttachmentGenericTemplate.swift
// VaporFacebookBot
//
// Created by Koray Koska on 26/05/2017.
//
//
import Foundation
import Vapor
public final class FacebookSendAttachmentGenericTemplate: FacebookSendAttachmentTemplate {
public static var templateType: FacebookSendAttachmentTemplateType {
return .generic
}
public var sharable: Bool?
public var imageAspectRatio: FacebookSendAttachmentImageRatio?
public var elements: [FacebookSendAttachmentGenericElement]
public init(sharable: Bool? = nil, imageAspectRatio: FacebookSendAttachmentImageRatio? = nil, elements: [FacebookSendAttachmentGenericElement]) {
self.sharable = sharable
self.imageAspectRatio = imageAspectRatio
self.elements = elements
}
public convenience init(json: JSON) throws {
let sharable = json["sharable"]?.bool
let imageAspectRatioString = json["image_aspect_ratio"]?.string
let imageAspectRatio = imageAspectRatioString == nil ? nil : FacebookSendAttachmentImageRatio(rawValue: imageAspectRatioString!)
guard let elementsArray = json["elements"]?.array else {
throw Abort(.badRequest, metadata: "elements must be set for FacebookSendAttachmentGenericTemplate")
}
var elements = [FacebookSendAttachmentGenericElement]()
for e in elementsArray {
try elements.append(FacebookSendAttachmentGenericElement(json: e))
}
self.init(sharable: sharable, imageAspectRatio: imageAspectRatio, elements: elements)
}
public func makeJSON() throws -> JSON {
var json = JSON()
try json.set("template_type", type(of: self).templateType.rawValue)
if let sharable = sharable {
try json.set("sharable", sharable)
}
if let imageAspectRatio = imageAspectRatio {
try json.set("image_aspect_ratio", imageAspectRatio.rawValue)
}
try json.set("elements", elements.jsonArray())
return json
}
}
public enum FacebookSendAttachmentImageRatio: String {
case horizontal = "horizontal"
case square = "square"
}
public final class FacebookSendAttachmentGenericElement: JSONConvertible {
public var title: String
public var subtitle: String?
public var imageUrl: String?
public var defaultAction: FacebookSendAttachmentGenericDefaultAction?
public var buttons: [FacebookSendButton]?
public init(
title: String,
subtitle: String? = nil,
imageUrl: String? = nil,
defaultAction: FacebookSendAttachmentGenericDefaultAction? = nil,
buttons: [FacebookSendButton]? = nil) {
self.title = title
self.subtitle = subtitle
self.imageUrl = imageUrl
self.defaultAction = defaultAction
self.buttons = buttons
}
public convenience init(json: JSON) throws {
let title: String = try json.get("title")
let subtitle = json["subtitle"]?.string
let imageUrl = json["image_url"]?.string
var defaultAction: FacebookSendAttachmentGenericDefaultAction? = nil
if let j = json["default_action"] {
defaultAction = try FacebookSendAttachmentGenericDefaultAction(json: j)
}
var buttons: [FacebookSendButton]? = nil
if let buttonsArray = json["buttons"]?.array {
buttons = [FacebookSendButton]()
for b in buttonsArray {
try buttons?.append(FacebookSendButtonHolder(json: b).button)
}
}
self.init(title: title, subtitle: subtitle, imageUrl: imageUrl, defaultAction: defaultAction, buttons: buttons)
}
public func makeJSON() throws -> JSON {
var json = JSON()
try json.set("title", title)
if let subtitle = subtitle {
try json.set("subtitle", subtitle)
}
if let imageUrl = imageUrl {
try json.set("image_url", imageUrl)
}
if let defaultAction = defaultAction {
try json.set("default_action", defaultAction.makeJSON())
}
if let buttons = buttons {
var jArray = [JSON]()
for b in buttons {
jArray.append(try b.makeJSON())
}
try json.set("buttons", jArray)
}
return json
}
}
// TODO: The only difference between this class and FacebookSendURLButton is that this one does not support `title`. Maybe there is a better solution than duplicating it...
public final class FacebookSendAttachmentGenericDefaultAction: JSONConvertible {
public let type = "web_url"
public var url: String
public var webviewHeightRatio: FacebookSendWebviewHeightRatio?
public var messengerExtensions: Bool?
public var fallbackUrl: String?
public var webviewShareButton: String?
public init(
url: String,
webviewHeightRatio: FacebookSendWebviewHeightRatio? = nil,
messengerExtensions: Bool? = nil,
fallbackUrl: String? = nil,
webviewShareButton: String? = nil) {
self.url = url
self.webviewHeightRatio = webviewHeightRatio
self.messengerExtensions = messengerExtensions
self.fallbackUrl = fallbackUrl
self.webviewShareButton = webviewShareButton
}
public convenience init(json: JSON) throws {
let url: String = try json.get("url")
var webviewHeightRatio: FacebookSendWebviewHeightRatio? = nil
if let w = json["webview_height_ratio"]?.string {
webviewHeightRatio = FacebookSendWebviewHeightRatio(rawValue: w)
}
let messengerExtensions = json["messenger_extensions"]?.bool
let fallbackUrl = json["fallback_url"]?.string
let webviewShareButton = json["webview_share_button"]?.string
self.init(url: url, webviewHeightRatio: webviewHeightRatio, messengerExtensions: messengerExtensions, fallbackUrl: fallbackUrl, webviewShareButton: webviewShareButton)
}
public func makeJSON() throws -> JSON {
var json = JSON()
try json.set("type", type)
try json.set("url", url)
if let webviewHeightRatio = webviewHeightRatio {
try json.set("webview_height_ratio", webviewHeightRatio.rawValue)
}
if let messengerExtensions = messengerExtensions {
try json.set("messenger_extensions", messengerExtensions)
}
if let fallbackUrl = fallbackUrl {
try json.set("fallback_url", fallbackUrl)
}
if let webviewShareButton = webviewShareButton {
try json.set("webview_share_button", webviewShareButton)
}
return json
}
}
| mit | 8a4cece63c8baa76d3cfbc9844c76004 | 32.328358 | 175 | 0.659352 | 4.93299 | false | false | false | false |
kickstarter/ios-oss | KsApi/models/MessageSubject.swift | 2 | 885 | public enum MessageSubject {
case backing(Backing)
case messageThread(MessageThread)
case project(Project)
public var backing: Backing? {
if case let .backing(backing) = self {
return backing
}
return nil
}
public var messageThread: MessageThread? {
if case let .messageThread(messageThread) = self {
return messageThread
}
return nil
}
public var project: Project? {
if case let .project(project) = self {
return project
}
return nil
}
}
extension MessageSubject: Equatable {}
public func == (lhs: MessageSubject, rhs: MessageSubject) -> Bool {
switch (lhs, rhs) {
case let (.backing(lhs), .backing(rhs)):
return lhs == rhs
case let (.messageThread(lhs), .messageThread(rhs)):
return lhs == rhs
case let (.project(lhs), .project(rhs)):
return lhs == rhs
default:
return false
}
}
| apache-2.0 | 70f20ee09ac04b54aed51dc54c2e7322 | 21.125 | 67 | 0.649718 | 3.96861 | false | false | false | false |
shoheiyokoyama/SYBlinkAnimationKit | Example/SYBlinkAnimationKit/TextFieldViewController.swift | 2 | 1964 | //
// TextFieldViewController.swift
// SYBlinkAnimationKit
//
// Created by Shoehi Yokoyama on 2015/12/13.
// Copyright © 2015年 CocoaPods. All rights reserved.
//
import UIKit
import SYBlinkAnimationKit
class TextFieldViewController: UIViewController {
@IBOutlet private weak var borderTextField: SYTextField!
@IBOutlet private weak var border2TextField: SYTextField!
@IBOutlet private weak var backgrondTextField: SYTextField!
@IBOutlet private weak var rippleTextField: SYTextField!
override func viewDidLoad() {
super.viewDidLoad()
configure()
}
private func configure() {
self.view.backgroundColor = .white
self.navigationItem.title = "SYTextField"
borderTextField.placeholder = "Border Animation"
borderTextField.delegate = self
borderTextField.startAnimating()
view.addSubview(borderTextField)
border2TextField.placeholder = "BorderWithShadow Animation"
border2TextField.delegate = self
border2TextField.animationType = .borderWithShadow
border2TextField.backgroundColor = .clear
border2TextField.startAnimating()
view.addSubview(border2TextField)
backgrondTextField.placeholder = "Background Animation"
backgrondTextField.delegate = self
backgrondTextField.animationType = .background
backgrondTextField.startAnimating()
view.addSubview(backgrondTextField)
rippleTextField.placeholder = "Ripple Animation"
rippleTextField.delegate = self
rippleTextField.animationType = .ripple
rippleTextField.startAnimating()
view.addSubview(rippleTextField)
}
}
//MARK: - UITextFieldDelegate
extension TextFieldViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | c19735c99b162d21cb219711e3b36237 | 31.147541 | 67 | 0.702703 | 5.080311 | false | false | false | false |
castial/Quick-Start-iOS | Quick-Start-iOS/Controllers/Location/Protocol/EmptyPresenter.swift | 1 | 2128 | //
// EmptyPresenter.swift
// Quick-Start-iOS
//
// Created by work on 2016/12/10.
// Copyright © 2016年 hyyy. All rights reserved.
//
import UIKit
struct EmptyOptions {
let message: String
let messageFont: UIFont
let messageColor: UIColor
let backgroundColor: UIColor
init(message: String = "暂无数据", messageFont: UIFont = UIFont.systemFont(ofSize: 16), messageColor: UIColor = UIColor.black, backgroundColor: UIColor = UIColor.white) {
self.message = message
self.messageFont = messageFont
self.messageColor = messageColor
self.backgroundColor = backgroundColor
}
}
protocol EmptyPresenter {
func presentEmpty(emptyOptions: EmptyOptions)
}
extension EmptyPresenter where Self: UIView {
func presentEmpty(emptyOptions: EmptyOptions = EmptyOptions()) {
let emptyView = defaultEmptyView(emptyOptions: emptyOptions)
self.addSubview(emptyView)
}
}
extension EmptyPresenter where Self: UIViewController {
func presentEmpty(emptyOptions: EmptyOptions = EmptyOptions()) {
let emptyView = defaultEmptyView(emptyOptions: emptyOptions)
self.view.addSubview(emptyView)
}
}
extension EmptyPresenter {
// default empty view
fileprivate func defaultEmptyView(emptyOptions: EmptyOptions) -> UIView {
let emptyView = UIView (frame: CGRect (x: 0,
y: 0,
width: UIScreen.main.bounds.size.width,
height: UIScreen.main.bounds.size.height))
emptyView.backgroundColor = emptyOptions.backgroundColor
// add a message label
let messageLabel = UILabel()
messageLabel.text = emptyOptions.message
messageLabel.font = emptyOptions.messageFont
messageLabel.textColor = emptyOptions.messageColor
messageLabel.textAlignment = .center
messageLabel.sizeToFit()
messageLabel.center = emptyView.center
emptyView.addSubview(messageLabel)
return emptyView
}
}
| mit | 44905fdce059992566e6fe41d1347514 | 31.569231 | 170 | 0.651393 | 5.076739 | false | false | false | false |
son11592/STNavigationViewController | Example/STNavigationViewController/HideNavigationViewController.swift | 1 | 2009 | //
// HideNavigationViewController.swift
// STNavigationViewController
//
// Created by Sơn Thái on 7/17/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
class HideNavigationViewController: ViewController {
internal let navigation = NavigationBar()
internal let titleLb = UILabel()
internal let segment = UISegmentedControl(items: ["0.23s", "3s", "5s"])
override func commonInit() {
super.commonInit()
self.contentView.backgroundColor = UIColor.red.withAlphaComponent(0.5)
}
override func loadView() {
super.loadView()
let mainBounds = UIScreen.main.bounds
self.navigation.setTitle("Hide Navigation View Controller")
self.navigationBar = self.navigation
self.titleLb.frame = CGRect(x: 15, y: 90, width: mainBounds.width - 30, height: 25)
self.titleLb.textColor = UIColor.black
self.titleLb.textAlignment = .center
self.titleLb.text = "Select duration for pop animation"
self.segment.frame = CGRect(x: 40, y: self.titleLb.frame.maxY + 20, width: mainBounds.width - 80, height: 40)
self.segment.selectedSegmentIndex = 0
self.contentView.addSubview(self.titleLb)
self.contentView.addSubview(self.segment)
self.contentView.addSubview(self.navigation)
}
override func getPopAnimatedTransitioning(from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning {
let animator = HideNavigationBarPopAnimator()
animator.duration = self.getDuration(from: self.segment)
return animator
}
override func getPopInteractionAnimatedTransitioning(from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning {
return HideNavigationBarPopAnimator()
}
private func getDuration(from segment: UISegmentedControl) -> TimeInterval {
switch segment.selectedSegmentIndex {
case 1:
return 3
case 2:
return 5
default:
return 0.23
}
}
}
| mit | bd3119b91583aae4a0a5960ba783277e | 30.84127 | 155 | 0.718843 | 4.487696 | false | false | false | false |
d4rkl0rd3r3b05/Data_Structure_And_Algorithm | LeetCode_AddTwoLinkedList.swift | 1 | 2828 | import Foundation
public class ListNode<T> : NSObject{
var nodeValue : T
var next : ListNode?
init(value : T) {
self.nodeValue = value
}
override public var description: String {
get{
return "\(self.nodeValue)->" + (self.next != nil ? self.next!.description : "NULL")
}
}
}
public class LinkedList<T> {
public var sourceElement : ListNode<T>?
public init(array : [T]) {
var previosNode : ListNode<T>?
for currentElement in array {
if self.sourceElement == nil {
self.sourceElement = ListNode(value: currentElement)
previosNode = self.sourceElement
}
else{
previosNode?.next = ListNode(value: currentElement)
previosNode = previosNode?.next
}
}
}
public static func addTwoList(firstList : ListNode<Int>?, secondList : ListNode<Int>?) -> ListNode<Int>? {
var solutionList : ListNode<Int>?
guard firstList != nil || secondList != nil else{
return nil
}
if firstList != nil {
if secondList != nil {
let sum = (firstList!.nodeValue + secondList!.nodeValue) % 10
let carryBalance = (firstList!.nodeValue + secondList!.nodeValue) / 10
var nextNode = secondList!.next
if carryBalance > 0 {
if nextNode == nil {
nextNode = ListNode(value: carryBalance)
}else{
nextNode!.nodeValue += carryBalance
}
}
solutionList = ListNode(value: sum)
solutionList!.next = addTwoList(firstList: firstList!.next, secondList: nextNode)
}
else {
let sum = firstList!.nodeValue % 10
let carryBalance = firstList!.nodeValue / 10
var nextNode : ListNode<Int>?
if carryBalance > 0 {
nextNode = ListNode(value: carryBalance)
}
solutionList = ListNode(value: sum)
solutionList!.next = addTwoList(firstList: firstList!.next, secondList: nextNode)
}
}else {
let sum = secondList!.nodeValue % 10
let carryBalance = secondList!.nodeValue / 10
var nextNode : ListNode<Int>?
if carryBalance > 0 {
nextNode = ListNode(value: carryBalance)
}
solutionList = ListNode(value: sum)
solutionList!.next = addTwoList(firstList: nextNode, secondList: secondList!.next)
}
return solutionList
}
}
| mit | e98ce859b113bceff4b646ed1eb58094 | 32.666667 | 110 | 0.50884 | 5.086331 | false | false | false | false |
hsuanan/Mr-Ride-iOS | Mr-Ride/View/HistoryCustomHeaderCell.swift | 1 | 1042 | //
// HistoryCustomHeaderCell.swift
// Mr-Ride
//
// Created by Hsin An Hsu on 6/14/16.
// Copyright © 2016 AppWorks School HsinAn Hsu. All rights reserved.
//
import UIKit
class HistoryCustomHeaderCell: UITableViewCell {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var headerView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.clearColor()
headerView.backgroundColor = UIColor.whiteColor()
headerView.layer.cornerRadius = 2
dateLabel.textColor = UIColor.mrDarkSlateBlueColor()
letterSpacing(dateLabel.text!, letterSpacing: -0.3, label: dateLabel)
}
func letterSpacing(text: String, letterSpacing: Double, label: UILabel){
let attributedText = NSMutableAttributedString (string: text)
attributedText.addAttribute(NSKernAttributeName, value: letterSpacing, range: NSMakeRange(0, attributedText.length))
label.attributedText = attributedText
}
}
| mit | cd80ca2bbdcb4f019ec20ea74de5d27c | 27.916667 | 124 | 0.685879 | 4.864486 | false | false | false | false |
eugenegolovanov/SocketChat | SocketChat/SocketIOManager.swift | 1 | 4154 | //
// SocketIOManager.swift
// SocketChat
//
// Created by eugene golovanov on 6/15/16.
// Copyright © 2016 AppCoda. All rights reserved.
//
import UIKit
class SocketIOManager: NSObject {
//--------------------------------------------------------------------------------------------------------------------------
//MARK: - Properties
static let sharedInstance = SocketIOManager()
// var socket: SocketIOClient = SocketIOClient(socketURL: NSURL(string: "http://192.168.0.4:3000")!)//HOME
var socket: SocketIOClient = SocketIOClient(socketURL: NSURL(string: "http://192.168.10.234:3000")!)//WORK
//--------------------------------------------------------------------------------------------------------------------------
//MARK: - Init
override init() {
super.init()
}
//--------------------------------------------------------------------------------------------------------------------------
//MARK: - Connection
func establishConnection() {
socket.connect()
}
func closeConnection() {
socket.disconnect()
}
//--------------------------------------------------------------------------------------------------------------------------
//MARK: - Operations
func connectToServerWithNickname(nickname: String, completionHandler: (userList: [[String: AnyObject]]!) -> Void) {
socket.emit("connectUser", nickname)
socket.on("userList") { ( dataArray, ack) -> Void in
completionHandler(userList: dataArray[0] as! [[String: AnyObject]])
}
listenForOtherMessages()
}
func exitChatWithNickname(nickname: String, completionHandler: () -> Void) {
socket.emit("exitUser", nickname)
completionHandler()
}
func sendMessage(message: String, withNickname nickname: String) {
socket.emit("chatMessage", nickname, message)
}
func getChatMessage(completionHandler: (messageInfo: [String: AnyObject]) -> Void) {
socket.on("newChatMessage") { (dataArray, socketAck) -> Void in
var messageDictionary = [String: AnyObject]()
messageDictionary["nickname"] = dataArray[0] as! String
messageDictionary["message"] = dataArray[1] as! String
messageDictionary["date"] = dataArray[2] as! String
completionHandler(messageInfo: messageDictionary)
}
}
//--------------------------------------------------------------------------------------------------------------------------
//MARK: - Listen users connection disconnection and typing
private func listenForOtherMessages() {
//send the respective information using the 'object' property of the notification
socket.on("userConnectUpdate") { (dataArray, socketAck) -> Void in
//the server returns a dictionary that contains all the new user information
NSNotificationCenter.defaultCenter().postNotificationName("userWasConnectedNotification", object: dataArray[0] as! [String: AnyObject])
}
socket.on("userExitUpdate") { (dataArray, socketAck) -> Void in
//the server returns just the nickname of the user that left the chat
NSNotificationCenter.defaultCenter().postNotificationName("userWasDisconnectedNotification", object: dataArray[0] as! String)
}
socket.on("userTypingUpdate") { (dataArray, socketAck) -> Void in
NSNotificationCenter.defaultCenter().postNotificationName("userTypingNotification", object: dataArray[0] as? [String: AnyObject])
}
}
//--------------------------------------------------------------------------------------------------------------------------
//MARK: - Typing
func sendStartTypingMessage(nickname: String) {
socket.emit("startType", nickname)
}
func sendStopTypingMessage(nickname: String) {
socket.emit("stopType", nickname)
}
}
| unlicense | 0d09a21a71596b5f00e74d07672a2e1d | 32.491935 | 147 | 0.502528 | 5.924394 | false | false | false | false |
Hansoncoder/Metal | MetalDemo/MetalCube/Cube.swift | 1 | 1394 | //
// Cube.swift
// MetalDemo
//
// Created by Hanson on 16/6/3.
// Copyright © 2016年 Hanson. All rights reserved.
//
import Foundation
import Metal
class Cube: Node {
init(device: MTLDevice) {
// 顶点数据
let A = Vertex(x: -1.0, y: 1.0, z: 1.0, w: 1.0, r: 1.0, g: 0.0, b: 0.0, a: 1.0)
let B = Vertex(x: -1.0, y: -1.0, z: 1.0, w: 1.0, r: 0.5, g: 1.0, b: 0.5, a: 1.0)
let C = Vertex(x: 1.0, y: -1.0, z: 1.0, w: 1.0, r: 0.0, g: 0.0, b: 1.0, a: 1.0)
let D = Vertex(x: 1.0, y: 1.0, z: 1.0, w: 1.0, r: 0.0, g: 0.0, b: 0.0, a: 1.0)
let Q = Vertex(x: -1.0, y: 1.0, z: -1.0, w: 1.0, r: 0.0, g: 1.0, b: 1.0, a: 1.0)
let R = Vertex(x: 1.0, y: 1.0, z: -1.0, w: 1.0, r: 1.0, g: 1.0, b: 0.0, a: 1.0)
let S = Vertex(x: -1.0, y: -1.0, z: -1.0, w: 1.0, r: 1.0, g: 0.0, b: 1.0, a: 1.0)
let T = Vertex(x: 1.0, y: -1.0, z: -1.0, w: 1.0, r: 0.0, g: 0.0, b: 0.0, a: 1.0)
let vertexArr = [A, B, C, A, C, D, // 前面
R, T, S, Q, R, S, // 后面
Q, S, B, Q, B, A, // 左面
D, C, T, D, T, R, // 右面
Q, A, D, Q, D, R, // 上面
B, S, T, B, T, C] // 下面
// 创建节点
super.init(name: "Cube", vertices: vertexArr, device: device)
}
} | apache-2.0 | 36d8fdfa8644a6568b8730fe88c9e2b6 | 38.764706 | 89 | 0.38564 | 2.043873 | false | false | false | false |
dvidlui/iOS8-day-by-day | 25-notification-actions/NotifyTimely/NotifyTimely/TimerNotifications.swift | 1 | 4728 | //
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
let restartTimerActionString = "RestartTimer"
let editTimerActionString = "EditTimer"
let snoozeTimerActionString = "SnoozeTimer"
let timerFiredCategoryString = "TimerFiredCategory"
protocol TimerNotificationManagerDelegate {
func timerStatusChanged()
func presentEditOptions()
}
class TimerNotificationManager: Printable {
let snoozeDuration: Float = 5.0
var delegate: TimerNotificationManagerDelegate?
var timerRunning: Bool {
didSet {
delegate?.timerStatusChanged()
}
}
var timerDuration: Float {
didSet {
delegate?.timerStatusChanged()
}
}
var description: String {
if timerRunning {
return "\(timerDuration)s timer, running"
} else {
return "\(timerDuration)s timer, stopped"
}
}
init() {
timerRunning = false
timerDuration = 30.0
registerForNotifications()
checkForPreExistingTimer()
}
func startTimer() {
if !timerRunning {
// Create the notification...
scheduleTimerWithOffset(timerDuration)
}
}
func stopTimer() {
if timerRunning {
// Kill all local notifications
UIApplication.sharedApplication().cancelAllLocalNotifications()
timerRunning = false
}
}
func restartTimer() {
stopTimer()
startTimer()
}
func timerFired() {
timerRunning = false
}
func handleActionWithIdentifier(identifier: String?) {
timerRunning = false
if let identifier = identifier {
switch identifier {
case restartTimerActionString:
restartTimer()
case snoozeTimerActionString:
scheduleTimerWithOffset(snoozeDuration)
case editTimerActionString:
delegate?.presentEditOptions()
default:
println("Unrecognised Identifier")
}
}
}
// MARK: - Utility methods
private func checkForPreExistingTimer() {
if UIApplication.sharedApplication().scheduledLocalNotifications.count > 0 {
timerRunning = true
}
}
private func scheduleTimerWithOffset(fireOffset: Float) {
let timer = createTimer(fireOffset)
UIApplication.sharedApplication().scheduleLocalNotification(timer)
timerRunning = true
}
private func createTimer(fireOffset: Float) -> UILocalNotification {
let notification = UILocalNotification()
notification.category = timerFiredCategoryString
notification.fireDate = NSDate(timeIntervalSinceNow: NSTimeInterval(fireOffset))
notification.alertBody = "Your time is up!"
return notification
}
private func registerForNotifications() {
let requestedTypes = UIUserNotificationType.Alert | .Sound
let categories = NSSet(object: timerFiredNotificationCategory())
let settingsRequest = UIUserNotificationSettings(forTypes: requestedTypes, categories: categories)
UIApplication.sharedApplication().registerUserNotificationSettings(settingsRequest)
}
private func timerFiredNotificationCategory() -> UIUserNotificationCategory {
let restartAction = UIMutableUserNotificationAction()
restartAction.identifier = restartTimerActionString
restartAction.destructive = false
restartAction.title = "Restart"
restartAction.activationMode = .Background
restartAction.authenticationRequired = false
let editAction = UIMutableUserNotificationAction()
editAction.identifier = editTimerActionString
editAction.destructive = true
editAction.title = "Edit"
editAction.activationMode = .Foreground
editAction.authenticationRequired = true
let snoozeAction = UIMutableUserNotificationAction()
snoozeAction.identifier = snoozeTimerActionString
snoozeAction.destructive = false
snoozeAction.title = "Snooze"
snoozeAction.activationMode = .Background
snoozeAction.authenticationRequired = false
let category = UIMutableUserNotificationCategory()
category.identifier = timerFiredCategoryString
category.setActions([restartAction, snoozeAction], forContext: .Minimal)
category.setActions([restartAction, snoozeAction, editAction], forContext: .Default)
return category
}
}
| apache-2.0 | 1e820305210c0712554d6462c2ed3af6 | 28.735849 | 102 | 0.730541 | 5.253333 | false | false | false | false |
minikin/Algorithmics | Pods/Charts/Charts/Classes/Data/Implementations/Standard/ChartDataSet.swift | 3 | 11391 | //
// ChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class ChartDataSet: ChartBaseDataSet
{
public required init()
{
super.init()
_yVals = [ChartDataEntry]()
}
public override init(label: String?)
{
super.init(label: label)
_yVals = [ChartDataEntry]()
}
public init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(label: label)
_yVals = yVals == nil ? [ChartDataEntry]() : yVals
self.calcMinMax(start: _lastStart, end: _lastEnd)
}
public convenience init(yVals: [ChartDataEntry]?)
{
self.init(yVals: yVals, label: "DataSet")
}
// MARK: - Data functions and accessors
internal var _yVals: [ChartDataEntry]!
internal var _yMax = Double(0.0)
internal var _yMin = Double(0.0)
/// the last start value used for calcMinMax
internal var _lastStart: Int = 0
/// the last end value used for calcMinMax
internal var _lastEnd: Int = 0
public var yVals: [ChartDataEntry] { return _yVals }
/// Use this method to tell the data set that the underlying data has changed
public override func notifyDataSetChanged()
{
calcMinMax(start: _lastStart, end: _lastEnd)
}
public override func calcMinMax(start start: Int, end: Int)
{
let yValCount = _yVals.count
if yValCount == 0
{
return
}
var endValue : Int
if end == 0 || end >= yValCount
{
endValue = yValCount - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = endValue
_yMin = DBL_MAX
_yMax = -DBL_MAX
for (var i = start; i <= endValue; i++)
{
let e = _yVals[i]
if (!e.value.isNaN)
{
if (e.value < _yMin)
{
_yMin = e.value
}
if (e.value > _yMax)
{
_yMax = e.value
}
}
}
if (_yMin == DBL_MAX)
{
_yMin = 0.0
_yMax = 0.0
}
}
/// - returns: the minimum y-value this DataSet holds
public override var yMin: Double { return _yMin }
/// - returns: the maximum y-value this DataSet holds
public override var yMax: Double { return _yMax }
/// - returns: the number of y-values this DataSet represents
public override var entryCount: Int { return _yVals?.count ?? 0 }
/// - returns: the value of the Entry object at the given xIndex. Returns NaN if no value is at the given x-index.
public override func yValForXIndex(x: Int) -> Double
{
let e = self.entryForXIndex(x)
if (e !== nil && e!.xIndex == x) { return e!.value }
else { return Double.NaN }
}
/// - returns: the entry object found at the given index (not x-index!)
/// - throws: out of bounds
/// if `i` is out of bounds, it may throw an out-of-bounds exception
public override func entryForIndex(i: Int) -> ChartDataEntry?
{
return _yVals[i]
}
/// - returns: the first Entry object found at the given xIndex with binary search.
/// If the no Entry at the specifed x-index is found, this method returns the Entry at the closest x-index.
/// nil if no Entry object at that index.
public override func entryForXIndex(x: Int) -> ChartDataEntry?
{
let index = self.entryIndex(xIndex: x)
if (index > -1)
{
return _yVals[index]
}
return nil
}
public func entriesForXIndex(x: Int) -> [ChartDataEntry]
{
var entries = [ChartDataEntry]()
var low = 0
var high = _yVals.count - 1
while (low <= high)
{
var m = Int((high + low) / 2)
var entry = _yVals[m]
if (x == entry.xIndex)
{
while (m > 0 && _yVals[m - 1].xIndex == x)
{
m--
}
high = _yVals.count
for (; m < high; m++)
{
entry = _yVals[m]
if (entry.xIndex == x)
{
entries.append(entry)
}
else
{
break
}
}
}
if (x > _yVals[m].xIndex)
{
low = m + 1
}
else
{
high = m - 1
}
}
return entries
}
/// - returns: the array-index of the specified entry
///
/// - parameter x: x-index of the entry to search for
public override func entryIndex(xIndex x: Int) -> Int
{
var low = 0
var high = _yVals.count - 1
var closest = -1
while (low <= high)
{
var m = (high + low) / 2
let entry = _yVals[m]
if (x == entry.xIndex)
{
while (m > 0 && _yVals[m - 1].xIndex == x)
{
m--
}
return m
}
if (x > entry.xIndex)
{
low = m + 1
}
else
{
high = m - 1
}
closest = m
}
return closest
}
/// - returns: the array-index of the specified entry
///
/// - parameter e: the entry to search for
public override func entryIndex(entry e: ChartDataEntry) -> Int
{
for (var i = 0; i < _yVals.count; i++)
{
if _yVals[i] === e
{
return i
}
}
return -1
}
/// Adds an Entry to the DataSet dynamically.
/// Entries are added to the end of the list.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
/// - parameter e: the entry to add
/// - returns: true
public override func addEntry(e: ChartDataEntry) -> Bool
{
let val = e.value
if (_yVals == nil)
{
_yVals = [ChartDataEntry]()
}
if (_yVals.count == 0)
{
_yMax = val
_yMin = val
}
else
{
if (_yMax < val)
{
_yMax = val
}
if (_yMin > val)
{
_yMin = val
}
}
_yVals.append(e)
return true
}
/// Adds an Entry to the DataSet dynamically.
/// Entries are added to their appropriate index respective to it's x-index.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
/// - parameter e: the entry to add
/// - returns: true
public override func addEntryOrdered(e: ChartDataEntry) -> Bool
{
let val = e.value
if (_yVals == nil)
{
_yVals = [ChartDataEntry]()
}
if (_yVals.count == 0)
{
_yMax = val
_yMin = val
}
else
{
if (_yMax < val)
{
_yMax = val
}
if (_yMin > val)
{
_yMin = val
}
}
if _yVals.last?.xIndex > e.xIndex
{
var closestIndex = entryIndex(xIndex: e.xIndex)
if _yVals[closestIndex].xIndex < e.xIndex
{
closestIndex++
}
_yVals.insert(e, atIndex: closestIndex)
return true
}
_yVals.append(e)
return true
}
/// Removes an Entry from the DataSet dynamically.
/// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum.
/// - parameter entry: the entry to remove
/// - returns: true if the entry was removed successfully, else if the entry does not exist
public override func removeEntry(entry: ChartDataEntry) -> Bool
{
var removed = false
for (var i = 0; i < _yVals.count; i++)
{
if (_yVals[i] === entry)
{
_yVals.removeAtIndex(i)
removed = true
break
}
}
if (removed)
{
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed
}
/// Removes the first Entry (at index 0) of this DataSet from the entries array.
///
/// - returns: true if successful, false if not.
public override func removeFirst() -> Bool
{
let entry: ChartDataEntry? = _yVals.isEmpty ? nil : _yVals.removeFirst()
let removed = entry != nil
if (removed)
{
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed;
}
/// Removes the last Entry (at index size-1) of this DataSet from the entries array.
///
/// - returns: true if successful, false if not.
public override func removeLast() -> Bool
{
let entry: ChartDataEntry? = _yVals.isEmpty ? nil : _yVals.removeLast()
let removed = entry != nil
if (removed)
{
calcMinMax(start: _lastStart, end: _lastEnd)
}
return removed;
}
/// Checks if this DataSet contains the specified Entry.
/// - returns: true if contains the entry, false if not.
public override func contains(e: ChartDataEntry) -> Bool
{
for entry in _yVals
{
if (entry.isEqual(e))
{
return true
}
}
return false
}
/// Removes all values from this DataSet and recalculates min and max value.
public override func clear()
{
_yVals.removeAll(keepCapacity: true)
_lastStart = 0
_lastEnd = 0
notifyDataSetChanged()
}
// MARK: - Data functions and accessors
/// - returns: the number of entries this DataSet holds.
public var valueCount: Int { return _yVals.count }
// MARK: - NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! ChartDataSet
copy._yVals = _yVals
copy._yMax = _yMax
copy._yMin = _yMin
copy._lastStart = _lastStart
copy._lastEnd = _lastEnd
return copy
}
}
| mit | fac62525af4c97138ce38614e54d18e5 | 24.426339 | 118 | 0.467299 | 4.796211 | false | false | false | false |
xedin/swift | test/TBD/enum.swift | 2 | 3531 | // Swift 3:
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -O
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -O
// Swift 4:
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4 -O
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4 -O
// With -enable-testing:
// Swift 3:
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing -O
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -enable-testing -O
// Swift 4:
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4 -enable-testing
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4 -enable-testing
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4 -enable-testing -O
// RUN: %target-swift-frontend -enable-library-evolution -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=missing %s -swift-version 4 -enable-testing -O
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -typecheck -parse-as-library -module-name test %s -emit-tbd -emit-tbd-path %t/typecheck.tbd
// RUN: %target-swift-frontend -emit-ir -parse-as-library -module-name test %s -emit-tbd -emit-tbd-path %t/emit-ir.tbd
// RUN: diff -u %t/typecheck.tbd %t/emit-ir.tbd
public protocol P {}
public class C {
}
public enum SinglePayload: P {
case A
case B(C)
case D
}
public enum MultiPayload {
case A
case B(C)
case D(C)
public func method() {}
}
public enum AutomaticEquatableHashable {
case a, b
}
public enum Synthesized: Equatable, Hashable {
case a(AutomaticEquatableHashable), b
}
public enum ConditionalSynthesized<T> {
case a(T), b
}
#if swift(>=4)
extension ConditionalSynthesized: Equatable where T: Equatable {}
extension ConditionalSynthesized: Hashable where T: Hashable {}
#endif
public enum ZeroCases {}
public enum OneCase {
case a
}
public enum OneCasePayload {
case a(C)
}
| apache-2.0 | fe8778ca7310fc82afb59d3ebc73d1b1 | 47.369863 | 185 | 0.735202 | 3.046592 | false | true | false | false |
zirinisp/SlackKit | SlackKit/Sources/Bot.swift | 1 | 1684 | //
// Bot.swift
//
// Copyright © 2016 Peter Zignego. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public struct Bot {
public let id: String?
internal(set) public var botToken: String?
internal(set) public var name: String?
internal(set) public var icons: [String: Any]?
internal init(bot: [String: Any]?) {
id = bot?["id"] as? String
name = bot?["name"] as? String
icons = bot?["icons"] as? [String: Any]
}
internal init(botUser: [String: Any]?) {
id = botUser?["bot_user_id"] as? String
botToken = botUser?["bot_access_token"] as? String
}
}
| mit | 10326c03b958f76d61accd8101e737b2 | 40.04878 | 80 | 0.700535 | 4.25 | false | false | false | false |
groue/GRDB.swift | GRDB/QueryInterface/FTS3+QueryInterface.swift | 1 | 1962 | extension TableRequest where Self: FilteredRequest {
// MARK: Full Text Search
/// Filters rows that match an ``FTS3`` full-text pattern.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM book WHERE book MATCH 'sqlite OR database'
/// let pattern = FTS3Pattern(matchingAnyTokenIn: "SQLite Database")
/// let request = Book.all().matching(pattern)
/// ```
///
/// If `pattern` is nil, the returned request fetches no row.
///
/// - parameter pattern: An ``FTS3Pattern``.
public func matching(_ pattern: FTS3Pattern?) -> Self {
guard let pattern else {
return none()
}
let alias = TableAlias()
let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression)
return self.aliased(alias).filter(matchExpression)
}
}
extension TableRecord {
// MARK: Full Text Search
/// Returns a request filtered on records that match an ``FTS3``
/// full-text pattern.
///
/// For example:
///
/// ```swift
/// // SELECT * FROM book WHERE book MATCH 'sqlite OR database'
/// let pattern = FTS3Pattern(matchingAnyTokenIn: "SQLite Database")
/// let request = Book.matching(pattern)
/// ```
///
/// If `pattern` is nil, the returned request fetches no row.
///
/// - parameter pattern: An ``FTS3Pattern``.
public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self> {
all().matching(pattern)
}
}
extension ColumnExpression {
/// A matching SQL expression with the `MATCH` SQL operator.
///
/// // content MATCH '...'
/// Column("content").match(pattern)
///
/// If the search pattern is nil, SQLite will evaluate the expression
/// to false.
public func match(_ pattern: FTS3Pattern?) -> SQLExpression {
.binary(.match, sqlExpression, pattern?.sqlExpression ?? .null)
}
}
| mit | b6b72c08666f5c4cca5df7d9a4f98bf1 | 30.645161 | 89 | 0.600408 | 4.438914 | false | false | false | false |
SteveClement/Swifter | Swifter/SwifterAuth.swift | 1 | 8182 | //
// SwifterAuth.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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
#if os(iOS)
import UIKit
#else
import AppKit
#endif
public extension Swifter {
public typealias TokenSuccessHandler = (accessToken: SwifterCredential.OAuthAccessToken?, response: NSURLResponse) -> Void
public func authorizeWithCallbackURL(callbackURL: NSURL, success: TokenSuccessHandler?, failure: ((error: NSError) -> Void)? = nil, openQueryURL: ((url: NSURL) -> Void)?, closeQueryURL:(() -> Void)? = nil) {
self.postOAuthRequestTokenWithCallbackURL(callbackURL, success: {
token, response in
var requestToken = token!
NSNotificationCenter.defaultCenter().addObserverForName(CallbackNotification.notificationName, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock:{
notification in
NSNotificationCenter.defaultCenter().removeObserver(self)
closeQueryURL?()
let url = notification.userInfo![CallbackNotification.optionsURLKey] as! NSURL
let parameters = url.query!.parametersFromQueryString()
requestToken.verifier = parameters["oauth_verifier"]
self.postOAuthAccessTokenWithRequestToken(requestToken, success: {
accessToken, response in
self.client.credential = SwifterCredential(accessToken: accessToken!)
success?(accessToken: accessToken!, response: response)
}, failure: failure)
})
let authorizeURL = NSURL(string: "/oauth/authorize", relativeToURL: self.apiURL)
let queryURL = NSURL(string: authorizeURL!.absoluteString + "?oauth_token=\(token!.key)")
if openQueryURL != nil {
openQueryURL?(url: queryURL!)
} else {
#if os(iOS)
UIApplication.sharedApplication().openURL(queryURL!)
#else
NSWorkspace.sharedWorkspace().openURL(queryURL!)
#endif
}
}, failure: failure)
}
public class func handleOpenURL(url: NSURL) {
let notification = NSNotification(name: CallbackNotification.notificationName, object: nil,
userInfo: [CallbackNotification.optionsURLKey: url])
NSNotificationCenter.defaultCenter().postNotification(notification)
}
public func authorizeAppOnlyWithSuccess(success: TokenSuccessHandler?, failure: FailureHandler?) {
self.postOAuth2BearerTokenWithSuccess({
json, response in
if let tokenType = json["token_type"].string {
if tokenType == "bearer" {
let accessToken = json["access_token"].string
let credentialToken = SwifterCredential.OAuthAccessToken(key: accessToken!, secret: "")
self.client.credential = SwifterCredential(accessToken: credentialToken)
success?(accessToken: credentialToken, response: response)
}
else {
let error = NSError(domain: "Swifter", code: SwifterError.appOnlyAuthenticationErrorCode, userInfo: [NSLocalizedDescriptionKey: "Cannot find bearer token in server response"]);
failure?(error: error)
}
}
else if let errors = json["errors"].object {
let error = NSError(domain: SwifterError.domain, code: errors["code"]!.integer!, userInfo: [NSLocalizedDescriptionKey: errors["message"]!.string!]);
failure?(error: error)
}
else {
let error = NSError(domain: SwifterError.domain, code: SwifterError.appOnlyAuthenticationErrorCode, userInfo: [NSLocalizedDescriptionKey: "Cannot find JSON dictionary in response"]);
failure?(error: error)
}
}, failure: failure)
}
public func postOAuth2BearerTokenWithSuccess(success: JSONSuccessHandler?, failure: FailureHandler?) {
let path = "/oauth2/token"
var parameters = Dictionary<String, Any>()
parameters["grant_type"] = "client_credentials"
self.jsonRequestWithPath(path, baseURL: self.apiURL, method: "POST", parameters: parameters, success: success, failure: failure)
}
public func postOAuth2InvalidateBearerTokenWithSuccess(success: TokenSuccessHandler?, failure: FailureHandler?) {
let path = "/oauth2/invalidate_token"
self.jsonRequestWithPath(path, baseURL: self.apiURL, method: "POST", parameters: [:], success: {
json, response in
if let accessToken = json["access_token"].string {
self.client.credential = nil
let credentialToken = SwifterCredential.OAuthAccessToken(key: accessToken, secret: "")
success?(accessToken: credentialToken, response: response)
}
else {
success?(accessToken: nil, response: response)
}
}, failure: failure)
}
public func postOAuthRequestTokenWithCallbackURL(callbackURL: NSURL, success: TokenSuccessHandler, failure: FailureHandler?) {
let path = "/oauth/request_token"
var parameters = Dictionary<String, Any>()
parameters["oauth_callback"] = callbackURL.absoluteString
self.client.post(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
data, response in
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
let accessToken = SwifterCredential.OAuthAccessToken(queryString: responseString as String!)
success(accessToken: accessToken, response: response)
}, failure: failure)
}
public func postOAuthAccessTokenWithRequestToken(requestToken: SwifterCredential.OAuthAccessToken, success: TokenSuccessHandler, failure: FailureHandler?) {
if let verifier = requestToken.verifier {
let path = "/oauth/access_token"
var parameters = Dictionary<String, Any>()
parameters["oauth_token"] = requestToken.key
parameters["oauth_verifier"] = verifier
self.client.post(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
data, response in
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
let accessToken = SwifterCredential.OAuthAccessToken(queryString: responseString! as String)
success(accessToken: accessToken, response: response)
}, failure: failure)
}
else {
let userInfo = [NSLocalizedFailureReasonErrorKey: "Bad OAuth response received from server"]
let error = NSError(domain: SwifterError.domain, code: NSURLErrorBadServerResponse, userInfo: userInfo)
failure?(error: error)
}
}
}
| mit | a4651353fde9983cd67348e83165c70d | 42.989247 | 211 | 0.650086 | 5.397098 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalServiceKit/src/Storage/Database/SDSModel.swift | 1 | 4318 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import GRDB
public protocol SDSModel: TSYapDatabaseObject {
var sdsTableName: String { get }
func asRecord() throws -> SDSRecord
var serializer: SDSSerializer { get }
func anyInsert(transaction: SDSAnyWriteTransaction)
func anyRemove(transaction: SDSAnyWriteTransaction)
static var table: SDSTableMetadata { get }
}
// MARK: -
public extension SDSModel {
func sdsSave(saveMode: SDSSaveMode, transaction: SDSAnyWriteTransaction) {
guard shouldBeSaved else {
Logger.warn("Skipping save of: \(type(of: self))")
return
}
switch saveMode {
case .insert:
anyWillInsert(with: transaction)
case .update:
anyWillUpdate(with: transaction)
}
switch transaction.writeTransaction {
case .yapWrite(let ydbTransaction):
ydb_save(with: ydbTransaction)
case .grdbWrite(let grdbTransaction):
do {
let record = try asRecord()
record.sdsSave(saveMode: saveMode, transaction: grdbTransaction)
} catch {
owsFail("Write failed: \(error)")
}
}
switch saveMode {
case .insert:
anyDidInsert(with: transaction)
if type(of: self).shouldBeIndexedForFTS {
FullTextSearchFinder().modelWasInserted(model: self, transaction: transaction)
}
case .update:
anyDidUpdate(with: transaction)
if type(of: self).shouldBeIndexedForFTS {
FullTextSearchFinder().modelWasUpdated(model: self, transaction: transaction)
}
}
}
func sdsRemove(transaction: SDSAnyWriteTransaction) {
guard shouldBeSaved else {
// Skipping remove.
return
}
anyWillRemove(with: transaction)
switch transaction.writeTransaction {
case .yapWrite(let ydbTransaction):
ydb_remove(with: ydbTransaction)
case .grdbWrite(let grdbTransaction):
// Don't use a record to delete the record;
// asRecord() is expensive.
let sql = """
DELETE
FROM \(sdsTableName)
WHERE uniqueId == ?
"""
grdbTransaction.executeWithCachedStatement(sql: sql, arguments: [uniqueId])
}
anyDidRemove(with: transaction)
if type(of: self).shouldBeIndexedForFTS {
FullTextSearchFinder().modelWasRemoved(model: self, transaction: transaction)
}
}
}
// MARK: -
public extension TableRecord {
static func ows_fetchCount(_ db: Database) -> UInt {
do {
let result = try fetchCount(db)
guard result >= 0 else {
owsFailDebug("Invalid result: \(result)")
return 0
}
guard result <= UInt.max else {
owsFailDebug("Invalid result: \(result)")
return UInt.max
}
return UInt(result)
} catch {
owsFailDebug("Read failed: \(error)")
return 0
}
}
}
// MARK: -
public extension SDSModel {
// If batchSize > 0, the enumeration is performed in autoreleased batches.
static func grdbEnumerateUniqueIds(transaction: GRDBReadTransaction,
sql: String,
batchSize: UInt,
block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
do {
let cursor = try String.fetchCursor(transaction.database,
sql: sql)
try Batching.loop(batchSize: batchSize,
loopBlock: { stop in
guard let uniqueId = try cursor.next() else {
stop.pointee = true
return
}
block(uniqueId, stop)
})
} catch let error as NSError {
owsFailDebug("Couldn't fetch uniqueIds: \(error)")
}
}
}
| gpl-3.0 | 4e686b714a1dc4d251ac9b400fd6f056 | 29.624113 | 107 | 0.535665 | 5.337454 | false | false | false | false |
HipHipArr/PocketCheck | Cheapify 2.0/View.swift | 1 | 1170 | //
// View.swift
// Cheapify 2.0
//
// Created by loaner on 7/8/15.
// Copyright (c) 2015 Your Friend. All rights reserved.
//
import UIKit
class View: UIImageView {
var bgImage: UIImage!
func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
setup()
}
func setup(){
self.bgImage = chooseImage(entryMgr.categoryname)
}
func chooseImage (cat: String) -> UIImage {
if(cat == "Food")
{
return UIImage(named: "food.jpg")!
}
else if(cat == "Personal")
{
return UIImage(named: "personal.jpg")!
}
else if(cat == "Travel")
{
return UIImage(named: "travel.jpg")!
}
else if(cat == "Transportation")
{
return UIImage(named: "transportation.jpg")!
}
else if(cat == "Business")
{
return UIImage(named: "business.jpg")!
}
else if(cat == "Entertainment")
{
return UIImage(named: "entertainment.jpg")!
}
return UIImage(named: "other.jpg")!
}
}
| mit | 64abe4af33bb5baefa81aea3c594c5a0 | 21.5 | 80 | 0.508547 | 4.090909 | false | false | false | false |
charleshkang/Weatherr | C4QWeather/C4QWeather/WeatherParser.swift | 1 | 1254 | //
// WeatherParser
// C4QWeather
//
// Created by Charles Kang on 11/21/16.
// Copyright © 2016 Charles Kang. All rights reserved.
//
import SwiftyJSON
class WeatherParser {
//MARK: Action Methods
/**
use flatMap instead of map here because data from a backend can always fail,
use flatMap so we only return successful weather objects
*/
func parseWeatherJSON(_ json: JSON) -> [Weather] {
let weatherArray = json["response"][0]["periods"].arrayValue
return weatherArray.flatMap { Weather(json: $0) }
}
}
extension Weather {
/**
create a failable initializer to make sure
we only get properties that are valid. also use
guard to take advantage of its early exit feature
*/
init?(json: JSON) {
guard let maxTempF = json["maxTempF"].int,
let minTempF = json["minTempF"].int,
let maxTempC = json["maxTempC"].int,
let minTempC = json["minTempC"].int,
let dateTimeISO = json["dateTimeISO"].string
else { return nil }
self.maxTempF = maxTempF
self.minTempF = minTempF
self.maxTempC = maxTempC
self.minTempC = minTempC
self.dateTime = dateTimeISO
}
}
| mit | 6cad0c5b1595a2901605a042d9cbbdc8 | 26.844444 | 81 | 0.616919 | 4.028939 | false | false | false | false |
blinksh/blink | KB/Native/Views/General/DefaultRow.swift | 1 | 2037 | //////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Blink is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import SwiftUI
struct DefaultRow<Details: View>: View {
@Binding var title: String
@Binding var description: String?
var details: () -> Details
init(title: String, description: String? = nil, details: @escaping () -> Details) {
_title = .constant(title)
_description = .constant(description)
self.details = details
}
init(title: Binding<String>, description: Binding<String?> = .constant(nil), details: @escaping () -> Details) {
_title = title
_description = description
self.details = details
}
var body: some View {
Row(content: {
HStack {
Text(self.title).foregroundColor(.primary)
Spacer()
Text(self.description ?? "").foregroundColor(.secondary)
}
}, details: self.details)
}
}
| gpl-3.0 | e4f1f3e816335d29c1a68b187a32d592 | 32.393443 | 114 | 0.635739 | 4.418655 | false | false | false | false |
trm36/stanford-calculator | Calculator/ViewController.swift | 1 | 11544 | //
// ViewController.swift
// Calculator
//
// Created by Taylor Mott on 13 Jul 15.
// Copyright (c) 2015 Mott Applications. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let displayLabel = UILabel()
let displayBackground = UIView()
var userIsInTheMiddleOfTypingANumber = false
var displayValue: Double {
get {
return (displayLabel.text! as NSString).doubleValue
}
set {
self.displayLabel.text = "\(newValue)"
self.userIsInTheMiddleOfTypingANumber = false
}
}
let brain = CalculatorBrain()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Row 1
self.displayBackground.backgroundColor = UIColor.lightGrayColor()
self.view.addSubview(self.displayBackground)
self.displayLabel.text = "0"
self.displayLabel.font = UIFont.systemFontOfSize(32)
self.displayLabel.textAlignment = NSTextAlignment.Right
self.view.addSubview(self.displayLabel)
self.displayLabel.alignTop("20", leading: "5", toView: self.view)
self.displayLabel.alignTrailingEdgeWithView(self.view, predicate: "-5")
self.displayLabel.constrainHeight("50")
self.displayBackground.alignTop("0", leading: "0", bottom: "0", trailing: "0", toView: self.displayLabel)
//Row 2
let button7 = UIButton()
button7.setTitle("7", forState: .Normal)
button7.setTitleColor(UIColor.blackColor(), forState: .Normal)
button7.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button7)
let button8 = UIButton()
button8.setTitle("8", forState: .Normal)
button8.setTitleColor(UIColor.blackColor(), forState: .Normal)
button8.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button8)
let button9 = UIButton()
button9.setTitle("9", forState: .Normal)
button9.setTitleColor(UIColor.blackColor(), forState: .Normal)
button9.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button9)
let buttonDivide = UIButton()
buttonDivide.setTitle("÷", forState: .Normal)
buttonDivide.setTitleColor(UIColor.blackColor(), forState: .Normal)
buttonDivide.addTarget(self, action: "operate:", forControlEvents: .TouchUpInside)
self.view.addSubview(buttonDivide)
button7.constrainTopSpaceToView(self.displayLabel, predicate: "5")
button7.alignLeadingEdgeWithView(self.displayLabel, predicate: "0")
button8.alignTopEdgeWithView(button7, predicate: "0")
button8.constrainLeadingSpaceToView(button7, predicate: "0")
button9.alignTopEdgeWithView(button7, predicate: "0")
button9.constrainLeadingSpaceToView(button8, predicate: "0")
buttonDivide.alignTopEdgeWithView(button7, predicate: "0")
buttonDivide.constrainLeadingSpaceToView(button9, predicate: "0")
buttonDivide.alignTrailingEdgeWithView(self.displayLabel, predicate: "0")
//Row 3
let button4 = UIButton()
button4.setTitle("4", forState: .Normal)
button4.setTitleColor(UIColor.blackColor(), forState: .Normal)
button4.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button4)
let button5 = UIButton()
button5.setTitle("5", forState: .Normal)
button5.setTitleColor(UIColor.blackColor(), forState: .Normal)
button5.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button5)
let button6 = UIButton()
button6.setTitle("6", forState: .Normal)
button6.setTitleColor(UIColor.blackColor(), forState: .Normal)
button6.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button6)
let buttonMultiply = UIButton()
buttonMultiply.setTitle("×", forState: .Normal)
buttonMultiply.setTitleColor(UIColor.blackColor(), forState: .Normal)
buttonMultiply.addTarget(self, action: "operate:", forControlEvents: .TouchUpInside)
self.view.addSubview(buttonMultiply)
button4.constrainTopSpaceToView(button7, predicate: "0")
button4.alignLeadingEdgeWithView(self.displayLabel, predicate: "0")
button5.alignTopEdgeWithView(button4, predicate: "0")
button5.constrainLeadingSpaceToView(button4, predicate: "0")
button6.alignTopEdgeWithView(button4, predicate: "0")
button6.constrainLeadingSpaceToView(button5, predicate: "0")
buttonMultiply.alignTopEdgeWithView(button4, predicate: "0")
buttonMultiply.constrainLeadingSpaceToView(button6, predicate: "0")
buttonMultiply.alignTrailingEdgeWithView(self.displayLabel, predicate: "0")
//Row 4
let button1 = UIButton()
button1.backgroundColor = .redColor()
button1.setTitle("1", forState: .Normal)
button1.setTitleColor(UIColor.blackColor(), forState: .Normal)
button1.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button1)
let button2 = UIButton()
button2.backgroundColor = .yellowColor()
button2.setTitle("2", forState: .Normal)
button2.setTitleColor(UIColor.blackColor(), forState: .Normal)
button2.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button2)
let button3 = UIButton()
button3.backgroundColor = .orangeColor()
button3.setTitle("3", forState: .Normal)
button3.setTitleColor(UIColor.blackColor(), forState: .Normal)
button3.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button3)
let buttonSubtract = UIButton()
buttonSubtract.setTitle("−", forState: .Normal)
buttonSubtract.setTitleColor(UIColor.blackColor(), forState: .Normal)
buttonSubtract.addTarget(self, action: "operate:", forControlEvents: .TouchUpInside)
self.view.addSubview(buttonSubtract)
button1.constrainTopSpaceToView(button4, predicate: "0")
button1.alignLeadingEdgeWithView(self.displayLabel, predicate: "0")
button2.alignTopEdgeWithView(button1, predicate: "0")
button2.constrainLeadingSpaceToView(button1, predicate: "0")
button3.alignTopEdgeWithView(button1, predicate: "0")
button3.constrainLeadingSpaceToView(button2, predicate: "0")
buttonSubtract.alignTopEdgeWithView(button1, predicate: "0")
buttonSubtract.constrainLeadingSpaceToView(button3, predicate: "0")
buttonSubtract.alignTrailingEdgeWithView(self.displayLabel, predicate: "0")
//Row 5
let buttonEnter = UIButton()
buttonEnter.backgroundColor = .purpleColor()
buttonEnter.setTitle("↩︎", forState: .Normal)
buttonEnter.setTitleColor(UIColor.blackColor(), forState: .Normal)
buttonEnter.addTarget(self, action: "enter", forControlEvents: .TouchUpInside)
self.view.addSubview(buttonEnter)
let button0 = UIButton()
button0.backgroundColor = .blueColor()
button0.setTitle("0", forState: .Normal)
button0.setTitleColor(UIColor.blackColor(), forState: .Normal)
button0.addTarget(self, action: "appendDigit:", forControlEvents: .TouchUpInside)
self.view.addSubview(button0)
let buttonSqrt = UIButton()
buttonSqrt.setTitle("√", forState: .Normal)
buttonSqrt.setTitleColor(UIColor.blackColor(), forState: .Normal)
buttonSqrt.addTarget(self, action: "operate:", forControlEvents: .TouchUpInside)
self.view.addSubview(buttonSqrt)
let buttonAdd = UIButton()
buttonAdd.setTitle("+", forState: .Normal)
buttonAdd.setTitleColor(UIColor.blackColor(), forState: .Normal)
buttonAdd.addTarget(self, action: "operate:", forControlEvents: .TouchUpInside)
self.view.addSubview(buttonAdd)
buttonEnter.constrainTopSpaceToView(button1, predicate: "0")
buttonEnter.alignLeadingEdgeWithView(self.displayLabel, predicate: "0")
buttonEnter.alignBottomEdgeWithView(self.view, predicate: "-5")
button0.alignTopEdgeWithView(buttonEnter, predicate: "0")
button0.constrainLeadingSpaceToView(buttonEnter, predicate: "0")
buttonSqrt.alignTopEdgeWithView(buttonEnter, predicate: "0")
buttonSqrt.constrainLeadingSpaceToView(button0, predicate: "0")
buttonAdd.alignTopEdgeWithView(buttonEnter, predicate: "0")
buttonAdd.constrainLeadingSpaceToView(buttonSqrt, predicate: "0")
buttonAdd.alignTrailingEdgeWithView(self.displayLabel, predicate: "0")
UIView.equalHeightForViews([button0, button1, button2, button3, button4, button5, button6, button7, button8, button9, buttonEnter, buttonDivide, buttonMultiply, buttonSubtract, buttonAdd, buttonSqrt])
UIView.equalWidthForViews([button0, button1, button2, button3, button4, button5, button6, button7, button8, button9, buttonEnter, buttonDivide, buttonMultiply, buttonSubtract, buttonAdd, buttonSqrt])
}
func operate(sender: UIButton) {
let operation = sender.currentTitle!
if self.userIsInTheMiddleOfTypingANumber {
enter()
}
if let result = self.brain.performOperation(operation) {
displayValue = result
} else {
//get rid of display
println("error paul was talking about with display value not being an optional")
}
}
func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if !(digit == "0" && self.displayLabel.text! == "0") {
if userIsInTheMiddleOfTypingANumber && self.displayLabel.text! != "0" {
self.displayLabel.text = self.displayLabel.text! + digit
} else {
self.displayLabel.text = digit
}
}
self.userIsInTheMiddleOfTypingANumber = true
println("\(digit)")
println("\(self.userIsInTheMiddleOfTypingANumber)")
}
func enter () {
self.userIsInTheMiddleOfTypingANumber = false
if let result = self.brain.pushOperand(self.displayValue) {
self.displayValue = result
} else {
// get rid of display
println("error paul was talking about in lecture 3")
}
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.displayBackground.alpha = 0.5
}) { (_) -> Void in
UIView.animateWithDuration(0.1, animations: { () -> Void in
self.displayBackground.alpha = 1.0
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 716795fbe6a89dba91b69de39fe4abd4 | 41.877323 | 208 | 0.65398 | 4.717382 | false | false | false | false |
niekang/NKDownload | NKDownload/DownloadingViewController.swift | 1 | 3616 | //
// ViewController.swift
// NKDownload
//
// Created by 聂康 on 2017/5/15.
// Copyright © 2017年 聂康. All rights reserved.
//
import UIKit
class DownloadingViewController: UIViewController {
fileprivate let reuse = "DownloadCell"
fileprivate lazy var dataArr = [DownloadObject]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension
NKDownloadManger.shared.delegate = self
dataArr = DownloadSqlite.manager.selectData()
}
}
extension DownloadingViewController{
/// 根据url获取对应的cell
///
/// - Parameter urlString: 下载url
/// - Returns: url对应的cell
func getCellWithURLString(urlString:String) -> DownloadCell?{
for (index,downloadObject) in dataArr.enumerated(){
if downloadObject.urlString == urlString {
let indexPath = IndexPath(row: index, section: 0)
let cell = tableView.cellForRow(at: indexPath) as? DownloadCell
return cell
}
}
return nil
}
}
extension DownloadingViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuse) as! DownloadCell
let downloadObject = dataArr[indexPath.row]
cell.disPlayCell(object: downloadObject)
return cell
}
}
extension DownloadingViewController:NKDownloadMangerDelegate{
func nk_downloadTaskStartDownload(nkDownloadTask: NKDownloadTask) {
guard let cell = getCellWithURLString(urlString: nkDownloadTask.urlString) else {
return
}
//回到主线程刷新UI
DispatchQueue.main.async {
cell.downloadObject.state = .downloading
cell.downloadBtn.setTitle("下载中", for: .normal)
}
}
/// 更新下载进度
///
/// - Parameter urlString: 下载网址
func nk_downloadTaskDidWriteData(nkDownloadTask: NKDownloadTask, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
guard let cell = getCellWithURLString(urlString: nkDownloadTask.urlString) else {
return
}
//回到主线程刷新UI
DispatchQueue.main.async {
cell.downloadObject.currentSize = totalBytesWritten
cell.downloadObject.totalSize = totalBytesExpectedToWrite
cell.downloadObject.state = .downloading
cell.disPlayCell(object: cell.downloadObject)
}
}
func nk_downloadTaskDidComleteWithError(nkDownloadTask: NKDownloadTask, error: NKDownloadError?) {
guard let cell = getCellWithURLString(urlString: nkDownloadTask.urlString) else {
return
}
//回到主线程刷新UI
DispatchQueue.main.async {
if let _ = error{
if error == NKDownloadError.cancelByUser{
cell.downloadObject.state = .suspend
}else if error == NKDownloadError.networkError{
cell.downloadObject.state = .fail
}
}else {
cell.downloadObject.state = .success
}
cell.disPlayCell(object: cell.downloadObject)
}
}
}
| apache-2.0 | 283f37f9c1cbb7245f49f279e9bddb1b | 30.936364 | 130 | 0.63934 | 5.004274 | false | false | false | false |
lizhenning87/SwiftZhiHu | SwiftZhiHu/SwiftZhiHu/Haneke/Haneke.swift | 1 | 1369 | //
// Haneke.swift
// Haneke
//
// Created by Hermes Pique on 9/9/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
public struct Haneke {
public static let Domain = "io.haneke"
public static func errorWithCode(code : Int, description : String) -> NSError {
let userInfo = [NSLocalizedDescriptionKey: description]
return NSError(domain: Haneke.Domain, code: code, userInfo: userInfo)
}
public static var sharedImageCache : Cache<UIImage> {
struct Static {
static let name = "shared-images"
static let cache = Cache<UIImage>(name: name)
}
return Static.cache
}
public static var sharedDataCache : Cache<NSData> {
struct Static {
static let name = "shared-data"
static let cache = Cache<NSData>(name: name)
}
return Static.cache
}
public static var sharedStringCache : Cache<String> {
struct Static {
static let name = "shared-strings"
static let cache = Cache<String>(name: name)
}
return Static.cache
}
public static var sharedJSONCache : Cache<JSON> {
struct Static {
static let name = "shared-json"
static let cache = Cache<JSON>(name: name)
}
return Static.cache
}
}
| apache-2.0 | c22afe4eec19ad780bd2c439cbb9a1d2 | 25.326923 | 83 | 0.591673 | 4.444805 | false | false | false | false |
cornerstonecollege/402 | 402_2016_2/CustomViewMaps/CustomViewMaps/ViewController.swift | 1 | 1567 | //
// ViewController.swift
// CustomViewMaps
//
// Created by Luiz on 2016-11-08.
// Copyright © 2016 Ideia do Luiz. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let vancouverCoordinate = CLLocationCoordinate2D(latitude: 49.2827, longitude: -123.1207)
self.mapView.setRegion(MKCoordinateRegionMake(vancouverCoordinate, MKCoordinateSpanMake(1, 1)), animated: true)
self.mapView.delegate = self
// let annotation = MKPointAnnotation()
// annotation.coordinate = vancouverCoordinate
// annotation.title = "City of Vancouver"
// annotation.subtitle = "Hello all."
let annotation = CustomAnnotation(coordinate: vancouverCoordinate)
annotation.title = "Custom annotation title"
annotation.subtitle = "Custom annotation subtitle"
self.mapView.addAnnotation(annotation)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is CustomAnnotation {
let annotationView = CustomAnnotationView(annotation: annotation, reuseIdentifier: "customIdentifier")
return annotationView
}
return nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 | dc5bb203ef1995e3466e53d1662ebe29 | 29.705882 | 119 | 0.670498 | 5.100977 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Model/LinearEquations/Solution/Items/MLinearEquationsSolutionEquationItemPolynomial.swift | 1 | 8068 | import UIKit
class MLinearEquationsSolutionEquationItemPolynomial:MLinearEquationsSolutionEquationItem
{
weak var indeterminate:MLinearEquationsSolutionIndeterminatesItem!
let coefficient:Double
let coefficientDividend:Double
let coefficientDivisor:Double
let showSign:Bool
let showAsDivision:Bool
init(
indeterminate:MLinearEquationsSolutionIndeterminatesItem,
coefficientDividend:Double,
coefficientDivisor:Double,
showSign:Bool,
showAsDivision:Bool,
reusableIdentifier:String,
cellWidth:CGFloat)
{
self.indeterminate = indeterminate
self.coefficientDividend = coefficientDividend
self.coefficientDivisor = coefficientDivisor
self.showSign = showSign
self.showAsDivision = showAsDivision
self.coefficient = coefficientDividend / coefficientDivisor
super.init(
reusableIdentifier:reusableIdentifier,
cellWidth:cellWidth)
}
//MARK: private
private func sum(
otherPolynomial:MLinearEquationsSolutionEquationItemPolynomial,
changeSign:Bool,
newIndex:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let sumItem:MLinearEquationsSolutionEquationItemPolynomial
let otherPolynomialDivisor:Double = otherPolynomial.coefficientDivisor
let otherPolynomialDividend:Double
let sumDividend:Double
let sumDivisor:Double
if changeSign
{
otherPolynomialDividend = -otherPolynomial.coefficientDividend
}
else
{
otherPolynomialDividend = otherPolynomial.coefficientDividend
}
if coefficientDivisor == otherPolynomialDivisor
{
sumDividend = coefficientDividend + otherPolynomialDividend
sumDivisor = coefficientDivisor
}
else
{
let scaledDividend:Double = coefficientDividend * otherPolynomialDivisor
let scaledOtherPolynomialDividend:Double = otherPolynomialDividend * coefficientDivisor
sumDividend = scaledDividend + scaledOtherPolynomialDividend
sumDivisor = coefficientDivisor * otherPolynomialDivisor
}
let newCoefficient:Double = abs(sumDividend / sumDivisor)
if newCoefficient > MSession.sharedInstance.kMinNumber
{
let showAsDivision:Bool
let coefficientAprox:Double = abs(newCoefficient - 1)
if coefficientAprox > MSession.sharedInstance.kMinNumber
{
if self.showAsDivision || otherPolynomial.showAsDivision
{
showAsDivision = true
}
else
{
showAsDivision = false
}
}
else
{
showAsDivision = false
}
sumItem = MLinearEquationsSolutionEquationItem.polynomial(
coefficientDividend:sumDividend,
coefficientDivisor:sumDivisor,
indeterminate:indeterminate,
index:newIndex,
showAsDivision:showAsDivision)
}
else
{
sumItem = MLinearEquationsSolutionEquationItem.emptyPolynomial(
indeterminate:indeterminate,
index:newIndex)
}
return sumItem
}
//MARK: public
func add(
otherPolynomial:MLinearEquationsSolutionEquationItemPolynomial,
newIndex:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let addedItem:MLinearEquationsSolutionEquationItemPolynomial = sum(
otherPolynomial:otherPolynomial,
changeSign:false,
newIndex:newIndex)
return addedItem
}
func subtract(
otherPolynomial:MLinearEquationsSolutionEquationItemPolynomial,
newIndex:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let subtractedItem:MLinearEquationsSolutionEquationItemPolynomial = sum(
otherPolynomial:otherPolynomial,
changeSign:true,
newIndex:newIndex)
return subtractedItem
}
func inversed(newIndex:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let inversedPolynomial:MLinearEquationsSolutionEquationItemPolynomial = MLinearEquationsSolutionEquationItem.polynomial(
coefficientDividend:-coefficientDividend,
coefficientDivisor:coefficientDivisor,
indeterminate:indeterminate,
index:newIndex,
showAsDivision:showAsDivision)
return inversedPolynomial
}
func multiply(
dividend:Double,
divisor:Double,
index:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let multiplied:MLinearEquationsSolutionEquationItemPolynomial
let newDividend:Double = coefficientDividend * dividend
let newDivisor:Double = coefficientDivisor * divisor
let newCoefficient:Double = abs(newDividend / newDivisor)
if newCoefficient > MSession.sharedInstance.kMinNumber
{
let showAsDivision:Bool
let coefficientAprox:Double = abs(newCoefficient - 1)
if coefficientAprox > MSession.sharedInstance.kMinNumber
{
showAsDivision = self.showAsDivision
}
else
{
showAsDivision = false
}
multiplied = MLinearEquationsSolutionEquationItem.polynomial(
coefficientDividend:newDividend,
coefficientDivisor:newDivisor,
indeterminate:indeterminate,
index:index,
showAsDivision:showAsDivision)
}
else
{
multiplied = MLinearEquationsSolutionEquationItem.emptyPolynomial(
indeterminate:indeterminate,
index:index)
}
return multiplied
}
func divide(
dividend:Double,
divisor:Double,
index:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let divided:MLinearEquationsSolutionEquationItemPolynomial
let newDividend:Double = coefficientDividend / dividend
let newDivisor:Double = coefficientDivisor / divisor
let newCoefficient:Double = abs(newDividend / newDivisor)
if newCoefficient > MSession.sharedInstance.kMinNumber
{
let showAsDivision:Bool
let coefficientAprox:Double = abs(newCoefficient - 1)
if coefficientAprox > MSession.sharedInstance.kMinNumber
{
showAsDivision = self.showAsDivision
}
else
{
showAsDivision = false
}
divided = MLinearEquationsSolutionEquationItem.polynomial(
coefficientDividend:newDividend,
coefficientDivisor:newDivisor,
indeterminate:indeterminate,
index:index,
showAsDivision:showAsDivision)
}
else
{
divided = MLinearEquationsSolutionEquationItem.emptyPolynomial(
indeterminate:indeterminate,
index:index)
}
return divided
}
func reIndexed(newIndex:Int) -> MLinearEquationsSolutionEquationItemPolynomial
{
let indexedPolynomial:MLinearEquationsSolutionEquationItemPolynomial = MLinearEquationsSolutionEquationItem.polynomial(
coefficientDividend:coefficientDividend,
coefficientDivisor:coefficientDivisor,
indeterminate:indeterminate,
index:newIndex,
showAsDivision:showAsDivision)
return indexedPolynomial
}
}
| mit | f088bb4cbe48eccdaeae0170fcbdc253 | 32.757322 | 128 | 0.622831 | 6.016406 | false | false | false | false |
343max/WorldTime | WorldTimeTodayWidget/TodayViewController.swift | 1 | 2814 | // Copyright 2014-present Max von Webel. All Rights Reserved.
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
@IBOutlet weak var collectionView: UICollectionView!
var collectionViewSource = LocationsCollectionViewDataSource()
var minuteChangeNotifier: MinuteChangeNotifier?
override func viewDidLoad() {
self.view.backgroundColor = UIColor.clear
collectionView.backgroundColor = UIColor.clear
collectionViewSource.prepare(collectionView: collectionView)
setup()
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setup()
self.minuteChangeNotifier = MinuteChangeNotifier(delegate: self)
self.timeHidden = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.timeHidden = true
self.minuteChangeNotifier = nil
}
func setup() {
let locations = Location.fromDefaults()
collectionViewSource.locations = locations
collectionView.reloadData()
guard let layout = collectionView.collectionViewLayout as? WorldTimeLayout else {
fatalError("not a WorldTimeLayout")
}
extensionContext?.widgetLargestAvailableDisplayMode = locations.count <= maximumLocationsCompactMode() ? .compact : .expanded
layout.prepareLayout(itemCount: collectionViewSource.locations.count)
}
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
guard let layout = collectionView.collectionViewLayout as? WorldTimeLayout else {
fatalError("not a WorldTimeLayout")
}
layout.minContentHeight = activeDisplayMode == .compact ? maxSize.height : nil
preferredContentSize = CGSize(width: 0, height: min(maxSize.height, layout.perfectContentHeight))
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
completionHandler(NCUpdateResult.newData)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.collectionView.frame = self.view.bounds
}
var timeHidden: Bool = false {
didSet(oldTimeHidden) {
collectionViewSource.timeHidden = timeHidden
collectionView.reloadData()
}
}
}
extension TodayViewController: MinuteChangeNotifierDelegate {
func minuteDidChange(notifier: MinuteChangeNotifier) {
for cell in collectionView.visibleCells {
if let cell = cell as? TimeZoneCollectionViewCell {
cell.update()
}
}
}
}
| mit | 0daa6400e3bcc49a57a68f4f50db6329 | 30.977273 | 133 | 0.687633 | 5.673387 | false | false | false | false |
albert438/JSPatch | Demo/SwiftDemo/SwiftDemo/AppDelegate.swift | 3 | 2979 | //
// AppDelegate.swift
// SwiftDemo
//
// Created by KouArlen on 16/2/3.
// Copyright © 2016年 Arlen. All rights reserved.
//
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 aClass: AnyClass? = NSClassFromString("SwiftDemo.ViewController")
if (aClass != nil) {
let clsName = NSStringFromClass(aClass!)
print(clsName)
} else {
print("error ViewController not found")
}
let bClass: AnyClass? = NSClassFromString("SwiftDemo.TestObject")
if (bClass != nil) {
let clsName = NSStringFromClass(bClass!)
print(clsName)
} else {
print("error TestObject not found")
}
let path = NSBundle.mainBundle().pathForResource("demo", ofType: "js")
do {
let patch = try String(contentsOfFile: path!)
JPEngine.startEngine()
JPEngine.evaluateScript(patch)
} catch {}
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:.
}
}
| mit | 84a58d466dc28bca90eb73531d82cbcd | 39.767123 | 285 | 0.684812 | 5.541899 | false | false | false | false |
mdznr/Keyboard | KeyboardExtension/Keyboard.swift | 1 | 6400 | //
// Keyboard.swift
// Keyboard
//
// Created by Matt Zanchelli on 6/19/14.
// Copyright (c) 2014 Matt Zanchelli. All rights reserved.
//
import UIKit
protocol KeyboardDelegate {
func keyboard(keyboard: Keyboard, didSelectKey key: KeyboardKey)
}
class Keyboard: UIControl {
// MARK: Initialization
convenience override init() {
self.init(frame: CGRectZero)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.autoresizingMask = .FlexibleWidth | .FlexibleHeight
self.multipleTouchEnabled = true
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: Properties
/// An array of rows (an array) of keys.
var keys: [[KeyboardKey]] = [[]] {
willSet {
// Remove all layout constraints.
self.removeConstraints(self.constraints())
// Remove all the rows from the view.
for view in self.subviews as [UIView] {
view.removeFromSuperview()
}
}
didSet {
var rows = Dictionary<String, UIView>()
var previousView: UIView = self
for x in 0..<keys.count {
let rowOfKeys = keys[x]
let row = Keyboard.createRow()
let rowName = "row" + x.description
rows[rowName] = row // rows.updateValue(row, forKey: rowName)
self.addSubview(row)
row.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[row]|", options: nil, metrics: nil, views: ["row": row]))
let attribute: NSLayoutAttribute = (x == 0) ? .Top : .Bottom
self.addConstraint(NSLayoutConstraint(item: row, attribute: .Top, relatedBy: .Equal, toItem: previousView, attribute: attribute, multiplier: 1, constant: 0))
previousView = row
self.addConstraint(NSLayoutConstraint(item: row, attribute: .Height, relatedBy: .Equal, toItem: row.superview, attribute: .Height, multiplier: rowHeights[x], constant: 0))
let metrics = ["top": edgeInsets[x].top, "bottom": edgeInsets[x].bottom]
var horizontalVisualFormatString = "H:|-(\(edgeInsets[x].left))-"
var views = Dictionary<String, UIView>()
var firstEquallySizedView = -1
for i in 0..<rowOfKeys.count {
let view = rowOfKeys[i]
let viewName = "view" + i.description
views.updateValue(view, forKey: viewName)
row.addSubview(view)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
row.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(top)-[view]-(bottom)-|", options: nil, metrics: metrics, views: ["view": view]))
let contentSize = view.intrinsicContentSize()
if contentSize.width == UIViewNoIntrinsicMetric {
if firstEquallySizedView < 0 {
firstEquallySizedView = i
horizontalVisualFormatString += "[\(viewName)]"
} else {
horizontalVisualFormatString += "[\(viewName)(==view\(firstEquallySizedView.description))]"
}
} else {
horizontalVisualFormatString += "[\(viewName)]"
}
}
horizontalVisualFormatString += "-(\(edgeInsets[x].right))-|"
if views.count > 0 {
row.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(horizontalVisualFormatString, options: nil, metrics: nil, views: views))
}
}
}
}
/// The edge insets for each row.
var edgeInsets: [UIEdgeInsets] = []
/// The heights for each row.
var rowHeights: [CGFloat] = []
// MARK: Helper functions
class func createRow() -> UIView {
let view = UIView()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
let divider = KeyboardDivider()
view.addSubview(divider)
let views = ["divider": divider]
divider.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[divider]|", options: nil, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[divider(0.5)]", options: nil, metrics: nil, views: views))
return view
}
// MARK: Gesture handling
var touchesToViews = Dictionary<UITouch, UIView>()
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch in touches.allObjects as [UITouch] {
let view = self.hitTest(touch.locationInView(self), withEvent: event)
touchesToViews[touch] = view
if let view = view as? KeyboardKey {
view.highlighted = true
}
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
for touch in touches.allObjects as [UITouch] {
let view = self.hitTest(touch.locationInView(self), withEvent: event)
let previousView = touchesToViews[touch]
if view != previousView {
if let previousView = previousView as? KeyboardKey {
previousView.highlighted = false
}
touchesToViews[touch] = view
if let view = view as? KeyboardKey {
view.highlighted = true
}
}
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
for touch in touches.allObjects as [UITouch] {
let view = touchesToViews[touch]
if let view = view as? KeyboardKey {
view.highlighted = false
view.didSelect()
}
touchesToViews.removeValueForKey(touch)
}
}
override func touchesCancelled(touches: NSSet, withEvent event: UIEvent) {
for touch in touches.allObjects as [UITouch] {
let view = touchesToViews[touch]
if let view = view as? KeyboardKey {
view.highlighted = false
}
touchesToViews.removeValueForKey(touch)
}
}
}
class KeyboardKey: UIView {
/// A Boolean value represeting whether the key is highlighted (a touch is inside).
var highlighted: Bool = false
// What to do when this is selected.
var action: () -> () = {}
override init(frame: CGRect) {
super.init(frame: frame)
self.setTranslatesAutoresizingMaskIntoConstraints(false)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// Called when a key has been selected. Subclasses can use this to present differently. Must call super!
func didSelect() {
action()
}
}
class KeyboardDivider: UIView {
convenience override init() {
self.init(frame: CGRectZero)
}
override init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
self.setTranslatesAutoresizingMaskIntoConstraints(false)
self.backgroundColor = KeyboardAppearance.dividerColorForAppearance(UIKeyboardAppearance.Default)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | f332b6244001e80fa278d3b805687f27 | 28.62963 | 175 | 0.701406 | 3.90482 | false | false | false | false |
tombuildsstuff/swiftcity | SwiftCity/Entities/SnapshotDependencies.swift | 1 | 834 | public struct SnapshotDependencies {
public let count: Int
public let dependencies: [SnapshotDependency]
init?(dictionary: [String: AnyObject]) {
guard let count = dictionary["count"] as? Int,
let dependenciesDictionary = dictionary["snapshot-dependency"] as? [[String: AnyObject]] else {
return nil
}
let dependencies = dependenciesDictionary.map { (dictionary: [String : AnyObject]) -> SnapshotDependency? in
return SnapshotDependency(dictionary: dictionary)
}.filter { (dependency: SnapshotDependency?) -> Bool in
return dependency != nil
}.map { (dependency: SnapshotDependency?) -> SnapshotDependency in
return dependency!
}
self.count = count
self.dependencies = dependencies
}
}
| mit | 46f6c95e70fa712937865ccab0fe5dfb | 35.26087 | 116 | 0.635492 | 5.380645 | false | false | false | false |
ello/ello-ios | Sources/Model/Love.swift | 1 | 2018 | ////
/// Love.swift
//
import SwiftyJSON
let LoveVersion: Int = 1
@objc(Love)
final class Love: Model, PostActionable {
let id: String
var isDeleted: Bool
let postId: String
let userId: String
var post: Post? { return getLinkObject("post") }
var user: User? { return getLinkObject("user") }
init(
id: String,
isDeleted: Bool,
postId: String,
userId: String
) {
self.id = id
self.isDeleted = isDeleted
self.postId = postId
self.userId = userId
super.init(version: LoveVersion)
addLinkObject("post", id: postId, type: .postsType)
addLinkObject("user", id: userId, type: .usersType)
}
required init(coder: NSCoder) {
let decoder = Coder(coder)
self.id = decoder.decodeKey("id")
self.isDeleted = decoder.decodeKey("deleted")
self.postId = decoder.decodeKey("postId")
self.userId = decoder.decodeKey("userId")
super.init(coder: coder)
}
override func encode(with encoder: NSCoder) {
let coder = Coder(encoder)
coder.encodeObject(id, forKey: "id")
coder.encodeObject(isDeleted, forKey: "deleted")
coder.encodeObject(postId, forKey: "postId")
coder.encodeObject(userId, forKey: "userId")
super.encode(with: coder.coder)
}
class func fromJSON(_ data: [String: Any]) -> Love {
let json = JSON(data)
let love = Love(
id: json["id"].idValue,
isDeleted: json["deleted"].boolValue,
postId: json["post_id"].stringValue,
userId: json["user_id"].stringValue
)
love.mergeLinks(data["links"] as? [String: Any])
love.addLinkObject("post", id: love.postId, type: .postsType)
love.addLinkObject("user", id: love.userId, type: .usersType)
return love
}
}
extension Love: JSONSaveable {
var uniqueId: String? { return "Love-\(id)" }
var tableId: String? { return id }
}
| mit | 0221ae9cb1cddcc7ab466fb5d8b8446a | 25.906667 | 69 | 0.594153 | 3.99604 | false | false | false | false |
naddison36/book-review-ios | Pods/RSBarcodes_Swift/Source/RSCodeReaderViewController.swift | 1 | 10986 | //
// RSCodeReaderViewController.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/12/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
import AVFoundation
public class RSCodeReaderViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
public lazy var device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
public lazy var output = AVCaptureMetadataOutput()
public lazy var session = AVCaptureSession()
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
public lazy var focusMarkLayer = RSFocusMarkLayer()
public lazy var cornersLayer = RSCornersLayer()
public var tapHandler: ((CGPoint) -> Void)?
public var barcodesHandler: ((Array<AVMetadataMachineReadableCodeObject>) -> Void)?
var ticker: NSTimer?
public var isCrazyMode = false
var isCrazyModeStarted = false
var lensPosition: Float = 0
// MARK: Public methods
public func hasFlash() -> Bool {
if let d = self.device {
return d.hasFlash
}
return false
}
public func hasTorch() -> Bool {
if let d = self.device {
return d.hasTorch
}
return false
}
public func toggleTorch() -> Bool {
if self.hasTorch() {
self.session.beginConfiguration()
self.device.lockForConfiguration(nil)
if self.device.torchMode == .Off {
self.device.torchMode = .On
} else if self.device.torchMode == .On {
self.device.torchMode = .Off
}
self.device.unlockForConfiguration()
self.session.commitConfiguration()
return self.device.torchMode == .On
}
return false
}
// MARK: Private methods
class func interfaceOrientationToVideoOrientation(orientation : UIInterfaceOrientation) -> AVCaptureVideoOrientation {
switch (orientation) {
case .Unknown:
fallthrough
case .Portrait:
return AVCaptureVideoOrientation.Portrait
case .PortraitUpsideDown:
return AVCaptureVideoOrientation.PortraitUpsideDown
case .LandscapeLeft:
return AVCaptureVideoOrientation.LandscapeLeft
case .LandscapeRight:
return AVCaptureVideoOrientation.LandscapeRight
}
}
func autoUpdateLensPosition() {
self.lensPosition += 0.01
if self.lensPosition > 1 {
self.lensPosition = 0
}
if device.lockForConfiguration(nil) {
self.device.setFocusModeLockedWithLensPosition(self.lensPosition, completionHandler: nil)
device.unlockForConfiguration()
}
if session.running {
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(10 * Double(USEC_PER_SEC)))
dispatch_after(when, dispatch_get_main_queue(), {
self.autoUpdateLensPosition()
})
}
}
func onTick() {
if let t = self.ticker {
t.invalidate()
}
self.cornersLayer.cornersArray = []
}
func onTap(gesture: UITapGestureRecognizer) {
let tapPoint = gesture.locationInView(self.view)
let focusPoint = CGPointMake(
tapPoint.x / self.view.bounds.size.width,
tapPoint.y / self.view.bounds.size.height)
if let d = self.device {
if d.lockForConfiguration(nil) {
if d.focusPointOfInterestSupported {
d.focusPointOfInterest = focusPoint
} else {
println("Focus point of interest not supported.")
}
if self.isCrazyMode {
if d.isFocusModeSupported(.Locked) {
d.focusMode = .Locked
} else {
println("Locked focus not supported.")
}
if !self.isCrazyModeStarted {
self.isCrazyModeStarted = true
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.autoUpdateLensPosition()
})
}
} else {
if d.isFocusModeSupported(.ContinuousAutoFocus) {
d.focusMode = .ContinuousAutoFocus
} else if d.isFocusModeSupported(.AutoFocus) {
d.focusMode = .AutoFocus
} else {
println("Auto focus not supported.")
}
}
if d.autoFocusRangeRestrictionSupported {
d.autoFocusRangeRestriction = .None
} else {
println("Auto focus range restriction not supported.")
}
d.unlockForConfiguration()
self.focusMarkLayer.point = tapPoint
}
}
if let h = self.tapHandler {
h(tapPoint)
}
}
func onApplicationWillEnterForeground() {
self.session.startRunning()
}
func onApplicationDidEnterBackground() {
self.session.stopRunning()
}
// MARK: Deinitialization
deinit {
println("RSCodeReaderViewController deinit")
}
// MARK: View lifecycle
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let l = self.videoPreviewLayer {
let videoOrientation = RSCodeReaderViewController.interfaceOrientationToVideoOrientation(UIApplication.sharedApplication().statusBarOrientation)
if l.connection.supportsVideoOrientation
&& l.connection.videoOrientation != videoOrientation {
l.connection.videoOrientation = videoOrientation
}
}
}
override public func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
let frame = CGRectMake(0, 0, size.width, size.height)
if let l = self.videoPreviewLayer {
l.frame = frame
}
if let l = self.focusMarkLayer {
l.frame = frame
}
if let l = self.cornersLayer {
l.frame = frame
}
}
override public func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.clearColor()
var error : NSError?
let input = AVCaptureDeviceInput(device: self.device, error: &error)
if let e = error {
println(e.description)
return
}
if let d = self.device {
if d.lockForConfiguration(nil) {
if self.device.isFocusModeSupported(.ContinuousAutoFocus) {
self.device.focusMode = .ContinuousAutoFocus
}
if self.device.autoFocusRangeRestrictionSupported {
self.device.autoFocusRangeRestriction = .Near
}
self.device.unlockForConfiguration()
}
}
if self.session.canAddInput(input) {
self.session.addInput(input)
}
self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
if let l = self.videoPreviewLayer {
l.videoGravity = AVLayerVideoGravityResizeAspectFill
l.frame = self.view.bounds
self.view.layer.addSublayer(l)
}
let queue = dispatch_queue_create("com.pdq.rsbarcodes.metadata", DISPATCH_QUEUE_CONCURRENT)
self.output.setMetadataObjectsDelegate(self, queue: queue)
if self.session.canAddOutput(self.output) {
self.session.addOutput(self.output)
self.output.metadataObjectTypes = self.output.availableMetadataObjectTypes
}
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "onTap:")
self.view.addGestureRecognizer(tapGestureRecognizer)
self.focusMarkLayer.frame = self.view.bounds
self.view.layer.addSublayer(self.focusMarkLayer)
self.cornersLayer.frame = self.view.bounds
self.view.layer.addSublayer(self.cornersLayer)
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onApplicationWillEnterForeground", name:UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onApplicationDidEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil)
self.session.startRunning()
}
override public func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidEnterBackgroundNotification, object: nil)
self.session.stopRunning()
}
// MARK: AVCaptureMetadataOutputObjectsDelegate
public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
var barcodeObjects : Array<AVMetadataMachineReadableCodeObject> = []
var cornersArray : Array<[AnyObject]> = []
for metadataObject : AnyObject in metadataObjects {
if let l = self.videoPreviewLayer {
let transformedMetadataObject = l.transformedMetadataObjectForMetadataObject(metadataObject as! AVMetadataObject)
if transformedMetadataObject.isKindOfClass(AVMetadataMachineReadableCodeObject.self) {
let barcodeObject = transformedMetadataObject as! AVMetadataMachineReadableCodeObject
barcodeObjects.append(barcodeObject)
cornersArray.append(barcodeObject.corners)
}
}
}
self.cornersLayer.cornersArray = cornersArray
if barcodeObjects.count > 0 {
if let h = self.barcodesHandler {
h(barcodeObjects)
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let t = self.ticker {
t.invalidate()
}
self.ticker = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "onTick", userInfo: nil, repeats: true)
})
}
}
| mit | b41946fa4b8052271822e705a7c55bd2 | 35.62 | 172 | 0.596851 | 5.797361 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/StudyNote/StudyNote/ScrollView/SNTableViewSummaryController.swift | 1 | 4293 | //
// SNTableViewSummaryController.swift
// StudyNote
//
// Created by wuyp on 2019/6/24.
// Copyright © 2019 Raymond. All rights reserved.
//
import UIKit
import Common
private let kCellID = String(describing: UITableViewCell.self)
class SNTableViewSummaryController: UIViewController {
@objc private lazy dynamic var table: UITableView = {
let tableview = UITableView(frame: self.view.bounds, style: .grouped)
tableview.backgroundColor = UIColor.purple
tableview.frame = CGRect(x: 0, y: kNavigationStatuBarHeight, width: kScreenWidth, height: kScreenHeight - kNavigationStatuBarHeight - kBottomSafeHeight)
tableview.delegate = self
tableview.dataSource = self
tableview.register(UITableViewCell.self, forCellReuseIdentifier: kCellID)
tableview.register(SNNormalTextCell.self, forCellReuseIdentifier: "SNNormalTextCell")
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tabTapAction))
// tapGesture.delegate = self
tapGesture.cancelsTouchesInView = false
tableview.addGestureRecognizer(tapGesture)
if #available(iOS 11, *) {
tableview.contentInsetAdjustmentBehavior = .never
tableview.contentInset = .zero
}
return tableview
}()
@objc override dynamic func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(table)
}
}
extension SNTableViewSummaryController: UITableViewDelegate, UITableViewDataSource {
@objc dynamic func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
@objc dynamic func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 25
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
@objc dynamic func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.0001
}
@objc dynamic func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.0001
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SNNormalTextCell", for: indexPath)
// setCellContent(row: indexPath.row, cell: cell)
return cell
}
@objc private dynamic func setCellContent(row: Int, cell: UITableViewCell) {
switch row {
case 0:
let btn = UIButton(frame: CGRect(x: 15, y: 10, width: 100, height: 30))
btn.setTitle("测试", for: .normal)
btn.setTitleColor(.purple, for: .normal)
btn.addTarget(self, action: #selector(cellBtnClickAction), for: .touchUpInside)
cell.contentView.addSubview(btn)
break
case 1:
let tf = UITextField(frame: CGRect(x: 15, y: 10, width: 150, height: 30))
tf.placeholder = "请输入"
cell.contentView.addSubview(tf)
break
default:
cell.textLabel?.text = "Row \(row)"
break
}
}
}
extension SNTableViewSummaryController {
@objc private dynamic func cellBtnClickAction() {
print("----click button")
}
@objc private dynamic func tabTapAction() {
self.view.endEditing(true)
}
}
extension SNTableViewSummaryController: UIGestureRecognizerDelegate {
@objc dynamic func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
guard let touchView = touch.view else { return true }
return true
}
}
extension CaseIterable where Self: RawRepresentable {
static var allValues: [RawValue] {
return self.allCases.map{ $0.rawValue }
}
static var allTypes: [Self] {
return self.allCases.map{ $0 }
}
}
extension SNTableViewSummaryController: SNRouteInterruptHandleProtocol {
static func handleRoute(route: SNRouteEntity) -> SNRouteFlowResult {
print("SNTableViewSummaryController load interrupt")
return .stop
}
}
| apache-2.0 | 0ab6c87993ec2dc823f5d9d47e2f27a4 | 31.687023 | 160 | 0.6539 | 4.956019 | false | false | false | false |
qvacua/vimr | Tabs/Support/TabsSupport/AppDelegate.swift | 1 | 2082 | //
// AppDelegate.swift
// TabsSupport
//
// Created by Tae Won Ha on 22.11.20.
//
import Cocoa
import PureLayout
import Tabs
@main
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var window: NSWindow!
override init() {
self.tabBar = TabBar(withTheme: .default)
super.init()
}
func applicationDidFinishLaunching(_: Notification) {
let contentView = self.window.contentView!
contentView.addSubview(self.tabBar)
let tb = self.tabBar
tb.autoPinEdge(toSuperviewEdge: .top)
tb.autoPinEdge(toSuperviewEdge: .left)
tb.autoPinEdge(toSuperviewEdge: .right)
tb.autoSetDimension(.height, toSize: Theme().tabBarHeight)
tb.selectHandler = { [weak self] _, selectedEntry, _ in
self?.tabEntries.enumerated().forEach { index, entry in
self?.tabEntries[index].isSelected = (entry == selectedEntry)
}
DispatchQueue.main.async {
Swift.print("select: \(self!.tabEntries)")
self?.tabBar.update(tabRepresentatives: self?.tabEntries ?? [])
}
}
tb.reorderHandler = { [weak self] index, reorderedEntry, entries in
self?.tabEntries = entries
self?.tabEntries.enumerated().forEach { index, entry in
self?.tabEntries[index].isSelected = (entry == reorderedEntry)
}
DispatchQueue.main.async {
Swift.print("reorder: \(entries)")
self?.tabBar.update(tabRepresentatives: self?.tabEntries ?? [])
}
}
self.tabEntries = [
DummyTabEntry(title: "Test 1"),
DummyTabEntry(title: "Test 2"),
DummyTabEntry(title: "Test 3"),
DummyTabEntry(title: "Very long long long title, and some more text!"),
]
self.tabEntries[0].isSelected = true
self.tabBar.update(tabRepresentatives: self.tabEntries)
}
func applicationWillTerminate(_: Notification) {
// Insert code here to tear down your application
}
private let tabBar: TabBar<DummyTabEntry>
private var tabEntries = [DummyTabEntry]()
}
struct DummyTabEntry: Hashable, TabRepresentative {
var title: String
var isSelected = false
}
| mit | 236c5786db9d555444dc1da883e0d275 | 28.323944 | 77 | 0.676273 | 4.114625 | false | false | false | false |
benwwchen/sysujwxt-ios | SYSUJwxt/GradeViewController.swift | 1 | 5052 | //
// GradeViewController.swift
// SYSUJwxt
//
// Created by benwwchen on 2017/8/17.
// Copyright © 2017年 benwwchen. All rights reserved.
//
import UIKit
class GradeViewController: ListWithFilterViewController,
UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var gradesTableView: UITableView!
// MARK: Properties
var grades = [Grade]()
// MARK: Methods
override func loadData(completion: (() -> Void)? = nil) {
loadSavedFilterData()
var isGetAll = false
var isGetAllTerms = false
var yearInt: Int = 0
var termInt: Int = 0
if self.year == "全部" {
isGetAll = true
} else {
yearInt = Int(self.year.components(separatedBy: "-")[0])!
}
if self.term == "全部" {
isGetAllTerms = true
} else {
termInt = Int(self.term)!
}
let coursesTypeValues = coursesType.map({ CourseType.fromString(string: $0) })
jwxt.getGradeList(year: yearInt, term: termInt, isGetAll: isGetAll, isGetAllTerms: isGetAllTerms) { (success, object) in
if success, let grades = object as? [Grade] {
self.grades.removeAll()
// filter a courseType and append to the table data
let filteredGrades = grades.filter({ coursesTypeValues.contains($0.courseType) })
let sortedFilteredGrades = filteredGrades.sorted(by: { (grade1, grade2) -> Bool in
if grade1.year > grade2.year {
return true
} else if grade1.year == grade2.year {
if grade1.term > grade2.term {
return true
} else if grade1.term == grade2.term {
return grade1.name > grade2.name
}
}
return false
})
self.grades.append(contentsOf: sortedFilteredGrades)
DispatchQueue.main.async {
self.gradesTableView.reloadData()
completion?()
}
}
}
}
// MARK: Table Views
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return grades.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "GradeTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? GradeTableViewCell else {
fatalError("The dequeued cell is not an instance of GradeTableViewCell.")
}
// populate the data
let grade = grades[indexPath.row]
cell.courseNameLabel.text = grade.name
cell.creditLabel.text = "\(grade.credit)"
cell.gpaLabel.text = "\(grade.gpa)"
cell.gradeLabel.text = "\(grade.totalGrade)"
cell.rankingInTeachingClassLabel.text = grade.rankingInTeachingClass
cell.rankingInMajorClassLabel.text = grade.rankingInMajorClass
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.setSelected(false, animated: true)
cell.isSelected = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupRefreshControl(tableView: gradesTableView)
gradesTableView.dataSource = self
gradesTableView.delegate = self
headerTitle = "成绩"
filterType = .grade
initSetup()
}
override func unwindToMainViewController(sender: UIStoryboardSegue) {
super.unwindToMainViewController(sender: sender)
if sender.source is UINavigationController {
print("nav")
}
if sender.source is NotifySettingTableViewController {
print("notify")
}
// save current grades if notification is on
if let _ = (sender.source as? UINavigationController)?.topViewController as? NotifySettingTableViewController,
let year = UserDefaults.standard.string(forKey: "notify.year"),
let yearInt = Int(year.components(separatedBy: "-")[0]),
let term = UserDefaults.standard.string(forKey: "notify.term") {
// save current grades
jwxt.getGradeList(year: yearInt, term: Int(term)!, completion: { (success, object) in
if success, let grades = object as? [Grade] {
UserDefaults.standard.set(grades, forKey: "monitorGrades")
}
})
isUnwindingFromFilter = false
}
}
}
| bsd-3-clause | 6a5f639ca4c6801c93e8010f0b43b5a1 | 33.5 | 133 | 0.5676 | 5.001986 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/design-hashset.swift | 1 | 872 | class MyHashSet {
private var visited: [Bool]
private var length: Int
init() {
self.visited = []
self.length = 0
}
// - Complexity:
// - Time: O(n),
func add(_ key: Int) {
if key >= self.length {
self.visited += Array(repeating: false, count: key - visited.count + 1)
self.length = key + 1
}
visited[key] = true
}
func remove(_ key: Int) {
if key < self.length {
visited[key] = false
}
}
func contains(_ key: Int) -> Bool {
if key < self.length {
return visited[key]
}
return false
}
}
/**
* Your MyHashSet object will be instantiated and called as such:
* let obj = MyHashSet()
* obj.add(key)
* obj.remove(key)
* let ret_3: Bool = obj.contains(key)
*/
| mit | fdb9cc349d409e17d746cf6e53e1f7a5 | 19.761905 | 83 | 0.488532 | 3.80786 | false | false | false | false |
treejames/firefox-ios | Client/Frontend/Settings/SettingsTableViewController.swift | 2 | 39520 | /* 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 Account
import Base32
import Shared
import UIKit
import XCGLogger
private var ShowDebugSettings: Bool = false
private var DebugSettingsClickCount: Int = 0
// A base TableViewCell, to help minimize initialization and allow recycling.
class SettingsTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
indentationWidth = 0
layoutMargins = UIEdgeInsetsZero
// So that the seperator line goes all the way to the left edge.
separatorInset = UIEdgeInsetsZero
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// A base setting class that shows a title. You probably want to subclass this, not use it directly.
class Setting {
private var cell: UITableViewCell?
private var _title: NSAttributedString?
// The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy.
var url: NSURL? { return nil }
// The title shown on the pref.
var title: NSAttributedString? { return _title }
// An optional second line of text shown on the pref.
var status: NSAttributedString? { return nil }
// Whether or not to show this pref.
var hidden: Bool { return false }
var style: UITableViewCellStyle { return .Subtitle }
var accessoryType: UITableViewCellAccessoryType { return .None }
// Called when the cell is setup. Call if you need the default behaviour.
func onConfigureCell(cell: UITableViewCell) {
cell.detailTextLabel?.attributedText = status
cell.textLabel?.attributedText = title
cell.accessoryType = accessoryType
cell.accessoryView = nil
}
// Called when the pref is tapped.
func onClick(navigationController: UINavigationController?) { return }
// Helper method to set up and push a SettingsContentViewController
func setUpAndPushSettingsContentViewController(navigationController: UINavigationController?) {
if let url = self.url {
let viewController = SettingsContentViewController()
viewController.settingsTitle = self.title
viewController.url = url
navigationController?.pushViewController(viewController, animated: true)
}
}
init(title: NSAttributedString? = nil) {
self._title = title
}
}
// A setting in the sections panel. Contains a sublist of Settings
class SettingSection : Setting {
private let children: [Setting]
init(title: NSAttributedString? = nil, children: [Setting]) {
self.children = children
super.init(title: title)
}
var count: Int {
var count = 0
for setting in children {
if !setting.hidden {
count++
}
}
return count
}
subscript(val: Int) -> Setting? {
var i = 0
for setting in children {
if !setting.hidden {
if i == val {
return setting
}
i++
}
}
return nil
}
}
// A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to
// the fxAccount happen.
private class AccountSetting: Setting, FxAContentViewControllerDelegate {
let settings: SettingsTableViewController
var profile: Profile {
return settings.profile
}
override var title: NSAttributedString? { return nil }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
private override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
if settings.profile.getAccount() != nil {
cell.selectionStyle = .None
}
}
override var accessoryType: UITableViewCellAccessoryType { return .None }
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void {
if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil {
// The /settings endpoint sends a partial "login"; ignore it entirely.
NSLog("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.")
return
}
// TODO: Error handling.
let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)!
settings.profile.setAccount(account)
// Reload the data to reflect the new Account immediately.
settings.tableView.reloadData()
// And start advancing the Account state in the background as well.
settings.SELrefresh()
settings.navigationController?.popToRootViewControllerAnimated(true)
}
func contentViewControllerDidCancel(viewController: FxAContentViewController) {
NSLog("didCancel")
settings.navigationController?.popToRootViewControllerAnimated(true)
}
}
private class WithAccountSetting: AccountSetting {
override var hidden: Bool { return !profile.hasAccount() }
}
private class WithoutAccountSetting: AccountSetting {
override var hidden: Bool { return profile.hasAccount() }
}
// Sync setting for connecting a Firefox Account. Shown when we don't have an account.
private class ConnectSetting: WithoutAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Sign in", comment: "Text message / button in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
let viewController = FxAContentViewController()
viewController.delegate = self
viewController.url = settings.profile.accountConfiguration.signInURL
navigationController?.pushViewController(viewController, animated: true)
}
}
// Sync setting for disconnecting a Firefox Account. Shown when we have an account.
private class DisconnectSetting: WithAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .None }
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Log Out", comment: "Button in settings screen to disconnect from your account"), attributes: [NSForegroundColorAttributeName: UIConstants.DestructiveRed])
}
override func onClick(navigationController: UINavigationController?) {
let alertController = UIAlertController(
title: NSLocalizedString("Log Out?", comment: "Title of the 'log out firefox account' alert"),
message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Text of the 'log out firefox account' alert"),
preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(
UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button in the 'log out firefox account' alert"), style: .Cancel) { (action) in
// Do nothing.
})
alertController.addAction(
UIAlertAction(title: NSLocalizedString("Log Out", comment: "Disconnect button in the 'log out firefox account' alert"), style: .Destructive) { (action) in
self.settings.profile.removeAccount()
// Refresh, to show that we no longer have an Account immediately.
self.settings.SELrefresh()
})
navigationController?.presentViewController(alertController, animated: true, completion: nil)
}
}
private class SyncNowSetting: WithAccountSetting {
private let syncNowTitle = NSAttributedString(string: NSLocalizedString("Sync Now", comment: "Sync Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont.systemFontOfSize(UIConstants.DefaultStandardFontSize, weight: UIFontWeightRegular)])
private let log = Logger.browserLogger
override var accessoryType: UITableViewCellAccessoryType { return .None }
override var style: UITableViewCellStyle { return .Value1 }
override var title: NSAttributedString? {
return syncNowTitle
}
override func onConfigureCell(cell: UITableViewCell) {
cell.textLabel?.attributedText = title
cell.accessoryType = accessoryType
cell.accessoryView = nil
self.cell = cell
}
override func onClick(navigationController: UINavigationController?) {
if let cell = self.cell {
cell.userInteractionEnabled = false
cell.textLabel?.attributedText = NSAttributedString(string: NSLocalizedString("Syncing…", comment: "Syncing Firefox Account"), attributes: [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(UIConstants.DefaultStandardFontSize, weight: UIFontWeightRegular)])
profile.syncManager.syncEverything().uponQueue(dispatch_get_main_queue()) { result in
if result.isSuccess {
self.log.debug("Sync succeeded.")
} else {
self.log.debug("Sync failed.")
}
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * Int64(NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
cell.textLabel?.attributedText = self.syncNowTitle
cell.userInteractionEnabled = true
})
}
}
}
// Sync setting that shows the current Firefox Account status.
private class AccountStatusSetting: WithAccountSetting {
override var accessoryType: UITableViewCellAccessoryType {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .NeedsVerification:
// We link to the resend verification email page.
return .DisclosureIndicator
case .NeedsPassword:
// We link to the re-enter password page.
return .DisclosureIndicator
case .None, .NeedsUpgrade:
// In future, we'll want to link to /settings and an upgrade page, respectively.
return .None
}
}
return .DisclosureIndicator
}
override var title: NSAttributedString? {
if let account = profile.getAccount() {
return NSAttributedString(string: account.email, attributes: [NSFontAttributeName: UIConstants.DefaultStandardFontBold, NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
return nil
}
override var status: NSAttributedString? {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .None:
return nil
case .NeedsVerification:
return NSAttributedString(string: NSLocalizedString("Verify your email address.", comment: "Text message in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
case .NeedsPassword:
let string = NSLocalizedString("Enter your password to connect.", comment: "Text message in the settings table view")
let range = NSRange(location: 0, length: count(string))
let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1)
let attrs : [NSObject : AnyObject]? = [NSForegroundColorAttributeName : orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
case .NeedsUpgrade:
let string = NSLocalizedString("Upgrade Firefox to connect.", comment: "Text message in the settings table view")
let range = NSRange(location: 0, length: count(string))
let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1)
let attrs : [NSObject : AnyObject]? = [NSForegroundColorAttributeName : orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
}
}
return nil
}
override func onClick(navigationController: UINavigationController?) {
let viewController = FxAContentViewController()
viewController.delegate = self
if let account = profile.getAccount() {
switch account.actionNeeded {
case .NeedsVerification:
let cs = NSURLComponents(URL: account.configuration.settingsURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs?.URL
case .NeedsPassword:
let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs?.URL
case .None, .NeedsUpgrade:
// In future, we'll want to link to /settings and an upgrade page, respectively.
if let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) {
cs.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs.URL
}
}
}
navigationController?.pushViewController(viewController, animated: true)
}
}
// For great debugging!
private class RequirePasswordDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsPassword {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.makeSeparated()
settings.tableView.reloadData()
}
}
// For great debugging!
private class RequireUpgradeDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsUpgrade {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.makeDoghouse()
settings.tableView.reloadData()
}
}
// For great debugging!
private class ForgetSyncAuthStateDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.syncAuthState.invalidate()
settings.tableView.reloadData()
}
}
// For great debugging!
private class HiddenSetting: Setting {
let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var hidden: Bool {
return !ShowDebugSettings
}
}
private class DeleteExportedDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
if let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as? String {
let browserDB = documentsPath.stringByAppendingPathComponent("browser.db")
var err: NSError?
NSFileManager.defaultManager().removeItemAtPath(browserDB, error: &err)
}
}
}
private class ExportBrowserDataSetting: HiddenSetting {
override var title: NSAttributedString? {
// Not localized for now.
return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
if let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as? String {
let browserDB = documentsPath.stringByAppendingPathComponent("browser.db")
self.settings.profile.files.copy("browser.db", toAbsolutePath: browserDB)
}
}
}
// Show the current version of Firefox
private class VersionSetting : Setting {
let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var title: NSAttributedString? {
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String
return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
private override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.selectionStyle = .None
}
override func onClick(navigationController: UINavigationController?) {
if AppConstants.BuildChannel != .Aurora {
DebugSettingsClickCount += 1
if DebugSettingsClickCount >= 5 {
DebugSettingsClickCount = 0
ShowDebugSettings = !ShowDebugSettings
settings.tableView.reloadData()
}
}
}
}
// Opens the the license page in a new tab
private class LicenseAndAcknowledgementsSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
return NSURL(string: WebServer.sharedInstance.URLForResource("license", module: "about"))
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the on-boarding screen again
private class ShowIntroductionSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
let rootNavigationController = appDelegate.rootViewController
appDelegate.browserViewController.presentIntroViewController(force: true)
}
})
}
}
private class SendFeedbackSetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Show an input.mozilla.org page where people can submit feedback"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
return NSURL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)")
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
// Opens the the SUMO page in a new tab
private class OpenSupportPageSetting: Setting {
init() {
super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
let rootNavigationController = appDelegate.rootViewController
rootNavigationController.popViewControllerAnimated(true)
if let url = NSURL(string: "https://support.mozilla.org/products/ios") {
appDelegate.browserViewController.openURLInNewTab(url)
}
}
})
}
}
class UseCompactTabLayoutSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Use Compact Tabs", comment: "Setting to enable compact tabs in the tab overview"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = profile.prefs.boolForKey("CompactTabLayout") ?? true
cell.accessoryView = control
cell.selectionStyle = .None
}
@objc func switchValueChanged(control: UISwitch) {
profile.prefs.setBool(control.on, forKey: "CompactTabLayout")
}
}
// Opens the search settings pane
private class SearchSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var style: UITableViewCellStyle { return .Value1 }
override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
let viewController = SearchSettingsTableViewController()
viewController.model = profile.searchEngines
navigationController?.pushViewController(viewController, animated: true)
}
}
private class ClearPrivateDataSetting: Setting {
let profile: Profile
var tabManager: TabManager!
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
let clearTitle = NSLocalizedString("Clear Private Data", comment: "Label used as an item in Settings. When touched it will open a dialog prompting the user to make sure they want to clear all of their private data.")
super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
let clearable = EverythingClearable(profile: profile, tabmanager: tabManager)
var title: String { return NSLocalizedString("Clear Everything", tableName: "ClearPrivateData", comment: "Title of the Clear private data dialog.") }
var message: String { return NSLocalizedString("Are you sure you want to clear all of your data? This will also close all open tabs.", tableName: "ClearPrivateData", comment: "Message shown in the dialog prompting users if they want to clear everything") }
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let clearString = NSLocalizedString("Clear", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to Clear private data dialog")
alert.addAction(UIAlertAction(title: clearString, style: UIAlertActionStyle.Destructive, handler: { (action) -> Void in
clearable.clear() >>== { NSNotificationCenter.defaultCenter().postNotificationName(NotificationPrivateDataCleared, object: nil) }
}))
let cancelString = NSLocalizedString("Cancel", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to cancel clear private data dialog")
alert.addAction(UIAlertAction(title: cancelString, style: UIAlertActionStyle.Cancel, handler: { (action) -> Void in }))
navigationController?.presentViewController(alert, animated: true) { () -> Void in }
}
}
private class SendCrashReportsSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Send Crash Reports", comment: "Setting to enable the sending of crash reports"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = profile.prefs.boolForKey("crashreports.send.always") ?? false
cell.accessoryView = control
}
@objc func switchValueChanged(control: UISwitch) {
profile.prefs.setBool(control.on, forKey: "crashreports.send.always")
configureActiveCrashReporter(profile.prefs.boolForKey("crashreports.send.always"))
}
}
private class PrivacyPolicySetting: Setting {
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override var url: NSURL? {
return NSURL(string: "https://www.mozilla.org/privacy/firefox/")
}
override func onClick(navigationController: UINavigationController?) {
setUpAndPushSettingsContentViewController(navigationController)
}
}
private class PopupBlockingSettings: Setting {
let prefs: Prefs
let tabManager: TabManager!
let prefKey = "blockPopups"
init(settings: SettingsTableViewController) {
self.prefs = settings.profile.prefs
self.tabManager = settings.tabManager
let title = NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting")
let attributes = [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]
super.init(title: NSAttributedString(string: title, attributes: attributes))
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = prefs.boolForKey(prefKey) ?? true
cell.accessoryView = control
cell.selectionStyle = .None
}
@objc func switchValueChanged(toggle: UISwitch) {
prefs.setObject(toggle.on, forKey: prefKey)
}
}
// The base settings view controller.
class SettingsTableViewController: UITableViewController {
private let Identifier = "CellIdentifier"
private let SectionHeaderIdentifier = "SectionHeaderIdentifier"
private var settings = [SettingSection]()
var profile: Profile!
var tabManager: TabManager!
override func viewDidLoad() {
super.viewDidLoad()
let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title")
let accountDebugSettings: [Setting]
if AppConstants.BuildChannel != .Aurora {
accountDebugSettings = [
// Debug settings:
RequirePasswordDebugSetting(settings: self),
RequireUpgradeDebugSetting(settings: self),
ForgetSyncAuthStateDebugSetting(settings: self),
]
} else {
accountDebugSettings = []
}
var generalSettings = [
SearchSetting(settings: self),
PopupBlockingSettings(settings: self),
]
// There is nothing to show in the Customize section if we don't include the compact tab layout
// setting on iPad. When more options are added that work on both device types, this logic can
// be changed.
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
generalSettings += [UseCompactTabLayoutSetting(settings: self)]
}
settings += [
SettingSection(title: nil, children: [
// Without a Firefox Account:
ConnectSetting(settings: self),
// With a Firefox Account:
AccountStatusSetting(settings: self),
SyncNowSetting(settings: self)
] + accountDebugSettings),
SettingSection(title: NSAttributedString(string: NSLocalizedString("General", comment: "General settings section title")), children: generalSettings)
]
settings += [
SettingSection(title: NSAttributedString(string: privacyTitle), children: [
ClearPrivateDataSetting(settings: self),
SendCrashReportsSetting(settings: self),
PrivacyPolicySetting(),
]),
SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [
ShowIntroductionSetting(settings: self),
SendFeedbackSetting(),
OpenSupportPageSetting()
]),
SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [
VersionSetting(settings: self),
LicenseAndAcknowledgementsSetting(),
DisconnectSetting(settings: self),
ExportBrowserDataSetting(settings: self),
DeleteExportedDataSetting(settings: self),
])
]
navigationItem.title = NSLocalizedString("Settings", comment: "Settings")
navigationItem.leftBarButtonItem = UIBarButtonItem(
title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"),
style: UIBarButtonItemStyle.Done,
target: navigationController, action: "SELdone")
tableView.registerClass(SettingsTableViewCell.self, forCellReuseIdentifier: Identifier)
tableView.registerClass(SettingsTableSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.tableFooterView = SettingsTableFooterView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 128))
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
SELrefresh()
}
@objc private func SELrefresh() {
// Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app.
if let account = self.profile.getAccount() {
account.advance().upon { _ in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.reloadData()
}
}
} else {
self.tableView.reloadData()
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
var cell: UITableViewCell!
if let status = setting.status {
// Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell.
// I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account.
// Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it.
cell = SettingsTableViewCell(style: setting.style, reuseIdentifier: nil)
} else {
cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as! UITableViewCell
}
setting.onConfigureCell(cell)
return cell
}
return tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as! UITableViewCell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return settings.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = settings[section]
return section.count
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderView
let section = settings[section]
if let sectionTitle = section.title?.string {
headerView.titleLabel.text = sectionTitle.uppercaseString
}
return headerView
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// empty headers should be 13px high, but headers with text should be 44
var height: CGFloat = 13
let section = settings[section]
if let sectionTitle = section.title {
if sectionTitle.length > 0 {
height = 44
}
}
return height
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
setting.onClick(navigationController)
}
return nil
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (indexPath.section == 0 && indexPath.row == 0) { return 64 } //make account/sign-in row taller, as per design specs
return 44
}
}
class SettingsTableFooterView: UITableViewHeaderFooterView {
var logo: UIImageView = {
var image = UIImageView(image: UIImage(named: "settingsFlatfox"))
image.contentMode = UIViewContentMode.Center
return image
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
var topBorder = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: 0.5))
topBorder.backgroundColor = UIConstants.TableViewSeparatorColor
addSubview(topBorder)
addSubview(logo)
logo.snp_makeConstraints { (make) -> Void in
make.centerY.centerX.equalTo(self)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class SettingsTableSectionHeaderView: UITableViewHeaderFooterView {
var titleLabel: UILabel = {
var headerLabel = UILabel()
var frame = headerLabel.frame
frame.origin.x = 15
frame.origin.y = 25
headerLabel.frame = frame
headerLabel.textColor = UIConstants.TableViewHeaderTextColor
headerLabel.font = UIFont.systemFontOfSize(12.0, weight: UIFontWeightRegular)
return headerLabel
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
addSubview(titleLabel)
self.clipsToBounds = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let topBorder = CALayer()
topBorder.frame = CGRectMake(0.0, 0.0, rect.size.width, 0.5)
topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
layer.addSublayer(topBorder)
let bottomBorder = CALayer()
bottomBorder.frame = CGRectMake(0.0, rect.size.height - 0.5, rect.size.width, 0.5)
bottomBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
layer.addSublayer(bottomBorder)
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.sizeToFit()
}
}
| mpl-2.0 | 7b0ffa73806024c57b28668e4d92d56f | 42.186885 | 317 | 0.687317 | 5.708755 | false | false | false | false |
kzaher/RxSwift | RxCocoa/Foundation/NSObject+Rx.swift | 3 | 19118 | //
// NSObject+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !os(Linux)
import Foundation
import RxSwift
#if SWIFT_PACKAGE && !DISABLE_SWIZZLING && !os(Linux)
import RxCocoaRuntime
#endif
#if !DISABLE_SWIZZLING && !os(Linux)
private var deallocatingSubjectTriggerContext: UInt8 = 0
private var deallocatingSubjectContext: UInt8 = 0
#endif
private var deallocatedSubjectTriggerContext: UInt8 = 0
private var deallocatedSubjectContext: UInt8 = 0
#if !os(Linux)
/**
KVO is a tricky mechanism.
When observing child in a ownership hierarchy, usually retaining observing target is wanted behavior.
When observing parent in a ownership hierarchy, usually retaining target isn't wanter behavior.
KVO with weak references is especially tricky. For it to work, some kind of swizzling is required.
That can be done by
* replacing object class dynamically (like KVO does)
* by swizzling `dealloc` method on all instances for a class.
* some third method ...
Both approaches can fail in certain scenarios:
* problems arise when swizzlers return original object class (like KVO does when nobody is observing)
* Problems can arise because replacing dealloc method isn't atomic operation (get implementation,
set implementation).
Second approach is chosen. It can fail in case there are multiple libraries dynamically trying
to replace dealloc method. In case that isn't the case, it should be ok.
*/
extension Reactive where Base: NSObject {
/**
Observes values on `keyPath` starting from `self` with `options` and retains `self` if `retainSelf` is set.
`observe` is just a simple and performant wrapper around KVO mechanism.
* it can be used to observe paths starting from `self` or from ancestors in ownership graph (`retainSelf = false`)
* it can be used to observe paths starting from descendants in ownership graph (`retainSelf = true`)
* the paths have to consist only of `strong` properties, otherwise you are risking crashing the system by not unregistering KVO observer before dealloc.
If support for weak properties is needed or observing arbitrary or unknown relationships in the
ownership tree, `observeWeakly` is the preferred option.
- parameter keyPath: Key path of property names to observe.
- parameter options: KVO mechanism notification options.
- parameter retainSelf: Retains self during observation if set `true`.
- returns: Observable sequence of objects on `keyPath`.
*/
public func observe<Element>(_ type: Element.Type,
_ keyPath: String,
options: KeyValueObservingOptions = [.new, .initial],
retainSelf: Bool = true) -> Observable<Element?> {
KVOObservable(object: self.base, keyPath: keyPath, options: options, retainTarget: retainSelf).asObservable()
}
/**
Observes values at the provided key path using the provided options.
- parameter keyPath: A key path between the object and one of its properties.
- parameter options: Key-value observation options, defaults to `.new` and `.initial`.
- note: When the object is deallocated, a completion event is emitted.
- returns: An observable emitting value changes at the provided key path.
*/
public func observe<Element>(_ keyPath: KeyPath<Base, Element>,
options: NSKeyValueObservingOptions = [.new, .initial]) -> Observable<Element> {
Observable<Element>.create { [weak base] observer in
let observation = base?.observe(keyPath, options: options) { obj, _ in
observer.on(.next(obj[keyPath: keyPath]))
}
return Disposables.create { observation?.invalidate() }
}
.take(until: base.rx.deallocated)
}
}
#endif
#if !DISABLE_SWIZZLING && !os(Linux)
// KVO
extension Reactive where Base: NSObject {
/**
Observes values on `keyPath` starting from `self` with `options` and doesn't retain `self`.
It can be used in all cases where `observe` can be used and additionally
* because it won't retain observed target, it can be used to observe arbitrary object graph whose ownership relation is unknown
* it can be used to observe `weak` properties
**Since it needs to intercept object deallocation process it needs to perform swizzling of `dealloc` method on observed object.**
- parameter keyPath: Key path of property names to observe.
- parameter options: KVO mechanism notification options.
- returns: Observable sequence of objects on `keyPath`.
*/
public func observeWeakly<Element>(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable<Element?> {
return observeWeaklyKeyPathFor(self.base, keyPath: keyPath, options: options)
.map { n in
return n as? Element
}
}
}
#endif
// Dealloc
extension Reactive where Base: AnyObject {
/**
Observable sequence of object deallocated events.
After object is deallocated one `()` element will be produced and sequence will immediately complete.
- returns: Observable sequence of object deallocated events.
*/
public var deallocated: Observable<Void> {
return self.synchronized {
if let deallocObservable = objc_getAssociatedObject(self.base, &deallocatedSubjectContext) as? DeallocObservable {
return deallocObservable.subject
}
let deallocObservable = DeallocObservable()
objc_setAssociatedObject(self.base, &deallocatedSubjectContext, deallocObservable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return deallocObservable.subject
}
}
#if !DISABLE_SWIZZLING && !os(Linux)
/**
Observable sequence of message arguments that completes when object is deallocated.
Each element is produced before message is invoked on target object. `methodInvoked`
exists in case observing of invoked messages is needed.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
In case some argument is `nil`, instance of `NSNull()` will be sent.
- returns: Observable sequence of arguments passed to `selector` method.
*/
public func sentMessage(_ selector: Selector) -> Observable<[Any]> {
return self.synchronized {
// in case of dealloc selector replay subject behavior needs to be used
if selector == deallocSelector {
return self.deallocating.map { _ in [] }
}
do {
let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector)
return proxy.messageSent.asObservable()
}
catch let e {
return Observable.error(e)
}
}
}
/**
Observable sequence of message arguments that completes when object is deallocated.
Each element is produced after message is invoked on target object. `sentMessage`
exists in case interception of sent messages before they were invoked is needed.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
In case some argument is `nil`, instance of `NSNull()` will be sent.
- returns: Observable sequence of arguments passed to `selector` method.
*/
public func methodInvoked(_ selector: Selector) -> Observable<[Any]> {
return self.synchronized {
// in case of dealloc selector replay subject behavior needs to be used
if selector == deallocSelector {
return self.deallocated.map { _ in [] }
}
do {
let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector)
return proxy.methodInvoked.asObservable()
}
catch let e {
return Observable.error(e)
}
}
}
/**
Observable sequence of object deallocating events.
When `dealloc` message is sent to `self` one `()` element will be produced and after object is deallocated sequence
will immediately complete.
In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`.
- returns: Observable sequence of object deallocating events.
*/
public var deallocating: Observable<()> {
return self.synchronized {
do {
let proxy: DeallocatingProxy = try self.registerMessageInterceptor(deallocSelector)
return proxy.messageSent.asObservable()
}
catch let e {
return Observable.error(e)
}
}
}
private func registerMessageInterceptor<T: MessageInterceptorSubject>(_ selector: Selector) throws -> T {
let rxSelector = RX_selector(selector)
let selectorReference = RX_reference_from_selector(rxSelector)
let subject: T
if let existingSubject = objc_getAssociatedObject(self.base, selectorReference) as? T {
subject = existingSubject
}
else {
subject = T()
objc_setAssociatedObject(
self.base,
selectorReference,
subject,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
if subject.isActive {
return subject
}
var error: NSError?
let targetImplementation = RX_ensure_observing(self.base, selector, &error)
if targetImplementation == nil {
throw error?.rxCocoaErrorForTarget(self.base) ?? RxCocoaError.unknown
}
subject.targetImplementation = targetImplementation!
return subject
}
#endif
}
// MARK: Message interceptors
#if !DISABLE_SWIZZLING && !os(Linux)
private protocol MessageInterceptorSubject: class {
init()
var isActive: Bool {
get
}
var targetImplementation: IMP { get set }
}
private final class DeallocatingProxy
: MessageInterceptorSubject
, RXDeallocatingObserver {
typealias Element = ()
let messageSent = ReplaySubject<()>.create(bufferSize: 1)
@objc var targetImplementation: IMP = RX_default_target_implementation()
var isActive: Bool {
return self.targetImplementation != RX_default_target_implementation()
}
init() {
}
@objc func deallocating() {
self.messageSent.on(.next(()))
}
deinit {
self.messageSent.on(.completed)
}
}
private final class MessageSentProxy
: MessageInterceptorSubject
, RXMessageSentObserver {
typealias Element = [AnyObject]
let messageSent = PublishSubject<[Any]>()
let methodInvoked = PublishSubject<[Any]>()
@objc var targetImplementation: IMP = RX_default_target_implementation()
var isActive: Bool {
return self.targetImplementation != RX_default_target_implementation()
}
init() {
}
@objc func messageSent(withArguments arguments: [Any]) {
self.messageSent.on(.next(arguments))
}
@objc func methodInvoked(withArguments arguments: [Any]) {
self.methodInvoked.on(.next(arguments))
}
deinit {
self.messageSent.on(.completed)
self.methodInvoked.on(.completed)
}
}
#endif
private final class DeallocObservable {
let subject = ReplaySubject<Void>.create(bufferSize:1)
init() {
}
deinit {
self.subject.on(.next(()))
self.subject.on(.completed)
}
}
// MARK: KVO
#if !os(Linux)
private protocol KVOObservableProtocol {
var target: AnyObject { get }
var keyPath: String { get }
var retainTarget: Bool { get }
var options: KeyValueObservingOptions { get }
}
private final class KVOObserver
: _RXKVOObserver
, Disposable {
typealias Callback = (Any?) -> Void
var retainSelf: KVOObserver?
init(parent: KVOObservableProtocol, callback: @escaping Callback) {
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
super.init(target: parent.target, retainTarget: parent.retainTarget, keyPath: parent.keyPath, options: parent.options.nsOptions, callback: callback)
self.retainSelf = self
}
override func dispose() {
super.dispose()
self.retainSelf = nil
}
deinit {
#if TRACE_RESOURCES
_ = Resources.decrementTotal()
#endif
}
}
private final class KVOObservable<Element>
: ObservableType
, KVOObservableProtocol {
typealias Element = Element?
unowned var target: AnyObject
var strongTarget: AnyObject?
var keyPath: String
var options: KeyValueObservingOptions
var retainTarget: Bool
init(object: AnyObject, keyPath: String, options: KeyValueObservingOptions, retainTarget: Bool) {
self.target = object
self.keyPath = keyPath
self.options = options
self.retainTarget = retainTarget
if retainTarget {
self.strongTarget = object
}
}
func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element? {
let observer = KVOObserver(parent: self) { value in
if value as? NSNull != nil {
observer.on(.next(nil))
return
}
observer.on(.next(value as? Element))
}
return Disposables.create(with: observer.dispose)
}
}
private extension KeyValueObservingOptions {
var nsOptions: NSKeyValueObservingOptions {
var result: UInt = 0
if self.contains(.new) {
result |= NSKeyValueObservingOptions.new.rawValue
}
if self.contains(.initial) {
result |= NSKeyValueObservingOptions.initial.rawValue
}
return NSKeyValueObservingOptions(rawValue: result)
}
}
#endif
#if !DISABLE_SWIZZLING && !os(Linux)
private func observeWeaklyKeyPathFor(_ target: NSObject, keyPath: String, options: KeyValueObservingOptions) -> Observable<AnyObject?> {
let components = keyPath.components(separatedBy: ".").filter { $0 != "self" }
let observable = observeWeaklyKeyPathFor(target, keyPathSections: components, options: options)
.finishWithNilWhenDealloc(target)
if !options.isDisjoint(with: .initial) {
return observable
}
else {
return observable
.skip(1)
}
}
// This should work correctly
// Identifiers can't contain `,`, so the only place where `,` can appear
// is as a delimiter.
// This means there is `W` as element in an array of property attributes.
private func isWeakProperty(_ properyRuntimeInfo: String) -> Bool {
properyRuntimeInfo.range(of: ",W,") != nil
}
private extension ObservableType where Element == AnyObject? {
func finishWithNilWhenDealloc(_ target: NSObject)
-> Observable<AnyObject?> {
let deallocating = target.rx.deallocating
return deallocating
.map { _ in
return Observable.just(nil)
}
.startWith(self.asObservable())
.switchLatest()
}
}
private func observeWeaklyKeyPathFor(
_ target: NSObject,
keyPathSections: [String],
options: KeyValueObservingOptions
) -> Observable<AnyObject?> {
weak var weakTarget: AnyObject? = target
let propertyName = keyPathSections[0]
let remainingPaths = Array(keyPathSections[1..<keyPathSections.count])
let property = class_getProperty(object_getClass(target), propertyName)
if property == nil {
return Observable.error(RxCocoaError.invalidPropertyName(object: target, propertyName: propertyName))
}
let propertyAttributes = property_getAttributes(property!)
// should dealloc hook be in place if week property, or just create strong reference because it doesn't matter
let isWeak = isWeakProperty(propertyAttributes.map(String.init) ?? "")
let propertyObservable = KVOObservable(object: target, keyPath: propertyName, options: options.union(.initial), retainTarget: false) as KVOObservable<AnyObject>
// KVO recursion for value changes
return propertyObservable
.flatMapLatest { (nextTarget: AnyObject?) -> Observable<AnyObject?> in
if nextTarget == nil {
return Observable.just(nil)
}
let nextObject = nextTarget! as? NSObject
let strongTarget: AnyObject? = weakTarget
if nextObject == nil {
return Observable.error(RxCocoaError.invalidObjectOnKeyPath(object: nextTarget!, sourceObject: strongTarget ?? NSNull(), propertyName: propertyName))
}
// if target is alive, then send change
// if it's deallocated, don't send anything
if strongTarget == nil {
return Observable.empty()
}
let nextElementsObservable = keyPathSections.count == 1
? Observable.just(nextTarget)
: observeWeaklyKeyPathFor(nextObject!, keyPathSections: remainingPaths, options: options)
if isWeak {
return nextElementsObservable
.finishWithNilWhenDealloc(nextObject!)
}
else {
return nextElementsObservable
}
}
}
#endif
// MARK: Constants
private let deallocSelector = NSSelectorFromString("dealloc")
// MARK: AnyObject + Reactive
extension Reactive where Base: AnyObject {
func synchronized<T>( _ action: () -> T) -> T {
objc_sync_enter(self.base)
let result = action()
objc_sync_exit(self.base)
return result
}
}
extension Reactive where Base: AnyObject {
/**
Helper to make sure that `Observable` returned from `createCachedObservable` is only created once.
This is important because there is only one `target` and `action` properties on `NSControl` or `UIBarButtonItem`.
*/
func lazyInstanceObservable<T: AnyObject>(_ key: UnsafeRawPointer, createCachedObservable: () -> T) -> T {
if let value = objc_getAssociatedObject(self.base, key) {
return value as! T
}
let observable = createCachedObservable()
objc_setAssociatedObject(self.base, key, observable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return observable
}
}
#endif
| mit | 1ce65e27653453b083905f218518444b | 32.59754 | 169 | 0.636031 | 5.172348 | false | false | false | false |
fiveagency/ios-five-utils | Example/Classes/ViewControllers/ContentCell/ContentCell.swift | 1 | 5370 | //
// ContentCell.swift
// Example
//
// Created by Miran Brajsa on 21/09/16.
// Copyright © 2016 Five Agency. All rights reserved.
//
import Foundation
import UIKit
class ContentCell: UITableViewCell {
private var viewModel: ContentCellViewModel?
@IBOutlet private weak var headerView: UIView!
@IBOutlet private weak var headerMarkerView: UIView!
@IBOutlet private weak var exampleNumberLabel: UILabel!
@IBOutlet private weak var descriptionView: UIView!
@IBOutlet private weak var descriptionLabel: UILabel!
@IBOutlet private weak var resultTitleLabel: UILabel!
@IBOutlet private weak var resultLabel: UILabel!
@IBOutlet private weak var actionButtonView: UIView!
@IBOutlet private weak var actionButton: UIButton!
@IBOutlet private weak var sliderView: UIView!
@IBOutlet private weak var slider: UISlider!
@IBOutlet private weak var firstSliderTitleLabel: UILabel!
@IBOutlet private weak var firstSliderResultTitleLabel: UILabel!
@IBOutlet private weak var secondSliderResultView: UIView!
@IBOutlet private weak var secondSliderTitleLabel: UILabel!
@IBOutlet private weak var secondSliderResultTitleLabel: UILabel!
override func awakeFromNib() {
setupAppearance()
}
func setup(withViewModel viewModel: ContentCellViewModel) {
self.viewModel = viewModel
setupContent()
setupLayout()
}
private func setupAppearance() {
guard
let headerTitleFont = UIFont.headerTitleText,
let descriptionLabelFont = UIFont.descriptionText,
let actionButtonFont = UIFont.buttonText,
let resultLabelFont = UIFont.resultLabelText,
let resultValueLabelFont = UIFont.resultValueText
else {
return
}
sliderView.backgroundColor = UIColor.white
let thumbImage = UIImage(named: "SliderDot")
slider.setThumbImage(thumbImage, for: .normal)
slider.setThumbImage(thumbImage, for: .highlighted)
slider.minimumTrackTintColor = UIColor.highlightRed
slider.maximumTrackTintColor = UIColor.headerLightGray
firstSliderTitleLabel.font = resultLabelFont
firstSliderTitleLabel.textColor = UIColor.descriptionLightGray
firstSliderResultTitleLabel.font = resultValueLabelFont
firstSliderResultTitleLabel.textColor = UIColor.descriptionDarkGray
secondSliderTitleLabel.font = resultLabelFont
secondSliderTitleLabel.textColor = UIColor.descriptionLightGray
secondSliderResultTitleLabel.font = resultValueLabelFont
secondSliderResultTitleLabel.textColor = UIColor.descriptionDarkGray
headerView.backgroundColor = UIColor.headerLightGray
headerMarkerView.backgroundColor = UIColor.headerDarkGray
exampleNumberLabel.font = headerTitleFont
exampleNumberLabel.textColor = UIColor.headerTitleGray
descriptionView.backgroundColor = UIColor.white
descriptionLabel.font = descriptionLabelFont
descriptionLabel.textColor = UIColor.descriptionDarkGray
actionButtonView.backgroundColor = UIColor.white
actionButton.titleLabel?.font = actionButtonFont
actionButton.setTitleColor(UIColor.highlightRed, for: .normal)
resultTitleLabel.font = resultLabelFont
resultTitleLabel.textColor = UIColor.descriptionLightGray
resultLabel.font = resultValueLabelFont
resultLabel.textColor = UIColor.descriptionDarkGray
}
private func setupContent() {
guard let viewModel = viewModel else { return }
exampleNumberLabel.text = viewModel.exampleTitle
descriptionLabel.text = viewModel.description
actionButton.setTitle(viewModel.actionButtonTitle, for: .normal)
resultLabel.text = viewModel.initialResult
firstSliderTitleLabel.text = viewModel.firstSliderTitle
secondSliderTitleLabel.text = viewModel.secondSliderTitle
let (firstResult, secondResult) = viewModel.initialSliderResults
firstSliderResultTitleLabel.text = firstResult
secondSliderResultTitleLabel.text = secondResult
if let sliderConfiguration = viewModel.sliderConfiguration {
slider.minimumValue = sliderConfiguration.minimumValue
slider.maximumValue = sliderConfiguration.maximumValue
slider.value = sliderConfiguration.startingValue
}
}
private func setupLayout() {
guard let viewModel = viewModel else { return }
actionButtonView.isHidden = !viewModel.shouldDisplayActionButtonView()
sliderView.isHidden = !viewModel.shouldDisplaySliderView()
secondSliderResultView.isHidden = !viewModel.shouldDisplaySecondSliderResultView()
}
@IBAction private func actionButtonTapped(_ sender: AnyObject) {
guard let viewModel = viewModel else { return }
let result = viewModel.updateButtonTapResult()
resultLabel.text = result
}
@IBAction private func sliderValueChanged(_ sender: UISlider) {
guard let viewModel = viewModel else { return }
let (firstResult, secondResult) = viewModel.updateSliderResults(newValue: sender.value)
firstSliderResultTitleLabel.text = firstResult
secondSliderResultTitleLabel.text = secondResult
}
}
| mit | c7c93726c89074b818a82a956c5005bd | 39.674242 | 95 | 0.725275 | 5.645636 | false | false | false | false |
developerY/Active-Learning-Swift-2.0_DEMO | ActiveLearningSwift2.playground/Pages/Advanced.xcplaygroundpage/Contents.swift | 3 | 10329 | //: [Previous](@previous)
// ------------------------------------------------------------------------------------------------
// Things to know:
//
// * Arithmetic operators in Swift do not automatically overflow. Adding two values that overflow
// their type (for example, storing 300 in a UInt8) will cause an error. There are special
// operators that allow overflow, including dividing by zero.
//
// * Swift allows developers to define their own operators, including those that Swift doesn't
// currently define. You can even specify the associativity and precedence for operators.
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// Bitwise Operators
//
// The Bitwise operators (AND, OR, XOR, etc.) in Swift effeectively mirror the functionality that
// you're used to with C++ and Objective-C.
//
// We'll cover them briefly. The odd formatting is intended to help show the results:
var andResult: UInt8 =
0b00101111 &
0b11110100
// 0b00100100 <- result
var notResult: UInt8 =
~0b11110000
// 0b00001111 <- result
var orResult: UInt8 =
0b01010101 |
0b11110000
// 0b11110101 <- result
var xorResult: UInt8 =
0b01010101 ^
0b11110000
// 0b10100101 <- result
// Shifting in Swift is slightly different than in C++.
//
// A lesser-known fact about C++ is that the signed right-shift of a signed value is
// implementation specific. Most compilers do what most programmers expect, which is an arithmetic
// shift (which maintains the sign bit and shifts 1's into the word from the right.)
//
// Swift defines this behavior to be what you expect, shifting signed values to the right will
// perform an arithmetic shift using two's compilment.
var leftShiftUnsignedResult: UInt8 = 32 << 1
var leftShiftSignedResult: Int8 = 32 << 1
var leftShiftSignedNegativeResult: Int8 = -32 << 1
var rightShiftUnsignedResult: UInt8 = 32 >> 1
var rightShiftSignedResult: Int8 = 32 >> 1
var rightShiftSignedNegativeResult: Int8 = -32 >> 1
// ------------------------------------------------------------------------------------------------
// Overflow operators
//
// If an arithmetic operation (specifically addition (+), subtraction (-) and multiplication (*))
// results in a value too large or too small for the constant or variable that the result is
// intended for, Swift will produce an overflow/underflow error.
//
// The last two lines of this code block will trigger an overflow/underflow:
//
// var positive: Int8 = 120
// var negative: Int8 = -120
// var overflow: Int8 = positive + positive
// var underflow: Int8 = negative + negative
//
// This is also true for division by zero, which can be caused with the division (/) or remainder
// (%) operators.
//
// Sometimes, however, overflow and underflow behavior is exactly what the programmer may intend,
// so Swift provides specific overflow/underflow operators which will not trigger an error and
// allow the overflow/underflow to perform as we see in C++/Objective-C.
//
// Special operators for division by zero are also provided, which return 0 in the case of a
// division by zero.
//
// Here they are, in all their glory:
var someValue: Int8 = 120
var aZero: Int8 = someValue - someValue
var overflowAdd: Int8 = someValue &+ someValue
var underflowSub: Int8 = -someValue &- someValue
var overflowMul: Int8 = someValue &* someValue
var divByZero: Int8 = 100 &/ aZero
var remainderDivByZero: Int8 = 100 &% aZero
// ------------------------------------------------------------------------------------------------
// Operator Functions (a.k.a., Operator Overloading)
//
// Most C++ programmers should be familiar with the concept of operator overloading. Swift offers
// the same kind of functionality as well as additional functionality of specifying the operator
// precednce and associativity.
//
// The most common operators will usually take one of the following forms:
//
// * prefix: the operator appears before a single identifier as in "-a" or "++i"
// * postfix: the operator appears after a single identifier as in "i++"
// * infix: the operator appears between two identifiers as in "a + b" or "c / d"
//
// These are specified with the three attributes, @prefix, @postfix and @infix.
//
// There are more types of operators (which use different attributes, which we'll cover shortly.
//
// Let's define a Vector2D class to work with:
struct Vector2D
{
var x = 0.0
var y = 0.0
}
// Next, we'll define a simple vector addition (adding the individual x & y components to create
// a new vector.)
//
// Since we're adding two Vector2D instances, we'll use operator "+". We want our addition to take
// the form "vectorA + vectorB", which means we'll be defining an infix operator.
//
// Here's what that looks like:
func + (left: Vector2D, right: Vector2D) -> Vector2D
{
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
// Let's verify our work:
var a = Vector2D(x: 1.0, y: 2.0)
var b = Vector2D(x: 3.0, y: 4.0)
var c = a + b
// We've seen the infix operator at work so let's move on to the prefix and postfix operators.
// We'll define a prefix operator that negates the vector taking the form (result = -value):
prefix func - (vector: Vector2D) -> Vector2D
{
return Vector2D(x: -vector.x, y: -vector.y)
}
// Check our work:
c = -a
// Next, let's consider the common prefix increment operator (++a) and postfix increment (a++)
// operations. Each of these performs the operation on a single value whle also returning the
// appropriate result (either the original value before the increment or the value after the
// increment.)
//
// Each will either use the @prefix or @postfix attribute, but since they also modify the value
// they are also @assigmnent operators (and make use of inout for the parameter.)
//
// Let's take a look:
prefix func ++ (inout vector: Vector2D) -> Vector2D
{
vector = vector + Vector2D(x: 1.0, y: 1.0)
return vector
}
postfix func ++ (inout vector: Vector2D) -> Vector2D
{
var previous = vector;
vector = vector + Vector2D(x: 1.0, y: 1.0)
return previous
}
// And we can check our work:
++c
c++
c
// Equivalence Operators allow us to define a means for checking if two values are the same
// or equivalent. They can be "equal to" (==) or "not equal to" (!=). These are simple infix
// opertors that return a Bool result.
//
// Let's also take a moment to make sure we do this right. When comparing floating point values
// you can either check for exact bit-wise equality (a == b) or you can compare values that are
// "very close" by using an epsilon. It's important to recognize the difference, as there are
// cases when IEEE floating point values should be equal, but are actually represented differently
// in their bit-wise format because they were calculated differently. In these cases, a simple
// equality comparison will not suffice.
//
// So here are our more robust equivalence operators:
let Epsilon = 0.1e-7
func == (left: Vector2D, right: Vector2D) -> Bool
{
if abs(left.x - right.x) > Epsilon { return false }
if abs(left.y - right.y) > Epsilon { return false }
return true
}
func != (left: Vector2D, right: Vector2D) -> Bool
{
// Here, we'll use the inverted result of the "==" operator:
return !(left == right)
}
// ------------------------------------------------------------------------------------------------
// Custom Operators
//
// So far, we've been defining operator functions for operators that Swift understands and
// for which Swift provides defined behaviors. We can also define our own custom operators for
// doing other interestig things.
//
// For example, Swift doesn't support the concept of a "vector normalization" or "cross product"
// because this functionality doesn't apply to any of the types Swift offers.
//
// Let's keep it simple, though. How about an operator that adds a vector to itself. Let's make
// this a prefix operator that takes the form "+++value"
//
// First, we we must introduce Swift to our new operator. The syntax takes the form of the
// 'operator' keyword, folowed by either 'prefix', 'postfix' or 'infix':
//
// Swift meet operator, operator meet swift:
prefix operator +++ {}
// Now we can declare our new operator:
prefix func +++ (inout vector: Vector2D) -> Vector2D
{
vector = vector + vector
return vector
}
// Let's check our work:
var someVector = Vector2D(x: 5.0, y: 9.0)
+++someVector
// ------------------------------------------------------------------------------------------------
// Precedence and Associativity for Custom Infix Operators
//
// Custom infix operators can define their own associativity (left-to-right or right-to-left or
// none) as well as a precedence for determining the order of operations.
//
// Associativity values are 'left' or 'right' or 'none'.
//
// Precedence values are ranked with a numeric value. If not specified, the default value is 100.
// Operations are performed in order of precedence, with higher values being performed first. The
// precedence values are relative to all other precedence values for other operators. The following
// are the default values for operator precedence in the Swift standard library:
//
// 160 (none): Operators << >>
// 150 (left): Operators * / % &* &/ &% &
// 140 (left): Operators + - &+ &- | ^
// 135 (none): Operators .. ...
// 132 (none): Operators is as
// 130 (none): Operators < <= > >= == != === !== ~=
// 120 (left): Operators &&
// 110 (left): Operators ||
// 100 (right): Operators ?:
// 90 (right): Operators = *= /= %= += -= <<= >>= &= ^= |= &&= ||=
//
// Let's take a look at how we define a new custom infix operator with left associativity and a
// precedence of 140.
//
// We'll define a function that adds the 'x' components of two vectors, but subtracts the 'y'
// components. We'll call this the "+-" operator:
infix operator +- { associativity left precedence 140 }
func +- (left: Vector2D, right: Vector2D) -> Vector2D
{
return Vector2D(x: left.x + right.x, y: left.y - right.y)
}
// Check our work. Let's setup a couple vectors that result in a value of (0, 0):
var first = Vector2D(x: 5.0, y: 5.0)
var second = Vector2D(x: -5.0, y: 5.0)
first +- second
//: [Next](@next)
| apache-2.0 | 5d3249482a06ef710a60261705e78e1b | 38.125 | 99 | 0.659696 | 3.925884 | false | false | false | false |
zitao0322/ShopCar | Shoping_Car/Shoping_Car/Extension/Communal.swift | 1 | 1769 |
import Foundation
import UIKit
//MARK:颜色公共的方法
//随机颜色
func kStochasticColor() -> UIColor{
return kColorDefine(r: CGFloat(random()%255),
g: CGFloat(random()%255),
b: CGFloat(random()%255))
}
//自定义颜色
func kColorDefine(r r: CGFloat,g: CGFloat,b: CGFloat) -> UIColor {
return UIColor(red: r/255, green: g/255, blue: b/255, alpha: 1)
}
//MARK:字体
let kFont_11 = UIFont.systemFontOfSize(11)
let kFont_12 = UIFont.systemFontOfSize(12)
let kFont_14 = UIFont.systemFontOfSize(14)
let kFont_15 = UIFont.systemFontOfSize(15)
let kFont_18 = UIFont.systemFontOfSize(18)
let kFont_19 = UIFont.systemFontOfSize(19)
//MARK:长宽
//定义宏
let kSCREENW = UIScreen.mainScreen().bounds.width
let kSCREENH = UIScreen.mainScreen().bounds.height
/**
根据比例计算横向的UI尺寸
- parameter w: UI标注的尺寸
- returns: 换算过后尺寸
*/
func kAUTO_WEX(w: CGFloat) -> CGFloat {
return w*kSCREEN_WIDTH_RATIO
}
/**
根据比例计算纵向的UI尺寸
- parameter h: UI标注的尺寸
- returns: 换算过后尺寸
*/
func kAUTO_HEX(h: CGFloat) -> CGFloat {
return h*kSCREEN_HEIGHT_RATIO
}
//计算现在屏幕和苹果6屏幕的比例
private let kSCREEN_WIDTH_RATIO: CGFloat = kSCREENW/375.0
private let kSCREEN_HEIGHT_RATIO: CGFloat = kSCREENH/667.0
func println<T>(message: T,
fileName: String = #file,
methodName: String = #function,
lineNumber: Int = #line)
{
#if DEBUG
let str: String = (fileName as NSString)
.pathComponents.last!
.stringByReplacingOccurrencesOfString("swift", withString: "")
print("\(str)\(methodName)[\(lineNumber)]:\(message)")
#endif
}
| mit | 6396f339ff390e94a1091b7a38f68a5e | 18.361446 | 74 | 0.657125 | 3.313402 | false | false | false | false |
dreamsxin/swift | test/Interpreter/capture_top_level.swift | 9 | 1030 | // RUN: %target-run-simple-swift | FileCheck %s
// RUN: %target-build-swift -DVAR %s -o %t-var
// RUN: %target-run %t-var | FileCheck %s
// RUN: %target-build-swift -DVAR_UPDATE %s -o %t-var
// RUN: %target-run %t-var | FileCheck %s
// REQUIRES: executable_test
#if VAR_UPDATE
guard var x = Optional(0) else { fatalError() }
#elseif VAR
guard var x = Optional(42) else { fatalError() }
#else
guard let x = Optional(42) else { fatalError() }
#endif
_ = 0 // intervening code
func function() {
print("function: \(x)")
}
let closure: () -> Void = {
print("closure: \(x)")
}
defer {
print("deferred: \(x)")
}
#if VAR_UPDATE
x = 42
#endif
let closureCapture: () -> Void = { [x] in
// Must come after the assignment because of the capture by value.
print("closure-capture: \(x)")
}
print("go! \(x)") // CHECK-LABEL: go! 42
function() // CHECK-NEXT: function: 42
closure() // CHECK-NEXT: closure: 42
closureCapture() // CHECK-NEXT: closure-capture: 42
print("done?") // CHECK-NEXT: done?
// CHECK-NEXT: deferred: 42
| apache-2.0 | 1906be057e108c8925a91ddd7ce8cec2 | 20.914894 | 68 | 0.635922 | 2.95977 | false | false | false | false |
sjrmanning/Birdsong | Source/Response.swift | 1 | 965 | //
// Response.swift
// Pods
//
// Created by Simon Manning on 23/06/2016.
//
//
import Foundation
open class Response {
open let ref: String
open let topic: String
open let event: String
open let payload: Socket.Payload
init?(data: Data) {
do {
guard let jsonObject = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? Socket.Payload else { return nil }
ref = jsonObject["ref"] as? String ?? ""
if let topic = jsonObject["topic"] as? String,
let event = jsonObject["event"] as? String,
let payload = jsonObject["payload"] as? Socket.Payload {
self.topic = topic
self.event = event
self.payload = payload
}
else {
return nil
}
}
catch {
return nil
}
}
}
| mit | 34d632a82c4afc2e7e0ee8605b16f0e0 | 24.394737 | 163 | 0.517098 | 4.753695 | false | false | false | false |
yoller/HanekeSwift | Haneke/Cache.swift | 1 | 13738 | //
// Cache.swift
// Haneke
//
// Created by Luis Ascorbe on 23/07/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
// Used to add T to NSCache
class ObjectWrapper : NSObject {
let value: Any
init(value: Any) {
self.value = value
}
}
extension HanekeGlobals {
// It'd be better to define this in the Cache class but Swift doesn't allow statics in a generic type
public struct Cache {
public static let OriginalFormatName = "original"
public enum ErrorCode : Int {
case ObjectNotFound = -100
case FormatNotFound = -101
}
}
}
public class Cache<T: DataConvertible where T.Result == T, T : DataRepresentable> {
let name: String
var memoryWarningObserver : NSObjectProtocol!
public init(name: String) {
self.name = name
let notifications = NSNotificationCenter.defaultCenter()
// Using block-based observer to avoid subclassing NSObject
memoryWarningObserver = notifications.addObserverForName(UIApplicationDidReceiveMemoryWarningNotification,
object: nil,
queue: NSOperationQueue.mainQueue(),
usingBlock: { [unowned self] (notification : NSNotification!) -> Void in
self.onMemoryWarning()
}
)
let originalFormat = Format<T>(name: HanekeGlobals.Cache.OriginalFormatName)
self.addFormat(originalFormat)
}
deinit {
let notifications = NSNotificationCenter.defaultCenter()
notifications.removeObserver(memoryWarningObserver, name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
}
public func set(value value: T, key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, success succeed: ((T) -> ())? = nil) {
if let (format, memoryCache, diskCache) = self.formats[formatName] {
self.format(value: value, format: format) { formattedValue in
let wrapper = ObjectWrapper(value: formattedValue)
memoryCache.setObject(wrapper, forKey: key)
// Value data is sent as @autoclosure to be executed in the disk cache queue.
diskCache.setData(self.dataFromValue(formattedValue, format: format), key: key)
succeed?(formattedValue)
}
} else {
assertionFailure("Can't set value before adding format")
}
}
public func fetch(key key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetch = Cache.buildFetch(failure: fail, success: succeed)
if let (format, memoryCache, diskCache) = self.formats[formatName] {
if let wrapper = memoryCache.objectForKey(key) as? ObjectWrapper, let result = wrapper.value as? T {
fetch.succeed(result)
diskCache.updateAccessDate(self.dataFromValue(result, format: format), key: key)
return fetch
}
self.fetchFromDiskCache(diskCache, key: key, memoryCache: memoryCache, failure: { error in
fetch.fail(error)
}) { value in
fetch.succeed(value)
}
} else {
let localizedFormat = NSLocalizedString("Format %@ not found", comment: "Error description")
let description = String(format:localizedFormat, formatName)
let error = errorWithCode(HanekeGlobals.Cache.ErrorCode.FormatNotFound.rawValue, description: description)
fetch.fail(error)
}
return fetch
}
public func fetchFromMemory(key key : String, formatName : String = HanekeGlobals.Cache.OriginalFormatName) -> T? {
if let (_, memoryCache, diskCache) = self.formats[formatName] {
if let wrapper = memoryCache.objectForKey(key) as? ObjectWrapper {
return wrapper.value as? T
}
let path = diskCache.pathForKey(key)
do {
let data = try NSData(contentsOfFile: path, options: NSDataReadingOptions())
let value = T.convertFromData(data)
if let value = value {
let descompressedValue = self.decompressedImageIfNeeded(value)
let wrapper = ObjectWrapper(value: descompressedValue)
memoryCache.setObject(wrapper, forKey: key)
return wrapper.value as? T
}
diskCache.updateDiskAccessDateAtPath(path)
} catch {
}
} else {
return nil
}
return nil
}
public func fetch(fetcher fetcher : Fetcher<T>, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let key = fetcher.key
let fetch = Cache.buildFetch(failure: fail, success: succeed)
self.fetch(key: key, formatName: formatName, failure: { error in
if error?.code == HanekeGlobals.Cache.ErrorCode.FormatNotFound.rawValue {
fetch.fail(error)
}
if let (format, _, _) = self.formats[formatName] {
self.fetchAndSet(fetcher, format: format, failure: {error in
fetch.fail(error)
}) {value in
fetch.succeed(value)
}
}
// Unreachable code. Formats can't be removed from Cache.
}) { value in
fetch.succeed(value)
}
return fetch
}
public func remove(key key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName) {
if let (_, memoryCache, diskCache) = self.formats[formatName] {
memoryCache.removeObjectForKey(key)
diskCache.removeData(key)
}
}
public func removeAll(completion: (() -> ())? = nil) {
let group = dispatch_group_create();
for (_, (_, memoryCache, diskCache)) in self.formats {
memoryCache.removeAllObjects()
dispatch_group_enter(group)
diskCache.removeAllData {
dispatch_group_leave(group)
}
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let timeout = dispatch_time(DISPATCH_TIME_NOW, Int64(60 * NSEC_PER_SEC))
if dispatch_group_wait(group, timeout) != 0 {
Log.error("removeAll timed out waiting for disk caches")
}
let path = self.cachePath
do {
try NSFileManager.defaultManager().removeItemAtPath(path)
} catch {
Log.error("Failed to remove path \(path)", error as NSError)
}
if let completion = completion {
dispatch_async(dispatch_get_main_queue()) {
completion()
}
}
}
}
// MARK: Size
public var size: UInt64 {
var size: UInt64 = 0
for (_, (_, _, diskCache)) in self.formats {
dispatch_sync(diskCache.cacheQueue) { size += diskCache.size }
}
return size
}
// MARK: Notifications
func onMemoryWarning() {
for (_, (_, memoryCache, _)) in self.formats {
memoryCache.removeAllObjects()
}
}
// MARK: Formats
var formats : [String : (Format<T>, NSCache, DiskCache)] = [:]
public func addFormat(format : Format<T>) {
let name = format.name
let formatPath = self.formatPath(formatName: name)
let memoryCache = NSCache()
let diskCache = DiskCache(path: formatPath, capacity : format.diskCapacity)
self.formats[name] = (format, memoryCache, diskCache)
}
// MARK: Internal
lazy var cachePath: String = {
let basePath = DiskCache.basePath()
let cachePath = (basePath as NSString).stringByAppendingPathComponent(self.name)
return cachePath
}()
func formatPath(formatName formatName: String) -> String {
let formatPath = (self.cachePath as NSString).stringByAppendingPathComponent(formatName)
do {
try NSFileManager.defaultManager().createDirectoryAtPath(formatPath, withIntermediateDirectories: true, attributes: nil)
} catch {
Log.error("Failed to create directory \(formatPath)", error as NSError)
}
return formatPath
}
// MARK: Private
func dataFromValue(value : T, format : Format<T>) -> NSData? {
if let data = format.convertToData?(value) {
return data
}
return value.asData()
}
private func fetchFromDiskCache(diskCache : DiskCache, key: String, memoryCache : NSCache, failure fail : ((NSError?) -> ())?, success succeed : (T) -> ()) {
diskCache.fetchData(key: key, failure: { error in
if let block = fail {
if (error?.code == NSFileReadNoSuchFileError) {
let localizedFormat = NSLocalizedString("Object not found for key %@", comment: "Error description")
let description = String(format:localizedFormat, key)
let error = errorWithCode(HanekeGlobals.Cache.ErrorCode.ObjectNotFound.rawValue, description: description)
block(error)
} else {
block(error)
}
}
}) { data in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let value = T.convertFromData(data)
if let value = value {
let descompressedValue = self.decompressedImageIfNeeded(value)
dispatch_async(dispatch_get_main_queue(), {
succeed(descompressedValue)
let wrapper = ObjectWrapper(value: descompressedValue)
memoryCache.setObject(wrapper, forKey: key)
})
}
})
}
}
private func fetchAndSet(fetcher : Fetcher<T>, format : Format<T>, failure fail : ((NSError?) -> ())?, success succeed : (T) -> ()) {
fetcher.fetch(failure: { error in
let _ = fail?(error)
}) { value in
self.set(value: value, key: fetcher.key, formatName: format.name, success: succeed)
}
}
private func format(value value : T, format : Format<T>, success succeed : (T) -> ()) {
// HACK: Ideally Cache shouldn't treat images differently but I can't think of any other way of doing this that doesn't complicate the API for other types.
if format.isIdentity && !(value is UIImage) {
succeed(value)
} else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
var formatted = format.apply(value)
if let formattedImage = formatted as? UIImage {
let originalImage = value as? UIImage
if formattedImage === originalImage {
formatted = self.decompressedImageIfNeeded(formatted)
}
}
dispatch_async(dispatch_get_main_queue()) {
succeed(formatted)
}
}
}
}
private func decompressedImageIfNeeded(value : T) -> T {
if let image = value as? UIImage {
let decompressedImage = image.hnk_decompressedImage() as? T
return decompressedImage!
}
return value
}
private class func buildFetch(failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetch = Fetch<T>()
if let succeed = succeed {
fetch.onSuccess(succeed)
}
if let fail = fail {
fetch.onFailure(fail)
}
return fetch
}
// MARK: Convenience fetch
// Ideally we would put each of these in the respective fetcher file as a Cache extension. Unfortunately, this fails to link when using the framework in a project as of Xcode 6.1.
public func fetch(key key: String, @autoclosure(escaping) value getValue : () -> T.Result, formatName: String = HanekeGlobals.Cache.OriginalFormatName, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetcher = SimpleFetcher<T>(key: key, value: getValue)
return self.fetch(fetcher: fetcher, formatName: formatName, success: succeed)
}
public func fetch(path path: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetcher = DiskFetcher<T>(path: path)
return self.fetch(fetcher: fetcher, formatName: formatName, failure: fail, success: succeed)
}
public func fetch(URL URL : NSURL, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail : Fetch<T>.Failer? = nil, success succeed : Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetcher = NetworkFetcher<T>(URL: URL)
return self.fetch(fetcher: fetcher, formatName: formatName, failure: fail, success: succeed)
}
}
| apache-2.0 | 48b93d04683fa66093d1e06ae3698649 | 38.705202 | 214 | 0.57876 | 4.915206 | false | false | false | false |
slavapestov/swift | test/Interpreter/protocol_extensions.swift | 3 | 5890 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// Extend a protocol with a property.
extension SequenceType {
final var myCount: Int {
var result = 0
for _ in self {
result += 1
}
return result
}
}
// CHECK: 4
print(["a", "b", "c", "d"].myCount)
// Extend a protocol with a function.
extension CollectionType {
final var myIndices: Range<Index> {
return Range(start: startIndex, end: endIndex)
}
func clone() -> Self {
return self
}
}
// CHECK: 4
print(["a", "b", "c", "d"].clone().myCount)
extension CollectionType {
final func indexMatching(fn: Generator.Element -> Bool) -> Index? {
for i in myIndices {
if fn(self[i]) { return i }
}
return nil
}
}
// CHECK: 2
print(["a", "b", "c", "d"].indexMatching({$0 == "c"})!)
// Extend certain instances of a collection (those that have equatable
// element types) with another algorithm.
extension CollectionType where Self.Generator.Element : Equatable {
final func myIndexOf(element: Generator.Element) -> Index? {
for i in self.indices {
if self[i] == element { return i }
}
return nil
}
}
// CHECK: 3
print(["a", "b", "c", "d", "e"].myIndexOf("d")!)
extension SequenceType {
final public func myEnumerate() -> EnumerateSequence<Self> {
return EnumerateSequence(self)
}
}
// CHECK: (0, a)
// CHECK-NEXT: (1, b)
// CHECK-NEXT: (2, c)
for (index, element) in ["a", "b", "c"].myEnumerate() {
print("(\(index), \(element))")
}
extension SequenceType {
final public func myReduce<T>(
initial: T, @noescape combine: (T, Self.Generator.Element) -> T
) -> T {
var result = initial
for value in self {
result = combine(result, value)
}
return result
}
}
// CHECK: 15
print([1, 2, 3, 4, 5].myReduce(0, combine: +))
extension SequenceType {
final public func myZip<S : SequenceType>(s: S) -> Zip2Sequence<Self, S> {
return Zip2Sequence(self, s)
}
}
// CHECK: (1, a)
// CHECK-NEXT: (2, b)
// CHECK-NEXT: (3, c)
for (a, b) in [1, 2, 3].myZip(["a", "b", "c"]) {
print("(\(a), \(b))")
}
// Mutating algorithms.
extension MutableCollectionType
where Self.Index: RandomAccessIndexType, Self.Generator.Element : Comparable {
public final mutating func myPartition(range: Range<Index>) -> Index {
return self.partition(range)
}
}
// CHECK: 4 3 1 2 | 5 9 8 6 7 6
var evenOdd = [5, 3, 6, 2, 4, 9, 8, 1, 7, 6]
var evenOddSplit = evenOdd.myPartition(evenOdd.myIndices)
for i in evenOdd.myIndices {
if i == evenOddSplit { print(" |", terminator: "") }
if i > 0 { print(" ", terminator: "") }
print(evenOdd[i], terminator: "")
}
print("")
extension RangeReplaceableCollectionType {
public final func myJoin<S : SequenceType where S.Generator.Element == Self>(
elements: S
) -> Self {
var result = Self()
var gen = elements.generate()
if let first = gen.next() {
result.appendContentsOf(first)
while let next = gen.next() {
result.appendContentsOf(self)
result.appendContentsOf(next)
}
}
return result
}
}
// CHECK: a,b,c
print(
String(
",".characters.myJoin(["a".characters, "b".characters, "c".characters])
)
)
// Constrained extensions for specific types.
extension CollectionType where Self.Generator.Element == String {
final var myCommaSeparatedList: String {
if startIndex == endIndex { return "" }
var result = ""
var first = true
for x in self {
if first { first = false }
else { result += ", " }
result += x
}
return result
}
}
// CHECK: x, y, z
print(["x", "y", "z"].myCommaSeparatedList)
// CHECK: {{[tuv], [tuv], [tuv]}}
print((["t", "u", "v"] as Set).myCommaSeparatedList)
// Existentials
protocol ExistP1 {
func existP1()
}
extension ExistP1 {
final func runExistP1() {
print("runExistP1")
self.existP1()
}
}
struct ExistP1_Struct : ExistP1 {
func existP1() {
print(" - ExistP1_Struct")
}
}
class ExistP1_Class : ExistP1 {
func existP1() {
print(" - ExistP1_Class")
}
}
// CHECK: runExistP1
// CHECK-NEXT: - ExistP1_Struct
var existP1: ExistP1 = ExistP1_Struct()
existP1.runExistP1()
// CHECK: runExistP1
// CHECK-NEXT: - ExistP1_Class
existP1 = ExistP1_Class()
existP1.runExistP1()
protocol P {
mutating func setValue(b: Bool)
func getValue() -> Bool
}
extension P {
final var extValue: Bool {
get { return getValue() }
set(newValue) { setValue(newValue) }
}
}
extension Bool : P {
mutating func setValue(b: Bool) { self = b }
func getValue() -> Bool { return self }
}
class C : P {
var theValue: Bool = false
func setValue(b: Bool) { theValue = b }
func getValue() -> Bool { return theValue }
}
func toggle(inout value: Bool) {
value = !value
}
var p: P = true
// CHECK: Bool
print("Bool")
// CHECK: true
p.extValue = true
print(p.extValue)
// CHECK: false
p.extValue = false
print(p.extValue)
// CHECK: true
toggle(&p.extValue)
print(p.extValue)
// CHECK: C
print("C")
p = C()
// CHECK: true
p.extValue = true
print(p.extValue)
// CHECK: false
p.extValue = false
print(p.extValue)
// CHECK: true
toggle(&p.extValue)
print(p.extValue)
// Logical lvalues of existential type.
struct HasP {
var _p: P
var p: P {
get { return _p }
set { _p = newValue }
}
}
var hasP = HasP(_p: false)
// CHECK: true
hasP.p.extValue = true
print(hasP.p.extValue)
// CHECK: false
toggle(&hasP.p.extValue)
print(hasP.p.extValue)
// rdar://problem/20739719
class Super: Init {
required init(x: Int) { print("\(x) \(self.dynamicType)") }
}
class Sub: Super {}
protocol Init { init(x: Int) }
extension Init { init() { self.init(x: 17) } }
// CHECK: 17 Super
_ = Super()
// CHECK: 17 Sub
_ = Sub()
// CHECK: 17 Super
var sup: Super.Type = Super.self
_ = sup.init()
// CHECK: 17 Sub
sup = Sub.self
_ = sup.init()
// CHECK: DONE
print("DONE")
| apache-2.0 | 1bf9df9f992ebd6c9b87826d3ff69a25 | 18.438944 | 80 | 0.621562 | 3.104902 | false | false | false | false |
kentaiwami/masamon | masamon/masamon/Setting.swift | 1 | 3684 | //
// Setting.swift
// masamon
//
// Created by 岩見建汰 on 2016/01/31.
// Copyright © 2016年 Kenta. All rights reserved.
//
import UIKit
import Eureka
class Setting: FormViewController {
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate //AppDelegateのインスタンスを取得
override func viewDidLoad() {
super.viewDidLoad()
//ナビゲーションバーの色などを設定する
self.navigationController!.navigationBar.barTintColor = UIColor.black
self.navigationController!.navigationBar.tintColor = UIColor.white
self.navigationController!.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
let storyboard: UIStoryboard = self.storyboard!
let HourlyWageSetting_VC = storyboard.instantiateViewController(withIdentifier: "HourlyWageSetting")
let ShiftImportSetting_VC = storyboard.instantiateViewController(withIdentifier: "ShiftImportSetting")
let StaffNameListSetting_VC = storyboard.instantiateViewController(withIdentifier: "StaffNameListSetting")
let ShiftNameListSetting_VC = storyboard.instantiateViewController(withIdentifier: "ShiftNameListSetting")
let ShiftListSetting_VC = storyboard.instantiateViewController(withIdentifier: "ShiftListSetting")
form +++ Section()
<<< ButtonRow() {
$0.title = "時給の設定"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return HourlyWageSetting_VC},
onDismiss: { vc in
vc.navigationController?.popViewController(animated: true)}
)
}
form +++ Section()
<<< ButtonRow() {
$0.title = "ユーザ名と従業員数の設定"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return ShiftImportSetting_VC},
onDismiss: { vc in
vc.navigationController?.popViewController(animated: true)}
)
}
form +++ Section()
<<< ButtonRow() {
$0.title = "従業員名の設定"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return StaffNameListSetting_VC},
onDismiss: { vc in
vc.navigationController?.popViewController(animated: true)}
)
}
form +++ Section()
<<< ButtonRow() {
$0.title = "シフト名の設定"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return ShiftNameListSetting_VC},
onDismiss: { vc in
vc.navigationController?.popViewController(animated: true)}
)
}
form +++ Section()
<<< ButtonRow() {
$0.title = "取り込んだシフトの設定"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return ShiftListSetting_VC},
onDismiss: { vc in
vc.navigationController?.popViewController(animated: true)}
)
}
}
override func viewDidAppear(_ animated: Bool) {
appDelegate.screennumber = 2
}
}
| mit | 4577b743706452d3b4adfb9d5075563c | 43.721519 | 125 | 0.565242 | 5.634769 | false | false | false | false |
suifengqjn/CatLive | CatLive/CatLive/Classes/Home/Controllers/AnchorController.swift | 1 | 2866 | //
// AnchorController.swift
// CatLive
//
// Created by qianjn on 2017/6/11.
// Copyright © 2017年 SF. All rights reserved.
//
import UIKit
private let kEdgeMargin : CGFloat = 8
private let kAnchorCellID = "kAnchorCellID"
class AnchorController: XCViewController {
// MARK: 对外属性
var homeType : HomeType!
// MARK: 定义属性
fileprivate lazy var homeVM : HomeViewModel = HomeViewModel()
lazy var collectionView: UICollectionView = {
let layout = CLWaterFallLayout()
layout.dataSource = self
layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
layout.minimumLineSpacing = 10;
layout.minimumInteritemSpacing = 10;
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib(nibName: "HomeViewCell", bundle: nil), forCellWithReuseIdentifier: kAnchorCellID)
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.backgroundColor = UIColor.white
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData(index: 0)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.collectionView.reloadData()
}
}
// MARK:- 设置UI界面内容
extension AnchorController {
fileprivate func setupUI() {
view.addSubview(collectionView)
}
}
extension AnchorController {
fileprivate func loadData(index : Int) {
homeVM.loadHomeData(type: homeType, index : index, finishedCallback: {
self.collectionView.reloadData()
})
}
}
// MARK:- collectionView的数据源&代理
extension AnchorController: UICollectionViewDataSource, UICollectionViewDelegate, CLWaterFallLayoutDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return homeVM.anchorModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kAnchorCellID, for: indexPath) as! HomeViewCell
cell.anchorModel = homeVM.anchorModels[indexPath.item]
if indexPath.item == homeVM.anchorModels.count - 1 {
loadData(index: homeVM.anchorModels.count)
}
return cell
}
func waterfallLayout(_ layout: CLWaterFallLayout, indexPath: IndexPath) -> CGFloat {
return indexPath.item % 2 == 0 ? kScreenW * 2 / 3 : kScreenW * 0.5
}
}
| apache-2.0 | fe6c1264b091ece2367cb6fe2081dbb0 | 26.950495 | 122 | 0.659936 | 5.266791 | false | false | false | false |
ahoppen/swift | test/SILGen/protocols.swift | 17 | 22622 |
// RUN: %target-swift-emit-silgen -module-name protocols %s | %FileCheck %s
//===----------------------------------------------------------------------===//
// Calling Existential Subscripts
//===----------------------------------------------------------------------===//
protocol SubscriptableGet {
subscript(a : Int) -> Int { get }
}
protocol SubscriptableGetSet {
subscript(a : Int) -> Int { get set }
}
var subscriptableGet : SubscriptableGet
var subscriptableGetSet : SubscriptableGetSet
func use_subscript_rvalue_get(_ i : Int) -> Int {
return subscriptableGet[i]
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_rvalue_get
// CHECK: bb0(%0 : $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols16subscriptableGetAA013SubscriptableC0_pvp : $*SubscriptableGet
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*SubscriptableGet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGet to $*[[OPENED:@opened(.*) SubscriptableGet]]
// CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: end_access [[READ]] : $*SubscriptableGet
// CHECK-NEXT: [[TMP:%.*]] = alloc_stack
// CHECK-NEXT: copy_addr [[ALLOCSTACK]] to [initialization] [[TMP]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGet.subscript!getter
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[TMP]])
// CHECK-NEXT: destroy_addr [[TMP]]
// CHECK-NEXT: destroy_addr [[ALLOCSTACK]]
// CHECK-NEXT: dealloc_stack [[TMP]]
// CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: return [[RESULT]]
func use_subscript_lvalue_get(_ i : Int) -> Int {
return subscriptableGetSet[i]
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_lvalue_get
// CHECK: bb0(%0 : $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols19subscriptableGetSetAA013SubscriptablecD0_pvp : $*SubscriptableGetSet
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*SubscriptableGetSet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]]
// CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!getter
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]])
// CHECK-NEXT: destroy_addr [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: end_access [[READ]] : $*SubscriptableGetSet
// CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: return [[RESULT]]
func use_subscript_lvalue_set(_ i : Int) {
subscriptableGetSet[i] = i
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_lvalue_set
// CHECK: bb0(%0 : $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols19subscriptableGetSetAA013SubscriptablecD0_pvp : $*SubscriptableGetSet
// CHECK: [[READ:%.*]] = begin_access [modify] [dynamic] [[GLOB]] : $*SubscriptableGetSet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[READ]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!setter
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, %0, [[PROJ]])
//===----------------------------------------------------------------------===//
// Calling Archetype Subscripts
//===----------------------------------------------------------------------===//
func use_subscript_archetype_rvalue_get<T : SubscriptableGet>(_ generic : T, idx : Int) -> Int {
return generic[idx]
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_archetype_rvalue_get
// CHECK: bb0(%0 : $*T, %1 : $Int):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGet.subscript!getter
// CHECK-NEXT: apply [[METH]]<T>(%1, [[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]] : $*T
// CHECK-NEXT: dealloc_stack [[STACK]] : $*T
// CHECK: } // end sil function '${{.*}}use_subscript_archetype_rvalue_get
func use_subscript_archetype_lvalue_get<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) -> Int {
return generic[idx]
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_archetype_lvalue_get
// CHECK: bb0(%0 : $*T, %1 : $Int):
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*T
// CHECK: [[GUARANTEEDSTACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr [[READ]] to [initialization] [[GUARANTEEDSTACK]] : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!getter
// CHECK-NEXT: [[APPLYRESULT:%[0-9]+]] = apply [[METH]]<T>(%1, [[GUARANTEEDSTACK]])
// CHECK-NEXT: destroy_addr [[GUARANTEEDSTACK]] : $*T
// CHECK-NEXT: end_access [[READ]]
// CHECK-NEXT: dealloc_stack [[GUARANTEEDSTACK]] : $*T
// CHECK: return [[APPLYRESULT]]
func use_subscript_archetype_lvalue_set<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) {
generic[idx] = idx
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_archetype_lvalue_set
// CHECK: bb0(%0 : $*T, %1 : $Int):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!setter
// CHECK-NEXT: apply [[METH]]<T>(%1, %1, [[WRITE]])
//===----------------------------------------------------------------------===//
// Calling Existential Properties
//===----------------------------------------------------------------------===//
protocol PropertyWithGetter {
var a : Int { get }
}
protocol PropertyWithGetterSetter {
var b : Int { get set }
}
var propertyGet : PropertyWithGetter
var propertyGetSet : PropertyWithGetterSetter
func use_property_rvalue_get() -> Int {
return propertyGet.a
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_rvalue_get
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols11propertyGetAA18PropertyWithGetter_pvp : $*PropertyWithGetter
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*PropertyWithGetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*PropertyWithGetter to $*[[OPENED:@opened(.*) PropertyWithGetter]]
// CHECK: [[COPY:%.*]] = alloc_stack $[[OPENED]]
// CHECK-NEXT: copy_addr [[PROJ]] to [initialization] [[COPY]] : $*[[OPENED]]
// CHECK-NEXT: end_access [[READ]] : $*PropertyWithGetter
// CHECK: [[BORROW:%.*]] = alloc_stack $[[OPENED]]
// CHECK-NEXT: copy_addr [[COPY]] to [initialization] [[BORROW]] : $*[[OPENED]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetter.a!getter
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[BORROW]])
func use_property_lvalue_get() -> Int {
return propertyGetSet.b
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_lvalue_get
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols14propertyGetSetAA24PropertyWithGetterSetter_pvp : $*PropertyWithGetterSetter
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*PropertyWithGetterSetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[STACK]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!getter
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[STACK]])
func use_property_lvalue_set(_ x : Int) {
propertyGetSet.b = x
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_lvalue_set
// CHECK: bb0(%0 : $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols14propertyGetSetAA24PropertyWithGetterSetter_pvp : $*PropertyWithGetterSetter
// CHECK: [[READ:%.*]] = begin_access [modify] [dynamic] [[GLOB]] : $*PropertyWithGetterSetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[READ]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!setter
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, [[PROJ]])
//===----------------------------------------------------------------------===//
// Calling Archetype Properties
//===----------------------------------------------------------------------===//
func use_property_archetype_rvalue_get<T : PropertyWithGetter>(_ generic : T) -> Int {
return generic.a
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_archetype_rvalue_get
// CHECK: bb0(%0 : $*T):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetter.a!getter
// CHECK-NEXT: apply [[METH]]<T>([[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]]
// CHECK-NEXT: dealloc_stack [[STACK]]
// CHECK: } // end sil function '{{.*}}use_property_archetype_rvalue_get
func use_property_archetype_lvalue_get<T : PropertyWithGetterSetter>(_ generic : T) -> Int {
return generic.b
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_archetype_lvalue_get
// CHECK: bb0(%0 : $*T):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]] : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!getter
// CHECK-NEXT: apply [[METH]]<T>([[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]] : $*T
// CHECK-NEXT: dealloc_stack [[STACK]] : $*T
// CHECK: } // end sil function '${{.*}}use_property_archetype_lvalue_get
func use_property_archetype_lvalue_set<T : PropertyWithGetterSetter>(_ generic: inout T, v : Int) {
generic.b = v
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_archetype_lvalue_set
// CHECK: bb0(%0 : $*T, %1 : $Int):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!setter
// CHECK-NEXT: apply [[METH]]<T>(%1, [[WRITE]])
//===----------------------------------------------------------------------===//
// Calling Initializers
//===----------------------------------------------------------------------===//
protocol Initializable {
init(int: Int)
}
// CHECK-LABEL: sil hidden [ossa] @$s9protocols27use_initializable_archetype{{[_0-9a-zA-Z]*}}F
func use_initializable_archetype<T: Initializable>(_ t: T, i: Int) {
// CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T
// CHECK: [[T_META:%[0-9]+]] = metatype $@thick T.Type
// CHECK: [[T_INIT:%[0-9]+]] = witness_method $T, #Initializable.init!allocator : {{.*}} : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[T_RESULT_ADDR:%[0-9]+]] = apply [[T_INIT]]<T>([[T_RESULT]], %1, [[T_META]]) : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: destroy_addr [[T_RESULT]] : $*T
// CHECK: dealloc_stack [[T_RESULT]] : $*T
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
T(int: i)
}
// CHECK: sil hidden [ossa] @$s9protocols29use_initializable_existential{{[_0-9a-zA-Z]*}}F
func use_initializable_existential(_ im: Initializable.Type, i: Int) {
// CHECK: bb0([[IM:%[0-9]+]] : $@thick Initializable.Type, [[I:%[0-9]+]] : $Int):
// CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[IM]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type
// CHECK: [[TEMP_VALUE:%[0-9]+]] = alloc_stack $Initializable
// CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method $@opened([[N]]) Initializable, #Initializable.init!allocator : {{.*}}, [[ARCHETYPE_META]]{{.*}} : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[TEMP_ADDR:%[0-9]+]] = init_existential_addr [[TEMP_VALUE]] : $*Initializable, $@opened([[N]]) Initializable
// CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[TEMP_ADDR]], [[I]], [[ARCHETYPE_META]]) : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: destroy_addr [[TEMP_VALUE]] : $*Initializable
// CHECK: dealloc_stack [[TEMP_VALUE]] : $*Initializable
im.init(int: i)
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
}
//===----------------------------------------------------------------------===//
// Protocol conformance and witness table generation
//===----------------------------------------------------------------------===//
class ClassWithGetter : PropertyWithGetter {
var a: Int {
get {
return 42
}
}
}
// Make sure we are generating a protocol witness that calls the class method on
// ClassWithGetter.
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW :
// CHECK: bb0([[C:%.*]] : $*ClassWithGetter):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow %0
// CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetter, #ClassWithGetter.a!getter : (ClassWithGetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetter) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: end_borrow [[CCOPY_LOADED]]
// CHECK-NEXT: return
class ClassWithGetterSetter : PropertyWithGetterSetter, PropertyWithGetter {
var a: Int {
get {
return 1
}
set {}
}
var b: Int {
get {
return 2
}
set {}
}
}
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivgTW :
// CHECK: bb0([[C:%.*]] : $*ClassWithGetterSetter):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow %0
// CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetterSetter, #ClassWithGetterSetter.b!getter : (ClassWithGetterSetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetterSetter) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: end_borrow [[CCOPY_LOADED]]
// CHECK-NEXT: return
// Stored variables fulfilling property requirements
//
class ClassWithStoredProperty : PropertyWithGetter {
var a : Int = 0
// Make sure that accesses go through the generated accessors for classes.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden [ossa] @$s9protocols23ClassWithStoredPropertyC011methodUsingE0SiyF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassWithStoredProperty):
// CHECK-NEXT: debug_value [[ARG]]
// CHECK-NOT: copy_value
// CHECK-NEXT: [[FUN:%.*]] = class_method [[ARG]] : $ClassWithStoredProperty, #ClassWithStoredProperty.a!getter : (ClassWithStoredProperty) -> () -> Int, $@convention(method) (@guaranteed ClassWithStoredProperty) -> Int
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[ARG]])
// CHECK-NOT: destroy_value
// CHECK-NEXT: return [[RESULT]] : $Int
}
struct StructWithStoredProperty : PropertyWithGetter {
var a : Int
// Make sure that accesses aren't going through the generated accessors.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden [ossa] @$s9protocols24StructWithStoredPropertyV011methodUsingE0SiyF
// CHECK: bb0(%0 : $StructWithStoredProperty):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredProperty, #StructWithStoredProperty.a
// CHECK-NEXT: return %2 : $Int
}
// Make sure that we generate direct function calls for out struct protocol
// witness since structs don't do virtual calls for methods.
//
// *NOTE* Even though at first glance the copy_addr looks like a leak
// here, StructWithStoredProperty is a trivial struct implying that no
// leak is occurring. See the test with StructWithStoredClassProperty
// that makes sure in such a case we don't leak. This is due to the
// thunking code being too dumb but it is harmless to program
// correctness.
//
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSivgTW :
// CHECK: bb0([[C:%.*]] : $*StructWithStoredProperty):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [trivial] [[C]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @$s9protocols24StructWithStoredPropertyV1aSivg : $@convention(method) (StructWithStoredProperty) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: return
class C {}
// Make sure that if the getter has a class property, we pass it in
// in_guaranteed and don't leak.
struct StructWithStoredClassProperty : PropertyWithGetter {
var a : Int
var c: C = C()
// Make sure that accesses aren't going through the generated accessors.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden [ossa] @$s9protocols29StructWithStoredClassPropertyV011methodUsingF0SiyF
// CHECK: bb0(%0 : @guaranteed $StructWithStoredClassProperty):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredClassProperty, #StructWithStoredClassProperty.a
// CHECK-NEXT: return %2 : $Int
}
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSivgTW :
// CHECK: bb0([[C:%.*]] : $*StructWithStoredClassProperty):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow [[C]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @$s9protocols29StructWithStoredClassPropertyV1aSivg : $@convention(method) (@guaranteed StructWithStoredClassProperty) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: end_borrow [[CCOPY_LOADED]]
// CHECK-NEXT: return
// rdar://22676810
protocol ExistentialProperty {
var p: PropertyWithGetterSetter { get set }
}
func testExistentialPropertyRead<T: ExistentialProperty>(_ t: inout T) {
let b = t.p.b
}
// CHECK-LABEL: sil hidden [ossa] @$s9protocols27testExistentialPropertyRead{{[_0-9a-zA-Z]*}}F
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*T
// CHECK: [[P_TEMP:%.*]] = alloc_stack $PropertyWithGetterSetter
// CHECK: [[T_TEMP:%.*]] = alloc_stack $T
// CHECK: copy_addr [[READ]] to [initialization] [[T_TEMP]] : $*T
// CHECK: [[P_GETTER:%.*]] = witness_method $T, #ExistentialProperty.p!getter :
// CHECK-NEXT: apply [[P_GETTER]]<T>([[P_TEMP]], [[T_TEMP]])
// CHECK-NEXT: destroy_addr [[T_TEMP]]
// CHECK-NEXT: [[OPEN:%.*]] = open_existential_addr immutable_access [[P_TEMP]] : $*PropertyWithGetterSetter to $*[[P_OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK-NEXT: [[T0:%.*]] = alloc_stack $[[P_OPENED]]
// CHECK-NEXT: copy_addr [[OPEN]] to [initialization] [[T0]]
// CHECK-NEXT: [[B_GETTER:%.*]] = witness_method $[[P_OPENED]], #PropertyWithGetterSetter.b!getter
// CHECK-NEXT: apply [[B_GETTER]]<[[P_OPENED]]>([[T0]])
// CHECK-NEXT: debug_value
// CHECK-NEXT: destroy_addr [[T0]]
// CHECK-NOT: witness_method
// CHECK: return
func modify(_ x: inout Int) {}
func modifyProperty<T : PropertyWithGetterSetter>(_ x: inout T) {
modify(&x.b)
}
// CHECK-LABEL: sil hidden [ossa] @$s9protocols14modifyPropertyyyxzAA0C16WithGetterSetterRzlF
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
// CHECK: [[WITNESS_FN:%.*]] = witness_method $T, #PropertyWithGetterSetter.b!modify
// CHECK: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[WITNESS_FN]]<T>
// CHECK: [[MODIFY_FN:%.*]] = function_ref @$s9protocols6modifyyySizF
// CHECK: apply [[MODIFY_FN]]([[ADDR]])
// CHECK: end_apply [[TOKEN]]
public struct Val {
public var x: Int = 0
}
public protocol Proto {
var val: Val { get nonmutating set}
}
public func test(_ p: Proto) {
p.val.x += 1
}
// CHECK-LABEL: sil [ossa] @$s9protocols4testyyAA5Proto_pF : $@convention(thin) (@in_guaranteed Proto) -> ()
// CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access
// CHECK: [[MAT:%.*]] = witness_method $@opened("{{.*}}") Proto, #Proto.val!modify
// CHECK: ([[BUF:%.*]], [[TOKEN:%.*]]) = begin_apply [[MAT]]
// CHECK: end_apply [[TOKEN]]
// CHECK: return
// SR-11748
protocol SelfReturningSubscript {
subscript(b: Int) -> Self { get }
}
public func testSelfReturningSubscript() {
// CHECK-LABEL: sil private [ossa] @$s9protocols26testSelfReturningSubscriptyyFAA0cdE0_pAaC_pXEfU_
// CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access
// CHECK: [[OPEN_ADDR:%.*]] = alloc_stack $@opened("{{.*}}") SelfReturningSubscript
// CHECK: copy_addr [[OPEN]] to [initialization] [[OPEN_ADDR]] : $*@opened("{{.*}}") SelfReturningSubscript
// CHECK: [[WIT_M:%.*]] = witness_method $@opened("{{.*}}") SelfReturningSubscript, #SelfReturningSubscript.subscript!getter
// CHECK: apply [[WIT_M]]<@opened("{{.*}}") SelfReturningSubscript>({{%.*}}, {{%.*}}, [[OPEN_ADDR]])
_ = [String: SelfReturningSubscript]().mapValues { $0[2] }
}
// CHECK-LABEL: sil_witness_table hidden ClassWithGetter: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetterSetter module protocols {
// CHECK-NEXT: method #PropertyWithGetterSetter.b!getter: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivgTW
// CHECK-NEXT: method #PropertyWithGetterSetter.b!setter: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivsTW
// CHECK-NEXT: method #PropertyWithGetterSetter.b!modify: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivMTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycD0A2aDP1aSivgTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden StructWithStoredProperty: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSivgTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden StructWithStoredClassProperty: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSivgTW
// CHECK-NEXT: }
| apache-2.0 | fa7c983fe4478452ca4c1f5e51fdfc7c | 47.303419 | 270 | 0.637618 | 3.772697 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/Supporting Files/UIComponents/INSPhotosGallery/INSPhotoViewController.swift | 1 | 7754 | //
// INSPhotoViewController.swift
// INSPhotoViewer
//
// Created by Michal Zaborowski on 28.02.2016.
// Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this library except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import AVKit
open class INSPhotoViewController: UIViewController, UIScrollViewDelegate {
var photo: INSPhotoViewable
var longPressGestureHandler: ((UILongPressGestureRecognizer) -> ())?
lazy private(set) var scalingImageView: INSScalingImageView = {
return INSScalingImageView()
}()
lazy private(set) var doubleTapGestureRecognizer: UITapGestureRecognizer = {
let gesture = UITapGestureRecognizer(target: self, action: #selector(INSPhotoViewController.handleDoubleTapWithGestureRecognizer(_:)))
gesture.numberOfTapsRequired = 2
return gesture
}()
lazy private(set) var longPressGestureRecognizer: UILongPressGestureRecognizer = {
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(INSPhotoViewController.handleLongPressWithGestureRecognizer(_:)))
return gesture
}()
lazy private(set) var activityIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
activityIndicator.startAnimating()
return activityIndicator
}()
public init(photo: INSPhotoViewable) {
self.photo = photo
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
scalingImageView.delegate = nil
}
let playerController = INSVideoPlayerViewController()
open override func viewDidLoad() {
super.viewDidLoad()
scalingImageView.delegate = self
scalingImageView.frame = view.bounds
scalingImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(scalingImageView)
view.addSubview(activityIndicator)
activityIndicator.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
activityIndicator.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin]
activityIndicator.sizeToFit()
if photo.localVideoURL != nil || photo.videoURL != nil {
playerController.view.addSubview(scalingImageView)
playerController.view.frame = view.bounds
if let urlString = photo.localVideoURL, let url = URL(string: urlString) {
playerController.player = AVPlayer(url: url)
view.addSubview(playerController.view)
} else if let urlString = photo.videoURL, let url = URL(string: urlString) {
playerController.player = AVPlayer(url: url)
view.addSubview(playerController.view)
}
playerController.view.addGestureRecognizer(doubleTapGestureRecognizer)
}
else {
view.addGestureRecognizer(doubleTapGestureRecognizer)
view.addGestureRecognizer(longPressGestureRecognizer)
}
if let image = photo.image {
self.scalingImageView.image = image
self.activityIndicator.stopAnimating()
} else if let thumbnailImage = photo.thumbnailImage {
self.scalingImageView.image = blurEffect(image: thumbnailImage)
loadFullSizeImage()
} else {
loadThumbnailImage()
}
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scalingImageView.frame = view.bounds
playerController.view.frame = view.bounds
}
private func loadThumbnailImage() {
view.bringSubviewToFront(activityIndicator)
photo.loadThumbnailImageWithCompletionHandler { [weak self] (image, error) -> () in
let completeLoading = {
self?.scalingImageView.image = blurEffect(image: image ?? UIImage())
// if image != nil {
// // self?.activityIndicator.stopAnimating()
// }
self?.loadFullSizeImage()
}
if Thread.isMainThread {
completeLoading()
} else {
DispatchQueue.main.async(execute: { () -> Void in
completeLoading()
})
}
}
}
private func loadFullSizeImage() {
print("loading full size")
view.bringSubviewToFront(activityIndicator)
self.photo.loadImageWithCompletionHandler({ [weak self] (image, error) -> () in
let completeLoading = {
self?.activityIndicator.stopAnimating()
self?.scalingImageView.image = image
}
if Thread.isMainThread {
completeLoading()
} else {
DispatchQueue.main.async(execute: { () -> Void in
completeLoading()
})
}
})
}
@objc private func handleLongPressWithGestureRecognizer(_ recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizer.State.began {
longPressGestureHandler?(recognizer)
}
}
@objc private func handleDoubleTapWithGestureRecognizer(_ recognizer: UITapGestureRecognizer) {
if photo.videoURL != nil || photo.localVideoURL != nil {
if playerController.videoGravity != .resizeAspectFill {
playerController.videoGravity = .resizeAspectFill
} else {
playerController.videoGravity = .resizeAspect
}
return
}
let pointInView = recognizer.location(in: scalingImageView.imageView)
var newZoomScale = scalingImageView.maximumZoomScale
if scalingImageView.zoomScale >= scalingImageView.maximumZoomScale || abs(scalingImageView.zoomScale - scalingImageView.maximumZoomScale) <= 0.01 {
newZoomScale = scalingImageView.minimumZoomScale
}
let scrollViewSize = scalingImageView.bounds.size
let width = scrollViewSize.width / newZoomScale
let height = scrollViewSize.height / newZoomScale
let originX = pointInView.x - (width / 2.0)
let originY = pointInView.y - (height / 2.0)
let rectToZoom = CGRect(x: originX, y: originY, width: width, height: height)
scalingImageView.zoom(to: rectToZoom, animated: true)
}
// MARK:- UIScrollViewDelegate
open func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return scalingImageView.imageView
}
open func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
scrollView.panGestureRecognizer.isEnabled = true
}
open func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
// There is a bug, especially prevalent on iPhone 6 Plus, that causes zooming to render all other gesture recognizers ineffective.
// This bug is fixed by disabling the pan gesture recognizer of the scroll view when it is not needed.
if (scrollView.zoomScale == scrollView.minimumZoomScale) {
scrollView.panGestureRecognizer.isEnabled = false;
}
}
}
| gpl-3.0 | b423d7dc9d1522151b542361b4da3ad3 | 37.562189 | 155 | 0.667527 | 5.283572 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne | 九宫格新/九宫格新/ViewController.swift | 1 | 2735 | //
// ViewController.swift
// 九宫格新
//
// Created by bingoogol on 14/9/30.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
/**
把素材放在bundle,可以允许在不同的bundle中中图片可以重名,实例化图片是需要指定bundle的名字
*/
let COL_COUNT = 5
let ROW_HEIGHT:CGFloat = 100
class ViewController: UIViewController,UITableViewDataSource,ProductCellDelegate {
let CELL_ID = "MyCell"
let PRODUCT_COUNT = 23
weak var tableView:UITableView!
var dataList:NSArray!
override func viewDidLoad() {
super.viewDidLoad()
// 如果成员变量是weak的,则需要重新定义一个变量,然后赋值给成员变量
var tableView = UITableView(frame: UIScreen.mainScreen().applicationFrame)
tableView.dataSource = self
// 表格的代理方法要少用
tableView.rowHeight = ROW_HEIGHT
// 取消分割线
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.view.addSubview(tableView)
self.tableView = tableView
// 初始化数据
var array = NSMutableArray(capacity: PRODUCT_COUNT)
var product:Product
for i in 0 ..< PRODUCT_COUNT {
product = Product.productWithName(NSString(format: "商品-%03d", i))
array.addObject(product)
}
self.dataList = array
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
/*
(1 - 1)/3 + 1 = 1
(2 - 1)/3 + 1 = 1
(3 - 1)/3 + 1 = 1
(4 - 1)/3 + 1 = 2
(5 - 1)/3 + 1 = 2
(6 - 1)/3 + 1 = 2
*/
return (self.dataList.count - 1) / COL_COUNT + 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(CELL_ID) as ProductCell?
if cell == nil {
cell = ProductCell(style: UITableViewCellStyle.Default, reuseIdentifier: CELL_ID)
cell?.delegate = self
}
var loc = indexPath.row * COL_COUNT
var avaliableLen = dataList.count - loc
var len = avaliableLen < COL_COUNT ? avaliableLen : COL_COUNT
var range = NSMakeRange(loc, len)
println("\(loc) \(avaliableLen) \(len)")
var array = self.dataList.subarrayWithRange(range)
cell?.cellRow = indexPath.row
cell?.resetButtonWithArray(array)
return cell!
}
func productCell(productCell: ProductCell, didSelectedAtIndex index: Int) {
var product = dataList[index] as Product
println("click \(product.name)")
}
} | apache-2.0 | 3710e998ddcb2b5a726c6f1657801d53 | 29.722892 | 109 | 0.614359 | 4.178689 | false | false | false | false |
kstaring/swift | stdlib/public/SDK/CoreAudio/CoreAudio.swift | 4 | 6326 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import CoreAudio // Clang module
extension UnsafeBufferPointer {
/// Initialize an `UnsafeBufferPointer<Element>` from an `AudioBuffer`.
/// Binds the buffer's memory type to `Element`.
public init(_ audioBuffer: AudioBuffer) {
let count = Int(audioBuffer.mDataByteSize) / MemoryLayout<Element>.stride
let elementPtr = audioBuffer.mData?.bindMemory(
to: Element.self, capacity: count)
self.init(start: elementPtr, count: count)
}
}
extension UnsafeMutableBufferPointer {
/// Initialize an `UnsafeMutableBufferPointer<Element>` from an
/// `AudioBuffer`.
public init(_ audioBuffer: AudioBuffer) {
let count = Int(audioBuffer.mDataByteSize) / MemoryLayout<Element>.stride
let elementPtr = audioBuffer.mData?.bindMemory(
to: Element.self, capacity: count)
self.init(start: elementPtr, count: count)
}
}
extension AudioBuffer {
/// Initialize an `AudioBuffer` from an
/// `UnsafeMutableBufferPointer<Element>`.
public init<Element>(
_ typedBuffer: UnsafeMutableBufferPointer<Element>,
numberOfChannels: Int
) {
self.mNumberChannels = UInt32(numberOfChannels)
self.mData = UnsafeMutableRawPointer(typedBuffer.baseAddress)
self.mDataByteSize = UInt32(typedBuffer.count * MemoryLayout<Element>.stride)
}
}
extension AudioBufferList {
/// - Returns: the size in bytes of an `AudioBufferList` that can hold up to
/// `maximumBuffers` `AudioBuffer`s.
public static func sizeInBytes(maximumBuffers: Int) -> Int {
_precondition(maximumBuffers >= 1,
"AudioBufferList should contain at least one AudioBuffer")
return MemoryLayout<AudioBufferList>.size +
(maximumBuffers - 1) * MemoryLayout<AudioBuffer>.stride
}
/// Allocate an `AudioBufferList` with a capacity for the specified number of
/// `AudioBuffer`s.
///
/// The `count` property of the new `AudioBufferList` is initialized to
/// `maximumBuffers`.
///
/// The memory should be freed with `free()`.
public static func allocate(maximumBuffers: Int)
-> UnsafeMutableAudioBufferListPointer {
let byteSize = sizeInBytes(maximumBuffers: maximumBuffers)
let ablMemory = calloc(byteSize, 1)
_precondition(ablMemory != nil,
"failed to allocate memory for an AudioBufferList")
let listPtr = ablMemory!.bindMemory(to: AudioBufferList.self, capacity: 1)
(ablMemory! + MemoryLayout<AudioBufferList>.stride).bindMemory(
to: AudioBuffer.self, capacity: maximumBuffers)
let abl = UnsafeMutableAudioBufferListPointer(listPtr)
abl.count = maximumBuffers
return abl
}
}
/// A wrapper for a pointer to an `AudioBufferList`.
///
/// Like `UnsafeMutablePointer`, this type provides no automated memory
/// management and the user must therefore take care to allocate and free
/// memory appropriately.
public struct UnsafeMutableAudioBufferListPointer {
/// Construct from an `AudioBufferList` pointer.
public init(_ p: UnsafeMutablePointer<AudioBufferList>) {
unsafeMutablePointer = p
}
/// Construct from an `AudioBufferList` pointer.
public init?(_ p: UnsafeMutablePointer<AudioBufferList>?) {
guard let unwrapped = p else { return nil }
self.init(unwrapped)
}
/// The number of `AudioBuffer`s in the `AudioBufferList`
/// (`mNumberBuffers`).
public var count: Int {
get {
return Int(unsafeMutablePointer.pointee.mNumberBuffers)
}
nonmutating set(newValue) {
unsafeMutablePointer.pointee.mNumberBuffers = UInt32(newValue)
}
}
/// The pointer to the first `AudioBuffer` in this `AudioBufferList`.
internal var _audioBuffersPointer: UnsafeMutablePointer<AudioBuffer> {
// AudioBufferList has one AudioBuffer in a "flexible array member".
// Position the pointer after that, and skip one AudioBuffer back. This
// brings us to the start of AudioBuffer array.
let rawPtr = UnsafeMutableRawPointer(unsafeMutablePointer + 1)
return rawPtr.assumingMemoryBound(to: AudioBuffer.self) - 1
}
// FIXME: the properties 'unsafePointer' and 'unsafeMutablePointer' should be
// initializers on UnsafePointer and UnsafeMutablePointer, but we don't want
// to allow any UnsafePointer<Element> to be initializable from an
// UnsafeMutableAudioBufferListPointer, only UnsafePointer<AudioBufferList>.
// We need constrained extensions for that. rdar://17821143
/// The pointer to the wrapped `AudioBufferList`.
public var unsafePointer: UnsafePointer<AudioBufferList> {
return UnsafePointer(unsafeMutablePointer)
}
/// The pointer to the wrapped `AudioBufferList`.
public var unsafeMutablePointer: UnsafeMutablePointer<AudioBufferList>
}
extension UnsafeMutableAudioBufferListPointer
: MutableCollection, RandomAccessCollection {
public typealias Index = Int
/// Always zero, which is the index of the first `AudioBuffer`.
public var startIndex: Int {
return 0
}
/// The "past the end" position; always identical to `count`.
public var endIndex: Int {
return count
}
/// Access an indexed `AudioBuffer` (`mBuffers[i]`).
public subscript(index: Int) -> AudioBuffer {
get {
_precondition(index >= 0 && index < self.count,
"subscript index out of range")
return (_audioBuffersPointer + index).pointee
}
nonmutating set(newValue) {
_precondition(index >= 0 && index < self.count,
"subscript index out of range")
(_audioBuffersPointer + index).pointee = newValue
}
}
public subscript(bounds: Range<Int>)
-> MutableRandomAccessSlice<UnsafeMutableAudioBufferListPointer> {
get {
return MutableRandomAccessSlice(base: self, bounds: bounds)
}
set {
_writeBackMutableSlice(&self, bounds: bounds, slice: newValue)
}
}
public typealias Indices = CountableRange<Int>
}
| apache-2.0 | 2ab6cde06af80f9050eee29efe358aa0 | 34.943182 | 81 | 0.70313 | 4.911491 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/uicollectionview-layouts-kit-master/vertical-snap-flow/Core/Layout/VerticalSnapCollectionFlowLayout.swift | 1 | 3514 | //
// SnapCollectionFlowLayout.swift
// snap-flow-layout
//
// Created by Astemir Eleev on 21/05/2018.
// Copyright © 2018 Astemir Eleev. All rights reserved.
//
import UIKit
class VerticalSnapCollectionFlowLayout: UICollectionViewFlowLayout {
// MARK: - Properties
private var firstSetupDone = false
var spacingMultiplier: CGFloat = 6 {
didSet {
invalidateLayout()
}
}
var minLineSpacing: CGFloat = 20 {
didSet {
minimumLineSpacing = minLineSpacing
invalidateLayout()
}
}
var itemHeight: CGFloat = 0 {
didSet {
recalculateItemSize(for: itemHeight)
}
}
// MARK: - Overrides
override func prepare() {
super.prepare()
if !firstSetupDone {
setup()
firstSetupDone = true
}
guard let unwrappedCollectionView = collectionView else {
return
}
let height = unwrappedCollectionView.frame.height
recalculateItemSize(for: height)
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
let layoutAttributes = layoutAttributesForElements(in: collectionView!.bounds)
let centerOffset = collectionView!.bounds.size.height / 2
let offsetWithCenter = proposedContentOffset.y + centerOffset
guard let unwrappedLayoutAttributes = layoutAttributes else {
return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
}
let closestAttribute = unwrappedLayoutAttributes
.sorted { abs($0.center.y - offsetWithCenter) < abs($1.center.y - offsetWithCenter) }
.first ?? UICollectionViewLayoutAttributes()
return CGPoint(x: 0, y: closestAttribute.center.y - centerOffset)
}
// MARK: - Private helpers
private func setup() {
guard let unwrappedCollectionView = collectionView else {
return
}
scrollDirection = .vertical
minimumLineSpacing = minLineSpacing
itemSize = CGSize(width: unwrappedCollectionView.bounds.width, height: itemHeight)
collectionView!.decelerationRate = UIScrollView.DecelerationRate.fast
}
private func recalculateItemSize(for itemHeight: CGFloat) {
guard let unwrappedCollectionView = collectionView else {
return
}
let horizontalContentInset = unwrappedCollectionView.contentInset.left + unwrappedCollectionView.contentInset.right
let verticalContentInset = unwrappedCollectionView.contentInset.bottom + unwrappedCollectionView.contentInset.top
var divider: CGFloat = 1.0
if unwrappedCollectionView.bounds.width > unwrappedCollectionView.bounds.height {
// collection view bounds are in landscape so we change the item width in a way where 2 rows can be displayed
divider = 2.0
}
itemSize = CGSize(width: unwrappedCollectionView.bounds.width / divider - horizontalContentInset, height: itemHeight - (minLineSpacing * spacingMultiplier) - verticalContentInset)
invalidateLayout()
}
}
| mit | 47acea42523f21e4d340a6de16e63fa7 | 33.441176 | 187 | 0.656704 | 5.894295 | false | false | false | false |
HongliYu/firefox-ios | Client/Frontend/Browser/TopTabsViewController.swift | 1 | 10211 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import WebKit
struct TopTabsUX {
static let TopTabsViewHeight: CGFloat = 44
static let TopTabsBackgroundShadowWidth: CGFloat = 12
static let TabWidth: CGFloat = 190
static let FaderPading: CGFloat = 8
static let SeparatorWidth: CGFloat = 1
static let HighlightLineWidth: CGFloat = 3
static let TabNudge: CGFloat = 1 // Nudge the favicon and close button by 1px
static let TabTitlePadding: CGFloat = 10
static let AnimationSpeed: TimeInterval = 0.1
static let SeparatorYOffset: CGFloat = 7
static let SeparatorHeight: CGFloat = 32
}
protocol TopTabsDelegate: AnyObject {
func topTabsDidPressTabs()
func topTabsDidPressNewTab(_ isPrivate: Bool)
func topTabsDidTogglePrivateMode()
func topTabsDidChangeTab()
}
class TopTabsViewController: UIViewController {
let tabManager: TabManager
weak var delegate: TopTabsDelegate?
fileprivate var tabDisplayManager: TabDisplayManager!
var tabCellIdentifer: TabDisplayer.TabCellIdentifer = TopTabCell.Identifier
lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: TopTabsViewLayout())
collectionView.register(TopTabCell.self, forCellWithReuseIdentifier: TopTabCell.Identifier)
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.bounces = false
collectionView.clipsToBounds = false
collectionView.accessibilityIdentifier = "Top Tabs View"
collectionView.semanticContentAttribute = .forceLeftToRight
return collectionView
}()
fileprivate lazy var tabsButton: TabsButton = {
let tabsButton = TabsButton.tabTrayButton()
tabsButton.semanticContentAttribute = .forceLeftToRight
tabsButton.addTarget(self, action: #selector(TopTabsViewController.tabsTrayTapped), for: .touchUpInside)
tabsButton.accessibilityIdentifier = "TopTabsViewController.tabsButton"
return tabsButton
}()
fileprivate lazy var newTab: UIButton = {
let newTab = UIButton.newTabButton()
newTab.semanticContentAttribute = .forceLeftToRight
newTab.addTarget(self, action: #selector(TopTabsViewController.newTabTapped), for: .touchUpInside)
newTab.accessibilityIdentifier = "TopTabsViewController.newTabButton"
return newTab
}()
lazy var privateModeButton: PrivateModeButton = {
let privateModeButton = PrivateModeButton()
privateModeButton.semanticContentAttribute = .forceLeftToRight
privateModeButton.accessibilityIdentifier = "TopTabsViewController.privateModeButton"
privateModeButton.addTarget(self, action: #selector(TopTabsViewController.togglePrivateModeTapped), for: .touchUpInside)
return privateModeButton
}()
fileprivate lazy var tabLayoutDelegate: TopTabsLayoutDelegate = {
let delegate = TopTabsLayoutDelegate()
delegate.tabSelectionDelegate = tabDisplayManager
return delegate
}()
init(tabManager: TabManager) {
self.tabManager = tabManager
super.init(nibName: nil, bundle: nil)
tabDisplayManager = TabDisplayManager(collectionView: self.collectionView, tabManager: self.tabManager, tabDisplayer: self, reuseID: TopTabCell.Identifier)
collectionView.dataSource = tabDisplayManager
collectionView.delegate = tabLayoutDelegate
[UICollectionElementKindSectionHeader, UICollectionElementKindSectionFooter].forEach {
collectionView.register(TopTabsHeaderFooter.self, forSupplementaryViewOfKind: $0, withReuseIdentifier: "HeaderFooter")
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabDisplayManager.refreshStore(evenIfHidden: true)
}
deinit {
tabManager.removeDelegate(self.tabDisplayManager)
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dragDelegate = tabDisplayManager
collectionView.dropDelegate = tabDisplayManager
let topTabFader = TopTabFader()
topTabFader.semanticContentAttribute = .forceLeftToRight
view.addSubview(topTabFader)
topTabFader.addSubview(collectionView)
view.addSubview(tabsButton)
view.addSubview(newTab)
view.addSubview(privateModeButton)
// Setup UIDropInteraction to handle dragging and dropping
// links onto the "New Tab" button.
let dropInteraction = UIDropInteraction(delegate: tabDisplayManager)
newTab.addInteraction(dropInteraction)
newTab.snp.makeConstraints { make in
make.centerY.equalTo(view)
make.trailing.equalTo(tabsButton.snp.leading)
make.size.equalTo(view.snp.height)
}
tabsButton.snp.makeConstraints { make in
make.centerY.equalTo(view)
make.trailing.equalTo(view).offset(-10)
make.size.equalTo(view.snp.height)
}
privateModeButton.snp.makeConstraints { make in
make.centerY.equalTo(view)
make.leading.equalTo(view).offset(10)
make.size.equalTo(view.snp.height)
}
topTabFader.snp.makeConstraints { make in
make.top.bottom.equalTo(view)
make.leading.equalTo(privateModeButton.snp.trailing)
make.trailing.equalTo(newTab.snp.leading)
}
collectionView.snp.makeConstraints { make in
make.edges.equalTo(topTabFader)
}
tabsButton.applyTheme()
applyUIMode(isPrivate: tabManager.selectedTab?.isPrivate ?? false)
updateTabCount(tabDisplayManager.dataStore.count, animated: false)
}
func switchForegroundStatus(isInForeground reveal: Bool) {
// Called when the app leaves the foreground to make sure no information is inadvertently revealed
if let cells = self.collectionView.visibleCells as? [TopTabCell] {
let alpha: CGFloat = reveal ? 1 : 0
for cell in cells {
cell.titleText.alpha = alpha
cell.favicon.alpha = alpha
}
}
}
func updateTabCount(_ count: Int, animated: Bool = true) {
self.tabsButton.updateTabCount(count, animated: animated)
}
@objc func tabsTrayTapped() {
delegate?.topTabsDidPressTabs()
}
@objc func newTabTapped() {
self.delegate?.topTabsDidPressNewTab(self.tabDisplayManager.isPrivate)
LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Add tab button in the URL Bar on iPad"])
}
@objc func togglePrivateModeTapped() {
tabDisplayManager.togglePrivateMode(isOn: !tabDisplayManager.isPrivate, createTabOnEmptyPrivateMode: true)
delegate?.topTabsDidTogglePrivateMode()
self.privateModeButton.setSelected(tabDisplayManager.isPrivate, animated: true)
}
func scrollToCurrentTab(_ animated: Bool = true, centerCell: Bool = false) {
assertIsMainThread("Only animate on the main thread")
guard let currentTab = tabManager.selectedTab, let index = tabDisplayManager.dataStore.index(of: currentTab), !collectionView.frame.isEmpty else {
return
}
if let frame = collectionView.layoutAttributesForItem(at: IndexPath(row: index, section: 0))?.frame {
if centerCell {
collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: false)
} else {
// Padding is added to ensure the tab is completely visible (none of the tab is under the fader)
let padFrame = frame.insetBy(dx: -(TopTabsUX.TopTabsBackgroundShadowWidth+TopTabsUX.FaderPading), dy: 0)
if animated {
UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: {
self.collectionView.scrollRectToVisible(padFrame, animated: true)
})
} else {
collectionView.scrollRectToVisible(padFrame, animated: false)
}
}
}
}
}
extension TopTabsViewController: TabDisplayer {
func focusSelectedTab() {
self.scrollToCurrentTab(true)
}
func cellFactory(for cell: UICollectionViewCell, using tab: Tab) -> UICollectionViewCell {
guard let tabCell = cell as? TopTabCell else { return UICollectionViewCell() }
tabCell.delegate = self
let isSelected = (tab == tabManager.selectedTab)
tabCell.configureWith(tab: tab, isSelected: isSelected)
return tabCell
}
}
extension TopTabsViewController: TopTabCellDelegate {
func tabCellDidClose(_ cell: UICollectionViewCell) {
tabDisplayManager.closeActionPerformed(forCell: cell)
}
}
extension TopTabsViewController: Themeable, PrivateModeUI {
func applyUIMode(isPrivate: Bool) {
tabDisplayManager.togglePrivateMode(isOn: isPrivate, createTabOnEmptyPrivateMode: true)
privateModeButton.onTint = UIColor.theme.topTabs.privateModeButtonOnTint
privateModeButton.offTint = UIColor.theme.topTabs.privateModeButtonOffTint
privateModeButton.applyUIMode(isPrivate: tabDisplayManager.isPrivate)
}
func applyTheme() {
tabsButton.applyTheme()
newTab.tintColor = UIColor.theme.topTabs.buttonTint
view.backgroundColor = UIColor.theme.topTabs.background
collectionView.backgroundColor = view.backgroundColor
tabDisplayManager.refreshStore()
}
}
// Functions for testing
extension TopTabsViewController {
func test_getDisplayManager() -> TabDisplayManager {
assert(AppConstants.IsRunningTest)
return tabDisplayManager
}
}
| mpl-2.0 | 445d8de748cc5217d066410f0c4ed4b8 | 38.886719 | 163 | 0.698169 | 5.431383 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Layers/Hillshade renderer/HillshadeSettingsViewController.swift | 1 | 3938 | // Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
protocol HillshadeSettingsViewControllerDelegate: AnyObject {
func hillshadeSettingsViewController(_ controller: HillshadeSettingsViewController, selectedAltitude altitude: Double, azimuth: Double, slopeType: AGSSlopeType)
}
class HillshadeSettingsViewController: UITableViewController {
@IBOutlet weak var altitudeSlider: UISlider?
@IBOutlet weak var azimuthSlider: UISlider?
@IBOutlet weak var azimuthLabel: UILabel?
@IBOutlet weak var altitudeLabel: UILabel?
@IBOutlet weak var slopeTypeCell: UITableViewCell?
weak var delegate: HillshadeSettingsViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
updateSlopeTypeUI()
updateAltitudeUI()
updateAzimuthUI()
}
private var slopeTypeOptions: [AGSSlopeType] = [.none, .degree, .percentRise, .scaled]
private let numberFormatter = NumberFormatter()
private func labelForSlopeType(_ slopeType: AGSSlopeType) -> String {
switch slopeType {
case .none: return "None"
case .degree: return "Degree"
case .percentRise: return "Percent Rise"
case .scaled: return "Scaled"
@unknown default: return "Unknown"
}
}
var slopeType: AGSSlopeType = .none {
didSet {
updateSlopeTypeUI()
}
}
private func updateSlopeTypeUI() {
slopeTypeCell?.detailTextLabel?.text = labelForSlopeType(slopeType)
}
var altitude: Double = 0 {
didSet {
updateAltitudeUI()
}
}
private func updateAltitudeUI() {
altitudeLabel?.text = numberFormatter.string(from: altitude as NSNumber)
altitudeSlider?.value = Float(altitude)
}
var azimuth: Double = 0 {
didSet {
updateAzimuthUI()
}
}
private func updateAzimuthUI() {
azimuthLabel?.text = numberFormatter.string(from: azimuth as NSNumber)
azimuthSlider?.value = Float(azimuth)
}
private func hillshadeParametersChanged() {
delegate?.hillshadeSettingsViewController(self, selectedAltitude: altitude, azimuth: azimuth, slopeType: slopeType)
}
// MARK: - Actions
@IBAction func azimuthSliderValueChanged(_ slider: UISlider) {
azimuth = Double(slider.value)
hillshadeParametersChanged()
}
@IBAction func altitudeSliderValueChanged(_ slider: UISlider) {
altitude = Double(slider.value)
hillshadeParametersChanged()
}
// UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard tableView.cellForRow(at: indexPath) == slopeTypeCell else {
return
}
let labels = slopeTypeOptions.map { (slopeType) -> String in
return labelForSlopeType(slopeType)
}
let selectedIndex = slopeTypeOptions.firstIndex(of: slopeType)!
let optionsViewController = OptionsTableViewController(labels: labels, selectedIndex: selectedIndex) { (newIndex) in
self.slopeType = self.slopeTypeOptions[newIndex]
self.hillshadeParametersChanged()
}
optionsViewController.title = "Slope Type"
show(optionsViewController, sender: self)
}
}
| apache-2.0 | d6747521963fe8fbb3a4655571f08fcc | 32.65812 | 164 | 0.672676 | 4.89801 | false | false | false | false |
jpush/jchat-swift | JChat/Src/Utilites/ExJMessage/Extensions/JMSGMessage+.swift | 1 | 8009 | //
// JMSGMessage+.swift
// JChat
//
// Created by JIGUANG on 2017/10/1.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import JMessage
let kLargeEmoticon = "kLargeEmoticon"
let kShortVideo = "video"
let kBusinessCard = "businessCard"
let kBusinessCardName = "userName"
let kBusinessCardAppKey = "appKey"
let kFileType = "fileType"
let kFileSize = "fileSize"
extension ExJMessage where Base: JMSGMessage {
var state: JCMessageState {
switch base.status {
case .sendFailed, .sendUploadFailed:
return .sendError
case .sending:
return .sending
default:
return .sendSucceed
}
}
var isFile: Bool {
guard let extras = _messageExtras(.file) else {
return false
}
if extras.keys.contains(where: { (key) -> Bool in
if let key = key as? String {
return key == kFileType || key == kFileSize
}
return false
}) {
return true
}
return false
}
var fileType: String? {
if !self.isFile {
return nil
}
guard let extras = base.content?.extras else {
return nil
}
return extras[kFileType] as? String
}
var fileSize: String? {
if !self.isFile {
return nil
}
guard let extras = base.content?.extras else {
return nil
}
if let size = extras[kFileSize] as? Int {
if size > 1024 * 1024 {
return String(format: "%.1fM", Double(size) / 1024.0 / 1024.0)
}
if size > 1024 {
return "\(size / 1024)K"
}
return "\(size)B"
}
return nil
}
var businessCardName: String? {
if !self.isBusinessCard {
return nil
}
guard let extras = base.content?.extras else {
return nil
}
return extras[kBusinessCardName] as? String
}
var businessCardAppKey: String? {
if !self.isBusinessCard {
return nil
}
guard let extras = base.content?.extras else {
return nil
}
return extras[kBusinessCardAppKey] as? String
}
var isBusinessCard: Bool {
get {
guard let extras = _messageExtras(.text) else {
return false
}
if extras.keys.contains(where: { (key) -> Bool in
if let key = key as? String {
return key == kBusinessCard
}
return false
}) {
return true
}
return false
}
set {
if let content = base.content as? JMSGTextContent {
content.addStringExtra(kBusinessCard, forKey: kBusinessCard)
}
}
}
var isShortVideo: Bool {
get {
guard let extras = _messageExtras(.file) else {
return false
}
if extras.keys.contains(where: { (key) -> Bool in
if let key = key as? String {
return key == kShortVideo
}
return false
}) {
return true
}
return false
}
// set {
// if let content = base.content as? JMSGFileContent {
// content.addStringExtra("mov", forKey: kShortVideo)
// }
// }
}
var isLargeEmoticon: Bool {
get {
guard let extras = _messageExtras(.image) else {
return false
}
if extras.keys.contains(where: { (key) -> Bool in
if let key = key as? String {
// android 的扩展字段:jiguang
return key == kLargeEmoticon || key == "jiguang"
}
return false
}) {
return true
}
return false
}
set {
if let content = base.content as? JMSGImageContent {
content.addStringExtra(kLargeEmoticon, forKey: kLargeEmoticon)
}
}
}
static func createBusinessCardMessage(_ conversation: JMSGConversation, _ userName: String, _ appKey: String) -> JMSGMessage {
let message: JMSGMessage!
let content = JMSGTextContent(text: "推荐了一张名片")
content.addStringExtra(userName, forKey: "userName")
content.addStringExtra(appKey, forKey: "appKey")
if conversation.ex.isGroup {
let group = conversation.target as! JMSGGroup
message = JMSGMessage.createGroupMessage(with: content, groupId: group.gid)
} else if conversation.ex.isChatRoom{
let chatRoom = conversation.target as! JMSGChatRoom
message = JMSGMessage.createChatRoomMessage(with: content, chatRoomId: chatRoom.roomID)
} else{
let user = conversation.target as! JMSGUser
message = JMSGMessage.createSingleMessage(with: content, username: user.username)
}
message.ex.isBusinessCard = true
return message
}
static func createBusinessCardMessage(gid: String, userName: String, appKey: String) -> JMSGMessage {
let message: JMSGMessage!
let content = JMSGTextContent(text: "推荐了一张名片")
content.addStringExtra(userName, forKey: "userName")
content.addStringExtra(appKey, forKey: "appKey")
message = JMSGMessage.createGroupMessage(with: content, groupId: gid)
message.ex.isBusinessCard = true
return message
}
/**
create a @ message
*/
static func createMessage(_ conversation: JMSGConversation, _ content: JMSGAbstractContent, _ reminds: [JCRemind]?) -> JMSGMessage {
var message: JMSGMessage?
if conversation.ex.isGroup {
let group = conversation.target as! JMSGGroup
if reminds != nil && reminds!.count > 0 {
var users: [JMSGUser] = []
var isAtAll = false
for remind in reminds! {
guard let user = remind.user else {
isAtAll = true
break
}
users.append(user)
}
if isAtAll {
message = JMSGMessage.createGroupAtAllMessage(with: content, groupId: group.gid)
} else {
message = JMSGMessage.createGroupMessage(with: content, groupId: group.gid, at_list: users)
}
} else {
message = JMSGMessage.createGroupMessage(with: content, groupId: group.gid)
}
} else if conversation.ex.isChatRoom {
let room = conversation.target as! JMSGChatRoom
message = JMSGMessage.createChatRoomMessage(with: content, chatRoomId: room.roomID)
} else {// conversation.ex.isSingle
let user = conversation.target as! JMSGUser
message = JMSGMessage.createSingleMessage(with: content, username: user.username)
}
return message!
}
// MARK: - private method
/**
get current message extras
*/
private func _messageExtras(_ contentType: JMSGContentType) -> [AnyHashable : Any]? {
let content: JMSGAbstractContent?
switch contentType {
case .text:
content = base.content as? JMSGTextContent
case .image:
content = base.content as? JMSGImageContent
case .file:
content = base.content as? JMSGFileContent
default:
return nil
}
guard let messsageContent = content else {
return nil
}
guard let extras = messsageContent.extras else {
return nil
}
return extras
}
}
| mit | 9419f499d208c45bea76ec6e29ea1a35 | 30.239216 | 136 | 0.534647 | 4.626016 | false | false | false | false |
steelwheels/iGlyphTrainer | GTGameData/Source/Preference/GTGUIPreference.swift | 1 | 1656 | /**
* @file GTGUIPreference.m
* @brief Define GTGUIPreference
* @par Copyright
* Copyright (C) 2016-2017 Steel Wheels Project
*/
import Foundation
import KiwiGraphics
import KiwiControls
public class GTGUIPreference
{
public static let backgroundColor: CGColor = KGColorTable.black.cgColor
public static func progressColor(scene s:GTScene) -> CGColor {
var result: CGColor
switch s {
case .StartScene: result = KGColorTable.gold.cgColor
case .QuestionScene: result = KGColorTable.gold.cgColor
case .AnswerScene: result = KGColorTable.cyan.cgColor
case .CheckScene: result = KGColorTable.cyan.cgColor
}
return result
}
public static let progressStrokeWidth: CGFloat = 2.0
public static let hintTextColor = KGColorPreference.TextColors(foreground: KGColorTable.darkGoldenrod4,
background: KGColorTable.darkGoldenrod3)
public static let glyphNameTextColor = KGColorPreference.TextColors(foreground: KGColorTable.gold,
background: KGColorTable.black)
public static let timerFontColor:CGColor = KGColorTable.gold.cgColor
public static let maxGlyphSize: CGFloat = 375
public static let glyphVertexColor: CGColor = KGColorTable.white.cgColor
public static let glyphStrokeWidth: CGFloat = 10.0
public static let glyphStrokeColor: CGColor = KGColorTable.gold.cgColor
public static let buttonColor = KGColorPreference.ButtonColors(title: KGColorTable.cyan,
background: KGColorPreference.BackgroundColors(highlight: KGColorTable.darkGray, normal: KGColorTable.black))
}
| gpl-2.0 | a15e758c31e9287143ca4a6ff3452b9d | 37.511628 | 111 | 0.728865 | 3.952267 | false | false | false | false |
sapphirezzz/ZInAppPurchase | ZInAppPurchase/Classes/ZInAppPurchase.swift | 1 | 4771 | //
// ZInAppPurchase.swift
// Meijiabang
//
// Created by Zack on 16/5/26.
// Copyright © 2016年 Double. All rights reserved.
//
import Foundation
import StoreKit
enum ZInAppPurchaseError: String {
case ProductIdNil
case ProductInfoRequestFailed
case ProductNotExisited
case PurchaseWasForbidden
case ErrorUnknown
case ClientInvalid
case PaymentCancelled
case PaymentInvalid
case PaymentNotAllowed
case StoreProductNotAvailable
}
class ZInAppPurchase: NSObject {
static let sharedInstance = ZInAppPurchase()
private override init() {super.init()}
var successAction: ((receipt: String)->Void)?
var failureAction: ((error: ZInAppPurchaseError)->Void)?
func purchaseProduct(productId: String?, successAction: ((receipt: String)->Void)? = nil, failureAction: ((error: ZInAppPurchaseError)->Void)? = nil) {
self.successAction = successAction
self.failureAction = failureAction
guard let productId = productId else {
failureAction?(error: ZInAppPurchaseError.ProductIdNil)
return
}
let productRequest = SKProductsRequest(productIdentifiers: Set<String>(arrayLiteral: productId))
productRequest.delegate = self
productRequest.start()
}
}
extension ZInAppPurchase: SKProductsRequestDelegate {
func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
if let product = response.products.first {
if SKPaymentQueue.canMakePayments() {
let payment = SKPayment(product: product)
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().addPayment(payment)
}else {
failureAction?(error: ZInAppPurchaseError.PurchaseWasForbidden)
}
}else {
failureAction?(error: ZInAppPurchaseError.ProductNotExisited)
}
}
func requestDidFinish(request: SKRequest) {
print("ZInAppPurchase request requestDidFinish")
}
func request(request: SKRequest, didFailWithError error: NSError) {
print("ZInAppPurchase request didFailWithError error = ", error)
failureAction?(error: ZInAppPurchaseError.ProductInfoRequestFailed)
}
}
extension ZInAppPurchase: SKPaymentTransactionObserver {
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .Purchased: // Transaction is in queue, user has been charged. Client should complete the transaction.
if let receiptUrl = NSBundle.mainBundle().appStoreReceiptURL, let receiptData = NSData(contentsOfURL: receiptUrl) {
let receiptString = receiptData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
successAction?(receipt: receiptString)
}else {
failureAction?(error: ZInAppPurchaseError.ErrorUnknown)
}
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
case .Failed: // Transaction was cancelled or failed before being added to the server queue.
if let code = transaction.error?.code , let errorCode = SKErrorCode(rawValue: code) {
switch errorCode {
case SKErrorCode.Unknown:
failureAction?(error: ZInAppPurchaseError.ErrorUnknown)
case SKErrorCode.ClientInvalid:
failureAction?(error: ZInAppPurchaseError.ClientInvalid)
case SKErrorCode.PaymentCancelled:
failureAction?(error: ZInAppPurchaseError.PaymentCancelled)
case SKErrorCode.PaymentInvalid:
failureAction?(error: ZInAppPurchaseError.PaymentInvalid)
case SKErrorCode.PaymentNotAllowed:
failureAction?(error: ZInAppPurchaseError.PaymentNotAllowed)
case SKErrorCode.StoreProductNotAvailable:
failureAction?(error: ZInAppPurchaseError.StoreProductNotAvailable)
default:
failureAction?(error: ZInAppPurchaseError.ErrorUnknown)
}
}else {
failureAction?(error: ZInAppPurchaseError.ErrorUnknown)
}
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
default:
break
}
}
}
}
| mit | 473b81a2b5878dd122b3d5a04419f775 | 38.404959 | 155 | 0.636745 | 5.821734 | false | false | false | false |
MisterZhouZhou/Objective-C-Swift-StudyDemo | SwiftDemo/SwiftDemo/classes/Category/ZWClassFromString.swift | 1 | 805 | //
// ZWClassFromString.swift
// Swift-Demo
//
// Created by rayootech on 16/6/17.
// Copyright © 2016年 rayootech. All rights reserved.
//
import Foundation
import UIKit
extension NSObject {
func swiftClassFromString(className: String) -> UIViewController! {
// get the project name
if let appName: String = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as! String? {
//拼接控制器名
let classStringName = "\(appName).\(className)"
//将控制名转换为类
let classType = NSClassFromString(classStringName) as? UIViewController.Type
if let type = classType {
let newVC = type.init()
return newVC
}
}
return nil;
}
}
| apache-2.0 | 845d995e3efd3fb07f6a3120c76c53bd | 23.1875 | 112 | 0.596899 | 4.526316 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/Helpers/Formatter.swift | 1 | 1195 | //
// Formatter.swift
// Inbbbox
//
// Created by Radoslaw Szeja on 14/12/15.
// Copyright © 2015 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
struct Formatter {
struct Date {
/// Basic date formatter with format yyyy-MM-dd
static var Basic: DateFormatter {
return Date.basicDateFormatter
}
/// Timestamp date formatter with ISO 8601 format yyyy-MM-dd'T'HH:mm:ssZZZZZ
static var Timestamp: DateFormatter {
return Date.timestampDateFormatter
}
}
}
private extension Formatter.Date {
static var basicDateFormatter = { Void -> DateFormatter in
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
static var timestampDateFormatter = { Void -> DateFormatter in
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}
| gpl-3.0 | ca573d046c6428584515ad097b0aecaa | 27.428571 | 84 | 0.654941 | 4.522727 | false | false | false | false |
LetItPlay/iOSClient | blockchainapp/UndBlurLabel.swift | 1 | 3605 | //
// UndBlurLabel.swift
// blockchainapp
//
// Created by Aleksey Tyurnin on 21/11/2017.
// Copyright © 2017 Ivan Gorbulin. All rights reserved.
//
import UIKit
import SnapKit
class UndBlurLabel: UIView {
// let blurView = UIVisualEffectView.init(effect: UIBlurEffect.init(style: UIBlurEffectStyle.regular))
let label: UILabel = UILabel.init(frame: CGRect.zero)
let shapeLayer: CAShapeLayer = CAShapeLayer()
init() {
super.init(frame: CGRect.zero)
self.backgroundColor = AppColor.Element.redBlur.withAlphaComponent(0.9)
// self.addSubview(blurView)
// blurView.snp.makeConstraints { (make) in
// make.edges.equalToSuperview()
// }
self.addSubview(label)
label.numberOfLines = 3
self.label.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(4)
}
// self.layer.mask = shapeLayer
}
// override func layoutSubviews() {
// super.layoutSubviews()
//// if let title = label.text, title != "" {
//// self.updateShape(text: title)
//// } else {
//// self.updateShape(text: " ")
//// }
// }
func setTitle(title: String) {
self.label.attributedText = formatString(text: title)
// self.layoutSubviews()
}
func updateShape(text: String) {
let widths = self.calcLinesWidths(text: formatString(text: text, calc: true), frame: self.label.frame).map({$0 + 4 + 4 + 4})
if widths.count > 0 {
let tooBig = widths.count > 3
let path = UIBezierPath.init()
path.move(to: CGPoint.zero)
path.addLine(to: CGPoint.init(x: min(widths[0], self.frame.width), y: 0))
path.addLine(to: CGPoint.init(x: min(widths[0], self.frame.width), y: 4))
for i in 1..<widths.prefix(3).count {
path.addLine(to: CGPoint.init(x: min(widths[i - 1], self.frame.width) , y: CGFloat(i*29) + 4))
path.addLine(to: CGPoint.init(x: min(widths[i], self.frame.width), y: CGFloat(i*29) + 4))
}
if tooBig {
path.addLine(to: CGPoint.init(x: self.frame.width, y: path.currentPoint.y))
path.addLine(to: CGPoint.init(x: self.frame.width, y: self.frame.height))
} else {
path.addLine(to: CGPoint.init(x: min(widths.last ?? 500.0, self.frame.width), y: self.frame.height))
}
path.addLine(to: CGPoint.init(x: 0, y: self.frame.height))
path.close()
self.shapeLayer.path = path.cgPath
} else {
self.shapeLayer.path = UIBezierPath.init(rect: CGRect.init(origin: CGPoint.zero, size: self.frame.size)).cgPath
}
}
func formatString(text: String, calc: Bool = false) -> NSAttributedString {
let para = NSMutableParagraphStyle()
para.alignment = .left
para.minimumLineHeight = 29
para.maximumLineHeight = 29
para.lineBreakMode = calc ? .byWordWrapping : .byTruncatingTail
return NSAttributedString.init(string: text,
attributes: [.font: UIFont.systemFont(ofSize: 24, weight: .regular),
.foregroundColor: UIColor.white,
.paragraphStyle: para])
// .kern:
}
func calcLinesWidths(text: NSAttributedString, frame: CGRect) -> [CGFloat] {
var newFrame = frame
newFrame.size.height = 200
var result: [CGFloat] = []
let fs = CTFramesetterCreateWithAttributedString(text)
let frame = CTFramesetterCreateFrame(fs, CFRangeMake(0, 0), CGPath.init(rect: newFrame, transform: nil), nil)
let lines = CTFrameGetLines(frame)
for line in lines as! Array<CTLine> {
let bounds = CTLineGetBoundsWithOptions(line, .useGlyphPathBounds)
let range = CTLineGetStringRange(line)
print("range = \(range.location) \(range.length)")
result.append(bounds.width - bounds.origin.x)
}
return result
}
required init?(coder aDecoder: NSCoder) {
return nil
}
}
| mit | eea5934684b596d31b7f98476a844f06 | 31.763636 | 126 | 0.683962 | 3.223614 | false | false | false | false |
ysnrkdm/Graphene | Sources/Graphene/BoardBuilder.swift | 1 | 1642 | //
// BoardBuilder.swift
// FlatReversi
//
// Created by Kodama Yoshinori on 10/30/14.
// Copyright (c) 2014 Yoshinori Kodama. All rights reserved.
//
import Foundation
open class BoardBuilder {
public class func build(_ fromText: String) -> BoardRepresentation {
let board = SimpleBitBoard()
board.initialize(8, height: 8)
var i = 0
for c in fromText.characters {
switch(c) {
case "B", "O":
board.set(.black, x: i % 8, y: i / 8)
case "W", "X":
board.set(.white, x: i % 8, y: i / 8)
case ".", "-":
board.set(.empty, x: i % 8, y: i / 8)
default:
assertionFailure("")
}
i += 1
}
return build(board)
}
public class func build(_ fromBoard: Board) -> BoardRepresentation {
let bm = BoardMediator(board: fromBoard)
let ret = BoardRepresentation(boardMediator: bm)
return ret
}
public class func buildBitBoard(_ fromText: String) -> BoardRepresentation {
let board = SimpleBitBoard()
board.initialize(8, height: 8)
var i = 0
for c in fromText.characters {
switch(c) {
case "B":
board.set(.black, x: i % 8, y: i / 8)
case "W":
board.set(.white, x: i % 8, y: i / 8)
case ".":
board.set(.empty, x: i % 8, y: i / 8)
default:
assertionFailure("")
}
i += 1
}
return build(board)
}
}
| mit | c890563f175caeb00f2f6ce874a34760 | 25.918033 | 80 | 0.474421 | 3.995134 | false | false | false | false |
mruiz723/CourseiOSSwift3 | HelloWorld/HelloWorld/Controllers/ViewController.swift | 1 | 1357 | //
// ViewController.swift
// HelloWorld
//
// Created by Marlon David Ruiz Arroyave on 9/22/17.
// Copyright © 2017 Eafit. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var welcomeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sendName(_ sender: Any) {
if (nameTextField.text?.characters.count)! > 0 {
welcomeLabel.text = "Welcome \(nameTextField.text!)!!!"
welcomeLabel.isHidden = false
}else {
welcomeLabel.isHidden = true
let alertController = UIAlertController(title: "Error", message: "Debes digitar tu nombre", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
view.endEditing(true) //Hide the keyboard
}
}
| mit | fe654c276ae292da3b0366e6bc90bf58 | 26.12 | 127 | 0.613569 | 5.040892 | false | false | false | false |
Eonil/Monolith.Swift | UIKitExtras/Sources/StaticTable/StaticTableViewController.swift | 3 | 16643 | //
// StaticTableViewController.swift
// CratesIOViewer
//
// Created by Hoon H. on 11/22/14.
//
//
import Foundation
import UIKit
//private let UILayoutPriorityRequired = 1000
//private let UILayoutPriorityDefaultHigh = 750
//private let UILayoutPriorityFittingSizeLevel = 50
private let REQUIRED = 1000 as Float
private let HIGH = 750 as Float
private let FITTING = 50 as Float
/// This class is designed for very small amount of cells.
/// Keeps all cells in memory.
public class StaticTableViewController: UITableViewController {
public typealias Table = StaticTable
public typealias Section = StaticTableSection
public typealias Row = StaticTableRow
private var _table = nil as Table?
deinit {
if let t = _table {
unownTable(t)
}
}
private func ownTable(targetTable:Table) {
precondition(table.hostTableViewController == nil, "Supplied table object alread bound to another table view controller.")
table.hostTableViewController = self
tableView?.tableHeaderView = table.header
tableView?.tableFooterView = table.footer
tableView?.reloadData()
}
private func unownTable(targetTable:Table) {
assert(table.hostTableViewController == self)
table.hostTableViewController = nil
tableView?.tableHeaderView = nil
tableView?.tableFooterView = nil
}
/// Table must be always non-nil value.
public final var table:Table {
get {
if _table == nil {
_table = Table()
ownTable(_table!)
}
return _table!
}
set(v) {
if _table != nil {
unownTable(_table!)
}
_table = v
ownTable(_table!)
}
// willSet {
// assert(table.hostTableViewController == self)
// table.hostTableViewController = nil
//
// tableView?.tableHeaderView = nil
// tableView?.tableFooterView = nil
// }
// didSet {
// precondition(table.hostTableViewController == nil, "Supplied table object alread bound to another table view controller.")
// table.hostTableViewController = self
// tableView?.tableHeaderView = table.header
// tableView?.tableFooterView = table.footer
// tableView?.reloadData()
// }
}
public override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return table.sections.count ||| 0
}
public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return table.sections[section].rows.count
}
public override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let sz = tableView.bounds.size
let sz1 = CGSize(width: sz.width, height: 0)
return table.sections[section].header?.heightAsCellInTableView(tableView) ||| 0
}
public override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let sz = tableView.bounds.size
let sz1 = CGSize(width: sz.width, height: 0)
return table.sections[section].footer?.heightAsCellInTableView(tableView) ||| 0
}
public override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return table.sections[section].header
}
public override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return table.sections[section].footer
}
public override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return table.rowAtIndexPath(indexPath).cell.heightAsCellInTableView(tableView)
}
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return table.rowAtIndexPath(indexPath).cell
}
public override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
return table.rowAtIndexPath(indexPath).willSelect()?.indexPath
}
public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
table.rowAtIndexPath(indexPath).didSelect()
}
public override func tableView(tableView: UITableView, willDeselectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
return table.rowAtIndexPath(indexPath).willDeselect()?.indexPath
}
public override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
table.rowAtIndexPath(indexPath).didDeselect()
}
}
private extension UIView {
func heightForMaximumWidth(width:CGFloat) -> CGFloat {
assert(width >= 0)
let sz1 = systemLayoutSizeFittingSize(CGSize(width: width, height: 0), withHorizontalFittingPriority: HIGH, verticalFittingPriority: FITTING)
return sz1.height
// let sz2 = intrinsicContentSize()
// return max(sz1.height, sz2.height)
}
func heightAsCellInTableView(tableView:UITableView) -> CGFloat {
return heightForMaximumWidth(tableView.bounds.size.width)
}
}
/// If you need to modify multiple elements at once, then the best practice is
/// making a new table and replacing whole table with it instead replacing each elements.
public class StaticTable {
public typealias Section = StaticTableSection
public typealias Row = StaticTableRow
private var _sections = [] as [Section]
public init() {
}
deinit {
for s in _sections {
s.table = nil
}
}
/// There's no effective way to set the header's size automatically using auto-layout.
/// You must set its frame manually BEFORE passing it into this property.
public var header:UIView? {
didSet {
assertView____SHOULD____SupportTranslationOfAutoresizingLayout(header)
// if let v = header {
// v.frame = CGRect(origin: CGPointZero, size: v.systemLayoutSizeFittingSize(CGSizeZero))
// }
hostTableViewController?.tableView?.tableHeaderView = header
}
}
/// There's no effective way to set the footer's size automatically using auto-layout.
/// You must set its frame manually BEFORE passing it into this property.
public var footer:UIView? {
didSet {
assertView____SHOULD____SupportTranslationOfAutoresizingLayout(footer)
// if let v = header {
// v.frame = CGRect(origin: CGPointZero, size: v.systemLayoutSizeFittingSize(CGSizeZero))
// }
hostTableViewController?.tableView?.tableFooterView = footer
}
}
public var sections:[Section] {
get {
return _sections
}
set(v) {
for s in _sections {
assert(s.table === self, "Old sections must still be bound to this table.")
s.table = nil
}
_sections = v
for s in _sections {
assert(s.table === self, "New sections must not be bound to any section.")
s.table = nil
}
reloadSelf()
}
}
public func setSections(sections:[Section], animation:UITableViewRowAnimation) {
if let t = hostTableViewController?.tableView {
_sections = []
t.deleteSections(NSIndexSet(indexesInRange: NSRange(location: 0, length: sections.count)), withRowAnimation: animation)
_sections = sections
t.insertSections(NSIndexSet(indexesInRange: NSRange(location: 0, length: sections.count)), withRowAnimation: animation)
}
}
public func insertSection(s:Section, atIndex:Int, animation:UITableViewRowAnimation) {
precondition(s.table == nil, "Supplied section must not be bound to a table.")
assert(hostTableViewController?.tableView == nil || _sections.count == hostTableViewController?.tableView?.numberOfSections())
_sections.insert(s, atIndex: atIndex)
s.table = self
hostTableViewController?.tableView?.insertSections(NSIndexSet(intArray: [atIndex]), withRowAnimation: animation)
}
public func replaceSectionAtIndex(index:Int, withSection:Section, animation:UITableViewRowAnimation) {
precondition(withSection.table == nil, "Supplied section must not be bound to a table.")
assert(sections[index].table === self)
if sections[index] !== withSection {
let old = sections[index]
old.table = nil
_sections[index] = withSection
withSection.table = self
withSection.reloadSelfInTable(animation: animation)
}
}
public func deleteSectionAtIndex(index:Int, animation:UITableViewRowAnimation) {
assert(sections[index].table === self)
sections[index].table = nil
_sections.removeAtIndex(index)
hostTableViewController?.tableView?.deleteSections(NSIndexSet(intArray: [index]), withRowAnimation: animation)
}
private func reloadSelf() {
hostTableViewController?.tableView?.reloadData()
}
private func reloadSectionsAtIndexes(indexes:[Int], animation:UITableViewRowAnimation) {
hostTableViewController?.tableView?.reloadSections(NSIndexSet(intArray: indexes), withRowAnimation: animation)
}
private weak var hostTableViewController:UITableViewController? {
didSet {
}
}
}
public class StaticTableSection {
public typealias Table = StaticTable
public typealias Row = StaticTableRow
private var _rows = [] as [Row]
private var _header : UIView?
private var _footer : UIView?
public init() {
}
deinit {
for r in _rows {
r.section = nil
}
}
/// Height will be resolved using auto-layout. (`systemLayoutSizeFittingSize`)
public var header:UIView? {
get {
return _header
}
set(v) {
setHeaderWithAnimation(v, animation: UITableViewRowAnimation.None)
}
}
/// Height will be resolved using auto-layout. (`systemLayoutSizeFittingSize`)
public var footer:UIView? {
get {
return _footer
}
set(v) {
setFooterWithAnimation(v, animation: UITableViewRowAnimation.None)
}
}
public var rows:[StaticTableRow] {
get {
return _rows
}
set(v) {
setRows(v, animation: UITableViewRowAnimation.None)
}
}
public func setHeaderWithAnimation(v:UIView?, animation:UITableViewRowAnimation) {
assertView____SHOULD____SupportTranslationOfAutoresizingLayout(v)
_header = v
if table != nil {
reloadSelfInTable(animation: animation)
}
}
public func setFooterWithAnimation(v:UIView?, animation:UITableViewRowAnimation) {
assertView____SHOULD____SupportTranslationOfAutoresizingLayout(v)
_footer = v
if table != nil {
reloadSelfInTable(animation: animation)
}
}
public func setRows(rows:[Row], animation:UITableViewRowAnimation) {
for r in _rows {
assert(r.section === self, "Old rows must still be bound to this section.")
r.section = nil
}
_rows = rows
for r in _rows {
assert(r.section === nil, "New rows must not be bound to any section.")
r.section = self
}
reloadSelfInTable(animation: animation)
}
public func insertRow(r:Row, atIndex:Int, animation:UITableViewRowAnimation) {
precondition(r.section == nil, "Supplied row must not be bound to a section.")
r.section = self
_rows.insert(r, atIndex: atIndex)
table?.hostTableViewController?.tableView?.insertRowsAtIndexPaths([NSIndexPath(forRow: atIndex, inSection: indexInTable!)], withRowAnimation: animation)
}
public func replaceRowAtIndex(index:Int, withRow:Row, animation:UITableViewRowAnimation) {
precondition(withRow.section == nil, "Supplied row must not be bound to a section.")
assert(rows[index].section === self)
if rows[index] !== withRow {
let old = rows[index]
old.section = nil
withRow.section = self
_rows[index] = withRow
withRow.reloadSelfInSection(animation: animation)
}
}
public func deleteRowAtIndex(index:Int, animation:UITableViewRowAnimation) {
assert(rows[index].section === self)
rows[index].section = nil
_rows.removeAtIndex(index)
table?.hostTableViewController?.tableView?.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: indexInTable!)], withRowAnimation: animation)
}
public func deleteAllRowsWithAnimation(animation:UITableViewRowAnimation) {
for r in rows {
r.section = nil
}
_rows.removeAll(keepCapacity: false)
reloadSelfInTable(animation: animation)
}
public func reloadSelfWithAnimation(animation:UITableViewRowAnimation) {
reloadSelfInTable(animation: animation)
}
private weak var table:Table? {
didSet {
}
}
private var indexInTable:Int? {
get {
if let t = table {
for i in 0..<t.sections.count {
if t.sections[i] === self {
return i
}
}
}
return nil
}
}
private func reloadSelfInTable(#animation:UITableViewRowAnimation) {
table?.reloadSectionsAtIndexes([indexInTable!], animation: animation)
}
private func reloadRowsAtIndexes(indexes:[Int], animation:UITableViewRowAnimation) {
if let sidx = indexInTable {
var idxps = [] as [NSIndexPath]
for idx in indexes {
idxps.append(NSIndexPath(forRow: idx, inSection: indexInTable!))
}
table?.hostTableViewController?.tableView?.reloadRowsAtIndexPaths(idxps, withRowAnimation: animation)
}
}
}
public class StaticTableRow {
public typealias Table = StaticTable
public typealias Section = StaticTableSection
private var _cell : UITableViewCell
public init(cell:UITableViewCell) {
_cell = cell
}
public var cell:UITableViewCell {
get {
return _cell
}
}
/// Return another row object if you want to override.
public func willSelect() -> StaticTableRow? {
return self
}
public func didSelect() {
}
/// Return another row object if you want to override.
public func willDeselect() -> StaticTableRow? {
return self
}
public func didDeselect() {
}
public func setCell(cell:UITableViewCell, animation:UITableViewRowAnimation) {
_cell = cell
reloadSelfInSection(animation: UITableViewRowAnimation.None)
}
private weak var section:Section? {
didSet {
}
}
private var indexInSection:Int? {
get {
if let s = section {
for i in 0..<s.rows.count {
if s.rows[i] === self {
return i
}
}
}
return nil
}
}
private func reloadSelfInSection(#animation:UITableViewRowAnimation) {
section?.reloadRowsAtIndexes([indexInSection!], animation: animation)
}
}
public extension StaticTable {
public func rowAtIndexPath(indexPath:NSIndexPath) -> Row {
return sections[indexPath.section].rows[indexPath.row]
}
public func appendSection(section:Section, animation:UITableViewRowAnimation) {
insertSection(section, atIndex: sections.count, animation: animation)
}
public func appendSection(section:Section) {
insertSection(section, atIndex: sections.count, animation: UITableViewRowAnimation.None)
}
public func insertSectionAtIndex(index:Int, animation:UITableViewRowAnimation) {
insertSection(Section(), atIndex: index, animation: animation)
}
public func appendSectionWithAnimation(animation:UITableViewRowAnimation) -> Section {
insertSectionAtIndex(sections.count, animation: animation)
return sections.last!
}
public func appendSection() -> Section {
appendSectionWithAnimation(UITableViewRowAnimation.None)
return sections.last!
}
public func deleteSectionAtIndex(index:Int) {
deleteSectionAtIndex(index, animation: UITableViewRowAnimation.None)
}
public func deleteLastSection() {
deleteSectionAtIndex(sections.count-1)
}
}
public extension StaticTableSection {
public func appendRow(row:Row, animation:UITableViewRowAnimation) {
insertRow(row, atIndex: rows.count, animation: animation)
}
public func appendRow(row:Row) {
appendRow(row, animation: UITableViewRowAnimation.None)
}
public func insertRowAtIndex(index:Int, animation:UITableViewRowAnimation) {
insertRow(Row(cell: UITableViewCell()), atIndex: index, animation: animation)
}
public func appendRowWithAnimation(animation:UITableViewRowAnimation) -> Row {
insertRowAtIndex(rows.count, animation: animation)
return rows.last!
}
public func appendRow() -> Row {
appendRowWithAnimation(UITableViewRowAnimation.None)
return rows.last!
}
public func deleteRowAtIndex(index:Int) {
deleteRowAtIndex(index, animation: UITableViewRowAnimation.None)
}
public func deleteLastRow() {
deleteRowAtIndex(rows.count-1)
}
public func deleteAllRows() {
deleteAllRowsWithAnimation(UITableViewRowAnimation.None)
}
}
public extension StaticTableRow {
public var indexPath:NSIndexPath? {
get {
if section == nil { return nil }
return NSIndexPath(forRow: indexInSection!, inSection: section!.indexInTable!)
}
}
}
private extension NSIndexSet {
convenience init(intArray:[Int]) {
let s1 = NSMutableIndexSet()
for v in intArray {
s1.addIndex(v)
}
self.init(indexSet: s1)
}
var intArray:[Int] {
get {
var a1 = [] as [Int]
self.enumerateIndexesUsingBlock { (index:Int, _) -> Void in
a1.append(index)
}
return a1
}
}
}
private func assertView____SHOULD____SupportTranslationOfAutoresizingLayout(v:UIView?) {
assert(v == nil || v!.translatesAutoresizingMaskIntoConstraints() == true, "Layout of table/section header/footer view are controlled by `UITableView`, then it should support translation of autoresizing masks.")
}
| mit | 8fc26f4a7e15d7307d6e48ee300fd97a | 25.671474 | 212 | 0.733401 | 3.690244 | false | false | false | false |
domenicosolazzo/practice-swift | Views/ScrollViews/ScrollViews/ScrollViews/PagedScrollViewController.swift | 1 | 4525 | //
// PagedScrollViewController.swift
// ScrollViews
//
// Created by Domenico on 06/06/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
class PagedScrollViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var pageControl: UIPageControl!
// It will hold all the images to display. 1 for page
var pageImages: [UIImage] = []
// It will hold instances of UIImageView to display each image on its respective page
var pageViews: [UIImageView?] = []
override func viewDidLoad() {
super.viewDidLoad()
// set up the page images
pageImages = [UIImage(named: "photo1.png")!,
UIImage(named: "photo2.png")!,
UIImage(named: "photo3.png")!,
UIImage(named: "photo4.png")!,
UIImage(named: "photo5.png")!]
let pageCount = pageImages.count
// set the page control to the first page and tell it how many pages there are.
pageControl.currentPage = 0
pageControl.numberOfPages = pageCount
// Set up the array that holds the UIImageView instances. At first, no pages have been lazily loaded and so you just fill it with nil objects as placeholders – one for each page
for _ in 0..<pageCount {
pageViews.append(nil)
}
// The scroll view, as before, needs to know its content size. Since you want a horizontal paging scroll view (it could just as easily be vertical if you want), you calculate the width to be the number of pages multiplied by the width of the scroll view. The height of the content is the same as the height of the scroll view.
let pagesScrollViewSize = scrollView.frame.size
scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageImages.count),
height: pagesScrollViewSize.height)
// need some pages shown initially
loadVisiblePages()
}
func loadPage(_ page: Int) {
if page < 0 || page >= pageImages.count {
// If it's outside the range of what you have to display, then do nothing
return
}
// Using optional binding to check if you’ve already loaded the view
if let pageView = pageViews[page] {
// Do nothing. The view is already loaded.
} else {
// Need to create a page
var frame = scrollView.bounds
frame.origin.x = frame.size.width * CGFloat(page)
frame.origin.y = 0.0
// It creates a new UIImageView, sets it up and adds it to the scroll view
let newPageView = UIImageView(image: pageImages[page])
newPageView.contentMode = .scaleAspectFit
newPageView.frame = frame
scrollView.addSubview(newPageView)
// Replace the nil in the pageViews array with the view you’ve just created
pageViews[page] = newPageView
}
}
func purgePage(_ page: Int) {
if page < 0 || page >= pageImages.count {
// If it's outside the range of what you have to display, then do nothing
return
}
// Remove a page from the scroll view and reset the container array
if let pageView = pageViews[page] {
pageView.removeFromSuperview()
pageViews[page] = nil
}
}
func loadVisiblePages() {
// First, determine which page is currently visible
let pageWidth = scrollView.frame.size.width
let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))
// Update the page control
pageControl.currentPage = page
// Work out which pages you want to load
let firstPage = page - 1
let lastPage = page + 1
// Purge anything before the first page
for index in 0 ..< firstPage += 1 {
purgePage(index)
}
// Load pages in our range
for index in firstPage...lastPage {
loadPage(index)
}
// Purge anything after the last page
for index in lastPage+1 ..< pageImages.count += 1 {
purgePage(index)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// Load the pages that are now on screen
loadVisiblePages()
}
}
| mit | dfc0425fc8bdb7db35ccc10933da0e6a | 36.658333 | 334 | 0.599469 | 5.049162 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/BuySellKit/Core/Service/OrderCreationService.swift | 1 | 2102 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import DIKit
import RxSwift
/// Used to create a pending order when the user confirms the transaction
public protocol OrderCreationServiceAPI: AnyObject {
func create(using candidateOrderDetails: CandidateOrderDetails) -> Single<CheckoutData>
}
final class OrderCreationService: OrderCreationServiceAPI {
// MARK: - Service Error
enum ServiceError: Error {
case mappingError
}
// MARK: - Properties
private let analyticsRecorder: AnalyticsEventRecorderAPI
private let client: OrderCreationClientAPI
// MARK: - Setup
init(
analyticsRecorder: AnalyticsEventRecorderAPI = resolve(),
client: OrderCreationClientAPI = resolve()
) {
self.analyticsRecorder = analyticsRecorder
self.client = client
}
// MARK: - API
func create(using candidateOrderDetails: CandidateOrderDetails) -> Single<CheckoutData> {
let data = OrderPayload.Request(
quoteId: candidateOrderDetails.quoteId,
action: candidateOrderDetails.action,
fiatValue: candidateOrderDetails.fiatValue,
fiatCurrency: candidateOrderDetails.fiatCurrency,
cryptoValue: candidateOrderDetails.cryptoValue,
paymentType: candidateOrderDetails.paymentMethod?.method,
paymentMethodId: candidateOrderDetails.paymentMethodId
)
let creation = client
.create(
order: data,
createPendingOrder: true
)
.asSingle()
.map(weak: self) { (self, response) in
OrderDetails(recorder: self.analyticsRecorder, response: response)
}
.map { details -> OrderDetails in
guard let details = details else {
throw ServiceError.mappingError
}
return details
}
.map { CheckoutData(order: $0) }
return creation
.asObservable()
.asSingle()
}
}
| lgpl-3.0 | 7627da62e44ee13a260f9cddbea592c0 | 29.897059 | 93 | 0.631128 | 5.48564 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.