repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lotpb/iosSQLswift
|
refs/heads/master
|
mySQLswift/LeadUserController.swift
|
gpl-2.0
|
1
|
//
// LeadUserController.swift
// mySQLswift
//
// Created by Peter Balsamo on 1/2/16.
// Copyright © 2016 Peter Balsamo. All rights reserved.
//
import UIKit
import Parse
class LeadUserController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let cellHeadtitle = UIFont.systemFontOfSize(20, weight: UIFontWeightBold)
let cellHeadsubtitle = UIFont.systemFontOfSize(18, weight: UIFontWeightLight)
let cellHeadlabel = UIFont.systemFontOfSize(18, weight: UIFontWeightRegular)
let ipadtitle = UIFont.systemFontOfSize(20, weight: UIFontWeightRegular)
let ipadsubtitle = UIFont.systemFontOfSize(16, weight: UIFontWeightRegular)
let ipadlabel = UIFont.systemFontOfSize(16, weight: UIFontWeightRegular)
let cellsubtitle = UIFont.systemFontOfSize(16, weight: UIFontWeightRegular)
let celllabel = UIFont.systemFontOfSize(16, weight: UIFontWeightRegular)
let headtitle = UIFont.systemFontOfSize(UIFont.smallSystemFontSize())
@IBOutlet weak var tableView: UITableView?
var _feedItems : NSMutableArray = NSMutableArray()
var _feedheadItems : NSMutableArray = NSMutableArray()
var filteredString : NSMutableArray = NSMutableArray()
var objects = [AnyObject]()
var pasteBoard = UIPasteboard.generalPasteboard()
var refreshControl: UIRefreshControl!
var emptyLabel : UILabel?
var objectId : NSString?
var leadDate : NSString?
var postBy : NSString?
var comments : NSString?
var formController : NSString?
//var selectedImage : UIImage?
override func viewDidLoad() {
super.viewDidLoad()
let titleButton: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 32))
titleButton.setTitle(formController as? String, forState: UIControlState.Normal)
titleButton.titleLabel?.font = Font.navlabel
titleButton.titleLabel?.textAlignment = NSTextAlignment.Center
titleButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
titleButton.addTarget(self, action: Selector(), forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.titleView = titleButton
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.estimatedRowHeight = 110
self.tableView!.rowHeight = UITableViewAutomaticDimension
self.tableView!.backgroundColor = UIColor.whiteColor()
tableView!.tableFooterView = UIView(frame: .zero)
self.automaticallyAdjustsScrollViewInsets = false
self.parseData()
//self.selectedImage = UIImage(named:"profile-rabbit-toy.png")
if (self.formController == "Blog") {
self.comments = "90 percent of my picks made $$$. The stock whisper has traded over 1000 traders worldwide"
}
let shareButton = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: Selector())
let buttons:NSArray = [shareButton]
self.navigationItem.rightBarButtonItems = buttons as? [UIBarButtonItem]
self.refreshControl = UIRefreshControl()
refreshControl.backgroundColor = UIColor.clearColor()
refreshControl.tintColor = UIColor.blackColor()
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl.addTarget(self, action: #selector(LeadUserController.refreshData), forControlEvents: UIControlEvents.ValueChanged)
self.tableView!.addSubview(refreshControl)
emptyLabel = UILabel(frame: self.view.bounds)
emptyLabel!.textAlignment = NSTextAlignment.Center
emptyLabel!.textColor = UIColor.lightGrayColor()
emptyLabel!.text = "You have no customer data :)"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//navigationController?.hidesBarsOnSwipe = true
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.barTintColor = UIColor(white:0.45, alpha:1.0)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
//navigationController?.hidesBarsOnSwipe = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - refresh
func refreshData(sender:AnyObject)
{
self.tableView!.reloadData()
self.refreshControl?.endRefreshing()
}
// MARK: - Table View
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView {
return _feedItems.count ?? 0
}
//return foundUsers.count
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cellIdentifier: String!
if tableView == self.tableView {
cellIdentifier = "Cell"
} else {
cellIdentifier = "UserFoundCell"
}
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! CustomTableCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.blogsubtitleLabel!.textColor = UIColor.grayColor()
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad {
cell.blogtitleLabel!.font = ipadtitle
cell.blogsubtitleLabel!.font = ipadsubtitle
cell.blogmsgDateLabel!.font = ipadlabel
cell.commentLabel!.font = ipadlabel
} else {
cell.blogtitleLabel!.font = Font.celltitle
cell.blogsubtitleLabel!.font = cellsubtitle
cell.blogmsgDateLabel!.font = celllabel
cell.commentLabel!.font = celllabel
}
let dateStr : String
let dateFormatter = NSDateFormatter()
if (self.formController == "Blog") {
dateStr = (_feedItems[indexPath.row] .valueForKey("MsgDate") as? String)!
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
} else {
dateStr = (_feedItems[indexPath.row] .valueForKey("Date") as? String)!
dateFormatter.dateFormat = "yyyy-MM-dd"
}
let date:NSDate = dateFormatter.dateFromString(dateStr)as NSDate!
dateFormatter.dateFormat = "MMM dd, yyyy"
if (self.formController == "Blog") {
cell.blogtitleLabel!.text = _feedItems[indexPath.row] .valueForKey("PostBy") as? String
cell.blogsubtitleLabel!.text = _feedItems[indexPath.row] .valueForKey("Subject") as? String
cell.blogmsgDateLabel!.text = dateFormatter.stringFromDate(date)as String!
var CommentCount:Int? = _feedItems[indexPath.row] .valueForKey("CommentCount")as? Int
if CommentCount == nil {
CommentCount = 0
}
cell.commentLabel?.text = "\(CommentCount!)"
} else {
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
cell.blogtitleLabel!.text = _feedItems[indexPath.row] .valueForKey("LastName") as? String
cell.blogsubtitleLabel!.text = _feedItems[indexPath.row] .valueForKey("City") as? String
cell.blogmsgDateLabel!.text = dateFormatter.stringFromDate(date)as String!
var CommentCount:Int? = _feedItems[indexPath.row] .valueForKey("Amount")as? Int
if CommentCount == nil {
CommentCount = 0
}
cell.commentLabel?.text = formatter.stringFromNumber(CommentCount!)
}
cell.actionBtn.tintColor = UIColor.lightGrayColor()
let imagebutton : UIImage? = UIImage(named:"Upload50.png")!.imageWithRenderingMode(.AlwaysTemplate)
cell.actionBtn .setImage(imagebutton, forState: .Normal)
//actionBtn .addTarget(self, action: "shareButton:", forControlEvents: UIControlEvents.TouchUpInside)
cell.replyButton.tintColor = UIColor.lightGrayColor()
let replyimage : UIImage? = UIImage(named:"Commentfilled.png")!.imageWithRenderingMode(.AlwaysTemplate)
cell.replyButton .setImage(replyimage, forState: .Normal)
//cell.replyButton .addTarget(self, action: "replyButton:", forControlEvents: UIControlEvents.TouchUpInside)
if !(cell.commentLabel.text! == "0") {
cell.commentLabel.textColor = UIColor.lightGrayColor()
} else {
cell.commentLabel.text! = ""
}
if (cell.commentLabel.text! == "") {
cell.replyButton.tintColor = UIColor.lightGrayColor()
} else {
cell.replyButton.tintColor = UIColor.redColor()
}
let myLabel:UILabel = UILabel(frame: CGRectMake(10, 10, 50, 50))
if (self.formController == "Leads") {
myLabel.text = "Cust"
} else if (self.formController == "Customer") {
myLabel.text = "Lead"
} else if (self.formController == "Blog") {
myLabel.text = "Blog"
}
myLabel.backgroundColor = UIColor(red: 0.02, green: 0.75, blue: 1.0, alpha: 1.0)
myLabel.textColor = UIColor.whiteColor()
myLabel.textAlignment = NSTextAlignment.Center
myLabel.layer.masksToBounds = true
myLabel.font = headtitle
myLabel.layer.cornerRadius = 25.0
myLabel.userInteractionEnabled = true
cell.addSubview(myLabel)
return cell
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 180.0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let vw = UIView()
vw.backgroundColor = UIColor(white:0.90, alpha:1.0)
//tableView.tableHeaderView = vw
let myLabel4:UILabel = UILabel(frame: CGRectMake(10, 70, self.tableView!.frame.size.width-20, 50))
let myLabel5:UILabel = UILabel(frame: CGRectMake(10, 105, self.tableView!.frame.size.width-20, 50))
let myLabel6:UILabel = UILabel(frame: CGRectMake(10, 140, self.tableView!.frame.size.width-20, 50))
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad {
myLabel4.font = cellHeadtitle
myLabel5.font = cellHeadsubtitle
myLabel6.font = cellHeadlabel
} else {
myLabel4.font = cellHeadtitle
myLabel5.font = cellHeadsubtitle
myLabel6.font = cellHeadlabel
}
let myLabel1:UILabel = UILabel(frame: CGRectMake(10, 15, 50, 50))
myLabel1.numberOfLines = 0
myLabel1.backgroundColor = UIColor.whiteColor()
myLabel1.textColor = UIColor.blackColor()
myLabel1.textAlignment = NSTextAlignment.Center
myLabel1.layer.masksToBounds = true
myLabel1.text = String(format: "%@%d", "Count\n", _feedItems.count)
myLabel1.font = headtitle
myLabel1.layer.cornerRadius = 25.0
myLabel1.userInteractionEnabled = true
vw.addSubview(myLabel1)
let separatorLineView1 = UIView(frame: CGRectMake(10, 75, 50, 2.5))
separatorLineView1.backgroundColor = UIColor.whiteColor()
vw.addSubview(separatorLineView1)
let myLabel2:UILabel = UILabel(frame: CGRectMake(80, 15, 50, 50))
myLabel2.numberOfLines = 0
myLabel2.backgroundColor = UIColor.whiteColor()
myLabel2.textColor = UIColor.blackColor()
myLabel2.textAlignment = NSTextAlignment.Center
myLabel2.layer.masksToBounds = true
myLabel2.text = String(format: "%@%d", "Active\n", _feedheadItems.count)
myLabel2.font = headtitle
myLabel2.layer.cornerRadius = 25.0
myLabel2.userInteractionEnabled = true
vw.addSubview(myLabel2)
let separatorLineView2 = UIView(frame: CGRectMake(80, 75, 50, 2.5))
separatorLineView2.backgroundColor = UIColor.whiteColor()
vw.addSubview(separatorLineView2)
let myLabel3:UILabel = UILabel(frame: CGRectMake(150, 15, 50, 50))
myLabel3.numberOfLines = 0
myLabel3.backgroundColor = UIColor.whiteColor()
myLabel3.textColor = UIColor.blackColor()
myLabel3.textAlignment = NSTextAlignment.Center
myLabel3.layer.masksToBounds = true
myLabel3.text = "Active"
myLabel3.font = headtitle
myLabel3.layer.cornerRadius = 25.0
myLabel3.userInteractionEnabled = true
vw.addSubview(myLabel3)
myLabel4.numberOfLines = 1
myLabel4.backgroundColor = UIColor.clearColor()
myLabel4.textColor = UIColor.blackColor()
myLabel4.layer.masksToBounds = true
myLabel4.text = self.postBy as? String
vw.addSubview(myLabel4)
myLabel5.numberOfLines = 0
myLabel5.backgroundColor = UIColor.clearColor()
myLabel5.textColor = UIColor.blackColor()
myLabel5.layer.masksToBounds = true
myLabel5.text = self.comments as? String
vw.addSubview(myLabel5)
if (self.formController == "Leads") || (self.formController == "Customer") {
var dateStr = self.leadDate as? String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date:NSDate = dateFormatter.dateFromString(dateStr!) as NSDate!
dateFormatter.dateFormat = "MMM dd, yyyy"
dateStr = dateFormatter.stringFromDate(date)as String!
var newString6 : String
if (self.formController == "Leads") {
newString6 = String(format: "%@%@", "Lead since ", dateStr!)
myLabel6.text = newString6
} else if (self.formController == "Customer") {
newString6 = String(format: "%@%@", "Customer since ", dateStr!)
myLabel6.text = newString6
} else if (self.formController == "Blog") {
newString6 = String(format: "%@%@", "Member since ", (self.leadDate as? String)!)
myLabel6.text = newString6
}
}
myLabel6.numberOfLines = 1
myLabel6.backgroundColor = UIColor.clearColor()
myLabel6.textColor = UIColor.blackColor()
myLabel6.layer.masksToBounds = true
//myLabel6.text = newString6
vw.addSubview(myLabel6)
let separatorLineView3 = UIView(frame: CGRectMake(150, 75, 50, 2.5))
separatorLineView3.backgroundColor = UIColor.whiteColor()
vw.addSubview(separatorLineView3)
return vw
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
// MARK: - Content Menu
func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
if (action == #selector(NSObject.copy(_:))) {
return true
}
return false
}
func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
pasteBoard.string = cell!.textLabel?.text
}
// MARK: - Parse
func parseData() {
if (self.formController == "Leads") {
let query = PFQuery(className:"Customer")
query.limit = 1000
query.whereKey("LastName", equalTo:self.postBy!)
query.cachePolicy = PFCachePolicy.CacheThenNetwork
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self._feedItems = temp.mutableCopy() as! NSMutableArray
if (self._feedItems.count == 0) {
self.tableView!.addSubview(self.emptyLabel!)
} else {
self.emptyLabel!.removeFromSuperview()
}
self.tableView!.reloadData()
} else {
print("Error")
}
}
let query1 = PFQuery(className:"Leads")
query1.limit = 1
query1.whereKey("objectId", equalTo:self.objectId!)
query1.cachePolicy = PFCachePolicy.CacheThenNetwork
query1.orderByDescending("createdAt")
query1.getFirstObjectInBackgroundWithBlock {(object: PFObject?, error: NSError?) -> Void in
if error == nil {
self.comments = object!.objectForKey("Coments") as! String
self.leadDate = object!.objectForKey("Date") as! String
self.tableView!.reloadData()
} else {
print("Error")
}
}
} else if (self.formController == "Customer") {
let query = PFQuery(className:"Leads")
query.limit = 1000
query.whereKey("LastName", equalTo:self.postBy!)
query.cachePolicy = PFCachePolicy.CacheThenNetwork
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self._feedItems = temp.mutableCopy() as! NSMutableArray
if (self._feedItems.count == 0) {
self.tableView!.addSubview(self.emptyLabel!)
} else {
self.emptyLabel!.removeFromSuperview()
}
self.tableView!.reloadData()
} else {
print("Error")
}
}
let query1 = PFQuery(className:"Customer")
query1.limit = 1
query1.whereKey("objectId", equalTo:self.objectId!)
query1.cachePolicy = PFCachePolicy.CacheThenNetwork
query1.orderByDescending("createdAt")
query1.getFirstObjectInBackgroundWithBlock {(object: PFObject?, error: NSError?) -> Void in
if error == nil {
self.comments = object!.objectForKey("Comments") as! String
self.leadDate = object!.objectForKey("Date") as! String
self.tableView!.reloadData()
} else {
print("Error")
}
}
} else if (self.formController == "Blog") {
let query = PFQuery(className:"Blog")
query.limit = 1000
query.whereKey("PostBy", equalTo:self.postBy!)
query.cachePolicy = PFCachePolicy.CacheThenNetwork
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self._feedItems = temp.mutableCopy() as! NSMutableArray
if (self._feedItems.count == 0) {
self.tableView!.addSubview(self.emptyLabel!)
} else {
self.emptyLabel!.removeFromSuperview()
}
self.tableView!.reloadData()
} else {
print("Error")
}
}
let query1:PFQuery = PFUser.query()!
query1.whereKey("username", equalTo:self.postBy!)
query1.limit = 1
query1.cachePolicy = PFCachePolicy.CacheThenNetwork
query1.getFirstObjectInBackgroundWithBlock {(object: PFObject?, error: NSError?) -> Void in
if error == nil {
self.postBy = object!.objectForKey("username") as! String
/*
let dateStr = (object!.objectForKey("createdAt") as? NSDate)!
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let createAtString = dateFormatter.stringFromDate(dateStr)as String!
self.leadDate = createAtString */
/*
if let imageFile = object!.objectForKey("imageFile") as? PFFile {
imageFile.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
self.selectedImage = UIImage(data: imageData!)
self.tableView!.reloadData()
}
} */
}
}
}
}
// MARK: - Segues
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
}
|
1d36de32eb097e2020b180aefa03d257
| 41.011152 | 160 | 0.60092 | false | false | false | false |
iOS-mamu/SS
|
refs/heads/master
|
P/genstrings.swift
|
mit
|
1
|
#!/usr/bin/swift
import Foundation
class GenStrings {
let fileManager = NSFileManager.defaultManager()
let acceptedFileExtensions = ["swift"]
let excludedFolderNames = ["Carthage"]
let excludedFileNames = ["genstrings.swift"]
var regularExpresions = [String:NSRegularExpression]()
let localizedRegex = "(?<=\")([^\"]*)(?=\".(localized|localizedFormat))|(?<=(Localized|NSLocalizedString)\\(\")([^\"]*?)(?=\")"
enum GenstringsError:ErrorType {
case Error
}
// Performs the genstrings functionality
func perform() {
let rootPath = NSURL(fileURLWithPath:fileManager.currentDirectoryPath)
let allFiles = fetchFilesInFolder(rootPath)
// We use a set to avoid duplicates
var localizableStrings = Set<String>()
for filePath in allFiles {
let stringsInFile = localizableStringsInFile(filePath)
localizableStrings = localizableStrings.union(stringsInFile)
}
// We sort the strings
let sortedStrings = localizableStrings.sort({ $0 < $1 })
var processedStrings = String()
for string in sortedStrings {
processedStrings.appendContentsOf("\"\(string)\" = \"\(string)\"; \n")
}
print(processedStrings)
}
// Applies regex to a file at filePath.
func localizableStringsInFile(filePath: NSURL) -> Set<String> {
if let fileContentsData = NSData(contentsOfURL: filePath), let fileContentsString = NSString(data: fileContentsData, encoding: NSUTF8StringEncoding) {
do {
let localizedStringsArray = try regexMatches(localizedRegex, string: fileContentsString as String).map({fileContentsString.substringWithRange($0.range)})
return Set(localizedStringsArray)
} catch {}
}
return Set<String>()
}
//MARK: Regex
func regexWithPattern(pattern: String) throws -> NSRegularExpression {
var safeRegex = regularExpresions
if let regex = safeRegex[pattern] {
return regex
}
else {
do {
let currentPattern: NSRegularExpression
currentPattern = try NSRegularExpression(pattern: pattern, options:NSRegularExpressionOptions.CaseInsensitive)
safeRegex.updateValue(currentPattern, forKey: pattern)
self.regularExpresions = safeRegex
return currentPattern
}
catch {
throw GenstringsError.Error
}
}
}
func regexMatches(pattern: String, string: String) throws -> [NSTextCheckingResult] {
do {
let internalString = string
let currentPattern = try regexWithPattern(pattern)
// NSRegularExpression accepts Swift strings but works with NSString under the hood. Safer to bridge to NSString for taking range.
let nsString = internalString as NSString
let stringRange = NSMakeRange(0, nsString.length)
let matches = currentPattern.matchesInString(internalString, options: [], range: stringRange)
return matches
}
catch {
throw GenstringsError.Error
}
}
//MARK: File manager
func fetchFilesInFolder(rootPath: NSURL) -> [NSURL] {
var files = [NSURL]()
do {
let directoryContents = try fileManager.contentsOfDirectoryAtURL(rootPath, includingPropertiesForKeys: [], options: .SkipsHiddenFiles)
for urlPath in directoryContents {
if let stringPath = urlPath.path, lastPathComponent = urlPath.lastPathComponent, pathExtension = urlPath.pathExtension {
var isDir : ObjCBool = false
if fileManager.fileExistsAtPath(stringPath, isDirectory:&isDir) {
if isDir {
if !excludedFolderNames.contains(lastPathComponent) {
let dirFiles = fetchFilesInFolder(urlPath)
files.appendContentsOf(dirFiles)
}
} else {
if acceptedFileExtensions.contains(pathExtension) && !excludedFileNames.contains(lastPathComponent) {
files.append(urlPath)
}
}
}
}
}
} catch {}
return files
}
}
let genStrings = GenStrings()
genStrings.perform()
|
650bdb31da7d52ce9974b370447db01f
| 38.834783 | 169 | 0.592884 | false | false | false | false |
LeonClover/DouYu
|
refs/heads/master
|
DouYuZB/DouYuZB/Classes/Main/ViewModel/BaseViewModel.swift
|
mit
|
1
|
//
// BaseViewModel.swift
// DouYuZB
//
// Created by Leon on 2017/8/3.
// Copyright © 2017年 pingan. All rights reserved.
//
import UIKit
class BaseViewModel {
lazy var anchorGroup: [AnchorGroup] = [AnchorGroup]()
}
extension BaseViewModel {
func loadAnchorData(isGroupData: Bool, URLString: String, parameters: [String : Any]? = nil, finishedCallback: @escaping () -> ()) {
NetworkTools.requestData(.get, URLString: URLString, parameters: parameters) { (result) in
guard let resultDict = result as? [String : Any] else { return }
guard let dataArray = resultDict["data"] as? [[String : Any]] else { return }
//MARK: 判断是否是分组数据
if isGroupData{
for dict in dataArray{
self.anchorGroup.append(AnchorGroup(dict: dict))
}
}else {
let group = AnchorGroup()
for dict in dataArray{
group.anchors.append(AnchorModel(dict: dict))
}
self.anchorGroup.append(group)
}
finishedCallback()
}
}
}
|
42de715bf0efcc0d07ff7c3d6fd5fc42
| 30.27027 | 136 | 0.554019 | false | false | false | false |
ingresse/ios-sdk
|
refs/heads/dev
|
IngresseSDK/Services/User/Requests/UserTransactionsRequest.swift
|
mit
|
1
|
//
// Copyright © 2022 Ingresse. All rights reserved.
//
import Alamofire
public struct UserTransactionsRequest: Encodable {
public let usertoken: String
public let status: String?
public let pageSize: Int?
public let page: Int?
public init(userToken: String) {
self.usertoken = userToken
self.status = nil
self.pageSize = nil
self.page = nil
}
public init(userToken: String,
status: Self.Status?,
pageSize: Int?,
page: Int?) {
self.usertoken = userToken
self.status = status?.rawValue
self.pageSize = pageSize
self.page = page
}
public init(userToken: String,
status: [Self.Status]?,
pageSize: Int?,
page: Int?) {
self.usertoken = userToken
self.status = status?
.map {$0.rawValue}
.joined(separator: ",")
self.pageSize = pageSize
self.page = page
}
public enum Status: String, Encodable {
case approved = "approved"
case authorized = "authorized"
case declined = "declined"
case error = "error"
case manualReview = "manual review"
case pending = "pending"
case refund = "refund"
}
}
|
469c38540737f5c37858dbfc5fd49f15
| 23.727273 | 51 | 0.535294 | false | false | false | false |
zhangchn/swelly
|
refs/heads/master
|
swelly/Connection.swift
|
gpl-2.0
|
1
|
//
// Connection.swift
// swelly
//
// Created by ZhangChen on 05/10/2016.
//
//
import AppKit
enum ConnectionProtocol {
case ssh
case telnet
}
extension Notification.Name {
static let connectionDidConnect = Notification.Name(rawValue: "conn_did_connect")
static let connectionDidDisconnect = Notification.Name(rawValue: "conn_did_disconn")
}
class Connection : NSObject, PTYDelegate {
var icon: NSImage?
var processing: Bool = false
private var _lastTouchDate : Date?
var lastTouchDate : Date? { get { return _lastTouchDate } }
var connected: Bool! {
didSet {
if connected! {
icon = NSImage(named: "online.pdf")
} else {
resetMessageCount()
icon = NSImage(named: "offline.pdf")
}
}
}
var terminal: Terminal! {
didSet {
terminal.connection = self
terminalFeeder.terminal = terminal
}
}
var terminalFeeder = TerminalFeeder()
var pty: PTY?
var site: Site
var userName: String!
var messageDelegate = MessageDelegate()
var messageCount: Int = 0
init(site: Site){
self.site = site
}
func setup() {
if !site.isDummy {
pty = PTY(proxyAddress: site.proxyAddress, proxyType: site.proxyType)
pty!.delegate = self
_ = pty!.connect(addr: site.address, connectionProtocol: site.connectionProtocol, userName: userName)
}
}
// PTY Delegate
func ptyWillConnect(_ pty: PTY) {
processing = true
connected = false
icon = NSImage(named: "waiting.pdf")
}
func ptyDidConnect(_ pty: PTY) {
processing = false
connected = true
Thread.detachNewThread {
autoreleasepool { [weak self] () in
self?.login()
}
}
NotificationCenter.default.post(name: .connectionDidConnect, object: self)
}
func pty(_ pty: PTY, didRecv data: Data) {
terminalFeeder.feed(data: data, connection: self)
}
func pty(_ pty: PTY, willSend data: Data) {
_lastTouchDate = Date()
}
func ptyDidClose(_ pty: PTY) {
processing = false
connected = false
terminalFeeder.clearAll()
terminal.clearAll()
NotificationCenter.default.post(name: .connectionDidDisconnect, object: self)
}
func close() {
pty?.close()
}
func reconnect() {
pty?.close()
_ = pty?.connect(addr: site.address, connectionProtocol: site.connectionProtocol, userName: userName)
resetMessageCount()
}
func sendMessage(msg: Data) {
pty?.send(data:msg)
}
func sendMessage(_ keys: [NSEvent.SpecialKey]) {
sendMessage(msg: Data(keys.map { UInt8($0.rawValue) }))
}
func sendAntiIdle() {
// 6 zeroed bytes:
let message = Data(count: 6)
sendMessage(msg: message)
}
func login() {
//let account = addr.utf8
switch site.connectionProtocol {
case .ssh:
if terminalFeeder.cursorX > 2, terminalFeeder.grid[terminalFeeder.cursorY][terminalFeeder.cursorX - 2].byte == "?".utf8.first! {
sendMessage(msg: "yes\r".data(using: .ascii)!)
sleep(1)
}
case .telnet:
while terminalFeeder.cursorY <= 3 {
sleep(1)
sendMessage(msg: userName!.data(using: .utf8)!)
sendMessage(msg: Data([0x0d]))
}
}
let service = "Welly".data(using: .utf8)
service?.withUnsafeBytes() { (buffer : UnsafeRawBufferPointer) in
let accountData = (userName! + "@" + site.address).data(using: .utf8)!
accountData.withUnsafeBytes() {(buffer2 : UnsafeRawBufferPointer) in
var len = UInt32(0)
var pass : UnsafeMutableRawPointer? = nil
let serviceNamePtr = buffer.baseAddress!.assumingMemoryBound(to: Int8.self)
let accountNamePtr = buffer2.baseAddress!.assumingMemoryBound(to: Int8.self)
if noErr == SecKeychainFindGenericPassword(nil, UInt32(service!.count), serviceNamePtr, UInt32(accountData.count), accountNamePtr, &len, &pass, nil) {
sendMessage(msg: Data(bytes: pass!, count: Int(len)))
sendMessage(msg: Data([0x0d]))
SecKeychainItemFreeContent(nil, pass)
}
}
}
}
func send(text: String, delay microsecond: Int = 0) {
let s = text.replacingOccurrences(of: "\n", with: "\r")
var data = Data()
let encoding = site.encoding
for ch in s.utf16 {
var buf = [UInt8](repeating:0, count: 2)
if ch < 0x007f {
buf[0] = UInt8(ch)
data.append(&buf, count: 1)
} else {
if CFStringIsSurrogateHighCharacter(ch) ||
CFStringIsSurrogateLowCharacter(ch) {
buf[0] = 0x3f
buf[1] = 0x3f
} else {
let code = encode(ch, to: encoding)
if code != 0 {
buf[0] = UInt8(code >> 8)
buf[1] = UInt8(code & 0xff)
} else {
if (ch == 8943 && encoding == .gbk) {
// hard code for the ellipsis
buf[0] = 0xa1
buf[1] = 0xad
} else if ch != 0 {
buf[0] = 0x20
buf[1] = 0x20
}
}
}
data.append(&buf, count: 2)
}
}
// Now send the message
if microsecond == 0 {
// send immediately
sendMessage(msg: data)
} else {
// send with delay
for i in 0..<data.count {
sendMessage(msg: data.subdata(in: i..<(i+1)))
usleep(useconds_t(microsecond))
}
}
}
func increaseMessageCount(value: Int) {
guard value > 0 else {
return
}
let config = GlobalConfig.sharedInstance
NSApp.requestUserAttention(config.shouldRepeatBounce ? .criticalRequest : .informationalRequest)
config.messageCount += value
messageCount += value
// self.objectCount = messageCount
}
func resetMessageCount() {
guard messageCount > 0 else {return}
GlobalConfig.sharedInstance.messageCount -= messageCount
messageCount = 0
//TODO:
//self.objectCount = 0
}
func didReceive(newMessage: String, from caller: String) {
//
}
}
|
522628b8884e1eb22ba8d1057c9d9e86
| 30.337838 | 166 | 0.521345 | false | false | false | false |
MKGitHub/UIPheonix
|
refs/heads/master
|
Demo/Shared/Views/Collection View/SimpleViewAnimationModelCVCell.swift
|
apache-2.0
|
1
|
/**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
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.
*/
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
final class SimpleViewAnimationModelCVCell:UIPBaseCollectionViewCell
{
// MARK: Private IB Outlet
@IBOutlet private weak var ibLeftSpaceConstraint:NSLayoutConstraint!
// MARK: Private Member
public var pSimpleViewAnimationModel:SimpleViewAnimationModel!
// MARK:- UICollectionViewCell
override func prepareForReuse()
{
super.prepareForReuse()
}
// MARK:- UIPBaseCollectionViewCell/UIPBaseCollectionViewCellProtocol
override func update(withModel model:Any, delegate:Any, collectionView:UIPPlatformCollectionView, indexPath:IndexPath) -> UIPCellSize
{
// save model for later
pSimpleViewAnimationModel = model as? SimpleViewAnimationModel
animateUI()
// return view size
return UIPCellSize(replaceWidth:true, width:collectionView.bounds.size.width,
replaceHeight:false, height:0)
}
// MARK:- Private IB Action
@IBAction func animateButtonAction(_ sender:AnyObject)
{
#if os(iOS) || os(tvOS)
self.layoutIfNeeded() // #1. Make sure all frames are at the starting position.
UIView.animate(withDuration:1.0)
{
[weak self] in
if let self = self
{
self.pSimpleViewAnimationModel.pAnimationState = !self.pSimpleViewAnimationModel.pAnimationState
self.animateUI()
self.layoutIfNeeded() // #2. Layout again to update the frames/constraints.
}
}
#elseif os(macOS)
self.view.layoutSubtreeIfNeeded() // #1. Make sure all frames are at the starting position.
NSAnimationContext.runAnimationGroup(
{
[weak self] (context) in
context.duration = 1.0
if let self = self
{
self.pSimpleViewAnimationModel.pAnimationState = !self.pSimpleViewAnimationModel.pAnimationState
self.animateUI()
self.view.layoutSubtreeIfNeeded() // #2. Layout again to update the frames/constraints.
}
},
completionHandler:nil)
#endif
}
// MARK:- Private
private func animateUI()
{
#if os(iOS)
self.ibLeftSpaceConstraint?.constant = (pSimpleViewAnimationModel.pAnimationState) ? (self.bounds.width - 70 - 8) : 8
#elseif os(tvOS)
self.ibLeftSpaceConstraint?.constant = (pSimpleViewAnimationModel.pAnimationState) ? (self.bounds.width - 150 - 16) : 16
#elseif os(macOS)
self.ibLeftSpaceConstraint?.animator().constant = (pSimpleViewAnimationModel.pAnimationState) ? (self.view.bounds.width - 70 - 8) : 8
#endif
}
}
|
cc0d29194405431569b1384d544dcceb
| 29.658333 | 145 | 0.634955 | false | false | false | false |
zhiquan911/CHKLineChart
|
refs/heads/master
|
CHKLineChart/CHKLineChart/Classes/CHAxisModel.swift
|
mit
|
2
|
//
// YAxis.swift
// CHKLineChart
//
// Created by Chance on 16/8/31.
// Copyright © 2016年 Chance. All rights reserved.
//
import Foundation
import UIKit
/**
Y轴显示的位置
- Left: 左边
- Right: 右边
- None: 不显示
*/
public enum CHYAxisShowPosition {
case left, right, none
}
/// 坐标轴辅助线样式风格
///
/// - none: 不显示
/// - dash: 虚线
/// - solid: 实线
public enum CHAxisReferenceStyle {
case none
case dash(color: UIColor, pattern: [NSNumber])
case solid(color: UIColor)
}
/**
* Y轴数据模型
*/
public struct CHYAxis {
public var max: CGFloat = 0 //Y轴的最大值
public var min: CGFloat = 0 //Y轴的最小值
public var ext: CGFloat = 0.00 //上下边界溢出值的比例
public var baseValue: CGFloat = 0 //固定的基值
public var tickInterval: Int = 4 //间断显示个数
public var pos: Int = 0
public var decimal: Int = 2 //约束小数位
public var isUsed = false
/// 辅助线样式
public var referenceStyle: CHAxisReferenceStyle = .dash(color: UIColor(white: 0.2, alpha: 1), pattern: [5])
}
/**
* X轴数据模型
*/
public struct CHXAxis {
public var tickInterval: Int = 6 //间断显示个数
/// 辅助线样式
public var referenceStyle: CHAxisReferenceStyle = .none
}
|
d06909ae9bcde729bf027f15b97e6f67
| 18.292308 | 111 | 0.582137 | false | false | false | false |
laurenyew/Stanford_cs193p_iOS_Application_Development
|
refs/heads/master
|
Spring_2017_iOS10_Swift/Calculator/Calculator/Graph/CalculatorGraphView.swift
|
mit
|
1
|
//
// CalculatorGraphView.swift
// Calculator
//
// Created by laurenyew on 12/13/17.
// Copyright © 2017 CS193p. All rights reserved.
//
import UIKit
@IBDesignable
class CalculatorGraphView: UIView
{
@IBInspectable
var scale: CGFloat = 40 {didSet {setNeedsDisplay()}}
@IBInspectable
var axesColor: UIColor = UIColor.blue {didSet {setNeedsDisplay()}}
@IBInspectable
var graphColor: UIColor = UIColor.red
// Center of the graph being viewed on the screen
// Used for calculating path via scale for each part of screen
var graphViewCenter: CGPoint{
return center
}
// Saved Origin of the function (changes propagate to the view here)
var originRelativeToGraphViewCenter: CGPoint = CGPoint.zero {didSet{setNeedsDisplay()}}
// Calculated origin of function
// Used for main logic, can be set to update the view's origin
var origin: CGPoint{
get{
var funcOrigin = originRelativeToGraphViewCenter
funcOrigin.x += graphViewCenter.x
funcOrigin.y += graphViewCenter.y
return funcOrigin
}
set{
var funcOrigin = newValue
funcOrigin.x -= graphViewCenter.x
funcOrigin.y -= graphViewCenter.y
originRelativeToGraphViewCenter = funcOrigin
}
}
//Graphing function: returns value Y for given value X for a given function
//If this value is changed, redraw
var graphFunctionY: ((Double) -> Double?)? {didSet {setNeedsDisplay()}}
private var axesDrawer = AxesDrawer()
override func draw(_ rect: CGRect) {
axesColor.setStroke()
axesDrawer.color = axesColor
axesDrawer.drawAxes(in: bounds, origin: origin, pointsPerUnit: scale)
//Draw the graph function in the view using the graphFunctionY
drawGraphFunction(in: bounds, origin: origin, pointsPerUnit: scale)
}
//Handles UI of drawing new function
private func drawGraphFunction(in rect: CGRect, origin: CGPoint, pointsPerUnit: CGFloat){
var graphX, graphY:CGFloat
var x,y: Double
UIGraphicsGetCurrentContext()?.saveGState()
graphColor.set()
let path = UIBezierPath()
path.lineWidth = 20.0
//For the graph view's width, calculate the function and show
for i in 0...Int(rect.size.width * scale) {
graphX = CGFloat(i)
x = Double((graphX - origin.x)/scale)
y = graphFunctionY?(x) ?? 0
graphY = (CGFloat(y) + origin.y) * scale
path.addLine(to: CGPoint(x: graphX, y: graphY))
}
path.stroke()
UIGraphicsGetCurrentContext()?.restoreGState()
}
}
|
8c387bfc70d6287af4e35ea476374ee3
| 30.873563 | 93 | 0.627119 | false | false | false | false |
mactive/rw-courses-note
|
refs/heads/master
|
ProgrammingInSwift/ControlFlow.playground/Pages/SwitchChallenge.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
import Foundation
let lifeStage: String
let age = 80
//switch age {
//case ..<0:
// lifeStage = "Not born yet"
//case 0...2:
// lifeStage = "Infant"
//case 3...12:
// lifeStage = "Child"
//case 13...19:
// lifeStage = "Teenager"
//case 20...39:
// lifeStage = "Adult"
//case 40...60:
// lifeStage = "Middle aged"
//case 61...99:
// lifeStage = "Eldery"
//case let age:
// fatalError("Unaccounted for age: \(age)")
//}
let name = "Jessy"
switch (name, age) {
case (name, ..<0):
lifeStage = "\(name) is Not born yet"
case (name, 0...2):
lifeStage = "\(name) is Infant"
case (name, 3...12):
lifeStage = "\(name) is Child"
case (name, 13...19):
lifeStage = "\(name) is Teenager"
case (name, 20...39):
lifeStage = "\(name) is Adult"
case (name, 40...60):
lifeStage = "\(name) is Middle aged"
case (name, 61...99):
lifeStage = "\(name) is Eldery"
case (_, let age):
fatalError("Unaccounted for age): \(age)")
}
//: [Next](@next)
|
b3f93b59d9837d46d226fb7d8b67a6f5
| 19.653061 | 47 | 0.56917 | false | false | false | false |
manuelbl/WirekiteMac
|
refs/heads/master
|
Examples/Nunchuck/Nunchuck/Nunchuck.swift
|
mit
|
1
|
// Wirekite for MacOS
//
// Copyright (c) 2017 Manuel Bleichenbacher
// Licensed under MIT License
// https://opensource.org/licenses/MIT
//
import Foundation
import WirekiteMac
class Nunchuck {
var device: WirekiteDevice?
var i2cPort: PortID = 0
var slaveAddress = 0x52
var joystickX = 0
var joystickY = 0
var accelerometerX = 0
var accelerometerY = 0
var accelerometerZ = 0
var cButton = false
var zButton = false
init(device: WirekiteDevice, i2cPort: PortID) {
self.device = device
self.i2cPort = i2cPort;
initController()
readData()
}
func readData() {
let senssorData = device!.requestData(onI2CPort: i2cPort, fromSlave: slaveAddress, length: 6)
if senssorData == nil || senssorData!.count != 6 {
let result = device!.lastResult(onI2CPort: i2cPort).rawValue
NSLog("nunchuck read failed - reason \(result)")
return
}
var sensorBytes = [UInt8](senssorData!)
joystickX = Int(sensorBytes[0])
joystickY = Int(sensorBytes[1])
accelerometerX = (Int(sensorBytes[2]) << 2) | Int((sensorBytes[5] >> 2) & 0x3)
accelerometerY = (Int(sensorBytes[3]) << 2) | Int((sensorBytes[5] >> 4) & 0x3)
accelerometerZ = (Int(sensorBytes[4]) << 2) | Int((sensorBytes[5] >> 6) & 0x3)
cButton = (sensorBytes[5] & 2) == 0
zButton = (sensorBytes[5] & 1) == 0
// prepare next data read (convert command)
let cmdBytes: [UInt8] = [ 0 ]
let cmdData = Data(bytes: cmdBytes)
device!.submit(onI2CPort: i2cPort, data: cmdData, toSlave: slaveAddress)
}
func initController() {
let initSequenceBytes: [[UInt8]] = [
[ 0xf0, 0x55 ],
[ 0xfb, 0x00 ]
]
for bytes in initSequenceBytes {
let data = Data(bytes: bytes)
let numBytes = device!.send(onI2CPort: i2cPort, data: data, toSlave: slaveAddress)
if numBytes != bytes.count {
let result = device!.lastResult(onI2CPort: i2cPort).rawValue
NSLog("nunchuck init seq failed - reason \(result)")
return
}
}
}
}
|
10e7c12894bd5a28470892d56c083af8
| 30.246575 | 101 | 0.572556 | false | false | false | false |
samburnstone/SwiftStudyGroup
|
refs/heads/master
|
Swift Language Guide Playgrounds/Homework Week 7.playground/Pages/Generics.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: [Previous](@previous)
//:## Generics
//: _________
//: Start with a simple function that swaps the values of the two parameters
func swapValues<T>(inout a: T, inout b: T)
{
let tempA = a
a = b
b = tempA
}
var value1 = 100
var value2 = 5
swapValues(&value1, b: &value2)
// Note how value1 now contains the value 5, whilst value2 stored 100
value1
value2
//:### Generic Types
struct Queue <Element>
{
var items = [Element]()
mutating func push(element: Element)
{
items.append(element)
}
mutating func pop() -> Element?
{
if items.isEmpty
{
return nil
}
return items.removeFirst()
}
func peek() -> Element?
{
return items.first
}
}
//: Let's try it out on some types
var integerQueue = Queue(items: [0, 1, 2, 4])
integerQueue.dynamicType // Note that compiler automatically infers the type of the Queue
integerQueue.pop()
integerQueue.peek()
integerQueue.pop()
var stringQueue = Queue<String>()
stringQueue.push("Sam")
stringQueue.push("Chris")
stringQueue.pop()
stringQueue.pop()
stringQueue.peek()
//:### Defining Constraints For Types
//: __________
//: A contrived example is a function taking two parameters where we check the type of the elements contained within each collection are equal AND the types conform to the `Equatable` protocol. NOTE: As C1 and C2 element types have already been checked to be equal, we can omit a check that C2's item type also conforms to Equatable
func collectionIsSubsetOfOtherCollection<C1: CollectionType, C2: CollectionType where C1.Generator.Element == C2.Generator.Element, C1.Generator.Element: Equatable>(possibleSubsetCollection: C1, collectionToCheckAgainst: C2) -> Bool
{
for itemA in possibleSubsetCollection
{
if !collectionToCheckAgainst.contains(itemA)
{
return false
}
}
// If we get to here then all items in collection A exist in collection B
return true
}
var queueOfStrings = Set<String>()
queueOfStrings.insert("Sam")
queueOfStrings.insert("Ryan")
queueOfStrings.insert("Rob")
//queueOfStrings.insert("Andy") // <- Would cause to return false
var arrayOfStrings = Array<String>()
arrayOfStrings.append("Sam")
arrayOfStrings.append("Ryan")
arrayOfStrings.append("Rob")
collectionIsSubsetOfOtherCollection(queueOfStrings, collectionToCheckAgainst:arrayOfStrings)
//: Tried to implement the above as an extension of CollectionType but had no luck :(´®
//extension CollectionType
//{
// func isSubsetOfCollection<T: CollectionType where T.Generator.Element == Self.Generator.Element, T.Generator.Element: Equatable>(otherCollection: T) -> Bool
// {
// for itemA in self
// {
// var found = false
// for itemB in otherCollection
// {
// if itemA == itemB
// {
// found = true
// }
// }
// if !found
// {
// return false
// }
// }
//
// // If we get to here then all items in collection A exist in collection B
// return true
// }
//}
//arrayOfStrings.isSubsetOfCollection(queueOfStrings)
//:### Associated types
//: Protocols cannot be defined generically using type parameters. Can instead define an **associated type** using `typealias` keyword
protocol FoodItemDigestingType
{
typealias Food: FoodItemType
func eat(food: Food)
func excrete(food: Food)
}
protocol FoodItemType {}
struct Bamboo: FoodItemType {}
struct Honey: FoodItemType {}
struct IronGirder {}
//: Note that if the types we pass in for `eat` and `excrete` don't match we get a compiler error
struct Panda: FoodItemDigestingType
{
func eat(food: Bamboo)
{
}
func excrete(food: Bamboo)
{
}
}
//: **Note:** The below does not compile as we're passing a type that does not conform to `FoodItemType`. This constraint is set by due to: `typealias Food: FoodItemType`
//struct Alien: FoodItemDigestingType {
// func eat(food: IronGirder) {}
//
// func excrete(food: IronGirder) {}
//}
//: [Next](@next)
|
6f6a88f4aafe081e665f2c150a4b2c6e
| 25.77707 | 332 | 0.652236 | false | false | false | false |
oliverrussellwhite/JSON
|
refs/heads/master
|
JSONTests/JSONTests.swift
|
unlicense
|
1
|
import JSON
import XCTest
class JSONTests: XCTestCase {
func testInit() {
func test(lhs: String, rhs: JSON, file: StaticString = #file, line: UInt = #line) {
do {
let lhs = try JSON(deserializing: Data(lhs.utf8))
XCTAssert(lhs == rhs, file: file, line: line)
}
catch {
XCTFail(file: file, line: line)
}
}
test(lhs: "{}", rhs: .dictionary([:]))
test(lhs: "{\"a\":1}", rhs: .dictionary(["a" : .integer(1)]))
test(lhs: "{\"a\":1,\"b\":2}", rhs: .dictionary(["a" : .integer(1), "b" : .integer(2)]))
test(lhs: "[]", rhs: .array([]))
test(lhs: "[1]", rhs: .array([.integer(1)]))
test(lhs: "[1,2]", rhs: .array([.integer(1), .integer(2)]))
test(lhs: "\"\"", rhs: .string(""))
test(lhs: "\"a\"", rhs: .string("a"))
test(lhs: "\"\\\"\"", rhs: .string("\""))
test(lhs: "\"\\\\\"", rhs: .string("\\"))
test(lhs: "\"\\/\"", rhs: .string("/"))
test(lhs: "\"\\b\"", rhs: .string("\u{8}"))
test(lhs: "\"\\f\"", rhs: .string("\u{c}"))
test(lhs: "\"\\n\"", rhs: .string("\n"))
test(lhs: "\"\\r\"", rhs: .string("\r"))
test(lhs: "\"\\t\"", rhs: .string("\t"))
test(lhs: "\"\\u203d\"", rhs: .string("‽"))
test(lhs: "\"\\ud83d\\ude00\"", rhs: .string("😀"))
test(lhs: "0", rhs: .integer(0))
test(lhs: "-0", rhs: .integer(-0))
test(lhs: "1", rhs: .integer(1))
test(lhs: "-1", rhs: .integer(-1))
test(lhs: "123", rhs: .integer(123))
test(lhs: "-123", rhs: .integer(-123))
test(lhs: "0e003", rhs: .double(0e003))
test(lhs: "-0e003", rhs: .double(-0e003))
test(lhs: "0e-0003", rhs: .double(0e-0003))
test(lhs: "-0e-0003", rhs: .double(-0e-0003))
test(lhs: "0e+003", rhs: .double(0e+003))
test(lhs: "-0e+003", rhs: .double(-0e+003))
test(lhs: "0E003", rhs: .double(0E003))
test(lhs: "-0E003", rhs: .double(-0E003))
test(lhs: "0E-0003", rhs: .double(0E-0003))
test(lhs: "-0E-0003", rhs: .double(-0E-0003))
test(lhs: "0E+003", rhs: .double(0E+003))
test(lhs: "-0E+003", rhs: .double(-0E+003))
test(lhs: "1e003", rhs: .double(1e003))
test(lhs: "-1e003", rhs: .double(-1e003))
test(lhs: "1e-0003", rhs: .double(1e-0003))
test(lhs: "-1e-0003", rhs: .double(-1e-0003))
test(lhs: "1e+003", rhs: .double(1e+003))
test(lhs: "-1e+003", rhs: .double(-1e+003))
test(lhs: "1E003", rhs: .double(1E003))
test(lhs: "-1E003", rhs: .double(-1E003))
test(lhs: "1E-0003", rhs: .double(1E-0003))
test(lhs: "-1E-0003", rhs: .double(-1E-0003))
test(lhs: "1E+003", rhs: .double(1E+003))
test(lhs: "-1E+003", rhs: .double(-1E+003))
test(lhs: "123e003", rhs: .double(123e003))
test(lhs: "-123e003", rhs: .double(-123e003))
test(lhs: "123e-0003", rhs: .double(123e-0003))
test(lhs: "-123e-0003", rhs: .double(-123e-0003))
test(lhs: "123e+003", rhs: .double(123e+003))
test(lhs: "-123e+003", rhs: .double(-123e+003))
test(lhs: "123E003", rhs: .double(123E003))
test(lhs: "-123E003", rhs: .double(-123E003))
test(lhs: "123E-0003", rhs: .double(123E-0003))
test(lhs: "-123E-0003", rhs: .double(-123E-0003))
test(lhs: "123E+003", rhs: .double(123E+003))
test(lhs: "-123E+003", rhs: .double(-123E+003))
test(lhs: "0.123", rhs: .double(0.123))
test(lhs: "-0.123", rhs: .double(-0.123))
test(lhs: "0.123e003", rhs: .double(0.123e003))
test(lhs: "-0.123e003", rhs: .double(-0.123e003))
test(lhs: "0.123e-0003", rhs: .double(0.123e-0003))
test(lhs: "-0.123e-0003", rhs: .double(-0.123e-0003))
test(lhs: "0.123e+003", rhs: .double(0.123e+003))
test(lhs: "-0.123e+003", rhs: .double(-0.123e+003))
test(lhs: "0.123E003", rhs: .double(0.123E003))
test(lhs: "-0.123E003", rhs: .double(-0.123E003))
test(lhs: "0.123E-0003", rhs: .double(0.123E-0003))
test(lhs: "-0.123E-0003", rhs: .double(-0.123E-0003))
test(lhs: "0.123E+003", rhs: .double(0.123E+003))
test(lhs: "-0.123E+003", rhs: .double(-0.123E+003))
test(lhs: "1.123", rhs: .double(1.123))
test(lhs: "-1.123", rhs: .double(-1.123))
test(lhs: "1.123e003", rhs: .double(1.123e003))
test(lhs: "-1.123e003", rhs: .double(-1.123e003))
test(lhs: "1.123e-0003", rhs: .double(1.123e-0003))
test(lhs: "-1.123e-0003", rhs: .double(-1.123e-0003))
test(lhs: "1.123e+003", rhs: .double(1.123e+003))
test(lhs: "-1.123e+003", rhs: .double(-1.123e+003))
test(lhs: "1.123E003", rhs: .double(1.123E003))
test(lhs: "-1.123E003", rhs: .double(-1.123E003))
test(lhs: "1.123E-0003", rhs: .double(1.123E-0003))
test(lhs: "-1.123E-0003", rhs: .double(-1.123E-0003))
test(lhs: "1.123E+003", rhs: .double(1.123E+003))
test(lhs: "-1.123E+003", rhs: .double(-1.123E+003))
test(lhs: "123.123", rhs: .double(123.123))
test(lhs: "-123.123", rhs: .double(-123.123))
test(lhs: "123.123e003", rhs: .double(123.123e003))
test(lhs: "-123.123e003", rhs: .double(-123.123e003))
test(lhs: "123.123e-0003", rhs: .double(123.123e-0003))
test(lhs: "-123.123e-0003", rhs: .double(-123.123e-0003))
test(lhs: "123.123e+003", rhs: .double(123.123e+003))
test(lhs: "-123.123e+003", rhs: .double(-123.123e+003))
test(lhs: "123.123E003", rhs: .double(123.123E003))
test(lhs: "-123.123E003", rhs: .double(-123.123E003))
test(lhs: "123.123E-0003", rhs: .double(123.123E-0003))
test(lhs: "-123.123E-0003", rhs: .double(-123.123E-0003))
test(lhs: "123.123E+003", rhs: .double(123.123E+003))
test(lhs: "-123.123E+003", rhs: .double(-123.123E+003))
test(lhs: "true", rhs: .boolean(true))
test(lhs: "false", rhs: .boolean(false))
test(lhs: "null", rhs: .null)
test(lhs: " \n\r\t{ \n\r\t\"a\" \n\r\t: \n\r\t[ \n\r\ttrue \n\r\t, \n\r\tfalse \n\r\t] \n\r\t, \n\r\t\"b\" \n\r\t: \n\r\tnull \n\r\t} \n\r\t", rhs: .dictionary(["a" : .array([.boolean(true), .boolean(false)]), "b" : .null]))
}
}
|
76dba2182cc890fc1284389aaf35649a
| 47.492424 | 232 | 0.513201 | false | true | false | false |
efremidze/Cluster
|
refs/heads/master
|
Example/Extensions.swift
|
mit
|
1
|
//
// Extensions.swift
// Cluster
//
// Created by Lasha Efremidze on 7/8/17.
// Copyright © 2017 efremidze. All rights reserved.
//
import UIKit
import MapKit
extension UIImage {
func filled(with color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
color.setFill()
guard let context = UIGraphicsGetCurrentContext() else { return self }
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0);
context.setBlendMode(CGBlendMode.normal)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
guard let mask = self.cgImage else { return self }
context.clip(to: rect, mask: mask)
context.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
static let pin = UIImage(named: "pin")?.filled(with: .green)
static let pin2 = UIImage(named: "pin2")?.filled(with: .green)
static let me = UIImage(named: "me")?.filled(with: .blue)
}
extension UIColor {
class var green: UIColor { return UIColor(red: 76 / 255, green: 217 / 255, blue: 100 / 255, alpha: 1) }
class var blue: UIColor { return UIColor(red: 0, green: 122 / 255, blue: 1, alpha: 1) }
}
extension MKMapView {
func annotationView<T: MKAnnotationView>(of type: T.Type, annotation: MKAnnotation?, reuseIdentifier: String) -> T {
guard let annotationView = dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as? T else {
return type.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
}
annotationView.annotation = annotation
return annotationView
}
}
|
67ebfaef6b6270eedc35523b0d68f362
| 34.897959 | 120 | 0.66174 | false | false | false | false |
coderLL/DYTV
|
refs/heads/master
|
DYTV/DYTV/Classes/Main/Controller/BaseViewController.swift
|
mit
|
1
|
//
// BaseViewController.swift
// DYTV
//
// Created by CodeLL on 2016/10/15.
// Copyright © 2016年 coderLL. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
// MARK:- 定义属性
var baseContentView : UIView?
// MARK:- 懒加载属性
fileprivate lazy var animImageView : UIImageView = { [unowned self] in
let imageView = UIImageView(image: UIImage(named: "home_header_normal"))
imageView.center = self.view.center
imageView.animationImages = [UIImage(named: "home_header_normal")!, UIImage(named: "home_header_hot")!]
imageView.animationDuration = 0.5
imageView.animationRepeatCount = LONG_MAX
imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin]
return imageView
}()
// MARK:- 系统回调
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
}
// MARK:- 添加UI界面
extension BaseViewController {
// MARK:- 设置UI界面
func setupUI() {
// 1.先隐藏内容的view
self.baseContentView?.isHidden = true
// 2.添加执行动画的UIImageView
self.view.addSubview(animImageView)
// 3.给UIImageView执行动画
self.animImageView.startAnimating()
// 4.设置背景颜色
view.backgroundColor = UIColor(r: 250, g: 250, b: 250)
}
// MARK:- 数据请求完成
func loadDataFinished() {
// 1.停止动画
self.animImageView.stopAnimating()
// 2.隐藏animImageView
self.animImageView.isHidden = true
// 3.显示内容的view
self.baseContentView?.isHidden = false
}
}
|
628aa9d29376017932dc4a9f03c32fd2
| 23.939394 | 111 | 0.602673 | false | false | false | false |
lucaswoj/sugar.swift
|
refs/heads/master
|
SugarEventStream.swift
|
mit
|
1
|
//
// SugarEventStream.swift
// Sugar
//
// Created by Lucas Wojciechowski on 10/20/14.
// Copyright (c) 2014 Scree Apps. All rights reserved.
//
import Foundation
class SugarEventStream<T> {
init() {}
var handlers:[(handler:Handler, once:Bool, queue:NSOperationQueue?)] = []
typealias Handler = T -> Void
func addHandler(handler:Handler, once:Bool = false, queue:NSOperationQueue? = nil) {
handlers.append((handler: handler, once: once, queue:queue))
}
func trigger(value:T) {
for (index, (handler, once, queue)) in enumerate(handlers) {
if queue == nil {
handler(value)
} else {
queue!.addOperation(NSBlockOperation({
handler(value)
}))
}
if once {
handlers.removeAtIndex(index)
}
}
}
}
|
45251ff5d742fbb39abf4bcaf848fc09
| 22.025641 | 88 | 0.548495 | false | false | false | false |
breadwallet/breadwallet-ios
|
refs/heads/master
|
breadwallet/src/SimpleRedux/State.swift
|
mit
|
1
|
//
// State.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-10-24.
// Copyright © 2016-2019 Breadwinner AG. All rights reserved.
//
import UIKit
struct State {
let isLoginRequired: Bool
let rootModal: RootModal
let showFiatAmounts: Bool
let alert: AlertType
let defaultCurrencyCode: String
let isPushNotificationsEnabled: Bool
let isPromptingBiometrics: Bool
let pinLength: Int
let walletID: String?
let wallets: [CurrencyId: WalletState]
var experiments: [Experiment]?
let creationRequired: [CurrencyId]
subscript(currency: Currency) -> WalletState? {
guard let walletState = wallets[currency.uid] else {
return nil
}
return walletState
}
var orderedWallets: [WalletState] {
return wallets.values.sorted(by: { $0.displayOrder < $1.displayOrder })
}
var currencies: [Currency] {
return orderedWallets.map { $0.currency }
}
var shouldShowBuyNotificationForDefaultCurrency: Bool {
switch defaultCurrencyCode {
// Currencies eligible for Coinify.
case C.euroCurrencyCode,
C.britishPoundCurrencyCode,
C.danishKroneCurrencyCode:
return true
default:
return false
}
}
}
extension State {
static var initial: State {
return State( isLoginRequired: true,
rootModal: .none,
showFiatAmounts: UserDefaults.showFiatAmounts,
alert: .none,
defaultCurrencyCode: UserDefaults.defaultCurrencyCode,
isPushNotificationsEnabled: UserDefaults.pushToken != nil,
isPromptingBiometrics: false,
pinLength: 6,
walletID: nil,
wallets: [:],
experiments: nil,
creationRequired: []
)
}
func mutate( isOnboardingEnabled: Bool? = nil,
isLoginRequired: Bool? = nil,
rootModal: RootModal? = nil,
showFiatAmounts: Bool? = nil,
alert: AlertType? = nil,
defaultCurrencyCode: String? = nil,
isPushNotificationsEnabled: Bool? = nil,
isPromptingBiometrics: Bool? = nil,
pinLength: Int? = nil,
walletID: String? = nil,
wallets: [CurrencyId: WalletState]? = nil,
experiments: [Experiment]? = nil,
creationRequired: [CurrencyId]? = nil) -> State {
return State(isLoginRequired: isLoginRequired ?? self.isLoginRequired,
rootModal: rootModal ?? self.rootModal,
showFiatAmounts: showFiatAmounts ?? self.showFiatAmounts,
alert: alert ?? self.alert,
defaultCurrencyCode: defaultCurrencyCode ?? self.defaultCurrencyCode,
isPushNotificationsEnabled: isPushNotificationsEnabled ?? self.isPushNotificationsEnabled,
isPromptingBiometrics: isPromptingBiometrics ?? self.isPromptingBiometrics,
pinLength: pinLength ?? self.pinLength,
walletID: walletID ?? self.walletID,
wallets: wallets ?? self.wallets,
experiments: experiments ?? self.experiments,
creationRequired: creationRequired ?? self.creationRequired)
}
func mutate(walletState: WalletState) -> State {
var wallets = self.wallets
wallets[walletState.currency.uid] = walletState
return mutate(wallets: wallets)
}
}
// MARK: - Experiments
extension State {
public func experimentWithName(_ experimentName: ExperimentName) -> Experiment? {
guard let set = experiments, let exp = set.first(where: { $0.name == experimentName.rawValue }) else { return nil }
return exp
}
public func requiresCreation(_ currency: Currency) -> Bool {
return creationRequired.contains(currency.uid)
}
}
// MARK: -
enum RootModal {
case none
case send(currency: Currency)
case receive(currency: Currency)
case loginScan
case requestAmount(currency: Currency, address: String)
case buy(currency: Currency?)
case sell(currency: Currency?)
case trade
case receiveLegacy
case stake(currency: Currency)
case gift
}
enum SyncState {
case syncing
case connecting
case success
case failed
}
// MARK: -
struct WalletState {
let currency: Currency
weak var wallet: Wallet?
let displayOrder: Int // -1 for hidden
let syncProgress: Float
let syncState: SyncState
let balance: Amount?
let lastBlockTimestamp: UInt32
let isRescanning: Bool
var receiveAddress: String? {
return wallet?.receiveAddress
}
let currentRate: Rate?
let fiatPriceInfo: FiatPriceInfo?
static func initial(_ currency: Currency, wallet: Wallet? = nil, displayOrder: Int) -> WalletState {
return WalletState(currency: currency,
wallet: wallet,
displayOrder: displayOrder,
syncProgress: 0.0,
syncState: .success,
balance: UserDefaults.balance(forCurrency: currency),
lastBlockTimestamp: 0,
isRescanning: false,
currentRate: UserDefaults.currentRate(forCode: currency.code),
fiatPriceInfo: nil)
}
func mutate( wallet: Wallet? = nil,
displayOrder: Int? = nil,
syncProgress: Float? = nil,
syncState: SyncState? = nil,
balance: Amount? = nil,
lastBlockTimestamp: UInt32? = nil,
isRescanning: Bool? = nil,
receiveAddress: String? = nil,
legacyReceiveAddress: String? = nil,
currentRate: Rate? = nil,
fiatPriceInfo: FiatPriceInfo? = nil) -> WalletState {
return WalletState(currency: self.currency,
wallet: wallet ?? self.wallet,
displayOrder: displayOrder ?? self.displayOrder,
syncProgress: syncProgress ?? self.syncProgress,
syncState: syncState ?? self.syncState,
balance: balance ?? self.balance,
lastBlockTimestamp: lastBlockTimestamp ?? self.lastBlockTimestamp,
isRescanning: isRescanning ?? self.isRescanning,
currentRate: currentRate ?? self.currentRate,
fiatPriceInfo: fiatPriceInfo ?? self.fiatPriceInfo)
}
}
extension WalletState: Equatable {}
func == (lhs: WalletState, rhs: WalletState) -> Bool {
return lhs.currency == rhs.currency &&
lhs.wallet?.currency == rhs.wallet?.currency &&
lhs.syncProgress == rhs.syncProgress &&
lhs.syncState == rhs.syncState &&
lhs.balance == rhs.balance &&
lhs.lastBlockTimestamp == rhs.lastBlockTimestamp &&
lhs.isRescanning == rhs.isRescanning &&
lhs.currentRate == rhs.currentRate
}
extension RootModal: Equatable {}
func == (lhs: RootModal, rhs: RootModal) -> Bool {
switch(lhs, rhs) {
case (.none, .none):
return true
case (.send(let lhsCurrency), .send(let rhsCurrency)):
return lhsCurrency == rhsCurrency
case (.receive(let lhsCurrency), .receive(let rhsCurrency)):
return lhsCurrency == rhsCurrency
case (.loginScan, .loginScan):
return true
case (.requestAmount(let lhsCurrency, let lhsAddress), .requestAmount(let rhsCurrency, let rhsAddress)):
return lhsCurrency == rhsCurrency && lhsAddress == rhsAddress
case (.buy(let lhsCurrency?), .buy(let rhsCurrency?)):
return lhsCurrency == rhsCurrency
case (.buy(nil), .buy(nil)):
return true
case (.sell(let lhsCurrency?), .sell(let rhsCurrency?)):
return lhsCurrency == rhsCurrency
case (.sell(nil), .sell(nil)):
return true
case (.trade, .trade):
return true
case (.receiveLegacy, .receiveLegacy):
return true
case (.stake(let lhsCurrency), .stake(let rhsCurrency)):
return lhsCurrency == rhsCurrency
case (.gift, .gift):
return true
default:
return false
}
}
extension Currency {
var state: WalletState? {
return Store.state[self]
}
var wallet: Wallet? {
return Store.state[self]?.wallet
}
}
|
269ad77193bdb3801bdd50438df5deec
| 34.090909 | 123 | 0.577382 | false | false | false | false |
sarunw/NavigationBarManager
|
refs/heads/master
|
Example/NavigationBarManager/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// NavigationBarManager
//
// Created by Sarun Wongpatcharapakorn on 12/01/2016.
// Copyright (c) 2016 Sarun Wongpatcharapakorn. All rights reserved.
//
import UIKit
import NavigationBarManager
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var refreshControl: UIRefreshControl!
var navBarManager: NavigationBarManager!
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
navBarManager = NavigationBarManager(viewController: self, scrollView: collectionView)
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(didPullToRefresh(sender:)), for: .valueChanged)
if #available(iOS 10.0, *) {
collectionView.refreshControl = refreshControl
} else {
// Fallback on earlier versions
collectionView.addSubview(refreshControl)
}
let rect = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 100)
let redView = UIView(frame: rect)
redView.backgroundColor = UIColor.red
navBarManager.extensionView = redView
}
func didPullToRefresh(sender: AnyObject) {
longRunningProcess()
}
private func longRunningProcess() {
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 2, execute: {
DispatchQueue.main.async {
self.refreshControl.endRefreshing()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Collection View
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
clear()
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfItems
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
return cell
}
private var numberOfItems = 10
@IBAction func didTapLoad(_ sender: Any) {
load()
}
private func clear() {
numberOfItems = 0
collectionView.reloadData()
}
private func load() {
numberOfItems = 10
collectionView.reloadData()
}
// MARK: - Scroll View
func scrollViewDidScroll(_ scrollView: UIScrollView) {
navBarManager.handleScrollViewDidScroll(scrollView: scrollView)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate == true {
// have inertia, handle in scrollViewDidEndDecelerating
return
}
navBarManager.handleScrollViewDidEnd(scrollView: scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// stop
navBarManager.handleScrollViewDidEnd(scrollView: scrollView)
}
}
|
45d8e8d7b7f19f51dfb0d5e3f9ce4b6e
| 29.348214 | 121 | 0.652545 | false | false | false | false |
wnagrodzki/DragGestureRecognizer
|
refs/heads/master
|
DragGestureRecognizer/DragGestureRecognizer.swift
|
mit
|
1
|
//
// DragGestureRecognizer.swift
// DragGestureRecognizer
//
// Created by Wojciech Nagrodzki on 01/09/16.
// Copyright © 2016 Wojciech Nagrodzki. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizerSubclass
/// `DragGestureRecognizer` is a subclass of `UILongPressGestureRecognizer` that allows for tracking translation similarly to `UIPanGestureRecognizer`.
class DragGestureRecognizer: UILongPressGestureRecognizer {
private var initialTouchLocationInScreenFixedCoordinateSpace: CGPoint?
private var initialTouchLocationsInViews = [UIView: CGPoint]()
/// The total translation of the drag gesture in the coordinate system of the specified view.
/// - parameters:
/// - view: The view in whose coordinate system the translation of the drag gesture should be computed. Pass `nil` to indicate window.
func translation(in view: UIView?) -> CGPoint {
// not attached to a view or outside window
guard let window = self.view?.window else { return CGPoint() }
// gesture not in progress
guard let initialTouchLocationInScreenFixedCoordinateSpace = initialTouchLocationInScreenFixedCoordinateSpace else { return CGPoint() }
let initialLocation: CGPoint
let currentLocation: CGPoint
if let view = view {
initialLocation = initialTouchLocationsInViews[view] ?? window.screen.fixedCoordinateSpace.convert(initialTouchLocationInScreenFixedCoordinateSpace, to: view)
currentLocation = location(in: view)
}
else {
initialLocation = initialTouchLocationInScreenFixedCoordinateSpace
currentLocation = location(in: nil)
}
return CGPoint(x: currentLocation.x - initialLocation.x, y: currentLocation.y - initialLocation.y)
}
/// Sets the translation value in the coordinate system of the specified view.
/// - parameters:
/// - translation: A point that identifies the new translation value.
/// - view: A view in whose coordinate system the translation is to occur. Pass `nil` to indicate window.
func setTranslation(_ translation: CGPoint, in view: UIView?) {
// not attached to a view or outside window
guard let window = self.view?.window else { return }
// gesture not in progress
guard let _ = initialTouchLocationInScreenFixedCoordinateSpace else { return }
let inView = view ?? window
let currentLocation = location(in: inView)
let initialLocation = CGPoint(x: currentLocation.x - translation.x, y: currentLocation.y - translation.y)
initialTouchLocationsInViews[inView] = initialLocation
}
override var state: UIGestureRecognizer.State {
didSet {
switch state {
case .began:
initialTouchLocationInScreenFixedCoordinateSpace = location(in: nil)
case .ended, .cancelled, .failed:
initialTouchLocationInScreenFixedCoordinateSpace = nil
initialTouchLocationsInViews = [:]
case .possible, .changed:
break
}
}
}
}
|
3c9405e5baf4b815187b8731f1080272
| 40.948718 | 170 | 0.662286 | false | false | false | false |
nuclearace/SwiftDiscord
|
refs/heads/master
|
Sources/SwiftDiscord/Guild/DiscordWebhook.swift
|
mit
|
1
|
// The MIT License (MIT)
// Copyright (c) 2016 Erik Little
// 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
/// Represents a webhook.
public struct DiscordWebhook {
// MARK: Properties
/// The avatar of this webhook.
public let avatar: String?
/// The snowflake for the channel this webhook is for.
public let channelId: ChannelID
/// The snowflake for of the guild this webhook is for, if for a guild.
public let guildId: GuildID?
/// The id of this webhook.
public let id: WebhookID
/// The default name of this webhook.
public let name: String?
/// The secure token for this webhook.
public let token: String
/// The user this webhook was created by (not present when the webhook was gotten by its token).
public let user: DiscordUser?
init(webhookObject: [String: Any]) {
avatar = webhookObject["avatar"] as? String
channelId = webhookObject.getSnowflake(key: "channel_id")
guildId = Snowflake(webhookObject["guild_id"] as? String)
id = webhookObject.getSnowflake()
name = webhookObject["name"] as? String
token = webhookObject.get("token", or: "")
if let userObject = webhookObject["user"] as? [String: Any] {
user = DiscordUser(userObject: userObject)
} else {
user = nil
}
}
static func webhooksFromArray(_ webhookArray: [[String: Any]]) -> [DiscordWebhook] {
return webhookArray.map(DiscordWebhook.init)
}
}
|
5973fc04dd6f0a21169abab43db49b7b
| 39.222222 | 119 | 0.701657 | false | false | false | false |
watson-developer-cloud/speech-ios-sdk
|
refs/heads/master
|
watsonsdktest-swift/SwiftTTSViewController.swift
|
apache-2.0
|
1
|
/**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import UIKit
class SwiftTTSViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UIGestureRecognizerDelegate {
var ttsVoices: NSArray?
var ttsInstance: TextToSpeech?
@IBOutlet var voiceSelectorButton: UIButton!
@IBOutlet weak var pickerViewContainer: UIView!
@IBOutlet var ttsField: UITextView!
var pickerView: UIPickerView!
let pickerViewHeight:CGFloat = 250.0
let pickerViewAnimationDuration: NSTimeInterval = 0.5
let pickerViewAnimationDelay: NSTimeInterval = 0.1
let pickerViewPositionOffset: CGFloat = 33.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let credentialFilePath = NSBundle.mainBundle().pathForResource("Credentials", ofType: "plist")
let credentials = NSDictionary(contentsOfFile: credentialFilePath!)
let confTTS: TTSConfiguration = TTSConfiguration()
confTTS.basicAuthUsername = credentials?["TTSUsername"] as! String
confTTS.basicAuthPassword = credentials?["TTSPassword"] as! String
confTTS.audioCodec = WATSONSDK_TTS_AUDIO_CODEC_TYPE_OPUS
confTTS.voiceName = WATSONSDK_DEFAULT_TTS_VOICE
confTTS.xWatsonLearningOptOut = false // Change to true to opt-out
self.ttsInstance = TextToSpeech(config: confTTS)
self.ttsInstance?.listVoices({ (jsonDict, error) -> Void in
if error == nil{
self.voiceHandler(jsonDict)
}
else{
self.ttsField.text = error.description
}
})
}
// dismiss keyboard when the background is touched
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.ttsField.endEditing(true)
}
// start recording
@IBAction func onStartSynthesizing(sender: AnyObject) {
self.ttsInstance?.synthesize({ (data: NSData!, reqError: NSError!) -> Void in
if reqError == nil {
self.ttsInstance?.playAudio({ (error: NSError!) -> Void in
if error == nil{
print("Audio finished playing")
}
else{
print("Error playing audio %@", error.localizedDescription)
}
}, withData: data)
}
else{
print("Error requesting data: %@", reqError.description)
}
}, theText: self.ttsField.text)
}
// show picker view when the button is clicked
@IBAction func onSelectingModel(sender: AnyObject) {
self.hidePickerView(false, withAnimation: true)
}
// hide picker view
func onHidingPickerView(){
self.hidePickerView(true, withAnimation: true)
}
// set voice name when the picker view data is changed
func onSelectedModel(row: Int){
guard let voices = self.ttsVoices else{
return
}
let voice = voices.objectAtIndex(row) as! NSDictionary
let voiceName:String = voice.objectForKey("name") as! String
let voiceGender:String = voice.objectForKey("gender") as! String
self.voiceSelectorButton.setTitle(String(format: "%@: %@", voiceGender, voiceName), forState: .Normal)
self.ttsInstance?.config.voiceName = voiceName
}
// setup picker view after the response is back
func voiceHandler(dict: NSDictionary){
self.ttsVoices = dict.objectForKey("voices") as? NSArray
self.getUIPickerViewInstance().backgroundColor = UIColor.whiteColor()
self.hidePickerView(true, withAnimation: false)
let gestureRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SwiftTTSViewController.pickerViewTapGestureRecognized))
gestureRecognizer.delegate = self
self.getUIPickerViewInstance().addGestureRecognizer(gestureRecognizer);
self.view.addSubview(self.getUIPickerViewInstance())
var row = 0
if let list = self.ttsVoices{
for i in 0 ..< list.count{
if list.objectAtIndex(i).objectForKey("name") as? String == self.ttsInstance?.config.voiceName{
row = i
}
}
}
else{
row = (self.ttsVoices?.count)! - 1
}
self.getUIPickerViewInstance().selectRow(row, inComponent: 0, animated: false)
self.onSelectedModel(row)
}
// get picker view initialized
func getUIPickerViewInstance() -> UIPickerView{
guard let _ = self.pickerView else{
let pickerViewframe = CGRectMake(0, UIScreen.mainScreen().bounds.height - self.pickerViewHeight + self.pickerViewPositionOffset, UIScreen.mainScreen().bounds.width, self.pickerViewHeight)
self.pickerView = UIPickerView(frame: pickerViewframe)
self.pickerView.dataSource = self
self.pickerView.delegate = self
self.pickerView.opaque = true
self.pickerView.showsSelectionIndicator = true
self.pickerView.userInteractionEnabled = true
return self.pickerView
}
return self.pickerView
}
// display/show picker view with animations
func hidePickerView(hide: Bool, withAnimation: Bool){
if withAnimation{
UIView.animateWithDuration(self.pickerViewAnimationDuration, delay: self.pickerViewAnimationDelay, options: .CurveEaseInOut, animations: { () -> Void in
var frame = self.getUIPickerViewInstance().frame
if hide{
frame.origin.y = (UIScreen.mainScreen().bounds.height)
}
else{
self.getUIPickerViewInstance().hidden = hide
frame.origin.y = UIScreen.mainScreen().bounds.height - self.pickerViewHeight + self.pickerViewPositionOffset
}
self.getUIPickerViewInstance().frame = frame
}) { (Bool) -> Void in
self.getUIPickerViewInstance().hidden = hide
}
}
else{
self.getUIPickerViewInstance().hidden = hide
}
}
func pickerViewTapGestureRecognized(sender: UIGestureRecognizer){
self.onSelectedModel(self.getUIPickerViewInstance().selectedRowInComponent(0))
}
// UIGestureRecognizerDelegate
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
// UIGestureRecognizerDelegate
// UIPickerView delegate methods
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
guard let voices = self.ttsVoices else {
return 0
}
return voices.count
}
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 50
}
func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return self.pickerViewHeight
}
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
var tView: UILabel? = view as? UILabel
if tView == nil {
tView = UILabel()
tView?.font = UIFont(name: "Helvetica", size: 12)
tView?.numberOfLines = 1
}
let model = self.ttsVoices?.objectAtIndex(row) as? NSDictionary
tView?.text = String(format: "%@: %@", (model?.objectForKey("gender") as? String)!, (model?.objectForKey("name") as? String)!)
return tView!
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.onSelectedModel(row)
self.hidePickerView(true, withAnimation: true)
}
// UIPickerView delegate methods
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
2337945fd8335cf359cc48a807e0876d
| 40.24186 | 199 | 0.647344 | false | false | false | false |
nua-schroers/mvvm-frp
|
refs/heads/master
|
10_Commandline-App/Matchgame/Matchgame/View/MatchGameUI.swift
|
mit
|
1
|
//
// PlayerMove.swift
// Matchgame
//
// Created by Dr. Wolfram Schroers on 5/9/16.
// Copyright © 2016 Wolfram Schroers. All rights reserved.
//
import Foundation
/// The text-based main UI of the app.
class MatchGameUI {
/// Print the welcome message at the beginning of the game.
class func welcome() {
print("Welcome to the match game\n")
print("The player removing the last match loses the game")
}
/// Query configuration parameters.
///
/// - returns: A tuple of the desired starting number of matches, the maximum number of matches to remove and the desired strategy (1: Dumb, 2: Wild, 3: Smart). Invalid values are returned as 0.
class func queryConfiguration() -> (Int, Int, Int) {
print("Starting number of matches: ", terminator:"")
let initialCount = queryIntNumber()
print("Maximum number of matches to remove: ", terminator:"")
let removeMax = queryIntNumber()
print("Strategy to use (1: Dumb, 2: Wild, 3: Smart): ", terminator:"")
let strategy = queryIntNumber()
return (initialCount, removeMax, strategy)
}
/// Display the current game state.
///
/// - Parameter count: The current number of matches.
class func showState(_ count: Int) {
print("There are \(count) matches")
}
/// Query a single user move. The user is queried for input until a valid move is entered.
///
/// - returns: The player move.
/// - Parameter limit: The maximum number of matches the player may remove.
class func userMove(_ limit:Int) -> Int {
var userMove = 0
var isMoveValid = false
repeat {
// Query the user move.
print("Please enter your move (1..\(limit))", terminator:"")
userMove = queryIntNumber()
if (userMove >= 1) && (userMove <= limit) {
// The move is valid, return it.
isMoveValid = true
} else {
// The move is invalid, inform the user.
print("This is not a valid move!")
}
} while !isMoveValid
return userMove
}
/// Show the number of matches the Mac has taken.
///
/// - Parameter move: The computer's move.
class func showComputerMove(_ move:Int) {
print("I have taken \(move) matches")
}
/// Print the final message at the end of a run.
class func byebye() {
print("I hope to see you soon again")
}
// MARK: Private implementation
/// Query user for an integer number.
///
/// - returns: The number the user has entered or 0 for an invalid input.
fileprivate class func queryIntNumber() -> Int {
// Query user input (may return arbitrary data), convert input to a string.
let userEntry = FileHandle.standardInput.availableData
let userString = String(data: userEntry,
encoding: String.Encoding.utf8) ?? "0"
// Attempt to convert to a number.
let userNumber = Int(userString.trimmingCharacters(in: .newlines)) ?? 0
return userNumber;
}
}
|
eebb71bbc2141f3cafa78b084f12f95c
| 32.924731 | 198 | 0.601268 | false | false | false | false |
JuanjoArreola/Apic
|
refs/heads/master
|
Sources/URLRequest+ParameterEncoding.swift
|
mit
|
1
|
import Foundation
enum EncodeError: Error {
case invalidMethod
}
public extension URLRequest {
mutating func encode(parameters: [String: Any], with encoding: ParameterEncoding) throws {
guard let method = httpMethod else { throw EncodeError.invalidMethod }
switch encoding {
case .url:
if ["GET", "HEAD", "DELETE"].contains(method) {
self.url = try self.url?.appending(parameters: parameters)
} else if let queryString = parameters.urlQueryString {
setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
self.httpBody = queryString.data(using: .utf8, allowLossyConversion: false)
} else {
throw RepositoryError.encodingError
}
case .json:
self.setValue("application/json", forHTTPHeaderField: "Content-Type")
self.httpBody = try JSONSerialization.data(withJSONObject: parameters.jsonValid, options: [])
}
}
}
public extension Dictionary where Key: ExpressibleByStringLiteral {
var urlQueryString: String? {
let string = self.map({ "\($0)=\(String(describing: $1))" }).joined(separator: "&")
return string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
}
var jsonValid: [Key: Any] {
var result = [Key: Any]()
self.forEach({ result[$0] = JSONSerialization.isValidJSONObject(["_": $1]) ? $1 : String(describing: $1) })
return result
}
}
public extension URL {
func appending(parameters: [String: Any]) throws -> URL {
guard let queryString = parameters.urlQueryString,
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)else {
throw RepositoryError.encodingError
}
let percentEncodedQuery = (components.percentEncodedQuery.map { $0 + "&" } ?? "") + queryString
components.percentEncodedQuery = percentEncodedQuery
if let url = components.url {
return url
}
throw RepositoryError.encodingError
}
}
|
8cf9c433c45b687cb241ca6d27b7409c
| 37.618182 | 115 | 0.632768 | false | false | false | false |
MrDeveloper4/TestProject-GitHubAPI
|
refs/heads/master
|
TestProject-GitHubAPI/TestProject-GitHubAPI/User.swift
|
mit
|
1
|
//
// User.swift
// TestProject-GitHubAPI
//
// Created by Yura Chukhlib on 05.07.16.
// Copyright © 2016 Yuri Chukhlib. All rights reserved.
//
import UIKit
import RealmSwift
class User: Object {
dynamic var id = ""
dynamic var userAvatarImageView = ""
dynamic var userBioLabel = ""
dynamic var followersCountLabel = 0
dynamic var followingCountLabel = 0
dynamic var publicGistsLabel = 0
dynamic var publicReposLabel = 0
var repositories = List<Project>()
override static func primaryKey() -> String? {
return "id"
}
}
|
0ed176e78ab083def0f9a7eb8b354b87
| 21.307692 | 56 | 0.667241 | false | false | false | false |
xu6148152/binea_project_for_ios
|
refs/heads/master
|
Dropit/Dropit/DropitBehavior.swift
|
mit
|
1
|
//
// DropitBehavior.swift
// Dropit
//
// Created by Binea Xu on 6/27/15.
// Copyright (c) 2015 Binea Xu. All rights reserved.
//
import UIKit
class DropitBehavior: UIDynamicBehavior {
let gravity = UIGravityBehavior()
lazy var collider : UICollisionBehavior = {
let lazilyCreatedCollider = UICollisionBehavior()
lazilyCreatedCollider.translatesReferenceBoundsIntoBoundary = true
return lazilyCreatedCollider
}()
lazy var dropBehavior : UIDynamicItemBehavior = {
let lazilyCreatedDropBehavior = UIDynamicItemBehavior()
lazilyCreatedDropBehavior.allowsRotation = false
lazilyCreatedDropBehavior.elasticity = 0.75
return lazilyCreatedDropBehavior
}()
override init(){
super.init()
addChildBehavior(gravity)
addChildBehavior(collider)
addChildBehavior(dropBehavior)
}
func addDrop(view : UIView){
dynamicAnimator?.referenceView?.addSubview(view)
gravity.addItem(view)
collider.addItem(view)
dropBehavior.addItem(view)
}
func removeDrop(view : UIView){
gravity.removeItem(view)
collider.removeItem(view)
dropBehavior.removeItem(view)
}
func addBarrier(path: UIBezierPath, named name: String){
collider.removeBoundaryWithIdentifier(name)
collider.addBoundaryWithIdentifier(name, forPath: path)
}
}
|
b2ba63cfdb754a8e42341ed65dfbd3f2
| 26.037037 | 74 | 0.666438 | false | false | false | false |
tianbinbin/DouYuShow
|
refs/heads/master
|
DouYuShow/DouYuShow/Classes/Main/ViewModel/BaseViewModel.swift
|
mit
|
1
|
//
// BaseViewModel.swift
// DouYuShow
//
// Created by 田彬彬 on 2017/6/16.
// Copyright © 2017年 田彬彬. All rights reserved.
//
import UIKit
class BaseViewModel {
// 共同的信息
lazy var anchorGroups:[AnchorGroup] = [AnchorGroup]()
}
extension BaseViewModel{
// 这里 [String:Any]? 是一个可选类型可传可不传 [String:Any]? = nil 直接给一个默认值为nil
// @escaping 当前闭包可能在其他地方使用到 作为逃逸的
// post 请求
func loadAnchorData(urlStr:String,parameters:[String:Any]? = nil,finishedCallBack:@escaping()->()){
NetWorkTools.RequestData(type: .GET, URLString: urlStr, parameters: parameters, SuccessCallBack: { (reslust) in
// 1.对结果进行处理
guard let reslutDict = reslust as? [String:Any] else{return}
guard let dataArr = reslutDict["data"] as? [[String:Any]] else {return}
// 2. 便利数组 将字典转换成模型
for dict in dataArr {
self.anchorGroups.append(AnchorGroup(dict: dict))
}
// 3. 完成回调
finishedCallBack()
}) { (flaseresult) in
}
}
}
|
1be8b95105e24ba268505e72cf552f38
| 23.652174 | 119 | 0.557319 | false | false | false | false |
CosmicMind/Samples
|
refs/heads/development
|
Projects/Programmatic/TransitionsWithIdentifier/TransitionsWithIdentifier/PurpleViewController.swift
|
bsd-3-clause
|
1
|
/*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
import Motion
class PurpleViewController: UIViewController {
fileprivate var v1 = View()
fileprivate var v2 = View()
open override func viewDidLoad() {
super.viewDidLoad()
prepareView()
prepareTransitionViews()
prepareAnimation()
Motion.delay(2) { [weak self] in
self?.dismiss(animated: true)
}
}
}
extension PurpleViewController {
fileprivate func prepareView() {
isMotionEnabled = true
view.backgroundColor = .white
}
fileprivate func prepareTransitionViews() {
v1.backgroundColor = Color.deepOrange.base
v2.backgroundColor = Color.blueGrey.lighten3
}
fileprivate func prepareAnimation() {
animationMatch()
// animationScale()
// animationTranslate()
// animationRotate()
// animationArc()
}
}
extension PurpleViewController {
fileprivate func animationMatch() {
v1.motionIdentifier = "v1"
view.layout(v1).top().left().right().height(200)
v2.motionIdentifier = "v2"
view.layout(v2).bottom().left().right().height(70)
}
fileprivate func animationScale() {
v1.layer.cornerRadius = 15
view.layout(v1).center(offsetY: 50).width(200).height(200)
v1.transition(.scale(0.3), .corner(radius: 15))
v2.motionIdentifier = "v2"
v2.layer.cornerRadius = 15
view.layout(v2).center(offsetY: -100).width(200).height(50)
}
fileprivate func animationTranslate() {
v1.layer.cornerRadius = 15
view.layout(v1).center(offsetY: 50).width(200).height(200)
v1.transition(.translate(x: -200), .corner(radius: 15))
v2.motionIdentifier = "v2"
v2.layer.cornerRadius = 15
view.layout(v2).center(offsetY: -100).width(200).height(50)
}
fileprivate func animationRotate() {
v1.layer.cornerRadius = 15
view.layout(v1).center(offsetY: 50).width(200).height(200)
v1.transition(.translate(x: -200, y: 100), .rotate(270), .corner(radius: 15))
v2.motionIdentifier = "v2"
v2.layer.cornerRadius = 15
view.layout(v2).center(offsetY: -100).width(200).height(50)
}
fileprivate func animationArc() {
v2.motionIdentifier = "v2"
v2.shapePreset = .circle
v2.transition(.arc())
view.layout(v2).center(offsetX: -100, offsetY: -100).width(100).height(100)
}
}
|
1308e576fbb3366648d7c4ca7213d5ce
| 32.810345 | 88 | 0.707292 | false | false | false | false |
kayoslab/CaffeineStatsview
|
refs/heads/master
|
CaffeineStatsview/CaffeineStatsview/View/StatsView.swift
|
mit
|
1
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 cr0ss
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
import UIKit
class StatsView: UIView {
internal var objects:Array<Double>?
private var intersectDistance:Int = 2
private var catmullAlpha:CGFloat = 0.3
private var useCatmullRom:Bool = true
// MARK: - Constants
private let margin:CGFloat = 20.0
private let topBorder:CGFloat = 10
private let bottomBorder:CGFloat = 40
private let graphBorder:CGFloat = 30
private let statsColor:UIColor = .redColor()
// MARK: - Init
override init (frame : CGRect) {
super.init(frame : frame)
}
convenience init () {
self.init(frame:CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func drawRect(rect: CGRect) {
if var objects = self.objects {
let graphHeight = rect.height - self.topBorder - self.bottomBorder - self.graphBorder
let spacer = (rect.width - self.margin * 2) / CGFloat((objects.count-1))
// Is there any maxValue?
let maxValue:Int = Int(objects.maxElement() != nil ? objects.maxElement()! : 0.0)
let columnXPoint = { (column:Int) -> CGFloat in
var x:CGFloat = CGFloat(column) * spacer
x += self.margin
return x
}
let columnYPoint = { (graphPoint:Int) -> CGFloat in
var y:CGFloat = CGFloat(graphPoint) / CGFloat(maxValue) * graphHeight
// Flip the graph
y = graphHeight + self.topBorder + self.graphBorder - y
return y
}
let intersectHeight = (bounds.height - bottomBorder - topBorder)
let numberOfIntersections = Int(ceil(Double(objects.count) / Double(intersectDistance)))
for index in 0 ..< numberOfIntersections {
let intersectPath = UIBezierPath()
let intersectStartPoint = CGPoint(x: columnXPoint(index * self.intersectDistance), y: bounds.height-bottomBorder)
let intersectEndPoint = CGPoint(x: intersectStartPoint.x, y: intersectStartPoint.y - intersectHeight)
intersectPath.moveToPoint(intersectStartPoint)
intersectPath.addLineToPoint(intersectEndPoint)
UIColor.clearColor().setStroke()
intersectPath.lineWidth = 1.0
intersectPath.stroke()
//2 - get the current context
let context = UIGraphicsGetCurrentContext()
let colors = [UIColor.lightGrayColor().CGColor, UIColor.lightGrayColor().CGColor]
//3 - set up the color space
let colorSpace = CGColorSpaceCreateDeviceRGB()
//4 - set up the color stops
let colorLocations:[CGFloat] = [0.0, 0.95]
//5 - create the gradient
let gradient = CGGradientCreateWithColors(colorSpace, colors, colorLocations)
//save the state of the context
CGContextSaveGState(context)
CGContextSetLineWidth(context, intersectPath.lineWidth)
CGContextAddPath(context, intersectPath.CGPath)
CGContextReplacePathWithStrokedPath(context)
CGContextClip(context)
CGContextDrawLinearGradient(context, gradient, intersectStartPoint, intersectEndPoint, .DrawsAfterEndLocation)
CGContextRestoreGState(context)
}
// Graph Color
self.statsColor.setFill()
self.statsColor.setStroke()
let graphPath = UIBezierPath()
var notZero:Bool = false
for object in objects {
if (object != 0.0) {
notZero = true
}
}
if(notZero) {
if (self.useCatmullRom == false || objects.count < 4) {
// Draw Graph without Catmull Rom
graphPath.moveToPoint(CGPoint(x:columnXPoint(0), y:columnYPoint(Int(objects[0]))))
for i in 1..<objects.count {
let nextPoint = CGPoint(x:columnXPoint(i), y:columnYPoint(Int(objects[i])))
graphPath.addLineToPoint(nextPoint)
}
} else {
// Implementation of Catmull Rom
let startIndex = 1
let endIndex = objects.count - 2
for i in startIndex ..< endIndex {
let p0 = CGPoint(x:columnXPoint(i-1 < 0 ? objects.count - 1 : i - 1), y:columnYPoint(Int(objects[i-1 < 0 ? objects.count - 1 : i - 1])))
let p1 = CGPoint(x:columnXPoint(i), y:columnYPoint(Int(objects[i])))
let p2 = CGPoint(x:columnXPoint((i+1) % objects.count), y:columnYPoint(Int(objects[(i+1)%objects.count])))
let p3 = CGPoint(x:columnXPoint((i+1) % objects.count + 1), y:columnYPoint(Int(objects[(i+1)%objects.count + 1])))
let d1 = p1.deltaTo(p0).length()
let d2 = p2.deltaTo(p1).length()
let d3 = p3.deltaTo(p2).length()
var b1 = p2.multiplyBy(pow(d1, 2 * self.catmullAlpha))
b1 = b1.deltaTo(p0.multiplyBy(pow(d2, 2 * self.catmullAlpha)))
b1 = b1.addTo(p1.multiplyBy(2 * pow(d1, 2 * self.catmullAlpha) + 3 * pow(d1, self.catmullAlpha) * pow(d2, self.catmullAlpha) + pow(d2, 2 * self.catmullAlpha)))
b1 = b1.multiplyBy(1.0 / (3 * pow(d1, self.catmullAlpha) * (pow(d1, self.catmullAlpha) + pow(d2, self.catmullAlpha))))
var b2 = p1.multiplyBy(pow(d3, 2 * self.catmullAlpha))
b2 = b2.deltaTo(p3.multiplyBy(pow(d2, 2 * self.catmullAlpha)))
b2 = b2.addTo(p2.multiplyBy(2 * pow(d3, 2 * self.catmullAlpha) + 3 * pow(d3, self.catmullAlpha) * pow(d2, self.catmullAlpha) + pow(d2, 2 * self.catmullAlpha)))
b2 = b2.multiplyBy(1.0 / (3 * pow(d3, self.catmullAlpha) * (pow(d3, self.catmullAlpha) + pow(d2, self.catmullAlpha))))
if i == startIndex {
graphPath.moveToPoint(p0)
}
graphPath.addCurveToPoint(p2, controlPoint1: b1, controlPoint2: b2)
}
let nextPoint = CGPoint(x:columnXPoint(objects.count - 1), y:columnYPoint(Int(objects[objects.count - 1])))
graphPath.addLineToPoint(nextPoint)
}
} else {
// Draw a Line, when there are no Objects in the Array
let zero = graphHeight + topBorder + graphBorder
graphPath.moveToPoint(CGPoint(x:columnXPoint(0), y:zero))
for i in 1..<objects.count {
let nextPoint = CGPoint(x:columnXPoint(i), y:zero)
graphPath.addLineToPoint(nextPoint)
}
}
graphPath.lineWidth = 2.0
graphPath.stroke()
for i in 0..<objects.count {
if (i % self.intersectDistance == 0) {
var point = CGPoint(x:columnXPoint(i), y:columnYPoint(Int(objects[i])))
point.x -= 5.0/2
point.y -= 5.0/2
let circle = UIBezierPath(ovalInRect: CGRect(origin: point, size: CGSize(width: 5.0, height: 5.0)))
circle.fill()
}
}
}
}
internal func setUpGraphView(statisticsItems:Array<Double>, intersectDistance:Int, catmullRom:Bool, catmullAlpha:CGFloat = 0.30) {
if statisticsItems.count <= 1 {
self.objects = [0.0, 0.0]
self.intersectDistance = 1
} else if intersectDistance == 0 {
self.intersectDistance = 1
self.intersectDistance += statisticsItems.count % 2
self.objects = statisticsItems
} else {
self.intersectDistance = intersectDistance
self.objects = statisticsItems
}
self.useCatmullRom = catmullRom
self.catmullAlpha = catmullAlpha
self.setNeedsDisplay()
}
}
// MARK: - CGPoint Extension
extension CGPoint{
func addTo(a: CGPoint) -> CGPoint {
return CGPointMake(self.x + a.x, self.y + a.y)
}
func deltaTo(a: CGPoint) -> CGPoint {
return CGPointMake(self.x - a.x, self.y - a.y)
}
func length() -> CGFloat {
return CGFloat(sqrt(CDouble(self.x*self.x + self.y*self.y)))
}
func multiplyBy(value:CGFloat) -> CGPoint{
return CGPointMake(self.x * value, self.y * value)
}
}
|
c05902d96a32d7f29113250cd8cee294
| 44.086364 | 183 | 0.575116 | false | false | false | false |
wess/overlook
|
refs/heads/master
|
Sources/overlook/commands/help.swift
|
mit
|
1
|
//
// help.swift
// overlook
//
// Created by Wesley Cope on 9/30/16.
//
//
import Foundation
import SwiftCLI
import Rainbow
public class HelpCommand : SwiftCLI.HelpCommand, Command {
public let name = "help"
public let signature = "[<opt>] ..."
public let shortDescription = "Prints help information"
public var printCLIDescription: Bool = true
public var allCommands: [Command] = []
public var availableCommands:[Command] = []
public func setupOptions(options: OptionRegistry) {}
public func execute(arguments: CommandArguments) throws {
print("Usage: overlook [OPTIONS]\n")
print("Available commands: ")
for command in allCommands {
var name = command.name
if !command.signature.isEmpty && !(command is HelpCommand) {
name += " \(command.signature)"
}
printLine(name: name, description: command.shortDescription)
}
}
private func printLine(name: String, description: String) {
let spacing = String(repeating: " ", count: 20 - name.characters.count)
print(" " + Overlook.name.lowercased() + " " + name.bold + "\(spacing)\(description)")
}
}
|
1c72df1e2a359df6b74640563e3e5ad2
| 24.510638 | 90 | 0.634696 | false | false | false | false |
Jubilant-Appstudio/Scuba
|
refs/heads/master
|
ScubaCalendar/Resource/Shared/CommonMethods.swift
|
mit
|
1
|
//
// CommonMethods.swift
// CredDirectory
//
// Created by Mahipal on 13/4/17.
// Copyright © 2017 Mahipal. All rights reserved.
//
import UIKit
import MBProgressHUD
import SkyFloatingLabelTextField
class CommonMethods: NSObject {
//Declare enum
enum AnimationType {
case ANIMATERIGHT
case ANIMATELEFT
case ANIMATEUP
case ANIMATEDOWN
}
struct SetFont {
static let MontserratSemiBold = UIFont(name: "Montserrat-SemiBold", size: 15.0)
static let MontserratMedium = UIFont(name: "Montserrat-Medium", size: 15.0)
static let MontserratBold = UIFont(name: "Montserrat-Bold", size: 15.0)
static let RalewayRegular = UIFont(name: "Raleway-Regular", size: 15.0)
static let RalewaySemiBold = UIFont(name: "Raleway-SemiBold", size: 15.0)
}
struct SetFontSize {
static let S10 = 10.0
static let S12 = 12.0
static let S15 = 15.0
static let S17 = 17.0
static let S20 = 20.0
}
struct SetColor {
static let clearColor = UIColor.clear
static let whiteColor = UIColor.white
static let themeColor = UIColor(red: 63/255.0, green: 81/255.0, blue: 114/255.0, alpha: 1.0)
static let darkGrayColor = UIColor(red: 104/255.0, green: 104/255.0, blue: 104/255.0, alpha: 1.0)
static let searchbarBGColor = UIColor(red: 15/255.0, green: 19/255.0, blue: 30/255.0, alpha: 1.0)
static let pickerBorderColor = UIColor(red: 0.0/255.0, green: 81.0/255.0, blue: 114.0/255.0, alpha: 1.0)
}
/*
static var setTextColor = UIColor.white
static var setLineColor = UIColor.white
static var setTopPlaceHolderColor = UIColor(red: 63/255.0, green: 81/255.0, blue: 114/255.0, alpha: 1.0)
*/
static var hud: MBProgressHUD = MBProgressHUD()
static var navControl: UINavigationController?
static var alert: UIAlertController?
static var sharedObj: Shared?
class func navigateTo(_ destinationVC: UIViewController, inNavigationViewController navigationController: UINavigationController, animated: Bool ) {
//Assign to global value
navControl = navigationController
var VCFound: Bool = false
let viewControllers: NSArray = navigationController.viewControllers as NSArray
var indexofVC: NSInteger = 0
for vc in navigationController.viewControllers {
if vc.nibName == (destinationVC.nibName) {
VCFound = true
break
} else {
indexofVC += 1
}
}
DispatchQueue.main.async(execute: {
if VCFound == true {
// navigationController .popToViewController(viewControllers.object(at: indexofVC) as! UIViewController, animated: animated)
if let navigationObj: UIViewController = viewControllers.object(at: indexofVC) as? UIViewController {
navigationController.popToViewController(navigationObj, animated: animated)
}
} else {
navigationController .pushViewController(destinationVC, animated: animated)
}
})
}
class func findViewControllerRefInStack(_ destinationVC: UIViewController, inNavigationViewController navigationController: UINavigationController) -> UIViewController {
var VCFound = false
var viewControllers = navigationController.viewControllers
var indexofVC = 0
for vc: UIViewController in viewControllers {
if vc.nibName == (destinationVC.nibName) {
VCFound = true
break
} else {
indexofVC += 1
}
}
if VCFound == true {
return viewControllers[indexofVC]
} else {
return destinationVC
}
}
// MARK: UIAlertView
class func showAlert(_ title: NSString, Description message: NSString) {
if alert != nil {
self.dismissAlertView()
}
DispatchQueue.main.async {
// alert = UIAlertView(title: title as String, message: message as String, delegate: nil, cancelButtonTitle: "Okay")
// alert!.show()
alert = UIAlertController(title: title as String, message: message as String, preferredStyle: .alert)
alert?.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
getTopViewController().present(alert!, animated: true, completion: nil)
}
}
class func dismissAlertView() {
alert?.dismiss(animated: true, completion: nil)
}
class func getTopViewController() -> UIViewController {
var viewController = UIViewController()
if let vc = UIApplication.shared.delegate?.window??.rootViewController {
viewController = vc
var presented = vc
while let top = presented.presentedViewController {
presented = top
viewController = top
}
}
print(viewController)
return viewController
}
class func showMBProgressHudView(_ view: UIView) {
DispatchQueue.main.async(execute: {
self.hud = MBProgressHUD.showAdded(to: view, animated: true)
})
}
class func showPercentageMBProgressHudView(_ view: UIView) {
DispatchQueue.main.async(execute: {
self.hud = MBProgressHUD.showAdded(to: view, animated: true)
hud.mode = .determinateHorizontalBar
})
}
class func hideMBProgressHud() {
DispatchQueue.main.async(execute: {
self.hud.hide(animated: true)
})
}
class func convertDateFormat(fullDate: String) -> String {
if fullDate != "" {
let dateFormatter = DateFormatter()
let tempLocale = dateFormatter.locale
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let date = dateFormatter.date(from: fullDate)!
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.locale = tempLocale
let dateString = dateFormatter.string(from: date)
return dateString
} else {
return ""
}
}
class func setCommonLayer(getButton: UIButton) -> UIButton {
getButton.layer.borderColor = UIColor.white.cgColor
getButton.layer.borderWidth = 0.5
getButton.layer.cornerRadius = 5.0
return getButton
}
class func setCommonTextfield(getTextfield: SkyFloatingLabelTextField) -> SkyFloatingLabelTextField {
getTextfield.textColor = CommonMethods.SetColor.whiteColor
getTextfield.selectedLineColor = CommonMethods.SetColor.whiteColor
getTextfield.placeholderColor = CommonMethods.SetColor.themeColor
getTextfield.titleColor = CommonMethods.SetColor.themeColor
getTextfield.lineColor = CommonMethods.SetColor.themeColor
getTextfield.selectedTitleColor = CommonMethods.SetColor.themeColor
return getTextfield
}
class func setCommonSearchField(getSearchBar: UISearchBar) -> UISearchBar {
getSearchBar.borderColor = CommonMethods.SetColor.darkGrayColor
getSearchBar.borderWidth = 0.5
getSearchBar.cornerRadius = 5
getSearchBar.shadowOffset = CGSize(width: 0, height: 1)
getSearchBar.barTintColor = CommonMethods.SetColor.clearColor
getSearchBar.barStyle = .black
getSearchBar.barTintColor = CommonMethods.SetColor.clearColor
getSearchBar.tintColor = CommonMethods.SetColor.clearColor
getSearchBar.textField?.textColor = CommonMethods.SetColor.whiteColor
return getSearchBar
}
class func showViewControllerWith(storyboard: String , newViewController: UIViewController, usingAnimation animationType: AnimationType) {
let currentViewController = UIApplication.shared.delegate?.window??.rootViewController
let width = currentViewController?.view.frame.size.width
let height = currentViewController?.view.frame.size.height
var previousFrame: CGRect?
var nextFrame: CGRect?
switch animationType {
case .ANIMATELEFT:
previousFrame = CGRect(x: (width!) - 1, y: 0.0, width: width!, height: height!)
nextFrame = CGRect(x: -(width!), y: 0.0, width: width!, height: height!)
case .ANIMATERIGHT:
previousFrame = CGRect(x: -(width!) + 1, y: 0.0, width: width!, height: height!)
nextFrame = CGRect(x: (width!), y: 0.0, width: width!, height: height!)
case .ANIMATEUP:
previousFrame = CGRect(x: 0.0, y: (height!) - 1, width: width!, height: height!)
nextFrame = CGRect(x: 0.0, y: -(height!) + 1, width: width!, height: height!)
case .ANIMATEDOWN:
previousFrame = CGRect(x: 0.0, y: -(height!) + 1, width: width!, height: height!)
nextFrame = CGRect(x: 0.0, y: (height!) + 1, width: width!, height: height!)
}
newViewController.view.frame = previousFrame!
UIApplication.shared.delegate?.window??.addSubview(newViewController.view)
UIView.animate(withDuration: 0.3,
animations: { () -> Void in
newViewController.view.frame = (currentViewController?.view.frame)!
currentViewController?.view.frame = nextFrame!
}) { (_: Bool) -> Void in
UIApplication.shared.delegate?.window??.removeSubviews()
if storyboard == "Home" {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Home", bundle: nil)
UIApplication.shared.delegate?.window??.rootViewController = mainStoryboard.instantiateInitialViewController()
} else {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
guard let loginVC = mainStoryboard.instantiateViewController(withIdentifier: "LoginVC") as? LoginVC else {
return
}
let nav = UINavigationController(rootViewController: loginVC)
nav.setNavigationBarHidden(true, animated: false)
UIApplication.shared.delegate?.window??.rootViewController = nav
}
}
}
}
|
e9ec4bd38994602c24811ee645c411f4
| 35.923588 | 173 | 0.592676 | false | false | false | false |
kfarst/alarm
|
refs/heads/master
|
alarm/TimePickerViewController.swift
|
mit
|
1
|
//
// TimePickerViewController.swift
// alarm
//
// Created by Michael Lewis on 3/8/15.
// Copyright (c) 2015 Kevin Farst. All rights reserved.
//
import UIKit
protocol TimePickerDelegate {
func timeSelected(time: TimePresenter)
}
class TimePickerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var timePicker: UIPickerView!
// We're turning a linear picker into a circular one by
// massively duplicating the number of rows, and starting
// off in the middle.
let circularPickerExplosionFactor = 50
let pickerNaturalWidth = CGFloat(160.0)
let pickerNaturalHeight = CGFloat(216.0)
var pickerWidthScaleRatio = CGFloat(1.0)
var pickerHeightScaleRatio = CGFloat(1.0)
// Vertically stretch up the picker element text
let pickerElementHeightScaleRatio = CGFloat(1.3)
var pickerData: Array<TimePresenter>?
var startingTimePresenter: TimePresenter?
var delegate: TimePickerDelegate!
override func viewDidLoad() {
super.viewDidLoad()
// Set up our visual elements
self.view.backgroundColor = UIColor.clearColor()
timePicker.backgroundColor = UIColor.clearColor()
timePicker.alpha = 1.0
// Do any additional setup after loading the view.
timePicker.dataSource = self
timePicker.delegate = self
// Generate our picker data
pickerData = TimePresenter.generateAllElements()
// If we were given a TimePresenter to start with,
// try to select it.
if let timePresenter = startingTimePresenter {
selectTimePresenterRow(timePresenter)
}
}
override func viewWillAppear(animated: Bool) {
fixTimePickerDimensions()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
// Run up the number by a factor of 100 in order to provide fake
// circular selection. This has been profiled and does not materially
// hurt memory usage.
return (pickerData?.count ?? 0) * circularPickerExplosionFactor * 2
}
// For each picker element, set up the view
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {
var timeView = UIView()
timeView.frame = CGRectMake(0, 0, pickerView.rowSizeForComponent(component).width, pickerView.rowSizeForComponent(component).height)
var timeLabel = UILabel()
var amPmLabel = UILabel()
if let activeElement = getTimePickerAtRow(row) {
let displayString = activeElement.stringForWheelDisplay()
var amPmString: String
if contains(["noon", "midnight"], displayString) {
amPmString = ""
} else {
amPmString = activeElement.stringForAmPm()
}
let transformation = CGAffineTransformMakeScale(
1.0 / pickerWidthScaleRatio,
pickerElementHeightScaleRatio / pickerHeightScaleRatio
)
// Create the labels with our attributed text
timeLabel.attributedText = NSAttributedString(
string: displayString,
attributes: [
NSFontAttributeName: UIFont(name: "Avenir-Light", size: 32.0)!,
NSForegroundColorAttributeName: UIColor(white: 0.8, alpha: 1.0),
]
)
timeLabel.textAlignment = .Center
amPmLabel.attributedText = NSAttributedString(
string: amPmString,
attributes: [
NSFontAttributeName: UIFont(name: "Avenir-Light", size: 18.0)!,
NSForegroundColorAttributeName: UIColor(white: 0.8, alpha: 1.0),
]
)
amPmLabel.textAlignment = .Center
// Finally, transform the text. This essentially performs two transforms.
// The first one is an inverse of the transform run on the picker
// as a whole. This makes sure that while the picker itself is
// stretched, the individual elements themselves are not.
// The second one is an individual scale of the element for
// aesthetics.
timeLabel.transform = transformation
amPmLabel.transform = transformation
}
timeLabel.sizeToFit()
timeLabel.center = timeView.center
amPmLabel.sizeToFit()
amPmLabel.center = CGPoint(x: (timeLabel.center.x + timeLabel.frame.width / 2) + (amPmLabel.frame.width / 2) + 10, y: timeLabel.center.y + amPmLabel.frame.height / 6)
timeView.addSubview(timeLabel)
timeView.addSubview(amPmLabel)
return timeView
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// pickerData[row]
}
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 20.0
}
// The accept button was selected
@IBAction func acceptTapped(sender: UITapGestureRecognizer) {
let selectedRow = timePicker.selectedRowInComponent(0)
if let activeElement = getTimePickerAtRow(selectedRow) {
delegate?.timeSelected(activeElement)
}
}
/* Private */
// Given a time presenter, select the row in the picker view
// that is equal.
private func selectTimePresenterRow(timePresenter: TimePresenter, animated: Bool = false) {
if let data = pickerData {
if let index = find(data, timePresenter) {
let newRowIndex = data.count * circularPickerExplosionFactor + index
timePicker.selectRow(newRowIndex, inComponent: 0, animated: animated)
}
}
}
// Get the element at a given row
// This is helpful because of our circular data
private func getTimePickerAtRow(row: Int) -> TimePresenter? {
if let data = pickerData {
// Because we're duplicating elements in order to simulate
// a circular effect, we need to use modulus when accessing
// the data by row number.
let numRows = data.count
return data[row % numRows]
} else {
NSLog("Should never nil here")
return nil
}
}
// Horizontally stretch the time picker to the full height of the
// surrounding view. This introduces some weird stretching effects that
// need to be dealt with, but it's the only way to get a picker to display
// with a height greater than 216.
private func fixTimePickerDimensions() {
pickerWidthScaleRatio = (self.view.frame.width / 2.0) / pickerNaturalWidth
pickerHeightScaleRatio = self.view.frame.height / pickerNaturalHeight
timePicker.transform = CGAffineTransformMakeScale(pickerWidthScaleRatio, pickerHeightScaleRatio)
}
}
|
a669c6a6136f12835254dca2f567d1e0
| 32.913265 | 170 | 0.705431 | false | false | false | false |
ibari/ios-yelp
|
refs/heads/master
|
Yelp/CheckMarkCell.swift
|
gpl-2.0
|
1
|
//
// CheckMarkCell.swift
// Yelp
//
// Created by Ian on 5/17/15.
// Copyright (c) 2015 Ian Bari. All rights reserved.
//
import UIKit
@objc protocol CheckMarkCellDelegate {
optional func checkMarkCell(checkMarkCell: CheckMarkCell, toggleIdenfifier: AnyObject, didChangeValue value:Bool)
}
class CheckMarkCell: UITableViewCell {
@IBOutlet weak var descriptionLabel: UILabel!
var checkIdentifier: AnyObject = ""
var isChecked: Bool = false {
didSet {
if isChecked {
self.accessoryType = .Checkmark
} else {
self.accessoryType = .None
}
}
}
weak var delegate: CheckMarkCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
if selected && !self.selected {
super.setSelected(true, animated: true)
isChecked = !isChecked
delegate?.checkMarkCell?(self, toggleIdenfifier: checkIdentifier, didChangeValue: isChecked)
super.setSelected(false, animated: true)
}
}
}
|
6ea04f6b88c091a0e3b66111f9f0644e
| 23.27907 | 115 | 0.68744 | false | false | false | false |
AlmostDoneGames/BrickBreaker-iOS
|
refs/heads/master
|
Sprong/Bullet.swift
|
apache-2.0
|
2
|
//
// Bullet.swift
// MathBreaker
//
// Created by Cameron Bardell on 2015-12-26.
// Copyright © 2015 Jared McGrath. All rights reserved.
//
import SpriteKit
class Bullet: SKSpriteNode {
var fromTop:Bool
// MARK: Initializers
init (position: CGPoint, fromTop: Bool) {
let texture = SKTexture(imageNamed: "Bullet")
//Changes where the score should be added
self.fromTop = fromTop
super.init(texture: texture, color: SKColor.clearColor(), size: texture.size())
self.physicsBody = SKPhysicsBody(circleOfRadius: texture.size().width/2)
self.physicsBody!.dynamic = true
self.physicsBody!.friction = 0
self.physicsBody!.collisionBitMask = 0x0
self.physicsBody!.linearDamping = 0
self.position = position
self.name = "bullet"
}
required init?(coder aDecoder: NSCoder) {
self.fromTop = false
super.init(coder: aDecoder)
}
}
|
1a266093509d2eef33d65af93962db78
| 26.685714 | 87 | 0.637397 | false | false | false | false |
CRAnimation/CRAnimation
|
refs/heads/master
|
Example/CRAnimation/Demo/WidgetDemo/S0004_WCLLoadingView/WCLLoadingViewDemoVC.swift
|
mit
|
1
|
//
// WCLLoadingViewDemoVC.swift
// CRAnimation
//
// **************************************************
// * _____ *
// * __ _ __ ___ \ / *
// * \ \/ \/ / / __\ / / *
// * \ _ / | (__ / / *
// * \/ \/ \___/ / /__ *
// * /_____/ *
// * *
// **************************************************
// Github :https://github.com/631106979
// HomePage:https://imwcl.com
// CSDN :http://blog.csdn.net/wang631106979
//
// Created by 王崇磊 on 16/9/14.
// Copyright © 2016年 王崇磊. All rights reserved.
//
// @class WCLLoadingViewDemoVC
// @abstract WCLLoadingView的DemoVC
// @discussion WCLLoadingView的DemoVC
//
import UIKit
public let SWIFT_WIDTH = UIScreen.main.bounds.size.width
public let SWIFT_HEIGHT = UIScreen.main.bounds.size.height
public let color_0a090e = UIColor.init(rgba: "#0a090e")
class WCLLoadingViewDemoVC: CRProductionBaseVC {
@IBOutlet weak var loadingView: WCLLoadingView!
let controlViewHeight = 40
let offY: CGFloat = 30
let gapX: CGFloat = 10
//MARK: Public Methods
//MARK: Override
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
loadingView.startAnimation()
view.backgroundColor = color_0a090e
addTopBar(withTitle: "WCLLoadingView")
createSizeControlView()
createDurationControlView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Target Methods
@IBAction func tapLoadingView(_ sender: UITapGestureRecognizer) {
switch loadingView.status {
case .animating:
loadingView.pauseAnimation()
case .pause:
loadingView.resumeAnimation()
case .normal:
loadingView.startAnimation()
}
}
@IBAction func sizeSliderValueChange(_ sender: UISlider) {
loadingView.transform = CGAffineTransform.identity.scaledBy(x: CGFloat(sender.value) , y: CGFloat(sender.value))
}
@IBAction func durationSliderValueChange(_ sender: UISlider) {
loadingView.duration = Double(sender.value)
}
func createControlView() -> Void {
createSizeControlView()
createDurationControlView()
}
func createSizeControlView() {
let sizeControlView = UIView.init(frame: CGRect.init(x: Int(CR_OFF_STARTX), y: 0, width: Int(SWIFT_WIDTH) - Int(CR_OFF_STARTX + CR_OFF_ENDX), height: controlViewHeight))
view.addSubview(sizeControlView)
let sizeLabel = UILabel.init()
sizeLabel.text = "Size"
sizeLabel.textColor = UIColor.white
sizeLabel.sizeToFit()
sizeControlView.addSubview(sizeLabel)
sizeLabel.bearSetRelativeLayout(with: .DIR_LEFT, destinationView: nil, parentRelation: true, distance: 0, center: true)
let sizeControlSlider = CRSlider.init(frame: CGRect.init(x: sizeLabel.maxX() + gapX, y: 0, width: sizeControlView.width() - sizeLabel.maxX() - gapX, height: sizeControlView.height()))
sizeControlSlider.sliderType = kCRSliderType_Normal
sizeControlSlider.minimumValue = 1
sizeControlSlider.maximumValue = 2
sizeControlSlider.value = 1
sizeControlSlider.addTarget(self, action: #selector(WCLLoadingViewDemoVC.sizeSliderValueChange(_:)), for: UIControlEvents.valueChanged)
sizeControlView.addSubview(sizeControlSlider)
sizeControlView.setMaxY(SWIFT_HEIGHT - CGFloat(controlViewHeight) - offY)
}
func createDurationControlView() {
let durationControlView = UIView.init(frame: CGRect.init(x: Int(CR_OFF_STARTX), y: 0, width: Int(SWIFT_WIDTH) - Int(CR_OFF_STARTX + CR_OFF_ENDX), height: controlViewHeight))
view.addSubview(durationControlView)
let durationLabel = UILabel.init()
durationLabel.text = "Duration"
durationLabel.textColor = UIColor.white
durationLabel.sizeToFit()
durationControlView.addSubview(durationLabel)
durationLabel.bearSetRelativeLayout(with: .DIR_LEFT, destinationView: nil, parentRelation: true, distance: 0, center: true)
let durationControlSlider = CRSlider.init(frame: CGRect.init(x: durationLabel.maxX() + gapX, y: 0, width: durationControlView.width() - durationLabel.maxX() - gapX, height: durationControlView.height()))
durationControlSlider.sliderType = kCRSliderType_Normal
durationControlSlider.minimumValue = 1
durationControlSlider.maximumValue = 2
durationControlSlider.value = 1
durationControlSlider.addTarget(self, action: #selector(WCLLoadingViewDemoVC.durationSliderValueChange(_:)), for: UIControlEvents.valueChanged)
durationControlView.addSubview(durationControlSlider)
durationControlView.setMaxY(SWIFT_HEIGHT - offY)
}
}
|
b6c01f36eaf828716dda7b7c086fabb7
| 39.920635 | 211 | 0.623157 | false | false | false | false |
kingcos/Swift-3-Design-Patterns
|
refs/heads/master
|
20-Command_Pattern.playground/Contents.swift
|
apache-2.0
|
1
|
//: Playground - noun: a place where people can play
// Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns
import UIKit
// 烧烤
struct Barbecuer {
enum BBQ: String {
case mutton = "烤羊肉串"
case chickenWing = "烤鸡翅"
}
var state: BBQ = .mutton
mutating func bakeMutton() {
state = .mutton
print("\(state.rawValue)")
}
mutating func backChickenWing() {
state = .chickenWing
print("\(state.rawValue)")
}
}
// 命令
class Command: Hashable {
var bbq: Barbecuer
init(_ bbq: Barbecuer) {
self.bbq = bbq
}
var hashValue: Int {
return bbq.state.hashValue
}
static func ==(l: Command, r: Command) -> Bool {
return l.hashValue == r.hashValue
}
func executeCommand() {}
}
// 烤羊肉串命令
class BakeMuttonCommand: Command {
override init(_ bbq: Barbecuer) {
super.init(bbq)
self.bbq.state = .mutton
}
override func executeCommand() {
bbq.bakeMutton()
}
}
// 烤鸡翅命令
class BakeChickenWingCommand: Command {
override init(_ bbq: Barbecuer) {
super.init(bbq)
self.bbq.state = .chickenWing
}
override func executeCommand() {
bbq.backChickenWing()
}
}
// 服务员
struct Waiter {
var cmdSet = Set<Command>()
mutating func setOrder(_ command: Command) {
if command.bbq.state == .chickenWing {
print("没有鸡翅了,请点别的烧烤")
} else {
cmdSet.insert(command)
print("增加订单:\(command.bbq.state.rawValue)")
}
}
mutating func removeOrder(_ command: Command) {
cmdSet.remove(command)
print("取消订单:\(command.bbq.state.rawValue)")
}
func notify() {
for command in cmdSet {
command.executeCommand()
}
}
}
let bbq = Barbecuer()
let muttonA = BakeMuttonCommand(bbq)
let muttonB = BakeMuttonCommand(bbq)
let chickenWingA = BakeChickenWingCommand(bbq)
var waiter = Waiter()
waiter.setOrder(muttonA)
waiter.setOrder(muttonB)
waiter.setOrder(chickenWingA)
|
ee30d78e9b4b37d89b9904ca4d619f21
| 19.757282 | 90 | 0.587933 | false | false | false | false |
brentsimmons/Evergreen
|
refs/heads/ios-candidate
|
Shared/Exporters/OPMLExporter.swift
|
mit
|
1
|
//
// OPMLExporter.swift
// NetNewsWire
//
// Created by Brent Simmons on 12/22/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import Account
import RSCore
struct OPMLExporter {
static func OPMLString(with account: Account, title: String) -> String {
let escapedTitle = title.escapingSpecialXMLCharacters
let openingText =
"""
<?xml version="1.0" encoding="UTF-8"?>
<!-- OPML generated by NetNewsWire -->
<opml version="1.1">
<head>
<title>\(escapedTitle)</title>
</head>
<body>
"""
let middleText = account.OPMLString(indentLevel: 0)
let closingText =
"""
</body>
</opml>
"""
let opml = openingText + middleText + closingText
return opml
}
}
|
e0c222cedc7986967700b53998b17e51
| 17.390244 | 73 | 0.648541 | false | false | false | false |
burnsra/SquidBar
|
refs/heads/master
|
SquidBar/PreferencesController.swift
|
mit
|
1
|
//
// PreferencesController.swift
// SquidBar
//
// Created by Robert Burns on 2/11/16.
// Copyright © 2016 Robert Burns. All rights reserved.
//
import Foundation
private let squidExecutableKey = "squidExecutable"
private let squidConfigurationKey = "squidConfiguration"
private let squidLaunchKey = "squidStartOnLaunch"
private let squidWatchNetworkKey = "squidWatchNetwork"
class PreferenceController {
private let userDefaults = NSUserDefaults.standardUserDefaults()
func registerDefaultPreferences() {
let defaults = [ squidExecutableKey : "/usr/local/opt/squid/sbin/squid", squidConfigurationKey : "/usr/local/etc/squid.conf", squidLaunchKey : false, squidWatchNetworkKey : true ]
userDefaults.registerDefaults(defaults)
}
func resetDefaultPreferences() {
userDefaults.removeObjectForKey(squidExecutableKey)
userDefaults.removeObjectForKey(squidConfigurationKey)
userDefaults.removeObjectForKey(squidLaunchKey)
userDefaults.removeObjectForKey(squidWatchNetworkKey)
registerDefaultPreferences()
}
func synchronizePreferences() {
userDefaults.synchronize()
}
init() {
registerDefaultPreferences()
}
var squidExecutable: String? {
set (newSquidExecutable) {
userDefaults.setObject(newSquidExecutable, forKey: squidExecutableKey)
}
get {
return userDefaults.objectForKey(squidExecutableKey) as? String
}
}
var squidConfiguration: String? {
set (newSquidConfiguration) {
userDefaults.setObject(newSquidConfiguration, forKey: squidConfigurationKey)
}
get {
return userDefaults.objectForKey(squidConfigurationKey) as? String
}
}
var squidStartOnLaunch: Bool? {
set (newSquidStartOnLaunch) {
userDefaults.setObject(newSquidStartOnLaunch, forKey: squidLaunchKey)
}
get {
return userDefaults.objectForKey(squidLaunchKey) as? Bool
}
}
var squidWatchNetwork: Bool? {
set (newSquidWatchNetwork) {
userDefaults.setObject(newSquidWatchNetwork, forKey: squidWatchNetworkKey)
}
get {
return userDefaults.objectForKey(squidWatchNetworkKey) as? Bool
}
}
}
|
c0e895f69e1432214abe1eff2dd848e1
| 29.194805 | 188 | 0.686317 | false | true | false | false |
rizumita/CTFeedbackSwift
|
refs/heads/main
|
CTFeedbackSwift/FeedbackConfiguration.swift
|
mit
|
1
|
//
// Created by 和泉田 領一 on 2017/09/07.
// Copyright (c) 2017 CAPH TECH. All rights reserved.
//
import Foundation
public class FeedbackConfiguration {
public var subject: String?
public var additionalDiagnosticContent: String?
public var toRecipients: [String]
public var ccRecipients: [String]
public var bccRecipients: [String]
public var usesHTML: Bool
public var dataSource: FeedbackItemsDataSource
/*
If topics array contains no topics, topics cell is hidden.
*/
public init(subject: String? = .none,
additionalDiagnosticContent: String? = .none,
topics: [TopicProtocol] = TopicItem.defaultTopics,
toRecipients: [String],
ccRecipients: [String] = [],
bccRecipients: [String] = [],
hidesUserEmailCell: Bool = true,
hidesAttachmentCell: Bool = false,
hidesAppInfoSection: Bool = false,
usesHTML: Bool = false,
appName: String? = nil) {
self.subject = subject
self.additionalDiagnosticContent = additionalDiagnosticContent
self.toRecipients = toRecipients
self.ccRecipients = ccRecipients
self.bccRecipients = bccRecipients
self.usesHTML = usesHTML
self.dataSource = FeedbackItemsDataSource(topics: topics,
hidesUserEmailCell: hidesUserEmailCell,
hidesAttachmentCell: hidesAttachmentCell,
hidesAppInfoSection: hidesAppInfoSection,
appName: appName)
}
}
|
67c2dd6c87e614e41f336739a58258b5
| 41.372093 | 91 | 0.548299 | false | false | false | false |
Hansoft/meteor
|
refs/heads/fav-96944
|
cordova-build-release/platforms/ios/Timelines/Plugins/cordova-plugin-meteor-webapp/Utility.swift
|
agpl-3.0
|
5
|
extension Collection {
func find(_ predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Self.Iterator.Element? {
return try index(where: predicate).map({self[$0]})
}
}
typealias JSONObject = [String:AnyObject]
// Regex that matches the query string part of a URL
let queryStringRegEx = try! NSRegularExpression(pattern: "(/[^?]+).*", options: [])
func URLPathByRemovingQueryString(_ URLString: String) -> String {
guard let match = queryStringRegEx.firstMatchInString(URLString) else {
return URLString
}
return (URLString as NSString).substring(with: match.range(at: 1))
}
// Regex that matches a SHA1 hash
let sha1HashRegEx = try! NSRegularExpression(pattern: "[0-9a-f]{40}", options: [])
// Regex that matches an ETag with a SHA1 hash
let ETagWithSha1HashRegEx = try! NSRegularExpression(pattern: "\"([0-9a-f]{40})\"", options: [])
func SHA1HashFromETag(_ ETag: String) -> String? {
guard let match = ETagWithSha1HashRegEx.firstMatchInString(ETag) else {
return nil
}
return (ETag as NSString).substring(with: match.range(at: 1))
}
extension NSRegularExpression {
func firstMatchInString(_ string: String) -> NSTextCheckingResult? {
return firstMatch(in: string, options: [],
range: NSRange(location: 0, length: string.utf16.count))
}
func matches(_ string: String) -> Bool {
return firstMatchInString(string) != nil
}
}
extension URL {
var isDirectory: Bool? {
let values = try? self.resourceValues(forKeys: [.isDirectoryKey])
return values?.isDirectory
}
var isRegularFile: Bool? {
let values = try? self.resourceValues(forKeys: [.isRegularFileKey])
return values?.isRegularFile
}
}
extension HTTPURLResponse {
var isSuccessful: Bool {
return (200..<300).contains(statusCode)
}
}
|
c396d5aec3cbdcb93284430d1c2260f7
| 28.85 | 101 | 0.704634 | false | false | false | false |
csontosgabor/Twitter_Post
|
refs/heads/master
|
Twitter_Post/ModalAnimatorPhoto.swift
|
mit
|
1
|
//
// ModalAnimatorPhoto.swift
// Transition
//
// Created by Gabor Csontos on 12/22/16.
// Copyright © 2016 GaborMajorszki. All rights reserved.
//
import UIKit
public class ModalAnimatorPhoto {
public class func present(_ toView: UIView, fromView: UIView, completion: @escaping () -> Void) {
let statusBarHeight = UIApplication.shared.statusBarFrame.height
var toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: statusBarHeight + fromView.bounds.size.height)
toViewFrame.size.height = toViewFrame.size.height
toView.frame = toViewFrame
toView.alpha = 0.0
fromView.addSubview(toView)
UIView.animate(
withDuration: 0.2,
animations: { () -> Void in
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: statusBarHeight + fromView.bounds.size.height / 2.0 + 4)
toView.frame = toViewFrame
toView.alpha = 1.0
}) { (result) -> Void in
completion()
}
}
public class func dismiss(_ toView: UIView, fromView: UIView, completion: @escaping () -> Void) {
//Checking PhotoAutorizationStatus
if PhotoAutorizationStatusCheck() {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: statusBarHeight + fromView.bounds.size.height / 2.0 + 4)
toView.frame = toViewFrame
}) { (result) -> Void in
completion()
}
} else {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: fromView.bounds.size.height - 44)
toView.frame = toViewFrame
}) { (result) -> Void in
completion()
}
}
}
public class func dismissOnBottom(_ toView: UIView, fromView: UIView, completion: @escaping () -> Void) {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: fromView.bounds.size.height - 44)
toView.frame = toViewFrame
}) { (result) -> Void in
completion()
}
}
public class func showOnfullScreen(_ toView: UIView, fromView: UIView, completion: @escaping () -> Void) {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: statusBarHeight)
toView.frame = toViewFrame
}) { (result) -> Void in
completion()
}
}
}
|
0d3fc072ea90840cd59420e323e50709
| 29.008929 | 126 | 0.51205 | false | false | false | false |
bsmith11/ScoreReporter
|
refs/heads/master
|
ScoreReporterCore/ScoreReporterCore/Extensions/String+Extensions.swift
|
mit
|
1
|
//
// String+Extensions.swift
// ScoreReporter
//
// Created by Bradley Smith on 7/19/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import Foundation
public extension String {
func matching(regexPattern: String) -> String? {
var strings = [String]()
do {
let regex = try NSRegularExpression(pattern: regexPattern, options: .caseInsensitive)
let options: NSRegularExpression.MatchingOptions = .reportProgress
let range = NSRange(location: 0, length: (self as NSString).length)
regex.enumerateMatches(in: self, options: options, range: range) { (result: NSTextCheckingResult?, _, _) in
if let result = result {
let match = (self as NSString).substring(with: result.range)
strings.append(match)
}
}
return strings.first
}
catch let error {
print("Failed to create regular expression with pattern: \(regexPattern) error: \(error)")
return nil
}
}
}
|
57c280d2324c5c77df216d84a141e707
| 30 | 119 | 0.589862 | false | false | false | false |
lfaoro/Cast
|
refs/heads/master
|
Cast/MenuSendersAction.swift
|
mit
|
1
|
//
// Created by Leonardo on 18/07/2015.
// Copyright © 2015 Leonardo Faoro. All rights reserved.
//
import Cocoa
import RxSwift
final class MenuSendersAction: NSObject {
let shortenClient = ShortenClient()
func shareClipboardContentsAction(sender: NSMenuItem) {
let _ = PasteboardClient.getPasteboardItems()
.debug("getPasteboardItems")
.subscribe(next: { value in
switch value {
case .Text(let item):
app.gistClient.setGist(content: item, isPublic: app.prefs.gistIsPublic!)
.debug("setGist")
.retry(3)
.flatMap { self.shortenClient.shorten(URL: $0) }
.subscribe { event in
switch event {
case .Next(let URL):
if let URL = URL {
PasteboardClient.putInPasteboard(items: [URL])
app.userNotification.pushNotification(openURL: URL)
} else {
app.userNotification.pushNotification(error: "Unable to Shorten URL")
}
case .Completed:
app.statusBarItem.menu = createMenu(self)
case .Error(let error):
app.userNotification.pushNotification(error: String(error))
}
}
case .File(let file):
print(file.path!)
default: break
}
})
}
func updateGistAction(sender: NSMenuItem) {
let _ = PasteboardClient.getPasteboardItems()
.debug("getPasteboardItems")
.subscribe(next: { value in
switch value {
case .Text(let item):
app.gistClient.setGist(content: item,
updateGist: true,
isPublic: app.prefs.gistIsPublic!)
.debug("setGist")
.retry(3)
.flatMap { self.shortenClient.shorten(URL: $0) }
.subscribe { event in
switch event {
case .Next(let URL):
if let URL = URL {
PasteboardClient.putInPasteboard(items: [URL])
app.userNotification.pushNotification(openURL: URL)
} else {
app.userNotification.pushNotification(error: "Unable to Shorten URL")
}
case .Completed:
app.statusBarItem.menu = createMenu(self)
case .Error(let error):
app.userNotification.pushNotification(error: String(error))
}
}
case .File(let file):
print(file.path!)
default: break
}
})
}
func shortenURLAction(sender: NSMenuItem) {
let _ = PasteboardClient.getPasteboardItems()
.debug("getPasteboardItems")
.subscribe(next: { value in
switch value {
case .Text(let item):
guard let url = NSURL(string: item) else { fallthrough }
self.shortenClient.shorten(URL: url)
.subscribe { event in
switch event {
case .Next(let shortenedURL):
guard let URL = shortenedURL else { fallthrough }
PasteboardClient.putInPasteboard(items: [URL])
app.userNotification.pushNotification(openURL: URL,
title: "Shortened with \(app.prefs.shortenService!)")
case .Completed:
print("completed")
case .Error(let error):
print("\(error)")
}
}
default:
app.userNotification.pushNotification(error: "Not a valid URL")
}
})
}
func loginToGithub(sender: NSMenuItem) {
app.oauth.authorize()
}
func logoutFromGithub(sender: NSMenuItem) {
if let error = OAuthClient.revoke() {
app.userNotification.pushNotification(error: error.localizedDescription)
} else {
app.statusBarItem.menu = createMenu(app.menuSendersAction)
app.userNotification.pushNotification(error: "GitHub Authentication",
description: "API key revoked internally")
}
}
func recentUploadsAction(sender: NSMenuItem) {
if let url = sender.representedObject as? NSURL {
NSWorkspace.sharedWorkspace().openURL(url)
} else {
fatalError("No link in recent uploads")
}
}
func clearItemsAction(sender: NSMenuItem) {
if app.prefs.recentActions!.count > 0 {
app.prefs.recentActions!.removeAll()
Swift.print(app.prefs.recentActions!)
app.statusBarItem.menu = createMenu(app.menuSendersAction)
}
}
func startAtLoginAction(sender: NSMenuItem) {
if sender.state == 0 {
sender.state = 1
} else {
sender.state = 0
}
}
func optionsAction(sender: NSMenuItem) {
NSApp.activateIgnoringOtherApps(true)
app.optionsWindowController.showWindow(nil)
}
}
|
94f6f96b8325131a14d44ced949d8dbe
| 23.410405 | 78 | 0.656405 | false | false | false | false |
BBBInc/AlzPrevent-ios
|
refs/heads/master
|
researchline/LoginViewController.swift
|
bsd-3-clause
|
1
|
//
// LoginViewController.swift
// researchline
//
// Created by riverleo on 2015. 11. 8..
// Copyright © 2015년 bbb. All rights reserved.
//
import UIKit
import Alamofire
class LoginViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var doneBarButtonItem: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBarHidden = false
}
// MARK: IBAction Methods
@IBAction func editChangedTextField(sender: UITextField) {
doneBarButtonItem.enabled = !emailTextField.text!.isEmpty && !passwordTextField.text!.isEmpty
}
@IBAction func passwordChanged(sender: AnyObject) {
doneBarButtonItem.enabled = !emailTextField.text!.isEmpty && !passwordTextField.text!.isEmpty
}
@IBAction func touchUpInsideDoneBarButtonItem(sender: UIBarButtonItem) {
sender.enabled = false
Alamofire.request(.POST, Constants.login,
parameters: [
"email": emailTextField.text ?? "",
"password": passwordTextField.text ?? ""
],
headers: [
"deviceKey": Constants.deviceKey,
"deviceType": Constants.deviceType
])
.responseJSON { (response: Response) -> Void in
debugPrint(response)
sender.enabled = true
switch response.result {
case .Success:
switch response.response!.statusCode {
case 200:
// save the sign key
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(response.result.value!["signKey"]!, forKey: "signKey")
userDefaults.setObject(self.emailTextField.text, forKey: "email")
Constants.userDefaults.setObject(Constants.STEP_FINISHED, forKey: "registerStep")
// shows tab bar
let storyboard = UIStoryboard(name: "TabBar", bundle: nil)
let controller = storyboard.instantiateInitialViewController()!
self.presentViewController(controller, animated: true, completion: nil)
break
default:
let alertView = UIAlertView(title: nil, message: response.result.value!["message"] as? String, delegate: nil, cancelButtonTitle: "Okay")
alertView.show()
break
}
break
case .Failure:
let alertView = UIAlertView(title: "Server Error", message: nil, delegate: nil, cancelButtonTitle: "Okay")
alertView.show()
break
}
}
}
}
|
244d4b506935abd56288f152c5a2e4de
| 37.556962 | 160 | 0.552709 | false | false | false | false |
hanwanjie853710069/iMessageTest
|
refs/heads/master
|
SmilLoveTwo/MessagesExtension/MessagesViewController.swift
|
apache-2.0
|
1
|
//
// MessagesViewController.swift
// MessagesExtension
//
// Created by Mr.H on 2017/7/31.
// Copyright © 2017年 Mr.H. All rights reserved.
//
import UIKit
import Messages
class MessagesViewController: MSMessagesAppViewController {
override func viewDidLoad() {
super.viewDidLoad()
creatMessageBtn()
}
/// 创建
func creatMessageBtn() {
let creatBtn = UIButton(frame: CGRect(x: 100, y: 30, width: 200, height: 200))
creatBtn.addTarget(self, action: #selector(touchBtn), for: .touchUpInside)
creatBtn.backgroundColor = UIColor.brown
creatBtn.setTitle("创建Message按钮", for: .normal)
view.addSubview(creatBtn)
}
/// 创建表情点击事件
func touchBtn() {
if let image = creatImage(), let conversation = activeConversation {
let layout = MSMessageTemplateLayout()
layout.image = image
layout.caption = "Stepper Value"
layout.subcaption = "subcaption"
layout.trailingCaption = "trailingCaption"
layout.trailingSubcaption = "trailingSubcaption"
let message = MSMessage()
message.layout = layout
message.url = URL(string: "emptyURL")
conversation.insert(message, completionHandler: { (error: NSError?) in
} as? (Error?) -> Void)
}
}
func creatImage() -> UIImage? {
let background = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
background.backgroundColor = UIColor.red
let label = UILabel(frame: CGRect(x: 75, y: 75, width: 150, height: 150))
label.font = UIFont.systemFont(ofSize: 56.0)
label.backgroundColor = UIColor.brown
label.textColor = UIColor.white
label.text = "Message"
label.textAlignment = .center
label.layer.cornerRadius = label.frame.size.width/2.0
label.clipsToBounds = true
background.addSubview(label)
background.frame.origin = CGPoint(x: view.frame.size.width, y: view.frame.size.height)
view.addSubview(background)
UIGraphicsBeginImageContextWithOptions(background.frame.size, false, UIScreen.main.scale)
background.drawHierarchy(in: background.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
background.removeFromSuperview()
return image
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Conversation Handling
override func willBecomeActive(with conversation: MSConversation) {
// Called when the extension is about to move from the inactive to active state.
// This will happen when the extension is about to present UI.
// Use this method to configure the extension and restore previously stored state.
}
override func didResignActive(with conversation: MSConversation) {
// Called when the extension is about to move from the active to inactive state.
// This will happen when the user dissmises the extension, changes to a different
// conversation or quits Messages.
// Use this method to release shared resources, save user data, invalidate timers,
// and store enough state information to restore your extension to its current state
// in case it is terminated later.
}
override func didReceive(_ message: MSMessage, conversation: MSConversation) {
// Called when a message arrives that was generated by another instance of this
// extension on a remote device.
// Use this method to trigger UI updates in response to the message.
}
override func didStartSending(_ message: MSMessage, conversation: MSConversation) {
// Called when the user taps the send button.
}
override func didCancelSending(_ message: MSMessage, conversation: MSConversation) {
// Called when the user deletes the message without sending it.
// Use this to clean up state related to the deleted message.
}
override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
// Called before the extension transitions to a new presentation style.
// Use this method to prepare for the change in presentation style.
}
override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
// Called after the extension transitions to a new presentation style.
// Use this method to finalize any behaviors associated with the change in presentation style.
}
}
|
db358add7f4ca83d619257a6c5bc9035
| 34.21831 | 102 | 0.633473 | false | false | false | false |
GuiminChu/HishowZone-iOS
|
refs/heads/master
|
HiShow/Features/Topics/TopicModel.swift
|
mit
|
1
|
//
// TopicModel.swift
// HiShow
//
// Created by Chu Guimin on 16/9/6.
// Copyright © 2016年 Chu Guimin. All rights reserved.
//
import Foundation
import SwiftyJSON
enum RefreshStatus {
case none
case pullSucess(hasMoreData: Bool)
case loadSucess(hasMoreData: Bool)
case error(message: String?)
}
let activityInfoStoreDidChangedNotification = "com.mst.MyRunning.ActivityInfoStoreDidChangedNotification"
class TopicItemStore {
static let shared = TopicItemStore()
private var topics = [Topic]()
private init() {}
private var refreshStatus = RefreshStatus.none {
didSet {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: activityInfoStoreDidChangedNotification), object: self, userInfo: [activityInfoStoreDidChangedNotification: refreshStatus])
}
}
var count: Int {
return topics.count
}
var start = 0 {
didSet {
request(start: start)
}
}
func topic(at index: Int) -> Topic {
return topics[index]
}
func request(start: Int) {
HiShowAPI.sharedInstance.getTopics(start: start, completion: { topicModel in
let hasMoreData = topicModel.topics.count < 20
if start == 0 {
self.topics = topicModel.topics
self.refreshStatus = RefreshStatus.pullSucess(hasMoreData: hasMoreData)
} else {
self.topics += topicModel.topics
self.refreshStatus = RefreshStatus.loadSucess(hasMoreData: hasMoreData)
}
}, failureHandler: { (reason, errorMessage) in
self.refreshStatus = RefreshStatus.error(message: errorMessage)
})
}
}
struct TopicModel {
var count: Int!
var start: Int!
var topics: [Topic]!
var total: Int!
init(fromJson json: JSON) {
if json == JSON.null {
return
}
count = json["count"].intValue
start = json["start"].intValue
total = json["total"].intValue
topics = [Topic]()
let topicsArray = json["topics"].arrayValue
for topicsJson in topicsArray {
let value = Topic(fromJson: topicsJson)
// 只展现有照片的话题
if value.photos.count > 0 {
// 过滤掉某些没有营养的广告贴
if value.id != "97583616" && value.id != "79786668" && value.id != "96555462" && value.id != "95243968" && value.id != "91716032" {
topics.append(value)
}
}
}
}
}
struct Topic {
var id: String!
var alt: String!
var author: Author!
var commentsCount: Int!
var content: String!
var created: String!
var likeCount: Int!
var photos: [Photo]!
var title: String!
var updated: String!
init(fromJson json: JSON) {
if json == JSON.null {
return
}
id = json["id"].stringValue
alt = json["alt"].stringValue
title = json["title"].stringValue
content = json["content"].stringValue
created = json["created"].stringValue
updated = json["updated"].stringValue
likeCount = json["like_count"].intValue
commentsCount = json["comments_count"].intValue
let authorJson = json["author"]
if authorJson != JSON.null {
author = Author(fromJson: authorJson)
}
photos = [Photo]()
let photosArray = json["photos"].arrayValue
for photosJson in photosArray {
let value = Photo(fromJson: photosJson)
photos.append(value)
}
}
}
struct Photo {
var id: String?
var alt: String?
var authorId: String?
var creationDate: String?
var seqId: String?
var title: String?
var topicId: String?
var size: PhotoSize!
init(fromJson json: JSON) {
if json == JSON.null {
return
}
id = json["id"].stringValue
alt = json["alt"].stringValue
seqId = json["seq_id"].stringValue
title = json["title"].stringValue
topicId = json["topic_id"].stringValue
authorId = json["author_id"].stringValue
creationDate = json["creation_date"].stringValue
let sizeJson = json["size"]
if !sizeJson.isEmpty {
size = PhotoSize(fromJson: sizeJson)
}
}
}
struct PhotoSize {
var height: Int = 1
var width: Int = 1
init(fromJson json: JSON) {
if json.isEmpty {
return
}
height = json["height"].intValue
width = json["width"].intValue
}
}
/**
* 作者
*/
struct Author {
var id: String?
var avatar: String?
var largeAvatar: String?
var isSuicide: Bool?
/// 主页地址
var alt: String?
/// 昵称
var name: String?
init(fromJson json: JSON) {
if json == JSON.null {
return
}
id = json["id"].stringValue
alt = json["alt"].stringValue
name = json["name"].stringValue
avatar = json["avatar"].stringValue
isSuicide = json["is_suicide"].boolValue
largeAvatar = json["large_avatar"].stringValue
}
}
|
af30122bb2ff77d243a302512fb979c1
| 24.990476 | 203 | 0.546354 | false | false | false | false |
nodes-ios/NStackSDK
|
refs/heads/master
|
LocalizationsGenerator/Classes/Other/HTTPMethod.swift
|
mit
|
2
|
//
// HTTPMethod.swift
// NStackSDK
//
// Created by Dominik Hadl on 25/09/2018.
// Copyright © 2018 Nodes ApS. All rights reserved.
//
import Foundation
public enum HTTPMethod: String {
case get = "GET"
case patch = "PATCH"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
|
329d1e303e6e65bdcf1c26c776ca8f09
| 17.352941 | 52 | 0.628205 | false | false | false | false |
Feyluu/DouYuZB
|
refs/heads/master
|
DouYuZB/DouYuZB/Classes/Tools/NetworkTools.swift
|
mit
|
1
|
//
// NetworkTools.swift
// AlamofireDemo
//
// Created by DuLu on 19/06/2017.
// Copyright © 2017 DuLu. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case GET
case POST
}
class NetworkTools {
class func requestData(type:MethodType, URLString:String,parameters:[String:String]?=nil,finishedCallback : @escaping (_ result:AnyObject) -> ()) {
// 获取type类型
let method = type == .GET ? HTTPMethod.get : HTTPMethod.post
Alamofire.request(URLString, method: method, parameters: parameters, encoding:URLEncoding.default , headers: nil).responseJSON { (response) in
guard let result = response.result.value else {
print(response.result.error!)
return
}
// 回调结果
finishedCallback(result as AnyObject)
}
}
}
|
36849d0c69b3bd1163c0cb0fc2297031
| 26.46875 | 151 | 0.61661 | false | false | false | false |
Killectro/RxGrailed
|
refs/heads/master
|
RxGrailed/RxGrailedTests/ViewModels/ListingsViewModelSpec.swift
|
mit
|
1
|
//
// ListingsViewModelSpec.swift
// RxGrailed
//
// Created by DJ Mitchell on 2/28/17.
// Copyright © 2017 Killectro. All rights reserved.
//
import Foundation
import Quick
import Nimble
import Mapper
import RxSwift
@testable
import RxGrailed
func testListingJSON() -> [String : Any] {
return [
"id" : 12345,
"retina_cover_photo" : [
"url" : "https://static.highsnobiety.com/wp-content/uploads/2016/10/02112116/cost-of-house-with-supreme-bricks-0.jpg"
],
"price_i" : 300,
"designer_names" : "Supreme",
"title" : "Supreme Brick",
"description" : "Literally just a brick",
"size" : "one size",
"user" : [
"username" : "not_YMBAPE"
]
]
}
class ListingsViewModelSpec: QuickSpec {
override func spec() {
var viewModel: ListingsViewModel!
var paginate: PublishSubject<Void>!
var disposeBag: DisposeBag!
beforeEach {
viewModel = ListingsViewModel(networkModel: MockGrailedNetworkModel())
paginate = PublishSubject()
disposeBag = DisposeBag()
}
it("loads a first page") {
viewModel.setupObservables(paginate: paginate.asObservable())
waitUntil { done in
viewModel.listings
.subscribe(onNext: { listings in
expect(listings).toNot(beEmpty())
expect(listings.count) == 5
done()
})
.disposed(by: disposeBag)
}
}
it("loads a second page when pagination occurs") {
viewModel.setupObservables(paginate: paginate.asObservable())
waitUntil { done in
viewModel.listings
.mapWithIndex { ($0, $1) }
.subscribe(onNext: { listings, index in
expect(listings).toNot(beEmpty())
expect(listings.count) == 5 * (index + 1)
if index == 1 {
done()
}
})
.disposed(by: disposeBag)
paginate.onNext(())
}
}
}
}
private class MockGrailedNetworkModel: GrailedNetworkModelable {
fileprivate func getListings(paginate: Observable<Void>, loadedSoFar: [Listing]) -> Observable<[Listing]> {
let listings = (0..<5).map { _ in
try! Listing(
map: Mapper(JSON: testListingJSON() as NSDictionary)
)
}
return Observable.of(listings).flatMap { listings -> Observable<[Listing]> in
let newListings = loadedSoFar + listings
let obs = [
// Return our current list of Listings
Observable.just(newListings),
// Wait until we are told to paginate
Observable.never().takeUntil(paginate),
// Retrieve the next list of listings
self.getListings(paginate: paginate, loadedSoFar: newListings)
]
return Observable.concat(obs)
}
}
}
|
7d502f10d25de39a552575ae94bbb0e7
| 28.495413 | 129 | 0.523173 | false | false | false | false |
nicadre/SwiftyProtein
|
refs/heads/master
|
SwiftyProtein/Controllers/PopOverViewController.swift
|
gpl-3.0
|
1
|
//
// PopOverController.swift
// SwiftyProtein
//
// Created by Leo LAPILLONNE on 7/20/16.
// Copyright © 2016 Nicolas CHEVALIER. All rights reserved.
//
import UIKit
class PopOverViewController: UIViewController {
@IBOutlet weak var chemicalIdLabel: UILabel!
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var weightLabel: UILabel!
@IBOutlet weak var chemicalNameLabel: UILabel!
@IBOutlet weak var formulaLabel: UILabel!
var chemicalId: String = ""
var type: String = ""
var weight: String = ""
var chemicalName: String = ""
var formula: String = ""
override func viewDidLoad() {
super.viewDidLoad()
self.chemicalIdLabel.text = "\(chemicalId)"
self.typeLabel.text = "\(type)"
self.weightLabel.text = "\(weight)"
self.chemicalNameLabel.text = "\(chemicalName)"
self.formulaLabel.text = "\(formula)"
}
}
|
eb832fe4d6fef47cea0066d6864cacdd
| 25.277778 | 60 | 0.637421 | false | false | false | false |
edx/edx-app-ios
|
refs/heads/master
|
Source/AuthenticatedWebViewController.swift
|
apache-2.0
|
1
|
//
// AuthenticatedWebViewController.swift
// edX
//
// Created by Akiva Leffert on 5/26/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
import WebKit
class HeaderViewInsets : ContentInsetsSource {
weak var insetsDelegate : ContentInsetsSourceDelegate?
var view : UIView?
var currentInsets : UIEdgeInsets {
return UIEdgeInsets(top : view?.frame.size.height ?? 0, left : 0, bottom : 0, right : 0)
}
var affectsScrollIndicators : Bool {
return true
}
}
private protocol WebContentController {
var view : UIView {get}
var scrollView : UIScrollView {get}
var isLoading: Bool {get}
var alwaysRequiresOAuthUpdate : Bool { get}
var initialContentState : AuthenticatedWebViewController.State { get }
func loadURLRequest(request : NSURLRequest)
func resetState()
}
@objc protocol WebViewNavigationDelegate: AnyObject {
func webView(_ webView: WKWebView, shouldLoad request: URLRequest) -> Bool
func webViewContainingController() -> UIViewController
}
// A class should implement AlwaysRequireAuthenticationOverriding protocol if it always require authentication.
protocol AuthenticatedWebViewControllerRequireAuthentication {
func alwaysRequireAuth() -> Bool
}
protocol AuthenticatedWebViewControllerDelegate: AnyObject {
func authenticatedWebViewController(authenticatedController: AuthenticatedWebViewController, didFinishLoading webview: WKWebView)
}
@objc protocol AJAXCompletionCallbackDelegate: AnyObject {
func didCompletionCalled(completion: Bool)
}
protocol WebViewNavigationResponseDelegate: AnyObject {
func handleHttpStatusCode(statusCode: OEXHTTPStatusCode) -> Bool
}
private class WKWebViewContentController : WebContentController {
fileprivate let webView: WKWebView
var view : UIView {
return webView
}
var scrollView : UIScrollView {
return webView.scrollView
}
init(configuration: WKWebViewConfiguration) {
webView = WKWebView(frame: .zero, configuration: configuration)
}
func loadURLRequest(request: NSURLRequest) {
webView.load(request as URLRequest)
}
func resetState() {
webView.stopLoading()
webView.loadHTMLString("", baseURL: nil)
}
var alwaysRequiresOAuthUpdate : Bool {
return false
}
var initialContentState : AuthenticatedWebViewController.State {
return AuthenticatedWebViewController.State.LoadingContent
}
var isLoading: Bool {
return webView.isLoading
}
}
private let OAuthExchangePath = "/oauth2/login/"
fileprivate let AJAXCallBackHandler = "ajaxCallbackHandler"
fileprivate let ajaxScriptFile = "ajaxHandler"
// Allows access to course content that requires authentication.
// Forwarding our oauth token to the server so we can get a web based cookie
public class AuthenticatedWebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler {
fileprivate enum xBlockCompletionCallbackType: String {
case html = "publish_completion"
case problem = "problem_check"
case dragAndDrop = "do_attempt"
case ora = "render_grade"
}
fileprivate enum State {
case CreatingSession
case LoadingContent
case NeedingSession
}
public typealias Environment = OEXAnalyticsProvider & OEXConfigProvider & OEXSessionProvider & ReachabilityProvider
weak var delegate: AuthenticatedWebViewControllerDelegate?
internal let environment : Environment
private let loadController : LoadStateViewController
private let insetsController : ContentInsetsController
private let headerInsets : HeaderViewInsets
weak var webViewDelegate: WebViewNavigationDelegate?
weak var ajaxCallbackDelegate: AJAXCompletionCallbackDelegate?
weak var webViewNavigationResponseDelegate: WebViewNavigationResponseDelegate?
private lazy var configurations = environment.config.webViewConfiguration()
private var shouldListenForAjaxCallbacks = false
private lazy var webController: WebContentController = {
let controller = WKWebViewContentController(configuration: configurations)
if shouldListenForAjaxCallbacks {
addAjaxCallbackScript(in: configurations.userContentController)
}
controller.webView.navigationDelegate = self
controller.webView.uiDelegate = self
return controller
}()
var scrollView: UIScrollView {
return webController.scrollView
}
private var state = State.CreatingSession
private var contentRequest : NSURLRequest? = nil
var currentUrl: NSURL? {
return contentRequest?.url as NSURL?
}
public func setLoadControllerState(withState state: LoadState) {
loadController.state = state
}
public init(environment : Environment, shouldListenForAjaxCallbacks: Bool = false) {
self.environment = environment
self.shouldListenForAjaxCallbacks = shouldListenForAjaxCallbacks
loadController = LoadStateViewController()
insetsController = ContentInsetsController()
headerInsets = HeaderViewInsets()
insetsController.addSource(source: headerInsets)
super.init(nibName: nil, bundle: nil)
scrollView.contentInsetAdjustmentBehavior = .automatic
webController.view.accessibilityIdentifier = "AuthenticatedWebViewController:authenticated-web-view"
addObservers()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
// Prevent crash due to stale back pointer, since WKWebView's UIScrollView apparently doesn't
// use weak for its delegate
webController.scrollView.delegate = nil
NotificationCenter.default.removeObserver(self)
}
override public func viewDidLoad() {
super.viewDidLoad()
state = webController.initialContentState
view.addSubview(webController.view)
webController.view.snp.makeConstraints { make in
make.edges.equalTo(safeEdges)
}
loadController.setupInController(controller: self, contentView: webController.view)
webController.view.backgroundColor = OEXStyles.shared().standardBackgroundColor()
webController.scrollView.backgroundColor = OEXStyles.shared().standardBackgroundColor()
insetsController.setupInController(owner: self, scrollView: webController.scrollView)
if let request = contentRequest {
loadRequest(request: request)
}
}
private func addObservers() {
NotificationCenter.default.oex_addObserver(observer: self, name: NOTIFICATION_DYNAMIC_TEXT_TYPE_UPDATE) { (_, observer, _) in
observer.reload()
}
}
private func addAjaxCallbackScript(in contentController: WKUserContentController) {
guard let url = Bundle.main.url(forResource: ajaxScriptFile, withExtension: "js"),
let handler = try? String(contentsOf: url, encoding: .utf8) else { return }
let script = WKUserScript(source: handler, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
contentController.add(self, name: AJAXCallBackHandler)
contentController.addUserScript(script)
}
public func reload() {
guard let request = contentRequest, !webController.isLoading else { return }
state = .LoadingContent
loadRequest(request: request)
}
private func resetState() {
loadController.state = .Initial
state = .CreatingSession
}
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
if view.window == nil {
webController.resetState()
}
resetState()
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if headerView != nil {
insetsController.updateInsets()
}
}
public func showError(error : NSError?, icon : Icon? = nil, message : String? = nil) {
let buttonInfo = MessageButtonInfo(title: Strings.reload) {[weak self] in
if let request = self?.contentRequest, self?.environment.reachability.isReachable() ?? false {
self?.loadController.state = .Initial
self?.webController.loadURLRequest(request: request)
}
}
loadController.state = LoadState.failed(error: error, icon: icon, message: message, buttonInfo: buttonInfo)
refreshAccessibility()
}
public func showError(with state: LoadState) {
loadController.state = state
refreshAccessibility()
}
// MARK: Header View
var headerView : UIView? {
get {
return headerInsets.view
}
set {
headerInsets.view?.removeFromSuperview()
headerInsets.view = newValue
if let headerView = newValue {
webController.view.addSubview(headerView)
headerView.snp.makeConstraints { make in
make.top.equalTo(safeTop)
make.leading.equalTo(webController.view)
make.trailing.equalTo(webController.view)
}
webController.view.setNeedsLayout()
webController.view.layoutIfNeeded()
}
}
}
private func loadOAuthRefreshRequest() {
if let hostURL = environment.config.apiHostURL() {
let URL = hostURL.appendingPathComponent(OAuthExchangePath)
let exchangeRequest = NSMutableURLRequest(url: URL)
exchangeRequest.httpMethod = HTTPMethod.POST.rawValue
for (key, value) in self.environment.session.authorizationHeaders {
exchangeRequest.addValue(value, forHTTPHeaderField: key)
}
self.webController.loadURLRequest(request: exchangeRequest)
}
}
private func refreshAccessibility() {
DispatchQueue.main.async {
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: nil)
}
}
// MARK: Request Loading
public func loadRequest(request : NSURLRequest) {
contentRequest = request
loadController.state = .Initial
state = webController.initialContentState
var isAuthRequestRequired = webController.alwaysRequiresOAuthUpdate
if let parent = parent as? AuthenticatedWebViewControllerRequireAuthentication {
isAuthRequestRequired = parent.alwaysRequireAuth()
}
if isAuthRequestRequired {
state = State.CreatingSession
loadOAuthRefreshRequest()
}
else {
webController.loadURLRequest(request: request)
}
}
// MARK: WKWebView delegate
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let isWebViewDelegateHandled = !(webViewDelegate?.webView(webView, shouldLoad: navigationAction.request) ?? true)
if isWebViewDelegateHandled {
decisionHandler(.cancel)
} else {
switch navigationAction.navigationType {
case .linkActivated:
if let url = navigationAction.request.url, UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
decisionHandler(.cancel)
default:
decisionHandler(.allow)
}
}
}
public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if let httpResponse = navigationResponse.response as? HTTPURLResponse, let statusCode = OEXHTTPStatusCode(rawValue: httpResponse.statusCode), let errorGroup = statusCode.errorGroup, state == .LoadingContent {
if webViewNavigationResponseDelegate?.handleHttpStatusCode(statusCode: statusCode) ?? false {
decisionHandler(.cancel)
return
}
switch errorGroup {
case .http4xx:
state = .NeedingSession
break
case .http5xx:
loadController.state = LoadState.failed()
decisionHandler(.cancel)
return
}
}
decisionHandler(.allow)
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
switch state {
case .CreatingSession:
if let request = contentRequest {
state = .LoadingContent
webController.loadURLRequest(request: request)
}
else {
loadController.state = LoadState.failed()
}
case .LoadingContent:
//The class which will implement this protocol method will be responsible to set the loadController state as Loaded
if delegate?.authenticatedWebViewController(authenticatedController: self, didFinishLoading: webView) == nil {
loadController.state = .Loaded
}
case .NeedingSession:
state = .CreatingSession
loadOAuthRefreshRequest()
}
refreshAccessibility()
}
/* Completion callbacks in case of different xBlocks
HTML /publish_completion
Video /publish_completion
Problem problem_check
DragAndDrop handler/do_attempt
ORABlock responseText contains class 'is--complete'
*/
private func isCompletionCallback(with data: Dictionary<AnyHashable, Any>) -> Bool {
let callback = AJAXCallbackData(data: data)
let requestURL = callback.url
if callback.statusCode != OEXHTTPStatusCode.code200OK.rawValue {
return false
}
if isBlockOf(type: .ora, with: requestURL) {
return callback.responseText.contains("is--complete")
} else {
return isBlockOf(type: .html, with: requestURL)
|| isBlockOf(type: .problem, with: requestURL)
|| isBlockOf(type: .dragAndDrop, with: requestURL)
}
}
private func isBlockOf(type: xBlockCompletionCallbackType, with requestURL: String) -> Bool {
return requestURL.contains(type.rawValue)
}
public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == AJAXCallBackHandler {
guard let data = message.body as? Dictionary<AnyHashable, Any> else { return }
if isCompletionCallback(with: data) {
ajaxCallbackDelegate?.didCompletionCalled(completion: true)
}
}
}
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
showError(error: error as NSError?)
}
public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
guard !loadController.state.isError else { return }
showError(error: error as NSError?)
}
public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// Don't use basic auth on exchange endpoint. That is explicitly non protected
// and it screws up the authorization headers
if let URL = webView.url, ((URL.absoluteString.hasSuffix(OAuthExchangePath)) != false) {
completionHandler(.performDefaultHandling, nil)
}
else if let credential = environment.config.URLCredentialForHost(challenge.protectionSpace.host as NSString) {
completionHandler(.useCredential, credential)
}
else {
completionHandler(.performDefaultHandling, nil)
}
}
public func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: Strings.ok, style: .default, handler: { action in
completionHandler(true)
}))
alertController.addAction(UIAlertAction(title: Strings.cancel, style: .cancel, handler: { action in
completionHandler(false)
}))
if let presenter = alertController.popoverPresentationController {
presenter.sourceView = view
presenter.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
}
if isViewVisible {
present(alertController, animated: true, completion: nil)
} else {
completionHandler(false)
}
}
}
private struct AJAXCallbackData {
private enum Keys: String {
case url = "url"
case statusCode = "status"
case responseText = "response_text"
}
let url: String
let statusCode: Int
let responseText: String
init(data: Dictionary<AnyHashable, Any>) {
url = data[Keys.url.rawValue] as? String ?? ""
statusCode = data[Keys.statusCode.rawValue] as? Int ?? 0
responseText = data[Keys.responseText.rawValue] as? String ?? ""
}
}
|
27264ff2cc8d70f9cadf50a2eaf71b69
| 35.627291 | 216 | 0.659753 | false | false | false | false |
adjusting/MemeMe
|
refs/heads/master
|
MemeMe/MemeEditorVC.swift
|
mit
|
1
|
//
// ViewController.swift
// MemeMe
//
// Created by Justin Gareau on 6/3/17.
// Copyright © 2017 Justin Gareau. All rights reserved.
//
import UIKit
class MemeEditorVC: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var cameraButton: UIBarButtonItem!
@IBOutlet weak var shareButton: UIBarButtonItem!
@IBOutlet weak var topTextField: UITextField!
@IBOutlet weak var bottomTextField: UITextField!
@IBOutlet weak var navbar: UIToolbar!
@IBOutlet weak var toolbar: UIToolbar!
let topDelegate = TopTextFieldDelegate()
let bottomDelegate = BottomTextFieldDelegate()
let memeTextAttributes:[String:Any] = [
NSStrokeColorAttributeName: UIColor.black,
NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName: -5]
override func viewDidLoad() {
super.viewDidLoad()
setupTextfield(topTextField, with: "TOP")
topTextField.delegate = topDelegate
setupTextfield(bottomTextField, with: "BOTTOM")
bottomTextField.delegate = bottomDelegate
shareButton.isEnabled = false
}
func setupTextfield(_ textField: UITextField, with text:String) {
textField.defaultTextAttributes = memeTextAttributes
textField.text = text
textField.textAlignment = .center
}
override func viewWillAppear(_ animated: Bool) {
cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
subscribeToKeyboardNotifications()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
override var prefersStatusBarHidden: Bool { return true }
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
@IBAction func pickAnImageFromAlbum(_ sender: Any) {
pickAnImage(sourceType:.photoLibrary)
}
@IBAction func pickAnImageFromCamera(_ sender: Any) {
pickAnImage(sourceType:.camera)
}
func pickAnImage(sourceType: UIImagePickerControllerSourceType) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = sourceType
present(imagePicker, animated: true, completion: nil)
}
@IBAction func shareMeme(_ sender: Any) {
let controller = UIActivityViewController(activityItems: [generateMemedImage()], applicationActivities: nil)
present(controller, animated: true, completion: {self.save()})
controller.completionWithItemsHandler = { (activityType: UIActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) -> Void in
if completed == true {
self.dismiss(animated: true, completion: nil)
}
}
}
@IBAction func cancel(_ sender: Any) {
imageView.image = nil
topTextField.text = "TOP"
bottomTextField.text = "BOTTOM"
shareButton.isEnabled = false
dismiss(animated: true, completion: nil)
}
func keyboardWillShow(_ notification:Notification) {
if bottomTextField.isEditing {
view.frame.origin.y = -getKeyboardHeight(notification)
}
}
func keyboardWillHide(_ notification:Notification) {
if bottomTextField.isEditing {
view.frame.origin.y = 0
}
}
func getKeyboardHeight(_ notification:Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect
return keyboardSize.cgRectValue.height
}
func generateMemedImage() -> UIImage {
hideToolbars(true)
// Render view to an image
UIGraphicsBeginImageContext(view.frame.size)
view.drawHierarchy(in: view.frame, afterScreenUpdates: true)
let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
hideToolbars(false)
return memedImage
}
func hideToolbars(_ flag:Bool) {
navbar.isHidden = flag
toolbar.isHidden = flag
}
func save() {
// Create the meme
let meme = Meme(topText: topTextField.text!, bottomText: bottomTextField.text!, originalImage: imageView.image!, memedImage: generateMemedImage())
// Add it to the memes array in the Application Delegate
let object = UIApplication.shared.delegate
let appDelegate = object as! AppDelegate
appDelegate.memes.append(meme)
}
}
extension MemeEditorVC: UIImagePickerControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: false, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.image = image
}
picker.dismiss(animated: false, completion: nil)
shareButton.isEnabled = true
}
}
extension MemeEditorVC: UINavigationControllerDelegate {
}
|
2ed6c7b46bc1e77879c3ce36025d00c4
| 33.561404 | 154 | 0.675635 | false | false | false | false |
pennlabs/penn-mobile-ios
|
refs/heads/main
|
PennMobile/Setup + Navigation/SplashViewController.swift
|
mit
|
1
|
//
// SplashViewController.swift
// PennMobile
//
// Created by Josh Doman on 2/25/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import Foundation
import UIKit
import FirebaseCore
class SplashViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
var imageView: UIImageView
imageView = UIImageView()
imageView.image = UIImage(named: "LaunchIcon")
imageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imageView)
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
imageView.widthAnchor.constraint(equalToConstant: view.frame.width/5*2).isActive = true
imageView.heightAnchor.constraint(equalToConstant: view.frame.width/5*2).isActive = true
}
}
|
0c8434205f7d64bd05c9fb255943fef8
| 33.321429 | 96 | 0.726327 | false | false | false | false |
Alexiuce/Tip-for-day
|
refs/heads/master
|
TextKitDemo/TextKitDemo/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// TextKitDemo
//
// Created by caijinzhu on 2018/3/20.
// Copyright © 2018年 alexiuce.github.io. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var titleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let stringStorage = textView.textStorage
let lineHeight = textView.font!.lineHeight
guard let textPath = Bundle.main.path(forResource: "abc", ofType: ".txt") else { return }
guard let text = try? String(contentsOf: URL(fileURLWithPath: textPath), encoding: String.Encoding.utf8) else{return}
stringStorage.replaceCharacters(in: NSMakeRange(0, 0), with: text)
let layoutManager = NSLayoutManager()
stringStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: CGSize(width: 100, height: 100))
textContainer.lineBreakMode = .byTruncatingTail
layoutManager.addTextContainer(textContainer)
let exclucePath = UIBezierPath(rect: CGRect(x: 70, y: 100 - lineHeight, width: 30, height: lineHeight))
textContainer.exclusionPaths = [exclucePath]
let textRect = CGRect(x: 100, y: 400, width: 100, height: 100)
let textView2 = UITextView(frame:textRect , textContainer: textContainer)
textView2.isEditable = false
textView2.isScrollEnabled = false
textView2.backgroundColor = UIColor.yellow
view.addSubview(textView2)
let textContainer2 = NSTextContainer(size: CGSize(width: 100, height: 150))
layoutManager.addTextContainer(textContainer2)
let rect2 = CGRect(x: 210, y: 400, width: 100, height: 150)
let textView3 = UITextView(frame: rect2, textContainer: textContainer2)
textView3.backgroundColor = UIColor.gray
view.addSubview(textView3)
}
}
extension ViewController{
fileprivate func labelTest(){
var test = "http:www.joinf.com:3333"
titleLabel.text = test
test = "www.jionf.com"
}
}
|
dedc8d2642ea99407381441515cd3620
| 28.051948 | 125 | 0.644613 | false | true | false | false |
mbeloded/discountsPublic
|
refs/heads/master
|
discounts/Classes/UI/DiscountView/DiscountView.swift
|
gpl-3.0
|
1
|
//
// DiscountView.swift
// discounts
//
// Created by Michael Bielodied on 9/10/14.
// Copyright (c) 2014 Michael Bielodied. All rights reserved.
//
import Foundation
import UIKit
import RSBarcodes_Swift
import AVFoundation
class DiscountView: UIView {
@IBOutlet weak private var codeImageView: UIImageView!
@IBOutlet weak private var productImageLogoView: UIImageView!
@IBOutlet weak private var productNameLabel: UILabel!
func generateCode(_ productIndex:Int)
{
let companyObject:CompanyObject = DiscountsManager.sharedInstance.discountsCategoryArrayData[productIndex]
productNameLabel.text = companyObject.companyName
productImageLogoView.image = UIImage(named: companyObject.imageName)
let codeImage:UIImage = RSCode128Generator(codeTable: .a).generateCode(companyObject.discountCode, machineReadableCodeObjectType: AVMetadataObjectTypeCode128Code)!
codeImageView.image = codeImage
codeImageView.center = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
codeImageView.frame = CGRect(x: codeImageView.frame.origin.x, y: codeImageView.frame.origin.y, width: codeImage.size.width, height: codeImage.size.height)
}
}
|
179722bea9c772cdb7174f0d52cdc563
| 36.727273 | 171 | 0.747791 | false | false | false | false |
BrunoMazzo/CocoaHeadsApp
|
refs/heads/master
|
CocoaHeadsApp/Classes/Events/Controllers/EventsListDataSource.swift
|
mit
|
3
|
import UIKit
class EventsListTableDataSource: NSObject, UITableViewDataSource {
let viewModel :EventsListViewModel
init(viewModel : EventsListViewModel) {
self.viewModel = viewModel
super.init()
}
// MARK: - Table view data source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel.items.value.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reuseIdentifier = R.nib.eventsListTableViewCell.name
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath)
guard let eventsCell = cell as? EventsListTableViewCell else {
return cell
}
//eventsCell.events.value = viewModel.items.value[indexPath.item]
return eventsCell
}
}
|
f0d9d2cd3f768bc70d0e34ea5522b4b6
| 29.580645 | 109 | 0.67616 | false | false | false | false |
PorridgeBear/imvs
|
refs/heads/master
|
IMVS/Residue.swift
|
mit
|
1
|
//
// Residue.swift
// IMVS
//
// Created by Allistair Crossley on 13/07/2014.
// Copyright (c) 2014 Allistair Crossley. All rights reserved.
//
import Foundation
/**
* Amino Acid Residue
*
* A protein chain will have somewhere in the range of 50 to 2000 amino acid residues.
* You have to use this term because strictly speaking a peptide chain isn't made up of amino acids.
* When the amino acids combine together, a water molecule is lost. The peptide chain is made up
* from what is left after the water is lost - in other words, is made up of amino acid residues.
* http://www.chemguide.co.uk/organicprops/aminoacids/proteinstruct.html
* C and N terminus
*/
class Residue {
var name: String = ""
var atoms: [Atom] = []
convenience init() {
self.init(name: "NONE")
}
init(name: String) {
self.name = name
}
func addAtom(atom: Atom) {
atoms.append(atom)
}
func getAlphaCarbon() -> Atom? {
for atom in atoms {
if atom.element == "C" && atom.remoteness == "A" {
return atom
}
}
return nil
}
/** TODO - Might not be 100% right grabbing the first O - check */
func getCarbonylOxygen() -> Atom? {
for atom in atoms {
if atom.element == "O" {
return atom
}
}
return nil
}
}
|
cf459bc4fc63165338b01a15234992d0
| 22.693548 | 101 | 0.560926 | false | false | false | false |
tbointeractive/TBODeveloperOverlay
|
refs/heads/develop
|
TBODeveloperOverlay/TBODeveloperOverlay/SectionDatasource.swift
|
mit
|
1
|
//
// SectionDatasource.swift
// TBODeveloperOverlay
//
// Created by Cornelius Horstmann on 28.07.17.
// Copyright © 2017 TBO Interactive GmbH & CO KG. All rights reserved.
//
import Foundation
public final class Datasource: NSObject, UITableViewDataSource {
let sections: [Section]
public init(sections: [Section]) {
self.sections = sections
}
public func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].title
}
public func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return sections[section].footer
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = self.item(at: indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: item.reuseIdentifier) ??
UITableViewCell(style: .subtitle, reuseIdentifier: item.reuseIdentifier)
switch item {
case .info(let title, let detail):
cell.textLabel?.text = title
cell.textLabel?.numberOfLines = 0
cell.detailTextLabel?.text = detail
cell.detailTextLabel?.numberOfLines = 0
cell.selectionStyle = .none
case .segue(let title, let detail, _, _):
cell.textLabel?.text = title
cell.detailTextLabel?.text = detail
cell.accessoryType = .disclosureIndicator
case .action(let title, let detail, _, _):
cell.textLabel?.text = title
cell.detailTextLabel?.text = detail
}
return cell
}
public func item(at indexPath: IndexPath) -> Section.Item {
guard indexPath.section < sections.count else { fatalError("indexPath.section out of bounds")}
guard indexPath.row < sections[indexPath.section].items.count else { fatalError("indexPath.row out of bounds")}
return sections[indexPath.section].items[indexPath.row]
}
}
|
1b1a71520188e75fe2b92fd3b4a22068
| 35.296875 | 119 | 0.649591 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
refs/heads/main
|
Swift/3sum-with-multiplicity.swift
|
mit
|
1
|
class Solution {
/// - Complexity:
/// - Time: O(nlogn + m * m), where n = arr.count, m is the number of unique keys in arr.
/// - Space: O(m), m is the number of unique keys in arr.
func threeSumMulti(_ arr: [Int], _ target: Int) -> Int {
let MOD = 1_000_000_007
var count = [Int : Int]()
for c in arr {
count[c, default: 0] += 1
}
let keys = count.keys.sorted()
var result = 0
let n = keys.count
for index in 0 ..< n {
var left = index + 1
var right = n - 1
let sum = target - keys[index]
/// Case: x < y <= z
while left <= right {
if keys[left] + keys[right] < sum {
left += 1
} else if keys[left] + keys[right] > sum {
right -= 1
} else {
if left != right {
result += (count[keys[index], default: 0] * count[keys[left], default: 0] * count[keys[right], default: 0]) % MOD
result %= MOD
} else {
let c = count[keys[left], default: 0]
result += (count[keys[index], default: 0] * (c) * (c - 1) / 2) % MOD
result %= MOD
}
left += 1
right -= 1
}
}
let leftover = target - keys[index] - keys[index]
/// Case: first two elements are the same, 3rd element is a larger number.
if leftover > keys[index] {
let c = count[keys[index], default: 0]
result += (count[leftover, default: 0] * (c) * (c - 1) / 2) % MOD
result %= MOD
}
/// Case: all 3 number are identical.
if leftover == keys[index] {
let c = count[keys[index], default: 0]
result += ((c) * (c - 1) * (c - 2) / 6) % MOD
result %= MOD
}
// print(keys[index], sum, result)
}
return result
}
}
|
b3a6a265a8d7a17c5fea5e7a3a1ff902
| 37.298246 | 137 | 0.400366 | false | false | false | false |
Mclarenyang/medicine_aid
|
refs/heads/master
|
medicine aid/QRCodeViewController.swift
|
apache-2.0
|
1
|
//
// QRCodeViewController.swift
// CodeScanner
//
// Created by zhuxuhong on 2017/4/19.
// Copyright © 2017年 zhuxuhong. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import RealmSwift
class QRCodeViewController: UIViewController {
static var QRResult = ""
fileprivate lazy var topBar: UINavigationBar = {
let bar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 64))
bar.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
let item = UINavigationItem(title: "扫一扫")
let leftBtn = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(QRCodeViewController.actionForBarButtonItemClicked(_:)))
let rightBtn = UIBarButtonItem(title: "相册", style: .plain, target: self, action: #selector(QRCodeViewController.actionForBarButtonItemClicked(_:)))
item.leftBarButtonItem = leftBtn
item.rightBarButtonItem = rightBtn
bar.items = [item]
return bar
}()
fileprivate lazy var readerView: QRCodeReaderView = {
let h = self.topBar.bounds.height
let frame = CGRect(x: 0, y: h, width: self.view.bounds.width, height: self.view.bounds.height-h)
let v = QRCodeReaderView(frame: frame)
v.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return v
}()
public var completion: QRCodeReaderCompletion?
convenience init(completion: QRCodeReaderCompletion?) {
self.init()
self.completion = completion
}
}
extension QRCodeViewController{
override func viewDidLoad() {
super.viewDidLoad()
let rightBtn = UIBarButtonItem(title: "相册", style: .plain, target: self, action: #selector(QRCodeViewController.actionForBarButtonItemClicked(_:)))
self.navigationItem.rightBarButtonItem = rightBtn
//view.addSubview(topBar)
if QRCodeReader.isDeviceAvailable() && !QRCodeReader.isCameraUseDenied(){
setupReader()
}
}
override func viewWillAppear(_ animated: Bool){
super.viewWillAppear(animated)
guard QRCodeReader.isDeviceAvailable() else{
let alert = UIAlertController(title: "Error", message: "相机无法使用", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "好", style: .cancel, handler: {
_ in
self.dismiss(animated: true, completion: nil)
}))
present(alert, animated: true, completion: nil)
return
}
if QRCodeReader.isCameraUseDenied(){
hanldeAlertForAuthorization(isCamera: true)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if QRCodeReader.isCameraUseAuthorized(){
readerView.updateRectOfOutput()
}
}
// MARK: - action & IBOutletAction
@IBAction func actionForBarButtonItemClicked(_ sender: UIBarButtonItem){
guard let item = topBar.items!.first else {
return
}
if sender == item.leftBarButtonItem! {
completionFor(result: nil, isCancel: true)
}
else if sender == self.navigationItem.rightBarButtonItem! {
handleActionForImagePicker()
}
}
fileprivate func completionFor(result: String?, isCancel: Bool){
readerView.reader.stopScanning()
dismiss(animated: true, completion: {
isCancel ? nil : self.completion?(result ?? "没有发现任何信息")
})
}
}
extension QRCodeViewController{
fileprivate func handleActionForImagePicker(){
if QRCodeReader.isAlbumUseDenied() {
hanldeAlertForAuthorization(isCamera: false)
return
}
readerView.reader.stopScanning()
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .savedPhotosAlbum
picker.allowsEditing = false
present(picker, animated: true, completion: nil)
}
fileprivate func setupReader(){
view.addSubview(readerView)
readerView.setup(completion: {[unowned self]
(result) in
self.completionFor(result: result, isCancel: false)
})
}
fileprivate func openSystemSettings(){
let url = URL(string: UIApplicationOpenSettingsURLString)!
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
fileprivate func hanldeAlertForAuthorization(isCamera: Bool){
let str = isCamera ? "相机" : "相册"
let alert = UIAlertController(title: "\(str)没有授权", message: "在[设置]中找到应用,开启[允许访问\(str)]", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "去设置", style: .cancel, handler: { _ in
self.openSystemSettings()
}))
present(alert, animated: true, completion: nil)
}
fileprivate func handleQRCodeScanningFor(image: UIImage){
let ciimage = CIImage(cgImage: image.cgImage!)
let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
if let features = detector?.features(in: ciimage),
let first = features.first as? CIQRCodeFeature{
self.completionFor(result: first.messageString, isCancel: false)
///相册扫描结果
NSLog(first.messageString!)
QRCodeViewController.QRResult = first.messageString!
//ID
let defaults = UserDefaults.standard
let UserID = defaults.value(forKey: "UserID")!
//直接链接
//提示
let alert = UIAlertController(title: "提示", message: "确定挂号排队?", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let doneAction = UIAlertAction(title: "好", style: .default, handler: {
action in
let url = AESEncoding.myURL + "igds/app/link"
let parameters: Parameters = [
"doctorId":first.messageString!,
"patientId":UserID
]
Alamofire.request(url, method: .post, parameters: parameters).responseJSON{
classValue in
if let value = classValue.result.value{
let json = JSON(value)
let code = json["code"]
print("患者挂号code:\(code)")
if code == 201{
//挂号信息本地化
saveRegister(doctorID: first.messageString!)
let queueView = queueViewController()
queueView.doctorID = first.messageString!
self.navigationController?.pushViewController(queueView, animated: true)
//储存挂号医生的ID,用于已挂查询
let defaults = UserDefaults.standard
defaults.set(first.messageString!, forKey: "doctorID")
//更新挂号状态
defaults.set("yes", forKey: "status")
}else if code == 403{
let alert = UIAlertController(title: "提示", message: "您已经挂号,请勿重复提交", preferredStyle: .alert)
let doneAction = UIAlertAction(title: "好", style: .default, handler:{
action in
let queueView = queueViewController()
queueView.doctorID = first.messageString!
self.navigationController?.pushViewController(queueView, animated: true)
})
alert.addAction(doneAction)
self.present(alert, animated: true, completion: nil)
}else{
let alert = UIAlertController(title: "链接错误", message: "你可能扫了一个假的二维码", preferredStyle: .alert)
let doneAction = UIAlertAction(title: "好", style: .default, handler:{
action in
_ = self.navigationController?.popViewController(animated: true)
})
alert.addAction(doneAction)
self.present(alert, animated: true, completion: nil)
}
}
}
})
alert.addAction(cancelAction)
alert.addAction(doneAction)
self.present(alert, animated: true, completion: nil)
}
}
}
//挂号本地化
func saveRegister(doctorID: String){
//读取储存信息
//ID
let defaults = UserDefaults.standard
let UserID = String(describing: defaults.value(forKey: "UserID")!)
//读Type
let realm = try! Realm()
let patientNickname = realm.objects(UserText.self).filter("UserID = '\(UserID)'")[0].UserNickname
//时间
let now = Date()
let dformatter = DateFormatter()
dformatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
print("当前日期时间:\(dformatter.string(from: now))")
let time = dformatter.string(from: now)
//存储
let dprlist = DPRList()
dprlist.DoctorID = doctorID
dprlist.PatientID = UserID
//dprlist.DocrorNickname = doctorNickname
dprlist.PatientNickname = patientNickname
dprlist.Time = time
//dprlist.MedicalList = medicalStr
try! realm.write {
realm.add(dprlist)
}
}
extension QRCodeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
readerView.reader.startScanning(completion: completion)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
picker.dismiss(animated: true, completion: {
self.handleQRCodeScanningFor(image: image)
})
}
}
}
extension QRCodeViewController{
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
if QRCodeReader.isDeviceAvailable() && QRCodeReader.isCameraUseAuthorized() {
readerView.updateRectOfOutput()
}
}
}
|
4c705fc5dfe9f9234902492856216466
| 34.901899 | 155 | 0.55152 | false | false | false | false |
skylib/SnapImagePicker
|
refs/heads/master
|
SnapImagePicker/SnapImagePickerTransition.swift
|
bsd-3-clause
|
1
|
import Foundation
import UIKit
class VerticalSlideTransitionManager : NSObject, UIViewControllerAnimatedTransitioning {
let animationDuration = 0.3
let action: Action
enum Action {
case push
case pop
}
init(action: Action) {
self.action = action
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return animationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if action == .push {
push(transitionContext)
} else {
pop(transitionContext)
}
}
func push(_ transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
if let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) {
containerView.addSubview(toView)
let size = containerView.bounds.size
let initalFrame = CGRect(x: CGFloat(0.0), y: -size.height, width: size.width, height: size.height)
let finalFrame = containerView.bounds
toView.frame = initalFrame
UIView.animate(withDuration: animationDuration,
animations: { toView.frame = finalFrame },
completion: { _ in transitionContext.completeTransition(true) })
}
}
func pop(_ transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
if let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from),
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) {
let size = containerView.bounds.size
let finalFrame = CGRect(x: CGFloat(0.0), y: -size.height, width: size.width, height: size.height)
toView.frame = CGRect(x: CGFloat(0.0), y: 0, width: size.width, height: size.height)
containerView.addSubview(toView)
containerView.sendSubview(toBack: toView)
UIView.animate(withDuration: animationDuration,
animations: {fromView.frame = finalFrame},
completion: { _ in transitionContext.completeTransition(true)})
}
}
}
open class SnapImagePickerNavigationControllerDelegate: NSObject, UINavigationControllerDelegate, UIViewControllerTransitioningDelegate {
public override init() {
super.init()
}
open func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .none: return nil
case .push: return VerticalSlideTransitionManager(action: .push)
case .pop: return VerticalSlideTransitionManager(action: .pop)
}
}
}
|
ae5147d366336f1b4766bf06f146b1e9
| 40.76 | 251 | 0.648787 | false | false | false | false |
Ansem717/PictureFeed
|
refs/heads/master
|
PictureFeed/Post.swift
|
mit
|
1
|
//
// Post.swift
// PictureFeed
//
// Created by Andy Malik on 2/16/16.
// Copyright © 2016 Andy Malik. All rights reserved.
//
import UIKit
import CloudKit
enum PostError: ErrorType {
case WritingImage
case CreatingCKRecord
}
class Post {
let image: UIImage
let status: String?
init(image: UIImage, status: String? = "") {
self.image = image
self.status = status
}
}
extension Post {
class func recordWith(post: Post) throws -> CKRecord? {
let imageURL = NSURL.imageURL()
guard let imgData = UIImageJPEGRepresentation(post.image, 0.7) else { throw PostError.WritingImage }
let saved = imgData.writeToURL(imageURL, atomically: true)
if saved {
let asset = CKAsset(fileURL: imageURL)
let record = CKRecord(recordType: "Post")
record.setObject(asset, forKey: "image")
return record
} else { throw PostError.CreatingCKRecord }
}
}
|
c42d32f4b18f6e791e8374d8f2e1b8fb
| 21.148936 | 108 | 0.591346 | false | false | false | false |
AckeeCZ/ACKReactiveExtensions
|
refs/heads/master
|
ACKReactiveExtensions/Realm/RealmExtensions.swift
|
mit
|
1
|
//
// RealmExtensions.swift
// Realm
//
// Created by Tomáš Kohout on 01/12/15.
// Copyright © 2015 Ackee s.r.o. All rights reserved.
//
import UIKit
import RealmSwift
import ReactiveCocoa
import ReactiveSwift
#if !COCOAPODS
import ACKReactiveExtensionsCore
#endif
/// Error return in case of Realm operation failure
public struct RealmError: Error {
public let underlyingError: NSError
public init(underlyingError: NSError){
self.underlyingError = underlyingError
}
}
/// Enum which represents RealmCollectionChange
public enum Change<T> {
typealias Element = T
/// Initial value
case initial(T)
/// RealmCollection was updated
case update(T, deletions: [Int], insertions: [Int], modifications: [Int])
}
public extension Reactive where Base: RealmCollection {
/// SignalProducer that sends changes as they happen
var changes: SignalProducer<Change<Base>, RealmError> {
var notificationToken: NotificationToken? = nil
let producer: SignalProducer<Change<Base>, RealmError> = SignalProducer { sink, d in
guard let realm = self.base.realm else {
print("Cannot observe object without Realm")
return
}
func observe() -> NotificationToken? {
return self.base.observe(on: OperationQueue.current?.underlyingQueue) { changes in
switch changes {
case .initial(let initial):
sink.send(value: Change.initial(initial))
case .update(let updates, let deletions, let insertions, let modifications):
sink.send(value: Change.update(updates, deletions: deletions, insertions: insertions, modifications: modifications))
case .error(let e):
sink.send(error: RealmError(underlyingError: e as NSError))
}
}
}
let registerObserverIfPossible: () -> (Bool, NotificationToken?) = {
if !realm.isInWriteTransaction { return (true, observe()) }
return (false, nil)
}
var counter = 0
let maxRetries = 10
func registerWhileNotSuccessful(queue: DispatchQueue) {
let (registered, token) = registerObserverIfPossible()
guard !registered, counter < maxRetries else { notificationToken = token; return }
counter += 1
queue.async { registerWhileNotSuccessful(queue: queue) }
}
if let opQueue = OperationQueue.current, let dispatchQueue = opQueue.underlyingQueue {
registerWhileNotSuccessful(queue: dispatchQueue)
} else {
notificationToken = observe()
}
}.on(terminated: {
notificationToken?.invalidate()
notificationToken = nil
}, disposed: {
notificationToken?.invalidate()
notificationToken = nil
})
return producer
}
/// SignalProducer that sends the latest value
var values: SignalProducer<Base, RealmError> {
return self.changes.map { changes -> Base in
switch changes {
case .initial(let initial):
return initial
case .update(let updates, _, _, _):
return updates
}
}
}
/// Property which represents the latest value
var property: ReactiveSwift.Property<Base> {
return ReactiveSwift.Property(initial: base, then: values.ignoreError() )
}
}
//MARK: Saving
public extension Reactive where Base: Object {
/**
* Reactive save Realm object
*
* - parameter update: Realm should find existing object using primaryKey() and update it if it exists otherwise create new object
* - parameter writeBlock: Closure which allows custom Realm operation instead of default add
*/
func save(update: Realm.UpdatePolicy = .all, writeBlock: ((Realm)->Void)? = nil) -> SignalProducer<Base, RealmError>{
return SignalProducer<Base, RealmError> { sink, d in
do {
let realm = try Realm()
realm.refresh()
try realm.write {
if let writeBlock = writeBlock {
writeBlock(realm)
} else {
realm.add(self.base, update: update)
}
}
sink.send(value: self.base)
sink.sendCompleted()
} catch (let e) {
sink.send(error: RealmError(underlyingError: e as NSError) )
}
}
}
/**
* Reactively delete object
*/
func delete() -> SignalProducer<(), RealmError> {
return SignalProducer { sink, d in
do {
let realm = try Realm()
realm.refresh()
try realm.write {
realm.delete(self.base)
}
sink.send(value: ())
sink.sendCompleted()
} catch (let e) {
sink.send(error: RealmError(underlyingError: e as NSError) )
}
}
}
var changes: SignalProducer<ObjectChange<ObjectBase>, RealmError> {
var notificationToken: NotificationToken? = nil
let producer: SignalProducer<ObjectChange<ObjectBase>, RealmError> = SignalProducer { sink, d in
guard let realm = self.base.realm else {
print("Cannot observe object without Realm")
return
}
func observe() -> NotificationToken? {
return self.base.observe { change in
switch change {
case .error(let e):
sink.send(error: RealmError(underlyingError: e))
default:
sink.send(value: change)
}
}
}
let registerObserverIfPossible: () -> (Bool, NotificationToken?) = {
if !realm.isInWriteTransaction { return (true, observe()) }
return (false, nil)
}
var counter = 0
let maxRetries = 10
func registerWhileNotSuccessful(queue: DispatchQueue) {
let (registered, token) = registerObserverIfPossible()
guard !registered, counter < maxRetries else { notificationToken = token; return }
counter += 1
queue.async { registerWhileNotSuccessful(queue: queue) }
}
if let opQueue = OperationQueue.current, let dispatchQueue = opQueue.underlyingQueue {
registerWhileNotSuccessful(queue: dispatchQueue)
} else {
notificationToken = observe()
}
}.on(terminated: {
notificationToken?.invalidate()
notificationToken = nil
}, disposed: {
notificationToken?.invalidate()
notificationToken = nil
})
return producer
}
var values: SignalProducer<Base, RealmError> {
return self.changes
.filter { if case .deleted = $0 { return false }; return true }
.map { _ in
return self.base
}
}
var property: ReactiveSwift.Property<Base> {
return ReactiveSwift.Property(initial: base, then: values.ignoreError() )
}
}
//MARK: Table view
/// Protocol which allows UITableView to be reloaded automatically when database changes happen
public protocol RealmTableViewReloading {
associatedtype Element: Object
var tableView: UITableView! { get set }
}
public extension Reactive where Base: UIViewController, Base: RealmTableViewReloading {
/// Binding target which updates tableView according to received changes
var changes: BindingTarget<Change<Results<Base.Element>>> {
return makeBindingTarget { vc, changes in
guard let tableView = vc.tableView else { return }
switch changes {
case .initial:
tableView.reloadData()
break
case .update(_, let deletions, let insertions, let modifications):
tableView.beginUpdates()
tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }),
with: .automatic)
tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}),
with: .automatic)
tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }),
with: .automatic)
tableView.endUpdates()
break
}
}
}
}
//MARK: PrimaryKeyEquatable
protocol PrimaryKeyEquatable: AnyObject {
static func primaryKey() -> String?
subscript(key: String) -> Any? { get set }
}
extension Object: PrimaryKeyEquatable {}
precedencegroup PrimaryKeyEquative {
associativity: left
}
infix operator ~== : PrimaryKeyEquative
func ~==(lhs: PrimaryKeyEquatable, rhs: PrimaryKeyEquatable) -> Bool {
//Super ugly but can't find nicer way to assert same types
guard "\(type(of: lhs))" == "\(type(of: rhs))" else {
assertionFailure("Trying to compare different types \(type(of: lhs)) and \(type(of: rhs))")
return false
}
guard let primaryKey = type(of: lhs).primaryKey(), let lValue = lhs[primaryKey],
let rValue = rhs[primaryKey] else {
assertionFailure("Trying to compare object that has no primary key")
return false
}
if let l = lValue as? String, let r = rValue as? String {
return l == r
} else if let l = lValue as? Int, let r = rValue as? Int {
return l == r
} else if let l = lValue as? Int8, let r = rValue as? Int8 {
return l == r
} else if let l = lValue as? Int16, let r = rValue as? Int16 {
return l == r
} else if let l = lValue as? Int32, let r = rValue as? Int32 {
return l == r
} else if let l = lValue as? Int64, let r = rValue as? Int64 {
return l == r
} else {
assertionFailure("Unsupported primary key")
return false
}
}
//MARK: Orphaned Object
extension Realm {
/// Add objects and delete non-present objects from the orphan query
public func add<S: Sequence>(_ objects: S, update: Realm.UpdatePolicy = .all, deleteOrphanedQuery: Results<S.Iterator.Element>) where S.Iterator.Element: Object {
let allObjects = deleteOrphanedQuery.map { $0 }
//This could be faster with set, but we can't redefine hashable
let objectsToDelete = allObjects.filter { old in
!objects.contains(where: {
old ~== $0
})
}
self.delete(objectsToDelete)
self.add(objects, update: update)
}
}
|
55e825c9cda321f9c40709cdcf7a5f27
| 33.04908 | 166 | 0.568919 | false | false | false | false |
couchbaselabs/mini-hacks
|
refs/heads/master
|
google-sign-in/SimpleLogin/SimpleLogin/CreateSyncGatewaySession.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
// Let asynchronous code run
XCPSetExecutionShouldContinueIndefinitely()
let userId = "4567891023456789012340000000000000000000000000"
// 1
let loginURL = NSURL(string: "http://localhost:8000/google_signin")!
// 2
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: loginURL)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
// 3
var properties = [
"user_id": userId,
"auth_provider": "google"
]
let data = try! NSJSONSerialization.dataWithJSONObject(properties, options: NSJSONWritingOptions.PrettyPrinted)
// 4
let uploadTask = session.uploadTaskWithRequest(request, fromData: data, completionHandler: { (data, response, error) -> Void in
// 5
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String, AnyObject>
print("\(json)")
// TODO: pull/push replications with authenticated user
})
uploadTask.resume()
|
240587d207c7667db3e0020cc7804c12
| 28.675676 | 145 | 0.752051 | false | false | false | false |
halonsoluis/ViewControllerHideButtonExample
|
refs/heads/master
|
ChangeValueViewControllerExample/SecondViewController.swift
|
gpl-2.0
|
1
|
//
// SecondViewController.swift
// ChangeValueViewControllerExample
//
// Created by Hugo on 12/1/15.
// Copyright © 2015 halonso. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initFirstViewController() -> FirstViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let firstViewController = storyboard.instantiateViewControllerWithIdentifier("FirstViewController") as! FirstViewController
return firstViewController
}
@IBAction func ShowNextViewWithButton(sender: AnyObject) {
let firstViewController = initFirstViewController()
self.presentViewController(firstViewController, animated: true, completion: {
//This lines will be called after the view is loaded so the code will run
firstViewController.firstButton.alpha = 1
})
}
@IBAction func ShowNextViewWithoutButton(sender: AnyObject) {
let firstViewController = initFirstViewController()
self.presentViewController(firstViewController, animated: true, completion: {
//This lines will be called after the view is loaded so the code will run
firstViewController.firstButton.alpha = 0
})
}
@IBAction func ShowNextViewWithButtonInit(sender: AnyObject) {
let firstViewController = initFirstViewController()
firstViewController.showButton = true
self.presentViewController(firstViewController, animated: true, completion: nil)
}
@IBAction func ShowNextViewWithoutButtonInit(sender: AnyObject) {
let firstViewController = initFirstViewController()
firstViewController.showButton = false
self.presentViewController(firstViewController, animated: true, completion: nil)
}
}
|
304af60b95bff2d7301198d6a0ce8a9c
| 34.193548 | 131 | 0.687758 | false | false | false | false |
leonereveel/Moya
|
refs/heads/master
|
Source/Moya+Internal.swift
|
mit
|
1
|
import Foundation
import Result
/// Internal extension to keep the inner-workings outside the main Moya.swift file.
internal extension MoyaProvider {
// Yup, we're disabling these. The function is complicated, but breaking it apart requires a large effort.
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable function_body_length
/// Performs normal requests.
func requestNormal(target: Target, queue: dispatch_queue_t?, progress: Moya.ProgressBlock?, completion: Moya.Completion) -> Cancellable {
let endpoint = self.endpoint(target)
let stubBehavior = self.stubClosure(target)
let cancellableToken = CancellableWrapper()
if trackInflights {
objc_sync_enter(self)
var inflightCompletionBlocks = self.inflightRequests[endpoint]
inflightCompletionBlocks?.append(completion)
self.inflightRequests[endpoint] = inflightCompletionBlocks
objc_sync_exit(self)
if inflightCompletionBlocks != nil {
return cancellableToken
} else {
objc_sync_enter(self)
self.inflightRequests[endpoint] = [completion]
objc_sync_exit(self)
}
}
let performNetworking = { (requestResult: Result<NSURLRequest, Moya.Error>) in
if cancellableToken.cancelled {
self.cancelCompletion(completion, target: target)
return
}
var request: NSURLRequest!
switch requestResult {
case .Success(let urlRequest):
request = urlRequest
case .Failure(let error):
completion(result: .Failure(error))
return
}
switch stubBehavior {
case .Never:
let networkCompletion: Moya.Completion = { result in
if self.trackInflights {
self.inflightRequests[endpoint]?.forEach({ $0(result: result) })
objc_sync_enter(self)
self.inflightRequests.removeValueForKey(endpoint)
objc_sync_exit(self)
} else {
completion(result: result)
}
}
switch target.task {
case .Request:
cancellableToken.innerCancellable = self.sendRequest(target, request: request, queue: queue, progress: progress, completion: networkCompletion)
case .Upload(.File(let file)):
cancellableToken.innerCancellable = self.sendUploadFile(target, request: request, queue: queue, file: file, progress: progress, completion: networkCompletion)
case .Upload(.Multipart(let multipartBody)):
guard !multipartBody.isEmpty && target.method.supportsMultipart else {
fatalError("\(target) is not a multipart upload target.")
}
cancellableToken.innerCancellable = self.sendUploadMultipart(target, request: request, queue: queue, multipartBody: multipartBody, progress: progress, completion: networkCompletion)
case .Download(.Request(let destination)):
cancellableToken.innerCancellable = self.sendDownloadRequest(target, request: request, queue: queue, destination: destination, progress: progress, completion: networkCompletion)
}
default:
cancellableToken.innerCancellable = self.stubRequest(target, request: request, completion: { result in
if self.trackInflights {
self.inflightRequests[endpoint]?.forEach({ $0(result: result) })
objc_sync_enter(self)
self.inflightRequests.removeValueForKey(endpoint)
objc_sync_exit(self)
} else {
completion(result: result)
}
}, endpoint: endpoint, stubBehavior: stubBehavior)
}
}
requestClosure(endpoint, performNetworking)
return cancellableToken
}
// swiftlint:enable cyclomatic_complexity
// swiftlint:enable function_body_length
func cancelCompletion(completion: Moya.Completion, target: Target) {
let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) }
completion(result: .Failure(error))
}
/// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters.
final func createStubFunction(token: CancellableToken, forTarget target: Target, withCompletion completion: Moya.Completion, endpoint: Endpoint<Target>, plugins: [PluginType]) -> (() -> ()) {
return {
if token.cancelled {
self.cancelCompletion(completion, target: target)
return
}
switch endpoint.sampleResponseClosure() {
case .NetworkResponse(let statusCode, let data):
let response = Moya.Response(statusCode: statusCode, data: data, response: nil)
plugins.forEach { $0.didReceiveResponse(.Success(response), target: target) }
completion(result: .Success(response))
case .NetworkError(let error):
let error = Moya.Error.Underlying(error)
plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) }
completion(result: .Failure(error))
}
}
}
/// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`.
final func notifyPluginsOfImpendingStub(request: NSURLRequest, target: Target) {
let alamoRequest = manager.request(request)
plugins.forEach { $0.willSendRequest(alamoRequest, target: target) }
}
}
private extension MoyaProvider {
private func sendUploadMultipart(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, multipartBody: [MultipartFormData], progress: Moya.ProgressBlock? = nil, completion: Moya.Completion) -> CancellableWrapper {
let cancellable = CancellableWrapper()
let multipartFormData = { (form: RequestMultipartFormData) -> Void in
for bodyPart in multipartBody {
switch bodyPart.provider {
case .Data(let data):
self.append(data: data, bodyPart: bodyPart, to: form)
case .File(let url):
self.append(fileURL: url, bodyPart: bodyPart, to: form)
case .Stream(let stream, let length):
self.append(stream: stream, length: length, bodyPart: bodyPart, to: form)
}
}
if let parameters = target.parameters {
parameters
.flatMap { (key, value) in multipartQueryComponents(key, value) }
.forEach { (key, value) in
if let data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
form.appendBodyPart(data: data, name: key)
}
}
}
}
manager.upload(request, multipartFormData: multipartFormData) { (result: MultipartFormDataEncodingResult) in
switch result {
case .Success(let alamoRequest, _, _):
if cancellable.cancelled {
self.cancelCompletion(completion, target: target)
return
}
cancellable.innerCancellable = self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion)
case .Failure(let error):
completion(result: .Failure(Moya.Error.Underlying(error as NSError)))
}
}
return cancellable
}
private func sendUploadFile(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, file: NSURL, progress: ProgressBlock? = nil, completion: Completion) -> CancellableToken {
let alamoRequest = manager.upload(request, file: file)
return self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion)
}
private func sendDownloadRequest(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, destination: DownloadDestination, progress: ProgressBlock? = nil, completion: Completion) -> CancellableToken {
let alamoRequest = manager.download(request, destination: destination)
return self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion)
}
private func sendRequest(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, progress: Moya.ProgressBlock?, completion: Moya.Completion) -> CancellableToken {
let alamoRequest = manager.request(request)
return sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion)
}
private func sendAlamofireRequest(alamoRequest: Request, target: Target, queue: dispatch_queue_t?, progress: Moya.ProgressBlock?, completion: Moya.Completion) -> CancellableToken {
// Give plugins the chance to alter the outgoing request
let plugins = self.plugins
plugins.forEach { $0.willSendRequest(alamoRequest, target: target) }
// Perform the actual request
if let progress = progress {
alamoRequest
.progress { (bytesWritten, totalBytesWritten, totalBytesExpected) in
let sendProgress: () -> () = {
progress(progress: ProgressResponse(totalBytes: totalBytesWritten, bytesExpected: totalBytesExpected))
}
if let queue = queue {
dispatch_async(queue, sendProgress)
} else {
sendProgress()
}
}
}
alamoRequest
.response(queue: queue) { (_, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in
let result = convertResponseToResult(response, data: data, error: error)
// Inform all plugins about the response
plugins.forEach { $0.didReceiveResponse(result, target: target) }
completion(result: result)
}
alamoRequest.resume()
return CancellableToken(request: alamoRequest)
}
}
// MARK: - RequestMultipartFormData appending
private extension MoyaProvider {
private func append(data data: NSData, bodyPart: MultipartFormData, to form: RequestMultipartFormData) {
if let mimeType = bodyPart.mimeType {
if let fileName = bodyPart.fileName {
form.appendBodyPart(data: data, name: bodyPart.name, fileName: fileName, mimeType: mimeType)
} else {
form.appendBodyPart(data: data, name: bodyPart.name, mimeType: mimeType)
}
} else {
form.appendBodyPart(data: data, name: bodyPart.name)
}
}
private func append(fileURL url: NSURL, bodyPart: MultipartFormData, to form: RequestMultipartFormData) {
if let fileName = bodyPart.fileName, mimeType = bodyPart.mimeType {
form.appendBodyPart(fileURL: url, name: bodyPart.name, fileName: fileName, mimeType: mimeType)
} else {
form.appendBodyPart(fileURL: url, name: bodyPart.name)
}
}
private func append(stream stream: NSInputStream, length: UInt64, bodyPart: MultipartFormData, to form: RequestMultipartFormData) {
form.appendBodyPart(stream: stream, length: length, name: bodyPart.name, fileName: bodyPart.fileName ?? "", mimeType: bodyPart.mimeType ?? "")
}
}
/// Encode parameters for multipart/form-data
private func multipartQueryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += multipartQueryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += multipartQueryComponents("\(key)[]", value)
}
} else {
components.append((key, "\(value)"))
}
return components
}
|
4e43fbec51216d2dd23428eb1597341c
| 46.842105 | 227 | 0.61614 | false | false | false | false |
marcosjvivar/WWE-iOS-Code-Test
|
refs/heads/development
|
WWEMobile/Model/Application/Video/WWEVideoTag.swift
|
mit
|
1
|
//
// WWEVideoTag.swift
// WWEMobile
//
// Created by Marcos Jesús Vivar on 8/25/17.
// Copyright © 2017 Spark Digital. All rights reserved.
//
import UIKit
import SwiftyJSON
import RealmSwift
class WWEVideoTag: Object {
dynamic var tagID: Int = 0
dynamic var tagType: String = ""
dynamic var tagTitle: String = ""
static func create(json: JSON) -> WWEVideoTag {
let tag = WWEVideoTag()
tag.tagID = json[attributes.id.rawValue].intValue
tag.tagTitle = json[attributes.title.rawValue].stringValue
tag.tagType = json[attributes.type.rawValue].stringValue
return tag
}
}
|
f8aa6f01aa05d4b4edbfabd4853aac5c
| 22.137931 | 66 | 0.636364 | false | false | false | false |
AfricanSwift/TUIKit
|
refs/heads/master
|
TUIKit/Source/Ansi/Ansi+Character.swift
|
mit
|
1
|
//
// File: Ansi+Character.swift
// Created by: African Swift
import Darwin
// MARK: -
// MARK: Character: Insert, Delete, ... -
public extension Ansi
{
/// Character
public enum Character
{
/// Insert Character(s) (ICH)
///
/// - parameters:
/// - quantity: Insert quantity (default = 1) of blank characters at current position
/// - returns: Ansi
public static func insert(quantity: Int = 1) -> Ansi
{
return Ansi("\(Ansi.C1.CSI)\(quantity)@")
}
/// Delete Character(s) (DCH)
///
/// - parameters:
/// - quantity: Delete quantity (default = 1) characters, current position to field end
/// - returns: Ansi
public static func delete(quantity: Int = 1) -> Ansi
{
return Ansi("\(Ansi.C1.CSI)\(quantity)P")
}
/// Erase Character(s) (ECH)
///
/// - parameters:
/// - quantity: Erase quantity (default = 1) characters
/// - returns: Ansi
public static func erase(quantity: Int = 1) -> Ansi
{
return Ansi("\(Ansi.C1.CSI)\(quantity)X")
}
/// Repeat the preceding graphic character (REP)
///
/// - parameters:
/// - quantity: Repeat previous displayable character a specified number of times (default = 1)
/// - returns: Ansi
public static func repeatLast(quantity: Int = 1) -> Ansi
{
return Ansi("\(Ansi.C1.CSI)\(quantity)b")
}
}
}
|
e2407913fc2d9b437ce9d0665b3fd9e8
| 25.5 | 102 | 0.569532 | false | false | false | false |
jkingyens/sports-stream
|
refs/heads/master
|
SportsStreamClient/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// SportsStreamClient
//
// Created by Jeff Kingyens on 10/11/15.
// Copyright © 2015 SportsStream. All rights reserved.
//
import UIKit
import KeychainAccess
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// properties?
var window: UIWindow?
var preferredServerRegion: String?
var apiKey: String?
var loggedIn: Bool?
var sessionToken: String?
var currentEndpoint: String?
var username: String?
var password: String?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let mainBundle = NSBundle.mainBundle()
let path = mainBundle.pathForResource("AppConfig", ofType: "plist")
let configurations = NSDictionary(contentsOfFile: path!)
let api = configurations!.objectForKey("ServerAPIKey")
NSLog("config = %@", configurations!)
NSLog("API Key = %@", api as! String)
self.apiKey = api as? String
self.preferredServerRegion = "North America - West";
self.loggedIn = false
// try to login automatically if we have credentials on file
let defaults = NSUserDefaults.standardUserDefaults()
let endpoint = defaults.objectForKey("endpoint") as? NSString
if (endpoint == nil) {
return true
}
let username = defaults.objectForKey("username")
if (username == nil) {
return true
}
let keychain = Keychain(server: endpoint as! String, protocolType: ProtocolType.HTTPS)
.label("com.sportsstream.sportsstreamclient")
.synchronizable(true)
if (keychain[username as! String] == nil) {
return true
}
// attempt login
let loginURL = NSURL(string:String(format: "%@/Login", endpoint!))
NSLog("connecting to endpoint: %@", loginURL!)
let request = NSMutableURLRequest(URL: loginURL!) as NSMutableURLRequest
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let postData = NSString(format: "username=%@&password=%@&key=%@", username as! NSString, keychain[username as! String]! as NSString, self.apiKey!) .dataUsingEncoding(NSUTF8StringEncoding)
NSLog("postdata = %@", NSString(data: postData!, encoding: NSUTF8StringEncoding)!)
request.HTTPMethod = "POST"
request.HTTPBody = postData
let defaultConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let urlSession = NSURLSession(configuration: defaultConfiguration)
let dataTask = urlSession.dataTaskWithRequest(request, completionHandler: { (data, response, error) in
if (error != nil) {
// ask user to check address or internet connection
NSLog("error connecting to endpoint: %@", error!)
return
}
let httpResponse = response as! NSHTTPURLResponse
if (httpResponse.statusCode != 200) {
NSLog("error authenticating with server: %d", httpResponse.statusCode)
// remove from keychain here?
return
}
do {
let userInfo = try NSJSONSerialization .JSONObjectWithData(data!, options:NSJSONReadingOptions()) as! NSDictionary
NSLog("User info = %@", userInfo)
let membership = userInfo.objectForKey("membership")
if (membership == nil) {
NSLog("Membership is not defined")
return
}
if (membership?.isEqualToString("Premium") == false) {
NSLog("Not a premium member: %@", membership as! NSString)
return
}
// load in meory account
self.currentEndpoint = endpoint as? String
self.username = username as? String
self.password = keychain[username as! String]! as String
self.sessionToken = userInfo.objectForKey("token") as? String
self.loggedIn = true
// switch to game list and reload games view
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
let ctrl = self.window?.rootViewController as! UITabBarController
ctrl.selectedIndex = 1
let gameList = ctrl.selectedViewController as! LiveGamesViewController
gameList.refreshTable()
let loginCtrl = ctrl.viewControllers![0] as! LoginViewController
loginCtrl.refreshView()
}
} catch {
NSLog("Error parsing JSON response, got body = %@", data!)
}
});
dataTask.resume()
return true
}
}
|
d4c8980290b9158f503501d5e7d992ed
| 38.067164 | 195 | 0.575931 | false | true | false | false |
MHaubenstock/Endless-Dungeon
|
refs/heads/master
|
EndlessDungeon/EndlessDungeon/Tile.swift
|
mit
|
1
|
//
// Tile.swift
// EndlessDungeon
//
// Created by Michael Haubenstock on 9/21/14.
// Copyright (c) 2014 Michael Haubenstock. All rights reserved.
//
import Foundation
import SpriteKit
class Tile
{
var enemies : [NPCharacter] = []
var lootables : [Container] = []
var cells : [[Cell]]
var entranceCell : Cell
var exitCells : [Cell]
var containers : [Container] = []
var tileSprite : SKSpriteNode = SKSpriteNode()
var roomGenerated : Bool = false
var numXCells : Int!
var numYCells : Int!
//Create Entrance Tile
init(nXCells : Int, nYCells : Int)
{
numXCells = nXCells
numYCells = nYCells
//Fill all cells with walls
cells = Array(count: numYCells, repeatedValue: Array(count: numXCells, repeatedValue: Cell()))
exitCells = Array(count: 0, repeatedValue: Cell(type: .Exit))
entranceCell = Cell()
}
init(nXCells : Int, nYCells : Int, gridLeft : CGFloat, gridBottom : CGFloat, cellSize : Int)
{
numXCells = nXCells
numYCells = nYCells
//Fill all cells with walls
cells = Array(count: numYCells, repeatedValue: Array(count: numXCells, repeatedValue: Cell()))
exitCells = Array(count: 0, repeatedValue: Cell(type: .Exit))
//Initialize each cell's position and index
for x in 0...(numXCells! - 1)
{
for y in 0...(numYCells! - 1)
{
cells[y][x] = Cell(theIndex: (x, y), type: .Wall, thePosition: CGPoint(x: gridLeft + CGFloat(cellSize * x), y: gridBottom + CGFloat(cellSize * y)))
}
}
entranceCell = Cell()
}
func draw(gridLeft : CGFloat, gridBottom : CGFloat, cellSize : CGFloat) -> SKSpriteNode
{
for x in 0...(numXCells! - 1)
{
for y in 0...(numYCells! - 1)
{
tileSprite.addChild(createCell(cells[y][x], cellSize: cellSize))
}
}
return tileSprite
}
func createCell(cell : Cell, cellSize : CGFloat) -> SKSpriteNode
{
var sprite = SKSpriteNode(imageNamed: cell.cellImage)
sprite.name = cell.cellImage.stringByReplacingOccurrencesOfString(".png", withString: "", options: nil, range: nil)
if(sprite.name == "Column")
{
sprite.shadowCastBitMask = 1
sprite.lightingBitMask = 1
}
sprite.anchorPoint = CGPoint(x: 0, y: 0)
sprite.size = CGSizeMake(cellSize, cellSize)
sprite.position = cell.position
return sprite
}
func getCellsOfType(type : Cell.CellType) -> [Cell]
{
var theCells : [Cell] = [Cell]()
for x in 0...(numXCells! - 1)
{
for y in 0...(numYCells! - 1)
{
if(cells[y][x].cellType == type)
{
theCells.append(cells[y][x])
}
}
}
return theCells
}
func getNeighboringCells(cell : Cell, getDiagonals : Bool) -> Dictionary<Dungeon.Direction, Cell>
{
var neighborDictionary : Dictionary<Dungeon.Direction, Cell> = Dictionary<Dungeon.Direction, Cell>()
//North
var neighborCellIndex : (Int, Int) = Dungeon.getNeighborCellindex(cell.index, exitDirection: .North)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .North)
}
//South
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .South)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .South)
}
//East
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .East)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .East)
}
//West
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .West)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .West)
}
if getDiagonals
{
//Northeast
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .Northeast)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .Northeast)
}
//Northwest
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .Northwest)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .Northwest)
}
//Southeast
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .Southeast)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .Southeast)
}
//Southwest
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .Southwest)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .Southwest)
}
}
return neighborDictionary
}
func isValidIndex(theIndex : (Int, Int)) -> Bool
{
return (theIndex.0 >= 0 && theIndex.0 < numXCells && theIndex.1 >= 0 && theIndex.1 < numYCells)
}
//For state searches and such
func getSimplifiedTileState() -> [[Int]]
{
var simplifiedTileState : [[Int]] = Array(count: numYCells, repeatedValue: Array(count: numXCells, repeatedValue: 0))
for x in 0...(numXCells! - 1)
{
for y in 0...(numYCells! - 1)
{
if(cells[y][x].cellType == .Wall)
{
simplifiedTileState[y][x] = 0
}
else if(cells[y][x].characterInCell != nil)
{
if(cells[y][x].characterInCell is Player)
{
simplifiedTileState[y][x] = 1
}
else if(cells[y][x].characterInCell is NPCharacter)
{
simplifiedTileState[y][x] = 2
}
}
else
{
simplifiedTileState[y][x] = 3
}
}
}
return simplifiedTileState
}
}
|
32d7c8f7ef86753b71a6de078d641fe7
| 31.633484 | 163 | 0.544786 | false | false | false | false |
RevenueCat/purchases-ios
|
refs/heads/main
|
Tests/TestingApps/PurchaseTester/PurchaseTester/InitialViewController.swift
|
mit
|
1
|
//
// InitialViewController.swift
// PurchaseTester
//
// Created by Ryan Kotzebue on 1/9/19.
// Copyright © 2019 RevenueCat. All rights reserved.
//
import UIKit
import RevenueCat
class InitialViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Get the latest customerInfo to see if we have a pro cat user or not
Purchases.shared.getCustomerInfo { (customerInfo, error) in
if let e = error {
print(e.localizedDescription)
}
// Route the view depending if we have a premium cat user or not
if customerInfo?.entitlements["pro_cat"]?.isActive == true {
// if we have a pro_cat subscriber, send them to the cat screen
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "cats")
controller.modalPresentationStyle = .fullScreen
self.present(controller, animated: true, completion: nil)
} else {
// if we don't have a pro subscriber, send them to the upsell screen
let controller = SwiftPaywall(
termsOfServiceUrlString: "https://www.revenuecat.com/terms",
privacyPolicyUrlString: "https://www.revenuecat.com/terms")
controller.titleLabel.text = "Upsell Screen"
controller.subtitleLabel.text = "New cats, unlimited cats, personal cat insights and more!"
controller.modalPresentationStyle = .fullScreen
self.present(controller, animated: true, completion: nil)
}
}
}
}
|
da13aff0a76ff27ba326ac1dcc7dafbf
| 37.980392 | 107 | 0.59507 | false | false | false | false |
rambler-digital-solutions/rambler-it-ios
|
refs/heads/develop
|
Carthage/Checkouts/rides-ios-sdk/examples/Swift SDK/Swift SDK/AuthorizationCodeGrantExampleViewController.swift
|
mit
|
1
|
//
// AuthorizationCodeGrantExampleViewController.swift
// Swift SDK
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UberRides
import CoreLocation
/// This class demonstrates how do use the LoginManager to complete Authorization Code Grant Authorization
/// and how to use some of the request endpoints
/// Make sure to replace instances of "YOUR_URL" with the path for your backend service
class AuthorizationCodeGrantExampleViewController: AuthorizationBaseViewController {
fileprivate let states = ["accepted", "arriving", "in_progress", "completed"]
/// The LoginManager to use for login
/// Specify authorization code grant as the loginType to use privileged scopes
let loginManager = LoginManager(loginType: .authorizationCode)
/// The RidesClient to use for endpoints
let ridesClient = RidesClient()
@IBOutlet weak var driverImageView: UIImageView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var loginButton: UIBarButtonItem!
@IBOutlet weak var carLabel: UILabel!
@IBOutlet weak var carImageView: UIImageView!
@IBOutlet weak var driverLabel: UILabel!
@IBOutlet weak var requestButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
loginButton.isEnabled = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let loggedIn = TokenManager.fetchToken() != nil
loginButton.isEnabled = !loggedIn
requestButton.isEnabled = loggedIn
reset()
}
override func reset() {
statusLabel.text = ""
carLabel.text = ""
driverLabel.text = ""
carImageView.image = nil
driverImageView.image = nil
}
@IBAction func login(_ sender: AnyObject) {
// Can define a state variable to prevent tampering
loginManager.state = UUID().uuidString
// Define which scopes we're requesting
// Need to be authorized on your developer dashboard at developer.uber.com
// Privileged scopes can be used by anyone in sandbox for your own account but must be approved for production
let requestedScopes = [RidesScope.request, RidesScope.allTrips]
// Use your loginManager to login with the requested scopes, viewcontroller to present over, and completion block
loginManager.login(requestedScopes: requestedScopes, presentingViewController: self) { (accessToken, error) -> () in
// Error
if let error = error {
self.showMessage(error.localizedDescription)
return
}
// Poll backend for access token
// Replace "YOUR_URL" with the path for your backend service
if let url = URL(string: "YOUR_URL") {
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let data = data,
let jsonString = String(data: data, encoding: String.Encoding.utf8) else {
self.showMessage("Unable to retrieve access token")
return
}
let token = AccessToken(tokenString: jsonString)
// Do any additional work to verify the state passed in earlier
if !TokenManager.save(accessToken: token) {
self.showMessage("Unable to save access token")
} else {
self.showMessage("Saved an AccessToken!")
self.loginButton.isEnabled = false
self.requestButton.isEnabled = true
}
}
}.resume()
}
}
}
@IBAction func requestRide(_ sender: AnyObject) {
// Create ride parameters
self.requestButton.isEnabled = false
let pickupLocation = CLLocation(latitude: 37.770, longitude: -122.466)
let dropoffLocation = CLLocation(latitude: 37.791, longitude: -122.405)
let builder = RideParametersBuilder()
builder.pickupLocation = pickupLocation
builder.pickupNickname = "California Academy of Sciences"
builder.dropoffLocation = dropoffLocation
builder.dropoffNickname = "Pier 39"
builder.productID = "a1111c8c-c720-46c3-8534-2fcdd730040d"
// Use the POST /v1/requests endpoint to make a ride request (in sandbox)
ridesClient.requestRide(parameters: builder.build(), completion: { ride, response in
DispatchQueue.main.async(execute: {
self.checkError(response)
if let ride = ride {
self.statusLabel.text = "Processing"
self.updateRideStatus(ride.requestID, index: 0)
} else {
self.requestButton.isEnabled = true
}
})
})
}
// Uses the the GET /v1/requests/{request_id} endpoint to get information about a ride request
func getRideData(_ requestID: String) {
ridesClient.fetchRideDetails(requestID: requestID) { ride, response in
self.checkError(response)
// Unwrap some optionals for data we want to use
guard let ride = ride,
let driverName = ride.driver?.name,
let driverNumber = ride.driver?.phoneNumber,
let licensePlate = ride.vehicle?.licensePlate,
let make = ride.vehicle?.make,
let model = ride.vehicle?.model,
let driverImage = ride.driver?.pictureURL,
let carImage = ride.vehicle?.pictureURL else {
return
}
// Update the UI on the main thread
DispatchQueue.main.async {
self.driverLabel.text = "\(driverName)\n\(driverNumber)"
self.carLabel.text = "\(make) \(model)\n(\(licensePlate)"
// Asynchronously fetch images
URLSession.shared.dataTask(with: driverImage) {
(data, response, error) in
DispatchQueue.main.async {
guard let data = data else {
return
}
self.driverImageView.image = UIImage(data: data)
}
}.resume()
URLSession.shared.dataTask(with: carImage) {
(data, response, error) in
DispatchQueue.main.async {
guard let data = data else {
return
}
self.carImageView.image = UIImage(data: data)
}
}.resume()
self.updateRideStatus(requestID, index: 1)
}
}
}
// Simulates stepping through ride statuses recursively
func updateRideStatus(_ requestID: String, index: Int) {
guard index < states.count,
let token = TokenManager.fetchToken() else {
return
}
let status = states[index]
// Use the PUT /v1/sandbox/requests/{request_id} to update the ride status
let updateStatusEndpoint = URL(string: "https://sandbox-api.uber.com/v1/sandbox/requests/\(requestID)")!
var request = URLRequest(url: updateStatusEndpoint)
request.httpMethod = "PUT"
request.setValue("Bearer \(token.tokenString!)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
do {
let data = try JSONSerialization.data(withJSONObject: ["status":status], options: .prettyPrinted)
request.httpBody = data
} catch { }
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
if let response = response as? HTTPURLResponse, response.statusCode != 204 {
return
}
self.statusLabel.text = status.capitalized
// Get ride data when in the Accepted state
if status == "accepted" {
self.getRideData(requestID)
return
}
self.delay(2) {
self.updateRideStatus(requestID, index: index+1)
}
}
}.resume()
}
}
|
00262ba6e9b08677f3eeeb6ed094a158
| 41.611111 | 124 | 0.583191 | false | false | false | false |
HabitRPG/habitrpg-ios
|
refs/heads/develop
|
HabitRPG/TableviewCells/CustomRewardCell.swift
|
gpl-3.0
|
1
|
//
// CustomRewrdCell.swift
// Habitica
//
// Created by Phillip on 21.08.17.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import UIKit
import Habitica_Models
import Down
class CustomRewardCell: UICollectionViewCell {
@IBOutlet weak var mainRewardWrapper: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var notesLabel: UILabel!
@IBOutlet weak var currencyImageView: UIImageView!
@IBOutlet weak var amountLabel: AbbreviatedNumberLabel!
@IBOutlet weak var buyButton: UIView!
var onBuyButtonTapped: (() -> Void)?
public var canAfford: Bool = false {
didSet {
if canAfford {
currencyImageView.alpha = 1.0
buyButton.backgroundColor = UIColor.yellow500.withAlphaComponent(0.3)
if ThemeService.shared.theme.isDark {
amountLabel.textColor = UIColor.yellow50
} else {
amountLabel.textColor = UIColor.yellow1.withAlphaComponent(0.85)
}
} else {
currencyImageView.alpha = 0.6
buyButton.backgroundColor = ThemeService.shared.theme.offsetBackgroundColor.withAlphaComponent(0.5)
amountLabel.textColor = ThemeService.shared.theme.dimmedTextColor
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
currencyImageView.image = HabiticaIcons.imageOfGold
buyButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(buyButtonTapped)))
}
func configure(reward: TaskProtocol) {
let theme = ThemeService.shared.theme
titleLabel.font = CustomFontMetrics.scaledSystemFont(ofSize: 15)
if let text = reward.text {
titleLabel.attributedText = try? Down(markdownString: text.unicodeEmoji).toHabiticaAttributedString(baseSize: 15, textColor: theme.primaryTextColor)
} else {
titleLabel.text = ""
}
notesLabel.font = CustomFontMetrics.scaledSystemFont(ofSize: 11)
if let trimmedNotes = reward.notes?.trimmingCharacters(in: .whitespacesAndNewlines), trimmedNotes.isEmpty == false {
notesLabel.attributedText = try? Down(markdownString: trimmedNotes.unicodeEmoji).toHabiticaAttributedString(baseSize: 11, textColor: theme.secondaryTextColor)
notesLabel.isHidden = false
} else {
notesLabel.isHidden = true
}
amountLabel.text = String(reward.value)
backgroundColor = theme.contentBackgroundColor
mainRewardWrapper.backgroundColor = theme.windowBackgroundColor
titleLabel.textColor = theme.primaryTextColor
notesLabel.textColor = theme.ternaryTextColor
}
@objc
func buyButtonTapped() {
if let action = onBuyButtonTapped {
action()
}
}
}
|
2bc1dd48db01d8724633d651e67f7e7a
| 36.435897 | 170 | 0.654452 | false | false | false | false |
liujinlongxa/AnimationTransition
|
refs/heads/master
|
testTransitioning/NormalFirstViewController.swift
|
mit
|
1
|
//
// NormalFirstViewController.swift
// AnimationTransition
//
// Created by Liujinlong on 8/12/15.
// Copyright © 2015 Jaylon. All rights reserved.
//
import UIKit
class NormalFirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// 设置模态的过场动画类型
if segue.identifier == "normalSegue1" {
segue.destination.modalTransitionStyle = UIModalTransitionStyle.flipHorizontal
}
else if segue.identifier == "normalSegue2" {
segue.destination.modalTransitionStyle = UIModalTransitionStyle.partialCurl
}
}
@IBAction func clickFirstButton(_ sender: AnyObject) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "normalSecondVC")
//设置过场动画
let transiton = CATransition()
transiton.type = "cube"
transiton.subtype = kCATransitionFromRight
self.navigationController!.view.layer.add(transiton, forKey: "transitionAnimation")
vc.view.backgroundColor = UIColor.orange
self.navigationController?.pushViewController(vc
, animated: false)
}
@IBAction func clickSecondButton(_ sender: AnyObject) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "normalSecondVC")
//设置过场动画
let transiton = CATransition()
transiton.type = "pageCurl"
self.navigationController!.view.layer.add(transiton, forKey: "transitionAnimation")
vc.view.backgroundColor = UIColor.orange
self.navigationController?.pushViewController(vc
, animated: false)
}
@IBAction func unwindForSegue(_ unwindSegue:UIStoryboardSegue) {
}
}
|
f98c38800052df6bdaa74df9a8ceea00
| 29.571429 | 116 | 0.648598 | false | false | false | false |
AckeeCZ/ACKategories
|
refs/heads/master
|
ACKategoriesExample/Screens/VC composition/TitleViewController.swift
|
mit
|
1
|
//
// TitleViewController.swift
// ACKategories
//
// Created by Jakub Olejník on 12/09/2018.
// Copyright © 2018 Ackee, s.r.o. All rights reserved.
//
import UIKit
import ACKategories
class TitleViewController: BaseViewControllerNoVM {
private(set) weak var nameLabel: UILabel!
private let name: String
private let color: UIColor
// MARK: Initializers
init(name: String, color: UIColor) {
self.name = name
self.color = color
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View life cycle
override func loadView() {
super.loadView()
view.backgroundColor = color
let nameLabel = UILabel()
nameLabel.textAlignment = .center
nameLabel.text = name
view.addSubview(nameLabel)
nameLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
nameLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
nameLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20),
nameLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20)
])
self.nameLabel = nameLabel
}
}
|
e3c8a60967e15b0afcc64aebc63dd587
| 26.857143 | 112 | 0.671795 | false | false | false | false |
Paulinechi/Swift-Pauline
|
refs/heads/master
|
day3/day3HW.playground/section-1.swift
|
mit
|
1
|
// Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//Q0
func printNumber(N: Int){
print(N)
if N > 0{
printNumber(N)
}
}
//Q1
class Recursion {
func printNumber(N: Int){
print(N)
if N > 1 {
printNumber(N - 1)
}
println(N)
}
}
//Q2
void; reverseWords( char * , str);_ = {
Int; i = 0;
char*; subStrStart;
char*; subStrEnd;
char*; currentPos;
currentPos = str;
while(*currentPos!=\0)
{
subStrStart = currentPos;
while(*currentPos!= "", &&*currentPos!=\0)
currentPos++;
subStrEnd = currentPos - 1;
reverseStr(str, (int)(subStrStart - str), (int)(subStrEnd - str));
currentPos++;
}
return;
}
Int(); main()
{
char; Str[20] = "I am a student.";
reverseStr(str, 0, strlen(str)-1 );
reverseWords(str);
printf("%s\n", str);
return 0;
}
//Q3
for (i) 1-n
push (ai)
pop (an)
min = an
for (i = n - 1 to n)
pop (ai)
if(ai < min){
min = ai
}
//Q4
/*void HeapAdjust(Int array[], Int i , Int , Length){
Int child , temp;
for(temp=array[i];2*i+1<Length;i=child)
{
child = 2*i+1;
if(child<Length-1 && array[child+1]<array[child]){
}
child++;
if (temp>array[child]){
}
array[i]=array[child];
} else{
break;
array[child]=temp;
}
}
void; Swap(int*, a,Int* b )
_ = {
*a=*a^*b;
*b=*a^*b;
*a=*a^*b;
}
Int GetMin( Int array[], Int Length, Int k)
{
int min=array[0];
Swap(&array[0],&array[Length-1]);
int child,temp;
int i=0,j=k-1;
for (temp=array[0]; j>0 && 2*i+1<Length; --j,i=child)
{
child = 2*i+1;
if(child<Length-1 && array[child+1]<array[child])
child++;
if (temp>array[child])
array[i]=array[child];
else
break;
array[child]=temp;
}
return min;
}
void Kmin(int array[] , int Length , int k)
{
for(int i=Length/2-1;i>=0;--i)
//初始建堆,时间复杂度为O(n)
HeapAdjust(array,i,Length);
int j=Length;
for(i=k;i>0;--i,--j)
//k次循环,每次循环的复杂度最多为k次交换,复杂度为o(k^2)
{
int min=GetMin(array,j,i);
printf("%d,", min);
}
}
Int main()
{
int array[MAXLEN];
for(int i=MAXLEN;i>0;--i)
array[MAXLEN-i] = i;
Kmin(array,MAXLEN,K);
return 0;
}
*/
//Q5
/*
6架
三架从一个方向起飞,到1/8路程时第一架将2 3加满油返回,到1/4时,2将3加满返回,3到1/2时,456从另一方向起飞,456飞行过程与123一致,3与6将在3/4相遇,6这时是满油,分一半给3就可以了。所以是6架。
//Q6
//Q7
//intergration
|
2b265e480dbdc50dd7b76c21c58bd411
| 14.152542 | 110 | 0.494407 | false | false | false | false |
MangoMade/MMNavigationController
|
refs/heads/master
|
Source/UIViewControllerExtension.swift
|
mit
|
1
|
//
// UIViewControllerExtension.swift
// MMNavigationController
//
// Created by Mango on 2017/4/9.
// Copyright © 2017年 MangoMade. All rights reserved.
//
import UIKit
extension UIViewController: NamespaceWrappable { }
private extension TypeWrapper {
var viewController: T {
return wrapperObject
}
}
fileprivate struct AssociatedKey {
static var viewWillAppearInjectBlock = 0
static var navigationBarHidden = 0
static var popGestrueEnable = 0
static var navigationBarBackgroundColor = 0
static var popGestrueEnableWidth = 0
static var navigationBarTitleColor = 0
static var gestureDelegate = 0
}
public extension TypeWrapper where T: UIViewController {
/// 在AppDelegate中调用此方法
public static func load() {
UIViewController.methodsSwizzling
}
/// navigationBar 是否隐藏
public var navigationBarHidden: Bool {
get {
var hidden = objc_getAssociatedObject(self.viewController, &AssociatedKey.navigationBarHidden) as? NSNumber
if hidden == nil {
hidden = NSNumber(booleanLiteral: false)
objc_setAssociatedObject(self.viewController,
&AssociatedKey.navigationBarHidden,
hidden,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return hidden!.boolValue
}
set {
objc_setAssociatedObject(self.viewController,
&AssociatedKey.navigationBarHidden,
NSNumber(booleanLiteral: newValue),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// pop 手势是否可用
public var popGestrueEnable: Bool {
get {
var enable = objc_getAssociatedObject(self.viewController, &AssociatedKey.popGestrueEnable) as? NSNumber
if enable == nil {
enable = NSNumber(booleanLiteral: true)
objc_setAssociatedObject(self.viewController,
&AssociatedKey.popGestrueEnable,
enable,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return enable!.boolValue
}
set {
objc_setAssociatedObject(self.viewController,
&AssociatedKey.popGestrueEnable,
NSNumber(booleanLiteral: newValue),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// pop手势可用宽度,从左开始计算
public var popGestrueEnableWidth: CGFloat {
get {
var width = objc_getAssociatedObject(self.viewController, &AssociatedKey.popGestrueEnableWidth) as? NSNumber
if width == nil {
width = NSNumber(floatLiteral: 0)
objc_setAssociatedObject(self.viewController,
&AssociatedKey.popGestrueEnableWidth,
width,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return CGFloat(width!.floatValue)
}
set {
objc_setAssociatedObject(self.viewController,
&AssociatedKey.popGestrueEnableWidth,
NSNumber(floatLiteral: Double(newValue)),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// navigationBar 背景颜色
public var navigationBarBackgroundColor: UIColor? {
get {
return objc_getAssociatedObject(self.viewController, &AssociatedKey.navigationBarBackgroundColor) as? UIColor
}
set {
objc_setAssociatedObject(self.viewController, &AssociatedKey.navigationBarBackgroundColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// navigationBar 标题字体颜色
public var navigationBarTitleColor: UIColor? {
get {
return objc_getAssociatedObject(self.viewController, &AssociatedKey.navigationBarTitleColor) as? UIColor
}
set {
objc_setAssociatedObject(self.viewController, &AssociatedKey.navigationBarTitleColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// gesture delegate
/// 可以通过设置这个代理,实现代理方法,解决手势冲突等问题
public weak var gestureDelegate: UIGestureRecognizerDelegate? {
get {
return gestureDelegateWrapper.instance
}
set {
gestureDelegateWrapper.instance = newValue
}
}
private var gestureDelegateWrapper: WeakReferenceWrapper<UIGestureRecognizerDelegate> {
var wrapper = objc_getAssociatedObject(self.viewController, &AssociatedKey.gestureDelegate) as? WeakReferenceWrapper<UIGestureRecognizerDelegate>
if wrapper == nil {
wrapper = WeakReferenceWrapper<UIGestureRecognizerDelegate>()
objc_setAssociatedObject(self.viewController, &AssociatedKey.gestureDelegate, wrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return wrapper!
}
internal var viewWillAppearInjectBlock: ViewControllerInjectBlockWrapper? {
get {
return objc_getAssociatedObject(self.viewController, &AssociatedKey.viewWillAppearInjectBlock) as? ViewControllerInjectBlockWrapper
}
set {
objc_setAssociatedObject(self.viewController, &AssociatedKey.viewWillAppearInjectBlock, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
extension UIViewController {
fileprivate static let methodsSwizzling: () = {
guard let originalViewWillAppearSelector = class_getInstanceMethod(UIViewController.self, #selector(viewWillAppear(_:))),
let swizzledViewWillAppearSelector = class_getInstanceMethod(UIViewController.self, #selector(mm_viewWillAppear(_:))) else {
return
}
method_exchangeImplementations(originalViewWillAppearSelector, swizzledViewWillAppearSelector)
}()
// MARK - private methods
@objc fileprivate func mm_viewWillAppear(_ animated: Bool) {
mm_viewWillAppear(animated)
mm.viewWillAppearInjectBlock?.block?(self, animated)
}
}
|
e6b56ed6ee773d9722a846f0aebb3d97
| 37.939394 | 153 | 0.602957 | false | false | false | false |
wangyuanou/Coastline
|
refs/heads/master
|
Coastline/Paint/AttributeString+Doc.swift
|
mit
|
1
|
//
// AttributeString+Html.swift
// Coastline
//
// Created by 王渊鸥 on 2016/9/25.
// Copyright © 2016年 王渊鸥. All rights reserved.
//
import UIKit
public extension NSAttributedString {
public convenience init?(html:String) {
let options = [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue] as [String : Any]
if let data = html.data(using: .utf8, allowLossyConversion: true) {
try? self.init(data: data, options: options, documentAttributes: nil)
} else {
return nil
}
}
@available(iOS 9.0, *)
public convenience init?(rtfUrl:String) {
let options = [NSDocumentTypeDocumentAttribute : NSRTFTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue] as [String : Any]
guard let url = rtfUrl.url else { return nil }
try? self.init(url: url, options: options, documentAttributes: nil)
}
@available(iOS 9.0, *)
public convenience init?(rtfdUrl:String) {
let options = [NSDocumentTypeDocumentAttribute : NSRTFDTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue] as [String : Any]
guard let url = rtfdUrl.url else { return nil }
try? self.init(url: url, options: options, documentAttributes: nil)
}
}
|
d48431822eb56665bc19678458cf4f2c
| 34.945946 | 104 | 0.716541 | false | false | false | false |
ji3g4m6zo6/bookmark
|
refs/heads/master
|
Pods/BarcodeScanner/Sources/Config.swift
|
mit
|
1
|
import UIKit
import AVFoundation
// MARK: - Configurations
public struct Title {
public static var text = NSLocalizedString("Scan barcode", comment: "")
public static var font = UIFont.boldSystemFont(ofSize: 17)
public static var color = UIColor.black
}
public struct CloseButton {
public static var text = NSLocalizedString("Close", comment: "")
public static var font = UIFont.boldSystemFont(ofSize: 17)
public static var color = UIColor.black
}
public struct SettingsButton {
public static var text = NSLocalizedString("Settings", comment: "")
public static var font = UIFont.boldSystemFont(ofSize: 17)
public static var color = UIColor.white
}
public struct Info {
public static var text = NSLocalizedString(
"Place the barcode within the window to scan. The search will start automatically.", comment: "")
public static var loadingText = NSLocalizedString(
"Looking for your product...", comment: "")
public static var notFoundText = NSLocalizedString(
"No product found.", comment: "")
public static var settingsText = NSLocalizedString(
"In order to scan barcodes you have to allow camera under your settings.", comment: "")
public static var font = UIFont.boldSystemFont(ofSize: 14)
public static var textColor = UIColor.black
public static var tint = UIColor.black
public static var loadingFont = UIFont.boldSystemFont(ofSize: 16)
public static var loadingTint = UIColor.black
public static var notFoundTint = UIColor.red
}
/**
Returns image with a given name from the resource bundle.
- Parameter name: Image name.
- Returns: An image.
*/
func imageNamed(_ name: String) -> UIImage {
let cls = BarcodeScannerController.self
var bundle = Bundle(for: cls)
let traitCollection = UITraitCollection(displayScale: 3)
if let path = bundle.resourcePath,
let resourceBundle = Bundle(path: path + "/BarcodeScanner.bundle") {
bundle = resourceBundle
}
guard let image = UIImage(named: name, in: bundle,
compatibleWith: traitCollection)
else { return UIImage() }
return image
}
/**
`AVCaptureMetadataOutput` metadata object types.
*/
public var metadata = [
AVMetadataObjectTypeUPCECode,
AVMetadataObjectTypeCode39Code,
AVMetadataObjectTypeCode39Mod43Code,
AVMetadataObjectTypeEAN13Code,
AVMetadataObjectTypeEAN8Code,
AVMetadataObjectTypeCode93Code,
AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypePDF417Code,
AVMetadataObjectTypeQRCode,
AVMetadataObjectTypeAztecCode
]
|
006f1a546c52ebd71a8206a34f18fbf9
| 29.851852 | 101 | 0.752701 | false | false | false | false |
nhojb/SyncthingBar
|
refs/heads/master
|
SyncthingBar/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// SyncthingBar
//
// Created by John on 11/11/2016.
// Copyright © 2016 Olive Toast Software Ltd. All rights reserved.
//
import Cocoa
let kSyncthingURLDefaultsKey = "SyncthingURL"
let kSyncthingAPIKeyDefaultsKey = "SyncthingAPIKey"
let kSyncthingPathDefaultsKey = "SyncthingPath"
let kSyncthingLaunchDefaultsKey = "LaunchAtStartup"
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
@IBOutlet weak var statusMenu: NSMenu!
@IBOutlet weak var connectedMenuItem: NSMenuItem!
var connected: Bool = false {
didSet {
if let client = self.client, connected {
self.statusItem.button?.image = NSImage(named: "SyncthingEnabled")
self.connectedMenuItem.title = "Connected - \(client.url)"
} else {
self.statusItem.button?.image = NSImage(named: "SyncthingDisabled")
self.connectedMenuItem.title = "Not Connected"
}
}
}
private lazy var webViewWindowController: WebViewWindowController = WebViewWindowController(windowNibName: "WebViewWindow")
private lazy var preferencesWindowController: PreferencesWindowController = PreferencesWindowController(windowNibName: "PreferencesWindow")
private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
private var client: SyncthingClient?
private var syncthing: Process?
private var syncthingPath: String?
private var launchSyncthing = true
func registerDefaults() {
UserDefaults.standard.register(defaults: [kSyncthingURLDefaultsKey: "http://127.0.0.1:8384",
kSyncthingPathDefaultsKey: "/usr/local/bin/syncthing",
kSyncthingLaunchDefaultsKey: true])
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
self.registerDefaults()
self.statusItem.menu = self.statusMenu
self.statusItem.button?.image = NSImage(named: "SyncthingDisabled")
self.launchSyncthing = UserDefaults.standard.bool(forKey: kSyncthingLaunchDefaultsKey)
self.syncthingPath = UserDefaults.standard.string(forKey: kSyncthingPathDefaultsKey)
self.updateClient()
self.updateSyncthing()
if self.client == nil {
self.openPreferences(self)
}
_ = NotificationCenter.default.addObserver(forName: PreferencesWindowController.preferencesDidCloseNotification,
object: nil,
queue: nil) { [weak self] notification in
self?.updateClient()
self?.updateSyncthing()
}
}
func applicationWillTerminate(_ aNotification: Notification) {
self.syncthing?.terminate()
}
func updateClient() {
guard let url = UserDefaults.standard.url(forKey: kSyncthingURLDefaultsKey) else {
return
}
// TODO: Store in keychain?
guard let apiKey = UserDefaults.standard.object(forKey: kSyncthingAPIKeyDefaultsKey) as? String else {
return
}
self.client = SyncthingClient(url: url, apiKey: apiKey)
self.client?.ping { [weak self] ok, error in
assert(Thread.isMainThread)
self?.connected = ok
}
}
func updateSyncthing() {
let launchSyncthing = UserDefaults.standard.bool(forKey: kSyncthingLaunchDefaultsKey)
let syncthingPath = UserDefaults.standard.string(forKey: kSyncthingPathDefaultsKey)
if launchSyncthing != self.launchSyncthing || syncthingPath != self.syncthingPath {
self.stopSyncthing()
}
self.launchSyncthing = launchSyncthing
self.syncthingPath = syncthingPath
if launchSyncthing {
self.startSyncthing()
}
}
func startSyncthing() {
guard self.syncthing == nil else {
return
}
guard let syncthingPath = self.syncthingPath else {
return
}
// syncthing -no-browser
if Processes.find(processName: "syncthing") == nil {
self.syncthing = Process.launchedProcess(launchPath: syncthingPath, arguments: ["-no-browser"])
} else {
print("syncthing already running!")
}
// Poll until the server is launched:
self.client?.checkConnection(repeating: 5) { [weak self] ok, error in
assert(Thread.isMainThread)
self?.connected = ok
}
}
func stopSyncthing() {
guard self.syncthing != nil else {
return
}
self.syncthing?.terminate()
self.syncthing?.waitUntilExit()
self.syncthing = nil
self.client?.ping { [weak self] ok, error in
assert(Thread.isMainThread)
self?.connected = ok
}
}
@IBAction func openPreferences(_ sender: Any) {
NSApplication.shared.activate(ignoringOtherApps: true)
self.preferencesWindowController.showWindow(self)
}
@IBAction func openSyncthing(_ sender: Any) {
// User UserDefaults url in case the API key has not yet been set (user can still connect via browser).
if let url = UserDefaults.standard.url(forKey: kSyncthingURLDefaultsKey) {
NSApplication.shared.activate(ignoringOtherApps: true)
self.webViewWindowController.showWindow(self)
let request = URLRequest(url: url)
self.webViewWindowController.webView?.load(request)
}
}
// NSMenuDelegate
func menuWillOpen(_ menu: NSMenu) {
self.client?.ping { [weak self] ok, error in
assert(Thread.isMainThread)
self?.connected = ok
}
}
}
|
ca5c4ba9c74f67dea51a25f517f7ee32
| 31.519337 | 143 | 0.631668 | false | false | false | false |
exchangegroup/paged-scroll-view-with-images
|
refs/heads/master
|
paged-scroll-view-with-images/TegColors.swift
|
mit
|
2
|
import UIKit
enum TegColor: String {
case Bag = "#2bb999"
case Heart = "#ea3160"
case Shade10 = "#000000"
case Shade20 = "#1C1C1C"
case Shade30 = "#383838"
case Shade40 = "#545454"
case Shade50 = "#707070"
case Shade60 = "#8C8C8C"
case Shade70 = "#A8A8A8"
case Shade80 = "#C4C4C4"
case Shade90 = "#E0E0E0"
case Shade95 = "#F0F0F0"
case Shade100 = "#FFFFFF"
var uiColor: UIColor {
return TegUIColor.fromHexString(rawValue)
}
}
|
d09c4e90a4fb87672a6c12dea01bd391
| 20.318182 | 45 | 0.637527 | false | false | false | false |
sonsongithub/reddift
|
refs/heads/master
|
test/CAPTCHATest.swift
|
mit
|
1
|
//
// CAPTCHATest.swift
// reddift
//
// Created by sonson on 2015/05/07.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import XCTest
#if os(iOS)
import UIKit
#endif
class CAPTCHATest: SessionTestSpec {
// now, CAPTCHA API does not work.....?
// func testCheckWhetherCAPTCHAIsNeededOrNot() {
// let msg = "is true or false as Bool"
// print(msg)
// var check_result: Bool? = nil
// let documentOpenExpectation = self.expectation(description: msg)
// do {
// try self.session?.checkNeedsCAPTCHA({(result) -> Void in
// switch result {
// case .failure(let error):
// print(error)
// case .success(let check):
// check_result = check
// }
// XCTAssert(check_result != nil, msg)
// documentOpenExpectation.fulfill()
// })
// } catch { XCTFail((error as NSError).description) }
// self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
// }
// now, CAPTCHA API does not work.....?
// func testGetIdenForNewCAPTCHA() {
// let msg = "is String"
// print(msg)
// var iden: String? = nil
// let documentOpenExpectation = self.expectation(description: msg)
// do {
// try self.session?.getIdenForNewCAPTCHA({ (result) -> Void in
// switch result {
// case .failure(let error):
// print(error.description)
// case .success(let identifier):
// iden = identifier
// }
// XCTAssert(iden != nil, msg)
// documentOpenExpectation.fulfill()
// })
// } catch { XCTFail((error as NSError).description) }
// self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
// }
// now, CAPTCHA API does not work.....?
// func testSizeOfNewImageGeneratedUsingIden() {
// let msg = "is 120x50"
// print(msg)
//#if os(iOS) || os(tvOS)
// var size: CGSize? = nil
//#elseif os(macOS)
// var size: NSSize? = nil
//#endif
// let documentOpenExpectation = self.expectation(description: msg)
// do {
// try self.session?.getIdenForNewCAPTCHA({ (result) -> Void in
// switch result {
// case .failure(let error):
// print(error.description)
// case .success(let string):
// try! self.session?.getCAPTCHA(string, completion: { (result) -> Void in
// switch result {
// case .failure(let error):
// print(error.description)
// case .success(let image):
// size = image.size
// }
// documentOpenExpectation.fulfill()
// })
// }
// })
// } catch { XCTFail((error as NSError).description) }
// self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
//
// if let size = size {
//#if os(iOS)
// XCTAssert(size == CGSize(width: 120, height: 50), msg)
//#elseif os(macOS)
// XCTAssert(size == NSSize(width: 120, height: 50), msg)
//#endif
// } else {
// XCTFail(msg)
// }
// }
}
|
a691831e836b4094ed944c1221e09226
| 33.49505 | 93 | 0.504018 | false | true | false | false |
SSU-CS-Department/ssumobile-ios
|
refs/heads/master
|
SSUMobile/Modules/Resources/Views/SSUResourcesViewController.swift
|
apache-2.0
|
1
|
//
// SSUResourcesViewController.swift
// SSUMobile
//
// Created by Eric Amorde on 10/5/14.
// Copyright (c) 2014 Sonoma State University Department of Computer Science. All rights reserved.
//
import Foundation
class SSUResourcesViewController: SSUCoreDataTableViewController<SSUResourcesEntry> {
var context: NSManagedObjectContext {
return SSUResourcesModule.instance.context
}
var selectedIndexPath: IndexPath?
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorColor = .ssuBlue
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension;
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(self.refresh), for: .valueChanged)
// Remove search button
navigationItem.rightBarButtonItem = nil
setupCoreData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadData()
}
@objc func refresh() {
SSUResourcesModule.instance.updateData { [weak self] in
DispatchQueue.main.async {
self?.refreshControl?.endRefreshing()
}
}
}
func setupCoreData() {
let sortDescriptors: [NSSortDescriptor] = [
NSSortDescriptor(key: "section.position", ascending: true),
NSSortDescriptor(key: "id", ascending: true)
]
let request: NSFetchRequest<SSUResourcesEntry> = SSUResourcesEntry.fetchRequest()
request.sortDescriptors = sortDescriptors
fetchedResultsController = NSFetchedResultsController<SSUResourcesEntry>(fetchRequest: request,
managedObjectContext: context,
sectionNameKeyPath: "section.position",
cacheName: nil)
}
// MARK: UITableView
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let info = fetchedResultsController?.sections?[section]
if let firstResource = info?.objects?.first as? SSUResourcesEntry {
return firstResource.section?.name
}
return nil
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SSUResourcesCell
let resource = object(atIndex: indexPath)
cell.titleLabel.text = resource.name
cell.phoneLabel.textColor = .ssuBlue
cell.phoneLabel.text = resource.phone
cell.urlLabel.text = resource.url?.replacingOccurrences(of: "http://", with: "").replacingOccurrences(of: "www.", with: "")
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let resource = object(atIndex: indexPath)
if resource.phone == nil && resource.url == nil {
SSULogging.logError("Resource selected but missing phone and url: \(resource)")
return
}
selectedIndexPath = indexPath
let controller = UIAlertController(title: resource.name, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
if let phone = resource.phone, !phone.isEmpty {
let title = "Call \(phone)"
controller.addAction(UIAlertAction(title: title, style: .default, handler: { (_) in
self.callPhoneNumber(phone)
}))
}
if let urlString = resource.url, let url = URL(string: urlString) {
let title = "Open in Safari"
controller.addAction(UIAlertAction(title: title, style: .default, handler: { (_) in
self.openURL(url)
}))
}
present(controller, animated: true, completion: nil)
}
func callPhoneNumber(_ phone: String) {
if let url = URL(string: "tel://\(phone))"), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
} else {
SSULogging.logError("Unable to call phone number \(phone)")
}
}
func openURL(_ url: URL) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
} else {
SSULogging.logError("Unable to open url \(url)")
}
}
}
|
3f26b6d939004a16d6fcdbfbc3993ecf
| 36.141732 | 131 | 0.614374 | false | false | false | false |
february29/Learning
|
refs/heads/master
|
swift/Fch_Contact/Fch_Contact/AppClasses/ViewController/FontViewController.swift
|
mit
|
1
|
//
// FontViewController.swift
// Fch_Contact
//
// Created by bai on 2018/1/15.
// Copyright © 2018年 北京仙指信息技术有限公司. All rights reserved.
//
import UIKit
import SnapKit
class FontViewController: BBaseViewController ,UITableViewDelegate,UITableViewDataSource{
let dataArray = [FontSize.small,FontSize.middle,FontSize.large]
lazy var tableView:UITableView = {
let table = UITableView.init(frame: CGRect.zero, style: .grouped);
table.showsVerticalScrollIndicator = false;
table.showsHorizontalScrollIndicator = false;
// table.estimatedRowHeight = 30;
table.delegate = self;
table.dataSource = self;
table.setBackgroundColor(.tableBackground);
table.setSeparatorColor(.primary);
table.register(FontTableViewCell.self, forCellReuseIdentifier: "cell")
table.rowHeight = UITableViewAutomaticDimension;
// table.separatorStyle = .none;
table.tableFooterView = UIView();
return table;
}();
override func viewDidLoad() {
super.viewDidLoad()
self.title = BLocalizedString(key: "Font Size");
self.view.addSubview(self.tableView);
self.tableView.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalToSuperview();
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = FontTableViewCell.init(style: .default, reuseIdentifier: "cell");
cell.coloumLable1?.text = dataArray[indexPath.row].displayName;
if indexPath.row == 0 {
cell.coloumLable1?.font = UIFont.systemFont(ofSize: 11);
}else if indexPath.row == 1{
cell.coloumLable1?.font = UIFont.systemFont(ofSize: 13);
}else{
cell.coloumLable1?.font = UIFont.systemFont(ofSize: 15);
}
// cell.setSelected(true, animated: false);
return cell;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
FontCenter.shared.fontSize = dataArray[indexPath.row] ;
let setting = UserDefaults.standard.getUserSettingModel()
setting.fontSize = dataArray[indexPath.row];
UserDefaults.standard.setUserSettingModel(model: setting);
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 1;
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 45;
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return UIView();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
d880373f673751e27d09c9de2812fea5
| 27.95283 | 100 | 0.622353 | false | false | false | false |
ianyh/Amethyst
|
refs/heads/development
|
Amethyst/Layout/Layouts/BinarySpacePartitioningLayout.swift
|
mit
|
1
|
//
// BinarySpacePartitioningLayout.swift
// Amethyst
//
// Created by Ian Ynda-Hummel on 5/29/16.
// Copyright © 2016 Ian Ynda-Hummel. All rights reserved.
//
import Silica
class TreeNode<Window: WindowType>: Codable {
typealias WindowID = Window.WindowID
private enum CodingKeys: String, CodingKey {
case left
case right
case windowID
}
weak var parent: TreeNode?
var left: TreeNode?
var right: TreeNode?
var windowID: WindowID?
init() {}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.left = try values.decodeIfPresent(TreeNode.self, forKey: .left)
self.right = try values.decodeIfPresent(TreeNode.self, forKey: .right)
self.windowID = try values.decodeIfPresent(WindowID.self, forKey: .windowID)
self.left?.parent = self
self.right?.parent = self
guard valid else {
throw LayoutDecodingError.invalidLayout
}
}
var valid: Bool {
return (left != nil && right != nil && windowID == nil) || (left == nil && right == nil && windowID != nil)
}
func findWindowID(_ windowID: WindowID) -> TreeNode? {
guard self.windowID == windowID else {
return left?.findWindowID(windowID) ?? right?.findWindowID(windowID)
}
return self
}
func orderedWindowIDs() -> [WindowID] {
guard let windowID = windowID else {
let leftWindowIDs = left?.orderedWindowIDs() ?? []
let rightWindowIDs = right?.orderedWindowIDs() ?? []
return leftWindowIDs + rightWindowIDs
}
return [windowID]
}
func insertWindowIDAtEnd(_ windowID: WindowID) {
guard left == nil && right == nil else {
right?.insertWindowIDAtEnd(windowID)
return
}
insertWindowID(windowID)
}
func insertWindowID(_ windowID: WindowID, atPoint insertionPoint: WindowID) {
guard self.windowID == insertionPoint else {
left?.insertWindowID(windowID, atPoint: insertionPoint)
right?.insertWindowID(windowID, atPoint: insertionPoint)
return
}
insertWindowID(windowID)
}
func removeWindowID(_ windowID: WindowID) {
guard let node = findWindowID(windowID) else {
log.error("Trying to remove window not in tree")
return
}
guard let parent = node.parent else {
return
}
guard let grandparent = parent.parent else {
if node == parent.left {
parent.windowID = parent.right?.windowID
} else {
parent.windowID = parent.left?.windowID
}
parent.left = nil
parent.right = nil
return
}
if parent == grandparent.left {
if node == parent.left {
grandparent.left = parent.right
} else {
grandparent.left = parent.left
}
grandparent.left?.parent = grandparent
} else {
if node == parent.left {
grandparent.right = parent.right
} else {
grandparent.right = parent.left
}
grandparent.right?.parent = grandparent
}
}
func insertWindowID(_ windowID: WindowID) {
guard parent != nil || self.windowID != nil else {
self.windowID = windowID
return
}
if let parent = parent {
let newParent = TreeNode()
let newNode = TreeNode()
newNode.parent = newParent
newNode.windowID = windowID
newParent.left = self
newParent.right = newNode
newParent.parent = parent
if self == parent.left {
parent.left = newParent
} else {
parent.right = newParent
}
self.parent = newParent
} else {
let newSelf = TreeNode()
let newNode = TreeNode()
newSelf.windowID = self.windowID
self.windowID = nil
newNode.windowID = windowID
left = newSelf
left?.parent = self
right = newNode
right?.parent = self
}
}
}
extension TreeNode: Equatable {
static func == (lhs: TreeNode, rhs: TreeNode) -> Bool {
return lhs.windowID == rhs.windowID && lhs.left == rhs.left && lhs.right == rhs.right
}
}
class BinarySpacePartitioningLayout<Window: WindowType>: StatefulLayout<Window> {
typealias WindowID = Window.WindowID
private typealias TraversalNode = (node: TreeNode<Window>, frame: CGRect)
private enum CodingKeys: String, CodingKey {
case rootNode
}
override static var layoutName: String { return "Binary Space Partitioning" }
override static var layoutKey: String { return "bsp" }
override var layoutDescription: String { return "\(lastKnownFocusedWindowID.debugDescription)" }
private var rootNode = TreeNode<Window>()
private var lastKnownFocusedWindowID: WindowID?
required init() {
super.init()
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.rootNode = try container.decode(TreeNode<Window>.self, forKey: .rootNode)
super.init()
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(rootNode, forKey: .rootNode)
}
private func constructInitialTreeWithWindows(_ windows: [LayoutWindow<Window>]) {
for window in windows {
guard rootNode.findWindowID(window.id) == nil else {
continue
}
rootNode.insertWindowIDAtEnd(window.id)
if window.isFocused {
lastKnownFocusedWindowID = window.id
}
}
}
override func updateWithChange(_ windowChange: Change<Window>) {
switch windowChange {
case let .add(window):
guard rootNode.findWindowID(window.id()) == nil else {
log.warning("Trying to add a window already in the tree")
return
}
if let insertionPoint = lastKnownFocusedWindowID, window.id() != insertionPoint {
log.info("insert \(window) - \(window.id()) at point: \(insertionPoint)")
rootNode.insertWindowID(window.id(), atPoint: insertionPoint)
} else {
log.info("insert \(window) - \(window.id()) at end")
rootNode.insertWindowIDAtEnd(window.id())
}
if window.isFocused() {
lastKnownFocusedWindowID = window.id()
}
case let .remove(window):
log.info("remove: \(window) - \(window.id())")
rootNode.removeWindowID(window.id())
case let .focusChanged(window):
lastKnownFocusedWindowID = window.id()
case let .windowSwap(window, otherWindow):
let windowID = window.id()
let otherWindowID = otherWindow.id()
guard let windowNode = rootNode.findWindowID(windowID), let otherWindowNode = rootNode.findWindowID(otherWindowID) else {
log.error("Tried to perform an unbalanced window swap: \(windowID) <-> \(otherWindowID)")
return
}
windowNode.windowID = otherWindowID
otherWindowNode.windowID = windowID
case .applicationDeactivate, .applicationActivate, .spaceChange, .layoutChange, .unknown:
break
}
}
override func nextWindowIDCounterClockwise() -> WindowID? {
guard let focusedWindow = Window.currentlyFocused() else {
return nil
}
let orderedIDs = rootNode.orderedWindowIDs()
guard let focusedWindowIndex = orderedIDs.index(of: focusedWindow.id()) else {
return nil
}
let nextWindowIndex = (focusedWindowIndex == 0 ? orderedIDs.count - 1 : focusedWindowIndex - 1)
return orderedIDs[nextWindowIndex]
}
override func nextWindowIDClockwise() -> WindowID? {
guard let focusedWindow = Window.currentlyFocused() else {
return nil
}
let orderedIDs = rootNode.orderedWindowIDs()
guard let focusedWindowIndex = orderedIDs.index(of: focusedWindow.id()) else {
return nil
}
let nextWindowIndex = (focusedWindowIndex == orderedIDs.count - 1 ? 0 : focusedWindowIndex + 1)
return orderedIDs[nextWindowIndex]
}
override func frameAssignments(_ windowSet: WindowSet<Window>, on screen: Screen) -> [FrameAssignmentOperation<Window>]? {
let windows = windowSet.windows
guard !windows.isEmpty else {
return []
}
if rootNode.left == nil && rootNode.right == nil {
constructInitialTreeWithWindows(windows)
}
let windowIDMap: [WindowID: LayoutWindow<Window>] = windows.reduce([:]) { (windowMap, window) -> [WindowID: LayoutWindow<Window>] in
var mutableWindowMap = windowMap
mutableWindowMap[window.id] = window
return mutableWindowMap
}
let baseFrame = screen.adjustedFrame()
var ret: [FrameAssignmentOperation<Window>] = []
var traversalNodes: [TraversalNode] = [(node: rootNode, frame: baseFrame)]
while !traversalNodes.isEmpty {
let traversalNode = traversalNodes[0]
traversalNodes = [TraversalNode](traversalNodes.dropFirst(1))
if let windowID = traversalNode.node.windowID {
guard let window = windowIDMap[windowID] else {
log.warning("Could not find window for ID: \(windowID)")
continue
}
let resizeRules = ResizeRules(isMain: true, unconstrainedDimension: .horizontal, scaleFactor: 1)
let frameAssignment = FrameAssignment<Window>(
frame: traversalNode.frame,
window: window,
screenFrame: baseFrame,
resizeRules: resizeRules
)
ret.append(FrameAssignmentOperation(frameAssignment: frameAssignment, windowSet: windowSet))
} else {
guard let left = traversalNode.node.left, let right = traversalNode.node.right else {
log.error("Encountered an invalid node")
continue
}
let frame = traversalNode.frame
if frame.width > frame.height {
let leftFrame = CGRect(
x: frame.origin.x,
y: frame.origin.y,
width: frame.width / 2.0,
height: frame.height
)
let rightFrame = CGRect(
x: frame.origin.x + frame.width / 2.0,
y: frame.origin.y,
width: frame.width / 2.0,
height: frame.height
)
traversalNodes.append((node: left, frame: leftFrame))
traversalNodes.append((node: right, frame: rightFrame))
} else {
let topFrame = CGRect(
x: frame.origin.x,
y: frame.origin.y,
width: frame.width,
height: frame.height / 2.0
)
let bottomFrame = CGRect(
x: frame.origin.x,
y: frame.origin.y + frame.height / 2.0,
width: frame.width,
height: frame.height / 2.0
)
traversalNodes.append((node: left, frame: topFrame))
traversalNodes.append((node: right, frame: bottomFrame))
}
}
}
return ret
}
}
extension BinarySpacePartitioningLayout: Equatable {
static func == (lhs: BinarySpacePartitioningLayout<Window>, rhs: BinarySpacePartitioningLayout<Window>) -> Bool {
return lhs.rootNode == rhs.rootNode
}
}
|
86912a532f0381c1456f8d8747571bf6
| 32.32 | 140 | 0.562225 | false | false | false | false |
MiezelKat/AWSense
|
refs/heads/master
|
AWSenseConnect/AWSenseConnectWatch/SensingDataBuffer.swift
|
mit
|
1
|
//
// SensingDataBuffer.swift
// AWSenseConnect
//
// Created by Katrin Hansel on 05/03/2017.
// Copyright © 2017 Katrin Haensel. All rights reserved.
//
import Foundation
import AWSenseShared
internal class SensingDataBuffer{
private let bufferLimit = 1024
private let bufferLimitHR = 10
// MARK: - properties
var sensingSession : SensingSession
var sensingBuffers : [AWSSensorType : [AWSSensorData]]
var sensingBufferBatchNo : [AWSSensorType : Int]
var sensingBufferEvent : SensingBufferEvent = SensingBufferEvent()
// MARK: - init
init(withSession session : SensingSession){
sensingSession = session
sensingBuffers = [AWSSensorType : [AWSSensorData]]()
sensingBufferBatchNo = [AWSSensorType : Int]()
for s : AWSSensorType in sensingSession.sensorConfig.enabledSensors{
sensingBuffers[s] = [AWSSensorData]()
sensingBufferBatchNo[s] = 1
}
}
// MARK: - methods
func append(sensingData data: AWSSensorData, forType type: AWSSensorType){
let count = sensingBuffers[type]!.count
sensingBuffers[type]!.append(data)
if(type != .heart_rate && count > bufferLimit){
if(type == .device_motion){
print("devide motion")
}
sensingBufferEvent.raiseEvent(withType: .bufferLimitReached, forSensor: type)
}else if (type == .heart_rate && count > bufferLimitHR){
sensingBufferEvent.raiseEvent(withType: .bufferLimitReached, forSensor: type)
}
}
func prepareDataToSend(forType type: AWSSensorType) -> (Int, [AWSSensorData]){
let batchNo = sensingBufferBatchNo[type]!
let data = sensingBuffers[type]!
// reset the buffer
sensingBuffers[type]!.removeAll(keepingCapacity: true)
return (batchNo, data)
}
public func subscribe(handler: SensingBufferEventHandler){
sensingBufferEvent.add(handler: handler)
}
public func unsubscribe(handler: SensingBufferEventHandler){
sensingBufferEvent.remove(handler: handler)
}
}
class SensingBufferEvent{
private var eventHandlers = [SensingBufferEventHandler]()
public func raiseEvent(withType type: SensingBufferEventType, forSensor stype : AWSSensorType) {
for handler in self.eventHandlers {
handler.handle(withType: type, forSensor: stype)
}
}
public func add(handler: SensingBufferEventHandler){
eventHandlers.append(handler)
}
public func remove(handler: SensingBufferEventHandler){
eventHandlers = eventHandlers.filter { $0 !== handler }
}
}
protocol SensingBufferEventHandler : class {
func handle(withType type: SensingBufferEventType, forSensor stype: AWSSensorType)
}
enum SensingBufferEventType{
case bufferLimitReached
}
|
c5053f0653119d618d467609124148f3
| 28.277228 | 100 | 0.655394 | false | false | false | false |
kickstarter/ios-oss
|
refs/heads/main
|
Library/TestHelpers/MockOptimizelyClient.swift
|
apache-2.0
|
1
|
import Library
import XCTest
internal enum MockOptimizelyError: Error {
case generic
var localizedDescription: String {
return "Optimizely Error"
}
}
internal class MockOptimizelyClient: OptimizelyClientType {
// MARK: - Experiment Activation Test Properties
var activatePathCalled: Bool = false
var allKnownExperiments: [String] = []
var experiments: [String: String] = [:]
var error: MockOptimizelyError?
var features: [String: Bool] = [:]
var getVariantPathCalled: Bool = false
var userAttributes: [String: Any?]?
// MARK: - Event Tracking Test Properties
var trackedAttributes: [String: Any?]?
var trackedEventKey: String?
var trackedUserId: String?
internal func activate(experimentKey: String, userId: String, attributes: [String: Any?]?) throws
-> String {
self.activatePathCalled = true
return try self.experiment(forKey: experimentKey, userId: userId, attributes: attributes)
}
internal func getVariationKey(experimentKey: String, userId: String, attributes: [String: Any?]?) throws
-> String {
self.getVariantPathCalled = true
return try self.experiment(forKey: experimentKey, userId: userId, attributes: attributes)
}
func isFeatureEnabled(featureKey: String, userId _: String, attributes _: [String: Any?]?) -> Bool {
return self.features[featureKey] == true
}
private func experiment(forKey key: String, userId _: String, attributes: [String: Any?]?) throws
-> String {
self.userAttributes = attributes
if let error = self.error {
throw error
}
guard let experimentVariant = self.experiments[key] else {
throw MockOptimizelyError.generic
}
return experimentVariant
}
func track(
eventKey: String,
userId: String,
attributes: [String: Any?]?,
eventTags _: [String: Any]?
) throws {
self.trackedEventKey = eventKey
self.trackedAttributes = attributes
self.trackedUserId = userId
}
func allExperiments() -> [String] {
return self.allKnownExperiments
}
}
|
ac8dc3d626203c950e67b80687dec33a
| 26.6 | 106 | 0.692754 | false | false | false | false |
ZeeQL/ZeeQL3
|
refs/heads/develop
|
Sources/ZeeQL/Access/AccessDataSource.swift
|
apache-2.0
|
1
|
//
// AccessDataSource.swift
// ZeeQL
//
// Created by Helge Hess on 24/02/17.
// Copyright © 2017-2020 ZeeZide GmbH. All rights reserved.
//
/**
* This class has a set of operations targetted at SQL based applications. It
* has three major subclasses with specific characteristics:
*
* - `DatabaseDataSource`
* - `ActiveDataSource`
* - `AdaptorDataSource`
*
* All of those datasources are very similiar in the operations they provide,
* but they differ in the feature set and overhead.
*
* `DatabaseDataSource` works on top of an `EditingContext`. It has the biggest
* overhead but provides features like object uniquing/registry. Eg if you need
* to fetch a bunch of objects and then perform subsequent processing on them
* (for example permission checks), it is convenient because the context
* remembers the fetched objects. This datasource returns DatabaseObject's as
* specified in the associated Model.
*
* `ActiveDataSource` is similiar to `DatabaseDataSource`, but it directly works
* on a channel. It has a reasonably small overhead and still provides a good
* feature set, like object mapping or prefetching.
*
* Finally `AdaptorDataSource`. This datasource does not perform object mapping,
* that is, it returns `AdaptorRecord` objects and works directly on top of an
* `AdaptorChannel`.
*/
open class AccessDataSource<Object: SwiftObject> : DataSource<Object> {
open var log : ZeeQLLogger = globalZeeQLLogger
var _fsname : String?
override open var fetchSpecification : FetchSpecification? {
set {
super.fetchSpecification = newValue
_fsname = nil
}
get {
if let fs = super.fetchSpecification { return fs }
if let name = _fsname, let entity = entity {
return entity[fetchSpecification: name]
}
return nil
}
}
open var fetchSpecificationName : String? {
set {
_fsname = newValue
if let name = _fsname, let entity = entity {
super.fetchSpecification = entity[fetchSpecification: name]
}
else {
super.fetchSpecification = nil
}
}
get { return _fsname }
}
var _entityName : String? = nil
open var entityName : String? {
set { _entityName = newValue }
get {
if let entityName = _entityName { return entityName }
if let entity = entity { return entity.name }
if let fs = fetchSpecification, let ename = fs.entityName { return ename }
return nil
}
}
open var auxiliaryQualifier : Qualifier?
open var isFetchEnabled = true
open var qualifierBindings : Any? = nil
// MARK: - Abstract Base Class
open var entity : Entity? {
fatalError("implement in subclass: \(#function)")
}
open func _primaryFetchObjects(_ fs: FetchSpecification,
yield: ( Object ) throws -> Void) throws
{
fatalError("implement in subclass: \(#function)")
}
open func _primaryFetchCount(_ fs: FetchSpecification) throws -> Int {
fatalError("implement in subclass: \(#function)")
}
open func _primaryFetchGlobalIDs(_ fs: FetchSpecification,
yield: ( GlobalID ) throws -> Void) throws {
fatalError("implement in subclass: \(#function)")
}
override open func fetchObjects(cb yield: ( Object ) -> Void) throws {
try _primaryFetchObjects(try fetchSpecificationForFetch(), yield: yield)
}
override open func fetchCount() throws -> Int {
return try _primaryFetchCount(try fetchSpecificationForFetch())
}
open func fetchGlobalIDs(yield: ( GlobalID ) throws -> Void) throws {
try _primaryFetchGlobalIDs(try fetchSpecificationForFetch(), yield: yield)
}
// MARK: - Bindings
var qualifierBindingKeys : [ String ] {
let q = fetchSpecification?.qualifier
let aux = auxiliaryQualifier
guard q != nil || aux != nil else { return [] }
var keys = Set<String>()
q?.addBindingKeys(to: &keys)
aux?.addBindingKeys(to: &keys)
return Array(keys)
}
// MARK: - Fetch Specification
func fetchSpecificationForFetch() throws -> FetchSpecification {
/* copy fetchspec */
var fs : FetchSpecification
if let ofs = fetchSpecification {
fs = ofs // a copy, it is a struct
}
else if let e = entity {
fs = ModelFetchSpecification(entity: e)
}
else if let entityName = entityName {
fs = ModelFetchSpecification(entityName: entityName)
}
else {
throw AccessDataSourceError
.CannotConstructFetchSpecification(.missingEntity)
}
let qb = qualifierBindings
let aux = auxiliaryQualifier
if qb == nil && aux == nil { return fs }
/* merge in aux qualifier */
if let aux = aux {
let combined = and(aux, fs.qualifier)
fs.qualifier = combined
}
/* apply bindings */
if let qb = qb {
guard let fs = try fs.fetchSpecificiationWith(bindings: qb) else {
throw AccessDataSourceError
.CannotConstructFetchSpecification(.bindingFailed)
}
return fs
}
else { return fs }
}
}
|
fc58b09f0ed3c1dd90d169f86d3f92cf
| 29.766467 | 80 | 0.655313 | false | false | false | false |
IamAlchemist/DemoDynamicCollectionView
|
refs/heads/master
|
DemoDynamicCollectionView/NewtownianLayoutAttributes.swift
|
mit
|
1
|
//
// NewtownianLayoutAttributes.swift
// DemoDynamicCollectionView
//
// Created by Wizard Li on 1/12/16.
// Copyright © 2016 morgenworks. All rights reserved.
//
import UIKit
class NewtownianLayoutAttributes : UICollectionViewLayoutAttributes {
var id : Int = 0
override func copyWithZone(zone: NSZone) -> AnyObject {
let newValue = super.copyWithZone(zone) as! NewtownianLayoutAttributes
newValue.id = id
return newValue
}
override func isEqual(object: AnyObject?) -> Bool {
if super.isEqual(object) {
if let attributeObject = object as? NewtownianLayoutAttributes {
if attributeObject.id == id {
return true
}
}
}
return false
}
}
|
898cb2051c7cf1775af3b846a6f16edd
| 24.935484 | 78 | 0.605721 | false | false | false | false |
ctarda/Turnstile
|
refs/heads/trunk
|
Sources/TurnstileTests/EventTests.swift
|
mit
|
1
|
//
// EventTests.swift
// Turnstile
//
// Created by Cesar Tardaguila on 09/05/15.
//
import XCTest
import Turnstile
class EventTests: XCTestCase {
private struct Constants {
static let eventName = "Event under test"
static let sourceStates = [State(value: "State 1"), State(value: "State 2")]
static let destinationState = State(value: "State3")
static let stringDiff = "💩"
}
var event: Event<String>?
override func setUp() {
super.setUp()
event = Event(name: Constants.eventName, sourceStates: Constants.sourceStates, destinationState: Constants.destinationState)
}
override func tearDown() {
event = nil
super.tearDown()
}
func testEventCanBeConstructed() {
XCTAssertNotNil(event, "Event must not be nil")
}
func testEventNameIsSetProperly() {
XCTAssertNotNil(event?.name, "Event name must not be nil")
}
func testEqualEventsAreEqual() {
let secondEvent = Event(name: Constants.eventName, sourceStates: Constants.sourceStates, destinationState: Constants.destinationState)
XCTAssertTrue( event == secondEvent, "A event must be equal to itself")
}
func testEventsWithDifferentNamesAreDifferent() {
let secondEvent = Event(name: Constants.eventName + Constants.stringDiff, sourceStates: Constants.sourceStates, destinationState: Constants.destinationState)
XCTAssertFalse( event == secondEvent, "Events with different name are different")
}
func testEventsWithDiffrentSourceStatesAndSameNameAreDifferent() {
let secondEvent = Event(name: Constants.eventName, sourceStates: [State(value: "State 3")], destinationState: Constants.destinationState)
XCTAssertFalse( event == secondEvent, "Events with different source states are different")
}
func testEventsWithSameNameAndSourceEventsAndDifferentDestinationEventsAreDifferent() {
let secondEvent = Event(name: Constants.eventName, sourceStates: Constants.sourceStates , destinationState: State(value: "State 3"))
XCTAssertFalse( event == secondEvent, "Events with different destination states are different")
}
func testSourceStatesCanBeSet() {
XCTAssertTrue((event!.sourceStates == Constants.sourceStates), "Source states must be set properly")
}
}
|
2710fb99451f01747b7a60dd1fd82587
| 35.69697 | 165 | 0.687861 | false | true | false | false |
robpearson/BlueRing
|
refs/heads/master
|
BlueRing/OctopusClient.swift
|
apache-2.0
|
1
|
//
// OctopusService.swift
// BlueRing
//
// Created by Robert Pearson on 11/2/17.
// Copyright © 2017 Rob Pearson. All rights reserved.
//
import Cocoa
import RxSwift
import Foundation
class OctopusClient: NSObject {
public func getAllProjects() -> Observable<String> {
let session = URLSession.shared
let url = URL(string: "http://192.168.8.107/api/projects/all?apiKey=API-GUEST") // hard coded for now
let observable = Observable<String>.create { observer in
let task = session.dataTask(with: url!) { data, response, err in
if let error = err {
// TODO: Handle errors nicely
print("octopus api error: \(error)")
}
// then check the response code
if let httpResponse = response as? HTTPURLResponse {
switch httpResponse.statusCode {
case 200: // all good!
let dataString = String(data: data!, encoding: String.Encoding.utf8)
observer.onNext(dataString!)
observer.onCompleted()
case 401: // unauthorized
print("octopus api returned an 'unauthorized' response. Did you forget to set your API key?")
default:
print("octopus api returned response: %d %@", httpResponse.statusCode, HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode))
}
}
}
task.resume()
return Disposables.create {
task.cancel()
}
}
return observable
}
}
|
2e28dcf460c38998a1fea7748081af12
| 32.272727 | 167 | 0.508743 | false | false | false | false |
naveengthoppan/NGTRefreshControl
|
refs/heads/master
|
NGTProgressView/NGTProgressView.swift
|
mit
|
1
|
//
// NGTProgressView.swift
// PullRefresh
//
// Created by Naveen George Thoppan on 28/12/16.
// Copyright © 2016 Appcoda. All rights reserved.
//
import UIKit
@IBDesignable
public class NGTProgressView: UIView {
@IBOutlet weak var view: UIView!
@IBOutlet weak var cityImageView: UIImageView!
@IBOutlet weak var sunImageView: UIImageView!
@IBOutlet weak var signBoardImageView: UIImageView!
@IBOutlet weak var carImageView: UIImageView!
@IBOutlet weak var carLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var cityLeadingConstriant: NSLayoutConstraint!
var isCompleted: Bool!
override public init(frame: CGRect) {
super.init(frame: frame)
nibSetup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
nibSetup()
}
private func nibSetup() {
backgroundColor = .clear
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.translatesAutoresizingMaskIntoConstraints = true
addSubview(view)
}
private func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView
return nibView
}
public func startAnimation(completion: @escaping (_ isCompleted: Bool)->()) {
isCompleted = false
rotateView(targetView: sunImageView)
animateRefreshStep2() { (isCompleted) -> () in
if isCompleted == true {
completion(isCompleted)
}
}
}
public func animateRefreshStep2(completion: @escaping (_ isCompleted: Bool)->()) {
self.carLeadingConstraint.constant = self.view.bounds.width/2 - 30
self.cityLeadingConstriant.constant -= 15
UIView.animate(withDuration: 4, animations: {
self.view.layoutIfNeeded()
self.startCarShakeAnimation()
}) { finished in
completion(true)
}
}
public func stopAnimation (completion: @escaping (_ isCompleted: Bool)->()) {
if (self.isCompleted == false) {
self.carLeadingConstraint.constant = self.view.bounds.width + 30
self.cityLeadingConstriant.constant -= 15
UIView.animate(withDuration: 2, delay:0.8, animations: {
self.view.layoutIfNeeded()
}) { finished in
self.isCompleted = true
self.stopCarShakeAnimation()
completion(self.isCompleted)
self.carLeadingConstraint.constant = -90
self.cityLeadingConstriant.constant = -37
}
}
}
private func rotateView(targetView: UIView, duration: Double = 2) {
UIView.animate(withDuration: duration, delay: 0.0, options: [.repeat, .curveLinear], animations: {
targetView.transform = targetView.transform.rotated(by: CGFloat(M_PI))
})
}
public func startCarShakeAnimation () {
let carShakeAnimation = CABasicAnimation(keyPath: "transform.rotation")
carShakeAnimation.duration = 0.1
carShakeAnimation.beginTime = CACurrentMediaTime() + 1
carShakeAnimation.autoreverses = true
carShakeAnimation.repeatDuration = 20
carShakeAnimation.fromValue = -0.1;
carShakeAnimation.toValue = 0.1
self.carImageView.layer.add(carShakeAnimation, forKey: "carAnimation")
}
public func stopCarShakeAnimation () {
self.carImageView.layer.removeAnimation(forKey: "carAnimation")
}
}
|
52b536582224a16260f932825418e84c
| 33.540541 | 106 | 0.622848 | false | false | false | false |
ingresse/ios-sdk
|
refs/heads/dev
|
IngresseSDKTests/Model/UserTests.swift
|
mit
|
1
|
//
// Copyright © 2018 Ingresse. All rights reserved.
//
import XCTest
@testable import IngresseSDK
class UserTests: XCTestCase {
func testDecode() {
// Given
var json = [String: Any]()
json["id"] = 1
json["name"] = "name"
json["email"] = "email"
json["type"] = "type"
json["username"] = "username"
json["phone"] = "phone"
json["cellphone"] = "cellphone"
json["pictures"] = [:]
json["social"] = [
[
"network": "facebook",
"id": "facebookId"
], [
"network": "twitter",
"id": "twitterId"
]
]
// When
let obj = JSONDecoder().decodeDict(of: User.self, from: json)
// Then
XCTAssertNotNil(obj)
XCTAssertEqual(obj?.id, 1)
XCTAssertEqual(obj?.name, "name")
XCTAssertEqual(obj?.email, "email")
XCTAssertEqual(obj?.type, "type")
XCTAssertEqual(obj?.username, "username")
XCTAssertEqual(obj?.phone, "phone")
XCTAssertEqual(obj?.cellphone, "cellphone")
XCTAssertEqual(obj?.pictures, [:])
let social = obj!.social
XCTAssertEqual(social[0].network, "facebook")
XCTAssertEqual(social[1].network, "twitter")
XCTAssertEqual(social[0].id, "facebookId")
XCTAssertEqual(social[1].id, "twitterId")
}
func testEmptyInit() {
// When
let obj = User()
// Then
XCTAssertEqual(obj.id, 0)
XCTAssertEqual(obj.name, "")
XCTAssertEqual(obj.email, "")
XCTAssertEqual(obj.type, "")
XCTAssertEqual(obj.username, "")
XCTAssertEqual(obj.phone, "")
XCTAssertEqual(obj.cellphone, "")
XCTAssertEqual(obj.pictures, [:])
XCTAssertEqual(obj.social, [])
}
}
|
b0de5ca9065483165ee5bf8d9ae5a7ce
| 27.014925 | 69 | 0.52797 | false | true | false | false |
Pluto-Y/SwiftyEcharts
|
refs/heads/master
|
DemoOptions/GaugeOptions.swift
|
mit
|
1
|
//
// GaugeOptions.swift
// SwiftyEcharts
//
// Created by Pluto-Y on 16/01/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
import SwiftyEcharts
public final class GaugeOptions {
// MARK: Gauge Car Dark
/// 地址: http://echarts.baidu.com/demo.html#gauge-car-dark
static func gaugeCarDarkOption() -> Option {
// TODO: 添加实现
return Option(
)
}
// MARK: Gauge Car
/// 地址: http://echarts.baidu.com/demo.html#gauge-car
static func gaugeCarOption() -> Option {
let serieData1: [Jsonable] = [["value": 40, "name": "km/h"]]
let serieData2: [Jsonable] = [["value": 1.5, "name": "x1000 r/min"]]
let serieData3: [Jsonable] = [["value": 0.5, "name": "gas"]]
let serieData4: [Jsonable] = [["value": 0.5, "name": "gas"]]
let serie1: GaugeSerie = GaugeSerie(
.name("速度"), // 缺少z
.min(0),
.max(220),
.splitNumber(11),
.radius(50%),
.axisLine(AxisLine(
.lineStyle(LineStyle(
.width(10)
))
)),
.axisTick(AxisTick(
.length(15),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.splitLine(SplitLine(
.length(20),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.title(GaugeSerie.Title(
.textStyle(TextStyle(
.fontWeight(.bolder),
.fontSize(20),
.fontStyle(.italic)
))
)),
.detail(GaugeSerie.Detail(
.textStyle(TextStyle(
.fontWeight(.bolder)
))
)),
.data(serieData1)
)
let serie2: GaugeSerie = GaugeSerie(
.name("转速"),
.center([20%, 55%]),
.radius(35%),
.min(0),
.max(7),
.endAngle(45),
.splitNumber(7),
.axisLine(AxisLine(
.lineStyle(LineStyle(
.width(8)
))
)),
.axisTick(AxisTick(
.length(12),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.splitLine(SplitLine(
.length(20),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.pointer(GaugeSerie.Pointer(
.width(5)
)),
.title(GaugeSerie.Title(
.offsetCenter([0, (-30)%])
)),
.detail(GaugeSerie.Detail(
.textStyle(TextStyle(
.fontWeight(.bolder)
))
)),
.data(serieData2)
)
let serie3: GaugeSerie = GaugeSerie(
.name("油表"),
.center([77%, 50%]),
.radius(25%),
.min(0),
.max(2),
.startAngle(135),
.endAngle(45),
.splitNumber(2),
.axisLine(AxisLine(
.lineStyle(LineStyle(
.width(8)
))
)),
.axisTick(AxisTick(
.splitNumber(5),
.length(10),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.axisLabel(AxisLabel(
.formatter(.function("function axisLabelFormattter(v){ switch (v + '') { case '0' : return 'E'; case '1' : return 'Gas'; case '2' : return 'F'; }}"))
)),
.splitLine(SplitLine(
.length(15),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.pointer(GaugeSerie.Pointer(
.width(2)
)),
.title(GaugeSerie.Title(
.show(false)
)),
.detail(GaugeSerie.Detail(
.show(false)
)),
.data(serieData3)
)
let serie4 = GaugeSerie(
.name("水表"),
.center([77%, 50%]),
.radius(25%),
.min(0),
.max(2),
.startAngle(315),
.endAngle(225),
.splitNumber(2),
.axisLine(AxisLine(
.lineStyle(LineStyle(
.width(8)
))
)),
.axisLabel(AxisLabel(
.formatter(.function("function axisLabelFomatter2(v){ switch (v + '') { case '0' : return 'H'; case '1' : return 'Water'; case '2' : return 'C'; } }"))
)),
.splitLine(SplitLine(
.length(15),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.pointer(GaugeSerie.Pointer(
.width(2)
)),
.title(GaugeSerie.Title(
.show(false)
)),
.detail(GaugeSerie.Detail(
.show(false)
)),
.data(serieData4)
)
let series: [Serie] = [
serie1,
serie2,
serie3,
serie4
]
return Option(
.tooltip(Tooltip(
.formatter(.string("{a}<br/>{c} {b}"))
)),
.toolbox(Toolbox(
.show(true),
.feature(ToolboxFeature(
.restore(ToolboxFeatureRestore(.show(true))),
.saveAsImage(ToolboxFeatureSaveAsImage(.show(true)))
))
)),
.series(series)
)
}
// MARK: Gauge
/// 地址: http://echarts.baidu.com/demo.html#gauge
static func gaugeOption() -> Option {
return Option(
.tooltip(Tooltip(
.formatter(.string("{a} <br/>{b} : {c}%"))
)),
.toolbox(Toolbox(
.feature(ToolboxFeature(
.restore(ToolboxFeatureRestore()),
.saveAsImage(ToolboxFeatureSaveAsImage())
))
)),
.series([
GaugeSerie(
.name("业务指标"),
.detail(GaugeSerieDetail(
.formatter(.string("{value}%"))
)),
.data([["name":"完成率", "value": 50]]) // FIXIM: 封装Data类型?
)
])
)
}
}
|
6fddb285aac919e22697722dd3e166c3
| 29.75 | 167 | 0.381098 | false | false | false | false |
huangboju/QMUI.swift
|
refs/heads/master
|
QMUI.swift/Demo/Modules/Demos/UIKit/QDTextFieldViewController.swift
|
mit
|
1
|
//
// QDTextFieldViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/17.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
class QDTextFieldViewController: QDCommonViewController {
private lazy var textField: QMUITextField = {
let textField = QMUITextField()
textField.delegate = self
textField.maximumTextLength = 10
textField.placeholder = "请输入文字"
textField.font = UIFontMake(16)
textField.layer.cornerRadius = 2
textField.layer.borderColor = UIColorSeparator.cgColor
textField.layer.borderWidth = PixelOne
textField.textInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
textField.clearButtonMode = .always
return textField
}()
private lazy var tipsLabel: UILabel = {
let label = UILabel()
let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: UIFontMake(12), NSAttributedString.Key.foregroundColor: UIColorGray6, NSAttributedString.Key.paragraphStyle: NSMutableParagraphStyle(lineHeight: 16)]
label.attributedText = NSAttributedString(string: "支持自定义 placeholder 颜色,支持调整输入框与文字之间的间距,支持限制最大可输入的文字长度(可试试输入 emoji、从中文输入法候选词输入等)。", attributes: attributes)
label.numberOfLines = 0
return label
}()
override func didInitialized() {
super.didInitialized()
automaticallyAdjustsScrollViewInsets = false
}
override func initSubviews() {
super.initSubviews()
view.addSubview(textField)
view.addSubview(tipsLabel)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let padding = UIEdgeInsets(top: qmui_navigationBarMaxYInViewCoordinator + 16, left: 16, bottom: 16, right: 16)
let contentWidth = view.bounds.width - padding.horizontalValue
textField.frame = CGRect(x: padding.left, y: padding.top, width: contentWidth, height: 40)
let tipsLabelHeight = tipsLabel.sizeThatFits(CGSize(width: contentWidth, height: CGFloat.greatestFiniteMagnitude)).height
tipsLabel.frame = CGRectFlat(padding.left, textField.frame.maxY + 8, contentWidth, tipsLabelHeight)
}
}
extension QDTextFieldViewController: QMUITextFieldDelegate {
func textField(_ textField: QMUITextField, didPreventTextChangeInRange range: NSRange, replacementString: String?) {
QMUITips.showSucceed(text: "文字不能超过 \(textField.maximumTextLength)个字符", in: view, hideAfterDelay: 2)
}
}
|
433abc76341d861ad20bfc77e39de687
| 38.71875 | 235 | 0.700236 | false | false | false | false |
RameshRM/Background-Fetch
|
refs/heads/master
|
Background-Fetch/Background-Fetch/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// Background-Fetch
//
// Created by Mahadevan, Ramesh on 10/29/14.
// Copyright (c) 2014 GoliaMania. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var helloLabel: UILabel!
var messageId: NSString!;
let _MESSAGE_FROM = "background.poll";
let _MESSAGE_POSTBOX = "pobox"
let _MESSAGE_PROCESSING_API = "http://citypageapp.com/messages.retrieve?to=";
override func viewDidLoad() {
super.viewDidLoad()
self.send();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func onMessageReceived(messageArgs: NSString){
println(messageArgs);
self.helloLabel.text = messageArgs;
processMessage(messageArgs);
}
func processMessage(messageArgs: NSString){
var encodedMessageArgs = messageArgs.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) as NSString!;
var url = "\(self._MESSAGE_PROCESSING_API)\(self.messageId)";
var request = NSURLRequest(URL: NSURL(string: url)!);
NSURLConnection.sendAsynchronousRequest(request,queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
self.send();
var receivedMessage = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary;
self.helloLabel.text = receivedMessage["body"] as NSString!;
}
}
func getNow() -> NSTimeInterval{
return NSDate().timeIntervalSince1970 * 1000;
}
func sendMessage(from: NSString, to: NSString, body: NSString) -> Void{
var url = "http://citypageapp.com/messages.send?from=\(from)&to=\(to)&body=\(body)";
var request = NSURLRequest(URL: NSURL(string: url)!);
NSURLConnection.sendAsynchronousRequest(request,queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
}
}
func getAndSetMessageId() -> NSString{
return "\(_MESSAGE_POSTBOX).\(self.getNow())";
}
func messageBody() -> NSString{
var message = "Hello, Current Time in Milli Seconds is : \(getNow())";
return message.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) as NSString!;
}
func send() -> Void{
self.messageId = self.getAndSetMessageId();
self.sendMessage(_MESSAGE_FROM, to: self.messageId, body: self.messageBody())
}
}
|
ca44af5330c436fb4e25d9f8667806b3
| 32.4375 | 122 | 0.643738 | false | false | false | false |
theabovo/Extend
|
refs/heads/master
|
Tests/HelpersTests/ThrottlerTests.swift
|
apache-2.0
|
1
|
//
// Copyright (c) 2016-present, Menly ApS
// All rights reserved.
//
// This source code is licensed under the Apache License 2.0 found in the
// LICENSE file in the root directory of this source tree.
//
@testable import Extend
import XCTest
class ThrottlerTests: XCTestCase {
// MARK: - Tests
func testStringThrottler() {
let interval: TimeInterval = 0.1
let firstText = "Hello World!"
let finalText = "Hello you world self"
let expectation = XCTestExpectation(description: "Throttling")
let stringThrottler = Throttler<String>(interval: interval) { text in
XCTAssertEqual(text, finalText)
expectation.fulfill()
}
stringThrottler.handle(firstText)
stringThrottler.handle(finalText)
wait(for: [expectation], timeout: 1)
}
}
|
9938eeaee46c276f2d8b1d2f2e94e812
| 23.548387 | 73 | 0.729304 | false | true | false | false |
sora0077/QiitaKit
|
refs/heads/master
|
QiitaKit/src/Endpoint/ExpandedTemplate/CreateExpandedTemplate.swift
|
mit
|
1
|
//
// CreateExpandedTemplate.swift
// QiitaKit
//
// Created on 2015/06/08.
// Copyright (c) 2015年 林達也. All rights reserved.
//
import Foundation
import APIKit
/**
* 受け取ったテンプレート用文字列の変数を展開して返します。
*/
public struct CreateExpandedTemplate {
/// テンプレートの本文
/// example: Weekly MTG on %{Year}/%{month}/%{day}
///
public let body: String
/// タグ一覧
/// example: [{"name"=>"MTG/%{Year}/%{month}/%{day}", "versions"=>["0.0.1"]}]
///
public let tags: Array<Tagging>
/// 生成される投稿のタイトルの雛形
/// example: Weekly MTG on %{Year}/%{month}/%{day}
///
public let title: String
public init(body: String, tags: Array<Tagging>, title: String) {
self.body = body
self.tags = tags
self.title = title
}
}
extension CreateExpandedTemplate: QiitaRequestToken {
public typealias Response = ExpandedTemplate
public typealias SerializedObject = [String: AnyObject]
public var method: HTTPMethod {
return .POST
}
public var path: String {
return "/api/v2/expanded_templates"
}
public var parameters: [String: AnyObject]? {
return [
"body": body,
"tags": tags.map({ ["name": $0.name, "versions": $0.versions] }),
"title": title
]
}
public var encoding: RequestEncoding {
return .JSON
}
}
public extension CreateExpandedTemplate {
func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response {
return _ExpandedTemplate(object)
}
}
|
5768751a422b8439840742dcd06587d3
| 21.8 | 119 | 0.601504 | false | false | false | false |
EZ-NET/CodePiece
|
refs/heads/Rev2
|
ESTwitter/Character.swift
|
gpl-3.0
|
1
|
//
// Character.swift
// ESTwitter
//
// Created by Tomohiro Kumagai on 2020/02/02.
// Copyright © 2020 Tomohiro Kumagai. All rights reserved.
//
import Foundation
extension String {
public var twitterCharacterView: [TwitterCharacter] {
return map(TwitterCharacter.init)
}
}
public struct TwitterCharacter {
private(set) var units: [UTF16Character]
public init(_ character: Character) {
units = character.utf16.map(UTF16Character.init)
}
}
extension TwitterCharacter {
public var rawString: String {
return units
.map { $0.rawValue }
.withUnsafeBufferPointer { buffer in
guard let address = buffer.baseAddress else {
return ""
}
return String(utf16CodeUnits: address, count: buffer.count)
}
}
public var utf8: String.UTF8View {
return rawString.utf8
}
public var unitCount: Int {
return units.count
}
public func contains(_ element: UTF16Character) -> Bool {
return units.contains(element)
}
public var wordCountForPost: Double {
if isEnglish {
return 0.5
}
else if contains(.tpvs) {
return 2
}
else {
return 1
}
}
public var wordCountForIndices: Int {
return utf8.map(UTF8Character.init).utf8LeadingByteCount
}
public var isEnglish: Bool {
guard units.count == 1 else {
return false
}
switch units.first!.rawValue {
case 0x0000 ... 0x10FF,
0x2000 ... 0x200D,
0x2010 ... 0x201F,
0x2032 ... 0x2037:
return true
default:
return false
}
}
public var isSurrogatePair: Bool {
guard units.count == 2 else {
return false
}
return units[0].isSurrogateHight && units[1].isSurrogateLow
}
}
extension Sequence where Element == TwitterCharacter {
public var wordCountForPost: Double {
return reduce(0) { $0 + $1.wordCountForPost }
}
}
|
398d79cd4591e526c39d6ef8a0ead2f5
| 14.521008 | 62 | 0.659989 | false | false | false | false |
loudnate/LoopKit
|
refs/heads/master
|
LoopKit/GlucoseKit/StoredGlucoseSample.swift
|
mit
|
1
|
//
// StoredGlucoseSample.swift
// LoopKit
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import HealthKit
public struct StoredGlucoseSample: GlucoseSampleValue {
public let sampleUUID: UUID
// MARK: - HealthKit Sync Support
public let syncIdentifier: String
public let syncVersion: Int
// MARK: - SampleValue
public let startDate: Date
public let quantity: HKQuantity
// MARK: - GlucoseSampleValue
public let isDisplayOnly: Bool
public let provenanceIdentifier: String
init(sample: HKQuantitySample) {
self.init(
sampleUUID: sample.uuid,
syncIdentifier: sample.metadata?[HKMetadataKeySyncIdentifier] as? String,
syncVersion: sample.metadata?[HKMetadataKeySyncVersion] as? Int ?? 1,
startDate: sample.startDate,
quantity: sample.quantity,
isDisplayOnly: sample.isDisplayOnly,
provenanceIdentifier: sample.provenanceIdentifier
)
}
public init(
sampleUUID: UUID,
syncIdentifier: String?,
syncVersion: Int,
startDate: Date,
quantity: HKQuantity,
isDisplayOnly: Bool,
provenanceIdentifier: String
) {
self.sampleUUID = sampleUUID
self.syncIdentifier = syncIdentifier ?? sampleUUID.uuidString
self.syncVersion = syncVersion
self.startDate = startDate
self.quantity = quantity
self.isDisplayOnly = isDisplayOnly
self.provenanceIdentifier = provenanceIdentifier
}
}
extension StoredGlucoseSample: Equatable, Hashable, Comparable {
public static func <(lhs: StoredGlucoseSample, rhs: StoredGlucoseSample) -> Bool {
return lhs.startDate < rhs.startDate
}
public static func ==(lhs: StoredGlucoseSample, rhs: StoredGlucoseSample) -> Bool {
return lhs.sampleUUID == rhs.sampleUUID
}
public func hash(into hasher: inout Hasher) {
hasher.combine(sampleUUID)
}
}
extension StoredGlucoseSample {
init(managedObject: CachedGlucoseObject) {
self.init(
sampleUUID: managedObject.uuid!,
syncIdentifier: managedObject.syncIdentifier,
syncVersion: Int(managedObject.syncVersion),
startDate: managedObject.startDate,
quantity: HKQuantity(unit: HKUnit(from: managedObject.unitString!), doubleValue: managedObject.value),
isDisplayOnly: managedObject.isDisplayOnly,
provenanceIdentifier: managedObject.provenanceIdentifier!
)
}
}
|
e663e3185d89438064055eecc73b74b8
| 28.215909 | 114 | 0.668611 | false | false | false | false |
prine/ROGenericTableViewController
|
refs/heads/master
|
ROGenericTableViewController/NavigationViewController.swift
|
mit
|
1
|
//
// NavigationViewController.swift
// ROTableViewController
//
// Created by Robin Oster on 27/03/15.
// Copyright (c) 2015 Rascor International AG. All rights reserved.
//
import UIKit
class User {
var firstname:String = ""
var lastname:String = ""
init(_ firstname:String, _ lastname:String) {
self.firstname = firstname
self.lastname = lastname
}
}
class NavigationViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
let user1 = User("Hugo", "Walker")
let user2 = User("Texas", "Ranger")
let cellForRow = ({ (tableView:UITableView, user:User) -> UITableViewCell in
// CellForRowAtIndexPath
var customCell:CustomTableViewCell? = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomTableViewCell?
if customCell == nil {
customCell = CustomTableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "CustomCell") as CustomTableViewCell
}
customCell!.setUser(user)
return customCell!
})
let didCellSelect = ({(user:User) -> () in
let detailViewController = self.storyboardLoad("DetailViewControllerScene") as DetailViewController
self.pushViewController(detailViewController, animated: true)
})
// Generic CustomTableViewCell solution
let tableViewController = createViewControllerGeneric([user1, user2], cellForRow: cellForRow, select: didCellSelect, storyboardName: "Main", tableViewControllerIdentifier: "TableViewControllerScene") as! ROGenericTableViewController
// If you need swipe actions just set the swipe actions variable
tableViewController.swipeActions = createSwipeActions()
// Update later on the data (need to use the generic outside method)
updateItems(tableViewController, items: [user1, user2, user1, user2])
tableViewController.tableView.reloadData()
self.viewControllers = [tableViewController]
}
func createSwipeActions() -> [UITableViewRowAction] {
let favAction = UITableViewRowAction(style: .normal, title: "Swipe 1") { (action, indexPath) -> Void in
print("Swipe 1")
}
favAction.backgroundColor = UIColor.brown
return [favAction]
}
func storyboardLoad<T>(_ sceneName:String) -> T {
return self.storyboard?.instantiateViewController(withIdentifier: sceneName) as! T
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
06d3a3b608ccf9816ade71e28a51842c
| 33.923077 | 240 | 0.64978 | false | false | false | false |
ReactKit/SwiftState
|
refs/heads/swift/5.0
|
Tests/SwiftStateTests/MiscTests.swift
|
mit
|
1
|
//
// MiscTests.swift
// SwiftState
//
// Created by Yasuhiro Inami on 2015-12-05.
// Copyright © 2015 Yasuhiro Inami. All rights reserved.
//
import SwiftState
import XCTest
/// Unarranged tests.
class MiscTests: _TestCase
{
func testREADME_string()
{
let machine = StateMachine<String, NoEvent>(state: ".State0") { machine in
machine.addRoute(".State0" => ".State1")
machine.addRoute(.any => ".State2") { context in print("Any => 2, msg=\(String(describing: context.userInfo))") }
machine.addRoute(".State2" => .any) { context in print("2 => Any, msg=\(String(describing: context.userInfo))") }
// add handler (handlerContext = (event, transition, order, userInfo))
machine.addHandler(".State0" => ".State1") { context in
print("0 => 1")
}
// add errorHandler
machine.addErrorHandler { context in
print("[ERROR] \(context.fromState) => \(context.toState)")
}
}
// tryState 0 => 1 => 2 => 1 => 0
machine <- ".State1"
XCTAssertEqual(machine.state, ".State1")
machine <- (".State2", "Hello")
XCTAssertEqual(machine.state, ".State2")
machine <- (".State1", "Bye")
XCTAssertEqual(machine.state, ".State1")
machine <- ".State0" // fail: no 1 => 0
XCTAssertEqual(machine.state, ".State1")
print("machine.state = \(machine.state)")
}
// StateType + associated value
func testREADME_associatedValue()
{
let machine = StateMachine<StrState, StrEvent>(state: .str("0")) { machine in
machine.addRoute(.str("0") => .str("1"))
machine.addRoute(.any => .str("2")) { context in print("Any => 2, msg=\(String(describing: context.userInfo))") }
machine.addRoute(.str("2") => .any) { context in print("2 => Any, msg=\(String(describing: context.userInfo))") }
// add handler (handlerContext = (event, transition, order, userInfo))
machine.addHandler(.str("0") => .str("1")) { context in
print("0 => 1")
}
// add errorHandler
machine.addErrorHandler { context in
print("[ERROR] \(context.fromState) => \(context.toState)")
}
}
// tryState 0 => 1 => 2 => 1 => 0
machine <- .str("1")
XCTAssertEqual(machine.state, StrState.str("1"))
machine <- (.str("2"), "Hello")
XCTAssertEqual(machine.state, StrState.str("2"))
machine <- (.str("1"), "Bye")
XCTAssertEqual(machine.state, StrState.str("1"))
machine <- .str("0") // fail: no 1 => 0
XCTAssertEqual(machine.state, StrState.str("1"))
print("machine.state = \(machine.state)")
}
func testExample()
{
let machine = StateMachine<MyState, NoEvent>(state: .state0) {
// add 0 => 1
$0.addRoute(.state0 => .state1) { context in
print("[Transition 0=>1] \(context.fromState) => \(context.toState)")
}
// add 0 => 1 once more
$0.addRoute(.state0 => .state1) { context in
print("[Transition 0=>1b] \(context.fromState) => \(context.toState)")
}
// add 2 => Any
$0.addRoute(.state2 => .any) { context in
print("[Transition exit 2] \(context.fromState) => \(context.toState) (Any)")
}
// add Any => 2
$0.addRoute(.any => .state2) { context in
print("[Transition Entry 2] \(context.fromState) (Any) => \(context.toState)")
}
// add 1 => 0 (no handler)
$0.addRoute(.state1 => .state0)
}
// 0 => 1
XCTAssertTrue(machine.hasRoute(.state0 => .state1))
// 1 => 0
XCTAssertTrue(machine.hasRoute(.state1 => .state0))
// 2 => Any
XCTAssertTrue(machine.hasRoute(.state2 => .state0))
XCTAssertTrue(machine.hasRoute(.state2 => .state1))
XCTAssertTrue(machine.hasRoute(.state2 => .state2))
XCTAssertTrue(machine.hasRoute(.state2 => .state3))
// Any => 2
XCTAssertTrue(machine.hasRoute(.state0 => .state2))
XCTAssertTrue(machine.hasRoute(.state1 => .state2))
XCTAssertTrue(machine.hasRoute(.state3 => .state2))
// others
XCTAssertFalse(machine.hasRoute(.state0 => .state0))
XCTAssertFalse(machine.hasRoute(.state0 => .state3))
XCTAssertFalse(machine.hasRoute(.state1 => .state1))
XCTAssertFalse(machine.hasRoute(.state1 => .state3))
XCTAssertFalse(machine.hasRoute(.state3 => .state0))
XCTAssertFalse(machine.hasRoute(.state3 => .state1))
XCTAssertFalse(machine.hasRoute(.state3 => .state3))
machine.configure {
// add error handlers
$0.addErrorHandler { context in
print("[ERROR 1] \(context.fromState) => \(context.toState)")
}
// add entry handlers
$0.addHandler(.any => .state0) { context in
print("[Entry 0] \(context.fromState) => \(context.toState)") // NOTE: this should not be called
}
$0.addHandler(.any => .state1) { context in
print("[Entry 1] \(context.fromState) => \(context.toState)")
}
$0.addHandler(.any => .state2) { context in
print("[Entry 2] \(context.fromState) => \(context.toState), userInfo = \(String(describing: context.userInfo))")
}
$0.addHandler(.any => .state2) { context in
print("[Entry 2b] \(context.fromState) => \(context.toState), userInfo = \(String(describing: context.userInfo))")
}
// add exit handlers
$0.addHandler(.state0 => .any) { context in
print("[Exit 0] \(context.fromState) => \(context.toState)")
}
$0.addHandler(.state1 => .any) { context in
print("[Exit 1] \(context.fromState) => \(context.toState)")
}
$0.addHandler(.state2 => .any) { context in
print("[Exit 2] \(context.fromState) => \(context.toState), userInfo = \(String(describing: context.userInfo))")
}
$0.addHandler(.state2 => .any) { context in
print("[Exit 2b] \(context.fromState) => \(context.toState), userInfo = \(String(describing: context.userInfo))")
}
}
XCTAssertEqual(machine.state, MyState.state0)
// tryState 0 => 1 => 2 => 1 => 0 => 3
machine <- .state1
XCTAssertEqual(machine.state, MyState.state1)
machine <- (.state2, "State2 activate")
XCTAssertEqual(machine.state, MyState.state2)
machine <- (.state1, "State2 deactivate")
XCTAssertEqual(machine.state, MyState.state1)
machine <- .state0
XCTAssertEqual(machine.state, MyState.state0)
machine <- .state3
XCTAssertEqual(machine.state, MyState.state0, "No 0 => 3.")
}
}
|
b11923757920c1d973bc7ab0da64982a
| 35.793814 | 130 | 0.543149 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.