repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lemonandlime/Strax
|
refs/heads/master
|
Strax/LocationView.swift
|
gpl-2.0
|
1
|
//
// LocationView.swift
// Strax
//
// Created by Karl Söderberg on 2015-06-27.
// Copyright (c) 2015 lemonandlime. All rights reserved.
//
import UIKit
import MapKit
class LocationView: MKAnnotationView {
class func locationView(location : Location)->LocationView {
let view : LocationView = NSBundle.mainBundle().loadNibNamed("LocationView", owner: self, options: nil).first as! LocationView
view.titleLabel.text = location.name
return view
}
@IBOutlet var titleLabel : UILabel!
@IBOutlet var pointImage : UIImageView!
let gesturecognizer : UIPanGestureRecognizer = UIPanGestureRecognizer()
lazy var realCenter : CGPoint = self.pointImage.convertPoint(self.pointImage.center, toView: self.superview)
var startDragPoint : CGPoint = CGPointMake(0, 0)
var didBeginMoveClosure:((CGPoint, UIView)->Void)?
var didChangeMoveClosure:((CGPoint, CGPoint)->Void)?
var didEndMoveClosure:((CGPoint, CGPoint)->Void)?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.clipsToBounds = false
gesturecognizer.addTarget(self, action: "didPan:")
self.addGestureRecognizer(gesturecognizer)
}
func didPan(gestureRecognizer : UIGestureRecognizer){
let point = gesturecognizer.locationInView(superview)
switch gesturecognizer.state{
case .Began :
pointImage!.highlighted = true
startDragPoint = gesturecognizer.locationInView(superview)
didBeginMoveClosure!(self.center, self)
return
case .Ended, .Cancelled :
pointImage!.highlighted = false
transform = CGAffineTransformIdentity
didEndMoveClosure!(self.center, point)
return
case .Changed :
didChangeMoveClosure!(self.center, point)
return
default:
return
}
}
}
|
ca336bcbf3461800ffd9620e04246589
| 28.764706 | 135 | 0.635375 | false | false | false | false |
ozgur/AutoLayoutAnimation
|
refs/heads/master
|
UserDataSource.swift
|
mit
|
1
|
//
// UserDataSource.swift
// AutoLayoutAnimation
//
// Created by Ozgur Vatansever on 10/25/15.
// Copyright © 2015 Techshed. All rights reserved.
//
import UIKit
import AddressBook
class UserDataSource {
fileprivate var users = [User]()
var count: Int {
return users.count
}
subscript(index: Int) -> User {
return users[index]
}
func addUser(_ user: User) -> Bool {
if users.contains(user) {
return false
}
users.append(user)
return true
}
func removeUser(_ user: User) -> Bool {
guard let index = users.index(of: user) else {
return false
}
users.remove(at: index)
return true
}
func loadUsersFromPlist(named: String) -> [User]? {
let mainBundle = Bundle.main
guard let path = mainBundle.path(forResource: named, ofType: "plist"),
content = NSArray(contentsOfFile: path) as? [[String: String]] else {
return nil
}
users = content.map { (dict) -> User in
return User(data: dict)
}
return users
}
}
class User: NSObject {
var firstName: String
var lastName: String
var userId: Int
var city: String
var fullName: String {
let record = ABPersonCreate().takeRetainedValue() as ABRecordRef
ABRecordSetValue(record, kABPersonFirstNameProperty, firstName, nil)
ABRecordSetValue(record, kABPersonLastNameProperty, lastName, nil)
guard let name = ABRecordCopyCompositeName(record)?.takeRetainedValue() else {
return ""
}
return name as String
}
override var description: String {
return "<User: \(fullName)>"
}
init(firstName: String, lastName: String, userId: Int, city: String) {
self.firstName = firstName
self.lastName = lastName
self.userId = userId
self.city = city
}
convenience init(data: [String: String]) {
let firstName = data["firstname"]!
let lastName = data["lastname"]!
let userId = Int(data["id"]!)!
let city = data["city"]!
self.init(firstName: firstName, lastName: lastName, userId: userId, city: city)
}
}
func ==(lhs: User, rhs: User) -> Bool {
return lhs.userId == rhs.userId
}
|
f032ee58df89001219296f4b25f29ac0
| 21.925532 | 83 | 0.642691 | false | false | false | false |
ztyjr888/WeChat
|
refs/heads/master
|
WeChat/Plugins/Chat/WeChatChatViewController.swift
|
apache-2.0
|
1
|
//
// WeChatChatViewController.swift
// WeChat
//
// Created by Smile on 16/3/29.
// Copyright © 2016年 [email protected]. All rights reserved.
//
import UIKit
import AVFoundation
let messageOutSound: SystemSoundID = {
var soundID: SystemSoundID = 10120
let soundUrl = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "MessageOutgoing", "aiff", nil)
AudioServicesCreateSystemSoundID(soundUrl, &soundID)
return soundID
}()
let messageInSound: SystemSoundID = {
var soundID: SystemSoundID = 10121
let soundUrl = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "MessageIncoming", "aiff", nil)
AudioServicesCreateSystemSoundID(soundUrl, &soundID)
return soundID
}()
//聊天窗口页面
class WeChatChatViewController: UIViewController,UITableViewDataSource, UITableViewDelegate , UITextViewDelegate {
var tableView:UITableView!
var toolBarView:WeChatChatToolBar!
var recordIndicatorView: WeChatChatRecordIndicatorView!
var recordIndicatorCancelView:WeChatChatRecordIndicatorCancelView?
var videoController: WeChatChatVideoViewController!
let toolBarMinHeight: CGFloat = 50
let indicatorViewH: CGFloat = 150
var nagTitle:String!
var nagHeight:CGFloat = 0//导航条高度
var messageList = [ChatMessage]()
var toolBarConstranit: NSLayoutConstraint!
var recorder: WeChatChatAudioRecorder!
var player: WeChatChatAudioPlayer!
var shortView:WeChatChatRecordShortView?
override func viewDidLoad() {
super.viewDidLoad()
initFrame()
}
//MARKS: 初始化
func initFrame(){
//MARKS: 设置导航行背景及字体颜色
//WeChatNavigation().setNavigationBarProperties((self.navigationController?.navigationBar)!)
//解决录音时touchDown事件影响
self.navigationController!.interactivePopGestureRecognizer!.delaysTouchesBegan = false
let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
self.nagHeight = statusBarFrame.height + self.navigationController!.navigationBar.frame.height
self.navigationItem.title = self.nagTitle
self.view.backgroundColor = UIColor.whiteColor()
initTableView()
initToolBar()
initRecordIndicatorView()
addConstraints()
}
//MARKS: 添加约束
func addConstraints(){
view.addConstraint(NSLayoutConstraint(item: toolBarView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: toolBarView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: toolBarView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: toolBarMinHeight))
toolBarConstranit = NSLayoutConstraint(item: toolBarView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)
view.addConstraint(toolBarConstranit)
view.addConstraint(NSLayoutConstraint(item: tableView, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: tableView, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: tableView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: tableView, attribute: .Bottom, relatedBy: .Equal, toItem: toolBarView, attribute: .Top, multiplier: 1, constant: 0))
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "hiddenMenuController:", name: UIMenuControllerWillHideMenuNotification, object: nil)
}
//MARKS: 初始化toolBar
func initToolBar(){
toolBarView = WeChatChatToolBar(taget: self, voiceSelector: "voiceClick:", recordSelector: "recordClick:", emotionSelector: "emotionClick:", moreSelector: "moreClick:")
toolBarView.textView.delegate = self
view.addSubview(toolBarView)
toolBarView.translatesAutoresizingMaskIntoConstraints = false
}
//MARKS: 初始化tableView
func initTableView(){
tableView = UITableView()
tableView.backgroundColor = UIColor.clearColor()
tableView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 44.0 //估算高度
tableView.contentInset = UIEdgeInsetsMake(0, 0, toolBarMinHeight / 2, 0)//内边距
tableView.separatorStyle = .None
tableView.registerClass(WeChatChatTextCell.self, forCellReuseIdentifier: NSStringFromClass(WeChatChatTextCell))
tableView.registerClass(WeChatChatVoiceCell.self, forCellReuseIdentifier: NSStringFromClass(WeChatChatVoiceCell))
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "tapTableView:"))
}
func initRecordIndicatorView(){
recordIndicatorView = WeChatChatRecordIndicatorView(frame: CGRectMake(self.view.center.x - indicatorViewH / 2, self.view.center.y - indicatorViewH / 3, indicatorViewH, indicatorViewH))
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if player != nil {
if player.audioPlayer.playing {
player.stopPlaying()
}
}
}
// show menuController
override func canBecomeFirstResponder() -> Bool {
return true
}
// MARK: - tableView dataSource/Delegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messageList.count
}
//MAKRS: tableView添加Cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: WeChatChatBaseCell?
let message = messageList[indexPath.row]
switch message.messageType {
case .Text:
cell = tableView.dequeueReusableCellWithIdentifier(NSStringFromClass(WeChatChatTextCell), forIndexPath: indexPath) as! WeChatChatTextCell
break
case .Voice:
cell = tableView.dequeueReusableCellWithIdentifier(NSStringFromClass(WeChatChatVoiceCell), forIndexPath: indexPath) as! WeChatChatVoiceCell
break
default:
cell = nil
break
}
//添加双击和长按手势菜单
let action: Selector = "showMenuAction:"
let doubleTapGesture = UITapGestureRecognizer(target: self, action: action)
doubleTapGesture.numberOfTapsRequired = 2
cell!.backgroundImageView.addGestureRecognizer(doubleTapGesture)
cell!.backgroundImageView.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: action))
cell!.backgroundImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "clickCellAction:"))
if indexPath.row > 0 {
let preMessage = messageList[indexPath.row - 1]
if preMessage.dataString == message.dataString {
cell!.timeLabel.hidden = true
} else {
cell!.timeLabel.hidden = false
}
}
cell!.setMessage(message)
return cell!
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
return nil
}
//MARKS: 添加tableViewCell后自动滚动到底部
func scrollToBottom() {
let numberOfRows = tableView.numberOfRowsInSection(0)
if numberOfRows > 0 {
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: numberOfRows - 1, inSection: 0), atScrollPosition: .Bottom, animated: true)
}
}
//MARKS: 刷新table
func reloadTableView() {
let count = messageList.count
tableView.beginUpdates()
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: count - 1, inSection: 0)], withRowAnimation: .Top)
tableView.endUpdates()
scrollToBottom()
}
// MARK: scrollview delegate
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if velocity.y > 2.0 {
scrollToBottom()
self.toolBarView.textView.becomeFirstResponder()
} else if velocity.y < -0.1 {
self.toolBarView.textView.resignFirstResponder()
}
}
// MARK: - keyBoard notification
func keyboardChange(notification: NSNotification) {
let userInfo = notification.userInfo as NSDictionary!
let newFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let animationTimer = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
view.layoutIfNeeded()
if newFrame.origin.y == UIScreen.mainScreen().bounds.size.height {
UIView.animateWithDuration(animationTimer, animations: { () -> Void in
self.toolBarConstranit.constant = 0
self.view.layoutIfNeeded()
})
} else {
UIView.animateWithDuration(animationTimer, animations: { () -> Void in
self.toolBarConstranit.constant = -newFrame.size.height
self.scrollToBottom()
self.view.layoutIfNeeded()
})
}
}
func showMenuAction(gestureRecognizer: UITapGestureRecognizer) {
let twoTaps = (gestureRecognizer.numberOfTapsRequired == 2)
let doubleTap = (twoTaps && gestureRecognizer.state == .Ended)
let longPress = (!twoTaps && gestureRecognizer.state == .Began)
if doubleTap || longPress {
let pressIndexPath = tableView.indexPathForRowAtPoint(gestureRecognizer.locationInView(tableView))!
tableView.selectRowAtIndexPath(pressIndexPath, animated: false, scrollPosition: .None)
let menuController = UIMenuController.sharedMenuController()
let localImageView = gestureRecognizer.view!
menuController.setTargetRect(localImageView.frame, inView: localImageView.superview!)
menuController.menuItems = [UIMenuItem(title: "复制", action: "copyAction:"), UIMenuItem(title: "转发", action: "transtionAction:"), UIMenuItem(title: "删除", action: "deleteAction:"), UIMenuItem(title: "更多", action: "moreAciton:")]
menuController.setMenuVisible(true, animated: true)
}
}
//MARKS: 复制
func copyAction(menuController: UIMenuController) {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
if let message = messageList[selectedIndexPath.row] as? TextMessage {
UIPasteboard.generalPasteboard().string = message.text
}
}
}
//MARKS: 转发
func transtionAction(menuController: UIMenuController) {
NSLog("转发")
}
//MARKS: 删除
func deleteAction(menuController: UIMenuController) {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
messageList.removeAtIndex(selectedIndexPath.row)
tableView.reloadData()
}
}
//MARKS: 更多
func moreAciton(menuController: UIMenuController) {
NSLog("click more")
}
// MARK: - gestureRecognizer
func tapTableView(gestureRecognizer: UITapGestureRecognizer) {
self.view.endEditing(true)
toolBarConstranit.constant = 0
toolBarView.showEmotion(false)
toolBarView.showMore(false)
}
func hiddenMenuController(notifiacation: NSNotification) {
if let selectedIndexpath = tableView.indexPathForSelectedRow {
tableView.deselectRowAtIndexPath(selectedIndexpath, animated: false)
}
(notifiacation.object as! UIMenuController).menuItems = nil
}
func clickCellAction(gestureRecognizer: UITapGestureRecognizer) {
let pressIndexPath = tableView.indexPathForRowAtPoint(gestureRecognizer.locationInView(tableView))!
let pressCell = tableView.cellForRowAtIndexPath(pressIndexPath)
let message = messageList[pressIndexPath.row]
if message.messageType == .Voice {
let message = message as! VoiceMessage
let cell = pressCell as! WeChatChatVoiceCell
let play = WeChatChatAudioPlayer()
player = play
player.startPlaying(message)
cell.beginAnimation()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(message.voiceTime.intValue) * 1000 * 1000 * 1000), dispatch_get_main_queue(), { () -> Void in
cell.stopAnimation()
})
} else if message.messageType == .Video {
let message = message as! VideoMessage
if videoController != nil {
videoController = nil
}
videoController = WeChatChatVideoViewController()
videoController.setPlayUrl(message.url)
presentViewController(videoController, animated: true, completion: nil)
}
}
}
extension WeChatChatViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate,WeChatChatAudioRecorderDelegate{
//MARKS: 点击左边图片事件
func voiceClick(button: UIButton) {
if toolBarView.recordButton.hidden == false {
toolBarView.showRecord(false)
} else {
toolBarView.showRecord(true)
self.view.endEditing(true)
}
}
//marks: 语音按住speak
func recordClick(button: UIButton) {
button.setTitle(talkButtonHightedMessage, forState: .Normal)
button.addTarget(self, action: "recordComplection:", forControlEvents: .TouchUpInside)
button.addTarget(self, action: "recordDragOut:", forControlEvents: .TouchDragOutside)
button.addTarget(self, action: "recordDragIn:", forControlEvents: .TouchDragInside)
button.addTarget(self, action: "recordCancel:", forControlEvents: .TouchUpOutside)
button.addTarget(self, action: "recordDragExit:", forControlEvents: .TouchDragExit)
button.addTarget(self, action: "recordDragEnter:", forControlEvents: .TouchDragEnter)
let currentTime = NSDate().timeIntervalSinceReferenceDate
let record = WeChatChatAudioRecorder(fileName: "\(currentTime).wav")
record.delegate = self
recorder = record
recorder.startRecord()
recordIndicatorView = WeChatChatRecordIndicatorView(frame: CGRectMake(self.view.center.x - indicatorViewH / 2, self.view.center.y - indicatorViewH / 3, indicatorViewH, indicatorViewH))
view.addSubview(recordIndicatorView)
}
//MARKS: 从控件窗口之外拖动到内部
func recordDragEnter(button: UIButton){
button.setTitle(talkButtonHightedMessage, forState: .Normal)
recorder.startRecord()
if recordIndicatorCancelView != nil {
recordIndicatorCancelView?.removeFromSuperview()
}
//recordIndicatorView.showText(talkMessage, textColor: UIColor.whiteColor())
view.addSubview(recordIndicatorView)
}
//MARKS: 手指在控件上拖动
func recordDragIn(button: UIButton){
}
//MARKS: 控件窗口内部拖动到外部
func recordDragExit(button: UIButton){
button.setTitle(talkButtonHightedMessage, forState: .Normal)
recorder.stopRecord()
recordIndicatorView.removeFromSuperview()
createCancelView()
view.addSubview(recordIndicatorCancelView!)
}
func createCancelView(){
if recordIndicatorCancelView == nil {
recordIndicatorCancelView = WeChatChatRecordIndicatorCancelView(frame: CGRectMake(self.view.center.x - indicatorViewH / 2, self.view.center.y - indicatorViewH / 3, indicatorViewH, indicatorViewH))
}
}
//MARKS: speak完成
func recordComplection(button: UIButton) {
button.setTitle(talkButtonDefaultMessage, forState: .Normal)
recorder.stopRecord()
recorder.delegate = nil
recordIndicatorView.removeFromSuperview()
recordIndicatorView = nil
if recorder.timeInterval != nil {
var time = 0
if recorder.timeInterval.intValue < 1 {
time = 1
}
let message = VoiceMessage(incoming: false, sentDate: NSDate(), iconName: "", voicePath: recorder.recorder.url, voiceTime: time)
let receiveMessage = VoiceMessage(incoming: true, sentDate: NSDate(), iconName: "", voicePath: recorder.recorder.url, voiceTime: time)
messageList.append(message)
reloadTableView()
//messageList.append(receiveMessage)
//reloadTableView()
AudioServicesPlayAlertSound(messageOutSound)
}else{
createShortView()
}
}
//MARKS: 移除shortView
func readyToRemoveShorView(){
self.shortView?.removeFromSuperview()
}
//MARKS: 说话时间太短
func createShortView(){
if self.shortView == nil {
self.shortView = WeChatChatRecordShortView(frame: CGRectMake(self.view.center.x - indicatorViewH / 2, self.view.center.y - indicatorViewH / 3, indicatorViewH, indicatorViewH))
}
self.view.addSubview(self.shortView!)
performSelector("readyToRemoveShorView", withObject: self, afterDelay: 0.2)
}
//MARKS: 触摸在控件外拖动时
func recordDragOut(button: UIButton) {
button.setTitle(talkButtonDefaultMessage, forState: .Normal)
recorder.stopRecord()
createCancelView()
view.addSubview(recordIndicatorCancelView!)
}
//MARKS: speak取消
func recordCancel(button: UIButton) {
button.setTitle(talkButtonDefaultMessage, forState: .Normal)
recorder.stopRecord()
recorder.delegate = nil
recordIndicatorView.removeFromSuperview()
recordIndicatorView = nil
recordIndicatorCancelView?.removeFromSuperview()
recordIndicatorCancelView = nil
}
// MARK: -WeChatChatAudioRecorderDelegate
func audioRecorderUpdateMetra(metra: Float) {
if recordIndicatorView != nil {
recordIndicatorView.updateLevelMetra(metra)
}
}
// MARK: - textViewDelegate
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
let messageStr = textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if messageStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0 {
return true
}
let message = TextMessage(incoming: false, sentDate: NSDate(), iconName: "", text: messageStr)
let receiveMessage = TextMessage(incoming: true, sentDate: NSDate(), iconName: "", text: messageStr)
messageList.append(message)
reloadTableView()
//messageList.append(receiveMessage)
//reloadTableView()
AudioServicesPlayAlertSound(messageOutSound)
textView.text = ""
return false
}
return true
}
}
|
cf2f599e0fc5934dda1bead873bd0dcb
| 39.736735 | 238 | 0.665548 | false | false | false | false |
makma/cloud-sdk-swift
|
refs/heads/master
|
KenticoCloud/Classes/DeliveryService/Models/ElementTypes/RichTextElement.swift
|
mit
|
1
|
//
// RichTextElement.swift
// Pods
//
// Created by Martin Makarsky on 04/09/2017.
//
//
import Kanna
import ObjectMapper
/// Represents RichText element.
public class RichTextElement: Mappable {
private var elementName: String = ""
private var supportedBlocksXpath = "//p | //h1 | //h2 | //h3 | //h4 | //strong | //em | //ol | //ul | //a | //object[@type='application/kenticocloud'][@data-type='item'] | //figure"
public private(set) var type: String?
public private(set) var name: String?
public private(set) var value: String?
public private(set) var blocks: [Block?] = []
public private(set) var inlineImages: [InlineImageBlock?] = []
public private(set) var htmlContent: [HtmlContentBlock?] = []
public private(set) var linkedItems: [LinkedItemsBlock?] = []
public private(set) var htmlContentString: String = ""
/// Maps response's json instance of the element into strongly typed object representation.
public required init?(map: Map){
if let context = map.context as? ElementContext {
elementName = context.elementName
}
let value = map["elements.\(elementName).value"].currentValue as? String
if let value = value {
if let doc = try? HTML(html: value, encoding: .utf8) {
let supportedBlocks = doc.xpath(supportedBlocksXpath)
for block in supportedBlocks {
if let tag = block.tagName {
switch tag {
case "p", "h1", "h2", "h3", "h4", "ol", "ul", "strong", "em", "a":
if let htmlContentblock = HtmlContentBlock.init(html: block.toHTML) {
self.blocks.append(htmlContentblock)
htmlContent.append(htmlContentblock)
}
if let contentString = block.toHTML {
htmlContentString.append(contentString)
}
case "object":
if let block = LinkedItemsBlock.init(html: block.toHTML) {
self.blocks.append(block)
linkedItems.append(block)
}
case "figure":
if let block = InlineImageBlock.init(html: block.toHTML) {
self.blocks.append(block)
inlineImages.append(block)
}
default:
print("Unknown block")
}
}
}
}
}
}
/// Maps response's json instance of the element into strongly typed object representation.
public func mapping(map: Map) {
type <- map["elements.\(elementName).type"]
name <- map["elements.\(elementName).name"]
value <- map["elements.\(elementName).value"]
}
}
|
b5b68ba7edb2f1915a026c25613bd2bb
| 41.223684 | 185 | 0.488314 | false | false | false | false |
Daij-Djan/DDUtils
|
refs/heads/master
|
swift/ddutils-ios/ui/CloudEmitterView [ios + demo]/CloudEmitterView.swift
|
mit
|
1
|
//
// CloudEmitterView.swift
// Created by D.Pich based on view created with Particle Playground on 8/23/16
//
import UIKit
class CloudEmitterView: UIView {
override class var layerClass: AnyClass {
get {
return CAEmitterLayer.self
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
let emitterLayer = layer as! CAEmitterLayer
//setup layer
emitterLayer.name = "emitterLayer"
emitterLayer.emitterSize = CGSize(width: 1.00, height: 5000)
emitterLayer.emitterDepth = 100.00
emitterLayer.emitterShape = kCAEmitterLayerRectangle
emitterLayer.emitterMode = kCAEmitterLayerOutline
emitterLayer.seed = 2491098502
// Create the emitter Cell
// let emitterCell1 = createEmitterForClouds1()
let emitterCell2 = createEmitterForClouds2()
//assign the emitter to the layer
// emitterLayer.emitterCells = [emitterCell1, emitterCell2]
emitterLayer.emitterCells = [emitterCell2]
}
func createEmitterForClouds1() -> CAEmitterCell {
// Create the emitter Cell
let emitterCell = CAEmitterCell()
emitterCell.name = "Clouds1"
emitterCell.isEnabled = true
let img = UIImage(named: "Clouds1")
emitterCell.contents = img?.cgImage
emitterCell.contentsRect = CGRect(x:0.00, y:0.00, width:3.00, height:1.00)
emitterCell.magnificationFilter = kCAFilterLinear
emitterCell.minificationFilter = kCAFilterLinear
emitterCell.minificationFilterBias = 0.00
emitterCell.scale = 0.3
emitterCell.scaleRange = 0.2
emitterCell.scaleSpeed = 0.1
let color = UIColor(red:1, green:1, blue:1, alpha:1)
emitterCell.color = color.cgColor
emitterCell.redRange = 0.00
emitterCell.greenRange = 0.00
emitterCell.blueRange = 0.00
emitterCell.alphaRange = 1.00
emitterCell.redSpeed = 0.00
emitterCell.greenSpeed = 0.00
emitterCell.blueSpeed = 0.00
emitterCell.alphaSpeed = 0.00
emitterCell.lifetime = 500.00
emitterCell.lifetimeRange = 0.00
emitterCell.birthRate = 1
emitterCell.velocity = 5.00
emitterCell.velocityRange = 5.00
emitterCell.xAcceleration = 1.00
emitterCell.yAcceleration = 0.00
emitterCell.zAcceleration = 0.00
// these values are in radians, in the UI they are in degrees
emitterCell.spin = 0.000
emitterCell.spinRange = 0.000
emitterCell.emissionLatitude = 0.017
emitterCell.emissionLongitude = 0.017
emitterCell.emissionRange = 1.745
return emitterCell
}
func createEmitterForClouds2() -> CAEmitterCell {
// Create the emitter Cell
let emitterCell = CAEmitterCell()
emitterCell.name = "Clouds2"
emitterCell.isEnabled = true
let img = UIImage(named: "Clouds2.png")
emitterCell.contents = img?.cgImage
emitterCell.contentsRect = CGRect(x:0.00, y:0.00, width:3.00, height:1.00)
emitterCell.magnificationFilter = kCAFilterLinear
emitterCell.minificationFilter = kCAFilterLinear
emitterCell.minificationFilterBias = 0.00
emitterCell.scale = 0.30
emitterCell.scaleRange = 0.20
emitterCell.scaleSpeed = 0.00
let color = UIColor(red:1, green:1, blue:1, alpha:1)
emitterCell.color = color.cgColor
emitterCell.redRange = 0.00
emitterCell.greenRange = 0.00
emitterCell.blueRange = 0.00
emitterCell.alphaRange = 1.00
emitterCell.redSpeed = 0.00
emitterCell.greenSpeed = 0.00
emitterCell.blueSpeed = 0.00
emitterCell.alphaSpeed = 0.00
emitterCell.lifetime = 500.00
emitterCell.lifetimeRange = 0.00
emitterCell.birthRate = 1
emitterCell.velocity = 5.00
emitterCell.velocityRange = 5.00
emitterCell.xAcceleration = 1.00
emitterCell.yAcceleration = 0.00
emitterCell.zAcceleration = 0.00
// these values are in radians, in the UI they are in degrees
emitterCell.spin = 0.000
emitterCell.spinRange = 0.000
emitterCell.emissionLatitude = 0.017
emitterCell.emissionLongitude = 0.017
emitterCell.emissionRange = 1.745
return emitterCell
}
}
|
beeb9c29e9e2dc6b9e25ef09e61fd793
| 31.931507 | 82 | 0.622088 | false | false | false | false |
AndrejJurkin/nova-osx
|
refs/heads/master
|
Nova/data/firebase/News.swift
|
apache-2.0
|
1
|
//
// Copyright 2017 Andrej Jurkin.
//
// 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.
//
//
// News.swift
// Nova
//
// Created by Andrej Jurkin on 12/30/17.
//
import Foundation
import RealmSwift
import ObjectMapper
class News: RealmObject, Mappable {
dynamic var id: Int = 0
dynamic var title: String = ""
dynamic var subtitle: String = ""
dynamic var link: String = ""
dynamic var imageUrl: String = ""
dynamic var buttonTitle: String = ""
dynamic var hidden: Bool = false
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
self.id <- map["id"]
self.title <- map["title"]
self.subtitle <- map["subtitle"]
self.link <- map["link"]
self.imageUrl <- map["imageUrl"]
self.buttonTitle <- map["buttonTitle"]
self.hidden <- map["hidden"]
}
override static func primaryKey() -> String? {
return "id"
}
}
|
44f33e7a836d6e0330544246388c2c11
| 26.648148 | 76 | 0.636973 | false | false | false | false |
JadenGeller/GraphView
|
refs/heads/master
|
Sources/EdgeBacking.swift
|
mit
|
1
|
//
// EdgeBacking.swift
// Edgy
//
// Created by Jaden Geller on 1/22/16.
// Copyright © 2016 Jaden Geller. All rights reserved.
//
internal class EdgeBacking<Node: Hashable> {
var nodesReachableFromNode = Dictionary<Node, Set<Node>>()
init(nodesReachableFromNode: Dictionary<Node, Set<Node>> = [:]) {
self.nodesReachableFromNode = nodesReachableFromNode
}
func copyByTrimmingIrrelevantNodes(relevantNodes relevantNodes: Set<Node>) -> EdgeBacking {
var copy = Dictionary<Node, Set<Node>>()
for (key, value) in nodesReachableFromNode {
if relevantNodes.contains(key) {
copy[key] = value.intersect(relevantNodes)
}
}
return EdgeBacking(nodesReachableFromNode: copy)
}
}
|
791811d52621c46c9ee7c1fe16d20c89
| 30.32 | 95 | 0.649616 | false | false | false | false |
DianQK/rx-sample-code
|
refs/heads/master
|
HandleError/QRScan/QRReadViewController.swift
|
mit
|
1
|
//
// QRReadViewController.swift
// HandleError
//
// Created by wc on 28/12/2016.
// Copyright © 2016 T. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import AVFoundation
let supportedCodeTypes = [AVMetadataObjectTypeUPCECode,
AVMetadataObjectTypeCode39Code,
AVMetadataObjectTypeCode39Mod43Code,
AVMetadataObjectTypeCode93Code,
AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypeEAN8Code,
AVMetadataObjectTypeEAN13Code,
AVMetadataObjectTypeAztecCode,
AVMetadataObjectTypePDF417Code,
AVMetadataObjectTypeQRCode]
/// 扫描二维码错误
///
/// - denied: 权限被拒绝
/// - unavailable: 相机不可用
enum QRScanError: Swift.Error {
case denied
case unavailable(Swift.Error)
case machineUnreadableCodeObject
}
class QRReadViewController: UIViewController {
@IBOutlet private weak var cancelBarButtonItem: UIBarButtonItem!
private let captureSession = AVCaptureSession()
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
Observable
.just(AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo))
.flatMap { authorizationStatus -> Observable<()> in
switch authorizationStatus {
case .authorized:
return Observable.just()
case .notDetermined:
return AVCaptureDevice.rx.requestAccess(forMediaType: AVMediaTypeVideo)
.flatMap { result -> Observable<()> in
if result {
return Observable.just(())
} else {
return Observable.error(QRScanError.denied)
}
}
.asObservable()
case .denied, .restricted:
return Observable.error(QRScanError.denied)
}
}
.flatMap { [unowned self] () -> Observable<(metadataObjects: [Any], connection: AVCaptureConnection)> in
let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
let input = try AVCaptureDeviceInput(device: captureDevice)
let videoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)!
videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer.frame = self.view.layer.bounds
self.view.layer.addSublayer(videoPreviewLayer)
self.captureSession.addInput(input)
let captureMetadataOutput = AVCaptureMetadataOutput()
self.captureSession.addOutput(captureMetadataOutput)
captureMetadataOutput.metadataObjectTypes = supportedCodeTypes
self.captureSession.startRunning()
return captureMetadataOutput.rx.didOutputMetadataObjects
}
.flatMap { (metadataObjects: [Any], connection: AVCaptureConnection) -> Observable<String> in
guard let metadataObj = metadataObjects.flatMap({ $0 as? AVMetadataMachineReadableCodeObject }).first else {
return Observable.empty()
}
guard let value = metadataObj.stringValue else {
return Observable.error(QRScanError.machineUnreadableCodeObject)
}
return Observable.just(value)
}
.debug()
.subscribe()
.disposed(by: disposeBag)
}
}
|
70831dcfce1575ce20467161456a5939
| 37.816327 | 124 | 0.586751 | false | false | false | false |
jdbateman/Lendivine
|
refs/heads/master
|
Lendivine/MapWithCheckoutViewController.swift
|
mit
|
1
|
//
// MapWithCheckoutViewController.swift
// Lendivine
//
// Created by john bateman on 4/3/16.
// Copyright © 2016 John Bateman. All rights reserved.
//
// This is the Cart Map View Controller which presents an MKMapView containing pins for each loan in the cart.
import UIKit
import MapKit
class MapWithCheckoutViewController: MapViewController {
var cart:KivaCart?
override func viewDidLoad() {
super.viewDidLoad()
self.kivaAPI = KivaAPI.sharedInstance
cart = KivaCart.sharedInstance
modifyBarButtonItems()
}
func modifyBarButtonItems() {
let loansByListButton = UIBarButtonItem(image: UIImage(named: "Donate-32"), style: .Plain, target: self, action: #selector(MapWithCheckoutViewController.onLoansByListButtonTap))
navigationItem.setRightBarButtonItems([loansByListButton], animated: true)
// remove back button
navigationItem.hidesBackButton = true
}
@IBAction func onCheckoutButtonTapped(sender: AnyObject) {
let loans = cart!.getLoans2()
KivaLoan.getCurrentFundraisingStatus(loans, context: CoreDataContext.sharedInstance().cartScratchContext) {
success, error, fundraising, notFundraising in
if success {
// remove notFundraising loans from the cart
if let notFundraising = notFundraising {
if notFundraising.count > 0 {
if var loans = loans {
for notFRLoan in notFundraising {
if let index = loans.indexOf(notFRLoan) {
loans.removeAtIndex(index)
}
// UIAlertController
var userMessage = "The following loans are no longer raising funds and have been removed from the cart:\n\n"
var allRemovedLoansString = ""
for nfLoan in notFundraising {
if let country = nfLoan.country, name = nfLoan.name, sector = nfLoan.sector {
let removedLoanString = String(format: "%@, %@, %@\n", name, sector, country)
allRemovedLoansString.appendContentsOf(removedLoanString)
}
}
userMessage.appendContentsOf(allRemovedLoansString)
let alertController = UIAlertController(title: "Cart Modified", message: userMessage, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
UIAlertAction in
self.displayKivaWebCartInBrowser()
}
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
} else {
// There are no loans to remove from the cart
self.displayKivaWebCartInBrowser()
}
}
} else {
// Even though an error occured just continue on to the cart on Kiva.org and they will handle any invalid loans in the cart.
print("Non-fatal error confirming fundraising status of loans.")
self.displayKivaWebCartInBrowser()
}
}
}
/*! Clear local cart of all items and present the Kiva web cart in the browser. */
func displayKivaWebCartInBrowser() {
// Display web cart.
self.showEmbeddedBrowser()
// Note: Enable this line if you want to remove all items from local cart view.
// cart?.empty()
}
/* Display url in an embeded webkit browser. */
func showEmbeddedBrowser() {
let controller = KivaCartViewController()
if let kivaAPI = self.kivaAPI {
controller.request = kivaAPI.getKivaCartRequest() // KivaCheckout()
}
// add the view controller to the navigation controller stack
self.navigationController?.pushViewController(controller, animated: true)
}
}
|
bec66b88c2ab02d57c82c4087fc946e9
| 42.161905 | 185 | 0.545675 | false | false | false | false |
tbointeractive/bytes
|
refs/heads/develop
|
Example/bytesTests/Specs/UIImage+ColorSpec.swift
|
mit
|
1
|
//
// UIImage+ColorSpec.swift
// bytesTests
//
// Created by Cornelius Horstmann on 06.06.18.
// Copyright © 2018 TBO INTERACTIVE GmbH & Co. KG. All rights reserved.
//
import bytes
import Quick
import Nimble
import Nimble_Snapshots
// replace "haveValidSnapshot()" with "recordSnapshot()" to record a new reference image
class UIImageColorSpec: QuickSpec {
override func spec() {
describe("uiimagefromcolorcache") {
it("should be not nil per default") {
expect(UIImage.imageFromColorCache).toNot(beNil())
}
it("should have a countLimit of 10 per default") {
expect(UIImage.imageFromColorCache?.countLimit) == 10
}
it("should be settable and keep its settings") {
let oldCache = UIImage.imageFromColorCache
UIImage.imageFromColorCache = NSCache<UIColor, UIImage>()
expect(UIImage.imageFromColorCache?.countLimit) == 0
UIImage.imageFromColorCache = oldCache
}
it("should be settable to nil") {
let oldCache = UIImage.imageFromColorCache
UIImage.imageFromColorCache = nil
expect(UIImage.imageFromColorCache).to(beNil())
UIImage.imageFromColorCache = oldCache
}
}
describe("fromColor") {
it("should return an image") {
let image = UIImage.from(.green)
expect(image).toNot(beNil())
}
it("should return an image with the size of 1x1") {
let image = UIImage.from(.green)
expect(image.size) == CGSize(width: 1, height: 1)
}
it("should return the exact same image from the cache if requesting one with the same color") {
let imageOne = UIImage.from(.green)
let imageTwo = UIImage.from(.green)
expect(imageOne == imageTwo) == true
}
it("should return an image with the correct color") {
let image = UIImage.from(.green)
expect(UIImageView(image: image)).to(haveValidSnapshot())
}
it("should return an image with the correct color, if the color has an alpha value") {
let color = UIColor.green.setting(alpha: 0.5)
let image = UIImage.from(color)
expect(UIImageView(image: image)).to(haveValidSnapshot())
}
}
}
}
|
5f1922b0f5969b6b0136650c814321a2
| 38.34375 | 107 | 0.569897 | false | false | false | false |
nextcloud/ios
|
refs/heads/master
|
iOSClient/Login/NCLoginQRCode.swift
|
gpl-3.0
|
1
|
//
// NCLoginQRCode.swift
// Nextcloud
//
// Created by Marino Faggiana on 04/03/2019.
// Copyright © 2019 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import QRCodeReader
@objc public protocol NCLoginQRCodeDelegate {
@objc func dismissQRCode(_ value: String?, metadataType: String?)
}
class NCLoginQRCode: NSObject, QRCodeReaderViewControllerDelegate {
lazy var reader: QRCodeReader = QRCodeReader()
weak var delegate: UIViewController?
lazy var readerVC: QRCodeReaderViewController = {
let builder = QRCodeReaderViewControllerBuilder {
$0.reader = QRCodeReader(metadataObjectTypes: [.qr], captureDevicePosition: .back)
$0.showTorchButton = true
$0.preferredStatusBarStyle = .lightContent
$0.showOverlayView = true
$0.rectOfInterest = CGRect(x: 0.2, y: 0.2, width: 0.6, height: 0.6)
$0.reader.stopScanningWhenCodeIsFound = false
}
return QRCodeReaderViewController(builder: builder)
}()
override init() {
}
@objc public init(delegate: UIViewController) {
self.delegate = delegate
}
@objc func scan() {
guard checkScanPermissions() else { return }
readerVC.modalPresentationStyle = .formSheet
readerVC.delegate = self
readerVC.completionBlock = { (_: QRCodeReaderResult?) in
self.readerVC.dismiss(animated: true, completion: nil)
}
delegate?.present(readerVC, animated: true, completion: nil)
}
private func checkScanPermissions() -> Bool {
do {
return try QRCodeReader.supportsMetadataObjectTypes()
} catch let error as NSError {
let alert: UIAlertController
switch error.code {
case -11852:
alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_qrcode_not_authorized_", comment: ""), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("_settings_", comment: ""), style: .default, handler: { _ in
DispatchQueue.main.async {
if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
}
}
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: nil))
default:
alert = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_qrcode_not_supported_", comment: ""), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .cancel, handler: nil))
}
delegate?.present(alert, animated: true, completion: nil)
return false
}
}
func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) {
reader.stopScanning()
(self.delegate as? NCLoginQRCodeDelegate)?.dismissQRCode(result.value, metadataType: result.metadataType)
}
func readerDidCancel(_ reader: QRCodeReaderViewController) {
reader.stopScanning()
(self.delegate as? NCLoginQRCodeDelegate)?.dismissQRCode(nil, metadataType: nil)
}
}
|
5e253600dfe7d0c2c0246fb1d1aabeb1
| 36 | 183 | 0.65128 | false | false | false | false |
yellowei/HWPicker
|
refs/heads/master
|
HWPhotoPicker-Swift/Views/VideoElementInfoView.swift
|
mit
|
1
|
//
// VideoElementInfoView.swift
// HWPicker
//
// Created by yellowei on 2017/5/17.
// Copyright © 2017年 yellowei. All rights reserved.
//
import UIKit
class VideoElementInfoView: UIView {
private var _duration: CGFloat = 0.0
var duration: CGFloat {
get {
return _duration
}
set {
_duration = newValue
if _duration >= 0 && _duration < 60*60 {
let min: Int = Int(_duration / 60.0)
let sec: Int = Int(_duration - CGFloat(60.0) * CGFloat(min))
durationLabel.text = String.init(format: "%zd:%02zd", min, sec)
}else if _duration >= 60*60 && _duration < 60*60*60 {
let hour: Int = Int(_duration / (60.0*60.0))
let min: Int = Int((_duration - CGFloat(60.0*60.0) * CGFloat(hour)) / 60.0)
let sec: Int = Int(_duration - CGFloat(60*60) * CGFloat(hour) - CGFloat(60*min))
self.durationLabel.text = String.init(format: "%zd:%02zd:%02zd", hour, min, sec)
}
}
}
private var durationLabel: UILabel
override init(frame: CGRect) {
durationLabel = UILabel()
super.init(frame: frame)
self.backgroundColor = UIColor.init(white: 0, alpha: 0.65)
//ImageView
let iconImageViewFrame = CGRect(x: 6, y: (self.bounds.size.height - 8) / 2, width: 14, height: 8)
let iconImageView = UIImageView.init(frame: iconImageViewFrame)
iconImageView.image = UIImage.init(named: "video")
iconImageView.autoresizingMask = UIViewAutoresizing.flexibleRightMargin
self.addSubview(iconImageView)
//Label
let durationLabelFrame: CGRect = CGRect(x: iconImageViewFrame.origin.x + iconImageViewFrame.size.width + 6,
y: 0,
width: self.bounds.size.width - (iconImageViewFrame.origin.x + iconImageViewFrame.size.width + 6),
height: self.bounds.size.height)
durationLabel.frame = durationLabelFrame
durationLabel.backgroundColor = UIColor.clear
durationLabel.textAlignment = NSTextAlignment.right
durationLabel.textColor = UIColor.white
durationLabel.font = UIFont.systemFont(ofSize: 12)
durationLabel.autoresizingMask = UIViewAutoresizing.init(rawValue: (UIViewAutoresizing.flexibleLeftMargin.rawValue | UIViewAutoresizing.flexibleWidth.rawValue))
self.addSubview(durationLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
f58e8d2bd6dbb3874193647cb18f0af0
| 34.728395 | 168 | 0.553214 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/CryptoAssets/Sources/BitcoinKit/Models/Accounts/KeyPair/BitcoinKeyPairDeriver.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import RxSwift
import WalletCore
struct BitcoinPrivateKey: Equatable {
let xpriv: String
init(xpriv: String) {
self.xpriv = xpriv
}
}
struct BitcoinKeyPair: KeyPair, Equatable {
let xpub: String
let privateKey: BitcoinPrivateKey
init(privateKey: BitcoinPrivateKey, xpub: String) {
self.privateKey = privateKey
self.xpub = xpub
}
}
struct BitcoinKeyDerivationInput: KeyDerivationInput, Equatable {
let mnemonic: String
let passphrase: String
init(mnemonic: String, passphrase: String = "") {
self.mnemonic = mnemonic
self.passphrase = passphrase
}
}
protocol BitcoinKeyPairDeriverAPI: KeyPairDeriverAPI where Input == BitcoinKeyDerivationInput, Pair == BitcoinKeyPair {
func derive(input: Input) -> Result<Pair, HDWalletError>
}
class AnyBitcoinKeyPairDeriver: BitcoinKeyPairDeriverAPI {
private let deriver: AnyKeyPairDeriver<BitcoinKeyPair, BitcoinKeyDerivationInput, HDWalletError>
// MARK: - Init
convenience init() {
self.init(with: BitcoinKeyPairDeriver())
}
init<D: KeyPairDeriverAPI>(
with deriver: D
) where D.Input == BitcoinKeyDerivationInput, D.Pair == BitcoinKeyPair, D.Error == HDWalletError {
self.deriver = AnyKeyPairDeriver(deriver: deriver)
}
func derive(input: BitcoinKeyDerivationInput) -> Result<BitcoinKeyPair, HDWalletError> {
deriver.derive(input: input)
}
}
class BitcoinKeyPairDeriver: BitcoinKeyPairDeriverAPI {
func derive(input: BitcoinKeyDerivationInput) -> Result<BitcoinKeyPair, HDWalletError> {
let bitcoinCoinType = CoinType.bitcoin
guard let hdwallet = HDWallet(mnemonic: input.mnemonic, passphrase: input.passphrase) else {
return .failure(.walletFailedToInitialise())
}
let privateKey = hdwallet.getExtendedPrivateKey(purpose: .bip44, coin: bitcoinCoinType, version: .xprv)
let xpub = hdwallet.getExtendedPublicKey(purpose: .bip44, coin: bitcoinCoinType, version: .xpub)
let bitcoinPrivateKey = BitcoinPrivateKey(xpriv: privateKey)
let keyPair = BitcoinKeyPair(
privateKey: bitcoinPrivateKey,
xpub: xpub
)
return .success(keyPair)
}
}
|
28c297b22c36ad0f417d8ace767d371c
| 29.802632 | 119 | 0.70141 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/RulerControllerWithScrollView.swift
|
mit
|
1
|
//
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
import UIKit
import SnapKit
class RulerControllerWithScrollView: UIViewController, UIScrollViewDelegate {
let DIAMETER: CGFloat = 80
let MARGIN: CGFloat = 16
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.clipsToBounds = true
automaticallyAdjustsScrollViewInsets = false
let touchView = TouchDelegateView()
touchView.touchDelegateView = scrollView
view.addSubview(touchView)
touchView.snp.makeConstraints { (make) in
make.top.bottom.leading.trailing.equalTo(view)
}
view.addSubview(scrollView)
scrollView.snp.makeConstraints { (make) in
make.top.bottom.equalTo(view)
make.width.equalTo(DIAMETER + MARGIN)
make.centerX.equalTo(view)
}
scrollView.clipsToBounds = false
scrollView.addSubview(contentView)
for subview in contentView.subviews {
subview.removeFromSuperview()
}
let count = 10000
let y = (scrollView.frame.height - (DIAMETER + MARGIN)) / 2
scrollView.contentSize = CGSize(width: (DIAMETER + MARGIN) * CGFloat(count), height: view.frame.height)
contentView.snp.makeConstraints { (make) in
make.height.equalTo(scrollView)
make.width.equalTo(scrollView.contentSize.width)
make.edges.equalTo(scrollView)
}
for i in 0 ..< count {
let x = MARGIN / 2 + CGFloat(i) * (DIAMETER + MARGIN)
let frame = CGRect(x: x, y: y, width: DIAMETER, height: 200)
let imageView = UIView(frame: frame)
imageView.backgroundColor = UIColor.lightGray
imageView.layer.masksToBounds = true
imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin, .flexibleRightMargin]
contentView.addSubview(imageView)
let graduationLine = CALayer()
graduationLine.frame = CGRect(x: (frame.width - 1) / 2, y: 0, width: 1, height: frame.height)
graduationLine.backgroundColor = UIColor.red.cgColor
imageView.layer.addSublayer(graduationLine)
}
let line = CALayer()
line.frame = CGRect(x: (view.frame.width - 1) / 2, y: 0, width: 1, height: view.frame.height)
line.backgroundColor = UIColor.red.cgColor
view.layer.addSublayer(line)
}
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.delegate = self
return scrollView
}()
private lazy var contentView: UIView = {
let contentView = UIView()
return contentView
}()
func nearestTargetOffset(for offset: CGPoint) -> CGPoint {
let pageSize: CGFloat = DIAMETER + MARGIN
let page = roundf(Float(offset.x / pageSize))
let targetX = pageSize * CGFloat(page)
return CGPoint(x: targetX, y: offset.y)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let targetOffset = nearestTargetOffset(for: targetContentOffset.pointee)
targetContentOffset.pointee.x = targetOffset.x
targetContentOffset.pointee.y = targetOffset.y
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
deinit {
print("\(classForCoder)释放")
}
}
|
eb31e796e86e97ddbc42403438a4b89e
| 33.970588 | 148 | 0.635548 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/CIFilter/MetalFilters-master/MetalFilters/ViewControllers/MainViewController.swift
|
mit
|
1
|
//
// MainViewController.swift
// MetalFilters
//
// Created by xushuifeng on 2018/6/9.
// Copyright © 2018 shuifeng.me. All rights reserved.
//
import UIKit
import Photos
class MainViewController: UIViewController {
@IBOutlet weak var photoView: UIView!
@IBOutlet weak var albumView: UIView!
fileprivate var scrollView: MTScrollView!
fileprivate var selectedAsset: PHAsset?
fileprivate var albumController: AlbumPhotoViewController?
override func viewDidLoad() {
super.viewDidLoad()
title = "Metal Filters"
setupScrollView()
requestPhoto()
}
private func setupScrollView() {
scrollView = MTScrollView(frame: photoView.bounds)
photoView.addSubview(scrollView)
}
fileprivate func requestPhoto() {
PHPhotoLibrary.requestAuthorization { (status) in
switch status {
case .authorized:
DispatchQueue.main.async {
PHPhotoLibrary.shared().register(self)
self.loadPhotos()
}
break
case .notDetermined:
break
default:
break
}
}
}
fileprivate func loadPhotos() {
let options = PHFetchOptions()
options.wantsIncrementalChangeDetails = false
options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ]
let result = PHAsset.fetchAssets(with: .image, options: options)
if let firstAsset = result.firstObject {
loadImageFor(firstAsset)
}
if let controller = albumController {
controller.update(dataSource: result)
} else {
let albumController = AlbumPhotoViewController(dataSource: result)
albumController.didSelectAssetHandler = { [weak self] selectedAsset in
self?.loadImageFor(selectedAsset)
}
albumController.view.frame = albumView.bounds
albumView.addSubview(albumController.view)
addChild(albumController)
albumController.didMove(toParent: self)
self.albumController = albumController
}
}
fileprivate func loadImageFor(_ asset: PHAsset) {
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.isSynchronous = true
let targetSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight)
PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: .default, options: options) { (image, _) in
DispatchQueue.main.async {
self.scrollView.image = image
}
}
selectedAsset = asset
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var prefersStatusBarHidden: Bool {
return true
}
@IBAction func nextButtonTapped(_ sender: Any) {
let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
guard let editorController = mainStoryBoard.instantiateViewController(withIdentifier: "PhotoEditorViewController") as? PhotoEditorViewController else {
return
}
editorController.croppedImage = scrollView.croppedImage
navigationController?.pushViewController(editorController, animated: false)
}
}
extension MainViewController: PHPhotoLibraryChangeObserver {
func photoLibraryDidChange(_ changeInstance: PHChange) {
self.loadPhotos()
}
}
|
50e876ec1c6933fb4ac0fa8c53847274
| 31.508772 | 159 | 0.62844 | false | false | false | false |
ByteriX/BxInputController
|
refs/heads/master
|
BxInputController/Sources/Rows/Pictures/BxInputSelectorPicturesRow.swift
|
mit
|
1
|
/**
* @file BxInputSelectorPicturesRow.swift
* @namespace BxInputController
*
* @details Implementation row with photos and camera selector. Selector is showed with keyboard frame
* @date 03.02.2017
* @author Sergey Balalaev
*
* @version last in https://github.com/ByteriX/BxInputController.git
* @copyright The MIT License (MIT) https://opensource.org/licenses/MIT
* Copyright (c) 2017 ByteriX. See http://byterix.com
*/
import UIKit
/// Implementation row with photos and camera selector. Selector is showed with keyboard frame
open class BxInputSelectorPicturesRow : BxInputValueRow, BxInputSelectorRow
{
/// Make and return Binder for binding row with cell.
open var binder : BxInputRowBinder {
return BxInputSelectorRowBinder<BxInputSelectorPicturesRow, BxInputSelectorCell>(row: self)
}
open var resourceId : String {
get { return "BxInputSelectorCell" }
}
open var estimatedHeight : CGFloat {
get { return 54 }
}
open var title : String?
open var subtitle: String?
open var placeholderHint: String?
open var placeholder : String? {
get {
if let placeholderHint = placeholderHint {
return "\(placeholderHint) \(pictures.count)"
} else {
return "\(pictures.count)"
}
}
}
open var isEnabled : Bool = true
open var isOpened: Bool = false
open var timeForAutoselection: TimeInterval = 0.0 // if < 0.5 then autoselection turned off
open var pictures: [BxInputPictureItem]
open var iconSize: CGSize = CGSize(width: 64, height: 64)
open var iconMargin: CGFloat = 8
open var iconMode: BxInputSelectorPictureView.ContentMode = .scaleAspectFill
open var countInRow: Int = 4
open var maxSelectedCount: Int = 5
open var isUniqueue: Bool = true
/// Return true if value for the row is empty
open var hasEmptyValue: Bool
{
return pictures.count == 0
}
public var child : BxInputChildSelectorPicturesRow
public var children: [BxInputChildSelectorRow] {
get {
return [child]
}
}
public init(title: String? = nil, subtitle: String? = nil,
placeholder: String? = nil, pictures: [BxInputPictureItem] = [])
{
self.title = title
self.subtitle = subtitle
self.placeholderHint = placeholder
self.pictures = pictures
child = BxInputChildSelectorPicturesRow()
child.parent = self
}
/// event when value of current row was changed
open func didChangeValue(){
//
}
}
/// Child row for BxInputSelectorPicturesRow with picture items
open class BxInputChildSelectorPicturesRow: BxInputChildSelectorRow, BxInputStaticHeight
{
/// Make and return Binder for binding row with cell.
open var binder : BxInputRowBinder {
return BxInputChildSelectorPicturesRowBinder<BxInputChildSelectorPicturesRow, BxInputChildSelectorPicturesCell, BxInputSelectorPicturesRow>(row: self)
}
open var resourceId : String = "BxInputChildSelectorPicturesCell"
open var height : CGFloat {
get {
if let parent = parent as? BxInputSelectorPicturesRow {
return parent.iconSize.height + 2 * parent.iconMargin + 2
}
return 75
}
}
open var estimatedHeight : CGFloat {
get { return height }
}
open var title : String? {
get {
return parent?.title ?? nil
}
}
open var subtitle: String? {
get {
return parent?.subtitle ?? nil
}
}
open var placeholder : String? {
get {
return parent?.placeholder ?? nil
}
}
open var isEnabled : Bool {
get {
return parent?.isEnabled ?? false
}
set {
parent?.isEnabled = newValue
}
}
weak open var parent: BxInputSelectorRow? = nil
}
|
f2839fdc9f4aba4efbf4b437d6b8c1e4
| 29.625954 | 158 | 0.632602 | false | false | false | false |
christinaxinli/Ana-Maria-Fox-Walking-Tour
|
refs/heads/master
|
slg - beta - 2/PathViewController.swift
|
mit
|
1
|
//
// PathViewController.swift
// slg - beta - 2
//
// Created by Sean Keenan on 7/10/16.
// Copyright © 2016 Christina li. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class PathViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var menuButton: UIBarButtonItem!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var currentFox: UILabel!
@IBOutlet weak var journeyButton: UIButton!
var locationManager = CLLocationManager()
let regionRadius : CLLocationDistance = 100.0
var currentRegion: String! = "NA"
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
locationManager.distanceFilter = kCLDistanceFilterNone
//locationManager.activityType = CLActivityTypeAutomativeNavigation
if CLLocationManager.authorizationStatus() == .authorizedAlways {
locationManager.startUpdatingLocation()
} else {
locationManager.requestAlwaysAuthorization()
}
getJSON()
mapView.delegate = self
mapView.mapType = MKMapType.standard
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
//MARK: unwrap JSON and create regions
func getJSON () {
let url = Bundle.main.url(forResource: "fox_locations", withExtension: "json")
let data = NSData(contentsOf: url!)
do {
let json = try JSONSerialization.jsonObject(with:data! as Data, options: .allowFragments)
for singleLocation in json as! Array<[String:AnyObject]> {
if let identifiers = singleLocation["identifier"] as? String {
if let name = singleLocation["name"] as? String {
if let lat = singleLocation["location"]?["lat"] as? Double {
if let lng = singleLocation["location"]!["lng"]! as? Double {
//MARK: turn locations into regions
let coordinate = CLLocationCoordinate2DMake(lat, lng)
let circularRegion = CLCircularRegion.init(center: coordinate, radius: regionRadius, identifier: identifiers)
locationManager.startMonitoring(for: circularRegion)
//MARK: Annotate the locations
let foxAnnotation = MKPointAnnotation ()
foxAnnotation.coordinate = coordinate
foxAnnotation.title = "\(name)"
mapView.addAnnotations([foxAnnotation])
print("\(foxAnnotation.title)")
//MARK: Draw Circles around regions/annotations
let circle = MKCircle(center: coordinate, radius: regionRadius)
mapView.add(circle)
}
}
}
}
}
} catch {
print ("error serializing JSON: \(error)")
}
}
private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
print("NotDetermined")
case .restricted:
print("Restricted")
case .denied:
print("Denied")
case .authorizedAlways:
print("AuthorizedAlways")
locationManager.startUpdatingLocation()
case .authorizedWhenInUse:
print("AuthorizedWhenInUse")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.first!
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius*10, regionRadius*10)
mapView.setRegion(coordinateRegion, animated: true)
//locationManager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Failed to initialize GPS: ", error.localizedDescription)
}
//MARK: fox image
func mapView(_ mapView: MKMapView, viewFor annotation:MKAnnotation) -> MKAnnotationView? {
let identifier = "MyPin"
//MARK: image dimensions
let foxImage = UIImage(named:"fox_image")
let size = CGSize(width:20,height:20)
UIGraphicsBeginImageContext(size)
foxImage!.draw(in: CGRect(x : 0, y : 0, width: size.width, height: size.height))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let detailButton: UIButton = UIButton(type: UIButtonType.detailDisclosure)
var annotationView: MKAnnotationView?
if annotationView == mapView.dequeueReusableAnnotationView(withIdentifier: identifier){
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.canShowCallout = true
annotationView?.image = resizedImage
annotationView?.rightCalloutAccessoryView = detailButton
}
else {
annotationView?.annotation = annotation
}
return annotationView
}
//MARK: Circle drawing
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let circleRenderer = MKCircleRenderer(overlay: overlay)
circleRenderer.strokeColor = UIColor.blue
circleRenderer.lineWidth = 2.0
return circleRenderer
}
//MARK: Entering and exiting region events
//1. user enter region
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
print("enter \(region.identifier)")
currentRegion = region.identifier
currentFox.text = "Click to explore this new Fox Spot"
}
@IBAction func journeyButtonTapped(_ sender: UIButton) {
let jvc = JourneyViewController()
jvc.currentFox = currentRegion
print("Current region : \(currentRegion)")
navigationController?.pushViewController(jvc, animated: true)
}
// 2. user exit region
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
print("exit \(region.identifier)")
currentRegion="NA"
currentFox.text="Please enter a new Fox Spot"
}
private func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: NSError) {
print("Error:" + error.localizedDescription)
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
print("Error:" + error.localizedDescription)
}
}
|
036961765398b5b3a19ecff70989ef7d
| 38.276923 | 141 | 0.607129 | false | false | false | false |
JohnSundell/SwiftKit
|
refs/heads/master
|
Source/OSX/NSView+SwiftKit.swift
|
mit
|
1
|
import Cocoa
/// SwiftKit extensions to Cocoa's NSView
public extension NSView {
/// The view's background color, setting this to non-nil causes the view to become layer backed
public var backgroundColor: NSColor? {
get {
guard let color = self.layer?.backgroundColor else {
return nil
}
return NSColor(CGColor: color)
}
set {
guard let color = newValue else {
self.layer?.backgroundColor = NSColor.clearColor().CGColor
return
}
self.wantsLayer = true
self.layer?.backgroundColor = color.CGColor
}
}
/// Adjust the view's autoreiszing mask to have both a flexible width and height
public func setFlexibleSizeAutoresizingMask() {
self.autoresizingMask.insert(.ViewWidthSizable)
self.autoresizingMask.insert(.ViewHeightSizable)
}
}
|
4eaf77dbf3e09c70b8c60e69e8807901
| 30.451613 | 99 | 0.586667 | false | false | false | false |
softmaxsg/trakt.tv-searcher
|
refs/heads/master
|
TraktSearcher/Models & View Models/MoviesViewModel.swift
|
mit
|
1
|
//
// MoviesViewModel.swift
// TraktSearcher
//
// Copyright © 2016 Vitaly Chupryk. All rights reserved.
//
import Foundation
import TraktSearchAPI
class MoviesViewModel: MoviesViewModelData, MoviesViewModelInput
{
static let pageSize: UInt = 10
let searchAPI: TraktSearchAPIProtocol
var lastPaginationInfo: PaginationInfo?
var lastCancelableToken: TraktSearchAPICancelable?
weak var delegate: MoviesViewModelOutput?
private (set) var loading: Bool = false
private (set) var movies: [MovieInfo] = []
var moreDataAvailable: Bool
{
get {
guard let pageNumber = self.lastPaginationInfo?.pageNumber, let pagesCount = self.lastPaginationInfo?.pagesCount else {
return false
}
return pageNumber < pagesCount
}
}
init(searchAPI: TraktSearchAPIProtocol)
{
self.searchAPI = searchAPI
}
func loadInitialData()
{
self.loadMovies(pageNumber: 1)
}
func loadMoreData()
{
if !self.moreDataAvailable {
// To keep behavior of this function always same delegate's method calling is called after end of this function
NSOperationQueue.mainQueue().addOperationWithBlock {
let error = NSError(domain: MoviesViewModelInputErrorDomain, code: MoviesViewModelInputNoMoreDataAvailableErrorCode, userInfo: nil)
self.delegate?.viewModelLoadingDidFail(error)
}
return
}
self.loadMovies(pageNumber: (self.lastPaginationInfo?.pageNumber ?? 0) + 1)
}
func clearData()
{
self.lastPaginationInfo = nil
self.movies = []
}
func loadMovies(pageNumber pageNumber: UInt, responseValidationHandler: ((MoviesResponse) -> Bool)? = nil)
{
assert(pageNumber > 0)
// It's preferable to call this method on the main thread
assert(NSOperationQueue.currentQueue() == NSOperationQueue.mainQueue())
if pageNumber == 1 {
self.clearData()
}
self.lastCancelableToken?.cancel()
self.loading = true
self.lastCancelableToken = self.performAPIRequest(pageNumber: pageNumber, pageSize: self.dynamicType.pageSize) { [weak self] response in
if !(responseValidationHandler?(response) ?? true) {
return
}
switch response {
case .Success(let movies, let paginationInfo):
let loadedMovies = movies.map { MovieInfo(
title: $0.title ?? "",
overview: $0.overview,
year: $0.year ?? 0,
imageUrl: $0.images?[MovieImageKind.Poster]?.thumbnail
)}
NSOperationQueue.mainQueue().addOperationWithBlock {
self?.lastPaginationInfo = paginationInfo
self?.movies = (self?.movies ?? []) + loadedMovies
self?.loading = false
self?.delegate?.viewModelDidUpdate()
}
case .Error(let error):
NSOperationQueue.mainQueue().addOperationWithBlock {
self?.loading = false
self?.delegate?.viewModelLoadingDidFail(error)
}
}
}
}
func performAPIRequest(pageNumber pageNumber: UInt, pageSize: UInt, completionHandler: (MoviesResponse) -> ()) -> TraktSearchAPICancelable?
{
assert(false, "Has to be overriden")
return nil
}
}
|
009a086bc541a132ce7a6f112bf72ccc
| 29.358974 | 147 | 0.600507 | false | false | false | false |
bengottlieb/ios
|
refs/heads/master
|
FiveCalls/FiveCalls/RemoteImageView.swift
|
mit
|
3
|
//
// RemoteImageView.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/4/17.
// Copyright © 2017 5calls. All rights reserved.
//
import UIKit
typealias RemoteImageCallback = (UIImage) -> Void
@IBDesignable
class RemoteImageView : UIImageView {
@IBInspectable
var defaultImage: UIImage?
lazy var session: URLSession = {
let session = URLSession(configuration: URLSessionConfiguration.default)
return session
}()
var currentTask: URLSessionDataTask?
private var currentImageURL: URL?
func setRemoteImage(url: URL) {
setRemoteImage(url: url) { [weak self] image in
self?.image = image
}
}
func setRemoteImage(url: URL, completion: @escaping RemoteImageCallback) {
setRemoteImage(preferred: defaultImage, url: url, completion: completion)
}
func setRemoteImage(preferred preferredImage: UIImage?, url: URL, completion: @escaping RemoteImageCallback) {
if let cachedImage = ImageCache.shared.image(forKey: url) {
image = cachedImage
return
}
image = preferredImage
guard preferredImage == nil || preferredImage == defaultImage else {
return completion(preferredImage!)
}
currentTask?.cancel()
currentTask = session.dataTask(with: url, completionHandler: { [weak self] (data, response, error) in
guard let strongSelf = self,
strongSelf.currentTask!.state != .canceling else {
return
}
if let e = error as NSError? {
if e.domain == NSURLErrorDomain && e.code == NSURLErrorCancelled {
// ignore cancellation errors
} else {
print("Error loading image: \(e.localizedDescription)")
}
} else {
guard let http = response as? HTTPURLResponse else { return }
if http.statusCode == 200 {
if let data = data, let image = UIImage(data: data) {
strongSelf.currentImageURL = url
ImageCache.shared.set(image: image, forKey: url)
if strongSelf.currentImageURL == url {
DispatchQueue.main.async {
completion(image)
}
}
}
} else {
print("HTTP \(http.statusCode) received for \(url)")
}
}
})
currentTask?.resume()
}
}
private struct ImageCache {
static var shared = ImageCache()
private let cache: NSCache<NSString, UIImage>
init() {
cache = NSCache()
}
func image(forKey key:URL) -> UIImage? {
return cache.object(forKey: key.absoluteString as NSString)
}
func set(image: UIImage, forKey key: URL) {
cache.setObject(image, forKey: key.absoluteString as NSString)
}
}
|
16df83fa9c46115916ca097c1f483e24
| 29.871287 | 114 | 0.543618 | false | false | false | false |
akkakks/firefox-ios
|
refs/heads/master
|
Client/Frontend/Browser/BrowserLocationView.swift
|
mpl-2.0
|
2
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
protocol BrowserLocationViewDelegate {
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView)
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView)
func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView)
func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView)
}
let ImageReload = UIImage(named: "toolbar_reload.png")
let ImageStop = UIImage(named: "toolbar_stop.png")
class BrowserLocationView : UIView, UIGestureRecognizerDelegate {
var delegate: BrowserLocationViewDelegate?
private var lockImageView: UIImageView!
private var locationLabel: UILabel!
private var stopReloadButton: UIButton!
private var readerModeButton: ReaderModeButton!
var readerModeButtonWidthConstraint: NSLayoutConstraint?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.whiteColor()
self.layer.cornerRadius = 3
lockImageView = UIImageView(image: UIImage(named: "lock_verified.png"))
lockImageView.hidden = false
lockImageView.isAccessibilityElement = true
lockImageView.accessibilityLabel = NSLocalizedString("Secure connection", comment: "")
addSubview(lockImageView)
locationLabel = UILabel()
locationLabel.font = UIFont(name: "HelveticaNeue-Light", size: 12)
locationLabel.lineBreakMode = .ByClipping
locationLabel.userInteractionEnabled = true
// TODO: This label isn't useful for people. We probably want this to be the page title or URL (see Safari).
locationLabel.accessibilityLabel = NSLocalizedString("URL", comment: "Accessibility label")
addSubview(locationLabel)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "SELtapLocationLabel:")
locationLabel.addGestureRecognizer(tapGestureRecognizer)
stopReloadButton = UIButton()
stopReloadButton.setImage(ImageReload, forState: .Normal)
stopReloadButton.addTarget(self, action: "SELtapStopReload", forControlEvents: .TouchUpInside)
addSubview(stopReloadButton)
readerModeButton = ReaderModeButton(frame: CGRectZero)
readerModeButton.hidden = true
readerModeButton.addTarget(self, action: "SELtapReaderModeButton", forControlEvents: .TouchUpInside)
addSubview(readerModeButton)
makeConstraints()
}
private func makeConstraints() {
let container = self
lockImageView.snp_remakeConstraints { make in
make.centerY.equalTo(container).centerY
make.leading.equalTo(container).with.offset(8)
make.width.equalTo(self.lockImageView.intrinsicContentSize().width)
}
locationLabel.snp_remakeConstraints { make in
make.centerY.equalTo(container.snp_centerY)
if self.url?.scheme == "https" {
make.leading.equalTo(self.lockImageView.snp_trailing).with.offset(8)
} else {
make.leading.equalTo(container).with.offset(8)
}
if self.readerModeButton.readerModeState == ReaderModeState.Unavailable {
make.trailing.equalTo(self.stopReloadButton.snp_leading).with.offset(-8)
} else {
make.trailing.equalTo(self.readerModeButton.snp_leading).with.offset(-8)
}
}
stopReloadButton.snp_remakeConstraints { make in
make.centerY.equalTo(container).centerY
make.trailing.equalTo(container).with.offset(-4)
make.size.equalTo(20)
}
readerModeButton.snp_remakeConstraints { make in
make.centerY.equalTo(container).centerY
make.trailing.equalTo(self.stopReloadButton.snp_leading).offset(-4)
// We fix the width of the button (to the height of the view) to prevent content
// compression when the locationLabel has more text contents than will fit. It
// would be nice to do this with a content compression priority but that does
// not seem to work.
make.width.equalTo(container.snp_height)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func intrinsicContentSize() -> CGSize {
return CGSize(width: 200, height: 28)
}
func SELtapLocationLabel(recognizer: UITapGestureRecognizer) {
delegate?.browserLocationViewDidTapLocation(self)
}
func SELtapReaderModeButton() {
delegate?.browserLocationViewDidTapReaderMode(self)
}
func SELtapStopReload() {
if loading {
delegate?.browserLocationViewDidTapStop(self)
} else {
delegate?.browserLocationViewDidTapReload(self)
}
}
var url: NSURL? {
didSet {
lockImageView.hidden = (url?.scheme != "https")
let t = url?.absoluteString
if t?.hasPrefix("http://") ?? false {
locationLabel.text = t!.substringFromIndex(advance(t!.startIndex, 7))
} else if t?.hasPrefix("https://") ?? false {
locationLabel.text = t!.substringFromIndex(advance(t!.startIndex, 8))
} else if t == "about:blank" {
let placeholderText = NSLocalizedString("Search or enter address", comment: "The text shown in the URL bar on about:home")
locationLabel.attributedText = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.grayColor()])
} else {
locationLabel.text = t
}
makeConstraints()
}
}
var loading: Bool = false {
didSet {
if loading {
stopReloadButton.setImage(ImageStop, forState: .Normal)
} else {
stopReloadButton.setImage(ImageReload, forState: .Normal)
}
}
}
var readerModeState: ReaderModeState {
get {
return readerModeButton.readerModeState
}
set (newReaderModeState) {
if newReaderModeState != self.readerModeButton.readerModeState {
self.readerModeButton.readerModeState = newReaderModeState
makeConstraints()
readerModeButton.hidden = (newReaderModeState == ReaderModeState.Unavailable)
UIView.animateWithDuration(0.1, animations: { () -> Void in
if newReaderModeState == ReaderModeState.Unavailable {
self.readerModeButton.alpha = 0.0
} else {
self.readerModeButton.alpha = 1.0
}
self.layoutIfNeeded()
})
}
}
}
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
// We only care about the horizontal position of this touch. Find the first
// subview that takes up that space and return it.
for view in subviews {
let x1 = view.frame.origin.x
let x2 = x1 + view.frame.width
if point.x >= x1 && point.x <= x2 {
return view as? UIView
}
}
return nil
}
}
private class ReaderModeButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setImage(UIImage(named: "reader.png"), forState: UIControlState.Normal)
setImage(UIImage(named: "reader_active.png"), forState: UIControlState.Selected)
accessibilityLabel = NSLocalizedString("Reader", comment: "Browser function that presents simplified version of the page with bigger text.")
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var _readerModeState: ReaderModeState = ReaderModeState.Unavailable
var readerModeState: ReaderModeState {
get {
return _readerModeState;
}
set (newReaderModeState) {
_readerModeState = newReaderModeState
switch _readerModeState {
case .Available:
self.enabled = true
self.selected = false
case .Unavailable:
self.enabled = false
self.selected = false
case .Active:
self.enabled = true
self.selected = true
}
}
}
}
|
9194645f37e34a3f84fbf0053104b234
| 38.196429 | 157 | 0.63656 | false | false | false | false |
boostcode/tori
|
refs/heads/master
|
Sources/tori/Core/Database.swift
|
apache-2.0
|
1
|
/**
* Copyright boostco.de 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 Foundation
import LoggerAPI
import MongoKitten
func setupDb() -> MongoKitten.Database {
// TODO: if not existing create db
// database setup
let (dbHost, dbPort, dbName, _, adminName, adminPassword) = getConfiguration()
let dbServer = try! Server(
at: dbHost,
port: dbPort,
automatically: true
)
let db = dbServer[dbName]
// default user admin
let userCollection = db["User"]
if try! userCollection.count(matching: "username" == adminName) == 0 {
let adminUser: Document = [
"username": .string(adminName),
"password": .string("\(adminPassword.md5())"),
"role": ~Role.Admin.hashValue
]
let _ = try! userCollection.insert(adminUser)
Log.debug("Setup / Added default admin user: \(adminName)")
}
return db
}
|
3069f9776204bc5a6b1498e559711064
| 29.058824 | 84 | 0.624266 | false | false | false | false |
ben-ng/swift
|
refs/heads/master
|
validation-test/compiler_crashers_fixed/00339-swift-clangimporter-implementation-mapselectortodeclname.swift
|
apache-2.0
|
1
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
}
}
}
typealias e : A.Type) -> Int {
class A {
func g.b : Int {
typealias B<T>()
init(false))() {
}
return d
}
case b {
var c: AnyObject.E == T>](("
protocol P {
print() -> (n: A? = b<T where H) -> U, b in a {
return { c: T>() {
return self.E == nil
}
import Foundation
enum A where T) ->(array: AnyObject, object1, AnyObject) -> [T: String {
}
let v: a = [T> Void>>>(c>Bool)
func call("A> Self {
protocol P {
typealias e == D>(false)
}
return nil
b: C) -> U, f.E
let c, V>(t: T) -> S("\() -> V>()
return self.d.b = F>()
let i: a {
var b in a {
typealias F
}
super.init(")
struct c = e: a = {
import Foundation
class func b: c> : C> ()
typealias R = 0)
func b: NSObject {
typealias R
return g, U)
}
return $0
struct e == F
func g.a("")
}
for b in
protocol A : T
enum S() {
}
}
import Foundation
self.d
f = 0
}
}
}
}(t: T -> {
private let h> {
func a(c) {
}
if c == { c: B<T>()
init <T) {
}
self.init("")
}
init <T>)
}
return nil
let g = {
typealias E
return [unowned self.init(g: T {
}
return g: A? {
let c(f<C) {
let t: U : ()
return $0
class A where I.d: B()
self.init(AnyObject) {
}
private let d<T>(t: AnyObject, g: NSObject {
0
class A : NSManagedObject {
protocol C {
d.Type) -> {
}
var e: C {
S<T>(c
}
}
return $0)
func a(array: C<T.c : d where g: d = c
protocol d = nil
func f.B : c(self.E == c>>) {
struct D : A? = A? = Int
protocol c == "")
typealias h> U, object1, AnyObject) -> Void>() -> T) -> {
typealias E
struct e = {
protocol A {
import Foundation
}
return self.e where T>) -> Void>(x: P {
return b<Q<I : String {
import Foundation
}
if c = 0
}
var f = {
let h == f<c: C) {
}
let i: () -> ()"A? = {
}
init()
var b {
}
}
struct e {
}
typealias h> T) -> {
var b = 0
typealias F>: NSObject {
}
struct c == nil
return d
import Foundation
}
}
return "A> {
protocol P {
}
typealias R = T.d
}
let d
}
struct B<T where g: I) {
}
S<U : c(#object2)
func g, U)() -> : A"")
typealias h: I.h
}
typealias F = b
var b()
var f = B) -> {
}
}
func compose()
}
let d<A: Int {
}
let i: A: A? = e, V, object1
return nil
let c(f<T>() {
}
enum S<C
}
class func f.E == a
class A : d where T
protocol P {
return $0
}
typealias h: B? {
}
}
var e
|
cb265219bd49c9809aafa5e2a66c0b6d
| 13.568966 | 79 | 0.588955 | false | false | false | false |
GagSquad/SwiftCommonUtil
|
refs/heads/master
|
CommonUtil/CommonUtil/KeychainUtil.swift
|
gpl-2.0
|
1
|
//
// KeychanUtil.swift
// CommonUtil
//
// Created by lijunjie on 15/11/12.
// Copyright © 2015年 lijunjie. All rights reserved.
//
import Foundation
public enum CommonUtilError: ErrorType {
case KeychainGetError
case KeychainSaveError
case KeychainDeleteError
case KeychainUpdateError
}
public class KeychainUtil {
private static let share = KeychainUtil()
private init () {}
public func getBaseKeychainQueryWithAccount(account: String, service: String, accessGroup: String) -> [NSString : AnyObject] {
var res = [NSString : AnyObject]()
res[kSecClass] = kSecClassGenericPassword
res[kSecAttrAccount] = account
res[kSecAttrService] = service
if !accessGroup.isEmpty {
#if TARGET_IPHONE_SIMULATOR
/*
如果在模拟器上运行,则忽略accessGroup
模拟器运行app没有签名, 所以这里没有accessGroup
在模拟器上运行时,所有的应用程序可以看到所有钥匙串项目
如果SecItem包含accessGroup,当SecItemAdd and SecItemUpdate时,将返回-25243 (errSecNoAccessForItem)
*/
#else
res[kSecAttrAccessGroup] = accessGroup
#endif
}
return res
}
public func getDataWithAccount(account: String, service: String, accessGroup: String) -> NSData? {
var res: [NSString : AnyObject] = self.getBaseKeychainQueryWithAccount(account, service: service, accessGroup: accessGroup)
res[kSecMatchCaseInsensitive] = kCFBooleanTrue
res[kSecMatchLimit] = kSecMatchLimitOne
res[kSecReturnData] = kCFBooleanTrue
var queryErr: OSStatus = noErr
var udidValue: NSData?
var inTypeRef : AnyObject?
queryErr = SecItemCopyMatching(res, &inTypeRef)
udidValue = inTypeRef as? NSData
if (queryErr != errSecSuccess) {
return nil
}
return udidValue
}
public func saveData(data: NSData, account: String, service:String, accessGroup: String) throws {
var query : [NSString : AnyObject] = self.getBaseKeychainQueryWithAccount(account, service: service, accessGroup: accessGroup)
query[kSecAttrLabel] = ""
query[kSecValueData] = data
var writeErr: OSStatus = noErr
writeErr = SecItemAdd(query, nil)
if writeErr != errSecSuccess {
throw CommonUtilError.KeychainSaveError
}
}
public func deleteDataWithAccount(account: String, service: String, accessGroup: String) throws {
let dictForDelete: [NSString : AnyObject] = self.getBaseKeychainQueryWithAccount(account, service: service, accessGroup: accessGroup)
var deleteErr: OSStatus = noErr
deleteErr = SecItemDelete(dictForDelete)
if(deleteErr != errSecSuccess){
throw CommonUtilError.KeychainDeleteError
}
}
public func updateData(data: NSData, account:String, service:String, accessGroup:String) throws {
var dictForQuery: [NSString : AnyObject] = self.getBaseKeychainQueryWithAccount(account, service: service, accessGroup: accessGroup)
dictForQuery[kSecMatchCaseInsensitive] = kCFBooleanTrue
dictForQuery[kSecMatchLimit] = kSecMatchLimitOne
dictForQuery[kSecReturnData] = kCFBooleanTrue
dictForQuery[kSecReturnAttributes] = kCFBooleanTrue
var queryResultRef: AnyObject?
SecItemCopyMatching(dictForQuery, &queryResultRef)
if queryResultRef != nil {
var dictForUpdate: [NSString : AnyObject] = self.getBaseKeychainQueryWithAccount(account, service: service, accessGroup: accessGroup)
dictForUpdate[kSecValueData] = data
var updateErr: OSStatus = noErr
updateErr = SecItemUpdate(dictForQuery, dictForUpdate)
if (updateErr != errSecSuccess) {
print("Update KeyChain Item Error!!! Error Code:%ld", updateErr)
throw CommonUtilError.KeychainUpdateError
}
}
}
}
public let SharedKeychanUtil: KeychainUtil = KeychainUtil.share
|
27f5b21a4ccf8e9ef33bb66f8755d5dd
| 37.885714 | 145 | 0.660054 | false | false | false | false |
DaftMobile/ios4beginners_2017
|
refs/heads/master
|
Class 6/Class6.playground/Pages/NavigationController.xcplaygroundpage/Contents.swift
|
apache-2.0
|
1
|
//: [Previous](@previous)
import UIKit
import PlaygroundSupport
class ParentViewController: UIViewController {
override func loadView() {
view = UIView()
view.backgroundColor = .white
let pushButton = UIButton(type: .system)
pushButton.addTarget(self, action: #selector(push), for: .touchUpInside)
pushButton.setTitle("Push!", for: [])
view.addSubview(pushButton)
view.addConstraint(NSLayoutConstraint.init(item: pushButton, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint.init(item: pushButton, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0))
pushButton.translatesAutoresizingMaskIntoConstraints = false
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Parent"
}
@objc func push() {
//Step 1: Create child view controller
//Step 2: Push child onto navigation stack
let childViewController = ChildViewController()
self.navigationController?.pushViewController(childViewController, animated: true)
}
}
class ChildViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Child"
}
override func loadView() {
view = UIView()
view.backgroundColor = .yellow
}
}
let navigationController = UINavigationController(rootViewController: ParentViewController())
PlaygroundPage.current.liveView = navigationController
//: [Next](@next)
|
7830abdcb4dbee4ae0df7b88db95e432
| 28.058824 | 166 | 0.755061 | false | false | false | false |
Mrwerdo/QuickShare
|
refs/heads/master
|
LibQuickShare/Sources/Communication/FileTransferer.swift
|
mit
|
1
|
//
// FileTransferer.swift
// QuickShare
//
// Copyright (c) 2016 Andrew Thompson
//
// 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 Dispatch
import Network
import Support
import Core
class FileSender {
var file: File
var metadata: FileMetadata
var timer: dispatch_source_t
weak var shareGroup: ShareGroup?
var bytesSent: UInt64 {
let k = UInt64(metadata.sizeOfPackets) * packetCounter
if k > metadata.filesize {
return metadata.filesize
} else {
return k
}
}
var packetCounter: UInt64 = 1
init(metadata: FileMetadata) throws {
self.metadata = metadata
file = try File(path: metadata.originPath!, mode: "r")
let frequence: UInt64 = 100
let queue = dispatch_queue_create("com.mrwerdo.quickshare.timer", nil)
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,
0,
0,
queue)
dispatch_source_set_timer(timer,
DISPATCH_TIME_NOW,
frequence * NSEC_PER_MSEC,
50 * NSEC_PER_MSEC)
dispatch_source_set_event_handler(timer, self.sendPacket)
dispatch_resume(timer)
}
func sendPacket() {
var amount = Int(metadata.sizeOfPackets)
var buff: [UInt8] = []
var isFinished = false
var totalRead = 0
do {
repeat {
if let data = try file.read(amount) {
buff.appendContentsOf(data)
amount -= data.count
totalRead += data.count
} else {
if totalRead != buff.count {
buff.removeLast(buff.count - totalRead)
}
dispatch_source_cancel(timer)
isFinished = true
break
}
} while buff.count < Int(metadata.sizeOfPackets)
} catch {
show("warninig: \(#function), couldn't read data from file; reason: \(error)")
}
if buff.count > 0 {
let packet = Packet(fileID: metadata.fileID, packetID: packetCounter, data: buff)
shareGroup?.add(message: packet)
packetCounter += 1
}
if let center = shareGroup?.center {
if let controller = center.groups[shareGroup!], let c = controller {
let percent = Double(packetCounter) / Double(metadata.numberOfPackets)
shareGroup!.syncState = .InProgress((percent * 100), metadata)
c.update(shareGroup!, using: center)
}
}
if isFinished {
// we are done.
print("i think we are finished.")
let message = TransferMessage(metadata: nil,
fileID: metadata.fileID,
type: .Check)
if let ts = shareGroup?.transferStates.first(matching: { $0.metadata == self.metadata }) {
ts.status = .Verifying(count: 0)
}
shareGroup?.add(message: message)
}
}
func sendMissingPacket(packetID: PIDType) {
let position = Int(truncatingBitPattern: (packetID - 1) * UInt64(metadata.sizeOfPackets))
var buff: [UInt8] = []
var amount = Int(metadata.sizeOfPackets)
do {
try file.seek(to: position)
repeat {
if let data = try file.read(amount) {
buff.appendContentsOf(data)
amount -= data.count
} else {
// end of file?
}
} while buff.count < Int(metadata.sizeOfPackets)
} catch {
show("warninig: \(#function), couldn't read data from file; reason: \(error)")
}
let packet = Packet(fileID: metadata.fileID, packetID: packetID, data: buff)
shareGroup?.add(message: packet)
}
func stop() {
dispatch_source_cancel(timer)
}
}
class Filereceiver {
var file: File
var metadata: FileMetadata
weak var shareGroup: ShareGroup?
var receivedPackets: [Bool]
var percentageComplete: UInt16 {
return receivedPackets.enumerate().reduce(0, combine: { $0 + ($1.element ? 1 : 0) }) / UInt16(metadata.numberOfPackets)
}
init(metadata: FileMetadata) throws {
self.metadata = metadata
let downloads = NSHomeDirectory() + "/Downloads/"
let path = downloads + metadata.filename
print("writing to: \(path)")
file = try File(path: path, mode: "w+")
receivedPackets = [Bool](count: Int(metadata.numberOfPackets), repeatedValue: false)
}
func process(packet: Packet) throws {
var data = packet.data
let id = packet.packetID
let size = metadata.sizeOfPackets
receivedPackets[Int(id-1)] = true
let percent = Double(packet.packetID) / Double(metadata.numberOfPackets)
shareGroup?.syncState = .InProgress(percent * 100, metadata)
if let center = shareGroup?.center {
if let controller = center.groups[shareGroup!], let c = controller {
c.update(shareGroup!, using: center)
}
}
_ = (id - 1) * UInt64(size)
try file.write(&data) // at: offset)
}
func checkPacket() throws {
for (n, i) in receivedPackets.enumerate() where i == false {
let packetID = UInt64(n + 1)
let m = PacketStatus(fileID: metadata.fileID,
packetID: packetID,
state: .Missing,
percentageComplete: percentageComplete)
shareGroup?.add(message: m)
}
let hash = try file.md5Hash()
let part1 = String(metadata.checksumP1, radix: 16, uppercase: false)
let part2 = String(metadata.checksumP2, radix: 16, uppercase: false)
let sum = part1 + part2
print("checking packet...", terminator: "")
print("sum=\(sum), hash=\(hash)")
if sum == hash {
print("good")
let message = PacketStatus(fileID: metadata.fileID,
packetID: 0,
state: .Good,
percentageComplete: percentageComplete)
shareGroup?.add(message: message)
} else {
print("not good")
}
print("end of \(#function)")
}
}
|
571567d11d41db4c9b99d0b8dff6bec2
| 36.308057 | 127 | 0.549289 | false | false | false | false |
aucl/YandexDiskKit
|
refs/heads/master
|
YandexDiskKit/YandexDiskKit/YDisk+Metainfo.swift
|
bsd-2-clause
|
1
|
//
// YDisk+Metainfo.swift
//
// Copyright (c) 2014-2015, Clemens Auer
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 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 OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
extension YandexDisk {
public enum MetainfoResult {
case Done(total_space: Int, used_space: Int, trash_size: Int, system_folders:[String:Path])
case Failed(NSError!)
}
/// Recieves meta info about the disk
///
/// :param: handler Optional.
/// :returns: `MetainfoResult` future.
///
/// API reference:
/// `english http://api.yandex.com/disk/api/reference/capacity.xml`_,
/// `russian https://tech.yandex.ru/disk/api/reference/capacity-docpage/`_.
public func metainfo(handler:((result:MetainfoResult) -> Void)? = nil) -> Result<MetainfoResult> {
let result = Result<MetainfoResult>(handler: handler)
var url = "\(baseURL)/v1/disk/"
let error = { result.set(.Failed($0)) }
session.jsonTaskWithURL(url, errorHandler: error) {
(jsonRoot, response)->Void in
switch response.statusCode {
case 200:
if let system_folders_dict = jsonRoot["system_folders"] as? NSDictionary,
total_space = (jsonRoot["total_space"] as? NSNumber)?.integerValue,
used_space = (jsonRoot["used_space"] as? NSNumber)?.integerValue,
trash_size = (jsonRoot["trash_size"] as? NSNumber)?.integerValue
{
var system_folders = Dictionary<String, Path>()
for (key, value) in system_folders_dict {
if let key = key as? String,
value = value as? String
{
system_folders[key] = Path.pathWithString(value)
}
}
return result.set(.Done(total_space:total_space, used_space:used_space, trash_size:trash_size, system_folders:system_folders))
} else {
fallthrough
}
default:
return error(NSError(domain: "YDisk", code: response.statusCode, userInfo: ["response":response, "json":jsonRoot]))
}
}.resume()
return result
}
}
|
e4024fd3c1343cb756b544b44361d18a
| 42.414634 | 146 | 0.628371 | false | false | false | false |
GhostSK/SpriteKitPractice
|
refs/heads/master
|
RestaurantManager/RestaurantManager/Main/Views/EmployeeView.swift
|
apache-2.0
|
1
|
//
// EmployeeView.swift
// RestaurantManager
//
// Created by 胡杨林 on 2017/9/26.
// Copyright © 2017年 胡杨林. All rights reserved.
//
import Foundation
import UIKit
class employeeViewInMarket: UIView {
class func BuildEmployeeView(model:EmployeeModel, PositionPoint:CGPoint)->employeeViewInMarket{
let view = employeeViewInMarket.init(frame: CGRect(x: PositionPoint.x, y: PositionPoint.y, width: 260, height: 300))
view.backgroundColor = UIColor.init(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.55)
let headImageView = UIImageView.init(frame: CGRect(x: 15, y: 15, width: 60, height:80))
headImageView.image = UIImage(named: "443png")
view.addSubview(headImageView)
let nameTitle = UILabel.init(frame: CGRect(x: 90, y: 25, width: 50, height: 25))
nameTitle.text = "姓名:"
nameTitle.adjustsFontSizeToFitWidth = true
view.addSubview(nameTitle)
let nameLabel = UILabel.init(frame: CGRect(x: 140, y: 25, width: 110, height: 25))
nameLabel.text = model.Name == "" ? "尼古拉斯·二狗子" : model.Name
nameLabel.adjustsFontSizeToFitWidth = true
nameLabel.font = UIFont.systemFont(ofSize: 16)
view.addSubview(nameLabel)
let PayPrice = UILabel.init(frame: CGRect(x: 90, y: 60, width: 50, height: 25))
PayPrice.text = "薪酬:"
PayPrice.adjustsFontSizeToFitWidth = true
view.addSubview(PayPrice)
let Price = UILabel.init(frame: CGRect(x: 140, y: 60, width: 110, height: 25))
Price.text = "\(model.Payment)"
view.addSubview(Price)
//数值条
let Label1 = UILabel.init(frame: CGRect(x: 15, y: 110, width: 55, height: 20))
Label1.text = "灵巧"
Label1.textAlignment = .center
Label1.adjustsFontSizeToFitWidth = true
view.addSubview(Label1)
let bar1 = abilityBar.buildBar(Frame: CGRect(x: 75, y: 115, width: 140, height: 10), value: model.agility, ColorType: 0)
view.addSubview(bar1)
let right1 = UILabel.init(frame: CGRect(x: 220, y: 110, width: 30, height: 20))
right1.text = "\(model.agility)"
right1.adjustsFontSizeToFitWidth = true
view.addSubview(right1)
let Label2 = UILabel.init(frame: CGRect(x: 15, y: 135, width: 55, height: 20))
Label2.text = "计算"
Label2.textAlignment = .center
Label2.adjustsFontSizeToFitWidth = true
view.addSubview(Label2)
let bar2 = abilityBar.buildBar(Frame: CGRect(x: 75, y: 140, width: 140, height: 10), value: model.calculateAbility, ColorType: 1)
view.addSubview(bar2)
let right2 = UILabel.init(frame: CGRect(x: 220, y: 135, width: 30, height: 20))
right2.text = "\(model.calculateAbility)"
right2.adjustsFontSizeToFitWidth = true
view.addSubview(right2)
let Label3 = UILabel.init(frame: CGRect(x: 15, y: 160, width: 55, height: 20))
Label3.text = "厨艺"
Label3.textAlignment = .center
Label3.adjustsFontSizeToFitWidth = true
view.addSubview(Label3)
let bar3 = abilityBar.buildBar(Frame: CGRect(x: 75, y: 165, width: 140, height: 10), value: model.CookAbility, ColorType: 2)
view.addSubview(bar3)
let right3 = UILabel.init(frame: CGRect(x: 220, y: 160, width: 30, height: 20))
right3.text = "\(model.CookAbility)"
right3.adjustsFontSizeToFitWidth = true
view.addSubview(right3)
let Label4 = UILabel.init(frame: CGRect(x: 15, y: 185, width: 55, height: 20))
Label4.text = "武力"
Label4.textAlignment = .center
Label4.adjustsFontSizeToFitWidth = true
view.addSubview(Label4)
let bar4 = abilityBar.buildBar(Frame: CGRect(x: 75, y: 190, width: 140, height: 10), value: model.military, ColorType: 3)
view.addSubview(bar4)
let right4 = UILabel.init(frame: CGRect(x: 220, y: 185, width: 30, height: 20))
right4.text = "\(model.military)"
right4.adjustsFontSizeToFitWidth = true
view.addSubview(right4)
let Label5 = UILabel.init(frame: CGRect(x: 15, y: 210, width: 55, height: 20))
Label5.text = "魅力"
Label5.textAlignment = .center
Label5.adjustsFontSizeToFitWidth = true
view.addSubview(Label5)
let bar5 = abilityBar.buildBar(Frame: CGRect(x: 75, y: 215, width: 140, height: 10), value: model.charmAbility, ColorType: 4)
view.addSubview(bar5)
let right5 = UILabel.init(frame: CGRect(x: 220, y: 210, width: 30, height: 20))
right5.text = "\(model.charmAbility)"
right5.adjustsFontSizeToFitWidth = true
view.addSubview(right5)
let Label6 = UILabel.init(frame: CGRect(x: 15, y: 235, width: 55, height: 20))
Label6.text = "气运"
Label6.textAlignment = .center
Label6.adjustsFontSizeToFitWidth = true
view.addSubview(Label6)
let bar6 = abilityBar.buildBar(Frame: CGRect(x: 75, y: 240, width: 140, height: 10), value: model.Lucky, ColorType: 5)
view.addSubview(bar6)
let right6 = UILabel.init(frame: CGRect(x: 220, y: 235, width: 30, height: 20))
right6.text = "\(model.Lucky)"
right6.adjustsFontSizeToFitWidth = true
view.addSubview(right6)
let judgeTitle = UILabel.init(frame: CGRect(x: 15, y: 260, width: 55, height: 20))
judgeTitle.text = "评价"
judgeTitle.textAlignment = .center
view.addSubview(judgeTitle)
let judge = UILabel.init(frame: CGRect(x: 75, y: 260, width: 170, height: 35))
judge.numberOfLines = 2
judge.textAlignment = .left
// judge.text = "吃的挺多,偷懒在行,凑合着用吧。"
judge.text = model.judge
judge.adjustsFontSizeToFitWidth = true
view.addSubview(judge)
return view
}
func didEmployed(){
let view = UIView.init(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
view.backgroundColor = UIColor.init(red: 147.0/255, green: 147.0/255, blue: 147.0/255, alpha: 0.8)
let mark = UIImageView.init(frame: CGRect(x: (view.frame.size.width - 200) / 2, y: (view.frame.size.height - 100) / 2, width: 200, height: 100))
mark.image = UIImage.init(named: "招募印章")
view.addSubview(mark)
self.addSubview(view)
}
}
class abilityBar: UIView {
//http://www.iconfont.cn/search/index?searchType=icon&q=%E8%BF%9B%E5%BA%A6%E6%9D%A1
class func buildBar(Frame:CGRect, value:NSInteger, ColorType:NSInteger)->abilityBar{
let view = abilityBar.init(frame: Frame)
let backImage = UIImageView.init(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
backImage.image = UIImage(named: "progress_back")
view.addSubview(backImage)
let value2 = CGFloat(value)
let upImage = UIImageView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width / 100.0 * value2, height: view.frame.size.height))
var color = ColorType
if color > 5{
color = 5
}
let upname = "progress_up\(color)"
upImage.image = UIImage(named: upname)
view.addSubview(upImage)
return view;
}
}
|
6ba1fb30977c0828d97d8f8991811a98
| 46.181818 | 152 | 0.630195 | false | false | false | false |
PopovVadim/PVDSwiftAddOns
|
refs/heads/master
|
PVDSwiftAddOns/Classes/Extensions/UIKit/UIViewExtension.swift
|
mit
|
1
|
//
// UIViewExtension.swift
// PVDSwiftExtensions
//
// Created by Вадим Попов on 9/25/17.
//
import Foundation
/**
*/
public func == (lhs: HoverStyle, rhs: HoverStyle) -> Bool {
return lhs.toInt() == rhs.toInt()
}
/**
*
*
*/
public enum HoverStyle: Hashable {
////
public var hashValue: Int {
return self.toInt()
}
case push
case shiftRight
case transform(() -> Void)
/**
*/
func toInt() -> Int {
switch self {
case .push:
return 0
case .shiftRight:
return 1
case .transform(_):
return 2
}
}
/**
*/
func applyHover(to view: UIView, duration: Double = 0.1, sender: Any? = nil) {
switch self {
case .transform(let animations):
animate(view, duration: duration, animations: animations)
break
case .push:
animate(view, duration: duration, animations: {
view.transform = CGAffineTransform(scaleX: 0.94, y: 0.94)
})
break
case .shiftRight:
animate(view, duration: duration, animations: {
view.transform = CGAffineTransform(translationX: 10.0, y: 0)
})
break
}
}
/**
*/
func applyUnhover(to view: UIView, duration: Double = 0.1, sender: Any? = nil) {
switch self {
default:
animate(view, duration: duration, animations: {
view.transform = CGAffineTransform.identity
})
break
}
}
/**
*/
private func animate(_ view: UIView, duration: Double = 0.1, animations: @escaping (() -> Void)) {
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: animations, completion: nil)
}
}
/**
*
*
*/
public extension UIView {
/**
*/
public func height() -> CGFloat {
return self.frame.height
}
/**
*/
public func width() -> CGFloat {
return self.frame.width
}
/**
*/
public func x() -> CGFloat {
return self.frame.minX
}
/**
*/
public func y() -> CGFloat {
return self.frame.minY
}
/**
*/
public func maxX() -> CGFloat {
return self.frame.maxX
}
/**
*/
public func maxY() -> CGFloat {
return self.frame.maxY
}
/**
*/
public func size() -> CGSize {
return self.frame.size
}
/**
*/
public func origin() -> CGPoint {
return self.frame.origin
}
/**
*/
public func setHeight(_ value: CGFloat) {
self.frame = CGRect(origin: self.origin(), size: CGSize(width: self.width(), height: value))
}
/**
*/
public func setWidth(_ value: CGFloat) {
self.frame = CGRect(origin: self.origin(), size: CGSize(width: value, height: self.height()))
}
/**
*/
public func setX(_ value: CGFloat) {
self.frame = CGRect(origin: CGPoint(x: value, y: self.y()), size: self.size())
}
/**
*/
public func setY(_ value: CGFloat) {
self.frame = CGRect(origin: CGPoint(x: self.x(), y: value), size: self.size())
}
/**
*/
public func applyRadius(_ radius: CGFloat) {
layer.cornerRadius = radius
}
/**
*/
public func makeRound() {
layer.cornerRadius = self.width()/2
}
/**
*/
public func applyShadow(_ color: UIColor, _ offset: CGSize = CGSize.zero, _ radius: CGFloat = 10.0, _ opacity: Float = 1.0) {
layer.shadowColor = color.cgColor
layer.shadowOffset = offset
layer.shadowRadius = radius
layer.shadowOpacity = opacity
}
/**
*/
public func applyBorder(width: CGFloat, color: UIColor) {
layer.borderWidth = width
layer.borderColor = color.cgColor
}
/**
*/
public func hover(with touch: UITouch, style: HoverStyle = .push, duration: Double = 0.3) {
if self.point(inside: touch.location(in: self), with: nil) {
style.applyHover(to: self, duration: duration)
}
else {
unhover(style: style, duration: duration)
}
}
/**
*/
public func unhover(style: HoverStyle = .push, duration: Double = 0.3) {
style.applyUnhover(to: self, duration: duration)
}
/**
*/
public func shake(duration: Double = 0.5, amplitude: CGFloat = 10.0, completion: ((Bool) -> Void)? = nil) {
UIView.animateKeyframes(withDuration: duration, delay: 0, options: .calculationModeLinear, animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.3, animations: {
self.transform = CGAffineTransform(translationX: amplitude, y: 0)
})
UIView.addKeyframe(withRelativeStartTime: 0.3, relativeDuration: 0.2, animations: {
self.transform = CGAffineTransform(translationX: -0.8 * amplitude, y: 0)
})
UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.20, animations: {
self.transform = CGAffineTransform(translationX: 0.5 * amplitude, y: 0)
})
UIView.addKeyframe(withRelativeStartTime: 0.7, relativeDuration: 0.15, animations: {
self.transform = CGAffineTransform(translationX: -0.2 * amplitude, y: 0)
})
UIView.addKeyframe(withRelativeStartTime: 0.85, relativeDuration: 0.15, animations: {
self.transform = CGAffineTransform(translationX: 0, y: 0)
})
}, completion: completion)
}
/**
*/
public func blink(duration: Double = 0.5, fromAlpha: CGFloat? = nil, toAlpha: CGFloat = 1.0, completion: ((Bool) -> Void)? = nil) {
var fa = fromAlpha
if fa == nil {
fa = self.alpha
}
UIView.animate(withDuration: duration/2, delay: 0, options: .curveEaseOut, animations: {
self.alpha = toAlpha
}, completion: { Void in
UIView.animate(withDuration: duration/2, delay: 0, options: .curveEaseOut, animations: {
self.alpha = fa!
}, completion: completion)
})
}
/**
*/
public func blink(with color: UIColor, duration: Double = 0.5, completion: ((Bool) -> Void)? = nil) {
let initialColor = self.backgroundColor
UIView.animate(withDuration: duration/2, delay: 0, options: .curveEaseOut, animations: {
self.backgroundColor = color
}, completion: { Void in
UIView.animate(withDuration: duration/2, delay: 0, options: .curveEaseOut, animations: {
self.backgroundColor = initialColor
}, completion: completion)
})
}
/**
*/
public func fadeIn(duration: Double = 0.3, alpha: CGFloat = 1.0, completion: (() -> Void)? = nil) {
fade(with: duration, to: alpha, completion: completion)
}
/**
*/
public func fadeOut(duration: Double = 0.3, alpha: CGFloat = 0.0, completion: (() -> Void)? = nil) {
fade(with: duration, to: alpha, completion: completion)
}
/**
*/
public func fade(with duration: Double = 0.3, to alpha: CGFloat, completion: (() -> Void)? = nil) {
UIView.animate(withDuration: duration, animations: {
self.alpha = alpha
}, completion: {_ in
completion?()
})
}
/**
*/
public func setHidden(_ hidden: Bool = true, animated: Bool = true, completion: (() -> Void)? = nil) {
if animated {
if hidden {
self.fadeOut() {
self.isHidden = true
completion?()
}
}
else {
self.isHidden = false
self.fadeIn(completion: completion)
}
}
else {
self.alpha = hidden ? 0 : 1
self.isHidden = hidden
completion?()
}
}
}
|
5460fbfa1e29ea5b8edd939b0f2c5d5e
| 26.088816 | 135 | 0.526047 | false | false | false | false |
openHPI/xikolo-ios
|
refs/heads/dev
|
iOS/CourseSceneDelegate.swift
|
gpl-3.0
|
1
|
//
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import Common
import UIKit
@available(iOS 13.0, *)
enum UserActivityAction {
case courseArea(CourseArea)
case action((CourseViewController) -> Void)
}
@available(iOS 13.0, *)
class CourseSceneDelegate: UIResponder, UIWindowSceneDelegate {
private lazy var courseNavigationController: CourseNavigationController = {
let courseNavigationController = R.storyboard.course.instantiateInitialViewController().require()
#if DEBUG
if ProcessInfo.processInfo.arguments.contains("-forceDarkMode") {
courseNavigationController.overrideUserInterfaceStyle = .dark
}
#endif
return courseNavigationController
}()
private var themeObservation: NSKeyValueObservation?
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let userActivity = connectionOptions.userActivities.first ?? session.stateRestorationActivity
guard let courseId = userActivity?.userInfo?["courseID"] as? String else { return }
let fetchRequest = CourseHelper.FetchRequest.course(withSlugOrId: courseId)
guard let course = CoreDataHelper.viewContext.fetchSingle(fetchRequest).value else { return }
let topViewController = self.courseNavigationController.topViewController.require(hint: "Top view controller required")
let courseViewController = topViewController.require(toHaveType: CourseViewController.self)
courseViewController.course = course
switch action(for: userActivity) {
case let .courseArea(area):
courseViewController.transitionIfPossible(to: area)
case let .action(action):
action(courseViewController)
case .none:
courseViewController.transitionIfPossible(to: .courseDetails)
}
if let windowScene = scene as? UIWindowScene {
self.window = UIWindow(windowScene: windowScene)
self.window?.rootViewController = self.courseNavigationController
self.window?.tintColor = Brand.default.colors.window
self.window?.makeKeyAndVisible()
}
self.themeObservation = UserDefaults.standard.observe(\UserDefaults.theme, options: [.initial, .new]) { [weak self] _, _ in
self?.window?.overrideUserInterfaceStyle = UserDefaults.standard.theme.userInterfaceStyle
}
}
func sceneWillResignActive(_ scene: UIScene) {
QuickActionHelper.setHomescreenQuickActions()
}
func stateRestorationActivity(for scene: UIScene) -> NSUserActivity? {
return scene.userActivity
}
// swiftlint:disable:next cyclomatic_complexity
private func action(for userActivity: NSUserActivity?) -> UserActivityAction? {
guard let url = userActivity?.userInfo?["url"] as? URL else {
return nil
}
switch url.pathComponents[safe: 3] {
case nil:
return .courseArea(.learnings)
case "items":
if let courseItemId = url.pathComponents[safe: 4] {
let itemId = CourseItem.uuid(forBase62UUID: courseItemId) ?? courseItemId
let itemFetchRequest = CourseItemHelper.FetchRequest.courseItem(withId: itemId)
if let courseItem = CoreDataHelper.viewContext.fetchSingle(itemFetchRequest).value {
return .action({ courseViewController in
courseViewController.show(item: courseItem, animated: trueUnlessReduceMotionEnabled)
})
} else {
return .courseArea(.learnings)
}
} else {
return .courseArea(.learnings)
}
case "pinboard":
return .courseArea(.discussions)
case "progress":
return .courseArea(.progress)
case "announcements":
return .courseArea(.announcements)
case "recap":
guard FeatureHelper.hasFeature(.quizRecap) else { return nil }
return .courseArea(.recap)
case "documents":
guard Brand.default.features.enableDocuments else { return nil }
return .courseArea(.documents)
default:
return nil
}
}
}
|
fb6824e11409dd2a272bd1165b11f15a
| 37.675439 | 131 | 0.658426 | false | false | false | false |
wikimedia/wikipedia-ios
|
refs/heads/main
|
Wikipedia/Code/MediaList.swift
|
mit
|
1
|
public struct MediaListItemSource: Codable {
public let urlString: String
public let scale: String
enum CodingKeys: String, CodingKey {
case urlString = "src"
case scale
}
public init (urlString: String, scale: String) {
self.urlString = urlString
self.scale = scale
}
}
public enum MediaListItemType: String {
case image
case audio
case video
}
public struct MediaListItem: Codable {
public let title: String?
public let sectionID: Int
public let type: String
public let showInGallery: Bool
public let isLeadImage: Bool
public let sources: [MediaListItemSource]?
public let audioType: String?
enum CodingKeys: String, CodingKey {
case title
case sectionID = "section_id"
case showInGallery
case isLeadImage = "leadImage"
case sources = "srcset"
case type
case audioType
}
public init(title: String?, sectionID: Int, type: String, showInGallery: Bool, isLeadImage: Bool, sources: [MediaListItemSource]?, audioType: String? = nil) {
self.title = title
self.sectionID = sectionID
self.type = type
self.showInGallery = showInGallery
self.isLeadImage = isLeadImage
self.sources = sources
self.audioType = audioType
}
}
extension MediaListItem {
public var itemType: MediaListItemType? {
return MediaListItemType(rawValue: type)
}
}
public struct MediaList: Codable {
public let items: [MediaListItem]
public init(items: [MediaListItem]) {
self.items = items
}
// This failable initializer is used for a single-image MediaList, given via a URL.
public init?(from url: URL?) {
guard let imageURL = url,
let imageName = WMFParseUnescapedNormalizedImageNameFromSourceURL(imageURL) else {
return nil
}
let filename = "File:" + imageName
let urlString = imageURL.absoluteString
let sources: [MediaListItemSource] = [
MediaListItemSource(urlString: urlString, scale: "1x"),
MediaListItemSource(urlString: urlString, scale: "2x"),
MediaListItemSource(urlString: urlString, scale: "1.5x")
]
let mediaListItem = MediaListItem(title: filename, sectionID: 0, type: "image", showInGallery: true, isLeadImage: true, sources: sources, audioType: nil)
self = MediaList(items: [mediaListItem])
}
}
|
a68a5e6db965e2d50cf6778bf8fc499f
| 29.703704 | 162 | 0.649377 | false | false | false | false |
slepcat/mint-lisp
|
refs/heads/master
|
mint-lisp/mint_CSG.swift
|
apache-2.0
|
1
|
//
// mint_CSG.swift
// MINT
//
// Created by NemuNeko on 2015/05/04.
// Copyright (c) 2015年 Taizo A. All rights reserved.
//
import Foundation
// # class PolygonTreeNode
// This class manages hierarchical splits of polygons
// At the top is a root node which doesn hold a polygon, only child PolygonTreeNodes
// Below that are zero or more 'top' nodes; each holds a polygon. The polygons can be in different planes
// splitByPlane() splits a node by a plane. If the plane intersects the polygon, two new child nodes
// are created holding the splitted polygon.
// getPolygons() retrieves the polygon from the tree. If for PolygonTreeNode the polygon is split but
// the two split parts (child nodes) are still intact, then the unsplit polygon is returned.
// This ensures that we can safely split a polygon into many fragments. If the fragments are untouched,
// getPolygons() will return the original unsplit polygon instead of the fragments.
// remove() removes a polygon from the tree. Once a polygon is removed, the parent polygons are invalidated
// since they are no longer intact.
// constructor creates the root node:
class PolygonTreeNode {
var parent : PolygonTreeNode? = nil
var children : [PolygonTreeNode] = []
var polygon : Polygon? = nil
var removed : Bool = false
// fill the tree with polygons. Should be called on the root node only; child nodes must
// always be a derivate (split) of the parent node.
func addPolygons(_ poly: [Polygon]) {
if !isRootNode() {
for p in poly {
addChild(p)
}
}
// new polygons can only be added to root node; children can only be splitted polygons
//MintErr.exc.raise()
}
// remove a node
// - the siblings become toplevel nodes
// - the parent is removed recursively
func remove() {
if removed == false {
removed = true
// remove ourselves from the parent's children list:
if let parentcsg = parent {
var i = 0
while i < parentcsg.children.count {
if parentcsg.children[i] === self {
parentcsg.children.remove(at: i)
i -= 1
}
i += 1
}
// invalidate the parent's polygon, and of all parents above it:
parentcsg.recursivelyInvalidatePolygon()
}
}
}
func isRootNode() -> Bool {
if parent == nil {
return true
} else {
return false
}
}
// invert all polygons in the tree. Call on the root node
func invert() {
if isRootNode() {// can only call this on the root node
invertSub()
} else {
print("Assertion failed", terminator: "\n")
}
}
func getPolygon() -> Polygon? {
if let poly = polygon {
return poly
} else { // doesn't have a polygon, which means that it has been broken down
print("Assertion failed", terminator: "\n")
return nil
}
}
func getPolygons() -> [Polygon] {
if let poly = polygon {
// the polygon hasn't been broken yet. We can ignore the children and return our polygon:
return [poly]
} else {
// our polygon has been split up and broken, so gather all subpolygons from the children:
var childpolygons = [Polygon]()
for child in children {
childpolygons += child.getPolygons()
}
return childpolygons
}
}
// split the node by a plane; add the resulting nodes to the frontnodes and backnodes array
// If the plane doesn't intersect the polygon, the 'this' object is added to one of the arrays
// If the plane does intersect the polygon, two new child nodes are created for the front and back fragments,
// and added to both arrays.
/* original
func splitByPlane(plane: Plane, inout cpfrontnodes: [PolygonTreeNode], inout cpbacknodes: [PolygonTreeNode], inout frontnodes: [PolygonTreeNode], inout backnodes: [PolygonTreeNode]) {
if children.count > 0 {
// if we have children, split the children
for child in children {
child.splitByPlane(plane, cpfrontnodes: &cpfrontnodes, cpbacknodes: &cpbacknodes, frontnodes: &frontnodes, backnodes: &backnodes)
}
} else {
// no children. Split the polygon:
if polygon != nil {
let bound = polygon!.boundingSphere()
var sphereradius = bound.radius + 1e-4
var planenormal = plane.normal
var spherecenter = bound.middle
var d = planenormal.dot(spherecenter) - plane.w
if d > sphereradius {
frontnodes.append(self)
} else if d < -sphereradius {
backnodes.append(self)
} else {
let splitresult = plane.splitPolygon(polygon!)
switch splitresult.type {
case .Coplanar_front:
// coplanar front:
cpfrontnodes.append(self)
case .Coplanar_back:
// coplanar back:
cpbacknodes.append(self)
case .Front:
// front:
frontnodes.append(self)
case .Back:
// back:
backnodes.append(self)
case .Spanning:
// spanning:
if let front = splitresult.front {
var frontnode = addChild(front)
frontnodes.append(frontnode)
}
if let back = splitresult.back {
var backnode = addChild(back)
backnodes.append(backnode)
}
default:
print("unexpected err")
break
}
}
}
}
}
*/
// Slightly modified. This ver of splitByPlane() does not have 'cpbacknodes' argument,
// because Swift cannot have 2 arguments of same reference.
func splitByPlane(_ plane: Plane, cpfrontnodes: inout [PolygonTreeNode], frontnodes: inout [PolygonTreeNode], backnodes: inout [PolygonTreeNode]) {
if children.count > 0 {
// if we have children, split the children
for child in children {
child.splitByPlane(plane, cpfrontnodes: &cpfrontnodes, frontnodes: &frontnodes, backnodes: &backnodes)
}
} else {
// no children. Split the polygon:
if polygon != nil {
let bound = polygon!.boundingSphere()
let sphereradius = bound.radius + 1e-4
let planenormal = plane.normal
let spherecenter = bound.middle
let d = planenormal.dot(spherecenter) - plane.w
if d > sphereradius {
frontnodes.append(self)
} else if d < -sphereradius {
backnodes.append(self)
} else {
let splitresult = plane.splitPolygon(polygon!)
switch splitresult.type {
case .Coplanar_front:
// coplanar front:
cpfrontnodes.append(self)
case .Coplanar_back:
// coplanar back:
backnodes.append(self)
case .Front:
// front:
frontnodes.append(self)
case .Back:
// back:
backnodes.append(self)
case .Spanning:
// spanning:
if let front = splitresult.front {
let frontnode = addChild(front)
frontnodes.append(frontnode)
}
if let back = splitresult.back {
let backnode = addChild(back)
backnodes.append(backnode)
}
default:
print("unexpected err", terminator: "\n")
break
}
}
}
}
}
// PRIVATE methods from here:
// add child to a node
// this should be called whenever the polygon is split
// a child should be created for every fragment of the split polygon
// returns the newly created child
fileprivate func addChild(_ poly: Polygon) -> PolygonTreeNode {
let newchild = PolygonTreeNode()
newchild.parent = self
newchild.polygon = poly
self.children.append(newchild)
return newchild
}
fileprivate func invertSub() {
if let poly = polygon {
polygon = poly.flipped()
}
for child in children {
child.invertSub()
}
}
fileprivate func recursivelyInvalidatePolygon() {
if polygon != nil {
polygon = nil
if let parentcsg = parent {
parentcsg.recursivelyInvalidatePolygon()
}
}
}
}
// # class MeshTree
// This is the root of a BSP tree
// We are using this separate class for the root of the tree, to hold the PolygonTreeNode root
// The actual tree is kept in this.rootnode
class MeshTree {
var polygonTree : PolygonTreeNode
var rootnode : Node
init(polygons : [Polygon]) {
polygonTree = PolygonTreeNode()
rootnode = Node(parent: nil)
if polygons.count > 0 {
addPolygons(polygons)
}
}
func invert() {
polygonTree.invert()
rootnode.invert()
}
// Remove all polygons in this BSP tree that are inside the other BSP tree
// `tree`.
func clipTo(_ tree: MeshTree, alsoRemovecoplanarFront: Bool) {
rootnode.clipTo(tree, alsoRemovecoplanarFront: alsoRemovecoplanarFront)
}
func allPolygons() -> [Polygon] {
return polygonTree.getPolygons()
}
func addPolygons(_ polygons : [Polygon]) {
var polygontreenodes : [PolygonTreeNode] = []
for poly in polygons {
polygontreenodes += [polygonTree.addChild(poly)]
}
rootnode.addPolygonTreeNodes(polygontreenodes)
}
}
// # class Node
// Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
// by picking a polygon to split along.
// Polygons are not stored directly in the tree, but in PolygonTreeNodes, stored in
// this.polygontreenodes. Those PolygonTreeNodes are children of the owning
// CSG.Tree.polygonTree
// This is not a leafy BSP tree since there is
// no distinction between internal and leaf nodes.
class Node {
var plane : Plane? = nil
var front : Node? = nil
var back : Node? = nil
var polyTreeNodes : [PolygonTreeNode] = []
var parent : Node?
init(parent: Node?) {
self.parent = parent
}
// Convert solid space to empty space and empty space to solid space.
func invert() {
if let p = plane {
plane = p.flipped()
}
if let f = front {
f.invert()
}
if let b = back {
b.invert()
}
let temp = front
front = back
back = temp
}
// clip polygontreenodes to our plane
// calls remove() for all clipped PolygonTreeNodes
func clipPolygons(_ ptNodes: [PolygonTreeNode], alsoRemovecoplanarFront: Bool) {
if let p = plane {
var backnodes = [PolygonTreeNode]()
var frontnodes = [PolygonTreeNode]()
var coplanarfrontnodes = alsoRemovecoplanarFront ? backnodes : frontnodes
for node in ptNodes {
if !node.removed {
node.splitByPlane(p, cpfrontnodes: &coplanarfrontnodes, frontnodes: &frontnodes, backnodes: &backnodes)
}
}
if let f = front {
if frontnodes.count > 0 {
f.clipPolygons(frontnodes, alsoRemovecoplanarFront: alsoRemovecoplanarFront)
}
}
if (back != nil) && (backnodes.count > 0) {
back!.clipPolygons(backnodes, alsoRemovecoplanarFront: alsoRemovecoplanarFront)
} else {
// there's nothing behind this plane. Delete the nodes behind this plane:
for node in backnodes {
node.remove()
}
}
}
}
// Remove all polygons in this BSP tree that are inside the other BSP tree
// `tree`.
func clipTo(_ tree: MeshTree, alsoRemovecoplanarFront: Bool) {
if polyTreeNodes.count > 0 {
tree.rootnode.clipPolygons(polyTreeNodes, alsoRemovecoplanarFront: alsoRemovecoplanarFront)
}
if let f = front {
f.clipTo(tree, alsoRemovecoplanarFront: alsoRemovecoplanarFront)
}
if let b = back {
b.clipTo(tree, alsoRemovecoplanarFront: alsoRemovecoplanarFront)
}
}
func addPolygonTreeNodes(_ polygontreenodes: [PolygonTreeNode]) {
if polygontreenodes.count > 0 {
if plane == nil {
let bestplane = polygontreenodes[0].getPolygon()?.plane
plane = bestplane;
}
var frontnodes : [PolygonTreeNode] = []
var backnodes : [PolygonTreeNode] = []
for node in polygontreenodes {
node.splitByPlane(plane!, cpfrontnodes: &self.polyTreeNodes, frontnodes: &frontnodes, backnodes: &backnodes)
}
if frontnodes.count > 0 {
if front == nil {
front = Node(parent: self)
}
if let f = front {
f.addPolygonTreeNodes(frontnodes)
}
}
if backnodes.count > 0 {
if back == nil {
back = Node(parent: self)
}
if let b = back {
b.addPolygonTreeNodes(backnodes)
}
}
}
}
func getParentPlaneNormals(_ normals: inout [Vector], maxdepth: Int) {
if maxdepth > 0 {
if let p = parent {
normals.append(p.plane!.normal)
p.getParentPlaneNormals(&normals, maxdepth: maxdepth - 1);
}
}
}
}
|
4e5fa1f3b60025ad5468d99ab8437aaa
| 34.784038 | 187 | 0.524797 | false | false | false | false |
Cessation/even.tr
|
refs/heads/master
|
Pods/ALCameraViewController/ALCameraViewController/Views/CameraView.swift
|
apache-2.0
|
1
|
//
// CameraView.swift
// ALCameraViewController
//
// Created by Alex Littlejohn on 2015/06/17.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
import AVFoundation
public class CameraView: UIView {
var session: AVCaptureSession!
var input: AVCaptureDeviceInput!
var device: AVCaptureDevice!
var imageOutput: AVCaptureStillImageOutput!
var preview: AVCaptureVideoPreviewLayer!
let cameraQueue = dispatch_queue_create("com.zero.ALCameraViewController.Queue", DISPATCH_QUEUE_SERIAL);
let focusView = CropOverlay(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
public var currentPosition = AVCaptureDevicePosition.Back
public func startSession() {
dispatch_async(cameraQueue) {
self.createSession()
self.session?.startRunning()
}
}
public func stopSession() {
dispatch_async(cameraQueue) {
self.session?.stopRunning()
self.preview?.removeFromSuperlayer()
self.session = nil
self.input = nil
self.imageOutput = nil
self.preview = nil
self.device = nil
}
}
public override func layoutSubviews() {
super.layoutSubviews()
preview?.frame = bounds
}
public func configureFocus() {
if let gestureRecognizers = gestureRecognizers {
for gesture in gestureRecognizers {
removeGestureRecognizer(gesture)
}
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(CameraView.focus(_:)))
addGestureRecognizer(tapGesture)
userInteractionEnabled = true
addSubview(focusView)
focusView.hidden = true
let lines = focusView.horizontalLines + focusView.verticalLines + focusView.outerLines
lines.forEach { line in
line.alpha = 0
}
}
internal func focus(gesture: UITapGestureRecognizer) {
let point = gesture.locationInView(self)
guard focusCamera(point) else {
return
}
focusView.hidden = false
focusView.center = point
focusView.alpha = 0
focusView.transform = CGAffineTransformMakeScale(1.2, 1.2)
bringSubviewToFront(focusView)
UIView.animateKeyframesWithDuration(1.5, delay: 0, options: UIViewKeyframeAnimationOptions(), animations: {
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.15, animations: { () -> Void in
self.focusView.alpha = 1
self.focusView.transform = CGAffineTransformIdentity
})
UIView.addKeyframeWithRelativeStartTime(0.80, relativeDuration: 0.20, animations: { () -> Void in
self.focusView.alpha = 0
self.focusView.transform = CGAffineTransformMakeScale(0.8, 0.8)
})
}, completion: { finished in
if finished {
self.focusView.hidden = true
}
})
}
private func createSession() {
session = AVCaptureSession()
session.sessionPreset = AVCaptureSessionPresetHigh
dispatch_async(dispatch_get_main_queue()) {
self.createPreview()
}
}
private func createPreview() {
device = cameraWithPosition(currentPosition)
if device.hasFlash {
do {
try device.lockForConfiguration()
device.flashMode = .Auto
device.unlockForConfiguration()
} catch _ {}
}
let outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
do {
input = try AVCaptureDeviceInput(device: device)
} catch let error as NSError {
input = nil
print("Error: \(error.localizedDescription)")
return
}
if session.canAddInput(input) {
session.addInput(input)
}
imageOutput = AVCaptureStillImageOutput()
imageOutput.outputSettings = outputSettings
session.addOutput(imageOutput)
preview = AVCaptureVideoPreviewLayer(session: session)
preview.videoGravity = AVLayerVideoGravityResizeAspectFill
preview.frame = bounds
layer.addSublayer(preview)
}
private func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice? {
guard let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as? [AVCaptureDevice] else {
return nil
}
return devices.filter { $0.position == position }.first
}
public func capturePhoto(completion: CameraShotCompletion) {
dispatch_async(cameraQueue) {
let orientation = AVCaptureVideoOrientation(rawValue: UIDevice.currentDevice().orientation.rawValue)!
takePhoto(self.imageOutput, videoOrientation: orientation, cropSize: self.frame.size) { image in
dispatch_async(dispatch_get_main_queue()) {
completion(image)
}
}
}
}
public func focusCamera(toPoint: CGPoint) -> Bool {
guard let device = device where device.isFocusModeSupported(.ContinuousAutoFocus) else {
return false
}
do { try device.lockForConfiguration() } catch {
return false
}
// focus points are in the range of 0...1, not screen pixels
let focusPoint = CGPoint(x: toPoint.x / frame.width, y: toPoint.y / frame.height)
device.focusMode = AVCaptureFocusMode.ContinuousAutoFocus
device.exposurePointOfInterest = focusPoint
device.exposureMode = AVCaptureExposureMode.ContinuousAutoExposure
device.unlockForConfiguration()
return true
}
public func swapCameraInput() {
guard let session = session, input = input else {
return
}
session.beginConfiguration()
session.removeInput(input)
if input.device.position == AVCaptureDevicePosition.Back {
currentPosition = AVCaptureDevicePosition.Front
device = cameraWithPosition(currentPosition)
} else {
currentPosition = AVCaptureDevicePosition.Back
device = cameraWithPosition(currentPosition)
}
guard let i = try? AVCaptureDeviceInput(device: device) else {
return
}
self.input = i
session.addInput(i)
session.commitConfiguration()
}
}
|
027ad76c14cad3ad7896004a0c8e41eb
| 30.74537 | 115 | 0.590346 | false | false | false | false |
Maturelittleman/ImitateQQMusicDemo
|
refs/heads/master
|
QQMusic/QQMusic/Classes/QQList/Controller/QQListTVC.swift
|
apache-2.0
|
1
|
//
// QQListTVC.swift
// QQMusic
//
// Created by 仲琦 on 16/5/18.
// Copyright © 2016年 仲琦. All rights reserved.
//
import UIKit
class QQListTVC: UITableViewController {
var musicMs: [QQListModel] = [QQListModel]() {
didSet {
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
//取出数据
QQMusicDataTool.getMusicData { (musicMs) -> () in
self.musicMs = musicMs
ZQAudioOperationTool.sharInstance.musicMList = musicMs
}
//界面搭建
setUpInit()
}
}
//数据显示
extension QQListTVC {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return musicMs.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//创建自定义cell
let cell = QQMusicListCell.cellWithTableView(tableView)
//取出模型
cell.musicM = musicMs[indexPath.row]
//选定样式
cell.selectionStyle = .None
return cell
}
//cell即将显示调用
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//动画效果
let musicCell = cell as! QQMusicListCell
musicCell.beginAnimation(AnimationType.Translation)
}
//cell被点击的时候调用
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//拿到数据模型
let musicM = musicMs[indexPath.row]
//播放音乐
ZQAudioOperationTool.sharInstance.playMusic(musicM)
//跳转到详情界面
performSegueWithIdentifier("listToDetail", sender: nil)
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
//取出在当前窗口的cell
guard let indexPaths = tableView.indexPathsForVisibleRows else {
return
}
//取出前后两行索引
let first = indexPaths.first?.row ?? 0
let last = indexPaths.last?.row ?? 0
//计算中间一行对应的索引
let middle = Int(Float(first + last) * 0.5)
//遍历当前窗口的cell
for indexPath in indexPaths
{
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.x = CGFloat(abs(indexPath.row - middle) * 20)
}
}
}
//界面搭建
extension QQListTVC {
private func setUpInit() -> () {
setUpTableView()
setUpNavigationBar()
}
private func setUpTableView() -> () {
//背景图片
let imageV = UIImageView(image: UIImage(named: "QQListBack"))
tableView.backgroundView = imageV
//行高
tableView.rowHeight = 60
//分割线效果
tableView.separatorStyle = .None
}
private func setUpNavigationBar() -> () {
//设置顶部导航栏隐藏
navigationController?.navigationBarHidden = true
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
//设置状态栏字体颜色
return .LightContent
}
}
|
d087d2a2aef997ef3ca9211ca4526f8f
| 23.361538 | 134 | 0.582886 | false | false | false | false |
vermont42/Conjugar
|
refs/heads/master
|
Conjugar/QuizVC.swift
|
agpl-3.0
|
1
|
//
// QuizVC.swift
// Conjugar
//
// Created by Joshua Adams on 6/18/17.
// Copyright © 2017 Josh Adams. All rights reserved.
//
import UIKit
class QuizVC: UIViewController, UITextFieldDelegate, QuizDelegate {
static let englishTitle = "Quiz"
var quizView: QuizUIV {
if let castedView = view as? QuizUIV {
return castedView
} else {
fatalError(fatalCastMessage(view: QuizUIV.self))
}
}
override func loadView() {
let quizView: QuizUIV
quizView = QuizUIV(frame: UIScreen.main.bounds)
quizView.startRestartButton.addTarget(self, action: #selector(startRestart), for: .touchUpInside)
quizView.quitButton.addTarget(self, action: #selector(quit), for: .touchUpInside)
navigationItem.titleView = UILabel.titleLabel(title: Localizations.Quiz.localizedTitle)
quizView.conjugationField.delegate = self
view = quizView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
Current.quiz.delegate = self
switch Current.quiz.quizState {
case .notStarted, .finished:
quizView.hideInProgressUI()
quizView.startRestartButton.setTitle(Localizations.Quiz.start, for: .normal)
case .inProgress:
quizView.showInProgressUI()
quizView.startRestartButton.setTitle(Localizations.Quiz.restart, for: .normal)
let verb = Current.quiz.verb
quizView.verb.text = verb
let translationResult = Conjugator.shared.conjugate(infinitive: verb, tense: .translation, personNumber: .none)
switch translationResult {
case let .success(value):
quizView.translation.text = value
default:
fatalError("translation not found.")
}
quizView.tenseLabel.text = Current.quiz.tense.displayName
quizView.pronoun.text = Current.quiz.currentPersonNumber.pronoun
quizView.score.text = String(Current.quiz.score)
quizView.progress.text = String(Current.quiz.currentQuestionIndex + 1) + " / " + String(Current.quiz.questionCount)
}
quizView.startRestartButton.pulsate()
authenticate()
Current.analytics.recordVisitation(viewController: "\(QuizVC.self)")
}
private func authenticate() {
if !Current.gameCenter.isAuthenticated && Current.settings.userRejectedGameCenter {
if !Current.settings.didShowGameCenterDialog {
showGameCenterDialog()
} else {
Current.gameCenter.authenticate(onViewController: self, completion: nil)
}
}
}
private func showGameCenterDialog() {
Current.settings.didShowGameCenterDialog = true
let gameCenterController = UIAlertController(title: Localizations.Quiz.gameCenter, message: Localizations.Quiz.gameCenterMessage, preferredStyle: UIAlertController.Style.alert)
let noAction = UIAlertAction(title: Localizations.Quiz.no, style: UIAlertAction.Style.destructive) { _ in
SoundPlayer.play(.sadTrombone)
Current.settings.userRejectedGameCenter = true
}
gameCenterController.addAction(noAction)
let yesAction = UIAlertAction(title: Localizations.Quiz.yes, style: UIAlertAction.Style.default) { _ in
Current.gameCenter.authenticate(onViewController: self, completion: nil)
}
gameCenterController.addAction(yesAction)
present(gameCenterController, animated: true, completion: nil)
}
@objc func startRestart() {
SoundPlayer.play(.gun)
Current.quiz.start()
quizView.startRestartButton.setTitle(Localizations.Quiz.restart, for: .normal)
[quizView.lastLabel, quizView.correctLabel, quizView.last, quizView.correct].forEach {
$0.isHidden = true
}
quizView.showInProgressUI()
quizView.startRestartButton.pulsate()
quizView.conjugationField.becomeFirstResponder()
quizView.quitButton.isHidden = false
Current.analytics.recordQuizStart()
}
@objc func quit() {
Current.quiz.quit()
SoundPlayer.play(.sadTrombone)
resetUI()
Current.analytics.recordQuizQuit(currentQuestionIndex: Current.quiz.currentQuestionIndex, score: Current.quiz.score)
}
func scoreDidChange(newScore: Int) {
quizView.score.text = String(newScore)
}
func timeDidChange(newTime: Int) {
quizView.elapsed.text = newTime.timeString
}
func progressDidChange(current: Int, total: Int) {
quizView.progress.text = String(current + 1) + " / " + String(total)
}
func questionDidChange(verb: String, tense: Tense, personNumber: PersonNumber) {
quizView.verb.text = verb
let translationResult = Conjugator.shared.conjugate(infinitive: verb, tense: .translation, personNumber: .none)
switch translationResult {
case let .success(value):
quizView.translation.text = value
default:
fatalError()
}
quizView.tenseLabel.text = Localizations.Quiz.tense + ": " + tense.displayName
quizView.pronoun.text = personNumber.pronoun
quizView.conjugationField.becomeFirstResponder()
}
func quizDidFinish() {
SoundPlayer.playRandomApplause()
let resultsVC = ResultsVC()
navigationController?.pushViewController(resultsVC, animated: true)
resetUI()
Current.gameCenter.showLeaderboard()
Current.analytics.recordQuizCompletion(score: Current.quiz.score)
}
private func resetUI() {
quizView.hideInProgressUI()
quizView.conjugationField.text = ""
quizView.conjugationField.resignFirstResponder()
quizView.startRestartButton.setTitle(Localizations.Quiz.start, for: .normal)
quizView.quitButton.isHidden = true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let text = quizView.conjugationField.text else { return false }
guard text != "" else { return false }
quizView.conjugationField.resignFirstResponder()
let (result, correctConjugation) = Current.quiz.process(proposedAnswer: text)
quizView.conjugationField.text = nil
switch result {
case .totalMatch:
SoundPlayer.play(.chime)
case .partialMatch:
SoundPlayer.play(.chirp)
case .noMatch:
SoundPlayer.play(.buzz)
}
if let correctConjugation = correctConjugation, Current.quiz.quizState == .inProgress {
[quizView.lastLabel, quizView.last, quizView.correctLabel, quizView.correct].forEach {
$0.isHidden = false
}
quizView.last.attributedText = text.coloredString(color: Colors.blue)
quizView.correct.attributedText = correctConjugation.conjugatedString
} else {
[quizView.lastLabel, quizView.last, quizView.correctLabel, quizView.correct].forEach {
$0.isHidden = true
}
}
return true
}
}
|
74378d7fe54858bcece1945b971d4c45
| 35.960452 | 180 | 0.722868 | false | false | false | false |
KyoheiG3/AttributedLabel
|
refs/heads/master
|
AttributedLabelExample/AttributedLabelExample/CustomizeViewController.swift
|
mit
|
1
|
//
// CustomizeViewController.swift
// AttributedLabelExample
//
// Created by Kyohei Ito on 2015/07/17.
// Copyright © 2015年 Kyohei Ito. All rights reserved.
//
import UIKit
import AttributedLabel
class CustomizeViewController: UIViewController {
@IBOutlet weak var attributedLabel: AttributedLabel!
override func viewDidLoad() {
super.viewDidLoad()
attributedLabel.text = "AttributedLabel"
}
private func rand(_ random: UInt32) -> CGFloat {
return CGFloat(arc4random_uniform(random))
}
private func randColor(_ random: UInt32) -> UIColor {
return UIColor(hue: rand(random) / 10, saturation: 0.8, brightness: 0.8, alpha: 1)
}
@IBAction func buttonTapped(_ sender: AnyObject) {
if let button = sender as? UIButton, let alignment = AttributedLabel.ContentAlignment(rawValue: button.tag) {
attributedLabel.contentAlignment = alignment
}
}
@IBAction func changeTextColor() {
attributedLabel.textColor = randColor(10)
}
@IBAction func changeFontSize() {
attributedLabel.font = UIFont.systemFont(ofSize: rand(20) + 12)
}
@IBAction func changeShadow() {
let shadow = NSShadow()
shadow.shadowBlurRadius = rand(5)
shadow.shadowOffset = CGSize(width: rand(5), height: rand(5))
shadow.shadowColor = randColor(10)
attributedLabel.shadow = shadow
}
}
|
944d88f4fe4f32ec312eb27f57e4fbc5
| 27.666667 | 117 | 0.649795 | false | false | false | false |
haawa799/WaniPersistance
|
refs/heads/master
|
WaniPersistance/KanjiInfo.swift
|
mit
|
1
|
//
// KanjiInfo.swift
// WaniKani
//
// Created by Andriy K. on 3/31/17.
// Copyright © 2017 haawa. All rights reserved.
//
import Foundation
import WaniModel
import RealmSwift
class KanjiInfo: Object, WaniModelConvertable {
typealias PersistantType = WaniPersistance.KanjiInfo
typealias WaniType = WaniModel.KanjiInfo
dynamic var character: String = ""
dynamic var meaning: String?
dynamic var onyomi: String?
dynamic var kunyomi: String?
dynamic var nanori: String?
dynamic var importantReading: String?
dynamic var level: Int = 0
dynamic var percentage: String?
dynamic var unlockedDate: Date?
dynamic var userSpecific: UserSpecific? {
didSet {
if userSpecific == nil {
userSpecific = oldValue
}
}
}
override static func primaryKey() -> String? {
return "character"
}
convenience required init(model: WaniType) {
self.init()
self.character = model.character
self.meaning = model.meaning
self.onyomi = model.onyomi
self.kunyomi = model.kunyomi
self.nanori = model.nanori
self.importantReading = model.importantReading
self.level = model.level
self.percentage = model.percentage
self.unlockedDate = model.unlockedDate
if let userSpecific = model.userSpecific {
self.userSpecific = WaniPersistance.UserSpecific(userSpecific: userSpecific)
}
}
var waniModelStruct: WaniType {
return WaniModel.KanjiInfo(realmObject: self)
}
}
extension KanjiInfo.WaniType: PersistanceModelInstantiatible {
typealias PersistantType = WaniPersistance.KanjiInfo
init(realmObject: PersistantType) {
self.character = realmObject.character
self.meaning = realmObject.meaning
self.onyomi = realmObject.onyomi
self.kunyomi = realmObject.kunyomi
self.nanori = realmObject.nanori
self.importantReading = realmObject.importantReading
self.level = realmObject.level
self.percentage = realmObject.percentage
self.unlockedDate = realmObject.unlockedDate
self.userSpecific = realmObject.userSpecific?.waniModelStruct
}
}
|
05dc0c67e2431a4ebbef2fd3257f8bed
| 25.974026 | 82 | 0.73038 | false | false | false | false |
LQJJ/demo
|
refs/heads/master
|
125-iOSTips-master/Demo/11.华丽的TableView刷新动效/TableViewRefreshAnimation/TableViewAnimator.swift
|
apache-2.0
|
1
|
//
// TableViewAnimator.swift
// TableViewRefreshAnimation
//
// Created by Dariel on 2018/10/12.
// Copyright © 2018年 Dariel. All rights reserved.
//
import UIKit
typealias Animation = (UITableViewCell, IndexPath, UITableView) -> Void
enum AnimationFactory {
static func makeFade(duration: TimeInterval, delayFactor: Double) -> Animation {
return { cell, indexPath, _ in
cell.alpha = 0
UIView.animate(
withDuration: duration,
delay: delayFactor * Double(indexPath.row),
animations: {
cell.alpha = 1
})
}
}
static func makeMoveUpWithBounce(rowHeight: CGFloat, duration: TimeInterval, delayFactor: Double) -> Animation {
return { cell, indexPath, tableView in
cell.transform = CGAffineTransform(translationX: 0, y: rowHeight)
UIView.animate(
withDuration: duration,
delay: delayFactor * Double(indexPath.row),
usingSpringWithDamping: 0.4,
initialSpringVelocity: 0.1,
options: [.curveEaseInOut],
animations: {
cell.transform = CGAffineTransform(translationX: 0, y: 0)
})
}
}
static func makeSlideIn(duration: TimeInterval, delayFactor: Double) -> Animation {
return { cell, indexPath, tableView in
cell.transform = CGAffineTransform(translationX: tableView.bounds.width, y: 0)
UIView.animate(
withDuration: duration,
delay: delayFactor * Double(indexPath.row),
options: [.curveEaseInOut],
animations: {
cell.transform = CGAffineTransform(translationX: 0, y: 0)
})
}
}
static func makeMoveUpWithFade(rowHeight: CGFloat, duration: TimeInterval, delayFactor: Double) -> Animation {
return { cell, indexPath, tableView in
cell.transform = CGAffineTransform(translationX: 0, y: rowHeight / 2)
cell.alpha = 0
UIView.animate(
withDuration: duration,
delay: delayFactor * Double(indexPath.row),
options: [.curveEaseInOut],
animations: {
cell.transform = CGAffineTransform(translationX: 0, y: 0)
cell.alpha = 1
})
}
}
}
final class TableViewAnimator {
private var hasAnimatedAllCells = false
private let animation: Animation
init(animation: @escaping Animation) {
self.animation = animation
}
func animate(cell: UITableViewCell, at indexPath: IndexPath, in tableView: UITableView) {
guard !hasAnimatedAllCells else {
return
}
animation(cell, indexPath, tableView)
hasAnimatedAllCells = tableView.isLastVisibleCell(at: indexPath)
}
}
|
351eb788337cea0be04fe5e612db9be1
| 31.548387 | 116 | 0.567889 | false | false | false | false |
franklinsch/marylouios
|
refs/heads/master
|
MarylouiOS/MarylouiOS/DataManager.swift
|
apache-2.0
|
1
|
//
// DataManager.swift
// TopApps
//
// Created by Dani Arnaout on 9/2/14.
// Edited by Eric Cerney on 9/27/14.
// Copyright (c) 2014 Ray Wenderlich All rights reserved.
//
import Foundation
let TopAppURL = "http://www.freddielindsey.me:3000/getcities"
class DataManager {
class func getTopAppsDataFromFileWithSuccess(success: ((data: NSData) -> Void)) {
//1
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
//2
let filePath = NSBundle.mainBundle().pathForResource("SampleData",ofType:"json")
var readError:NSError?
if let data = NSData(contentsOfFile:filePath!,
options: NSDataReadingOptions.DataReadingUncached,
error:&readError) {
success(data: data)
}
})
}
class func loadDataFromURL(url: NSURL, completion:(data: NSData?, error: NSError?) -> Void) {
var session = NSURLSession.sharedSession()
// Use NSURLSession to get data from an NSURL
let loadDataTask = session.dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if let responseError = error {
completion(data: nil, error: responseError)
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
var statusError = NSError(domain:"com.raywenderlich", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
completion(data: nil, error: statusError)
} else {
completion(data: data, error: nil)
}
}
})
loadDataTask.resume()
}
class func getDataFromServerWithSuccess(success: ((ServerData: NSData!) -> Void)) {
loadDataFromURL(NSURL(string: TopAppURL)!, completion:{(data, error) -> Void in
println("here")
if let urlData = data {
success(ServerData: urlData)
}
println("Data \(data)")
})
}
}
|
6c59a38f22e9e6df756ddfbcc8e1a3b9
| 33.181818 | 184 | 0.578271 | false | false | false | false |
gadLinux/thrift
|
refs/heads/master
|
lib/swift/Sources/TCompactProtocol.swift
|
apache-2.0
|
5
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import Foundation
import CoreFoundation
public enum TCType: UInt8 {
case stop = 0x00
case boolean_TRUE = 0x01
case boolean_FALSE = 0x02
case i8 = 0x03
case i16 = 0x04
case i32 = 0x05
case i64 = 0x06
case double = 0x07
case binary = 0x08
case list = 0x09
case set = 0x0A
case map = 0x0B
case `struct` = 0x0C
public static let typeMask: UInt8 = 0xE0 // 1110 0000
public static let typeBits: UInt8 = 0x07 // 0000 0111
public static let typeShiftAmount = 5
}
public class TCompactProtocol: TProtocol {
public static let protocolID: UInt8 = 0x82
public static let version: UInt8 = 1
public static let versionMask: UInt8 = 0x1F // 0001 1111
public var transport: TTransport
var lastField: [UInt8] = []
var lastFieldId: UInt8 = 0
var boolFieldName: String?
var boolFieldType: TType?
var boolFieldId: Int32?
var booleanValue: Bool?
var currentMessageName: String?
public required init(on transport: TTransport) {
self.transport = transport
}
/// Mark: - TCompactProtocol helpers
func writebyteDirect(_ byte: UInt8) throws {
let byte = Data(bytes: [byte])
try ProtocolTransportTry(error: TProtocolError(message: "Transport Write Failed")) {
try self.transport.write(data: byte)
}
}
func writeVarint32(_ val: UInt32) throws {
var val = val
var i32buf = [UInt8](repeating: 0, count: 5)
var idx = 0
while true {
if (val & ~0x7F) == 0 {
i32buf[idx] = UInt8(val)
idx += 1
break
} else {
i32buf[idx] = UInt8((val & 0x7F) | 0x80)
idx += 1
val >>= 7
}
}
try ProtocolTransportTry(error: TProtocolError(message: "Transport Write Failed")) {
try self.transport.write(data: Data(bytes: i32buf[0..<idx]))
}
}
func writeVarint64(_ val: UInt64) throws {
var val = val
var varint64out = [UInt8](repeating: 0, count: 10)
var idx = 0
while true {
if (val & ~0x7F) == 0{
varint64out[idx] = UInt8(val)
idx += 1
break
} else {
varint64out[idx] = UInt8(val & 0x7F) | 0x80
idx += 1
val >>= 7
}
}
try ProtocolTransportTry(error: TProtocolError(message: "Transport Write Failed")) {
try self.transport.write(data: Data(bytes: varint64out[0..<idx]))
}
}
func writeCollectionBegin(_ elementType: TType, size: Int32) throws {
let ctype = compactType(elementType).rawValue
if size <= 14 {
try writebyteDirect(UInt8(size << 4) | ctype)
} else {
try writebyteDirect(0xF0 | ctype)
try writeVarint32(UInt32(size))
}
}
func readBinary(_ size: Int) throws -> Data {
var result = Data()
if size != 0 {
try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) {
result = try self.transport.readAll(size: size)
}
}
return result
}
func readVarint32() throws -> UInt32 {
var result: UInt32 = 0
var shift: UInt32 = 0
while true {
let byte: UInt8 = try read()
result |= UInt32(byte & 0x7F) << shift
if (byte & 0x80) == 0 {
break
}
shift += 7
}
return result
}
func readVarint64() throws -> UInt64 {
var result: UInt64 = 0
var shift: UInt64 = 0
while true {
let byte: UInt8 = try read()
result |= UInt64(byte & 0x7F) << shift
if (byte & 0x80) == 0 {
break
}
shift += 7
}
return result
}
func ttype(_ compactTypeVal: UInt8) throws -> TType {
guard let compactType = TCType(rawValue: compactTypeVal) else {
throw TProtocolError(message: "Unknown TCType value: \(compactTypeVal)")
}
switch compactType {
case .stop: return .stop;
case .boolean_FALSE, .boolean_TRUE: return .bool;
case .i8: return .i8;
case .i16: return .i16;
case .i32: return .i32;
case .i64: return .i64;
case .double: return .double;
case .binary: return .string;
case .list: return .list;
case .set: return .set;
case .map: return .map;
case .struct: return .struct;
}
}
func compactType(_ ttype: TType) -> TCType {
switch ttype {
case .stop: return .stop
case .void: return .i8
case .bool: return .boolean_FALSE
case .i8: return .i8
case .double: return .double
case .i16: return .i16
case .i32: return .i32
case .i64: return .i64
case .string: return .binary
case .struct: return .struct
case .map: return .map
case .set: return .set
case .list: return .list
case .utf8: return .binary
case .utf16: return .binary
}
}
/// ZigZag encoding maps signed integers to unsigned integers so that
/// numbers with a small absolute value (for instance, -1) have
/// a small varint encoded value too. It does this in a way that
/// "zig-zags" back and forth through the positive and negative integers,
/// so that -1 is encoded as 1, 1 is encoded as 2, -2 is encoded as 3, and so
///
/// - parameter n: number to zigzag
///
/// - returns: zigzaged UInt32
func i32ToZigZag(_ n : Int32) -> UInt32 {
return UInt32(bitPattern: Int32(n << 1) ^ Int32(n >> 31))
}
func i64ToZigZag(_ n : Int64) -> UInt64 {
return UInt64(bitPattern: Int64(n << 1) ^ Int64(n >> 63))
}
func zigZagToi32(_ n: UInt32) -> Int32 {
return Int32(n >> 1) ^ (-Int32(n & 1))
}
func zigZagToi64(_ n: UInt64) -> Int64 {
return Int64(n >> 1) ^ (-Int64(n & 1))
}
/// Mark: - TProtocol
public func readMessageBegin() throws -> (String, TMessageType, Int32) {
let protocolId: UInt8 = try read()
if protocolId != TCompactProtocol.protocolID {
let expected = String(format:"%2X", TCompactProtocol.protocolID)
let got = String(format:"%2X", protocolId)
throw TProtocolError(message: "Wrong Protocol ID \(got)",
extendedError: .mismatchedProtocol(expected: expected, got: got))
}
let versionAndType: UInt8 = try read()
let version: UInt8 = versionAndType & TCompactProtocol.versionMask
if version != TCompactProtocol.version {
throw TProtocolError(error: .badVersion(expected: "\(TCompactProtocol.version)",
got:"\(version)"))
}
let type = (versionAndType >> UInt8(TCType.typeShiftAmount)) & TCType.typeBits
guard let mtype = TMessageType(rawValue: Int32(type)) else {
throw TProtocolError(message: "Unknown TMessageType value: \(type)")
}
let sequenceId = try readVarint32()
let name: String = try read()
return (name, mtype, Int32(sequenceId))
}
public func readMessageEnd() throws { }
public func readStructBegin() throws -> String {
lastField.append(lastFieldId)
lastFieldId = 0
return ""
}
public func readStructEnd() throws {
lastFieldId = lastField.last ?? 0
lastField.removeLast()
}
public func readFieldBegin() throws -> (String, TType, Int32) {
let byte: UInt8 = try read()
guard let type = TCType(rawValue: byte & 0x0F) else {
throw TProtocolError(message: "Unknown TCType \(byte & 0x0F)")
}
// if it's a stop, then we can return immediately, as the struct is over
if type == .stop {
return ("", .stop, 0)
}
var fieldId: Int16 = 0
// mask off the 4MSB of the type header. it could contain a field id delta
let modifier = (byte & 0xF0) >> 4
if modifier == 0 {
// not a delta. look ahead for the zigzag varint field id
fieldId = try read()
} else {
// has a delta. add the delta to the last Read field id.
fieldId = Int16(lastFieldId + modifier)
}
let fieldType = try ttype(type.rawValue)
// if this happens to be a boolean field, the value is encoded in the type
if type == .boolean_TRUE || type == .boolean_FALSE {
// save the boolean value in a special instance variable
booleanValue = type == .boolean_TRUE
}
// push the new field onto the field stack so we can keep the deltas going
lastFieldId = UInt8(fieldId)
return ("", fieldType, Int32(fieldId))
}
public func readFieldEnd() throws { }
public func read() throws -> String {
let length = try readVarint32()
var result: String
if length != 0 {
let data = try readBinary(Int(length))
result = String(data: data, encoding: String.Encoding.utf8) ?? ""
} else {
result = ""
}
return result
}
public func read() throws -> Bool {
if let val = booleanValue {
self.booleanValue = nil
return val
} else {
let result = try read() as UInt8
return TCType(rawValue: result) == .boolean_TRUE
}
}
public func read() throws -> UInt8 {
var buff: UInt8 = 0
try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) {
buff = try self.transport.readAll(size: 1)[0]
}
return buff
}
public func read() throws -> Int16 {
let v = try readVarint32()
return Int16(zigZagToi32(v))
}
public func read() throws -> Int32 {
let v = try readVarint32()
return zigZagToi32(v)
}
public func read() throws -> Int64 {
let v = try readVarint64()
return zigZagToi64(v)
}
public func read() throws -> Double {
var buff = Data()
try ProtocolTransportTry(error: TProtocolError(message: "Transport Read Failed")) {
buff = try self.transport.readAll(size: 8)
}
let i64: UInt64 = buff.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> UInt64 in
return UnsafePointer<UInt64>(OpaquePointer(ptr)).pointee
}
let bits = CFSwapInt64LittleToHost(i64)
return Double(bitPattern: bits)
}
public func read() throws -> Data {
let length = try readVarint32()
return try readBinary(Int(length))
}
public func readMapBegin() throws -> (TType, TType, Int32) {
var keyAndValueType: UInt8 = 8
let size = try readVarint32()
if size != 0 {
keyAndValueType = try read()
}
let keyType = try ttype(keyAndValueType >> 4)
let valueType = try ttype(keyAndValueType & 0xF)
return (keyType, valueType, Int32(size))
}
public func readMapEnd() throws { }
public func readSetBegin() throws -> (TType, Int32) {
return try readListBegin()
}
public func readSetEnd() throws { }
public func readListBegin() throws -> (TType, Int32) {
let sizeAndType: UInt8 = try read()
var size: UInt32 = UInt32(sizeAndType >> 4) & 0x0f
if size == 15 {
size = try readVarint32()
}
let elementType = try ttype(sizeAndType & 0x0F)
return (elementType, Int32(size))
}
public func readListEnd() throws { }
public func writeMessageBegin(name: String,
type messageType: TMessageType,
sequenceID: Int32) throws {
try writebyteDirect(TCompactProtocol.protocolID)
let nextByte: UInt8 = (TCompactProtocol.version & TCompactProtocol.versionMask) |
(UInt8((UInt32(messageType.rawValue) << UInt32(TCType.typeShiftAmount))) &
TCType.typeMask)
try writebyteDirect(nextByte)
try writeVarint32(UInt32(sequenceID))
try write(name)
currentMessageName = name
}
public func writeMessageEnd() throws {
currentMessageName = nil
}
public func writeStructBegin(name: String) throws {
lastField.append(lastFieldId)
lastFieldId = 0
}
public func writeStructEnd() throws {
lastFieldId = lastField.last ?? 0
lastField.removeLast()
}
public func writeFieldBegin(name: String,
type fieldType: TType,
fieldID: Int32) throws {
if fieldType == .bool {
boolFieldName = name
boolFieldType = fieldType
boolFieldId = fieldID
return
} else {
try writeFieldBeginInternal(name: name,
type: fieldType,
fieldID: fieldID,
typeOverride: 0xFF)
}
}
func writeFieldBeginInternal(name: String,
type fieldType: TType,
fieldID: Int32,
typeOverride: UInt8) throws {
let typeToWrite = typeOverride == 0xFF ? compactType(fieldType).rawValue : typeOverride
// check if we can use delta encoding for the field id
let diff = UInt8(fieldID) - lastFieldId
if (UInt8(fieldID) > lastFieldId) && (diff <= 15) {
// Write them together
try writebyteDirect((UInt8(fieldID) - lastFieldId) << 4 | typeToWrite)
} else {
// Write them separate
try writebyteDirect(typeToWrite)
try write(Int16(fieldID))
}
lastFieldId = UInt8(fieldID)
}
public func writeFieldStop() throws {
try writebyteDirect(TCType.stop.rawValue)
}
public func writeFieldEnd() throws { }
public func writeMapBegin(keyType: TType, valueType: TType, size: Int32) throws {
if size == 0 {
try writebyteDirect(0)
} else {
try writeVarint32(UInt32(size))
let compactedTypes = compactType(keyType).rawValue << 4 | compactType(valueType).rawValue
try writebyteDirect(compactedTypes)
}
}
public func writeMapEnd() throws { }
public func writeSetBegin(elementType: TType, size: Int32) throws {
try writeCollectionBegin(elementType, size: size)
}
public func writeSetEnd() throws { }
public func writeListBegin(elementType: TType, size: Int32) throws {
try writeCollectionBegin(elementType, size: size)
}
public func writeListEnd() throws { }
public func write(_ value: String) throws {
try write(value.data(using: String.Encoding.utf8)!)
}
public func write(_ value: Bool) throws {
if let boolFieldId = boolFieldId, let boolFieldType = boolFieldType,
let boolFieldName = boolFieldName {
// we haven't written the field header yet
let compactType: TCType = value ? .boolean_TRUE : .boolean_FALSE
try writeFieldBeginInternal(name: boolFieldName, type: boolFieldType, fieldID: boolFieldId,
typeOverride: compactType.rawValue)
self.boolFieldId = nil
self.boolFieldType = nil
self.boolFieldName = nil
} else {
// we're not part of a field, so just write the value.
try writebyteDirect(value ? TCType.boolean_TRUE.rawValue : TCType.boolean_FALSE.rawValue)
}
}
public func write(_ value: UInt8) throws {
try writebyteDirect(value)
}
public func write(_ value: Int16) throws {
try writeVarint32(i32ToZigZag(Int32(value)))
}
public func write(_ value: Int32) throws {
try writeVarint32(i32ToZigZag(value))
}
public func write(_ value: Int64) throws {
try writeVarint64(i64ToZigZag(value))
}
public func write(_ value: Double) throws {
var bits = CFSwapInt64HostToLittle(value.bitPattern)
let data = withUnsafePointer(to: &bits) {
return Data(bytes: UnsafePointer<UInt8>(OpaquePointer($0)), count: MemoryLayout<UInt64>.size)
}
try ProtocolTransportTry(error: TProtocolError(message: "Transport Write Failed")) {
try self.transport.write(data: data)
}
}
public func write(_ data: Data) throws {
try writeVarint32(UInt32(data.count))
try ProtocolTransportTry(error: TProtocolError(message: "Transport Write Failed")) {
try self.transport.write(data: data)
}
}
}
|
bd23c0971d5c5ea1ce050d540db54546
| 27.951304 | 100 | 0.61837 | false | false | false | false |
microtherion/Octarine
|
refs/heads/master
|
Octarine/OctSearch.swift
|
bsd-2-clause
|
1
|
//
// OctSearch.swift
// Octarine
//
// Created by Matthias Neeracher on 18/04/16.
// Copyright © 2016 Matthias Neeracher. All rights reserved.
//
import AppKit
class OctSearch : NSObject, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet weak var resultTable : NSTableView!
@IBOutlet weak var octApp : OctApp!
@IBOutlet weak var sheets: OctSheets!
override func awakeFromNib() {
resultTable.setDraggingSourceOperationMask(.Copy, forLocal: true)
resultTable.setDraggingSourceOperationMask(.Copy, forLocal: false)
}
dynamic var searchResults = [[String: AnyObject]]() {
didSet {
if searchResults.count == 1 {
resultTable.selectRowIndexes(NSIndexSet(index: 0), byExtendingSelection: false)
updateDataSheets()
}
}
}
func focusSearchResults() {
self.octApp.window.makeFirstResponder(resultTable)
}
class func partFromJSON(item: AnyObject?) -> [String: AnyObject] {
let item = item as! [String: AnyObject]
let manu = item["manufacturer"] as! [String: AnyObject]
var datasheets = [String]()
if let ds = item["datasheets"] as? [[String: AnyObject]] {
for sheet in ds {
if let url = sheet["url"] as? String {
datasheets.append(url)
}
}
}
let newItem : [String: AnyObject] = [
"ident": stringRep(item["uid"]),
"name": stringRep(item["mpn"]),
"manu": stringRep(manu["name"]),
"desc": stringRep(item["short_description"]),
"murl": stringRep(manu["homepage_url"]),
"purl": stringRep(item["octopart_url"]),
"sheets": datasheets
]
return newItem
}
var partFromUIDCache = [String: [String: AnyObject]]()
var cacheExpiry = NSDate(timeIntervalSinceNow: 86400)
func partsFromCachedUIDs(uids: [String], completion:([[String: AnyObject]]) -> Void) {
var results = [[String: AnyObject]]()
for uid in uids {
if let cached = partFromUIDCache[uid] {
results.append(cached)
}
}
completion(results)
}
func partsFromUIDs(uids: [String], completion:([[String: AnyObject]]) -> Void) {
let now = NSDate()
if now.compare(cacheExpiry) == .OrderedDescending {
// Flush cache to comply with Octopart terms of use
partFromUIDCache = [:]
cacheExpiry = NSDate(timeIntervalSinceNow: 86400)
}
let uidsToFetch = uids.filter { (uid: String) -> Bool in
return partFromUIDCache.indexForKey(uid) == nil
}
guard uidsToFetch.count > 0 else {
partsFromCachedUIDs(uids, completion: completion)
return
}
let urlComponents = NSURLComponents(string: "https://octopart.com/api/v3/parts/get_multi")!
let queryItems = [
NSURLQueryItem(name: "apikey", value: OCTOPART_API_KEY),
NSURLQueryItem(name: "include[]", value: "datasheets"),
NSURLQueryItem(name: "include[]", value: "short_description"),
] + uidsToFetch.map() { (uid: String) -> NSURLQueryItem in
NSURLQueryItem(name: "uid[]", value: uid)
}
urlComponents.queryItems = queryItems
let task = OctarineSession.dataTaskWithURL(urlComponents.URL!) { (data: NSData?, response: NSURLResponse?, error: NSError?) in
let response = try? NSJSONSerialization.JSONObjectWithData(data!, options: [])
if let results = response as? [String: AnyObject] where results["class"] == nil {
for (_,result) in results {
var part = OctSearch.partFromJSON(result)
self.partFromUIDCache[part["ident"] as! String] = part
}
}
self.octApp.endingRequest()
self.partsFromCachedUIDs(uids, completion: completion)
}
octApp.startingRequest()
task.resume()
}
@IBAction func searchComponents(sender: NSSearchField!) {
let urlComponents = NSURLComponents(string: "https://octopart.com/api/v3/parts/search")!
urlComponents.queryItems = [
NSURLQueryItem(name: "apikey", value: OCTOPART_API_KEY),
NSURLQueryItem(name: "q", value: sender.stringValue),
NSURLQueryItem(name: "include[]", value: "datasheets"),
NSURLQueryItem(name: "include[]", value: "short_description"),
NSURLQueryItem(name: "limit", value: "100")
]
let task = OctarineSession.dataTaskWithURL(urlComponents.URL!) { (data: NSData?, response: NSURLResponse?, error: NSError?) in
let response = try? NSJSONSerialization.JSONObjectWithData(data!, options: [])
var newResults = [[String: AnyObject]]()
if response != nil {
let results = response!["results"] as! [[String: AnyObject]]
for result in results {
newResults.append(OctSearch.partFromJSON(result["item"]))
}
}
self.octApp.endingRequest()
dispatch_async(dispatch_get_main_queue(), {
self.focusSearchResults()
self.searchResults = newResults
})
}
octApp.startingRequest()
task.resume()
}
func tableView(tableView: NSTableView, writeRowsWithIndexes rowIndexes: NSIndexSet, toPasteboard pboard: NSPasteboard) -> Bool {
let serialized = rowIndexes.map({ (index: Int) -> [String : AnyObject] in
let part = searchResults[index]
return ["is_part": true, "ident": part["ident"]!, "name": part["name"]!, "desc": part["desc"]!]
})
let urls = rowIndexes.map({ (index: Int) -> NSPasteboardItem in
let part = searchResults[index]
let pbitem = NSPasteboardItem()
pbitem.setString(part["purl"] as? String, forType: "public.url")
pbitem.setString(part["name"] as? String, forType: "public.url-name")
return pbitem
})
pboard.declareTypes([kOctPasteboardType], owner: self)
pboard.setPropertyList(serialized, forType: kOctPasteboardType)
pboard.writeObjects(urls)
return true
}
func updateDataSheets() {
if resultTable.selectedRowIndexes.count == 1 {
let newSheets = searchResults[resultTable.selectedRow]["sheets"] as? [String] ?? []
sheets.dataSheets = newSheets
if newSheets.count > 0 {
sheets.dataSheetSelection = 0
}
} else {
sheets.dataSheets = []
}
}
func tableViewSelectionDidChange(_: NSNotification) {
updateDataSheets()
}
}
|
4186e3b05639e9dbc9b2e0b6d9fd4051
| 37.983051 | 134 | 0.582609 | false | false | false | false |
AlanAherne/BabyTunes
|
refs/heads/master
|
BabyTunes/BabyTunes/Modules/Main/Home/View controllers/RevealViewController.swift
|
mit
|
1
|
import UIKit
import AVFoundation
class RevealViewController: UIViewController, AVAudioPlayerDelegate, UIScrollViewDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var playPauseButton: UIButton!
@IBOutlet weak var currentTimeLabel: UILabel!
@IBOutlet weak var remainingTimeLabel: UILabel!
@IBOutlet weak var visualizerView: UIView!
var song: Song?
var swipeInteractionController: SwipeInteractionController?
var visualizerTimer:Timer! = Timer()
var audioVisualizer: ATAudioVisualizer!
var lowPassResults1:Double! = 0.0
var lowPassResult:Double! = 0.0
var audioPlayer:AVAudioPlayer!
var songTitel = ""
let visualizerAnimationDuration = 0.01
override func viewDidLoad() {
super.viewDidLoad()
guard let revealSong = song else {
NSLog("no song set in the card view controller")
return
}
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 5.0
let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapSinlge(recognizer:)))
singleTapGesture.numberOfTapsRequired = 1
self.scrollView.addGestureRecognizer(singleTapGesture)
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapDouble(recognizer:)))
doubleTapGesture.numberOfTapsRequired = 2
doubleTapGesture.numberOfTouchesRequired = 1
self.scrollView.addGestureRecognizer(doubleTapGesture)
imageView.image = UIImage(named: (revealSong.title) + ".jpg")
view.backgroundColor = revealSong.languageEnum.languageTintColor()
swipeInteractionController = SwipeInteractionController(viewController: self)
self.initAudioPlayer()
self.initAudioVisualizer()
}
override func viewDidAppear(_ animated: Bool) {
NotificationCenter.default.post(name: .pauseBGMusic, object: nil)
self.audioPlayer.play()
startAudioVisualizer()
}
override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.post(name: .playBGMusic, object: nil)
self.audioPlayer.stop()
stopAudioVisualizer()
}
@objc func tapSinlge(recognizer: UITapGestureRecognizer) {
if !self.audioPlayer.isPlaying{
self.audioPlayer.play()
startAudioVisualizer()
}
}
@objc func tapDouble(recognizer: UITapGestureRecognizer) {
if (self.scrollView!.zoomScale == self.scrollView!.minimumZoomScale) {
let center = recognizer.location(in: self.scrollView!)
let size = self.imageView!.image!.size
let zoomRect = CGRect(x:center.x, y:center.y, width:(size.width / 2), height:(size.height / 2))
self.scrollView!.zoom(to: zoomRect, animated: true)
} else {
self.scrollView!.setZoomScale(self.scrollView!.minimumZoomScale, animated: true)
}
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
@IBAction func dismissPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
func initAudioPlayer() {
let urlpath = Bundle.main.path(forResource: song?.title, ofType: "mp3")
let url = URL(fileURLWithPath: urlpath!)
let _: NSError?
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: url)
}
catch let error {
print(error)
}
audioPlayer.isMeteringEnabled = true
self.audioPlayer.delegate = self
audioPlayer.prepareToPlay()
}
func initAudioVisualizer() {
if (self.audioVisualizer == nil){
var frame = visualizerView.frame
frame.origin.x = 0
frame.origin.y = 0
let visualizerColor = UIColor(red: 255.0 / 255.0, green: 84.0 / 255.0, blue: 116.0 / 255.0, alpha: 1.0)
self.audioVisualizer = ATAudioVisualizer(barsNumber: 11, frame: frame, andColor: visualizerColor)
visualizerView.addSubview(audioVisualizer)
}
}
func startAudioVisualizer() {
if visualizerTimer != nil
{
visualizerTimer.invalidate()
visualizerTimer = nil
}
Timer.scheduledTimer(timeInterval: visualizerAnimationDuration, target: self, selector: #selector(visualizerTimerChanged), userInfo: nil, repeats: true)
}
func stopAudioVisualizer()
{
if visualizerTimer != nil
{
visualizerTimer.invalidate()
visualizerTimer = nil
}
audioVisualizer.stop()
}
@objc func visualizerTimerChanged(_ timer:CADisplayLink)
{
audioPlayer.updateMeters()
let ALPHA: Double = 1.05
let averagePower: Double = Double(audioPlayer.averagePower(forChannel: 0))
let averagePowerForChannel: Double = pow(10, (0.05 * averagePower))
lowPassResult = ALPHA * averagePowerForChannel + (1.0 - ALPHA) * lowPassResult
let averagePowerForChannel1: Double = pow(10, (0.05 * Double(audioPlayer.averagePower(forChannel: 1))))
lowPassResults1 = ALPHA * averagePowerForChannel1 + (1.0 - ALPHA) * lowPassResults1
audioVisualizer.animate(withChannel0Level: self._normalizedPowerLevelFromDecibels(audioPlayer.averagePower(forChannel: 0)), andChannel1Level: self._normalizedPowerLevelFromDecibels(audioPlayer.averagePower(forChannel: 1)))
self.updateLabels()
}
func updateLabels() {
self.currentTimeLabel.text! = self.convertSeconds(Float(audioPlayer.currentTime))
self.remainingTimeLabel.text! = self.convertSeconds(Float(audioPlayer.duration) - Float(audioPlayer.currentTime))
}
func convertSeconds(_ secs: Float) -> String {
var currentSecs = secs
if currentSecs < 0.1 {
currentSecs = 0
}
var totalSeconds = Int(secs)
if currentSecs > 0.45 {
totalSeconds += 1
}
let seconds = totalSeconds % 60
let minutes = (totalSeconds / 60) % 60
let hours = totalSeconds / 3600
if hours > 0 {
return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}
return String(format: "%02d:%02d", minutes, seconds)
}
func _normalizedPowerLevelFromDecibels(_ decibels: Float) -> Float {
if decibels < -60.0 || decibels == 0.0 {
return 0.0
}
return powf((powf(10.0, 0.05 * decibels) - powf(10.0, 0.05 * -60.0)) * (1.0 / (1.0 - powf(10.0, 0.05 * -60.0))), 1.0 / 2.0)
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
print("audioPlayerDidFinishPlaying")
playPauseButton.setImage(UIImage(named: "play_")!, for: UIControlState())
playPauseButton.setImage(UIImage(named: "play")!, for: .highlighted)
playPauseButton.isSelected = false
self.currentTimeLabel.text! = "00:00"
self.remainingTimeLabel.text! = self.convertSeconds(Float(audioPlayer.duration))
self.stopAudioVisualizer()
}
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
print("audioPlayerDecodeErrorDidOccur")
playPauseButton.setImage(UIImage(named: "play_")!, for: UIControlState())
playPauseButton.setImage(UIImage(named: "play")!, for: .highlighted)
playPauseButton.isSelected = false
self.currentTimeLabel.text! = "00:00"
self.remainingTimeLabel.text! = "00:00"
self.stopAudioVisualizer()
}
}
|
e53526a8ea9525881578cccd18041046
| 37.318627 | 230 | 0.640143 | false | false | false | false |
rosslebeau/bytefish
|
refs/heads/master
|
App/Models/Link.swift
|
mit
|
1
|
import Vapor
import Foundation
enum LinkError: ErrorProtocol {
case InvalidURL
}
final class Link {
var id: String
var seq: Int64
var slug: String
var originalUrl: NSURL
var shortUrl: NSURL
init(id: String, seq: Int64, slug: String, originalUrl: NSURL, shortUrl: NSURL) {
self.id = id
self.seq = seq
self.slug = slug
self.originalUrl = originalUrl
self.shortUrl = shortUrl
}
}
extension Link: JsonRepresentable {
func makeJson() -> Json {
return Json([
"id": "\(id)",
"slug": "\(slug)",
"originalUrl": "\(originalUrl)",
"shortUrl:": "\(shortUrl)"
])
}
}
extension Link: StringInitializable {
convenience init?(from slug: String) throws {
self.init(fromSlug: slug)
}
}
extension String {
func hasHttpPrefix() -> Bool {
return self.hasPrefix("http://") || self.hasPrefix("https://")
}
func hasScheme() -> Bool {
return range(of: "://") != nil
}
}
|
2c07e49c0f9f818cb55a01e615d7cb74
| 20.306122 | 85 | 0.564176 | false | false | false | false |
infobip/mobile-messaging-sdk-ios
|
refs/heads/master
|
Example/Tests/MobileMessagingTests/CoreDataHelpersTests.swift
|
apache-2.0
|
1
|
//
// CoreDataHelpersTests.swift
// MobileMessagingExample
//
// Created by Andrey K. on 08/09/16.
//
import XCTest
@testable import MobileMessaging
func date(withDay d: Int) -> NSDate {
var comps = DateComponents()
comps.day = d
comps.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
return NSDate(timeIntervalSince1970: comps.date!.timeIntervalSince1970)
}
class CoreDataHelpersTests: MMTestCase {
func testFetchingLimits() {
MMTestCase.startWithCorrectApplicationCode()
let ctx = self.storage.mainThreadManagedObjectContext!
let summaryMessagesNumber = 100
let fetchLimit = 10
let notOlderThanDay = 30
for i in 0..<summaryMessagesNumber {
let newMsg = MessageManagedObject.MM_createEntityInContext(context: ctx)
newMsg.creationDate = date(withDay: i+1) as Date
}
let resultsAll = MessageManagedObject.MM_findAllInContext(ctx)
XCTAssertEqual(resultsAll?.count, summaryMessagesNumber)
let resultsLimited = MessageManagedObject.MM_find(withPredicate: NSPredicate(format: "creationDate < %@", date(withDay: notOlderThanDay)), fetchLimit: fetchLimit, sortedBy: "creationDate", ascending: false, inContext: ctx)
XCTAssertEqual(resultsLimited?.count, fetchLimit)
let mostRecentMsg = resultsLimited?.first!
XCTAssertEqual(mostRecentMsg?.creationDate, date(withDay: notOlderThanDay-1) as Date)
waitForExpectations(timeout: 30, handler: nil)
}
}
|
50dc0954405f43dd0b1387eb2f7b3e6f
| 32.651163 | 224 | 0.754665 | false | true | false | false |
SwiftTools/Switt
|
refs/heads/master
|
Switt/Source/Swift/Module/File/Support/Private/RawDeclarationModifier.swift
|
mit
|
1
|
enum RawDeclarationModifier {
case Access(RawAccessLevelModifier)
case Other(RawDeclarationModifierOther)
}
enum RawDeclarationModifierOther: String {
case Class = "class"
case Convenience = "convenience"
case Dynamic = "dynamic"
case Final = "final"
case Infix = "infix"
case Lazy = "lazy"
case Mutating = "mutating"
case Nonmutating = "nonmutating"
case Optional = "optional"
case Override = "override"
case Postfix = "postfix"
case Prefix = "prefix"
case Required = "required"
case Static = "static"
case Unowned = "unowned"
case UnownedSafe = "unowned(safe)"
case UnownedUnsafe = "unowned(unsafe)"
case Weak = "weak"
}
|
e7d255bd524d8bb5360738574364cdfe
| 27.16 | 43 | 0.669986 | false | false | false | false |
exponent/exponent
|
refs/heads/master
|
ios/versioned/sdk44/ExpoModulesCore/Tests/FunctionSpec.swift
|
bsd-3-clause
|
2
|
import Quick
import Nimble
@testable import ABI44_0_0ExpoModulesCore
class FunctionSpec: QuickSpec {
override func spec() {
let appContext = AppContext()
let functionName = "test function name"
func testFunctionReturning<T: Equatable>(value returnValue: T) {
waitUntil { done in
mockModuleHolder(appContext) {
$0.function(functionName) {
return returnValue
}
}
.call(function: functionName, args: []) { value, error in
expect(value).notTo(beNil())
expect(value).to(beAKindOf(T.self))
expect(value as? T).to(equal(returnValue))
done()
}
}
}
it("is called") {
waitUntil { done in
mockModuleHolder(appContext) {
$0.function(functionName) {
done()
}
}
.call(function: functionName, args: [])
}
}
it("returns bool values") {
testFunctionReturning(value: true)
testFunctionReturning(value: false)
testFunctionReturning(value: [true, false])
}
it("returns int values") {
testFunctionReturning(value: 1234)
testFunctionReturning(value: [2, 1, 3, 7])
}
it("returns double values") {
testFunctionReturning(value: 3.14)
testFunctionReturning(value: [0, 1.1, 2.2])
}
it("returns string values") {
testFunctionReturning(value: "a string")
testFunctionReturning(value: ["expo", "modules", "core"])
}
it("is called with nil value") {
let str: String? = nil
mockModuleHolder(appContext) {
$0.function(functionName) { (a: String?) in
expect(a == nil) == true
}
}
.callSync(function: functionName, args: [str as Any])
}
it("is called with an array of arrays") {
let array: [[String]] = [["expo"]]
mockModuleHolder(appContext) {
$0.function(functionName) { (a: [[String]]) in
expect(a.first!.first) == array.first!.first
}
}
.callSync(function: functionName, args: [array])
}
describe("converting dicts to records") {
struct TestRecord: Record {
@Field var property: String = "expo"
@Field var optionalProperty: Int? = nil
@Field("propertyWithCustomKey") var customKeyProperty: String = "expo"
}
let dict = [
"property": "Hello",
"propertyWithCustomKey": "Expo!"
]
it("converts to simple record when passed as an argument") {
waitUntil { done in
mockModuleHolder(appContext) {
$0.function(functionName) { (a: TestRecord) in
return a.property
}
}
.call(function: functionName, args: [dict]) { value, error in
expect(value).notTo(beNil())
expect(value).to(beAKindOf(String.self))
expect(value).to(be(dict["property"]))
done()
}
}
}
it("converts to record with custom key") {
waitUntil { done in
mockModuleHolder(appContext) {
$0.function(functionName) { (a: TestRecord) in
return a.customKeyProperty
}
}
.call(function: functionName, args: [dict]) { value, error in
expect(value).notTo(beNil())
expect(value).to(beAKindOf(String.self))
expect(value).to(be(dict["propertyWithCustomKey"]))
done()
}
}
}
it("returns the record back") {
waitUntil { done in
mockModuleHolder(appContext) {
$0.function(functionName) { (a: TestRecord) in
return a.toDictionary()
}
}
.call(function: functionName, args: [dict]) { value, error in
expect(value).notTo(beNil())
expect(value).to(beAKindOf(Record.Dict.self))
let valueAsDict = value as! Record.Dict
expect(valueAsDict["property"] as? String).to(equal(dict["property"]))
expect(valueAsDict["propertyWithCustomKey"] as? String).to(equal(dict["propertyWithCustomKey"]))
done()
}
}
}
}
it("throws when called with more arguments than expected") {
waitUntil { done in
mockModuleHolder(appContext) {
$0.function(functionName) { (a: Int) in
return "something"
}
}
// Function expects one argument, let's give it more.
.call(function: functionName, args: [1, 2]) { value, error in
expect(error).notTo(beNil())
expect(error).to(beAKindOf(InvalidArgsNumberError.self))
expect(error?.code).to(equal("ERR_INVALID_ARGS_NUMBER"))
expect(error?.description).to(equal(InvalidArgsNumberError(received: 2, expected: 1).description))
done()
}
}
}
it("throws when called with arguments of incompatible types") {
waitUntil { done in
mockModuleHolder(appContext) {
$0.function(functionName) { (a: String) in
return "something"
}
}
// Function expects a string, let's give it a number.
.call(function: functionName, args: [1]) { value, error in
expect(error).notTo(beNil())
expect(error).to(beAKindOf(Conversions.CastingError<String>.self))
expect(error?.code).to(equal("ERR_CASTING_FAILED"))
expect(error?.description).to(equal(Conversions.CastingError<String>(value: 1).description))
done()
}
}
}
}
}
|
ab6aac5be94f43f958db1fc3b4eb65b1
| 29.78453 | 108 | 0.564609 | false | true | false | false |
Eonil/EditorLegacy
|
refs/heads/trial1
|
Modules/EditorWorkspaceNavigationFeature/EditorWorkspaceNavigationFeature/Internals/Dropping.swift
|
mit
|
1
|
//
// Dropping.swift
// EditorWorkspaceNavigationFeature
//
// Created by Hoon H. on 2015/02/28.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
import AppKit
import EditorCommon
import EditorUIComponents
struct Dropping {
let internals:InternalController
enum Op {
case Copy
case Move
static func determinateOp(info:NSDraggingInfo, currentOutlineView:NSOutlineView) -> Op {
if info.draggingSource() === currentOutlineView {
return Move
}
return Copy
}
}
func processDropping(info:NSDraggingInfo, destinationNode n:WorkspaceNode, destinationChildIndex index:Int, operation op:Op) {
assert(index >= 0)
assert(index <= n.children.count)
let draggingFiles = getDraggingURLs(info)
////
switch op {
case Op.Copy: processCopyDropping(sourceURLs: draggingFiles, destinationNode: n, destinationChildIndex: index, skipCopyingIntoSamePlace: true)
case Op.Move: processMoveDropping(sourceURLs: draggingFiles, destinationNode: n, destinationChildIndex: index)
}
}
/// This just copies the file sequentially as many as possible.
/// Operation will be halted on any error.
///
/// :param: skipCopyingIntoSamePlace
/// If this is set to `true`, this will skip URLs that are same from source and destination locations.
/// Otherwise, same location is incopyable, and will cause an error that will be displayed to user.
func processCopyDropping(sourceURLs us:[NSURL], destinationNode n:WorkspaceNode, destinationChildIndex index:Int, skipCopyingIntoSamePlace:Bool) {
for u in us {
let c = u.lastPathComponent!
let nu = internals.owner!.URLRepresentation!.URLByAppendingPath(n.path)
let u1 = nu.URLByAppendingPathComponent(c)
let k = u.existingAsDirectoryFile ? WorkspaceNodeKind.Folder : WorkspaceNodeKind.File
var e = nil as NSError?
let ok = (skipCopyingIntoSamePlace && wouldBeSame(u, u1)) || NSFileManager.defaultManager().copyItemAtURL(u, toURL: u1, error: &e)
if ok {
let cn = n.createChildNodeAtIndex(index, asKind: k, withName: c)
internals.owner!.outlineView.insertItemsAtIndexes(NSIndexSet(index: index), inParent: n, withAnimation: NSTableViewAnimationOptions.SlideDown)
cn.fillAllDescendantsFromFileSystemWithWorkspaceURL(internals.owner!.URLRepresentation!)
} else {
internals.owner!.presentError(e!)
return
}
}
}
/// This just moves the file sequentially as many as possible.
/// Operation will be halted on any error.
func processMoveDropping(sourceURLs us:[NSURL], destinationNode n:WorkspaceNode, destinationChildIndex index:Int) {
for u in us {
let c = u.lastPathComponent!
let nu = internals.owner!.URLRepresentation!.URLByAppendingPath(n.path)
let u1 = nu.URLByAppendingPathComponent(c)
var e = nil as NSError?
let ok = NSFileManager.defaultManager().moveItemAtURL(u, toURL: u1, error: &e)
if ok {
let n1 = internals.owner.nodeForAbsoluteFileURL(u)!
let n2 = n1.parent!
let i1 = n2.indexOfNode(n1)!
let i2 = (n2 === n && index > i1) ? index - 1 : index
n2.moveChildNode(i1, toNewParentNode: n, atNewIndex: i2)
internals.owner!.outlineView.moveItemAtIndex(i1, inParent: n2, toIndex: i2, inParent: n)
} else {
internals.owner!.presentError(e!)
return
}
}
}
}
private extension WorkspaceNode {
/// Current node must be empty.
/// If current node is not a directory node, this is no-op.
///
/// :param: workspaceURL
/// URL of workspace root node. A connection point to file-system.
///
/// :result: If any error occured and operation unexpectedily quit,
/// this will return an `NSError` that caused it.
/// `nil` for otherwise.
func fillAllDescendantsFromFileSystemWithWorkspaceURL(workspaceURL:NSURL) -> NSError? {
assert(self.children.count == 0)
let u = workspaceURL.URLByAppendingPath(self.path)
if u.existingAsDirectoryFile {
var err = nil as NSError?
let opt = NSDirectoryEnumerationOptions.SkipsHiddenFiles | NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants
let cus = NSFileManager.defaultManager().enumeratorAtURL(u, includingPropertiesForKeys: nil, options: opt, errorHandler: { (issueURL:NSURL!, issueError:NSError!) -> Bool in
err = issueError
return false
})!
for co in cus {
if err != nil {
return err
}
let cu = co as! NSURL
let kind = cu.existingAsDirectoryFile ? WorkspaceNodeKind.Folder : WorkspaceNodeKind.File
let name = cu.lastPathComponent!
let cn = self.createChildNodeAtLastAsKind(kind, withName: name)
let cerr = cn.fillAllDescendantsFromFileSystemWithWorkspaceURL(workspaceURL)
if cerr != nil {
return cerr
}
}
if err != nil {
return err
}
}
return nil
}
}
//private func filterFilesThatAreNotInDirectory(files:[NSURL], directory:NSURL) -> [NSURL] {
// let fs1 = files.filter({ f in
// let f1 = f.URLByDeletingLastPathComponent!
// return f1 != directory
// })
// return fs1
//}
////private func findNameDuplicationsForDragging(source:NSDraggingInfo, destination:WorkspaceNode, workspaceURL:NSURL) -> NameDuplications {
//// let us1 = getDraggingURLs(source)
//// let us2 = destination.children.map({ n in workspaceURL.URLByAppendingPath(n.path) })
//// let dup = findNameDuplications(us1+us2)
////
//// return dup
////}
//private func findNameDuplications(us:[NSURL]) -> NameDuplications {
// var countingTable = [:] as [String:Int]
// for u in us {
// let n = u.lastPathComponent!
// if let c = countingTable[n] {
// countingTable[n] = c+1
// } else {
// countingTable[n] = 1
// }
// }
//
// let us1 =
// us.filter({ u in
// let n = u.lastPathComponent!
// let c = countingTable[n]
// return c > 1
// })
//
// return NameDuplications(URLs: us1)
//}
//
//private func alertNameDuplicationError(duplicatedNames:[String]) {
// let txt = "Some files have duplicated names, and cannot be placed into same directory. Operation cancelled"
// let cmt = nil as String?
// UIDialogues.alertModally(txt, comment: cmt, style: NSAlertStyle.WarningAlertStyle)
//}
//
//private struct NameDuplications {
// var URLs = [] as [NSURL]
//
// var names:[String] {
// get {
// return URLs.map({ u in u.lastPathComponent! })
// }
// }
//}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//private struct URLDuplication {
// var exactDuplications:[NSURL]
// var nameOnlyDuplications:[NSURL]
//}
/// When you comparing two file URLS, two URLs a=may be different by path, but
/// can be equal in file reference level. (inode hard-link) This considers such
/// duplication.
private func wouldBeSame(a:NSURL, b:NSURL) -> Bool {
let u1 = a.URLByDeletingLastPathComponent!
let u2 = b.URLByDeletingLastPathComponent!
precondition(u1.existingAsDirectoryFile)
precondition(u2.existingAsDirectoryFile)
let eq1 = u1.fileReferenceURL() == u2.fileReferenceURL()
let eq2 = a.lastPathComponent! == b.lastPathComponent!
return eq1 && eq2
}
private func getDraggingURLs(info:NSDraggingInfo) -> [NSURL] {
let pb = info.draggingPasteboard()
let ps = pb.propertyListForType(NSFilenamesPboardType) as! [String]
let us = ps.map({ p in NSURL(fileURLWithPath: p)! })
return us
}
|
64af609f020194e49a15c8c8c24b0850
| 21.719626 | 175 | 0.696558 | false | false | false | false |
6ag/BaoKanIOS
|
refs/heads/master
|
BaoKanIOS/Classes/Module/News/View/Comment/JFCommentCell.swift
|
apache-2.0
|
1
|
//
// JFCommentCell.swift
// BaoKanIOS
//
// Created by zhoujianfeng on 16/5/18.
// Copyright © 2016年 六阿哥. All rights reserved.
//
import UIKit
import YYWebImage
protocol JFCommentCellDelegate {
func didTappedStarButton(_ button: UIButton, commentModel: JFCommentModel)
}
class JFCommentCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var starButton: UIButton!
@IBOutlet weak var commentButton: UIButton!
var delegate: JFCommentCellDelegate?
var commentModel: JFCommentModel? {
didSet {
guard let commentModel = commentModel else { return }
avatarImageView.setAvatarImage(urlString: commentModel.userpic, placeholderImage: UIImage(named: "default-portrait"))
usernameLabel.text = commentModel.plnickname
timeLabel.text = commentModel.saytime
contentLabel.text = commentModel.saytext
starButton.setTitle("\(commentModel.zcnum)", for: UIControlState())
}
}
func getCellHeight(_ commentModel: JFCommentModel) -> CGFloat {
self.commentModel = commentModel
layoutIfNeeded()
return contentLabel.frame.maxY + 10
}
/**
点击了赞
*/
@IBAction func didTappedStarButton(_ sender: UIButton) {
delegate?.didTappedStarButton(sender, commentModel: commentModel!)
}
}
|
93eb1edc82074c56abeec9aecf5c9890
| 29.66 | 129 | 0.68167 | false | false | false | false |
vishalvshekkar/Cusp
|
refs/heads/master
|
Cusp/Cusp.swift
|
mit
|
1
|
//
// Cusp.swift
// Cusp
//
// Created by Vishal V. Shekkar on 21/12/15.
// Copyright © 2015 Vishal V. Shekkar. All rights reserved.
//
import UIKit
enum StartQuadrant: Int {
case BottomRight = 1
case BottomLeft
case TopLeft
case TopRight
}
enum Direction: Int {
//When viewing perpendicular to the front of the screen
case ClockWise = 1
case AntiClockwise = 2
}
struct Cusp {
/*
Always returns angle in StartQuadrant.BottomRight quadrant and Direction.Clockwise direction
Use methods in Angle struct to modify these properties and convert angles accordingly
The Angle Returned is nil if 'toLine' does not have one of the points same as 'center'
*/
static func getAngle(center: CGPoint, toLine: Line) -> Angle? {
let baseLine = Line(pointA: center, pointB: CGPoint(x: center.x + 500, y: center.y))
return Cusp.getAngleBetweenLines(baseLine, toLine: toLine)
}
static func getAngleBetweenLines(baseLine: Line, toLine: Line) -> Angle? {
if let originPoint = baseLine.hasCommonPointWith(toLine) {
let otherPoint = toLine.getPoint(originPoint)
let adjacentDistance = originPoint.distanceToPoint(CGPoint(x: otherPoint.x, y: originPoint.y))
let oppositeDistance = otherPoint.distanceToPoint(CGPoint(x: otherPoint.x, y: originPoint.y))
let radianAngleBetweenLines = Radian(radian: atan(oppositeDistance/adjacentDistance))
let angleBetweenLinesWithoutQuadrantManagement = Angle(degree: radianAngleBetweenLines.convertToDegree(), startQuadrant: .BottomRight, direction: .ClockWise)
let angleBetweenLines = Cusp.handleQuadrant(originPoint, pointMakingAngle: otherPoint, angle: angleBetweenLinesWithoutQuadrantManagement)
return angleBetweenLines
}
else {
return nil
}
}
private static func handleQuadrant(origin: CGPoint, pointMakingAngle: CGPoint, angle: Angle) -> Angle {
var angleToReturn = angle
//Bottom Right Quadrant
if pointMakingAngle.x >= origin.x && pointMakingAngle.y >= origin.y {
}
//Bottom Left Quadrant
else if pointMakingAngle.x < origin.x && pointMakingAngle.y >= origin.y {
let degreeAngleInQuadrant = Degree(degree: 180 - angle.degree.degree)
angleToReturn = Angle(degree: degreeAngleInQuadrant, startQuadrant: .BottomRight, direction: .ClockWise)
}
//Top Left Quadrant
else if pointMakingAngle.x < origin.x && pointMakingAngle.y < origin.y {
let degreeAngleInQuadrant = Degree(degree: 180 + angle.degree.degree)
angleToReturn = Angle(degree: degreeAngleInQuadrant, startQuadrant: .BottomRight, direction: .ClockWise)
}
//Top Right Quadrant
else if pointMakingAngle.x >= origin.x && pointMakingAngle.y < origin.y {
let degreeAngleInQuadrant = Degree(degree: 360 - angle.degree.degree)
angleToReturn = Angle(degree: degreeAngleInQuadrant, startQuadrant: .BottomRight, direction: .ClockWise)
}
return angleToReturn
}
}
struct Degree {
var degree: CGFloat
func addDegree(degreeToAdd: CGFloat) -> Degree {
var newDegree = degree + degreeToAdd
if newDegree > 360 {
newDegree = newDegree%360
}
else if newDegree < 0 {
let degreeToSubtract = (newDegree * -1)%360
newDegree = 360 - degreeToSubtract
}
return Degree(degree: newDegree)
}
func convertToRadian() -> Radian {
return Radian(radian: self.degree.degreeToRadian())
}
}
struct Radian {
var radian: CGFloat
func addradian(radianToAdd: CGFloat) -> Radian {
let degree = Degree(degree: radian.radianToDegree())
let degreeToAdd = radianToAdd.radianToDegree()
return degree.addDegree(degreeToAdd).convertToRadian()
}
func convertToDegree() -> Degree {
return Degree(degree: self.radian.radianToDegree())
}
}
struct Angle {
var degree: Degree
var radian: Radian {
get {
return degree.convertToRadian()
}
set {
degree = radian.convertToDegree()
}
}
var startQuadrant: StartQuadrant = .BottomRight
var direction: Direction = .ClockWise
func moveOneQuadrantForward() -> Angle {
var newStartQuadrant: StartQuadrant
let newDegreeAngle = degree.addDegree(-90)
switch startQuadrant {
case .BottomRight:
if direction == .ClockWise {
newStartQuadrant = .BottomLeft
}
else {
newStartQuadrant = .TopRight
}
case .BottomLeft:
if direction == .ClockWise {
newStartQuadrant = .TopLeft
}
else {
newStartQuadrant = .BottomRight
}
case .TopLeft:
if direction == .ClockWise {
newStartQuadrant = .TopRight
}
else {
newStartQuadrant = .BottomLeft
}
case .TopRight:
if direction == .ClockWise {
newStartQuadrant = .BottomRight
}
else {
newStartQuadrant = .TopLeft
}
}
return Angle(degree: newDegreeAngle, startQuadrant: newStartQuadrant, direction: direction)
}
func moveOneQuadrantBackward() -> Angle {
var angleToChangeQuadrant = self
for _ in 1...3 {
angleToChangeQuadrant = angleToChangeQuadrant.moveOneQuadrantForward()
}
return angleToChangeQuadrant
}
func switchDirection() -> Angle {
var newDirection: Direction
let newDegreeAngle = Degree(degree: 360).addDegree(-self.degree.degree)
if self.direction == .ClockWise {
newDirection = .AntiClockwise
}
else {
newDirection = .ClockWise
}
return Angle(degree: newDegreeAngle, startQuadrant: self.startQuadrant, direction: newDirection)
}
}
struct Line {
var pointA: CGPoint
var pointB: CGPoint
func hasCommonPointWith(line: Line) -> CGPoint? {
let lineAPoints = [self.pointA, self.pointB]
let lineBPoints = [line.pointA, line.pointB]
if self.pointA.isEqualTo(self.pointB) || line.pointA.isEqualTo(line.pointB) {
return nil
}
for aPoint in lineAPoints {
for bPoint in lineBPoints {
if aPoint.isEqualTo(bPoint) {
return aPoint
}
}
}
return nil
}
func getPoint(otherThanPoint: CGPoint) -> CGPoint {
if self.pointA.isEqualTo(otherThanPoint) {
return self.pointB
}
else {
return self.pointA
}
}
}
extension CGPoint {
func getDifferenceWithPoint(point: CGPoint) -> CGPoint {
return CGPoint(x: self.x - point.x, y: self.y - point.y)
}
func getPointAfterAddingDifference(difference: CGPoint) -> CGPoint {
return CGPoint(x: self.x + difference.x, y: self.y + difference.y)
}
func distanceToPoint(point: CGPoint) -> CGFloat {
let xSquareDistance = pow((self.x - point.x), 2)
let ySquareDistance = pow((self.y - point.y), 2)
return sqrt(xSquareDistance + ySquareDistance)
}
func isEqualTo(point: CGPoint) -> Bool {
if self.x == point.x && self.y == point.y {
return true
}
else {
return false
}
}
}
extension CGFloat {
func degreeToRadian() -> CGFloat {
return self * CGFloat(M_PI/180)
}
func radianToDegree() -> CGFloat {
return self * CGFloat(180/M_PI)
}
}
|
0f916a45c5205114e5dc18c30ad7e296
| 29.570342 | 169 | 0.595398 | false | false | false | false |
tzef/BmoImageLoader
|
refs/heads/master
|
BmoImageLoader/Classes/BmoImageViewExtension.swift
|
mit
|
1
|
//
// BmoImageViewExtension.swift
// CrazyMikeSwift
//
// Created by LEE ZHE YU on 2016/8/2.
// Copyright © 2016年 B1-Media. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
enum BmoImageCatch {
case catchDefault
case catchNone
}
extension UIImageView {
func bmo_removeProgressAnimation() {
for subView in self.subviews {
if subView.isKind(of: BmoProgressHelpView.self) || subView.isKind(of: BmoProgressImageView.self) {
subView.removeFromSuperview()
}
}
if let subLayers = self.layer.sublayers {
for subLayer in subLayers {
if subLayer.isKind(of: BmoProgressShapeLayer.self) {
subLayer.removeFromSuperlayer()
}
}
}
}
// MARK: - Public
public func bmo_setImageWithURL (
_ URL: Foundation.URL,
style: BmoImageViewProgressStyle,
placeholderImage: UIImage? = nil,
completion: ((DataResponse<UIImage>) -> Void)? = nil) {
let urlRequest = URLRequestWithURL(URL)
guard !isURLRequestURLEqualToActiveRequestURL(urlRequest) else { return }
self.af_cancelImageRequest()
self.bmo_removeProgressAnimation()
let imageDownloader = UIImageView.af_sharedImageDownloader
let imageCache = imageDownloader.imageCache
guard let request = urlRequest.urlRequest else {
return
}
// Use the image from the image cache if it exists
if let image = imageCache?.image(for: request, withIdentifier: nil) {
let response = DataResponse<UIImage>(
request: request,
response: nil,
data: nil,
result: .success(image)
)
completion?(response)
if let runAnimation = self.bmo_runAnimationIfCatched, runAnimation == true {
let animator = generateAnimator(placeholderImage, style: style, urlRequest: request, completion: completion)
animator
.setNewImage(image)
.setCompletionState(.succeed)
.closure()
} else {
self.image = image
}
return
}
// Generate progress animation if the image need to downlaod from internet
let animator = generateAnimator(placeholderImage, style: style, urlRequest: request, completion: completion)
let progrssHandler: ImageDownloader.ProgressHandler = {(progress) in
animator
.setTotalUnitCount(progress.totalUnitCount)
.setCompletedUnitCount(progress.completedUnitCount)
.closure()
}
// Generate a unique download id to check whether the active request has changed while downloading
let downloadID = UUID().uuidString
// Download the image, then run the image transition or completion handler
let requestReceipt = imageDownloader.download(
urlRequest,
receiptID: downloadID,
filter: nil,
progress: progrssHandler,
progressQueue: DispatchQueue.main,
completion: { [weak self] response in
guard let strongSelf = self else { return }
guard
strongSelf.isURLRequestURLEqualToActiveRequestURL(response.request) &&
strongSelf.af_activeRequestReceipt?.receiptID == downloadID
else { return }
if let image = response.result.value {
animator
.setNewImage(image)
.setCompletionState(.succeed)
.closure()
} else {
animator
.setCompletionState(BmoProgressCompletionState.failed(error: response.result.error as NSError?))
.closure()
}
strongSelf.af_activeRequestReceipt = nil
}
)
af_activeRequestReceipt = requestReceipt
}
public func bmo_runAnimationIfCatched(_ run: Bool) {
self.bmo_runAnimationIfCatched = run
}
private func generateAnimator(_ newImage: UIImage?, style: BmoImageViewProgressStyle, urlRequest: URLRequest, completion: ((DataResponse<UIImage>) -> Void)?) -> BmoProgressAnimator {
let animator = BmoImageViewFactory.progressAnimation(self, newImage: newImage, style: style)
animator.setCompletionBlock { (animatorResult) in
var errorMsg = ""
guard let request = urlRequest.urlRequest else {
return
}
if animatorResult.isSuccess {
if let image = animatorResult.value {
let response = DataResponse<UIImage>(
request: request,
response: nil,
data: nil,
result: .success(image)
)
completion?(response)
} else {
errorMsg = "Fetch Image Failed"
}
} else {
if let error = animatorResult.error {
let response = DataResponse<UIImage>(
request: request,
response: nil,
data: nil,
result: .failure(error)
)
completion?(response)
} else {
errorMsg = "Unknown Error"
}
}
if errorMsg != "" {
let userInfo = [NSLocalizedFailureReasonErrorKey: errorMsg]
let response = DataResponse<UIImage>(
request: request,
response: nil,
data: nil,
result: .failure(NSError(domain: request.url?.absoluteString ?? "Unknown Domain", code: NSURLErrorCancelled, userInfo: userInfo))
)
completion?(response)
}
}.closure()
return animator
}
// MARK: - Private - AssociatedKeys
private struct AssociatedKeys {
static var ActiveRequestReceiptKey = "af_UIImageView.ActiveRequestReceipt"
static var BmoProgressAnimatorKey = "bmo_ProgressAnimator"
static var BmoRunAnimationIfCatched = "bmo_runAnimationIfCatched"
}
var af_activeRequestReceipt: RequestReceipt? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.ActiveRequestReceiptKey) as? RequestReceipt
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.ActiveRequestReceiptKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var bmo_runAnimationIfCatched: Bool? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.BmoRunAnimationIfCatched) as? Bool
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.BmoRunAnimationIfCatched, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Private AlamofireImage URL Request Helper Methods
private func URLRequestWithURL(_ URL: Foundation.URL) -> URLRequest {
let mutableURLRequest = NSMutableURLRequest(url: URL)
for mimeType in Request.acceptableImageContentTypes {
mutableURLRequest.addValue(mimeType, forHTTPHeaderField: "Accept")
}
return mutableURLRequest as URLRequest
}
private func isURLRequestURLEqualToActiveRequestURL(_ urlRequest: URLRequestConvertible?) -> Bool {
if
let currentRequestURL = af_activeRequestReceipt?.request.task?.originalRequest?.url,
let requestURL = urlRequest?.urlRequest?.url,
currentRequestURL == requestURL
{
return true
}
return false
}
}
// MARK: - Private AlamofireImage Request Extension
extension Request {
static var acceptableImageContentTypes: Set<String> = [
"image/tiff",
"image/jpeg",
"image/gif",
"image/png",
"image/ico",
"image/x-icon",
"image/bmp",
"image/x-bmp",
"image/x-xbitmap",
"image/x-ms-bmp",
"image/x-win-bitmap"
]
}
|
1c4c16e4205f2a69913555ab33987b31
| 35.851528 | 186 | 0.569262 | false | false | false | false |
UIKit0/AudioKit
|
refs/heads/master
|
AudioKit/Examples/OSX/Swift/AudioKitDemo/AudioKitDemo/ProcessingViewController.swift
|
mit
|
11
|
//
// ProcessingViewController.swift
// AudioKitDemo
//
// Created by Nicholas Arner on 3/1/15.
// Copyright (c) 2015 AudioKit. All rights reserved.
//
class ProcessingViewController: NSViewController {
@IBOutlet var sourceSegmentedControl: NSSegmentedControl!
@IBOutlet var maintainPitchSwitch: NSButton!
@IBOutlet var pitchSlider: NSSlider!
var isPlaying = false
var pitchToMaintain: Float = 1.0
var conv: ConvolutionInstrument!
let audioFilePlayer = AKAudioFilePlayer()
override func viewDidLoad() {
super.viewDidLoad()
conv = ConvolutionInstrument(input: audioFilePlayer.output)
AKOrchestra.addInstrument(audioFilePlayer)
AKOrchestra.addInstrument(conv)
}
@IBAction func start(sender:NSButton) {
if (!isPlaying) {
conv.play()
audioFilePlayer.play()
isPlaying = true
}
}
@IBAction func stop(sender:NSButton) {
if (isPlaying) {
conv.stop()
audioFilePlayer.stop()
isPlaying = false
}
}
@IBAction func wetnessChanged(sender:NSSlider) {
AKTools.setProperty(conv.dryWetBalance, withSlider: sender)
}
@IBAction func impulseResponseChanged(sender:NSSlider) {
AKTools.setProperty(conv.dishWellBalance, withSlider: sender)
}
@IBAction func speedChanged(sender:NSSlider) {
AKTools.setProperty(audioFilePlayer.speed, withSlider: sender)
if (maintainPitchSwitch.state == 1 && fabs(audioFilePlayer.speed.floatValue) > 0.1) {
audioFilePlayer.scaling.floatValue = pitchToMaintain / fabs(audioFilePlayer.speed.floatValue)
AKTools.setSlider(pitchSlider, withProperty: audioFilePlayer.scaling)
}
}
@IBAction func pitchChanged(sender:NSSlider) {
AKTools.setProperty(audioFilePlayer.scaling, withSlider: sender)
}
@IBAction func togglePitchMaintenance(sender:NSButton) {
if sender.state == 1 {
pitchSlider.enabled = false
pitchToMaintain = fabs(audioFilePlayer.speed.floatValue) * audioFilePlayer.scaling.floatValue
} else {
pitchSlider.enabled = true
}
}
@IBAction func fileChanged(sender:NSSegmentedControl) {
audioFilePlayer.sampleMix.floatValue = Float(sender.selectedSegment)
}
}
|
0ef0f3721e147068e2c57ded28094a2a
| 28.5625 | 105 | 0.668076 | false | false | false | false |
SummerHF/SinaPractice
|
refs/heads/master
|
Example/Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel.swift
|
mit
|
2
|
//
// LTMorphingLabel.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2016 Lex Tang, http://lexrus.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files
// (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import UIKit
import QuartzCore
enum LTMorphingPhases: Int {
case Start, Appear, Disappear, Draw, Progress, SkipFrames
}
typealias LTMorphingStartClosure =
(Void) -> Void
typealias LTMorphingEffectClosure =
(Character, index: Int, progress: Float) -> LTCharacterLimbo
typealias LTMorphingDrawingClosure =
LTCharacterLimbo -> Bool
typealias LTMorphingManipulateProgressClosure =
(index: Int, progress: Float, isNewChar: Bool) -> Float
typealias LTMorphingSkipFramesClosure =
(Void) -> Int
@objc public protocol LTMorphingLabelDelegate {
optional func morphingDidStart(label: LTMorphingLabel)
optional func morphingDidComplete(label: LTMorphingLabel)
optional func morphingOnProgress(label: LTMorphingLabel, progress: Float)
}
// MARK: - LTMorphingLabel
@IBDesignable public class LTMorphingLabel: UILabel {
@IBInspectable public var morphingProgress: Float = 0.0
@IBInspectable public var morphingDuration: Float = 0.6
@IBInspectable public var morphingCharacterDelay: Float = 0.026
@IBInspectable public var morphingEnabled: Bool = true
@IBOutlet public weak var delegate: LTMorphingLabelDelegate?
public var morphingEffect: LTMorphingEffect = .Scale
var startClosures = [String: LTMorphingStartClosure]()
var effectClosures = [String: LTMorphingEffectClosure]()
var drawingClosures = [String: LTMorphingDrawingClosure]()
var progressClosures = [String: LTMorphingManipulateProgressClosure]()
var skipFramesClosures = [String: LTMorphingSkipFramesClosure]()
var diffResults = [LTCharacterDiffResult]()
var previousText = ""
var currentFrame = 0
var totalFrames = 0
var totalDelayFrames = 0
var totalWidth: Float = 0.0
var previousRects = [CGRect]()
var newRects = [CGRect]()
var charHeight: CGFloat = 0.0
var skipFramesCount: Int = 0
#if TARGET_INTERFACE_BUILDER
let presentingInIB = true
#else
let presentingInIB = false
#endif
override public var text: String! {
get {
return super.text
}
set {
guard text != newValue else { return }
previousText = text ?? ""
diffResults = previousText >> (newValue ?? "")
super.text = newValue ?? ""
morphingProgress = 0.0
currentFrame = 0
totalFrames = 0
setNeedsLayout()
if !morphingEnabled {
return
}
if presentingInIB {
morphingDuration = 0.01
morphingProgress = 0.5
} else if previousText != text {
displayLink.paused = false
let closureKey = "\(morphingEffect.description)\(LTMorphingPhases.Start)"
if let closure = startClosures[closureKey] {
return closure()
}
delegate?.morphingDidStart?(self)
}
}
}
public override func setNeedsLayout() {
super.setNeedsLayout()
previousRects = rectsOfEachCharacter(previousText, withFont: font)
newRects = rectsOfEachCharacter(text ?? "", withFont: font)
}
override public var bounds: CGRect {
get {
return super.bounds
}
set {
super.bounds = newValue
setNeedsLayout()
}
}
override public var frame: CGRect {
get {
return super.frame
}
set {
super.frame = newValue
setNeedsLayout()
}
}
private lazy var displayLink: CADisplayLink = {
let displayLink = CADisplayLink(
target: self,
selector: #selector(LTMorphingLabel.displayFrameTick))
displayLink.addToRunLoop(
NSRunLoop.currentRunLoop(),
forMode: NSRunLoopCommonModes)
return displayLink
}()
lazy var emitterView: LTEmitterView = {
let emitterView = LTEmitterView(frame: self.bounds)
self.addSubview(emitterView)
return emitterView
}()
}
// MARK: - Animation extension
extension LTMorphingLabel {
func displayFrameTick() {
if displayLink.duration > 0.0 && totalFrames == 0 {
let frameRate = Float(displayLink.duration) / Float(displayLink.frameInterval)
totalFrames = Int(ceil(morphingDuration / frameRate))
let totalDelay = Float((text!).characters.count) * morphingCharacterDelay
totalDelayFrames = Int(ceil(totalDelay / frameRate))
}
currentFrame += 1
if previousText != text && currentFrame < totalFrames + totalDelayFrames + 5 {
morphingProgress += 1.0 / Float(totalFrames)
let closureKey = "\(morphingEffect.description)\(LTMorphingPhases.SkipFrames)"
if let closure = skipFramesClosures[closureKey] {
skipFramesCount += 1
if skipFramesCount > closure() {
skipFramesCount = 0
setNeedsDisplay()
}
} else {
setNeedsDisplay()
}
if let onProgress = delegate?.morphingOnProgress {
onProgress(self, progress: morphingProgress)
}
} else {
displayLink.paused = true
delegate?.morphingDidComplete?(self)
}
}
// Could be enhanced by kerning text:
// http://stackoverflow.com/questions/21443625/core-text-calculate-letter-frame-in-ios
func rectsOfEachCharacter(textToDraw: String, withFont font: UIFont) -> [CGRect] {
var charRects = [CGRect]()
var leftOffset: CGFloat = 0.0
charHeight = "Leg".sizeWithAttributes([NSFontAttributeName: font]).height
let topOffset = (bounds.size.height - charHeight) / 2.0
for (_, char) in textToDraw.characters.enumerate() {
let charSize = String(char).sizeWithAttributes([NSFontAttributeName: font])
charRects.append(
CGRect(
origin: CGPoint(
x: leftOffset,
y: topOffset
),
size: charSize
)
)
leftOffset += charSize.width
}
totalWidth = Float(leftOffset)
var stringLeftOffSet: CGFloat = 0.0
switch textAlignment {
case .Center:
stringLeftOffSet = CGFloat((Float(bounds.size.width) - totalWidth) / 2.0)
case .Right:
stringLeftOffSet = CGFloat(Float(bounds.size.width) - totalWidth)
default:
()
}
var offsetedCharRects = [CGRect]()
for r in charRects {
offsetedCharRects.append(CGRectOffset(r, stringLeftOffSet, 0.0))
}
return offsetedCharRects
}
func limboOfOriginalCharacter(
char: Character,
index: Int,
progress: Float) -> LTCharacterLimbo {
var currentRect = previousRects[index]
let oriX = Float(currentRect.origin.x)
var newX = Float(currentRect.origin.x)
let diffResult = diffResults[index]
var currentFontSize: CGFloat = font.pointSize
var currentAlpha: CGFloat = 1.0
switch diffResult.diffType {
// Move the character that exists in the new text to current position
case .Move, .MoveAndAdd, .Same:
newX = Float(newRects[index + diffResult.moveOffset].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
default:
// Otherwise, remove it
// Override morphing effect with closure in extenstions
if let closure = effectClosures[
"\(morphingEffect.description)\(LTMorphingPhases.Disappear)"
] {
return closure(char, index: index, progress: progress)
} else {
// And scale it by default
let fontEase = CGFloat(
LTEasing.easeOutQuint(
progress, 0, Float(font.pointSize)
)
)
// For emojis
currentFontSize = max(0.0001, font.pointSize - fontEase)
currentAlpha = CGFloat(1.0 - progress)
currentRect = CGRectOffset(previousRects[index], 0,
CGFloat(font.pointSize - currentFontSize))
}
}
return LTCharacterLimbo(
char: char,
rect: currentRect,
alpha: currentAlpha,
size: currentFontSize,
drawingProgress: 0.0
)
}
func limboOfNewCharacter(
char: Character,
index: Int,
progress: Float) -> LTCharacterLimbo {
let currentRect = newRects[index]
var currentFontSize = CGFloat(
LTEasing.easeOutQuint(progress, 0, Float(font.pointSize))
)
if let closure = effectClosures[
"\(morphingEffect.description)\(LTMorphingPhases.Appear)"
] {
return closure(char, index: index, progress: progress)
} else {
currentFontSize = CGFloat(
LTEasing.easeOutQuint(progress, 0.0, Float(font.pointSize))
)
// For emojis
currentFontSize = max(0.0001, currentFontSize)
let yOffset = CGFloat(font.pointSize - currentFontSize)
return LTCharacterLimbo(
char: char,
rect: CGRectOffset(currentRect, 0.0, yOffset),
alpha: CGFloat(morphingProgress),
size: currentFontSize,
drawingProgress: 0.0
)
}
}
func limboOfCharacters() -> [LTCharacterLimbo] {
var limbo = [LTCharacterLimbo]()
// Iterate original characters
for (i, character) in previousText.characters.enumerate() {
var progress: Float = 0.0
if let closure = progressClosures[
"\(morphingEffect.description)\(LTMorphingPhases.Progress)"
] {
progress = closure(index: i, progress: morphingProgress, isNewChar: false)
} else {
progress = min(1.0, max(0.0, morphingProgress + morphingCharacterDelay * Float(i)))
}
let limboOfCharacter = limboOfOriginalCharacter(character, index: i, progress: progress)
limbo.append(limboOfCharacter)
}
// Add new characters
for (i, character) in (text!).characters.enumerate() {
if i >= diffResults.count {
break
}
var progress: Float = 0.0
if let closure = progressClosures[
"\(morphingEffect.description)\(LTMorphingPhases.Progress)"
] {
progress = closure(index: i, progress: morphingProgress, isNewChar: true)
} else {
progress = min(1.0, max(0.0, morphingProgress - morphingCharacterDelay * Float(i)))
}
// Don't draw character that already exists
let diffResult = diffResults[i]
if diffResult.skip {
continue
}
switch diffResult.diffType {
case .MoveAndAdd, .Replace, .Add, .Delete:
let limboOfCharacter = limboOfNewCharacter(character, index: i, progress: progress)
limbo.append(limboOfCharacter)
default:
()
}
}
return limbo
}
}
// MARK: - Drawing extension
extension LTMorphingLabel {
override public func didMoveToSuperview() {
if let s = text {
text = s
}
// Load all morphing effects
for effectName: String in LTMorphingEffect.allValues {
let effectFunc = Selector("\(effectName)Load")
if respondsToSelector(effectFunc) {
performSelector(effectFunc)
}
}
}
override public func drawTextInRect(rect: CGRect) {
if !morphingEnabled {
super.drawTextInRect(rect)
return
}
for charLimbo in limboOfCharacters() {
let charRect = charLimbo.rect
let willAvoidDefaultDrawing: Bool = {
if let closure = drawingClosures[
"\(morphingEffect.description)\(LTMorphingPhases.Draw)"
] {
return closure($0)
}
return false
}(charLimbo)
if !willAvoidDefaultDrawing {
let s = String(charLimbo.char)
s.drawInRect(charRect, withAttributes: [
NSFontAttributeName:
UIFont.init(name: font.fontName, size: charLimbo.size)!,
NSForegroundColorAttributeName:
textColor.colorWithAlphaComponent(charLimbo.alpha)
])
}
}
}
}
|
41ffd23d90e59cc8da03e48cb9d484ba
| 32.970787 | 100 | 0.55732 | false | false | false | false |
GenericDataSource/GenericDataSource
|
refs/heads/master
|
GenericDataSourceTests/XCTest+Extension.swift
|
mit
|
2
|
//
// XCTest+Extension.swift
// GenericDataSource
//
// Created by Mohamed Afifi on 2/28/16.
// Copyright © 2016 mohamede1945. All rights reserved.
//
import XCTest
public func XCTAssertIdentical<T: AnyObject>(_ expression1: @autoclosure () -> T?, _ expression2: @autoclosure () -> T?, _ message: String = "", file: StaticString = #file, line: UInt = #line) {
let object1 = expression1()
let object2 = expression2()
let errorMessage = !message.isEmpty ? message : "Object \(String(describing: object1)) is not identical to \(String(describing: object2))"
XCTAssertTrue(object1 === object2, errorMessage, file: file, line: line)
}
public func XCTAssertIdentical<T: AnyObject>(_ expression1: @autoclosure () -> [T]?, _ expression2: @autoclosure () -> [T]?, _ message: String = "", file: StaticString = #file, line: UInt = #line) {
let object1 = expression1()
let object2 = expression2()
let errorMessage = !message.isEmpty ? message : "Object \(String(describing: object1)) is not identical to \(String(describing: object2))"
XCTAssertEqual(object1?.count, object2?.count, errorMessage, file: file, line: line)
guard let castedObject1 = object1, let castedObject2 = object2 else {
return
}
for i in 0..<castedObject1.count {
XCTAssertTrue(castedObject1[i] === castedObject2[i], errorMessage, file: file, line: line)
}
}
|
f90412069e5a104306533175d131b491
| 38.857143 | 198 | 0.677419 | false | true | false | false |
MichaelSelsky/TheBeatingAtTheGates
|
refs/heads/master
|
BeatingGatesCommon/ControllerComponent.swift
|
mit
|
1
|
//
// ControllerComponent.swift
// The Beating at the Gates
//
// Created by Grant Butler on 1/31/16.
// Copyright © 2016 Grant J. Butler. All rights reserved.
//
import GameplayKit
import SpriteKit
public protocol ControllerComponentDelegate: class {
func performAction(gesture: Gesture)
}
public enum InputButton {
case A
case B
case X
case Y
case DpadUp
case DpadDown
}
extension InputButton {
public var gesture: Gesture {
switch self {
case .A:
return .Skeleton
case .B:
return .Snake
case .X:
return .Spider
case .Y:
return .Attack
case .DpadDown:
return .Down
case .DpadUp:
return .Up
}
}
var isDirectional: Bool {
switch self.gesture {
case .Up, .Down:
return true
default:
return false
}
}
}
public class ControllerComponent: GKComponent {
public let playerIndex: Int
public let laneCount = 5
public private(set) var laneIndex = 2
public weak var delegate: ControllerComponentDelegate?
public init(playerIndex: Int) {
self.playerIndex = playerIndex
super.init()
}
public func handleInput(input: InputButton) {
if input.isDirectional {
if input == .DpadUp {
guard laneIndex < laneCount - 1 else { return }
}
if input == .DpadDown {
guard laneIndex > 0 else { return }
}
guard let entity = entity else { return }
guard let renderComponent = entity.componentForClass(RenderComponent.self) else { return }
var increment = renderComponent.node.calculateAccumulatedFrame().height
if input == .DpadDown {
increment *= -1.0
}
let action = SKAction.moveByX(0, y: increment, duration: 0.5)
renderComponent.node.runAction(action)
if input == .DpadUp {
laneIndex += 1
}
else if input == .DpadDown {
laneIndex -= 1
}
}
else {
delegate?.performAction(input.gesture)
}
}
}
|
e6f07ac182ac5dbb28cb9dc69b8672c7
| 16.290909 | 93 | 0.6551 | false | false | false | false |
qq565999484/RXSwiftDemo
|
refs/heads/master
|
SWIFT_RX_RAC_Demo/SWIFT_RX_RAC_Demo/GeolocationService.swift
|
apache-2.0
|
1
|
//
// GeolocationService.swift
// SWIFT_RX_RAC_Demo
//
// Created by chenyihang on 2017/6/6.
// Copyright © 2017年 chenyihang. All rights reserved.
//
import UIKit
import CoreLocation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class GeolocationService {
//创建单例
static let instance = GeolocationService()
private (set) var authorized: Driver<Bool>
private (set) var location: Driver<CLLocationCoordinate2D>
private let locationManager = CLLocationManager()
private init(){
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
authorized = Observable.deferred {[weak locationManager] in
let status = CLLocationManager.authorizationStatus()
guard let locationManager = locationManager else {
return Observable.just(status)
}
return locationManager
.rx.didChangeAuthorizationStatus
.startWith(status)
}
.asDriver(onErrorJustReturn: CLAuthorizationStatus.notDetermined)
.map{
switch $0{
case .authorizedAlways:
return true
default:
return false
}
}
location = locationManager.rx.didUpdateLocations.asDriver(onErrorJustReturn: [])
.flatMap{
return $0.last.map(Driver.just) ?? Driver.empty()
}
.map{ $0.coordinate}
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
|
8baadd4b8abcd393dabf7222c9f12256
| 24.985507 | 88 | 0.577803 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/NUX/ContentViews/Editor/UnifiedPrologueNotificationsContentView.swift
|
gpl-2.0
|
1
|
import SwiftUI
/// Prologue notifications page contents
struct UnifiedPrologueNotificationsContentView: View {
var body: some View {
GeometryReader { content in
let spacingUnit = content.size.height * 0.06
let notificationIconSize = content.size.height * 0.2
let smallIconSize = content.size.height * 0.175
let largerIconSize = content.size.height * 0.2
let fontSize = content.size.height * 0.055
let notificationFont = Font.system(size: fontSize,
weight: .regular,
design: .default)
VStack {
Spacer()
RoundRectangleView {
HStack {
NotificationIcon(image: Appearance.topImage, size: notificationIconSize)
Text(string: Appearance.topElementTitle)
.font(notificationFont)
.fixedSize(horizontal: false, vertical: true)
.lineLimit(.none)
Spacer()
}
.padding(spacingUnit / 2)
HStack {
CircledIcon(size: smallIconSize,
xOffset: -smallIconSize * 0.7,
yOffset: smallIconSize * 0.7,
iconType: .reply,
backgroundColor: Color(UIColor.muriel(name: .celadon, .shade30)))
Spacer()
CircledIcon(size: smallIconSize,
xOffset: smallIconSize * 0.25,
yOffset: -smallIconSize * 0.7,
iconType: .star,
backgroundColor: Color(UIColor.muriel(name: .yellow, .shade20)))
}
}
.fixedSize(horizontal: false, vertical: true)
Spacer(minLength: spacingUnit / 2)
.fixedSize(horizontal: false, vertical: true)
RoundRectangleView {
HStack {
NotificationIcon(image: Appearance.middleImage, size: notificationIconSize)
Text(string: Appearance.middleElementTitle)
.font(notificationFont)
.fixedSize(horizontal: false, vertical: true)
.lineLimit(.none)
Spacer()
}
.padding(spacingUnit / 2)
}
.fixedSize(horizontal: false, vertical: true)
.offset(x: spacingUnit)
Spacer(minLength: spacingUnit / 2)
.fixedSize(horizontal: false, vertical: true)
RoundRectangleView {
HStack {
NotificationIcon(image: Appearance.bottomImage, size: notificationIconSize)
Text(string: Appearance.bottomElementTitle)
.font(notificationFont)
.fixedSize(horizontal: false, vertical: true)
.lineLimit(.none)
Spacer()
}
.padding(spacingUnit / 2)
HStack {
Spacer()
CircledIcon(size: largerIconSize,
xOffset: largerIconSize * 0.6,
yOffset: largerIconSize * 0.3,
iconType: .comment,
backgroundColor: Color(UIColor.muriel(name: .blue, .shade50)))
}
}
.fixedSize(horizontal: false, vertical: true)
Spacer()
}
}
}
}
private struct NotificationIcon: View {
let image: String
let size: CGFloat
var body: some View {
Image(image)
.resizable()
.frame(width: size, height: size)
.clipShape(Circle())
}
}
private extension UnifiedPrologueNotificationsContentView {
enum Appearance {
static let topImage = "page3Avatar1"
static let middleImage = "page3Avatar2"
static let bottomImage = "page3Avatar3"
static let topElementTitle: String = NSLocalizedString("*Madison Ruiz* liked your post", comment: "Example Like notification displayed in the prologue carousel of the app. Username should be marked with * characters and will be displayed as bold text.")
static let middleElementTitle: String = NSLocalizedString("You received *50 likes* on your site today", comment: "Example Likes notification displayed in the prologue carousel of the app. Number of likes should marked with * characters and will be displayed as bold text.")
static let bottomElementTitle: String = NSLocalizedString("*Johann Brandt* responded to your post", comment: "Example Comment notification displayed in the prologue carousel of the app. Username should be marked with * characters and will be displayed as bold text.")
}
}
|
ed535fd12eee01c3c126bb73e5952a75
| 44.401709 | 281 | 0.504142 | false | false | false | false |
congncif/PagingDataController
|
refs/heads/master
|
Example/Pods/SiFUtilities/Show/UIViewController+Overlay.swift
|
mit
|
2
|
//
// UIViewController+Child.swift
//
//
// Created by FOLY on 2/20/18.
// Copyright © 2018 [iF] Solution. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
public typealias OverlayAnimationBlock = (_ container: UIView, _ overlay: UIView) -> Void
public struct OverlayAnimation {
public static var fade: OverlayAnimationBlock = { container, _ in container.fade() }
}
@objc public func displayContentController(content: UIViewController,
animation: OverlayAnimationBlock = OverlayAnimation.fade) {
addChild(content)
content.willMove(toParent: self)
content.view.frame = view.bounds
content.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(content.view)
animation(view, content.view)
content.didMove(toParent: self)
}
@objc public func hideContentController(content: UIViewController,
animation: OverlayAnimationBlock = OverlayAnimation.fade) {
content.willMove(toParent: nil)
let superView = content.view.superview ?? view!
animation(superView, view)
content.view.removeFromSuperview()
content.removeFromParent()
content.didMove(toParent: nil)
}
@objc public func showOverlay(on viewController: UIViewController,
animation: OverlayAnimationBlock = OverlayAnimation.fade) {
viewController.displayContentController(content: self, animation: animation)
}
@objc public func hideOverlay(animation: OverlayAnimationBlock = OverlayAnimation.fade) {
willMove(toParent: nil)
let superView = view.superview ?? view!
animation(superView, view)
view.removeFromSuperview()
removeFromParent()
didMove(toParent: nil)
}
}
|
98784d974cf1c84129b1f1343f3b4a9e
| 29.967742 | 106 | 0.652083 | false | false | false | false |
fhchina/EasyIOS-Swift
|
refs/heads/master
|
Pod/Classes/Extend/EUI/EUI+ViewProperty.swift
|
mit
|
3
|
//
// EUI+ViewProperty.swift
// medical
//
// Created by zhuchao on 15/5/2.
// Copyright (c) 2015年 zhuchao. All rights reserved.
//
import Foundation
class ViewProperty :NSObject{
var tag:GumboTag?
var tagId = ""
var style = ""
var type = ""
var subTags = Array<ViewProperty>()
var otherProperty = Dictionary<String,AnyObject>()
var tagOut = Array<String>()
var imageMode = UIViewContentMode.ScaleAspectFill
var align = Array<Constrain>()
var margin = Array<Constrain>()
var width:Constrain?
var height:Constrain?
var onTap:TapGestureAction?
var onSwipe:SwipeGestureAction?
var onTapBind:TapGestureAction?
var onSwipeBind:SwipeGestureAction?
var frame:CGRect?
var bind = Dictionary<String,String>()
var contentText:String?
func getView() -> UIView{
if self.tag == nil {
return UIView()
}
return self.view()
}
func view() -> UIView{
var view = UIView()
view.tagProperty = self
self.renderViewStyle(view)
for subTag in self.subTags {
view.addSubview(subTag.getView())
}
return view
}
func renderTag(pelement:OGElement){
self.tagOut += ["id","style","align","margin","type","image-mode","name","width","height","class","ontap","onswipe","ontap-bind","onswipe-bind","frame","reuseid","push","present"]
self.tag = pelement.tag
if let tagId = EUIParse.string(pelement,key:"id") {
self.tagId = tagId
}
if let style = EUIParse.string(pelement,key:"style") {
self.style = "html{" + style + "}"
}
if let theAlign = EUIParse.getStyleProperty(pelement,key: "align") {
self.align = theAlign
}
if let theMargin = EUIParse.getStyleProperty(pelement,key: "margin") {
self.margin = theMargin
}
if let theWidth = EUIParse.string(pelement,key:"width") {
var values = theWidth.trimArray
if values.count == 1 {
if values[0].hasSuffix("%") {
var val = values[0]
val.removeAtIndex(advance(val.startIndex, count(val) - 1))
self.width = Constrain(name:.Width,value: CGFloat(val.floatValue/100))
}else{
self.width = Constrain(name:.Width,value: CGFloat(values[0].trim.floatValue),target:"")
}
}else if values.count >= 2 && values[0].trim.hasSuffix("%"){
var val = values[0].trim
val.removeAtIndex(advance(val.startIndex, count(val) - 1))
self.width = Constrain(name:.Width,value: CGFloat(val.floatValue/100),target:values[1].trim)
}
}
if let theHeight = EUIParse.string(pelement,key:"height") {
var values = theHeight.trimArray
if values.count == 1 {
if values[0].hasSuffix("%") {
var val = values[0]
val.removeAtIndex(advance(val.startIndex, count(val) - 1))
self.height = Constrain(name:.Height,value: CGFloat(val.floatValue/100))
}else{
self.height = Constrain(name:.Height,value: CGFloat(values[0].trim.floatValue),target:"")
}
}else if values.count >= 2 && values[0].trim.hasSuffix("%"){
var val = values[0].trim
val.removeAtIndex(advance(val.startIndex, count(val) - 1))
self.height = Constrain(name:.Height,value: CGFloat(val.floatValue/100),target:values[1].trim)
}
}
if let frame = EUIParse.string(pelement, key: "frame") {
self.frame = CGRectFromString(frame)
}
if let theType = EUIParse.string(pelement,key:"type") {
self.type = theType
}
if let theImageMode = EUIParse.string(pelement,key:"image-mode") {
self.imageMode = ViewProperty.imageModeFormat(theImageMode)
}
if let theGestureAction = EUIParse.string(pelement, key: "ontap") {
var values = theGestureAction.trimArray
if values.count == 1 {
self.onTap = TapGestureAction(selector: values[0])
}else if values.count >= 2 {
self.onTap = TapGestureAction(selector: values[0], tapNumber: values[1])
}
}
if let theGestureAction = EUIParse.string(pelement, key: "onswipe") {
var values = theGestureAction.trimArray
if values.count == 2 {
self.onSwipe = SwipeGestureAction(selector: values[0], direction: values[1])
}else if values.count >= 3 {
self.onSwipe = SwipeGestureAction(selector: values[0], direction: values[1], numberOfTouches: values[2])
}
}
if let theGestureAction = EUIParse.string(pelement, key: "ontap-bind") {
var values = theGestureAction.trimArray
if values.count == 1 {
self.onTapBind = TapGestureAction(selector: values[0])
}else if values.count >= 2 {
self.onTapBind = TapGestureAction(selector: values[0], tapNumber: values[1])
}
}
if let theGestureAction = EUIParse.string(pelement, key: "onswipe-bind") {
var values = theGestureAction.trimArray
if values.count == 2 {
self.onSwipeBind = SwipeGestureAction(selector: values[0], direction: values[1])
}else if values.count >= 3 {
self.onSwipeBind = SwipeGestureAction(selector: values[0], direction: values[1], numberOfTouches: values[2])
}
}
for (key,value) in pelement.attributes {
if contains(self.tagOut, key as! String) == false {
self.otherProperty[key as! String] = value
}
}
self.childLoop(pelement)
}
func renderViewStyle(view:UIView){
view.contentMode = self.imageMode;
if let frame = self.frame {
view.frame = frame
}
for (key,value) in self.otherProperty {
var theValue: AnyObject = value
if let str = value as? String {
if let newValue = self.bindTheKeyPath(str, key: key) {
theValue = newValue
}
if theValue as! String == "" {
continue
}
}
view.attr(key, value)
}
}
func childLoop(pelement:OGElement){
for element in pelement.children {
if element.isKindOfClass(OGElement) {
if let pro = EUIParse.loopElement(element as! OGElement) {
self.subTags.append(pro)
}
}
}
}
class func imageModeFormat(str:String) -> UIViewContentMode{
switch str.trim {
case "ScaleToFill":
return UIViewContentMode.ScaleToFill
case "ScaleAspectFit":
return UIViewContentMode.ScaleAspectFit
case "ScaleAspectFill":
return UIViewContentMode.ScaleAspectFill
case "Redraw":
return UIViewContentMode.Redraw
case "Center":
return UIViewContentMode.Center
case "Top":
return UIViewContentMode.Top
case "Bottom":
return UIViewContentMode.Bottom
case "Left":
return UIViewContentMode.Left
case "Right":
return UIViewContentMode.Right
case "TopLeft":
return UIViewContentMode.TopLeft
case "TopRight":
return UIViewContentMode.TopRight
case "BottomLeft":
return UIViewContentMode.BottomLeft
case "BottomRight":
return UIViewContentMode.BottomRight
default:
return UIViewContentMode.ScaleToFill
}
}
func bindTheKeyPath(str:String,key:String) -> String?{
let value = Regex("\\{\\{(\\w+)\\}\\}").replace(str, withBlock: { (regx) -> String in
var keyPath = regx.subgroupMatchAtIndex(0)?.trim
self.bind[key] = keyPath
return ""
})
return value
}
}
|
41c48ec2ff15628b41380e98b82af5b6
| 34.60084 | 187 | 0.547858 | false | false | false | false |
KhunLam/Swift_weibo
|
refs/heads/master
|
LKSwift_weibo/LKSwift_weibo/Classes/Module/NewFeature/Controller/LKWelcomeViewController.swift
|
apache-2.0
|
1
|
//
// LKWelcomeViewController.swift
// LKSwift_weibo
//
// Created by lamkhun on 15/11/1.
// Copyright © 2015年 lamKhun. All rights reserved.
//
import UIKit
import SDWebImage
class LKWelcomeViewController: UIViewController {
// MARK: - 属性
/// 头像底部约束
private var iconViewBottomCons: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
//添加约束
prepareUI()
//拿到 用户返回的 头像地址 修改iconVIew
if let urlString = LKUserAccount.loadAccount()?.avatar_large {
// 设置用户的头像 --SDW --// 地址 头像 占位图
iconView.lk_setImageWithURL(NSURL(string: urlString), placeholderImage: UIImage(named: "avatar_default_big"))
}
}
///View 出来了 能看见 再做动画
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// 开始动画 修改 底部约束 constant 值 改为头像底部距离 View头160 向上移动 用-
iconViewBottomCons?.constant = -(UIScreen.height() - 160)
//添加动画
UIView.animateWithDuration(1.0, delay: 0.1, usingSpringWithDamping: 0.6, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
// 重新布局
self.view.layoutIfNeeded()
}) { (_) -> Void in
// 动画完成后再添加动画 显示 欢迎归来
UIView.animateWithDuration(1.0, animations: { () -> Void in
self.welcomeLabel.alpha = 1
}, completion: { (_) -> Void in
// 动画 彻底完成 --->进入 下一个界面 (主界面)
(UIApplication.sharedApplication().delegate as! AppDelegate).switchRootController(true)
})
}
}
/// MARK: - 准备UI
private func prepareUI() {
// 添加子控件
view.addSubview(backgorundImageView)
view.addSubview(iconView)
view.addSubview(welcomeLabel)
// 添加约束
backgorundImageView.translatesAutoresizingMaskIntoConstraints = false
iconView.translatesAutoresizingMaskIntoConstraints = false
welcomeLabel.translatesAutoresizingMaskIntoConstraints = false
// 背景
// 填充父控件 VFL
/*
H | 父控件的左边 | 父控件的右边
V | 父控件的顶部 | 父控件的底部
*/
// view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bkg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkg" : backgorundImageView]))
// view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[bkg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkg" : backgorundImageView]))
backgorundImageView.ff_Fill(view)
// 头像
// view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
//
// view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 85))
//
// view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 85))
// 垂直 底部160 ---属性 修改它 就能做动画效果 原来在距离View底部 160的地方
// iconViewBottomCons = NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160)
// view.addConstraint(iconViewBottomCons!)
// 内部: ff_AlignInner, 中间下边: ff_AlignType.BottomCenter
// 返回所有的约束
let cons = iconView.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: view, size: CGSize(width: 85, height: 85), offset: CGPoint(x: 0, y: -160))
// 在所有的约束里面查找某个约束
// iconView: 获取哪个view上面的约束
// constraintsList: iconView上面的所有约束
// attribute: 获取的约束
iconViewBottomCons = iconView.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
// 欢迎归来 ---跟随 头像(在其底部 有一点间距)
// H
// view.addConstraint(NSLayoutConstraint(item: welcomeLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
// view.addConstraint(NSLayoutConstraint(item: welcomeLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16))
welcomeLabel.ff_AlignVertical(type: ff_AlignType.BottomCenter, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 16))
}
// MARK: - 懒加载
/// 背景
private lazy var backgorundImageView: UIImageView = UIImageView(image: UIImage(named: "ad_background"))
/// 头像
private lazy var iconView: UIImageView = {
// 头像 占位图
let imageView = UIImageView(image: UIImage(named: "avatar_default_big"))
// 切成圆
imageView.layer.cornerRadius = 42.5
imageView.layer.masksToBounds = true
return imageView
}()
/// 欢迎归来
private lazy var welcomeLabel: UILabel = {
let label = UILabel()
label.text = "欢迎归来"
label.alpha = 0
return label
}()
}
|
e866ac0f609d1ce5ccd5992a47ff4204
| 40.37594 | 225 | 0.64274 | false | false | false | false |
ancilmarshall/iOS
|
refs/heads/master
|
General/TextViewKeyboardResize/TextViewKeyboardResize/ResizableTextView.swift
|
gpl-2.0
|
1
|
//
// ResizableTextView.swift
// TextViewKeyboardResize
//
// Created by Ancil on 8/4/15.
// Copyright (c) 2015 Ancil Marshall. All rights reserved.
//
import UIKit
/*
NOTE & ACKNOWLEDGEMENT
This great and concise code is taken from GitHub Nikita2k/resizableTextView
code, and converted by me into Swift
*/
class ResizableTextView: UITextView {
override func updateConstraints() {
//println("updateConstraints - Text")
var contentSize = sizeThatFits(CGSizeMake(frame.size.width, CGFloat.max))
if let allConstraints = constraints() as? [NSLayoutConstraint] {
for constraint in allConstraints {
if constraint.firstAttribute == NSLayoutAttribute.Height {
constraint.constant = contentSize.height
break
}
}
}
super.updateConstraints()
}
override func layoutSubviews() {
//println("layoutSubviews - Text")
super.layoutSubviews()
}
}
|
2152f85757509899e3283ea8ad8698a6
| 25.538462 | 81 | 0.619324 | false | false | false | false |
TouchInstinct/LeadKit
|
refs/heads/master
|
TIMoyaNetworking/Playground.playground/Contents.swift
|
apache-2.0
|
1
|
import TIMoyaNetworking
import TINetworking
import Moya
import TIFoundationUtils
import Foundation
// MARK: - Models
enum ErrorType: String, Codable {
// 400
case incorrectLoginAndPasswordGiven = "Incorrect login and password given"
// 401
case invalidJwtToken = "Invalid JWT Token"
// 403
case userAlreadyExists = "User already exists"
// 404
case userNotFound = "User not found"
case sessionNotFound = "Session not found"
// 500
case internalError = "Internal error"
// 503
case cannotSendCode = "Cannot send code"
// Unknown
case unknown = "Unknown error"
init(_ rawValue: String, `default`: ErrorType = .unknown) {
self = ErrorType(rawValue: rawValue) ?? `default`
}
}
struct ErrorResponse: Codable {
let errorCode: ErrorType
let message: String
}
struct LoginRequestBody: Encodable {
var login: String
var password: String
}
struct Profile: Codable {
var name: String
}
enum ApiResponse<ResponseType> {
case ok(ResponseType)
case error(ErrorResponse)
}
// MARK: - Request
extension EndpointRequest {
static func apiV3MobileAuthLoginPassword(body: LoginRequestBody) -> EndpointRequest<LoginRequestBody> {
.init(templatePath: "/api/v3/mobile/auth/login/password/",
method: .post,
body: body,
acceptableStatusCodes: [200, 400, 403, 500],
server: Server(baseUrl: "https://server.base.url"))
}
}
// MARK: - Services
struct JsonCodingService {
let jsonEncoder: JSONEncoder
let jsonDecoder: JSONDecoder
init(dateFormattersReusePool: DateFormattersReusePool) {
self.jsonEncoder = JSONEncoder()
self.jsonDecoder = JSONDecoder()
guard let userInfoKey = CodingUserInfoKey.dateFormattersReusePool else {
assertionFailure("Unable to create dateFormattersReusePool CodingUserInfoKey")
return
}
jsonDecoder.userInfo.updateValue(dateFormattersReusePool, forKey: userInfoKey)
jsonEncoder.userInfo.updateValue(dateFormattersReusePool, forKey: userInfoKey)
}
}
final class ProjectNetworkService: DefaultJsonNetworkService {
init(jsonCodingService: JsonCodingService) {
super.init(session: SessionFactory(timeoutInterval: 60).createSession(),
jsonDecoder: jsonCodingService.jsonDecoder,
jsonEncoder: jsonCodingService.jsonEncoder)
}
func process<B: Encodable, S: Decodable>(request: EndpointRequest<B>,
decodableSuccessStatusCodes: Set<Int>? = nil,
decodableFailureStatusCodes: Set<Int>? = nil) async -> ApiResponse<S> {
await process(request: request,
decodableSuccessStatusCodes: decodableSuccessStatusCodes,
decodableFailureStatusCodes: decodableFailureStatusCodes,
mapSuccess: ApiResponse.ok,
mapFailure: ApiResponse.error,
mapMoyaError: { ApiResponse.error($0.convertToErrorModel()) })
}
}
private extension MoyaError {
func convertToErrorModel() -> ErrorResponse {
switch self {
case .underlying:
return ErrorResponse(errorCode: .unknown,
message: "Нет соединения с сетью 😔 Проверьте соединение с сетью и повторите попытку")
case .objectMapping:
return ErrorResponse(errorCode: .unknown,
message: "Ошибка 😔")
default:
return ErrorResponse(errorCode: .unknown,
message: "Ошибка 😔")
}
}
}
let reusePool = DateFormattersReusePool()
let jsonCodingService = JsonCodingService(dateFormattersReusePool: reusePool)
let networkSerice = ProjectNetworkService(jsonCodingService: jsonCodingService)
let body = LoginRequestBody(login: "qwe", password: "asd")
let profileResponse: ApiResponse<Profile> = await networkSerice.process(request: .apiV3MobileAuthLoginPassword(body: body))
//switch profileResponse {
//case let .ok(profile):
// showUser(name: profile.name)
//case let .error(errorResponse):
// showAlert(with: errorResponse.message)
//}
|
3cfef4a6f2ec24493129259e7247a2ec
| 29.35461 | 123 | 0.656542 | false | false | false | false |
BoutFitness/Concept2-SDK
|
refs/heads/master
|
Pod/Classes/Delegates/CentralManagerDelegate.swift
|
mit
|
1
|
//
// CentralManagerDelegate.swift
// Pods
//
// Created by Jesse Curry on 9/30/15.
// Copyright © 2015 Bout Fitness, LLC. All rights reserved.
//
import Foundation
import CoreBluetooth
final class CentralManagerDelegate:NSObject, CBCentralManagerDelegate {
// MARK: Central Manager Status
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .unknown:
print("[BluetoothManager]state: unknown")
break
case .resetting:
print("[BluetoothManager]state: resetting")
break
case .unsupported:
print("[BluetoothManager]state: not available")
break
case .unauthorized:
print("[BluetoothManager]state: not authorized")
break
case .poweredOff:
print("[BluetoothManager]state: powered off")
break
case .poweredOn:
print("[BluetoothManager]state: powered on")
break
@unknown default:
assertionFailure("Unexpected and unhandled CBCentralManager state")
print("[[BluetoothManager]state: \(String(describing: central.state))]")
}
BluetoothManager.isReady.value = (central.state == .poweredOn)
}
// MARK: Peripheral Discovery
func centralManager(
_ central: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData: [String : Any],
rssi RSSI: NSNumber
) {
print("[BluetoothManager]didDiscoverPeripheral \(peripheral)")
PerformanceMonitorStore.sharedInstance.addPerformanceMonitor(
performanceMonitor: PerformanceMonitor(withPeripheral: peripheral)
)
}
// MARK: Peripheral Connections
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("[BluetoothManager]didConnectPeripheral")
peripheral.discoverServices([
Service.deviceDiscovery.uuid,
Service.deviceInformation.uuid,
Service.control.uuid,
Service.rowing.uuid])
postPerformanceMonitorNotificationForPeripheral(peripheral: peripheral)
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
print("[BluetoothManager]didFailToConnectPeripheral")
postPerformanceMonitorNotificationForPeripheral(peripheral: peripheral)
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("[BluetoothManager]didDisconnectPeripheral")
postPerformanceMonitorNotificationForPeripheral(peripheral: peripheral)
}
// MARK: -
private func postPerformanceMonitorNotificationForPeripheral(peripheral:CBPeripheral) {
let performanceMonitorStore = PerformanceMonitorStore.sharedInstance
if let pm = performanceMonitorStore.performanceMonitorWithPeripheral(peripheral: peripheral) {
pm.updatePeripheralObservers()
NotificationCenter.default.post(
name: PerformanceMonitor.DidUpdateStateNotification,
object: pm
)
}
}
}
|
2dfd0ee7da7c3c932130c695bc29b1d9
| 33.689655 | 119 | 0.722995 | false | false | false | false |
runtastic/Matrioska
|
refs/heads/master
|
Tests/ComponentTests.swift
|
mit
|
1
|
//
// ComponentTests.swift
// MatrioskaTests
//
// Created by Alex Manzella on 09/11/16.
// Copyright © 2016 runtastic. All rights reserved.
//
import XCTest
import Quick
import Nimble
@testable import Matrioska
class ComponentTests: QuickSpec {
override func spec() {
typealias DictMeta = [String: String]
describe("View component") {
it("should build a viewController") {
let component = Component.single(viewBuilder: { _ in UIViewController() }, meta: nil)
expect(component.viewController()).toNot(beNil())
}
it("should pass metadata to the builder") {
var value: ComponentMeta? = nil
_ = Component.single(viewBuilder: { (meta) in
value = meta
return UIViewController()
}, meta: ["foo": "bar"]).viewController()
expect(value as? DictMeta) == ["foo": "bar"]
}
it("should have the correct metadata") {
let component = Component.single(viewBuilder: { _ in UIViewController() },
meta: ["foo": "bar"])
expect(component.meta as? DictMeta) == ["foo": "bar"]
}
}
describe("Wrapper component") {
it("should build a viewController") {
let component = Component.wrapper(viewBuilder: { _ in UIViewController() },
child: randComponent(),
meta: nil)
expect(component.viewController()).toNot(beNil())
}
it("should pass the child to the builder") {
var component: Component? = nil
let viewBuilder: Component.WrapperViewBuilder = { (child, _) in
component = child
return UIViewController()
}
_ = Component.wrapper(viewBuilder: viewBuilder,
child: randComponent(),
meta: nil).viewController()
expect(component).toNot(beNil())
}
it("should pass metadata to the builder") {
var value: ComponentMeta? = nil
let viewBuilder: Component.WrapperViewBuilder = { (_, meta) in
value = meta
return UIViewController()
}
_ = Component.wrapper(viewBuilder: viewBuilder,
child: randComponent(),
meta: ["foo": "bar"]).viewController()
expect(value as? DictMeta) == ["foo": "bar"]
}
it("should have the correct metadata") {
let component = Component.wrapper(viewBuilder: { _ in UIViewController() },
child: randComponent(),
meta: ["foo": "bar"])
expect(component.meta as? DictMeta) == ["foo": "bar"]
}
}
describe("Cluster component") {
it("should build a viewController") {
let component = Component.cluster(viewBuilder: { _ in UIViewController() },
children: [randComponent()],
meta: nil)
expect(component.viewController()).toNot(beNil())
}
it("should pass the children to the builder") {
var components: [Component]? = nil
let viewBuilder: Component.ClusterViewBuilder = { (children, _) in
components = children
return UIViewController()
}
_ = Component.cluster(viewBuilder: viewBuilder,
children: [randComponent()],
meta: nil).viewController()
expect(components).toNot(beNil())
}
it("should pass metadata to the builder") {
var value: ComponentMeta? = nil
let viewBuilder: Component.ClusterViewBuilder = { (_, meta) in
value = meta
return UIViewController()
}
_ = Component.cluster(viewBuilder: viewBuilder,
children: [randComponent()],
meta: ["foo": "bar"]).viewController()
expect(value as? DictMeta) == ["foo": "bar"]
}
it("should have the correct metadata") {
let component = Component.cluster(viewBuilder: { _ in UIViewController() },
children: [randComponent()],
meta: ["foo": "bar"])
expect(component.meta as? DictMeta) == ["foo": "bar"]
}
}
describe("Rule component") {
it("builds his child view controller if it evaluates to true") {
let cluster = Component.cluster(viewBuilder: { _ in UIViewController() },
children: [randComponent()],
meta: nil)
let rule = Rule.not(rule: Rule.simple(evaluator: { false }))
let component = Component.rule(rule: rule, component: cluster)
expect(component.viewController()).toNot(beNil())
}
it("does not build his child view controller if it evaluates to false") {
let cluster = Component.cluster(viewBuilder: { _ in UIViewController() },
children: [randComponent()],
meta: nil)
let rule = Rule.and(rules: [Rule.simple(evaluator: { false }), Rule.simple(evaluator: { true })])
let component = Component.rule(rule: rule, component: cluster)
expect(component.viewController()).to(beNil())
}
it("passes the children to the child's builder if it evaluates to true") {
let rule = Rule.or(rules: [Rule.simple(evaluator: { false }), Rule.simple(evaluator: { true })])
var components: [Component]? = nil
let viewBuilder: Component.ClusterViewBuilder = { (children, _) in
components = children
return UIViewController()
}
let cluster = Component.cluster(viewBuilder: viewBuilder,
children: [randComponent()],
meta: nil)
_ = Component.rule(rule: rule, component: cluster).viewController()
expect(components).toNot(beNil())
}
it("does not pass the children to the child's builder if it evaluates to false") {
let rule = Rule.not(rule: Rule.simple(evaluator: { true }))
var components: [Component]? = nil
let viewBuilder: Component.ClusterViewBuilder = { (children, _) in
components = children
return UIViewController()
}
let cluster = Component.cluster(viewBuilder: viewBuilder,
children: [randComponent()],
meta: nil)
_ = Component.rule(rule: rule, component: cluster).viewController()
expect(components).to(beNil())
}
it("passes metadata to the child's builder if it evaluates to true") {
let rule = Rule.not(rule: Rule.simple(evaluator: { false }))
var value: ComponentMeta? = nil
let viewBuilder: Component.ClusterViewBuilder = { (_, meta) in
value = meta
return UIViewController()
}
let cluster = Component.cluster(viewBuilder: viewBuilder,
children: [randComponent()],
meta: ["foo": "bar"])
_ = Component.rule(rule: rule, component: cluster).viewController()
expect(value as? DictMeta) == ["foo": "bar"]
}
it("does not pass metadata to the child's builder if it evaluates to false") {
let rule = Rule.simple(evaluator: { false })
var value: ComponentMeta? = nil
let viewBuilder: Component.ClusterViewBuilder = { (_, meta) in
value = meta
return UIViewController()
}
let cluster = Component.cluster(viewBuilder: viewBuilder,
children: [randComponent()],
meta: ["one": "two"])
_ = Component.rule(rule: rule, component: cluster).viewController()
expect(value).to(beNil())
}
it("has the correct child's metadata regardless of evaluating to true/false") {
let rule = Rule.simple(evaluator: { false })
let cluster = Component.cluster(viewBuilder: { _ in UIViewController() },
children: [randComponent()],
meta: ["foo": "bar"])
let falseComponent = Component.rule(rule: rule, component: cluster)
let trueComponent = Component.rule(rule: Rule.not(rule: rule), component: cluster)
expect(falseComponent.meta as? DictMeta) == ["foo": "bar"]
expect(trueComponent.meta as? DictMeta) == ["foo": "bar"]
}
}
}
}
private func randComponent() -> Component {
return Component.single(viewBuilder: { _ in UIViewController() }, meta: nil)
}
|
2ffc1e2671b47694af11bc3ab3a798f2
| 45.141026 | 113 | 0.445679 | false | false | false | false |
CaiMiao/CGSSGuide
|
refs/heads/master
|
DereGuide/Toolbox/Colleague/DMComposing/Controller/DMComposingStepOneController.swift
|
mit
|
1
|
//
// DMComposingStepOneController.swift
// DereGuide
//
// Created by zzk on 01/09/2017.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import SwiftyJSON
class DMComposingStepOneController: BaseViewController {
let idLabel = UILabel()
let input = UITextField()
let confirmButton = WideLoadingButton()
override func viewDidLoad() {
super.viewDidLoad()
prepareUI()
if let profile = Profile.fetchSingleObject(in: CoreDataStack.default.viewContext, cacheKey: "MyProfile", configure: { _ in }) {
input.text = profile.gameID
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
input.becomeFirstResponder()
}
private func prepareUI() {
idLabel.font = UIFont.systemFont(ofSize: 24)
view.addSubview(idLabel)
idLabel.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.top.equalTo(160)
}
idLabel.text = NSLocalizedString("输入您的游戏ID", comment: "")
input.font = UIFont.systemFont(ofSize: 20)
input.autocorrectionType = .no
input.autocapitalizationType = .none
input.borderStyle = .none
input.textAlignment = .center
input.keyboardType = .numberPad
input.returnKeyType = .done
input.contentVerticalAlignment = .center
input.delegate = self
view.addSubview(input)
input.snp.makeConstraints { (make) in
make.top.equalTo(idLabel.snp.bottom).offset(20)
make.centerX.equalToSuperview()
make.width.equalTo(240)
}
let line = LineView()
view.addSubview(line)
line.snp.makeConstraints { (make) in
make.top.equalTo(input.snp.bottom)
make.width.equalTo(input)
make.left.equalTo(input)
}
view.addSubview(confirmButton)
confirmButton.setup(normalTitle: NSLocalizedString("下一步", comment: ""), loadingTitle: NSLocalizedString("获取数据中...", comment: ""))
confirmButton.addTarget(self, action: #selector(confirmAction), for: .touchUpInside)
confirmButton.snp.makeConstraints { (make) in
make.left.equalTo(10)
make.right.equalTo(-10)
make.bottom.equalTo(-10)
}
confirmButton.backgroundColor = Color.dance
if UIDevice.current.userInterfaceIdiom == .pad {
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelAction))
}
NotificationCenter.default.addObserver(self, selector: #selector(avoidKeyboard(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(avoidKeyboard(_:)), name: .UIKeyboardWillHide, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func avoidKeyboard(_ notification: Notification) {
guard
// 结束位置
let endFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
// 开始位置
// let beginFrame = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue,
// 持续时间
let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber
else {
return
}
// 时间曲线函数
let curve = UIViewAnimationOptions.init(rawValue: (notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue ?? UIViewAnimationOptions.curveEaseOut.rawValue)
lastKeyboardFrame = endFrame
lastCurve = curve
lastDuration = duration.doubleValue
let frame = view.convert(endFrame, from: nil)
let intersection = frame.intersection(view.frame)
UIView.animate(withDuration: duration.doubleValue, delay: 0, options: [curve], animations: {
self.confirmButton.transform = CGAffineTransform(translationX: 0, y: -intersection.height )
}, completion: nil)
view.setNeedsLayout()
}
private var lastKeyboardFrame: CGRect?
private var lastCurve: UIViewAnimationOptions?
private var lastDuration: TimeInterval?
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let lastFrame = lastKeyboardFrame, let curve = lastCurve, let duration = lastDuration {
let frame = view.convert(lastFrame, from: nil)
let intersection = frame.intersection(view.frame)
UIView.animate(withDuration: duration, delay: 0, options: [curve, .beginFromCurrentState], animations: {
self.confirmButton.transform = CGAffineTransform(translationX: 0, y: -intersection.height )
}, completion: nil)
}
}
@objc func cancelAction() {
dismiss(animated: true, completion: nil)
}
@objc func confirmAction() {
guard input.check(pattern: "^[0-9]{9}$") else {
UIAlertController.showHintMessage(NSLocalizedString("您输入的游戏ID不合法", comment: ""), in: self)
return
}
confirmButton.setLoading(true)
BaseRequest.default.getWith(urlString: "https://deresute.me/\(input.text!)/json") { [weak self] (data, response, error) in
DispatchQueue.main.async {
self?.confirmButton.setLoading(false)
if error != nil {
UIAlertController.showHintMessage(NSLocalizedString("未能获取到正确的数据,请稍后再试", comment: ""), in: self)
} else if response?.statusCode != 200 {
UIAlertController.showHintMessage(NSLocalizedString("您输入的游戏ID不存在", comment: ""), in: self)
} else {
let json = JSON(data!)
let profile = DMProfile(fromJson: json)
let vc = DMComposingStepTwoController()
vc.setup(dmProfile: profile)
self?.navigationController?.pushViewController(vc, animated: true)
}
}
}
}
}
extension DMComposingStepOneController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
confirmAction()
return true
}
}
|
f68a8682a11b5970299d570db5583247
| 36.699422 | 192 | 0.616682 | false | false | false | false |
victorchee/CollectionView
|
refs/heads/master
|
WaterfallColletionView/WaterfallCollectionView/ViewController.swift
|
mit
|
2
|
//
// ViewController.swift
// WaterfallCollectionView
//
// Created by Victor Chee on 16/5/12.
// Copyright © 2016年 VictorChee. All rights reserved.
//
import UIKit
class ViewController: UICollectionViewController, WaterfallFlowLayoutDataSource {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let layout = self.collectionView?.collectionViewLayout as? WaterfallFlowLayout {
layout.dataSource = self
layout.sectionInset = UIEdgeInsets(top: 10, left: 20, bottom: 20, right: 20)
layout.columnCount = 5
layout.lineSpacing = 10
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - WaterfallFlowLayoutDataSource
func collectionView(collectionView: UICollectionView, layout: WaterfallFlowLayout, sizeForItemAtIndexPath: NSIndexPath) -> CGSize {
let width = (collectionView.frame.width - layout.sectionInset.left - layout.sectionInset.right - layout.interitemSpacing * CGFloat(layout.columnCount - 1)) / CGFloat(layout.columnCount)
let height = CGFloat(sizeForItemAtIndexPath.item * 10 + 20)
return CGSize(width: width, height: height)
}
// MARK: - UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 30;
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.label.text = "\(indexPath.section) - \(indexPath.item)"
return cell;
}
}
|
b88248cad8ca32f9b8ceeb937ea3a27d
| 38.392157 | 193 | 0.696864 | false | false | false | false |
sopinetchat/SopinetChat-iOS
|
refs/heads/master
|
Pod/Extensions/SChatUIImage.swift
|
gpl-3.0
|
1
|
//
// SChatUIImage.swift
// Pods
//
// Created by David Moreno Lora on 1/5/16.
//
//
import Foundation
extension UIImage
{
func sChatImageMaskedWithColor(maskColor: UIColor) -> UIImage
{
let imageRect = CGRectMake(0.0, 0.0, self.size.width, self.size.height)
var newImage = UIImage()
UIGraphicsBeginImageContextWithOptions(imageRect.size, false, self.scale)
let context = UIGraphicsGetCurrentContext()
CGContextScaleCTM(context, 1.0, -1.0)
CGContextTranslateCTM(context, 0.0, -(imageRect.size.height))
CGContextClipToMask(context, imageRect, self.CGImage)
CGContextSetFillColorWithColor(context, maskColor.CGColor)
CGContextFillRect(context, imageRect)
newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
static func sChatImageFromBundleWithName(name: String) -> UIImage
{
let bundle = NSBundle.sChatAssetBundle()
let path = bundle.pathForResource(name, ofType: "png", inDirectory: "Images")
return UIImage(contentsOfFile: path!)!
}
static func sChatBubbleRegularImage() -> UIImage
{
return UIImage.sChatImageFromBundleWithName("bubble_regular")
}
static func sChatBubbleRegularTaillessImage() -> UIImage
{
return UIImage.sChatImageFromBundleWithName("bubble_tailless")
}
static func sChatBubbleStrokedImage() -> UIImage
{
return UIImage.sChatImageFromBundleWithName("bubble_stroked")
}
static func sChatBubbleStrokedTaillessImage() -> UIImage
{
return UIImage.sChatImageFromBundleWithName("bubble_stroked_tailless")
}
static func sChatBubbleCompactImage() -> UIImage
{
return UIImage.sChatImageFromBundleWithName("bubble_min")
}
static func sChatBubbleCompactTaillessImage() -> UIImage
{
return UIImage.sChatImageFromBundleWithName("bubble_min_tailless")
}
static func sChatDefaultAccesoryImage() -> UIImage
{
return sChatImageFromBundleWithName("clip")
}
static func sChatDefaultTypingIndicatorImage() -> UIImage
{
return UIImage.sChatImageFromBundleWithName("typing")
}
static func sChatDefaultPlayImage() -> UIImage
{
return UIImage.sChatImageFromBundleWithName("play")
}
}
|
a53bbb52914c045012fc60cad065ee20
| 27.37931 | 85 | 0.663695 | false | false | false | false |
icylydia/PlayWithLeetCode
|
refs/heads/master
|
21. Merge Two Sorted Lists/solution.swift
|
mit
|
1
|
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func mergeTwoLists(l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var bt: BTree? = nil
var i1 = l1
var i2 = l2
if(i1 != nil) {
bt = BTree(i1!.val)
i1 = i1!.next
} else if(i2 != nil) {
bt = BTree(i2!.val)
i2 = i2!.next
}
while(i1 != nil) {
bt?.insert(i1!.val)
i1 = i1!.next
}
while(i2 != nil) {
bt?.insert(i2!.val)
i2 = i2!.next
}
if(bt == nil) {
return nil
} else {
var ret = ListNode(0)
var itr = ret
bt!.traversal {
itr.next = ListNode($0)
itr = itr.next!
}
return ret.next
}
}
}
class BTree {
public var val: Int
public var leftNode: BTree?
public var rightNode: BTree?
public init(_ val: Int) {
self.val = val
self.leftNode = nil
self.rightNode = nil
}
public func insert(val: Int) {
if(val > self.val) {
if(rightNode == nil) {
rightNode = BTree(val)
} else {
rightNode!.insert(val)
}
} else {
if(leftNode == nil) {
leftNode = BTree(val)
} else {
leftNode!.insert(val)
}
}
}
public func traversal(closure: (val: Int) -> ()) {
leftNode?.traversal(closure)
closure(val: val)
rightNode?.traversal(closure)
}
}
|
6738567d7868a0609ef997cf55a51ca2
| 19.202703 | 69 | 0.523427 | false | false | false | false |
spritekitbook/flappybird-swift
|
refs/heads/master
|
Chapter 10/Finish/FloppyBird/FloppyBird/Tutorial.swift
|
apache-2.0
|
5
|
//
// Tutorial.swift
// FloppyBird
//
// Created by Jeremy Novak on 9/26/16.
// Copyright © 2016 SpriteKit Book. All rights reserved.
//
import SpriteKit
class Tutorial:SKSpriteNode {
// MARK: - Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
convenience init() {
let texture = Textures.sharedInstance.textureWith(name: SpriteName.tutorial)
self.init(texture: texture, color: SKColor.white, size: texture.size())
setup()
setupPhysics()
}
// MARK: - Setup
private func setup() {
self.position = kScreenCenter
}
private func setupPhysics() {
}
// MARK: - Update
func update(delta: TimeInterval) {
}
// MARK: - Actions
private func animate() {
}
// MARK: - Tapped
func tapepd() {
let scaleUp = SKAction.scale(to: 1.1, duration: 0.25)
let scaleDown = SKAction.scale(to: 0.0, duration: 0.5)
let completion = SKAction.removeFromParent()
let sequence = SKAction.sequence([scaleUp, scaleDown, completion])
self.run(sequence)
self.run(Sound.sharedInstance.playSound(sound: .pop))
}
}
|
6828f0e67ff2087b4a86241a7c052173
| 22.711864 | 84 | 0.586848 | false | false | false | false |
brave/browser-ios
|
refs/heads/development
|
Utils/DynamicFontHelper.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
let NotificationDynamicFontChanged = Notification.Name("NotificationDynamicFontChanged")
private let iPadFactor: CGFloat = 1.06
private let iPhoneFactor: CGFloat = 0.88
class DynamicFontHelper: NSObject {
static var defaultHelper: DynamicFontHelper {
struct Singleton {
static let instance = DynamicFontHelper()
}
return Singleton.instance
}
override init() {
defaultStandardFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.body).pointSize // 14pt -> 17pt -> 23pt
deviceFontSize = defaultStandardFontSize * (UIDevice.current.userInterfaceIdiom == .pad ? iPadFactor : iPhoneFactor)
defaultMediumFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.footnote).pointSize // 12pt -> 13pt -> 19pt
defaultSmallFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.caption2).pointSize // 11pt -> 11pt -> 17pt
extraSmallFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.caption2).pointSize - 2
super.init()
}
/**
* Starts monitoring the ContentSizeCategory chantes
*/
func startObserving() {
NotificationCenter.default.addObserver(self, selector: #selector(DynamicFontHelper.SELcontentSizeCategoryDidChange(_:)), name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/**
* Device specific
*/
fileprivate var deviceFontSize: CGFloat
var DeviceFontSize: CGFloat {
return deviceFontSize
}
var DeviceFont: UIFont {
return UIFont.systemFont(ofSize: deviceFontSize, weight: UIFont.Weight.medium)
}
var DeviceFontLight: UIFont {
return UIFont.systemFont(ofSize: deviceFontSize, weight: UIFont.Weight.light)
}
var DeviceFontSmall: UIFont {
return UIFont.systemFont(ofSize: deviceFontSize - 1, weight: UIFont.Weight.medium)
}
var DeviceFontSmallLight: UIFont {
return UIFont.systemFont(ofSize: deviceFontSize - 1, weight: UIFont.Weight.light)
}
var DeviceFontSmallHistoryPanel: UIFont {
return UIFont.systemFont(ofSize: deviceFontSize - 3, weight: UIFont.Weight.light)
}
var DeviceFontHistoryPanel: UIFont {
return UIFont.systemFont(ofSize: deviceFontSize)
}
var DeviceFontSmallBold: UIFont {
return UIFont.systemFont(ofSize: deviceFontSize - 1, weight: UIFont.Weight.bold)
}
/**
* ExtraSmall
*/
fileprivate var extraSmallFontSize: CGFloat
var ExtraSmallFontSize: CGFloat {
return extraSmallFontSize
}
var ExtraSmallFont: UIFont {
return UIFont.systemFont(ofSize: extraSmallFontSize, weight: UIFont.Weight.regular)
}
var ExtraSmallFontBold: UIFont {
return UIFont.boldSystemFont(ofSize: extraSmallFontSize)
}
/**
* Small
*/
fileprivate var defaultSmallFontSize: CGFloat
var DefaultSmallFontSize: CGFloat {
return defaultSmallFontSize
}
var DefaultSmallFont: UIFont {
return UIFont.systemFont(ofSize: defaultSmallFontSize, weight: UIFont.Weight.regular)
}
var DefaultSmallFontBold: UIFont {
return UIFont.boldSystemFont(ofSize: defaultSmallFontSize)
}
/**
* Medium
*/
fileprivate var defaultMediumFontSize: CGFloat
var DefaultMediumFontSize: CGFloat {
return defaultMediumFontSize
}
var DefaultMediumFont: UIFont {
return UIFont.systemFont(ofSize: defaultMediumFontSize, weight: UIFont.Weight.regular)
}
var DefaultMediumBoldFont: UIFont {
return UIFont.boldSystemFont(ofSize: defaultMediumFontSize)
}
/**
* Standard
*/
fileprivate var defaultStandardFontSize: CGFloat
var DefaultStandardFontSize: CGFloat {
return defaultStandardFontSize
}
var DefaultStandardFont: UIFont {
return UIFont.systemFont(ofSize: defaultStandardFontSize, weight: UIFont.Weight.regular)
}
var DefaultStandardFontBold: UIFont {
return UIFont.boldSystemFont(ofSize: defaultStandardFontSize)
}
/**
* Reader mode
*/
var ReaderStandardFontSize: CGFloat {
return defaultStandardFontSize - 2
}
var ReaderBigFontSize: CGFloat {
return defaultStandardFontSize + 5
}
/**
* Intro mode
*/
var IntroStandardFontSize: CGFloat {
return defaultStandardFontSize - 1
}
var IntroBigFontSize: CGFloat {
return defaultStandardFontSize + 1
}
func refreshFonts() {
defaultStandardFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.body).pointSize
deviceFontSize = defaultStandardFontSize * (UIDevice.current.userInterfaceIdiom == .pad ? iPadFactor : iPhoneFactor)
defaultMediumFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.footnote).pointSize
defaultSmallFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.caption2).pointSize
extraSmallFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFontTextStyle.caption2).pointSize - 2
}
@objc func SELcontentSizeCategoryDidChange(_ notification: Notification) {
refreshFonts()
let notification = Notification(name: NotificationDynamicFontChanged, object: nil)
NotificationCenter.default.post(notification)
}
}
|
c40f851b4503d8458db28b78adfffc6a
| 34.993789 | 199 | 0.713374 | false | false | false | false |
minimoog/filters
|
refs/heads/master
|
filters/MaskedBlur.swift
|
mit
|
1
|
//
// MaskedBlur.swift
// filters
//
// Created by Toni Jovanoski on 2/15/17.
// Copyright © 2017 Antonie Jovanoski. All rights reserved.
//
import Foundation
import CoreImage
class MaskedBlur: CIFilter {
var inputImage: CIImage?
var inputBlurImage: CIImage?
var inputBlurRadius: CGFloat = 5
override var attributes: [String : Any] {
return [
kCIAttributeFilterDisplayName: "Metal Pixellate",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputBlurImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputBlurRadius": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 5,
kCIAttributeDisplayName: "Blur Radius",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 100,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
let maskedBlur = CIKernel(string:
"kernel vec4 lumaVariableBlur(sampler image, sampler blurImage, float blurRadius) " +
"{ " +
" vec2 d = destCoord(); " +
" vec3 blurPixel = sample(blurImage, samplerCoord(blurImage)).rgb; " +
" float blurAmount = dot(blurPixel, vec3(0.2126, 0.7152, 0.0072)); " +
" float n = 0.0; " +
" int radius = int(blurAmount * blurRadius); " +
" vec3 accumulator = vec3(0.0, 0.0, 0.0); " +
" for (int x = -radius; x <= radius; x++) " +
" { " +
" for (int y = -radius; y <= radius; y++) " +
" { " +
" vec2 workingSpaceCoord = d + vec2(x, y); " +
" vec2 imageSpaceCoord = samplerTransform(image, workingSpaceCoord); " +
" vec3 color = sample(image, imageSpaceCoord).rgb; " +
" accumulator += color; " +
" n += 1.0; " +
" } " +
" } " +
" accumulator /= n; " +
" return vec4(accumulator, 1.0); " +
"} ")
override var outputImage: CIImage? {
guard let inputImage = inputImage,
let inputBlurImage = inputBlurImage else {
return nil
}
let extent = inputImage.extent
let scaledBlurImage = inputBlurImage.applying(CGAffineTransform(scaleX: inputImage.extent.width / inputBlurImage.extent.width, y: inputImage.extent.height / inputBlurImage.extent.height))
let blur = maskedBlur?.apply(withExtent: inputImage.extent,
roiCallback: {
(index, rect) in
if index == 0 {
return rect.insetBy(dx: -self.inputBlurRadius, dy: -self.inputBlurRadius)
} else {
return scaledBlurImage.extent
}
},
arguments: [inputImage, scaledBlurImage, inputBlurRadius])
return blur?.cropping(to: extent)
}
}
|
2c4896f2937db0463494149799b79cc5
| 37.477778 | 195 | 0.513139 | false | false | false | false |
vbudhram/firefox-ios
|
refs/heads/master
|
XCUITests/BrowsingPDFTests.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import XCTest
let PDF_website = ["url": "http://www.pdf995.com/samples/pdf.pdf", "pdfValue": "www.pdf995.com/samples", "urlValue": "www.pdf995.com/", "bookmarkLabel": "http://www.pdf995.com/samples/pdf.pdf", "longUrlValue": "http://www.pdf995.com/"]
class BrowsingPDFTests: BaseTestCase {
func testOpenPDFViewer() {
navigator.openURL(PDF_website["url"]!)
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: PDF_website["pdfValue"]!)
// Swipe Up and Down
let element = app/*@START_MENU_TOKEN@*/.webViews/*[[".otherElements[\"Web content\"].webViews",".otherElements[\"contentView\"].webViews",".webViews"],[[[-1,2],[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.children(matching: .other).element.children(matching: .other).element(boundBy: 0)
element.swipeUp()
waitforExistence(app.staticTexts["2 of 5"])
var i = 0
repeat {
element.swipeDown()
i = i+1
} while (app.staticTexts["1 of 5"].exists == false && i < 10)
waitforExistence(app.staticTexts["1 of 5"])
XCTAssertTrue(app.staticTexts["1 of 5"].exists)
}
func testOpenLinkFromPDF() {
navigator.openURL(PDF_website["url"]!)
waitUntilPageLoad()
// Click on a link on the pdf and check that the website is shown
app/*@START_MENU_TOKEN@*/.webViews/*[[".otherElements[\"Web content\"].webViews",".otherElements[\"contentView\"].webViews",".webViews"],[[[-1,2],[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.children(matching: .other).element.children(matching: .other).element(boundBy: 0).tap()
waitForValueContains(app.textFields["url"], value: PDF_website["pdfValue"]!)
let element = app/*@START_MENU_TOKEN@*/.webViews/*[[".otherElements[\"Web content\"].webViews",".otherElements[\"contentView\"].webViews",".webViews"],[[[-1,2],[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.children(matching: .other).element.children(matching: .other).element(boundBy: 0)
element.children(matching: .other).element(boundBy: 11).tap()
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: PDF_website["urlValue"]!)
XCTAssertTrue(app.webViews.links["Download Now"].exists)
// Go back to pdf view
if iPad() {
app.buttons["URLBarView.backButton"].tap()
} else {
app.buttons["TabToolbar.backButton"].tap()
}
waitForValueContains(app.textFields["url"], value: PDF_website["pdfValue"]!)
}
func testLongPressOnPDFLink() {
navigator.openURL(PDF_website["url"]!)
waitUntilPageLoad()
// Long press on a link on the pdf and check the options shown
app/*@START_MENU_TOKEN@*/.webViews/*[[".otherElements[\"Web content\"].webViews",".otherElements[\"contentView\"].webViews",".webViews"],[[[-1,2],[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.children(matching: .other).element.children(matching: .other).element(boundBy: 0).tap()
waitForValueContains(app.textFields["url"], value: PDF_website["pdfValue"]!)
let element = app/*@START_MENU_TOKEN@*/.webViews/*[[".otherElements[\"Web content\"].webViews",".otherElements[\"contentView\"].webViews",".webViews"],[[[-1,2],[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.children(matching: .other).element.children(matching: .other).element(boundBy: 0)
element.children(matching: .other).element(boundBy: 11).press(forDuration: 1)
waitforExistence(app.sheets.staticTexts[PDF_website["longUrlValue"]!])
waitforExistence(app.sheets.buttons["Open"])
waitforExistence(app.sheets.buttons["Add to Reading List"])
waitforExistence(app.sheets.buttons["Copy"])
waitforExistence(app.sheets.buttons["Share…"])
}
func testLongPressOnPDFLinkToAddToReadingList() {
navigator.openURL(PDF_website["url"]!)
waitUntilPageLoad()
// Long press on a link on the pdf and check the options shown
app/*@START_MENU_TOKEN@*/.webViews/*[[".otherElements[\"Web content\"].webViews",".otherElements[\"contentView\"].webViews",".webViews"],[[[-1,2],[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.children(matching: .other).element.children(matching: .other).element(boundBy: 0).tap()
waitForValueContains(app.textFields["url"], value: PDF_website["pdfValue"]!)
let element = app/*@START_MENU_TOKEN@*/.webViews/*[[".otherElements[\"Web content\"].webViews",".otherElements[\"contentView\"].webViews",".webViews"],[[[-1,2],[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.children(matching: .other).element.children(matching: .other).element(boundBy: 0)
element.children(matching: .other).element(boundBy: 11).press(forDuration: 1)
waitforExistence(app.sheets.staticTexts[PDF_website["longUrlValue"]!])
app.sheets.buttons["Add to Reading List"].tap()
navigator.nowAt(BrowserTab)
// Go to reading list and check that the item is there
navigator.goto(HomePanel_ReadingList)
let savedToReadingList = app.tables["ReadingTable"].cells.staticTexts[PDF_website["longUrlValue"]!]
waitforExistence(savedToReadingList)
XCTAssertTrue(savedToReadingList.exists)
}
func testPinPDFtoTopSites() {
navigator.openURL(PDF_website["url"]!)
waitUntilPageLoad()
navigator.browserPerformAction(.pinToTopSitesOption)
navigator.nowAt(BrowserTab)
navigator.goto(NewTabScreen)
waitforExistence(app.collectionViews.cells["TopSitesCell"].cells["pdf995"])
XCTAssertTrue(app.collectionViews.cells["TopSitesCell"].cells["pdf995"].exists)
// Open pdf from pinned site
let pdfTopSite = app.collectionViews.cells["TopSitesCell"].cells["pdf995"]
pdfTopSite.tap()
waitUntilPageLoad()
waitForValueContains(app.textFields["url"], value: PDF_website["pdfValue"]!)
// Remove pdf pinned site
navigator.performAction(Action.OpenNewTabFromTabTray)
waitforExistence(app.collectionViews.cells["TopSitesCell"].cells["pdf995"])
pdfTopSite.press(forDuration: 1)
waitforExistence(app.tables["Context Menu"].cells["action_unpin"])
app.tables["Context Menu"].cells["action_unpin"].tap()
waitforExistence(app.collectionViews.cells["TopSitesCell"])
XCTAssertTrue(app.collectionViews.cells["TopSitesCell"].cells["pdf995"].exists)
}
func testBookmarkPDF() {
navigator.openURL(PDF_website["url"]!)
navigator.performAction(Action.BookmarkThreeDots)
navigator.goto(HomePanel_Bookmarks)
waitforExistence(app.tables["Bookmarks List"])
XCTAssertTrue(app.tables["Bookmarks List"].staticTexts[PDF_website["bookmarkLabel"]!].exists)
}
}
|
b70601620ae54edeb8c0c6d9402aff52
| 55.422764 | 288 | 0.661816 | false | true | false | false |
laonayt/NewFreshBeen-Swift
|
refs/heads/master
|
WEFreshBeen/Classes/Mine/View/MineCell.swift
|
apache-2.0
|
1
|
//
// MineCell.swift
// WEFreshBeen
//
// Created by WE on 16/6/29.
// Copyright © 2016年 马玮. All rights reserved.
//
import UIKit
class MineCell: UITableViewCell {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
var mineCellModel: MineCellModel? {
didSet {
iconView.image = UIImage(named: (mineCellModel?.imageName)!)
titleLabel.text = mineCellModel?.titleStr
}
}
}
class MineCellModel: NSObject {
var imageName: String?
var titleStr: String?
class func loadMineCelModels() -> [MineCellModel] {
var mines = [MineCellModel]()
let path = NSBundle.mainBundle().pathForResource("MinePlist", ofType: "plist")
let array = NSArray(contentsOfFile: path!)
for dic in array! {
mines.append(MineCellModel.mineModelWithDic(dic as! NSDictionary))
}
return mines
}
class func mineModelWithDic(dic: NSDictionary) -> MineCellModel {
let model = MineCellModel()
model.imageName = dic["iconName"] as! String?
model.titleStr = dic["title"] as! String?
return model
}
}
|
0c6ee425ce58a577e5315745d67a311e
| 24.404255 | 86 | 0.618928 | false | false | false | false |
jhurray/SQLiteModel
|
refs/heads/master
|
SQLiteModel/SQLiteModelError.swift
|
mit
|
1
|
//
// SQLiteModelError.swift
// SQLiteModel
//
// Created by Jeff Hurray on 12/24/15.
// Copyright © 2015 jhurray. All rights reserved.
//
import Foundation
public enum SQLiteModelError : ErrorType {
case InitializeDatabase
case CreateError
case DropError
case InsertError
case UpdateError
case DeleteError
case FetchError
case IndexError
case ScalarQueryError
func errorMessage(type modelType: Any.Type, model: Any?) -> String {
var message: String
switch self {
case .InitializeDatabase:
message = "SQLiteModel Initialize Database Error: "
case .CreateError:
message = "SQLiteModel Create Table Error: "
case .DropError:
message = "SQLiteModel Drop Table Error: "
case .InsertError:
message = "SQLiteModel Insert Error: "
case .UpdateError:
message = "SQLiteModel Update Error: "
case .DeleteError:
message = "SQLiteModel Delete Error: "
case .FetchError:
message = "SQLiteModel Fetch Error: "
case .IndexError:
message = "SQLiteModel Create Index Error: "
case .ScalarQueryError:
message = "SQLiteModel Scalar Query Error: "
}
message += "Type: \(modelType)"
if let instance = model {
message += " Instance: \(instance)"
}
return message
}
func logError(modelType: Any.Type, error: ErrorType, model: Any? = nil) -> Void {
LogManager.log("SQLiteModel: Caught error: \(error)")
LogManager.log(self.errorMessage(type: modelType, model: model))
LogManager.log("SQLiteModel: Throwing error: \(self)")
}
}
|
7c6c0729e220e60d0b4c9dbfb37ee4f6
| 28.65 | 85 | 0.597863 | false | false | false | false |
justindarc/firefox-ios
|
refs/heads/master
|
Client/Frontend/AuthenticationManager/SensitiveViewController.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import SnapKit
import SwiftKeychainWrapper
enum AuthenticationState {
case notAuthenticating
case presenting
}
class SensitiveViewController: UIViewController {
var promptingForTouchID: Bool = false
var backgroundedBlur: UIImageView?
var authState: AuthenticationState = .notAuthenticating
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(checkIfUserRequiresValidation), name: UIApplication.willEnterForegroundNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(checkIfUserRequiresValidation), name: UIApplication.didBecomeActiveNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(blurContents), name: UIApplication.willResignActiveNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(hideLogins), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
@objc func checkIfUserRequiresValidation() {
guard authState != .presenting else {
return
}
presentedViewController?.dismiss(animated: false, completion: nil)
guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo(), authInfo.requiresValidation() else {
removeBackgroundedBlur()
return
}
promptingForTouchID = true
AppAuthenticator.presentAuthenticationUsingInfo(authInfo,
touchIDReason: AuthenticationStrings.loginsTouchReason,
success: {
self.promptingForTouchID = false
self.authState = .notAuthenticating
self.removeBackgroundedBlur()
},
cancel: {
self.promptingForTouchID = false
self.authState = .notAuthenticating
_ = self.navigationController?.popToRootViewController(animated: true)
},
fallback: {
self.promptingForTouchID = false
AppAuthenticator.presentPasscodeAuthentication(self.navigationController).uponQueue(.main) { isOk in
if isOk {
self.removeBackgroundedBlur()
self.navigationController?.dismiss(animated: true, completion: nil)
self.authState = .notAuthenticating
} else {
_ = self.navigationController?.popToRootViewController(animated: false)
self.authState = .notAuthenticating
}
}
}
)
authState = .presenting
}
@objc func hideLogins() {
_ = self.navigationController?.popToRootViewController(animated: true)
}
@objc func blurContents() {
if backgroundedBlur == nil {
backgroundedBlur = addBlurredContent()
}
}
func removeBackgroundedBlur() {
if !promptingForTouchID {
backgroundedBlur?.removeFromSuperview()
backgroundedBlur = nil
}
}
fileprivate func addBlurredContent() -> UIImageView? {
guard let snapshot = view.screenshot() else {
return nil
}
let blurredSnapshot = snapshot.applyBlur(withRadius: 10, blurType: BOXFILTER, tintColor: UIColor(white: 1, alpha: 0.3), saturationDeltaFactor: 1.8, maskImage: nil)
let blurView = UIImageView(image: blurredSnapshot)
view.addSubview(blurView)
blurView.snp.makeConstraints { $0.edges.equalTo(self.view) }
view.layoutIfNeeded()
return blurView
}
}
|
8e2ac1769bb6a80fc017f96ee2cac2c1
| 37.95283 | 171 | 0.653427 | false | false | false | false |
getwagit/Baya
|
refs/heads/master
|
Baya/layouts/BayaConditionalLayout.swift
|
mit
|
1
|
//
// Copyright (c) 2017 wag it GmbH.
// License: MIT
//
import Foundation
/**
A layout that skips the child element if a certain condition is met.
In that case, size and margins are zero.
Mirrors bayaModes but wraps the margins (in order to zero them out if the condition is not met)
*/
public struct BayaConditionalLayout: BayaLayout {
public var bayaMargins = UIEdgeInsets.zero
public var frame: CGRect
public var bayaModes: BayaLayoutOptions.Modes {
return element.bayaModes
}
private var element: BayaLayoutable
private var measure: CGSize?
private let condition: () -> Bool
init(
element: BayaLayoutable,
condition: @escaping () -> Bool) {
self.element = element
self.condition = condition
self.frame = CGRect()
}
public mutating func layoutWith(frame: CGRect) {
self.frame = frame
guard condition() else {
return
}
let size = calculateSizeForLayout(forChild: &element, cachedSize: measure, ownSize: frame.size)
let margins = element.bayaMargins
element.layoutWith(frame: CGRect(
x: frame.minX + margins.left,
y: frame.minY + margins.top,
width: size.width,
height: size.height))
}
public mutating func sizeThatFits(_ size: CGSize) -> CGSize {
guard condition() else {
return CGSize()
}
measure = element.sizeThatFitsWithMargins(size)
return measure?.addMargins(ofElement: element) ?? CGSize()
}
}
public extension BayaLayoutable {
/// The child element is measured and positioned only if the condition is met.
/// Wraps the child element and its margins.
/// Mirrors the modes.
/// - parameter condition: Should return `true` if the layout should be executed.
/// - returns: A `BayaConditionalLayout`.
func layoutIf(condition: @escaping () -> Bool) -> BayaConditionalLayout {
return BayaConditionalLayout(
element: self, condition: condition)
}
}
|
1b7b72fc1f660356efafedf97403cec7
| 31.375 | 103 | 0.642375 | false | false | false | false |
TrustWallet/trust-wallet-ios
|
refs/heads/master
|
Trust/Export/Coordinators/ExportPhraseCoordinator.swift
|
gpl-3.0
|
1
|
// Copyright DApps Platform Inc. All rights reserved.
import Foundation
import TrustKeystore
import TrustCore
final class ExportPhraseCoordinator: RootCoordinator {
let keystore: Keystore
let account: Wallet
let words: [String]
var coordinators: [Coordinator] = []
var rootViewController: UIViewController {
return passphraseViewController
}
var passphraseViewController: PassphraseViewController {
let controller = PassphraseViewController(
account: account,
words: words
)
controller.delegate = self
controller.title = viewModel.title
return controller
}
private lazy var viewModel: ExportPhraseViewModel = {
return .init(keystore: keystore, account: account)
}()
init(
keystore: Keystore,
account: Wallet,
words: [String]
) {
self.keystore = keystore
self.account = account
self.words = words
}
}
extension ExportPhraseCoordinator: PassphraseViewControllerDelegate {
func didPressVerify(in controller: PassphraseViewController, with account: Wallet, words: [String]) {
// Missing functionality
}
}
|
8bfe7028049225fa40a596163f68615d
| 26.318182 | 105 | 0.671381 | false | false | false | false |
manish-1988/MPAudioRecorder
|
refs/heads/master
|
AudioFunctions/SplitAudioFile.swift
|
mit
|
1
|
//
// SplitAudioFile.swift
// AudioFunctions
//
// Created by iDevelopers on 6/19/17.
// Copyright © 2017 iDevelopers. All rights reserved.
//
import UIKit
import AVFoundation
class SplitAudioFile: UIViewController, AVAudioPlayerDelegate {
@IBOutlet weak var label_lengthFAudio: UILabel!
@IBOutlet weak var txt_start: UITextField!
@IBOutlet weak var txt_end: UITextField!
@IBOutlet weak var btn_Split: UIButton!
@IBOutlet weak var btn_Play: UIButton!
@IBOutlet weak var audioSlider: UISlider!
@IBOutlet weak var lblStart: UILabel!
@IBOutlet weak var lblEnd: UILabel!
var audioFileOutput:URL!
var fileURL:URL!
var audioFile:AnyObject!
var filecount:Int = 0
var audioPlayer : AVAudioPlayer!
override func viewDidLoad() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func viewWillAppear(_ animated: Bool) {
self.audioPlayer = try! AVAudioPlayer(contentsOf: fileURL!)
label_lengthFAudio.text = "\(self.audioPlayer.duration)"
lblEnd.text = "\(audioPlayer.duration)"
}
@IBAction func click_Split(_ sender: Any) {
let fileManager = FileManager.default
let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = urls[0] as NSURL
audioFileOutput = documentDirectory.appendingPathComponent("abcdf.m4a")
print("\(audioFileOutput!)")
do {
try FileManager.default.removeItem(at: audioFileOutput)
} catch let error as NSError {
print(error.debugDescription)
}
let asset = AVAsset.init(url: fileURL)
let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A)
let startTrimTime: Float = Float(txt_start.text!)!
let endTrimTime: Float = Float(txt_end.text!)!
let startTime: CMTime = CMTimeMake(value: Int64(Int(floor(startTrimTime * 100))), timescale: 100)
let stopTime: CMTime = CMTimeMake(value: Int64(Int(ceil(endTrimTime * 100))), timescale: 100)
let exportTimeRange: CMTimeRange = CMTimeRangeFromTimeToTime(start: startTime, end: stopTime)
exportSession?.outputURL = audioFileOutput
exportSession?.outputFileType = .m4a
exportSession?.timeRange = exportTimeRange
exportSession?.exportAsynchronously(completionHandler: {() -> Void in
if AVAssetExportSession.Status.completed == exportSession?.status {
print("Success!")
self.audioPlayer = try! AVAudioPlayer(contentsOf: self.audioFileOutput)
self.lblEnd.text = "\(self.audioPlayer.duration)"
let alert = UIAlertController(title: "Alert", message: "File Trimmed Successfuly. Click on play to check", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
else if AVAssetExportSession.Status.failed == exportSession?.status {
print("failed")
}
})
}
@IBAction func click_Play(_ sender: Any) {
self.audioPlayer.prepareToPlay()
self.audioPlayer.delegate = self
self.audioPlayer.play()
audioSlider.maximumValue = Float(audioPlayer.duration)
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(playerTimeIntervalSplitController), userInfo: nil, repeats: true)
}
@objc func playerTimeIntervalSplitController()
{
audioSlider.value = Float(audioPlayer.currentTime)
lblStart.text = "\(audioSlider.value)"
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
print(flag)
}
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?){
print(error.debugDescription)
}
internal func audioPlayerBeginInterruption(_ player: AVAudioPlayer){
print(player.debugDescription)
}
}
|
fcf52356c242e5a2f00b785a1f340537
| 36.638655 | 146 | 0.654387 | false | false | false | false |
Isuru-Nanayakkara/Swift-Extensions
|
refs/heads/master
|
Swift+Extensions/Swift+Extensions/UIKit/UISearchBar+Extensions.swift
|
mit
|
1
|
//
// UISearchBar+Extensions.swift
// Swift+Extensions
//
// Created by Isuru Nanayakkara on 7/26/19.
// Copyright © 2019 BitInvent. All rights reserved.
//
import UIKit
extension UISearchBar {
func setPlaceholderTextColor(_ color: UIColor) {
guard let textFieldInsideSearchBar = value(forKey: "searchField") as? UITextField else { return }
guard let textFieldInsideSearchBarLabel = textFieldInsideSearchBar.value(forKey: "placeholderLabel") as? UILabel else { return }
textFieldInsideSearchBarLabel.textColor = color
}
func setTextColor(_ color: UIColor) {
guard let textFieldInsideSearchBar = value(forKey: "searchField") as? UITextField else { return }
textFieldInsideSearchBar.textColor = color
}
}
|
5743015ee40efe0633edd4a46473e2f5
| 34 | 136 | 0.716883 | false | false | false | false |
attaswift/BigInt
|
refs/heads/master
|
Carthage/Checkouts/BigInt/sources/Floating Point Conversion.swift
|
mit
|
5
|
//
// Floating Point Conversion.swift
// BigInt
//
// Created by Károly Lőrentey on 2017-08-11.
// Copyright © 2016-2017 Károly Lőrentey.
//
extension BigUInt {
public init?<T: BinaryFloatingPoint>(exactly source: T) {
guard source.isFinite else { return nil }
guard !source.isZero else { self = 0; return }
guard source.sign == .plus else { return nil }
let value = source.rounded(.towardZero)
guard value == source else { return nil }
assert(value.floatingPointClass == .positiveNormal)
assert(value.exponent >= 0)
let significand = value.significandBitPattern
self = (BigUInt(1) << value.exponent) + BigUInt(significand) >> (T.significandBitCount - Int(value.exponent))
}
public init<T: BinaryFloatingPoint>(_ source: T) {
self.init(exactly: source.rounded(.towardZero))!
}
}
extension BigInt {
public init?<T: BinaryFloatingPoint>(exactly source: T) {
switch source.sign{
case .plus:
guard let magnitude = BigUInt(exactly: source) else { return nil }
self = BigInt(sign: .plus, magnitude: magnitude)
case .minus:
guard let magnitude = BigUInt(exactly: -source) else { return nil }
self = BigInt(sign: .minus, magnitude: magnitude)
}
}
public init<T: BinaryFloatingPoint>(_ source: T) {
self.init(exactly: source.rounded(.towardZero))!
}
}
extension BinaryFloatingPoint where RawExponent: FixedWidthInteger, RawSignificand: FixedWidthInteger {
public init(_ value: BigInt) {
guard !value.isZero else { self = 0; return }
let v = value.magnitude
let bitWidth = v.bitWidth
var exponent = bitWidth - 1
let shift = bitWidth - Self.significandBitCount - 1
var significand = value.magnitude >> (shift - 1)
if significand[0] & 3 == 3 { // Handle rounding
significand >>= 1
significand += 1
if significand.trailingZeroBitCount >= Self.significandBitCount {
exponent += 1
}
}
else {
significand >>= 1
}
let bias = 1 << (Self.exponentBitCount - 1) - 1
guard exponent <= bias else { self = Self.infinity; return }
significand &= 1 << Self.significandBitCount - 1
self = Self.init(sign: value.sign == .plus ? .plus : .minus,
exponentBitPattern: RawExponent(bias + exponent),
significandBitPattern: RawSignificand(significand))
}
public init(_ value: BigUInt) {
self.init(BigInt(sign: .plus, magnitude: value))
}
}
|
75a0276c81fe0d30a96cd314ea8ee642
| 35.671233 | 117 | 0.602914 | false | false | false | false |
cache0928/CCWeibo
|
refs/heads/master
|
CCWeibo/CCWeibo/Classes/Discover/DiscoverTableViewController.swift
|
mit
|
1
|
//
// DiscoverTableViewController.swift
// CCWeibo
//
// Created by 徐才超 on 16/2/2.
// Copyright © 2016年 徐才超. All rights reserved.
//
import UIKit
class DiscoverTableViewController: BaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
if !isLogin {
(view as! VisitorView).setupViews(false, iconName: "visitordiscover_image_message", info: "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过")
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
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
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
58064ebbf40543f8f77209621dea16eb
| 34.030928 | 157 | 0.684815 | false | false | false | false |
AloneMonkey/RxSwiftStudy
|
refs/heads/master
|
RxSwiftMoya/RxSwiftMoya/Controller/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// RxSwiftMoya
//
// Created by monkey on 2017/3/29.
// Copyright © 2017年 Coder. All rights reserved.
//
import UIKit
import RxSwift
import Moya_ObjectMapper
class ViewController: UIViewController {
@IBOutlet weak var click: UIButton!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
UserProvider
.request(.list(0, 10))
.mapResult(User.self)
.subscribe{
event in
switch event{
case .next(let users):
for user in users{
print("\(user.name) \(user.age)")
}
case .error(let error):
var message = "出错了!"
if let amerror = error as? AMError, let msg = amerror.message{
message = msg
}
print(message)
default:
break
}
}
.disposed(by: disposeBag)
}
}
|
4bd0cb4c9b3447db231604cd1225c2bf
| 23.555556 | 82 | 0.462443 | false | false | false | false |
CD1212/Doughnut
|
refs/heads/master
|
Pods/FeedKit/Sources/FeedKit/Models/JSON/JSONFeedAttachment.swift
|
gpl-3.0
|
2
|
//
// JSONFeedAttachment.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// 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
/// Describes optional attatchments of a JSON Feed item.
public class JSONFeedAttachment {
/// (required, string) specifies the location of the attachment.
public var url: String?
/// (required, string) specifies the type of the attachment, such as
/// "audio/mpeg."
public var mimeType: String?
/// (optional, string) is a name for the attachment. Important: if there are
/// multiple attachments, and two or more have the exact same title (when title
/// is present), then they are considered as alternate representations of the
/// same thing. In this way a podcaster, for instance, might provide an audio
/// recording in different formats.
public var title: String?
/// (optional, number) specifies how large the file is.
public var sizeInBytes: Int?
/// (optional, number) specifies how long it takes to listen to or watch, when
/// played at normal speed.
public var durationInSeconds: TimeInterval?
}
// MARK: - Initializers
extension JSONFeedAttachment {
convenience init?(dictionary: [String : Any?]) {
if dictionary.isEmpty {
return nil
}
self.init()
self.title = dictionary["title"] as? String
self.url = dictionary["url"] as? String
self.mimeType = dictionary["mime_type"] as? String
self.sizeInBytes = dictionary["size_in_bytes"] as? Int
self.durationInSeconds = dictionary["duration_in_seconds"] as? TimeInterval
}
}
// MARK: - Equatable
extension JSONFeedAttachment: Equatable {
public static func ==(lhs: JSONFeedAttachment, rhs: JSONFeedAttachment) -> Bool {
return
lhs.title == rhs.title &&
lhs.url == rhs.url &&
lhs.mimeType == rhs.mimeType &&
lhs.sizeInBytes == rhs.sizeInBytes &&
lhs.durationInSeconds == rhs.durationInSeconds
}
}
|
c31e2edea18f7c1c0bcaac16f469e673
| 35.443182 | 85 | 0.662925 | false | false | false | false |
open-telemetry/opentelemetry-swift
|
refs/heads/main
|
Sources/OpenTelemetrySdk/Metrics/Export/Metric.swift
|
apache-2.0
|
1
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
public struct Metric {
public private(set) var namespace: String
public private(set) var resource: Resource
public private(set) var instrumentationScopeInfo : InstrumentationScopeInfo
public private(set) var name: String
public private(set) var description: String
public private(set) var aggregationType: AggregationType
public internal(set) var data = [MetricData]()
init(namespace: String, name: String, desc: String, type: AggregationType, resource: Resource, instrumentationScopeInfo: InstrumentationScopeInfo) {
self.namespace = namespace
self.instrumentationScopeInfo = instrumentationScopeInfo
self.name = name
description = desc
aggregationType = type
self.resource = resource
}
}
extension Metric: Equatable {
private static func isEqual<T: Equatable>(type: T.Type, lhs: Any, rhs: Any) -> Bool {
guard let lhs = lhs as? T, let rhs = rhs as? T else { return false }
return lhs == rhs
}
public static func == (lhs: Metric, rhs: Metric) -> Bool {
if lhs.namespace == rhs.namespace &&
lhs.resource == rhs.resource &&
lhs.instrumentationScopeInfo == rhs.instrumentationScopeInfo &&
lhs.name == rhs.name &&
lhs.description == rhs.description &&
lhs.aggregationType == rhs.aggregationType {
switch lhs.aggregationType {
case .doubleGauge:
return isEqual(type: [SumData<Double>].self, lhs: lhs.data, rhs: rhs.data)
case .intGauge:
return isEqual(type: [SumData<Int>].self, lhs: lhs.data, rhs: rhs.data)
case .doubleSum:
return isEqual(type: [SumData<Double>].self, lhs: lhs.data, rhs: rhs.data)
case .doubleSummary:
return isEqual(type: [SummaryData<Double>].self, lhs: lhs.data, rhs: rhs.data)
case .intSum:
return isEqual(type: [SumData<Int>].self, lhs: lhs.data, rhs: rhs.data)
case .intSummary:
return isEqual(type: [SummaryData<Int>].self, lhs: lhs.data, rhs: rhs.data)
case .doubleHistogram:
return isEqual(type: [HistogramData<Double>].self, lhs: lhs.data, rhs: rhs.data)
case .intHistogram:
return isEqual(type: [HistogramData<Int>].self, lhs: lhs.data, rhs: rhs.data)
}
}
return false
}
}
// explicit encoding & decoding implementation is needed in order to correctly
// deduce the concrete type of `Metric.data`.
extension Metric: Codable {
enum CodingKeys: String, CodingKey {
case namespace
case resource
case instrumentationScopeInfo
case name
case description
case aggregationType
case data
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let namespace = try container.decode(String.self, forKey: .namespace)
let resource = try container.decode(Resource.self, forKey: .resource)
let instrumentationScopeInfo = try container.decode(InstrumentationScopeInfo.self, forKey: .instrumentationScopeInfo)
let name = try container.decode(String.self, forKey: .name)
let description = try container.decode(String.self, forKey: .description)
let aggregationType = try container.decode(AggregationType.self, forKey: .aggregationType)
self.init(namespace: namespace, name: name, desc: description, type: aggregationType, resource: resource, instrumentationScopeInfo: instrumentationScopeInfo)
switch aggregationType {
case .doubleGauge:
data = try container.decode([SumData<Double>].self, forKey: .data)
case .intGauge:
data = try container.decode([SumData<Int>].self, forKey: .data)
case .doubleSum:
data = try container.decode([SumData<Double>].self, forKey: .data)
case .doubleSummary:
data = try container.decode([SummaryData<Double>].self, forKey: .data)
case .intSum:
data = try container.decode([SumData<Int>].self, forKey: .data)
case .intSummary:
data = try container.decode([SummaryData<Int>].self, forKey: .data)
case .doubleHistogram:
data = try container.decode([HistogramData<Double>].self, forKey: .data)
case .intHistogram:
data = try container.decode([HistogramData<Int>].self, forKey: .data)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(namespace, forKey: .namespace)
try container.encode(resource, forKey: .resource)
try container.encode(instrumentationScopeInfo, forKey: .instrumentationScopeInfo)
try container.encode(name, forKey: .name)
try container.encode(description, forKey: .description)
try container.encode(aggregationType, forKey: .aggregationType)
switch aggregationType {
case .doubleGauge:
guard let gaugeData = data as? [SumData<Double>] else {
let encodingContext = EncodingError.Context(
codingPath: encoder.codingPath,
debugDescription: "Expected [SumData<Double>] type for doubleGauge aggregationType, but instead found \(type(of: data))"
)
throw EncodingError.invalidValue(data, encodingContext)
}
try container.encode(gaugeData, forKey: .data)
case .intGauge:
guard let gaugeData = data as? [SumData<Int>] else {
let encodingContext = EncodingError.Context(
codingPath: encoder.codingPath,
debugDescription: "Expected [SumData<Int>] type for intGauge aggregationType, but instead found \(type(of: data))"
)
throw EncodingError.invalidValue(data, encodingContext)
}
try container.encode(gaugeData, forKey: .data)
case .doubleSum:
guard let sumData = data as? [SumData<Double>] else {
let encodingContext = EncodingError.Context(
codingPath: encoder.codingPath,
debugDescription: "Expected [SumData<Double>] type for doubleSum aggregationType, but instead found \(type(of: data))"
)
throw EncodingError.invalidValue(data, encodingContext)
}
try container.encode(sumData, forKey: .data)
case .doubleSummary:
guard let summaryData = data as? [SummaryData<Double>] else {
let encodingContext = EncodingError.Context(
codingPath: encoder.codingPath,
debugDescription: "Expected [SummaryData<Double>] type for doubleSummary aggregationType, but instead found \(type(of: data))"
)
throw EncodingError.invalidValue(data, encodingContext)
}
try container.encode(summaryData, forKey: .data)
case .intSum:
guard let sumData = data as? [SumData<Int>] else {
let encodingContext = EncodingError.Context(
codingPath: encoder.codingPath,
debugDescription: "Expected [SumData<Int>] type for intSum aggregationType, but instead found \(type(of: data))"
)
throw EncodingError.invalidValue(data, encodingContext)
}
try container.encode(sumData, forKey: .data)
case .intSummary:
guard let summaryData = data as? [SummaryData<Int>] else {
let encodingContext = EncodingError.Context(
codingPath: encoder.codingPath,
debugDescription: "Expected [SummaryData<Int>] type for intSummary aggregationType, but instead found \(type(of: data))"
)
throw EncodingError.invalidValue(data, encodingContext)
}
try container.encode(summaryData, forKey: .data)
case .doubleHistogram:
guard let summaryData = data as? [HistogramData<Double>] else {
let encodingContext = EncodingError.Context(
codingPath: encoder.codingPath,
debugDescription: "Expected [HistogramData<Double>] type for doubleHistogram aggregationType, but instead found \(type(of: data))"
)
throw EncodingError.invalidValue(data, encodingContext)
}
try container.encode(summaryData, forKey: .data)
case .intHistogram:
guard let summaryData = data as? [HistogramData<Int>] else {
let encodingContext = EncodingError.Context(
codingPath: encoder.codingPath,
debugDescription: "Expected [HistogramData<Int>] type for intHistogram aggregationType, but instead found \(type(of: data))"
)
throw EncodingError.invalidValue(data, encodingContext)
}
try container.encode(summaryData, forKey: .data)
}
}
}
|
23329c2f9c55232aee77d9e30813becb
| 44.375587 | 165 | 0.600724 | false | false | false | false |
cxchope/NyaaCatAPP_iOS
|
refs/heads/master
|
nyaacatapp/DynmapAnalysis.swift
|
gpl-3.0
|
1
|
//
// DynmapAnalysis.swift
// dynmapanalysistest
//
// Created by 神楽坂雅詩 on 16/2/11.
// Copyright © 2016年 KagurazakaYashi. All rights reserved.
//
import UIKit
class DynmapAnalysis: NSObject {
var html:String? = nil
var 解析:Analysis = Analysis()
let 页面特征:String = "<div id=\"mcmap\" class=\"dynmap\">"
// override init() {
// NSLog("构造:DynmapAnalysis")
// }
//
// deinit {
// NSLog("析构:DynmapAnalysis")
// }
func 有效性校验() -> Bool {
if (html?.range(of: 页面特征) != nil) {
return true
}
return false
}
func 取得世界列表() -> [String] {
var 世界名称:[String] = Array<String>()
let 起始点到结束点字符串:String = 解析.抽取区间(html!, 起始字符串: "<ul class=\"worldlist\"", 结束字符串: "</a></li></ul></li></ul>", 包含起始字符串: true, 包含结束字符串: false)
let classworld分割:[String] = 起始点到结束点字符串.components(separatedBy: "<li class=\"world\">")
if (classworld分割.count < 2) {
return 世界名称
}
for classworld分割循环 in 1...classworld分割.count-1 {
autoreleasepool {
var 当前classworld分割:String = classworld分割[classworld分割循环]
let 当前地图名称结束位置:Range = 当前classworld分割.range(of: "<")!
当前classworld分割 = 当前classworld分割.substring(to: 当前地图名称结束位置.lowerBound)
世界名称.append(当前classworld分割)
}
}
// NSLog("取得世界名称:\(世界名称)")
return 世界名称
}
func 取得时间和天气() -> [String] {
let 起始点到结束点字符串:String = 解析.抽取区间(html!, 起始字符串: "<div class=\"timeofday digitalclock", 结束字符串: "</div></div></div>", 包含起始字符串: false, 包含结束字符串: false)
let 时间字符串:String = 解析.抽取区间(起始点到结束点字符串, 起始字符串: "\">", 结束字符串: "</div>", 包含起始字符串: false, 包含结束字符串: false)
let 天气字符串:String = 解析.抽取区间(起始点到结束点字符串, 起始字符串: "weather ", 结束字符串: "\">", 包含起始字符串: false, 包含结束字符串: false)
let 天气分割:[String] = 天气字符串.components(separatedBy: "_")
var 天气:String = ""
var 时段:String = ""
if (天气分割.count == 2) {
天气 = 天气分割[0]
时段 = 天气分割[1]
} else {
天气 = 天气字符串
}
// NSLog("时间:\(时间字符串),时段:\(时段),天气:\(天气)")
//let 时段中文数据:Dictionary<String,String> = ["day":"白天","night":"夜晚"]
//let 天气中文数据:Dictionary<String,String> = ["stormy":"雨","sunny":"晴","thunder":"雷"]
return [时间字符串,时段,天气]
}
func 取得在线玩家() -> [[String]] {
let 起始点到结束点字符串:String = 解析.抽取区间(html!, 起始字符串: "<ul class=\"playerlist\"", 结束字符串: "</ul><div class=\"scrolldown\"", 包含起始字符串: true, 包含结束字符串: true)
let li分割:[String] = 起始点到结束点字符串.components(separatedBy: "<li class=\"player")
var 在线玩家头像:[String] = Array<String>()
var 在线玩家名:[String] = Array<String>()
var 在线玩家名带字体格式:[String] = Array<String>()
if (li分割.count < 2) {
return [在线玩家名, 在线玩家头像, 在线玩家名带字体格式]
}
for li分割循环 in 1...li分割.count-1 {
autoreleasepool {
let 当前li分割:String = li分割[li分割循环]
let 图片相对路径:String = 解析.抽取区间(当前li分割, 起始字符串: "<img src=\"", 结束字符串: "\"></span><a href=\"#\"", 包含起始字符串: false, 包含结束字符串: false)
let 图片相对路径分割:[String] = 图片相对路径.components(separatedBy: "/")
let 图片文件名:String = 图片相对路径分割[图片相对路径分割.count-1]
在线玩家头像.append(图片文件名)
let 玩家名带格式:String = 解析.抽取区间(当前li分割, 起始字符串: "title=\"Center on player\">", 结束字符串: "</a>", 包含起始字符串: false, 包含结束字符串: false)
在线玩家名带字体格式.append(玩家名带格式)
let 玩家名:[String] = 解析.去除HTML标签(玩家名带格式,需要合成: true)
在线玩家名.append(玩家名[0])
}
}
/*
使用 在线玩家头像 时应补充:
let 头像网址:String = "https://map.nyaa.cat/tiles/faces/"
let 图片补路径:String = 头像网址 + "16x16/" + 在线玩家头像 //支持32x32
使用 在线玩家名带字体格式 时应补充:
let 网页头:String = "<html><meta http-equiv=Content-Type content=\"text/html;charset=utf-8\"><body>"
let 网页尾:String = "</body></html>"
*/
// NSLog("在线玩家头像:\(在线玩家头像)")
// NSLog("在线玩家名:\(在线玩家名)")
// NSLog("在线玩家名带字体格式:\(在线玩家名带字体格式)")
let 合并二维数组:[[String]] = [在线玩家名, 在线玩家头像, 在线玩家名带字体格式]
return 合并二维数组
}
//返回值= 在线玩家名:[在线玩家头像, 在线玩家名带字体格式,在线玩家血量宽度,在线玩家护甲宽度,在线玩家位置]
func 取得在线玩家和当前世界活动状态() -> Dictionary<String,[String]> {
var 在线玩家:Dictionary<String,[String]> = 转换玩家二维数组格式(取得在线玩家())
var 活动玩家:Dictionary<String,[String]> = 转换玩家二维数组格式(取得当前世界活动玩家状态())
for key in 活动玩家.keys
{
autoreleasepool {
var 在线玩家当前值:[String] = 在线玩家[key]!
let 活动玩家当前值:[String] = 活动玩家[key]!
for i in 0...活动玩家当前值.count-1 {
autoreleasepool {
在线玩家当前值.append(活动玩家当前值[i])
}
}
在线玩家[key] = 在线玩家当前值
}
}
// NSLog("在线玩家\(在线玩家.count)=\(在线玩家)");
return 在线玩家
//果然不用字典用数组的话好麻烦:
// let 修改前玩家数量:Int = 在线玩家.count
// for (var 在线玩家循环 = 1; 在线玩家循环 < 修改前玩家数量; 在线玩家循环++) {
// var 当前在线玩家:[String] = 在线玩家[在线玩家循环]
// let 当前在线玩家名称:String = 当前在线玩家[0]
// for (var 世界活动玩家状态循环 = 0; 世界活动玩家状态循环 < 世界活动玩家状态.count; 世界活动玩家状态循环++) {
// var 当前世界活动玩家状态:[String] = 世界活动玩家状态[世界活动玩家状态循环]
// let 当前世界活动玩家名称:String = 当前世界活动玩家状态[0]
// if (当前世界活动玩家名称 == 当前在线玩家名称) {
// NSLog("添加详情到:\(当前世界活动玩家名称)")
// let 修改前属性数量:Int = 当前世界活动玩家状态.count
// for (var 当前世界活动玩家状态循环 = 0; 当前世界活动玩家状态循环 < 修改前属性数量; 当前世界活动玩家状态循环++) {
// let 当前要补充的属性:String = 当前世界活动玩家状态[当前世界活动玩家状态循环]
// 当前世界活动玩家状态.append(当前要补充的属性)
// 在线玩家[在线玩家循环] = 当前世界活动玩家状态
// //当前在线玩家.append(当前要补充的属性)
// }
// }
// }
// }
// NSLog("在线玩家:\(在线玩家.count):\(在线玩家)")
//NSLog("新在线玩家:\(新在线玩家.count):\(新在线玩家)")
}
func 转换玩家二维数组格式(_ 数组:[[String]]) -> Dictionary<String,[String]> {
let 在线玩家二维数组:[[String]] = 数组
let 在线玩家名:[String] = 在线玩家二维数组[0]
var 玩家信息:Dictionary<String,[String]> = Dictionary<String,[String]>()
if (在线玩家名.count < 1) {
return 玩家信息
}
for 在线玩家名循环 in 0...在线玩家名.count-1 {
autoreleasepool {
var 当前玩家信息:[String] = Array<String>()
var 当前玩家名:String = ""
for 在线玩家二维数组循环 in 0...在线玩家二维数组.count-1 {
autoreleasepool {
let 当前玩家名数组:[String] = 在线玩家二维数组[在线玩家二维数组循环]
let 当前信息:String = 当前玩家名数组[在线玩家名循环]
if (在线玩家二维数组循环 > 0) {
当前玩家信息.append(当前信息)
} else {
当前玩家名 = 当前信息
}
}
}
玩家信息[当前玩家名] = 当前玩家信息
}
}
//NSLog("玩家信息:\(玩家信息)")
return 玩家信息
}
func 取得当前世界活动玩家状态() -> [[String]] {
let 活动玩家块起始:String = "<div class=\"Marker playerMarker leaflet-marker-icon leaflet-clickable\""
let 活动玩家块:String = 解析.抽取区间(html!, 起始字符串: 活动玩家块起始, 结束字符串: "<div class=\"leaflet-popup-pane\">", 包含起始字符串: true, 包含结束字符串: false)
let 活动玩家块分割:[String] = 活动玩家块.components(separatedBy: 活动玩家块起始)
var 在线玩家名称:[String] = Array<String>()
var 在线玩家血量宽度:[String] = Array<String>()
var 在线玩家护甲宽度:[String] = Array<String>()
var 在线玩家位置:[String] = Array<String>()
if (活动玩家块分割.count < 2) {
return [在线玩家名称,在线玩家血量宽度,在线玩家护甲宽度,在线玩家位置]
}
for 活动玩家块分割循环 in 1...活动玩家块分割.count-1 {
autoreleasepool {
let 当前活动玩家块分割:String = 活动玩家块分割[活动玩家块分割循环]
//NSLog("当前活动玩家块分割:\(当前活动玩家块分割)")
var 玩家名称:String = 解析.抽取区间(当前活动玩家块分割, 起始字符串: "<span class=\"playerNameSm\">", 结束字符串: "<div c", 包含起始字符串: false, 包含结束字符串: false)
玩家名称 = 解析.去除HTML标签(玩家名称, 需要合成: true)[0]
let 玩家位置:String = translate3d标签抽取(当前活动玩家块分割)
//NSLog("玩家translate3d位置:\(玩家translate3d位置)")
let 玩家血量宽度:String = 解析.抽取区间(当前活动玩家块分割, 起始字符串: "<div class=\"playerHealth\" style=\"width: ", 结束字符串: "px;\">", 包含起始字符串: false, 包含结束字符串: false)
let 玩家护甲宽度:String = 解析.抽取区间(当前活动玩家块分割, 起始字符串: "<div class=\"playerArmor\" style=\"width: ", 结束字符串: "px;\">", 包含起始字符串: false, 包含结束字符串: false)
在线玩家名称.append(玩家名称)
在线玩家血量宽度.append(玩家血量宽度)
在线玩家护甲宽度.append(玩家护甲宽度)
在线玩家位置.append(玩家位置)
}
}
// NSLog("玩家名称:\(在线玩家名称)")
// NSLog("玩家translate3d位置:\(在线玩家位置)")
// NSLog("玩家血量宽度:\(在线玩家血量宽度)")
// NSLog("玩家护甲宽度:\(在线玩家护甲宽度)")
let 合并二维数组:[[String]] = [在线玩家名称,在线玩家血量宽度,在线玩家护甲宽度,在线玩家位置]
return 合并二维数组
}
func 取得当前聊天记录() -> [[String]] {
let 聊天信息块:String = 解析.抽取区间(html!, 起始字符串: "<div class=\"messagelist", 结束字符串: "</div><button", 包含起始字符串: false, 包含结束字符串: true)
let 聊天信息块分割:[String] = 聊天信息块.components(separatedBy: "</div>")
var 聊天:[[String]] = Array<Array<String>>()
if (聊天信息块分割.count < 1) {
return 聊天
}
for 聊天信息块分割循环 in 0...聊天信息块分割.count-1 {
autoreleasepool {
var 已处理:Bool = false
let 当前聊天信息块:String = 聊天信息块分割[聊天信息块分割循环]
let 聊天图标单元:String = "<div class=\"messageicon\">"
let 当前聊天信息块分割:[String] = 当前聊天信息块.components(separatedBy: 聊天图标单元)
if (当前聊天信息块分割.count > 0) { //玩家消息
let 分割信息字段:[String] = 当前聊天信息块.components(separatedBy: "<span class=\"message")
var 类型:String = "0" //0=游戏内聊天,1=上下线消息,2=电报等第三方平台,3=手机
if (分割信息字段.count > 1) {
var 玩家头像:String = 解析.抽取区间(分割信息字段[1], 起始字符串: "icon\">", 结束字符串: "</span>", 包含起始字符串: false, 包含结束字符串: false)
if (玩家头像 != "") {
let 图片相对路径 = 解析.抽取区间(玩家头像, 起始字符串: "<img src=\"", 结束字符串: "\" class=", 包含起始字符串: false, 包含结束字符串: false)
let 图片相对路径分割:[String] = 图片相对路径.components(separatedBy: "/")
玩家头像 = 图片相对路径分割[图片相对路径分割.count-1]
}
var 玩家名称:String = 解析.抽取区间(分割信息字段[2], 起始字符串: "text\"> ", 结束字符串: "</span>", 包含起始字符串: false, 包含结束字符串: false)
var 玩家消息:String = 解析.抽取区间(分割信息字段[3], 起始字符串: "text\">", 结束字符串: "</span>", 包含起始字符串: false, 包含结束字符串: false)
if (玩家名称 == "") {
类型 = "2"
let 玩家消息分割:[String] = 玩家消息.components(separatedBy: "] ")
玩家名称 = 解析.抽取区间(玩家消息分割[0], 起始字符串: "[", 结束字符串: "", 包含起始字符串: false, 包含结束字符串: false)
if (玩家消息分割.count > 1) {
玩家消息 = 玩家消息分割[1]
} else {
玩家消息 = "<APP发生了错误QAQ>"
}
}
let 手机关键字:Range? = 玩家消息.range(of: 全局_手机发送消息关键字)
if (手机关键字 != nil) {
类型 = "3"
玩家消息 = 玩家消息.substring(from: 手机关键字!.upperBound)
}
// NSLog("玩家头像:\(玩家头像)")
// NSLog("玩家名称:\(玩家名称)")
// NSLog("来自第三方聊天软件:\(来自第三方聊天软件)")
// NSLog("玩家消息:\(玩家消息)")
聊天.append([玩家头像,玩家名称,类型,玩家消息])
已处理 = true
}
if (已处理 == false) { //系统消息
let 上下线提示分割:[String] = 当前聊天信息块.components(separatedBy: "</span> ")
let 上下线玩家名:String = 解析.抽取区间(上下线提示分割[0], 起始字符串: "<div class=\"messagerow\">", 结束字符串: "", 包含起始字符串: false, 包含结束字符串: false)
if (上下线提示分割.count > 1) {
let 上下线行为:String = 上下线提示分割[1]
// NSLog("上下线玩家名:\(上下线玩家名)")
// NSLog("上下线行为:\(上下线行为)")
聊天.append(["",上下线玩家名,"1",上下线行为])
已处理 = true
}
}
} else { //系统消息
NSLog("[ERR]溢出聊天信息块:\(当前聊天信息块)")
}
}
}
// NSLog("聊天:\(聊天)")
return 聊天
}
func 取得商店和地点列表() -> [[[String]]] {
var 商店:[[String]] = Array<Array<String>>()
var 地点:[[String]] = Array<Array<String>>()
let 商店块起始:String = "Marker mapMarker "
let 商店块结束:String = "playerMarker"
let 商店块:String = 解析.抽取区间(html!, 起始字符串: 商店块起始, 结束字符串: 商店块结束, 包含起始字符串: true, 包含结束字符串: false)
let 商店块分割:[String] = 商店块.components(separatedBy: 商店块起始)
if (商店块分割.count < 2) {
return [商店,地点]
}
for 商店块分割循环 in 1...商店块分割.count-1 {
autoreleasepool {
let 商店描述:String = 商店块分割[商店块分割循环]
let 商店判定:Range? = 商店描述.range(of: "markerName_SignShopMarkers")
let 商店名:String = 解析.抽取区间(商店描述, 起始字符串: "markerName16x16\">", 结束字符串: "</span>", 包含起始字符串: false, 包含结束字符串: false)
let 商店位置:String = translate3d标签抽取(商店描述)
if (商店判定 == nil) {
地点.append([商店名,商店位置])
} else {
商店.append([商店名,商店位置])
}
}
}
// NSLog("商店:\(商店)")
// NSLog("地点:\(地点)")
return [商店,地点]
}
func translate3d标签抽取(_ 源:String) -> String {
let translate3d位置描述:String = 解析.抽取区间(源, 起始字符串: "translate3d(", 结束字符串: "px, 0px);", 包含起始字符串: false, 包含结束字符串: false)
let translate3d位置数组:[String] = translate3d位置描述.components(separatedBy: "px, ")
let 位置描述:String = translate3d位置数组.joined(separator: ",")
return 位置描述
}
func 取得弹出提示() -> [String] {
//<div class="alertbox" style>Could not update map: error</div>
var 对话框正在被显示:String = "0"
var 起始点到结束点字符串:String = ""
let alertbox起始点位置:Range? = html!.range(of: "<div class=\"alertbox\"")
if (alertbox起始点位置 != nil) {
起始点到结束点字符串 = html!.substring(from: alertbox起始点位置!.lowerBound)
let 搜索结束点:Range = 起始点到结束点字符串.range(of: "</div>")!
起始点到结束点字符串 = 起始点到结束点字符串.substring(to: 搜索结束点.lowerBound)
let 检查对话框是否隐藏:Range? = html!.range(of: "display: none")
if (检查对话框是否隐藏 == nil) { //没有被隐藏
对话框正在被显示 = "1"
}
let 提示信息起始点位置:Range = 起始点到结束点字符串.range(of: ">")!
起始点到结束点字符串 = 起始点到结束点字符串.substring(from: 提示信息起始点位置.upperBound)
}
let 弹出提示信息:[String] = [ 对话框正在被显示, 起始点到结束点字符串 ]
// NSLog("弹出提示信息:\(弹出提示信息)")
return 弹出提示信息
}
}
|
c20fe8cb220b1afef6475c140cecedd7
| 44.215339 | 157 | 0.480167 | false | false | false | false |
jeffreybergier/WaterMe2
|
refs/heads/master
|
WaterMe/WaterMe/ReminderVesselMain/ReminderEdit/ReminderIntervalPickerViewController.swift
|
gpl-3.0
|
1
|
//
// ReminderIntervalPickerViewController.swift
// WaterMe
//
// Created by Jeffrey Bergier on 6/24/17.
// Copyright © 2017 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WaterMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import Datum
import UIKit
class ReminderIntervalPickerViewController: StandardViewController {
typealias CompletionHandler = (UIViewController, Int?) -> Void
class func newVC(from storyboard: UIStoryboard!,
existingValue: Int,
popoverSourceView: UIView?,
completionHandler: @escaping CompletionHandler) -> UIViewController
{
let id = "ReminderIntervalPickerViewController"
// swiftlint:disable:next force_cast
let navVC = storyboard.instantiateViewController(withIdentifier: id) as! UINavigationController
// swiftlint:disable:next force_cast
let vc = navVC.viewControllers.first as! ReminderIntervalPickerViewController
vc.completionHandler = completionHandler
vc.existingValue = existingValue
if let sourceView = popoverSourceView {
navVC.modalPresentationStyle = .popover
navVC.popoverPresentationController?.sourceView = sourceView
navVC.popoverPresentationController?.sourceRect = sourceView.bounds
navVC.popoverPresentationController?.delegate = vc
} else {
navVC.presentationController?.delegate = vc
}
return navVC
}
@IBOutlet private weak var pickerView: UIPickerView?
private var completionHandler: CompletionHandler!
private var existingValue: Int = ReminderConstants.defaultInterval
private let data: [Int] = (ReminderConstants.minimumInterval...ReminderConstants.maximumInterval).map({ $0 })
private let formatter = DateComponentsFormatter.newReminderIntervalFormatter
private var rowCache: [Int : NSAttributedString] = [:]
private var heightCache: CGFloat?
override func viewDidLoad() {
super.viewDidLoad()
self.title = LocalizedString.title
self.view.backgroundColor = Color.systemBackgroundColor
let existingIndex = self.data.firstIndex(of: self.existingValue) ?? 0
self.pickerView?.selectRow(existingIndex, inComponent: 0, animated: false)
}
@IBAction private func cancelButtonTapped(_ sender: Any) {
self.completionHandler(self, nil)
}
@IBAction private func doneButtonTapped(_ sender: Any) {
let selectedIndex = self.pickerView?.selectedRow(inComponent: 0) ?? 0
let selectedItem = self.data[selectedIndex]
self.completionHandler(self, selectedItem)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
self.rowCache = [:]
self.heightCache = nil
self.pickerView?.reloadAllComponents()
}
}
extension ReminderIntervalPickerViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView,
viewForRow row: Int,
forComponent component: Int,
reusing view: UIView?) -> UIView
{
let view: UILabel = (view as? UILabel) ?? UILabel()
view.attributedText = self.attributedString(forRow: row)
view.sizeToFit()
return view
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
if let cache = self.heightCache { return cache }
let height = self.attributedString(forRow: 100).size().height + 8
self.heightCache = height
return height
}
private func attributedString(forRow row: Int) -> NSAttributedString {
if let cache = self.rowCache[row] {
return cache
}
let days = self.data[row]
let interval: TimeInterval = TimeInterval(days) * (24 * 60 * 60)
let formattedString = self.formatter.string(from: interval) ?? "–"
let string = NSAttributedString(string: formattedString,
attributes: Font.selectableTableViewCell.attributes)
self.rowCache[row] = string
return string
}
}
extension ReminderIntervalPickerViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.data.count
}
}
extension ReminderIntervalPickerViewController: UIPopoverPresentationControllerDelegate /*: UIAdaptivePresentationControllerDelegate*/
{
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
self.doneButtonTapped(presentationController)
}
func presentationController(_ presentationController: UIPresentationController,
willPresentWithAdaptiveStyle style: UIModalPresentationStyle,
transitionCoordinator: UIViewControllerTransitionCoordinator?)
{
switch style {
case .none:
self.preferredContentSize = .init(width: 320, height: 260)
case .overFullScreen, .formSheet:
self.preferredContentSize = .zero
default:
assertionFailure("Unexpected presentation style reached")
}
}
override func adaptivePresentationStyle(for controller: UIPresentationController,
traitCollection: UITraitCollection) -> UIModalPresentationStyle
{
guard !traitCollection.preferredContentSizeCategory.isAccessibilityCategory else {
return super.adaptivePresentationStyle(for: controller, traitCollection: traitCollection)
}
// if on narrow iphone screen, present as popover
// on ipad present as normal form sheet
return traitCollection.horizontalSizeClassIsCompact ? .none : .formSheet
}
}
|
d4f2ba6d12d480e191e5268faf2b7308
| 39.884146 | 134 | 0.682028 | false | false | false | false |
wyp767363905/TestKitchen_1606
|
refs/heads/master
|
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRecommendNewCell.swift
|
mit
|
1
|
//
// CBRecommendNewCell.swift
// TestKitchen
//
// Created by qianfeng on 16/8/19.
// Copyright © 2016年 1606. All rights reserved.
//
import UIKit
class CBRecommendNewCell: UITableViewCell {
//显示数据
var model : CBRecommendWidgetListModel?{
didSet {
showData()
}
}
func showData(){
//按照三列来遍历
for i in 0..<3 {
//图片
if model?.widget_data?.count > i*4 {
let imageModel = model?.widget_data![i*4]
if imageModel?.type == "image" {
let url = NSURL(string: (imageModel?.content)!)
let dImage = UIImage(named: "sdefaultImage")
//获取图片视图
let subView = contentView.viewWithTag(200+i)
if ((subView?.isKindOfClass(UIImageView.self)) == true) {
let imageView = subView as! UIImageView
imageView.kf_setImageWithURL(url, placeholderImage: dImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
//视频(直接跳转视频可以跳过)
//标题文字
if model?.widget_data?.count > i*4+2 {
let titleModel = model?.widget_data![i*4+2]
if titleModel?.type == "text" {
//获取标题的label
let subView = contentView.viewWithTag(400+i)
if ((subView?.isKindOfClass(UILabel.self)) == true) {
let titleLable = subView as! UILabel
titleLable.text = titleModel?.content
}
}
}
//描述文字
if model?.widget_data?.count > i*4+3 {
let descModel = model?.widget_data![i*4+3]
if descModel?.type == "text" {
//获取描述文字的label
let subView = contentView.viewWithTag(500+i)
if ((subView?.isKindOfClass(UILabel.self)) == true) {
let descLabel = subView as! UILabel
descLabel.text = descModel?.content
}
}
}
}
}
//创建cell的方法
class func createNewCellFor(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withListModel listModel: CBRecommendWidgetListModel) -> CBRecommendNewCell {
let cellId = "recommendNewCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBRecommendNewCell
if nil == cell {
cell = NSBundle.mainBundle().loadNibNamed("CBRecommendNewCell", owner: nil, options: nil).last as? CBRecommendNewCell
}
cell?.model = listModel
return cell!
}
//点击进详情
@IBAction func clickBtn(sender: UIButton) {
}
//播放视频
@IBAction func playAction(sender: UIButton) {
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
b713e8741c9ea7ce57c4d60a0cf1fb5d
| 26.519084 | 168 | 0.466297 | false | false | false | false |
SuperJerry/Swift
|
refs/heads/master
|
sorting.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
//import UIKit
//var str = "Hello, playground"
var list = [1,2,3,5,8,13,21,34,55,89,144,233,377,610]
public func linear(key: Int){
for number in list {
if number == key{
var result = "value \(key) found"
println(result)
//break
return
}
}
println("value \(key) not found")
}
//linear(144)
func round(n: Double)-> Double{
if Int(2*n) > 2*Int(n){
return Double(Int(n+1))
}
return Double(Int(n))
}
//println(round(2.9999))
public func log(key: Int, imin: Int, imax: Int){
if (imin == imax) && (list[imin] != key) {
println("not found")
return
}
var midindex: Double = round(Double((imin + imax) / 2))
var midnumber = list[Int(midindex)]
if midnumber > key {
log(key, imin, Int(midindex)-1)
}else if midnumber < key{
log(key, Int(midindex) + 1, imax)
}else{
var result = "value \(key) found"
println(result)
}
}
log(233, 0, 13)
//isFound
|
a73a3ff6fb425123e992d61303dfbe96
| 17.389831 | 59 | 0.538249 | false | false | false | false |
AshuMishra/TicTacToe
|
refs/heads/master
|
TicTacToe/TicTacToe/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// TicTacToe
//
// Created by Ashutosh Mishra on 09/01/16.
// Copyright © 2016 Ashutosh. All rights reserved.
//
import UIKit
enum GameResult {
case win
case lose
case draw
var stringForResult: String {
switch self {
case .win:
return "Won"
case .lose:
return "Lost"
case .draw:
return "Draw"
}
}
}
struct GameHistory {
var opponentName = String()
var gameResults = [GameResult]()
}
class ViewController: UIViewController {
@IBOutlet weak var playerTurnsLabel: UILabel!
@IBOutlet weak var playAgainButton: UIButton!
@IBOutlet weak var segmentControl: UISegmentedControl!
@IBOutlet weak var gameBoardView: GameBoardView!
var game = Game()
var matches = [GameHistory]()
var gameCount = 0
var nextTurn = Player.first
var playerAI = Player.second
override func viewDidLoad() {
super.viewDidLoad()
game.isTwoPlayerGame = false
game.gameBoard = gameBoardView
game.currentPlayer = .first
segmentControl.selectedSegmentIndex = 0
startMatch()
game.gameOverCompletion = {[weak self] winner in
guard let weakSelf = self else {
return
}
var history = weakSelf.matches.last
weakSelf.gameCount++
if winner == Player.first {
weakSelf.playerTurnsLabel.text = "You won"
weakSelf.nextTurn = Player.first
history!.gameResults.append(GameResult.win)
}else if winner == Player.second {
weakSelf.playerTurnsLabel.text = weakSelf.game.isTwoPlayerGame ? "Player 2 won" : "Computer won"
weakSelf.nextTurn = Player.second
history!.gameResults.append(GameResult.lose)
}else {
weakSelf.playerTurnsLabel.text = "Match Drawn"
weakSelf.nextTurn = weakSelf.game.playerLastTapped!
history!.gameResults.append(GameResult.draw)
}
weakSelf.matches.removeLast()
weakSelf.matches.append(history!)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playAgainButtonPressed(sender: UIButton) {
game.currentPlayer = nextTurn
playerTurnsLabel.text = "Get 3 in a Row to Win"
if game.isTwoPlayerGame == false {
if nextTurn == playerAI { // AI won
game.currentPlayer = nextTurn
game.firstMoveByAI()
} else {
game.startGame()
}
}else {
game.startGame()
}
}
@IBAction func handlePlayerMode(sender: AnyObject) {
game.isTwoPlayerGame = segmentControl.selectedSegmentIndex == 1
startMatch()
playAgainButtonPressed(playAgainButton)
}
func startMatch() {
let player = game.isTwoPlayerGame ? "Player 2" : "Computer"
let history = GameHistory(opponentName: player, gameResults: [])
matches.append(history)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "viewScore" {
let destinationVC = segue.destinationViewController as! ScoreViewController
destinationVC.matches = matches
}
}
}
|
dc14f24dcd0790db2a976a914395c235
| 23.762712 | 101 | 0.71937 | false | false | false | false |
Gurpartap/Swifter
|
refs/heads/master
|
Swifter/SwifterSearch.swift
|
mit
|
10
|
//
// SwifterSearch.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Swifter {
// GET search/tweets
public func getSearchTweetsWithQuery(q: String, geocode: String? = nil, lang: String? = nil, locale: String? = nil, resultType: String? = nil, count: Int? = nil, until: String? = nil, sinceID: String? = nil, maxID: String? = nil, includeEntities: Bool? = nil, callback: String? = nil, success: ((statuses: [JSONValue]?, searchMetadata: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler) {
let path = "search/tweets.json"
var parameters = Dictionary<String, Any>()
parameters["q"] = q
if geocode != nil {
parameters["geocode"] = geocode!
}
if lang != nil {
parameters["lang"] = lang!
}
if locale != nil {
parameters["locale"] = locale!
}
if resultType != nil {
parameters["result_type"] = resultType!
}
if count != nil {
parameters["count"] = count!
}
if until != nil {
parameters["until"] = until!
}
if sinceID != nil {
parameters["since_id"] = sinceID!
}
if maxID != nil {
parameters["max_id"] = maxID!
}
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if callback != nil {
parameters["callback"] = callback!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
switch (json["statuses"].array, json["search_metadata"].object) {
case (let statuses, let searchMetadata):
success?(statuses: statuses, searchMetadata: searchMetadata)
default:
success?(statuses: nil, searchMetadata: nil)
}
}, failure: failure)
}
}
|
20cc964c017a9f86bfbea213167e2944
| 37.802469 | 415 | 0.622017 | false | false | false | false |
pennlabs/penn-mobile-ios
|
refs/heads/main
|
PennMobile/General/Networking + Analytics/UserDBManager.swift
|
mit
|
1
|
//
// UserDBManager.swift
// PennMobile
//
// Created by Josh Doman on 2/20/18.
// Copyright © 2018 PennLabs. All rights reserved.
//
import UIKit
import SwiftyJSON
func getDeviceID() -> String {
let deviceID = UIDevice.current.identifierForVendor!.uuidString
#if DEBUG
return "test"
#else
return deviceID
#endif
}
class UserDBManager: NSObject, Requestable, SHA256Hashable {
static let shared = UserDBManager()
fileprivate let baseUrl = "https://api.pennlabs.org"
/**
Retrieves an access token and makes an authenticated POST request by adding it as a header to the request.
Note: Do NOT use this to make POST requests to non-Labs services. Doing so will compromise the user's access token.
- parameter url: A string URL.
- parameter params: A dictionary of parameters to attach to the POST request.
- parameter callback: A callback containing the data and response that the request receives.
*/
fileprivate func makePostRequestWithAccessToken(url: String, params: [String: Any], callback: @escaping (Data?, URLResponse?, Error?) -> Void) {
OAuth2NetworkManager.instance.getAccessToken { (token) in
guard let token = token else {
callback(nil, nil, nil)
return
}
let url = URL(string: url)!
var request = URLRequest(url: url, accessToken: token)
request.httpMethod = "POST"
request.httpBody = String.getPostString(params: params).data(using: .utf8)
let task = URLSession.shared.dataTask(with: request, completionHandler: callback)
task.resume()
}
}
/**
Returns a URLRequest configured for making anonymous requests. The server matches either the pennkey-password hash or the private UUID in the DB to find the anonymous account ID, updating the identifiers if the password of device changes.
- parameter url: A string URL.
- parameter privacyOption: A PrivacyOption
- returns: URLRequest containing the data type, a SHA256 hash of the pennkey-password, and the privacy option UUID in the headers
*/
fileprivate func getAnonymousPrivacyRequest(url: String, for privacyOption: PrivacyOption) -> URLRequest {
let url = URL(string: url)!
var request = URLRequest(url: url)
guard let pennkey = KeychainAccessible.instance.getPennKey(), let password = KeychainAccessible.instance.getPassword(), let privateUUID = privacyOption.privateUUID else {
return request
}
let passwordHash = hash(string: pennkey + "-" + password + "-" + privacyOption.rawValue, encoding: .hex)
request.setValue(passwordHash, forHTTPHeaderField: "X-Password-Hash")
request.setValue(privateUUID, forHTTPHeaderField: "X-Device-Key")
request.setValue(privacyOption.rawValue, forHTTPHeaderField: "X-Data-Type")
return request
}
}
// MARK: - Backend Login
extension UserDBManager {
func loginToBackend() {
OAuth2NetworkManager.instance.getAccessToken { (token) in
guard let token = token else { return }
let url = URL(string: "https://pennmobile.org/api/login")!
let request = URLRequest(url: url, accessToken: token)
let task = URLSession.shared.dataTask(with: request)
task.resume()
}
}
}
// MARK: - Dining
extension UserDBManager {
func fetchDiningPreferences(_ completion: @escaping(_ result: Result<[DiningVenue], NetworkingError>) -> Void) {
OAuth2NetworkManager.instance.getAccessToken { (token) in
guard let token = token else {
// TODO: - Add network error handling for OAuth2
completion(.failure(.authenticationError))
return
}
let url = URL(string: "https://pennmobile.org/api/dining/preferences/")!
let request = URLRequest(url: url, accessToken: token)
let task = URLSession.shared.dataTask(with: request) { (data, _, error) in
guard let data = data else {
if let error = error as? NetworkingError {
completion(.failure(error))
} else {
completion(.failure(.other))
}
return
}
let diningVenueIds = JSON(data)["preferences"].arrayValue.map({ $0["venue_id"].int! })
let diningVenues = DiningAPI.instance.getVenues(with: diningVenueIds)
completion(.success(diningVenues))
}
task.resume()
}
}
func saveDiningPreference(for venueIds: [Int]) {
let url = "https://pennmobile.org/api/dining/preferences/"
OAuth2NetworkManager.instance.getAccessToken { (token) in
let url = URL(string: url)!
var request = token != nil ? URLRequest(url: url, accessToken: token!) : URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try? JSON(["venues": venueIds]).rawData()
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request)
task.resume()
}
}
}
// MARK: - Laundry
extension UserDBManager {
func saveLaundryPreferences(for rooms: [LaundryRoom]) {
let ids = rooms.map { $0.id }
saveLaundryPreferences(for: ids)
}
func saveLaundryPreferences(for ids: [Int]) {
let url = "https://pennmobile.org/api/laundry/preferences/"
let params = ["rooms": ids]
OAuth2NetworkManager.instance.getAccessToken { (token) in
let url = URL(string: url)!
var request = token != nil ? URLRequest(url: url, accessToken: token!) : URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSON(params).rawData()
let deviceID = getDeviceID()
request.setValue(deviceID, forHTTPHeaderField: "X-Device-ID")
let task = URLSession.shared.dataTask(with: request)
task.resume()
}
}
func getLaundryPreferences(_ callback: @escaping (_ rooms: [Int]?) -> Void) {
let url = "https://pennmobile.org/api/laundry/preferences/"
OAuth2NetworkManager.instance.getAccessToken { (token) in
let url = URL(string: url)!
var request = token != nil ? URLRequest(url: url, accessToken: token!) : URLRequest(url: url)
let deviceID = getDeviceID()
request.setValue(deviceID, forHTTPHeaderField: "X-Device-ID")
let task = URLSession.shared.dataTask(with: request) { (data, _, _) in
if let data = data, let rooms = JSON(data)["rooms"].arrayObject {
callback(rooms.compactMap { $0 as? Int })
return
}
callback(nil)
}
task.resume()
}
}
}
// MARK: - Student Account
extension UserDBManager {
func saveAccount(_ account: Account, _ completion: @escaping (_ accountID: String?) -> Void) {
let jsonEncoder = JSONEncoder()
jsonEncoder.keyEncodingStrategy = .convertToSnakeCase
do {
let url = URL(string: "\(baseUrl)/account/register")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let jsonData = try jsonEncoder.encode(account)
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, _) in
var accountID: String?
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
if let data = data, NSString(data: data, encoding: String.Encoding.utf8.rawValue) != nil {
let json = JSON(data)
accountID = json["account_id"].string
}
}
}
completion(accountID)
})
task.resume()
} catch {
completion(nil)
}
}
func deleteAnonymousCourses(_ completion: @escaping (_ success: Bool) -> Void) {
var request = getAnonymousPrivacyRequest(url: "\(baseUrl)/account/courses/private/delete", for: .anonymizedCourseSchedule)
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request, completionHandler: { (_, response, _) in
if let httpResponse = response as? HTTPURLResponse {
completion(httpResponse.statusCode == 200)
} else {
completion(false)
}
})
task.resume()
}
func getWhartonStatus(_ completion: @escaping (_ result: Result<Bool, NetworkingError>) -> Void) {
OAuth2NetworkManager.instance.getAccessToken { (token) in
guard let token = token else {
completion(.failure(.authenticationError))
return
}
let url = URL(string: "https://pennmobile.org/api/gsr/wharton/")!
let request = URLRequest(url: url, accessToken: token)
let task = URLSession.shared.dataTask(with: request) { data, _, _ in
guard let data = data else {
completion(.failure(.serverError))
return
}
if let isWharton = try? JSON(data: data)["is_wharton"].bool {
completion(.success(isWharton))
} else {
completion(.failure(.serverError))
}
}
task.resume()
}
}
}
// MARK: - Transaction Data
extension UserDBManager {
func saveTransactionData(csvStr: String, _ callback: (() -> Void)? = nil) {
let url = "\(baseUrl)/dining/transactions"
let params = ["transactions": csvStr]
makePostRequestWithAccessToken(url: url, params: params) { (_, _, _) in
callback?()
}
}
}
// MARK: - Housing Data
extension UserDBManager {
/// Uploads raw CampusExpress housing html to the server, which parses it and saves the corresponding housing result. This result is returned and stored in UserDefaults.
func saveHousingData(html: String, _ completion: (( _ result: HousingResult?) -> Void)? = nil) {
let url = "\(baseUrl)/housing"
let params = ["html": html]
makePostRequestWithAccessToken(url: url, params: params) { (data, response, _) in
if let data = data, let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
if let result = try? decoder.decode(HousingResult.self, from: data) {
UserDefaults.standard.saveHousingResult(result)
completion?(result)
return
}
}
completion?(nil)
}
}
/// Uploads all housing results stored in UserDefaults to the server
func saveMultiyearHousingData(_ completion: (( _ success: Bool) -> Void)? = nil) {
guard let housingResults = UserDefaults.standard.getHousingResults() else {
completion?(true)
return
}
OAuth2NetworkManager.instance.getAccessToken { (token) in
guard let token = token else {
completion?(false)
return
}
let url = URL(string: "\(self.baseUrl)/housing/all")!
var request = URLRequest(url: url, accessToken: token)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let jsonEncoder = JSONEncoder()
jsonEncoder.keyEncodingStrategy = .convertToSnakeCase
let jsonData = try? jsonEncoder.encode(housingResults)
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { (_, response, _) in
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
completion?(true)
} else {
completion?(false)
}
}
task.resume()
}
}
func deleteHousingData(_ completion: (( _ success: Bool) -> Void)? = nil) {
let url = "\(baseUrl)/housing/delete"
makePostRequestWithAccessToken(url: url, params: [:]) { (_, response, _) in
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
completion?(true)
} else {
completion?(false)
}
}
}
}
// MARK: - Privacy and Notification Settings
extension UserDBManager {
func fetchNotificationSettings(_ completion: @escaping (_ result: Result<[NotificationSetting], NetworkingError>) -> Void) {
OAuth2NetworkManager.instance.getAccessToken { (token) in
guard let token = token else {
completion(.failure(.authenticationError))
return
}
let url = URL(string: "https://pennmobile.org/api/user/notifications/settings/")!
let request = URLRequest(url: url, accessToken: token)
let task = URLSession.shared.dataTask(with: request) { data, _, _ in
guard let data = data else {
completion(.failure(.serverError))
return
}
let decoder = JSONDecoder()
if let notifSettings = try? decoder.decode([NotificationSetting].self, from: data) {
completion(.success(notifSettings))
} else {
completion(.failure(.parsingError))
}
}
task.resume()
}
}
func updateNotificationSetting(id: Int, service: String, enabled: Bool, _ callback: ((_ success: Bool) -> Void)?) {
OAuth2NetworkManager.instance.getAccessToken { (token) in
guard let token = token, let payload = try? JSONSerialization.data(withJSONObject: ["service": service, "enabled": enabled]) else {
callback?(false)
return
}
let url = URL(string: "https://pennmobile.org/api/user/notifications/settings/\(id)/")!
var request = URLRequest(url: url, accessToken: token)
request.httpMethod = "PATCH"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = payload
let task = URLSession.shared.dataTask(with: request) { (_, response, _) in
if let httpResponse = response as? HTTPURLResponse {
callback?(httpResponse.statusCode == 200 || httpResponse.statusCode == 201)
} else {
callback?(false)
}
}
task.resume()
}
}
// TO-DO: Remove/update below functions with api/user/privacy/settings/ route
func syncUserSettings(_ callback: @escaping (_ success: Bool) -> Void) {
self.fetchUserSettings { (success, privacySettings, notificationSettings) in
if success {
if let privacySettings = privacySettings {
UserDefaults.standard.saveAll(privacyPreferences: privacySettings)
}
if let notificationSettings = notificationSettings {
UserDefaults.standard.saveAll(notificationPreferences: notificationSettings)
}
}
callback(success)
}
}
func fetchUserSettings(_ callback: @escaping (_ success: Bool, _ privacyPreferences: PrivacyPreferences?, _ notificationPreferences: NotificationPreferences?) -> Void) {
let urlRoute = "\(baseUrl)/account/settings"
struct CodableUserSettings: Codable {
let notifications: NotificationPreferences
let privacy: PrivacyPreferences
}
OAuth2NetworkManager.instance.getAccessToken { (token) in
if let token = token {
let url = URL(string: urlRoute)!
let request = URLRequest(url: url, accessToken: token)
let task = URLSession.shared.dataTask(with: request) { (data, _, error) in
if error == nil, let data = data, let settings = try? JSONDecoder().decode(CodableUserSettings.self, from: data) {
callback(true, settings.privacy, settings.notifications)
} else {
callback(false, nil, nil)
}
}
task.resume()
} else {
callback(false, nil, nil)
}
}
}
func saveUserNotificationSettings(_ callback: ((_ success: Bool) -> Void)? = nil) {
let urlRoute = "\(baseUrl)/notifications/settings"
let params = UserDefaults.standard.getAllNotificationPreferences()
saveUserSettingsDictionary(route: urlRoute, params: params, callback)
}
func saveUserPrivacySettings(_ callback: ((_ success: Bool) -> Void)? = nil) {
let urlRoute = "\(baseUrl)/privacy/settings"
let params = UserDefaults.standard.getAllPrivacyPreferences()
saveUserSettingsDictionary(route: urlRoute, params: params, callback)
}
private func saveUserSettingsDictionary(route: String, params: [String: Bool], _ callback: ((_ success: Bool) -> Void)?) {
OAuth2NetworkManager.instance.getAccessToken { (token) in
guard let token = token, let payload = try? JSONEncoder().encode(params) else {
callback?(false)
return
}
let url = URL(string: route)!
var request = URLRequest(url: url, accessToken: token)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = payload
let task = URLSession.shared.dataTask(with: request) { (_, response, _) in
if let httpResponse = response as? HTTPURLResponse {
callback?(httpResponse.statusCode == 200)
} else {
callback?(false)
}
}
task.resume()
}
}
}
// MARK: - Push Notifications
extension UserDBManager {
// Gets the notification token information using the access token.
func getNotificationId(_ completion: @escaping (_ result: Result<[GetNotificationID], NetworkingError>) -> Void) {
OAuth2NetworkManager.instance.getAccessToken { (token) in
guard let token = token else {
completion(.failure(.authenticationError))
return
}
let url = URL(string: "https://pennmobile.org/api/user/notifications/tokens/")!
var params: [String: Any] = [
"dev": false
]
#if DEBUG
params["dev"] = true
#endif
let request = URLRequest(url: url, accessToken: token)
let task = URLSession.shared.dataTask(with: request) { data, _, _ in
guard let data = data else {
completion(.failure(.serverError))
return
}
let decoder = JSONDecoder()
if let response = try?
decoder.decode([GetNotificationID].self, from: data) {
completion(.success(response))
} else {
completion(.failure(.parsingError))
}
}
task.resume()
}
}
// Updates device token.
func savePushNotificationDeviceToken(deviceToken: String, notifId: Int, _ completion: (() -> Void)? = nil) {
let url = "https://pennmobile.org/api/user/notifications/tokens/\(notifId)"
var params: [String: Any] = [
"kind": "IOS",
"token": deviceToken,
"dev": false
]
#if DEBUG
params["dev"] = true
#endif
makePostRequestWithAccessToken(url: url, params: params) { (_, _, _) in
completion?()
}
}
func clearPushNotificationDeviceToken(_ completion: (() -> Void)? = nil) {
let url = "\(baseUrl)/notifications/register"
makePostRequestWithAccessToken(url: url, params: [:]) { (_, _, _) in
completion?()
}
}
}
// MARK: - Anonymized Token Registration
extension UserDBManager {
/// Updates the anonymization keys in case either of them changed. The only key that may change is the pennkey-password.
func updateAnonymizationKeys() {
for option in PrivacyOption.anonymizedOptions {
var request = getAnonymousPrivacyRequest(url: "\(baseUrl)/privacy/anonymous/register", for: option)
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request)
task.resume()
}
}
}
// MARK: - Academic Degrees
extension UserDBManager {
/// Deletes all academic degree information from server (school, grad year, major)
func deleteAcademicInfo(_ completion: (( _ success: Bool) -> Void)? = nil) {
let url = "\(baseUrl)/account/degrees/delete"
makePostRequestWithAccessToken(url: url, params: [:]) { (_, response, _) in
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
completion?(true)
} else {
completion?(false)
}
}
}
func saveAcademicInfo(_ degrees: Set<Degree>, _ completion: (( _ success: Bool) -> Void)? = nil) {
OAuth2NetworkManager.instance.getAccessToken { (token) in
guard let token = token else {
completion?(false)
return
}
let url = URL(string: "\(self.baseUrl)/account/degrees")!
var request = URLRequest(url: url, accessToken: token)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let jsonEncoder = JSONEncoder()
jsonEncoder.keyEncodingStrategy = .convertToSnakeCase
let jsonData = try? jsonEncoder.encode(degrees)
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { (_, response, _) in
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
completion?(true)
} else {
completion?(false)
}
}
task.resume()
}
}
}
|
c50d152be9a0ca13b6e5bcc3cc046cdc
| 39.12069 | 244 | 0.577482 | false | false | false | false |
MounikaAnkam/Lab-Exam
|
refs/heads/master
|
LabExam/StatisticsTableViewController.swift
|
mit
|
1
|
//
// StatisticsTableViewController.swift
// LabExam
//
// Created by Mounika Ankam on 3/12/15.
// Copyright (c) 2015 Mounika Ankam. All rights reserved.
//
import UIKit
class StatisticsTableViewController: UITableViewController {
var app:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return app.differences.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = app.differences[indexPath.row].description
// Configure the cell...
return cell
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50.0
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
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
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
|
d5328af91fb35a3c06ff18a171287428
| 34.019802 | 157 | 0.685609 | false | false | false | false |
igorkotkovets/ios-swift-tdd-loading-view
|
refs/heads/master
|
LoadingView/Classes/FramesManager.swift
|
mit
|
1
|
//
// FramesManager.swift
// Pods
//
// Created by Igor Kotkovets on 3/23/17.
//
//
import Foundation
public class FramesManager {
final class Constants {
static public let maxFps: TimeInterval = 60
static public let minTimePerFrame: TimeInterval = 1.0/maxFps
}
private var frames: Int = 0
private var lastTimestamp: TimeInterval = 0
private var timeSpan: TimeInterval = 0
private var _fps: Int = 0
private var timeFrame: TimeInterval = 0
private var timestampProvider: TimestampProvider?
public init(_ timestampProvider: TimestampProvider) {
self.timestampProvider = timestampProvider
}
public func frame() {
if self.canGo() {
timeFrame = timeFrame.truncatingRemainder(dividingBy: Constants.minTimePerFrame)
}
let currentTimestamp = timestampProvider!.timestamp()
let timeStep = currentTimestamp-lastTimestamp
timeFrame += timeStep
timeSpan += timeStep
if timeSpan > 1 {
timeSpan = 0
_fps = getFramesCount()
frames = 0
}
if self.canGo() {
frames += 1
}
lastTimestamp = currentTimestamp
}
public func fps() -> Int {
return _fps
}
public func getFramesCount() -> Int {
return frames
}
public func canGo() -> Bool {
return timeFrame > Constants.minTimePerFrame
}
}
|
e7dc5e1b2eb54b2e80327b1cf2a4a9bd
| 22.322581 | 92 | 0.612033 | false | false | false | false |
tlax/looper
|
refs/heads/master
|
looper/Metal/MetalFilterBlender.swift
|
mit
|
1
|
import MetalPerformanceShaders
class MetalFilterBlender:MetalFilter
{
private let kIndexBaseTexture:Int = 0
private let kIndexOverTexture:Int = 1
private let kIndexMapTexture:Int = 2
private let kIndexDestinationTexture:Int = 3
//MARK: public
func render(
overlayTexture:MTLTexture,
baseTexture:MTLTexture,
mapTexture:MTLTexture)
{
guard
let commandEncoder:MTLComputeCommandEncoder = self.commandEncoder,
let pipeline:MTLComputePipelineState = self.pipeline,
let threadgroupCounts:MTLSize = self.threadgroupCounts,
let threadgroups:MTLSize = self.threadgroups
else
{
return
}
commandEncoder.setComputePipelineState(pipeline)
commandEncoder.setTexture(baseTexture, at:kIndexBaseTexture)
commandEncoder.setTexture(overlayTexture, at:kIndexOverTexture)
commandEncoder.setTexture(mapTexture, at:kIndexMapTexture)
commandEncoder.setTexture(baseTexture, at:kIndexDestinationTexture)
commandEncoder.dispatchThreadgroups(
threadgroups,
threadsPerThreadgroup:threadgroupCounts)
commandEncoder.endEncoding()
}
}
|
3cb8173d1d568347336f67af005944ec
| 31.025 | 78 | 0.672912 | false | false | false | false |
cheyongzi/MGTV-Swift
|
refs/heads/master
|
MGTV-Swift/Home/ViewSource/TemplateCollectionViewSource.swift
|
mit
|
1
|
//
// TemplateCollectionViewSource.swift
// MGTV-Swift
//
// Created by Che Yongzi on 16/10/10.
// Copyright © 2016年 Che Yongzi. All rights reserved.
//
import UIKit
protocol TemplateCollectionViewSourceDelegate: class {
func fetchTemplate(params: [String : Any])
}
extension TemplateCollectionViewSourceDelegate {
func fetchTemplate(params: [String : Any]) {
}
}
class HomeCollectionViewModel: CollectionViewModel<ChannelResponseData>, ChannelSegmentViewDelegate {
weak var viewSourceDelegate: TemplateCollectionViewSourceDelegate?
//MARK: - CollectionView
lazy public private(set) var collectionView: UICollectionView = { [unowned self] in
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect(x:0, y:100, width:HNTVDeviceWidth, height:HNTVDeviceHeight-149), collectionViewLayout: flowLayout);
collectionView.isPagingEnabled = true;
collectionView.showsVerticalScrollIndicator = false;
collectionView.showsHorizontalScrollIndicator = false;
collectionView.scrollsToTop = false;
collectionView.clipsToBounds = false;
collectionView.delegate = self;
collectionView.dataSource = self;
collectionView.backgroundColor = UIColor.white
collectionView.register(TemplateCollectionViewCell.self, forCellWithReuseIdentifier: "TemplateCollectionViewCell")
return collectionView;
}()
lazy public private(set) var segment: ChannelSegmentView = self.initSegment()
private func initSegment() -> ChannelSegmentView {
let segmentView = ChannelSegmentView(frame: CGRect(x: 0, y: 64, width: HNTVDeviceWidth, height: 36))
var channelTitleDatas: [String] = []
for channelData in datas[0] {
channelTitleDatas.append(channelData.title ?? "")
}
segmentView.datas = channelTitleDatas
segmentView.delegate = self
return segmentView
}
override func cellConfig(_ view: UICollectionView, datas: [[ChannelResponseData]], indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TemplateCollectionViewCell", for: indexPath)
guard let collectionCell = cell as? TemplateCollectionViewCell else {
return cell
}
guard let channelId = datas[indexPath.section][indexPath.row].vclassId else {
return cell
}
collectionCell.setOffset(channelId)
let templateResponse = TemplateDataManager.dataManager.template(channelId: channelId)
TemplateDataManager.dataManager.currentChannelId = channelId
collectionCell.configCell(response: templateResponse)
return collectionCell
}
//MARK: - UIScollView delegate
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x / scrollView.frame.width)
let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0))
if let homeCell = cell as? TemplateCollectionViewCell {
homeCell.storeOffset()
}
}
//手动拖拽滑动会走这个方法
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollEnded(scrollView)
}
//scrolltoItem 会走这个方法
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
scrollEnded(scrollView)
}
//MARK: - UICollectionView scroll animtaion end action
private func scrollEnded(_ scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x / scrollView.bounds.width)
segment.move(index)
let channelData = datas[0][index]
guard let channelId = channelData.vclassId else {
return
}
/// 判断接口数据是否失效
let response = TemplateDataManager.dataManager.template(channelId: channelId)
if response != nil {
if let lastRequestTime = response?.lastRequestTime {
let timeInterval = Date().timeIntervalSince(lastRequestTime)
guard timeInterval > 500 else {
return
}
}
}
TemplateDataManager.dataManager.storeOffset(0, channelId: channelId)
self.viewSourceDelegate?.fetchTemplate(params: ["type" : "5", "version" : "5.0", "vclassId" : channelId])
}
//MARK: - ChannelSegmentView Delegate
func select(_ fromIndex: Int, toIndex: Int) {
let cell = collectionView.cellForItem(at: IndexPath(item: fromIndex, section: 0))
if let homeCell = cell as? TemplateCollectionViewCell {
homeCell.storeOffset()
}
collectionView.scrollToItem(at: IndexPath(item: toIndex, section: 0), at: .centeredHorizontally, animated: true)
}
}
|
fa667d41a0e7da1ad6ba17b689a82977
| 40.084034 | 159 | 0.68153 | false | false | false | false |
skedgo/tripkit-ios
|
refs/heads/main
|
Sources/TripKit/core/Loc+TripKit.swift
|
apache-2.0
|
1
|
//
// Loc+TripKit.swift
// TripKit
//
// Created by Adrian Schoenig on 30/11/16.
//
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
#endif
extension Loc {
@objc public static var Trip: String {
return NSLocalizedString("Trip", tableName: "TripKit", bundle: .tripKit, comment: "Title for a trip")
}
public static var OpeningHours: String {
return NSLocalizedString("Opening Hours", tableName: "TripKit", bundle: .tripKit, comment: "Title for opening hours")
}
public static var PublicHoliday: String {
return NSLocalizedString("Public holiday", tableName: "TripKit", bundle: .tripKit, comment: "")
}
public static var ShowTimetable: String {
return NSLocalizedString("Show timetable", tableName: "TripKit", bundle: .tripKit, comment: "")
}
// MARK: - Vehicles and transport modes
public static var Vehicles: String {
return NSLocalizedString("Vehicles", tableName: "TripKit", bundle: .tripKit, comment: "Title for showing the number of available vehicles (e.g., scooters, cars or bikes)")
}
public static var Vehicle: String {
return NSLocalizedString("Vehicle", tableName: "TripKit", bundle: .tripKit, comment: "Title for a vehicle of unspecified type")
}
@objc
public static var VehicleTypeBicycle: String {
return NSLocalizedString("Bicycle", tableName: "TripKit", bundle: .tripKit, comment: "Text for vehicle of type: Bicycle")
}
public static var VehicleTypeEBike: String {
return NSLocalizedString("E-Bike", tableName: "TripKit", bundle: .tripKit, comment: "Text for vehicle of type: E-Bike")
}
@objc
public static var VehicleTypeCar: String {
return NSLocalizedString("Car", tableName: "TripKit", bundle: .tripKit, comment: "Text for vehicle of type: Car")
}
public static var VehicleTypeKickScooter: String {
return NSLocalizedString("Kick Scooter", tableName: "TripKit", bundle: .tripKit, comment: "Text for vehicle of type: Kick Scooter")
}
public static var VehicleTypeMotoScooter: String {
return NSLocalizedString("Moto Scooter", tableName: "TripKit", bundle: .tripKit, comment: "Text for vehicle of type: Moto Scooter")
}
@objc
public static var VehicleTypeMotorbike: String {
return NSLocalizedString("Motorbike", tableName: "TripKit", bundle: .tripKit, comment: "Text for vehicle of type: Motorbike")
}
@objc
public static var VehicleTypeSUV: String {
return NSLocalizedString("SUV", tableName: "TripKit", bundle: .tripKit, comment: "Text for vehicle of type: SUV")
}
// MARK: - Linking to TSP
@objc public static var Disconnect: String {
return NSLocalizedString("Disconnect", tableName: "TripKit", bundle: .tripKit, comment: "To disconnect/unlink from a service provider, e.g., Uber")
}
@objc public static var Setup: String {
return NSLocalizedString("Setup", tableName: "TripKit", bundle: .tripKit, comment: "Set up to connect/link to a service provider, e.g., Uber")
}
// MARK: - Accessibility
public static var FriendlyPath: String {
return NSLocalizedString("Friendly", tableName: "TripKit", bundle: .tripKit, comment: "Indicating a path is wheelchair/cycyling friendly")
}
public static var UnfriendlyPath: String {
return NSLocalizedString("Unfriendly", tableName: "TripKit", bundle: .tripKit, comment: "Indicating a path is wheelchair/cycyling unfriendly")
}
public static var Dismount: String {
return NSLocalizedString("Dismount", tableName: "TripKit", bundle: .tripKit, comment: "Indicating a path requires you to dismount and push your bicycle")
}
public static var Unknown: String {
return NSLocalizedString("Unknown", tableName: "TripKit", bundle: .tripKit, comment: "Indicator for something unknown/unspecified")
}
// MARK: - Permission manager
public static var ContactsAuthorizationAlertText: String {
return NSLocalizedString("You previously denied this app access to your contacts. Please go to the Settings app > Privacy > Contacts and authorise this app to use this feature.", tableName: "Shared", bundle: .tripKit, comment: "Contacts authorisation needed text")
}
public static func PersonsHome(name: String) -> String {
let format = NSLocalizedString("%@'s Home", tableName: "Shared", bundle: .tripKit, comment: "'%@' will be replaced with the person's name")
return String(format: format, name)
}
public static func PersonsWork(name: String) -> String {
let format = NSLocalizedString("%@'s Work", tableName: "Shared", bundle: .tripKit, comment: "'%@' will be replaced with the person's name")
return String(format: format, name)
}
public static func PersonsPlace(name: String) -> String {
let format = NSLocalizedString("%@'s", tableName: "Shared", bundle: .tripKit, comment: "'%@' will be replaced with the person's name. Name for a person's place if it's unclear if it's home, work or something else.")
return String(format: format, name)
}
// MARK: - Cards
@objc public static var Dismiss: String {
return NSLocalizedString("Dismiss", tableName: "TripKit", bundle: .tripKit, comment: "Button to dismiss something, e.g., an error or action action sheet")
}
public static var LeaveNow: String {
return NSLocalizedString("Leave now", tableName: "TripKit", bundle: .tripKit, comment: "Leave ASAP/now option")
}
@objc public static var LeaveAt: String {
return NSLocalizedString("Leave at", tableName: "TripKit", bundle: .tripKit, comment: "Leave after button")
}
@objc public static var ArriveBy: String {
return NSLocalizedString("Arrive by", tableName: "TripKit", bundle: .tripKit, comment: "Arrive before button")
}
@objc public static var Transport: String {
return NSLocalizedString("Transport", tableName: "TripKit", bundle: .tripKit, comment: "Title for button to access transport modes")
}
// MARK: - Format
@objc(Departs:capitalize:)
public static func Departs(atTime time: String, capitalize: Bool = false) -> String {
let format = NSLocalizedString("departs %@", tableName: "Shared", bundle: .tripKit, comment: "Estimated time of departure; parameter is time, e.g., 'departs 15:30'")
return String(format: capitalize ? format.localizedCapitalized : format, time)
}
@objc(Arrives:capitalize:)
public static func Arrives(atTime time: String, capitalize: Bool = false) -> String {
let format = NSLocalizedString("arrives %@", tableName: "Shared", bundle: .tripKit, comment: "Estimated time of arrival; parameter is time, e.g., 'arrives 15:30'")
return String(format: capitalize ? format.localizedCapitalized : format, time)
}
@objc(FromLocation:)
public static func From(location from: String) -> String {
let format = NSLocalizedString("From %@", tableName: "TripKit", bundle: .tripKit, comment: "Departure location. (old key: PrimaryLocationStart)")
return String(format: format, from)
}
@objc(ToLocation:)
public static func To(location to: String) -> String {
let format = NSLocalizedString("To %@", tableName: "TripKit", bundle: .tripKit, comment: "Destination location. For trip titles, e.g., 'To work'. (old key: PrimaryLocationEnd)")
return String(format: format, to)
}
@objc(FromTime:toTime:)
public static func fromTime(_ from: String, toTime to: String) -> String {
#if os(iOS) || os(tvOS)
switch UIView.userInterfaceLayoutDirection(for: .unspecified) {
case .leftToRight:
return String(format: "%@ → %@", from, to)
case .rightToLeft:
return String(format: "%@ ← %@", to, from)
@unknown default:
assertionFailure("Unexpected case encountered")
return String(format: "%@ → %@", from, to)
}
#else
return String(format: "%@ → %@", from, to)
#endif
}
@objc(Stops:)
public static func Stops(_ count: Int) -> String {
switch count {
case 0: return ""
case 1: return NSLocalizedString("1 stop", tableName: "TripKit", bundle: .tripKit, comment: "Number of stops before you get off a stop, if there's just 1 stop.")
default:
let format = NSLocalizedString("%@ stops", tableName: "TripKit", bundle: .tripKit, comment: "Number of stops before you get off a vehicle, if there are 2 stops or more, e.g., '10 stops'. (old key: Stops)")
return String(format: format, NSNumber(value: count))
}
}
public static func UpdatedAgo(duration: String) -> String {
let format = NSLocalizedString("Updated %@ ago", tableName: "TripKit", bundle: .tripKit, comment: "Vehicle updated. (old key: VehicleUpdated)")
return String(format: format, duration)
}
}
// MARK: - Segment instructions
extension Loc {
public static var Direction: String {
return NSLocalizedString("Direction", tableName: "TripKit", bundle: .tripKit, comment: "Destination of the bus")
}
public static func SomethingAt(time: String) -> String {
let format = NSLocalizedString("at %@", tableName: "TripKit", bundle: .tripKit, comment: "Time of the bus departure.")
return String(format: format, time)
}
public static func SomethingFor(duration: String) -> String {
let format = NSLocalizedString("for %@", tableName: "TripKit", bundle: .tripKit, comment: "Text indiction for how long a segment might take, where '%@' will be replaced with a duration. E.g., the instruction 'Take bus' might have this next to it as 'for 10 minutes'.")
return String(format: format, duration)
}
public static func DurationWithoutTraffic( _ duration: String) -> String {
let format = NSLocalizedString("%@ w/o traffic", tableName: "TripKit", bundle: .tripKit, comment: "Duration without traffic")
return String(format: format, duration)
}
public static func LeaveFromLocation(_ name: String? = nil, at time: String? = nil) -> String {
if let name = name, !name.isEmpty, let time = time, !time.isEmpty {
let format = NSLocalizedString("Leave %@ at %@", tableName: "TripKit", bundle: .tripKit, comment: "The first '%@' will be replaced with the place of departure, the second with the departure time. (old key: LeaveLocationTime)")
return String(format: format, name, time)
} else if let name = name, !name.isEmpty {
let format = NSLocalizedString("Leave %@", tableName: "TripKit", bundle: .tripKit, comment: "The place of departure. (old key: LeaveLocation)")
return String(format: format, name)
} else if let time = time, !time.isEmpty {
let format = NSLocalizedString("Leave at %@", tableName: "TripKit", bundle: .tripKit, comment: "Departure time. (old key: LeaveTime)")
return String(format: format, time)
} else {
return NSLocalizedString("Leave", tableName: "TripKit", bundle: .tripKit, comment: "Single line instruction to leave")
}
}
public static func LeaveNearLocation(_ name: String?) -> String {
guard let name = name else { return LeaveFromLocation() }
let format = NSLocalizedString("Depart near %@", tableName: "TripKit", bundle: .tripKit, comment: "Used when the trip does not start at the requested location, but nearby. The '%@' will be replaced with requested departure location.")
return String(format: format, name)
}
public static func ArriveAtLocation(_ name: String? = nil, at time: String? = nil) -> String {
if let name = name, !name.isEmpty, let time = time, !time.isEmpty {
let format = NSLocalizedString("Arrive %@ at %@", tableName: "TripKit", bundle: .tripKit, comment: "The first '%@' will be replaced with the place of arrival, the second with the arrival time. (old key: ArrivalLocationTime)")
return String(format: format, name, time)
} else if let name = name, !name.isEmpty {
let format = NSLocalizedString("Arrive %@", tableName: "TripKit", bundle: .tripKit, comment: "The place of arrival.")
return String(format: format, name)
} else if let time = time, !time.isEmpty {
let format = NSLocalizedString("Arrive at %@", tableName: "TripKit", bundle: .tripKit, comment: "Arrival time.")
return String(format: format, time)
} else {
return NSLocalizedString("Arrive", tableName: "TripKit", bundle: .tripKit, comment: "Single line instruction to arrive")
}
}
public static func ArriveNearLocation(_ name: String?) -> String {
guard let name = name else { return ArriveAtLocation() }
let format = NSLocalizedString("Arrive near %@", tableName: "TripKit", bundle: .tripKit, comment: "Used when the trip does not end at the requested location, but nearby. The '%@' will be replaced with requested destination location.")
return String(format: format, name)
}
}
// MARK: - Alerts
extension Loc {
public static var Alerts: String {
return NSLocalizedString("Alerts", tableName: "TripKit", bundle: .tripKit, comment: "")
}
public static var WeWillKeepYouUpdated: String {
return NSLocalizedString("We'll keep you updated with the latest transit alerts here", tableName: "TripKit", bundle: .tripKit, comment: "")
}
public static func InTheMeantimeKeepExploring(appName: String) -> String {
let format = NSLocalizedString("In the meantime, let's keep exploring %@ and enjoy your trips", tableName: "TripKit", bundle: .tripKit, comment: "%@ is replaced with app name")
return String(format: format, appName)
}
public static func Alerts(_ count: Int) -> String {
if count == 1 {
return NSLocalizedString("1 alert", tableName: "TripKit", bundle: .tripKit, comment: "Number of alerts, in this case, there is just one")
}
let format = NSLocalizedString("%@ alerts", tableName: "TripKit", bundle: .tripKit, comment: "Number of alerts, in this case, there are multiple (plural)")
return String(format: format, NSNumber(value: count))
}
@objc
public static var RoutingBetweenTheseLocationsIsNotYetSupported: String {
return NSLocalizedString("Routing between these locations is not yet supported.", tableName: "TripKit", bundle: .tripKit, comment: "")
}
}
// MARK: - Helpers
extension Bundle {
@objc public static let tripKit: Bundle = TripKit.bundle
}
|
5a6d1f9c8ab0e980bc44c697cc575d47
| 41.821752 | 272 | 0.693382 | false | false | false | false |
SwiftyMagic/Magic
|
refs/heads/master
|
Magic/Magic/Foundation/IntExtension.swift
|
mit
|
1
|
//
// IntExtension.swift
// Magic
//
// Created by Broccoli on 16/9/18.
// Copyright © 2016年 broccoliii. All rights reserved.
//
import Foundation
// MARK: - Properties
public extension Int {
var isEven:Bool {return (self % 2 == 0)}
var isOdd:Bool {return (self % 2 != 0)}
var isPositive:Bool {return (self >= 0)}
var isNegative:Bool {return (self < 0)}
}
// MARK: - Methods
public extension Int {
func toDouble() -> Double {
return Double(self)
}
func toFloat() -> Float {
return Float(self)
}
func times(in thread: DispatchQueue = DispatchQueue.global(qos: .background), handler: @escaping (Int) -> ()) {
(0..<self).forEach {_ in
handler(self)
}
}
func delay(in thread: DispatchQueue = DispatchQueue.global(qos: .background), handler: @escaping (Int) -> ()) {
let deadlineTime = DispatchTime.now() + .seconds(self)
thread.asyncAfter(deadline: deadlineTime) {
handler(self)
}
}
}
|
2cfc60a1a2c9cb86df5dbd44646ad192
| 23.325581 | 115 | 0.580306 | false | false | false | false |
muneebm/AsterockX
|
refs/heads/master
|
AsterockX/BaseTableViewController.swift
|
mit
|
1
|
//
// BasseTableViewController.swift
// AsterockX
//
// Created by Muneeb Rahim Abdul Majeed on 1/4/16.
// Copyright © 2016 beenum. All rights reserved.
//
import UIKit
import CoreData
class BaseTableViewController: UITableViewController {
var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
var coreDataStack: CoreDataStack {
return CoreDataStack.sharedInstance()
}
var sharedContext: NSManagedObjectContext {
return coreDataStack.managedObjectContext
}
func startActitvityIndicator() {
dispatch_async(dispatch_get_main_queue()) {
self.view.window?.userInteractionEnabled = false
self.view.window?.addSubview(self.activityIndicator)
self.activityIndicator.center = (self.view.window?.center)!
self.view.window?.alpha = 0.75
self.activityIndicator.startAnimating()
}
}
func stopActivityIndicator() {
dispatch_async(dispatch_get_main_queue()) {
self.activityIndicator.stopAnimating()
self.activityIndicator.removeFromSuperview()
self.view.window?.alpha = 1
self.view.window?.userInteractionEnabled = true
}
}
}
|
4b34b6df3b7e36196e1869d091bbc0a2
| 27.125 | 110 | 0.639259 | false | false | false | false |
sfinx87/SWDataStructure
|
refs/heads/master
|
SWDataStructure/TreeNode.swift
|
mit
|
1
|
//
// TreeNode.swift
// SWDataStructure
//
// Created by Alexander Kobylinskyy on 7/6/15.
// Copyright © 2015 Alex. All rights reserved.
//
class TreeNode<T: Equatable>: CustomStringConvertible, Equatable {
var data: T
var left: TreeNode<T>? = nil
var right: TreeNode<T>? = nil
init(data: T, left: TreeNode<T>? = nil, right: TreeNode<T>? = nil) {
self.data = data
self.left = left
self.right = right
}
var description: String {
return "\(data) Left:\(left?.data) Right:\(right?.data)"
}
}
func == <T>(lhs: TreeNode<T>, rhs: TreeNode<T>) -> Bool {
return lhs.data == rhs.data
}
|
234566de874af711c108d97180007f76
| 21.333333 | 69 | 0.643449 | false | false | false | false |
edx/edx-app-ios
|
refs/heads/master
|
Source/RegistrationFieldController.swift
|
apache-2.0
|
2
|
//
// RegistrationFieldController.swift
// edX
//
// Created by Muhammad Zeeshan Arif on 23/11/2017.
// Copyright © 2017 edX. All rights reserved.
//
class RegistrationFieldController: NSObject, OEXRegistrationFieldController {
var field: OEXRegistrationFormField
var fieldView: RegistrationFormFieldView
var view: UIView {
return fieldView
}
var hasValue: Bool {
return fieldView.hasValue
}
var accessibleInputField: UIView? {
return fieldView.textInputView
}
var isValidInput: Bool {
return fieldView.isValidInput
}
init(with formField: OEXRegistrationFormField) {
field = formField
fieldView = RegistrationFormFieldView(with: formField)
super.init()
setupView()
}
private func setupView() {
switch field.fieldType {
case OEXRegistrationFieldTypeEmail:
fieldView.textInputField.keyboardType = .emailAddress
fieldView.textInputField.accessibilityIdentifier = "field-\(field.name)"
break
case OEXRegistrationFieldTypePassword:
fieldView.textInputField.isSecureTextEntry = true
break
default:
break
}
}
/// id should be a JSON safe type.
func currentValue() -> Any {
return fieldView.currentValue
}
func setValue(_ value: Any) {
if let value = value as? String {
fieldView.setValue(value)
}
}
func handleError(_ errorMessage: String?) {
fieldView.errorMessage = errorMessage
}
}
|
f9deff30cae2b774a09d20ba5a762893
| 24.4375 | 84 | 0.624079 | false | false | false | false |
CaueAlvesSilva/FeaturedGames
|
refs/heads/master
|
FeaturedGames/FeaturedGames/Extensions/LoaderView.swift
|
mit
|
1
|
//
// LoaderView.swift
// FeaturedGames
//
// Created by Cauê Silva on 04/08/17.
// Copyright © 2017 Caue Alves. All rights reserved.
//
import UIKit
class LoaderView: UIView {
@IBOutlet weak var backgroundView: UIView!
@IBOutlet weak var alertView: UIView!
@IBOutlet weak var indicatorView: UIActivityIndicatorView!
@IBOutlet weak var loadingMessageLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
setComponentsIDs()
setupAppearence()
}
private func setComponentsIDs() {
accessibilityIdentifier = "LoaderView"
indicatorView.accessibilityIdentifier = "LoaderView.indicatorView"
loadingMessageLabel.accessibilityIdentifier = "LoaderView.loadingMessageLabel"
}
private func setupAppearence() {
backgroundView.backgroundColor = Colors.black.color.withAlphaComponent(0.9)
alertView.layer.cornerRadius = alertView.frame.size.height / 5
loadingMessageLabel.textColor = Colors.primary.color
indicatorView.color = Colors.primary.color
}
func startAnimation(with message: String = "") {
loadingMessageLabel.text = message
indicatorView.startAnimating()
}
}
|
e2dd4c0731c72944a58d6f5515df8d6a
| 28.595238 | 86 | 0.691874 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.