repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ezefranca/EFIntroVideoViewController | EFIntroVideoViewController/Classes/EFIntroVideoViewController.swift | 1 | 2819 | //
// EFIntroVideoViewController.swift
// EFIntroVideoViewController
//
// Created by techthings on 7/13/16.
// Copyright © 2016 Ezequiel França. All rights reserved.
//
import UIKit
import AVFoundation
class EFIntroVideoViewController: UIViewController {
var player: AVPlayer?
var playerLayer: AVPlayerLayer!
var playerView: UIView!
@IBInspectable var nextViewControllerIdentifier: String = ""
@IBInspectable var storyboardName:String = "Main"
@IBInspectable var videoPath:String = ""
@IBInspectable var videoType:String = ""
@IBInspectable var videoTime:Double = 5.0
@IBInspectable var videoTransitionTime:Double = 1.0
@IBInspectable var animated:Bool = false
convenience init(storyboardName:String, videoPath:String, videoType:String, videoTime:Double, videoTransitionTime:Double, nextViewControllerIdentifier:String, animated:Bool) {
self.init()
self.storyboardName = storyboardName
self.videoPath = videoPath
self.videoType = videoType
self.videoTime = videoTime
self.videoTransitionTime = videoTransitionTime
self.nextViewControllerIdentifier = nextViewControllerIdentifier
self.animated = animated
}
override func viewDidLoad() {
super.viewDidLoad()
loadVideo()
}
func loadVideo() {
playerView = UIView(frame: view.bounds)
view.addSubview(playerView)
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
} catch {
fatalError()
}
guard let path = Bundle.main.path(forResource: videoPath, ofType:videoType) else {
return
}
player = AVPlayer(url: URL(fileURLWithPath: path))
playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.frame
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
playerLayer.zPosition = -1
playerView.layer.addSublayer(playerLayer)
player?.seek(to: kCMTimeZero)
player?.play()
Timer.scheduledTimer(timeInterval: videoTime, target: self, selector: #selector(openNextViewController), userInfo: nil, repeats: false)
}
func openNextViewController() {
UIView.animate(withDuration: videoTransitionTime, animations: {
self.playerView.alpha = 0
}, completion: { (completed) in
let storyboard = UIStoryboard(name: self.storyboardName, bundle: nil)
self.playerView.removeFromSuperview()
let next = storyboard.instantiateViewController(withIdentifier: self.nextViewControllerIdentifier)
self.present(next, animated: self.animated, completion: nil)
})
}
}
| mit | b1ab1835fe98b2bbf106f7a38291c2ed | 34.658228 | 179 | 0.671282 | 5.24581 | false | false | false | false |
JeanetteMueller/fyydAPI | Example/FyydDefinitions.swift | 1 | 2811 | //
// FyydDefinitions.swift
// Podcat 2
//
// Created by Jeanette Müller on 06.04.17.
// Copyright © 2017 Jeanette Müller. All rights reserved.
//
import Foundation
let kfyydAuthClientId :String = "fyydAuthClientId"
let kfyydAuthToken :String = "kfyydAuthToken"
let kfyydUserID :String = "kfyydUserID"
let kfyydUrlBase :String = "https://fyyd.de"
let kfyydUrlApi :String = "https://api.fyyd.de"
let kfyydUrlApiV2 :String = "https://api.fyyd.de/0.2"
public enum FyydAPIError {}
public extension FyydAPIError{
enum Auth {
case failed, succeed, canceled
var localizedDescription:String{
get{
return "localizedDescription"
}
}
}
}
public typealias FyydAPILoginHandler = (FyydAPIError.Auth?) -> Swift.Void
let FyydCategories = [
FyydCategory(identifier: 1, andSlug:"arts", andName:"network_category_1301".localized, andImage:"kunst"),
FyydCategory(identifier: 8, andSlug:"business", andName:"network_category_1321".localized, andImage:"wirtschaft"),
FyydCategory(identifier: 14, andSlug:"comedy", andName:"network_category_1303".localized, andImage:"comedy"),
FyydCategory(identifier: 15, andSlug:"education", andName:"network_category_1304".localized, andImage:"bildung"),
FyydCategory(identifier: 21, andSlug:"games-hobbies", andName:"network_category_1323".localized, andImage:"spiele"),
FyydCategory(identifier: 27, andSlug:"government-organizations", andName:"network_category_1325".localized, andImage:"regierung"),
FyydCategory(identifier: 32, andSlug:"health", andName:"network_category_1307".localized, andImage:"gesundheit"),
FyydCategory(identifier: 37, andSlug:"kids-family", andName:"network_category_1305".localized, andImage:"familie"),
FyydCategory(identifier: 38, andSlug:"music", andName:"network_category_1310".localized, andImage:"musik"),
FyydCategory(identifier: 39, andSlug:"news-politics", andName:"network_category_1311".localized, andImage:"news"),
FyydCategory(identifier: 40, andSlug:"religion-spirituality", andName:"network_category_1314".localized, andImage:"religion"),
FyydCategory(identifier: 48, andSlug:"science-medicine", andName:"network_category_1315".localized, andImage:"wissenschaft"),
FyydCategory(identifier: 52, andSlug:"society-culture", andName:"network_category_1324".localized, andImage:"gesellschaft"),
FyydCategory(identifier: 57, andSlug:"sports-recreation", andName:"network_category_1316".localized, andImage:"freizeit"),
FyydCategory(identifier: 62, andSlug:"technology", andName:"network_category_1318".localized, andImage:"technologie"),
FyydCategory(identifier: 67, andSlug:"tv-film", andName:"network_category_1309".localized, andImage:"tv_film")
]
| mit | 52ce925e5ce76da7aebe72c696e9b700 | 48.263158 | 134 | 0.723647 | 3.595391 | false | false | false | false |
finngaida/wwdc | 2016/Finn Gaida/GifCell.swift | 1 | 3026 | //
// GifCell.swift
// Finn Gaida
//
// Created by Finn Gaida on 21.04.16.
// Copyright © 2016 Finn Gaida. All rights reserved.
//
import UIKit
import PhotosUI
class GifCell: UIView, PHLivePhotoViewDelegate {
var imageView:PHLivePhotoView?
var container: UIView?
var textLabel:UILabel?
var button:UIButton?
var delegate:MasterViewController?
func initialize(index: Int) {
let right = index % 2 != 0
self.layer.masksToBounds = true
self.layer.cornerRadius = self.frame.width / 10
container = UIView(frame: CGRectMake(right ? dist : 0, 0, self.frame.width - dist, self.frame.width - dist))
container?.layer.borderWidth = 2
container?.layer.masksToBounds = true
container?.layer.cornerRadius = self.frame.width / 10
container?.layer.borderColor = UIColor.whiteColor().CGColor
self.addSubview(container!)
let connector = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
connector.frame = CGRectMake(right ? 0 : (container?.frame.width)! - (vibrancyWidth / 2), self.frame.height / 2 - (vibrancyWidth / 2), dist * 1.1, vibrancyWidth)
connector.layer.masksToBounds = true
connector.layer.cornerRadius = connector.frame.height / 2
self.insertSubview(connector, belowSubview: container!)
imageView = PHLivePhotoView(frame: CGRectMake(0, 0, self.frame.width - dist, self.frame.height - dist))
imageView?.delegate = self
imageView?.layer.masksToBounds = true
imageView?.layer.cornerRadius = self.layer.cornerRadius
container?.addSubview(imageView!)
textLabel = UILabel(frame: CGRectMake(right ? dist : 0, self.frame.height - dist, self.frame.width - dist, dist))
textLabel?.textAlignment = .Center
textLabel?.textColor = .whiteColor()
textLabel?.font = UIFont.systemFontOfSize(12)
textLabel?.text = "Loading..."
self.addSubview(textLabel!)
button = UIButton(frame: CGRectMake(0, 0, self.frame.width, self.frame.height))
button?.addTarget(self, action: #selector(GifCell.buttonPress), forControlEvents: .TouchUpInside)
self.addSubview(button!)
ImageSorcery.share.loadPhoto(index, size: imageView!.frame.size) { (photo) in
if let p = photo {
self.imageView?.livePhoto = p
self.imageView?.startPlaybackWithStyle(.Full)
} else {
print("error photo unwrap")
}
}
}
func buttonPress() {
self.delegate?.showDetail(self.tag)
}
func livePhotoView(livePhotoView: PHLivePhotoView, didEndPlaybackWithStyle playbackStyle: PHLivePhotoViewPlaybackStyle) {
imageView?.startPlaybackWithStyle(.Full)
}
func livePhotoView(livePhotoView: PHLivePhotoView, willBeginPlaybackWithStyle playbackStyle: PHLivePhotoViewPlaybackStyle) {
}
}
| gpl-2.0 | d116ad19f43419a5d5b39b8f5947aa16 | 36.8125 | 169 | 0.643636 | 4.521674 | false | false | false | false |
pavankataria/SwiftDataTables | Example/DemoSwiftDataTables/AppDelegate.swift | 1 | 824 | //
// AppDelegate.swift
// SwiftDataTables
//
// Created by pavankataria on 03/09/2017.
// Copyright (c) 2017 pavankataria. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let window = UIWindow(frame: UIScreen.main.bounds)
let instance = MenuViewController()
self.navigationController = UINavigationController(rootViewController: instance)
window.rootViewController = self.navigationController
self.window = window
window.makeKeyAndVisible()
return true
}
}
| mit | 6de73e05279538c71340a6c1ff61f7b9 | 30.692308 | 145 | 0.725728 | 5.21519 | false | false | false | false |
chenchangqing/ioscomponents | SelectionCollectionView/SelectionCollectionView/DataHelper.swift | 1 | 4589 | //
// DataHelper.swift
// SelectionCollectionView
//
// Created by green on 15/8/24.
// Copyright (c) 2015年 com.chenchangqing. All rights reserved.
//
import UIKit
class DataHelper: NSObject {
/**
* 获得来自json的数据源
*/
class func dataSource(fileName:String) -> OrderedDictionary<CJCollectionViewHeaderModel,[CJCollectionViewCellModel]> {
// 单例
struct DataSourceSingleton{
static var predicate:dispatch_once_t = 0
static var instance:OrderedDictionary<CJCollectionViewHeaderModel,[CJCollectionViewCellModel]>!
}
dispatch_once(&DataSourceSingleton.predicate, { () -> Void in
DataSourceSingleton.instance = OrderedDictionary<CJCollectionViewHeaderModel,[CJCollectionViewCellModel]>()
let filePath = NSBundle.mainBundle().pathForResource(fileName, ofType: "json")!
let data = NSFileManager.defaultManager().contentsAtPath(filePath)
if let data = data {
var dataSource: [String:[[String:AnyObject]]]!
do {
try
dataSource = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String : [[String : AnyObject]]]
} catch {
}
for key in dataSource.keys {
let keyData = key.dataUsingEncoding(NSUTF8StringEncoding)!
var keyDic : [String:AnyObject]!
do {
try
keyDic = NSJSONSerialization.JSONObjectWithData(keyData, options: NSJSONReadingOptions.MutableContainers) as! [String : AnyObject]
} catch {
}
let icon = keyDic["icon"] as? String
let title = keyDic["title"] as? String
let type = keyDic["type"] as? Int
let isExpend = keyDic["isExpend"] as? Bool
let isShowClearButton = keyDic["isShowClearButton"] as? Bool
let height = keyDic["height"] as? CGFloat
let headerModel = CJCollectionViewHeaderModel(icon: icon, title: title)
if let type=type {
if let type=CJCollectionViewHeaderModelTypeEnum.instance(type) {
headerModel.type = type
}
}
if let isExpend=isExpend {
headerModel.isExpend = isExpend
}
if let isShowClearButton=isShowClearButton {
headerModel.isShowClearButton = isShowClearButton
}
if let height=height {
headerModel.height = height
}
var cellModels = [CJCollectionViewCellModel]()
let cellArray = dataSource[key]!
for cellDic in cellArray {
let icon = cellDic["icon"] as? String
let title = cellDic["title"] as? String
let selected = cellDic["selected"] as? Bool
let width = cellDic["width"] as? CGFloat
let cellModel = CJCollectionViewCellModel(icon: icon, title: title)
if let selected=selected {
cellModel.selected = selected
}
if let width=width {
cellModel.width = width
}
cellModels.append(cellModel)
}
DataSourceSingleton.instance[headerModel] = cellModels
}
}
})
return DataSourceSingleton.instance
}
}
| apache-2.0 | d54b9518bd95a42b81d7cce928991d0c | 37.378151 | 164 | 0.436829 | 7.015361 | false | false | false | false |
shajrawi/swift | stdlib/public/core/AssertCommon.swift | 2 | 8622 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Implementation Note: this file intentionally uses very LOW-LEVEL
// CONSTRUCTS, so that assert and fatal may be used liberally in
// building library abstractions without fear of infinite recursion.
//
// FIXME: We could go farther with this simplification, e.g. avoiding
// UnsafeMutablePointer
@_transparent
public // @testable
func _isDebugAssertConfiguration() -> Bool {
// The values for the assert_configuration call are:
// 0: Debug
// 1: Release
// 2: Fast
return Int32(Builtin.assert_configuration()) == 0
}
@usableFromInline @_transparent
internal func _isReleaseAssertConfiguration() -> Bool {
// The values for the assert_configuration call are:
// 0: Debug
// 1: Release
// 2: Fast
return Int32(Builtin.assert_configuration()) == 1
}
@_transparent
public // @testable
func _isFastAssertConfiguration() -> Bool {
// The values for the assert_configuration call are:
// 0: Debug
// 1: Release
// 2: Fast
return Int32(Builtin.assert_configuration()) == 2
}
@_transparent
public // @testable
func _isStdlibInternalChecksEnabled() -> Bool {
#if INTERNAL_CHECKS_ENABLED
return true
#else
return false
#endif
}
@usableFromInline @_transparent
internal func _fatalErrorFlags() -> UInt32 {
// The current flags are:
// (1 << 0): Report backtrace on fatal error
#if os(iOS) || os(tvOS) || os(watchOS)
return 0
#else
return _isDebugAssertConfiguration() ? 1 : 0
#endif
}
/// This function should be used only in the implementation of user-level
/// assertions.
///
/// This function should not be inlined because it is cold and inlining just
/// bloats code.
@usableFromInline
@inline(never)
@_semantics("programtermination_point")
internal func _assertionFailure(
_ prefix: StaticString, _ message: StaticString,
file: StaticString, line: UInt,
flags: UInt32
) -> Never {
prefix.withUTF8Buffer {
(prefix) -> Void in
message.withUTF8Buffer {
(message) -> Void in
file.withUTF8Buffer {
(file) -> Void in
_swift_stdlib_reportFatalErrorInFile(
prefix.baseAddress!, CInt(prefix.count),
message.baseAddress!, CInt(message.count),
file.baseAddress!, CInt(file.count), UInt32(line),
flags)
Builtin.int_trap()
}
}
}
Builtin.int_trap()
}
/// This function should be used only in the implementation of user-level
/// assertions.
///
/// This function should not be inlined because it is cold and inlining just
/// bloats code.
@usableFromInline
@inline(never)
@_semantics("programtermination_point")
internal func _assertionFailure(
_ prefix: StaticString, _ message: String,
file: StaticString, line: UInt,
flags: UInt32
) -> Never {
prefix.withUTF8Buffer {
(prefix) -> Void in
var message = message
message.withUTF8 {
(messageUTF8) -> Void in
file.withUTF8Buffer {
(file) -> Void in
_swift_stdlib_reportFatalErrorInFile(
prefix.baseAddress!, CInt(prefix.count),
messageUTF8.baseAddress!, CInt(messageUTF8.count),
file.baseAddress!, CInt(file.count), UInt32(line),
flags)
}
}
}
Builtin.int_trap()
}
/// This function should be used only in the implementation of user-level
/// assertions.
///
/// This function should not be inlined because it is cold and inlining just
/// bloats code.
@usableFromInline
@inline(never)
@_semantics("programtermination_point")
internal func _assertionFailure(
_ prefix: StaticString, _ message: String,
flags: UInt32
) -> Never {
prefix.withUTF8Buffer {
(prefix) -> Void in
var message = message
message.withUTF8 {
(messageUTF8) -> Void in
_swift_stdlib_reportFatalError(
prefix.baseAddress!, CInt(prefix.count),
messageUTF8.baseAddress!, CInt(messageUTF8.count),
flags)
}
}
Builtin.int_trap()
}
/// This function should be used only in the implementation of stdlib
/// assertions.
///
/// This function should not be inlined because it is cold and it inlining just
/// bloats code.
@usableFromInline
@inline(never)
@_semantics("programtermination_point")
internal func _fatalErrorMessage(
_ prefix: StaticString, _ message: StaticString,
file: StaticString, line: UInt,
flags: UInt32
) -> Never {
#if INTERNAL_CHECKS_ENABLED
prefix.withUTF8Buffer() {
(prefix) in
message.withUTF8Buffer() {
(message) in
file.withUTF8Buffer() {
(file) in
_swift_stdlib_reportFatalErrorInFile(
prefix.baseAddress!, CInt(prefix.count),
message.baseAddress!, CInt(message.count),
file.baseAddress!, CInt(file.count), UInt32(line),
flags)
}
}
}
#else
prefix.withUTF8Buffer() {
(prefix) in
message.withUTF8Buffer() {
(message) in
_swift_stdlib_reportFatalError(
prefix.baseAddress!, CInt(prefix.count),
message.baseAddress!, CInt(message.count),
flags)
}
}
#endif
Builtin.int_trap()
}
/// Prints a fatal error message when an unimplemented initializer gets
/// called by the Objective-C runtime.
@_transparent
public // COMPILER_INTRINSIC
func _unimplementedInitializer(className: StaticString,
initName: StaticString = #function,
file: StaticString = #file,
line: UInt = #line,
column: UInt = #column
) -> Never {
// This function is marked @_transparent so that it is inlined into the caller
// (the initializer stub), and, depending on the build configuration,
// redundant parameter values (#file etc.) are eliminated, and don't leak
// information about the user's source.
if _isDebugAssertConfiguration() {
className.withUTF8Buffer {
(className) in
initName.withUTF8Buffer {
(initName) in
file.withUTF8Buffer {
(file) in
_swift_stdlib_reportUnimplementedInitializerInFile(
className.baseAddress!, CInt(className.count),
initName.baseAddress!, CInt(initName.count),
file.baseAddress!, CInt(file.count),
UInt32(line), UInt32(column),
/*flags:*/ 0)
}
}
}
} else {
className.withUTF8Buffer {
(className) in
initName.withUTF8Buffer {
(initName) in
_swift_stdlib_reportUnimplementedInitializer(
className.baseAddress!, CInt(className.count),
initName.baseAddress!, CInt(initName.count),
/*flags:*/ 0)
}
}
}
Builtin.int_trap()
}
public // COMPILER_INTRINSIC
func _undefined<T>(
_ message: @autoclosure () -> String = String(),
file: StaticString = #file, line: UInt = #line
) -> T {
_assertionFailure("Fatal error", message(), file: file, line: line, flags: 0)
}
/// Called when falling off the end of a switch and the type can be represented
/// as a raw value.
///
/// This function should not be inlined because it is cold and inlining just
/// bloats code. It doesn't take a source location because it's most important
/// in release builds anyway (old apps that are run on new OSs).
@inline(never)
@usableFromInline // COMPILER_INTRINSIC
internal func _diagnoseUnexpectedEnumCaseValue<SwitchedValue, RawValue>(
type: SwitchedValue.Type,
rawValue: RawValue
) -> Never {
_assertionFailure("Fatal error",
"unexpected enum case '\(type)(rawValue: \(rawValue))'",
flags: _fatalErrorFlags())
}
/// Called when falling off the end of a switch and the value is not safe to
/// print.
///
/// This function should not be inlined because it is cold and inlining just
/// bloats code. It doesn't take a source location because it's most important
/// in release builds anyway (old apps that are run on new OSs).
@inline(never)
@usableFromInline // COMPILER_INTRINSIC
internal func _diagnoseUnexpectedEnumCase<SwitchedValue>(
type: SwitchedValue.Type
) -> Never {
_assertionFailure(
"Fatal error",
"unexpected enum case while switching on value of type '\(type)'",
flags: _fatalErrorFlags())
}
| apache-2.0 | 58a35a570be686190efdb6b0ec5100d2 | 28.426621 | 80 | 0.655184 | 4.311 | false | false | false | false |
bradhowes/SynthInC | SynthInC/Parameters.swift | 1 | 2649 | // Parameters.swift
// SynthInC
//
// Created by Brad Howes
// Copyright (c) 2016 Brad Howes. All rights reserved.
import Foundation
import SwiftyUserDefaults
// MARK: - Key definitions
extension DefaultsKeys {
static let randomSeed = DefaultsKey<Int>("randomSeed", defaultValue: 123123)
static let maxInstrumentCount = DefaultsKey<Int>("maxInstrumentCount", defaultValue: 32)
static let noteTimingSlop = DefaultsKey<Int>("noteTimingSlop", defaultValue: 30)
static let seqRepNorm = DefaultsKey<Double>("seqRepNorm", defaultValue: 30.0)
static let seqRepVar = DefaultsKey<Double>("seqRepVar", defaultValue: 20.0)
static let ensemble = DefaultsKey<Data?>("ensemble", defaultValue: nil)
static let performance = DefaultsKey<Data?>("performance", defaultValue: nil)
}
/**
Collection of static attributes that obtain/update application parameter settings from/in NSUserDefaults
*/
struct Parameters {
/// Seed value for random number generator
static var randomSeed: Int {
get { return Defaults[.randomSeed] }
set { Defaults[.randomSeed] = newValue }
}
/// Maximum number of instruments that we can create
static var maxInstrumentCount: Int {
get { return Defaults[.maxInstrumentCount] }
set { Defaults[.maxInstrumentCount] = newValue }
}
/// Variability in note ON accuracy
static var noteTimingSlop: Int {
get { return Defaults[.noteTimingSlop] }
set { Defaults[.noteTimingSlop] = newValue }
}
/// A norm number of repetitions of an "In C" phrase. Expressed in beats.
static var seqRepNorm: Double {
get { return Defaults[.seqRepNorm] }
set { Defaults[.seqRepNorm] = newValue }
}
/// The variation about the norm for repetitions of an "In C" phrase. Expressed in beats.
static var seqRepVar: Double {
get { return Defaults[.seqRepVar] }
set { Defaults[.seqRepVar] = newValue }
}
/// The latest ensemble
static var ensemble: Data? {
get { return Defaults[.ensemble] }
set { Defaults[.ensemble] = newValue }
}
/// The latest generated "In C" MIDI phrase sequences
static var performance: Data? {
get { return Defaults[.performance] }
set { Defaults[.performance] = newValue }
}
/**
Print out the current application settings.
*/
static func dump() {
print("randomSeed: \(randomSeed)")
print("maxInstrumentCount: \(maxInstrumentCount)")
print("noteTimingSlop: \(noteTimingSlop)")
print("seqRepNorm: \(seqRepNorm)")
print("seqRepVar: \(seqRepVar)")
}
}
| mit | c4deab277ec8d4e80e64e85717ded1a1 | 32.961538 | 105 | 0.665534 | 4.400332 | false | false | false | false |
ploden/viral-bible-ios | Viral-Bible-Ios/Viral-Bible-Ios/Classes/Controllers/BooksVC.swift | 1 | 2148 | //
// BooksVC.swift
// Viral-Bible-Ios
//
// Created by Philip Loden on 10/4/15.
// Copyright © 2015 Alan Young. All rights reserved.
//
import UIKit
class BooksVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var bibleVersion : BibleVersion?
var books : [BibleBook]?
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")
if let version = self.bibleVersion {
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
APIController.getBooks(version) { (books, error) -> () in
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
MBProgressHUD.hideHUDForView(self.view, animated: true)
self.books = books
self.tableView.reloadData()
})
}
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let books = self.books {
return books.count
} else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let aCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
if let books = self.books {
let book = books[indexPath.row]
aCell.titleLabel.text = book.bookName
}
return aCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let books = self.books {
let selectedBook = books[indexPath.row]
let vc = ChaptersVC.VB_instantiateFromStoryboard() as! ChaptersVC
vc.bibleBook = selectedBook
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
| mit | 5d0910b007886f3301515f69e84e67bb | 30.573529 | 119 | 0.61714 | 5.111905 | false | false | false | false |
libdx/SimpleLayout | SimpleLayout/Constraint.swift | 1 | 4010 | //
// Constraint.swift
// SimpleLayout
//
// Created by Alexander Ignatenko on 05/07/14.
// Copyright (c) 2014 Alexander Ignatenko. All rights reserved.
//
#if os(OSX)
import AppKit
#elseif os(iOS)
import UIKit
#endif
class ConstraintValue {
unowned let constraint: Constraint
let attribute: NSLayoutAttribute
let relation: NSLayoutRelation?
var multiplier: CGFloat = 1
var constant: CGFloat = 0
init(constraint: Constraint, attribute: NSLayoutAttribute) {
self.constraint = constraint
self.attribute = attribute
}
}
class Constraint {
let view: UIView
var value: ConstraintValue!
init(view: UIView) {
self.view = view
}
var left: ConstraintValue {
get {
self.value = ConstraintValue(constraint: self, attribute: .Left)
return self.value
}
}
var right: ConstraintValue {
get {
self.value = ConstraintValue(constraint: self, attribute: .Right)
return self.value
}
}
var top: ConstraintValue {
get {
self.value = ConstraintValue(constraint: self, attribute: .Top)
return self.value
}
}
var bottom: ConstraintValue {
get {
self.value = ConstraintValue(constraint: self, attribute: .Bottom)
return self.value
}
}
var leading: ConstraintValue {
get {
self.value = ConstraintValue(constraint: self, attribute: .Leading)
return self.value
}
}
var trailing: ConstraintValue {
get {
self.value = ConstraintValue(constraint: self, attribute: .Trailing)
return self.value
}
}
var width: ConstraintValue {
get {
self.value = ConstraintValue(constraint: self, attribute: .Width)
return self.value
}
}
var height: ConstraintValue {
get {
self.value = ConstraintValue(constraint: self, attribute: .Height)
return self.value
}
}
var centerX: ConstraintValue {
get {
self.value = ConstraintValue(constraint: self, attribute: .CenterX)
return self.value
}
}
var centerY: ConstraintValue {
get {
self.value = ConstraintValue(constraint: self, attribute: .CenterY)
return self.value
}
}
var baseline: ConstraintValue {
get {
self.value = ConstraintValue(constraint: self, attribute: .Baseline)
return self.value
}
}
var firstBaseline: ConstraintValue {
get {
self.value = ConstraintValue(constraint: self, attribute: .FirstBaseline)
return self.value
}
}
func create(rightValue: ConstraintValue, relation: NSLayoutRelation) -> NSLayoutConstraint {
return NSLayoutConstraint(
item: self.view,
attribute: self.value.attribute,
relatedBy: relation,
toItem: rightValue.constraint.view,
attribute: rightValue.attribute,
multiplier: rightValue.multiplier,
constant: rightValue.constant)
}
}
func constraint(
view1: UIView,
view2: UIView,
formula: (c1: Constraint, c2: Constraint) -> NSLayoutConstraint
) -> NSLayoutConstraint {
return formula(c1: Constraint(view: view1), c2: Constraint(view: view2))
}
func == (left: ConstraintValue, right: ConstraintValue) -> NSLayoutConstraint {
return left.constraint.create(right, relation: .Equal)
}
func <= (left: ConstraintValue, right: ConstraintValue) -> NSLayoutConstraint {
return left.constraint.create(right, relation: .LessThanOrEqual)
}
func >= (left: ConstraintValue, right: ConstraintValue) -> NSLayoutConstraint {
return left.constraint.create(right, relation: .GreaterThanOrEqual)
}
func + (attribute: ConstraintValue, constant: CGFloat) -> ConstraintValue {
attribute.constant = constant
return attribute
}
func * (attribute: ConstraintValue, multiplier: CGFloat) -> ConstraintValue {
attribute.multiplier = multiplier
return attribute
}
| mit | 1d6ddd8fc152041e6da49c774db71057 | 23.601227 | 96 | 0.64813 | 4.426049 | false | false | false | false |
apple/swift-format | Sources/swift-format/Subcommands/Format.swift | 1 | 1575 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import ArgumentParser
extension SwiftFormatCommand {
/// Formats one or more files containing Swift code.
struct Format: ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "Format Swift source code",
discussion: "When no files are specified, it expects the source from standard input.")
/// Whether or not to format the Swift file in-place.
///
/// If specified, the current file is overwritten when formatting.
@Flag(
name: .shortAndLong,
help: "Overwrite the current file when formatting.")
var inPlace: Bool = false
@OptionGroup()
var formatOptions: LintFormatOptions
func validate() throws {
if inPlace && formatOptions.paths.isEmpty {
throw ValidationError("'--in-place' is only valid when formatting files")
}
}
func run() throws {
let frontend = FormatFrontend(lintFormatOptions: formatOptions, inPlace: inPlace)
frontend.run()
if frontend.diagnosticsEngine.hasErrors { throw ExitCode.failure }
}
}
}
| apache-2.0 | 94c4d556bd897f36d4605476fdd4de59 | 34 | 92 | 0.629841 | 5.015924 | false | false | false | false |
necrowman/CRLAlamofireFuture | Examples/SimpleTvOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleTvOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleTvOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleTvOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleTvOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleTvOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleTvOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleIOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Examples/SimpleIOSCarthage/Carthage/Checkouts/CRLAlamofireFuture/Carthage/Checkouts/Boilerplate/Boilerplate/C.swift | 111 | 4501 | //===--- C.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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
#if swift(>=3.0)
#else
public typealias OpaquePointer = COpaquePointer
public extension OpaquePointer {
public init<T>(bitPattern:Unmanaged<T>) {
self = bitPattern.toOpaque()
}
}
public extension UnsafePointer {
public typealias Pointee = Memory
/// Access the `Pointee` instance referenced by `self`.
///
/// - Precondition: the pointee has been initialized with an instance of
/// type `Pointee`.
public var pointee: Pointee {
get {
return self.memory
}
}
}
public extension UnsafeMutablePointer {
public typealias Pointee = Memory
/// Allocate and point at uninitialized aligned memory for `count`
/// instances of `Pointee`.
///
/// - Postcondition: The pointee is allocated, but not initialized.
public init(allocatingCapacity count: Int) {
self = UnsafeMutablePointer.alloc(count)
}
/// Deallocate uninitialized memory allocated for `count` instances
/// of `Pointee`.
///
/// - Precondition: The memory is not initialized.
///
/// - Postcondition: The memory has been deallocated.
public func deallocateCapacity(num: Int) {
self.dealloc(num)
}
/// Access the `Pointee` instance referenced by `self`.
///
/// - Precondition: the pointee has been initialized with an instance of
/// type `Pointee`.
public var pointee: Pointee {
get {
return self.memory
}
nonmutating set {
self.memory = newValue
}
}
public func initialize(with newValue: Pointee, count: Int = 1) {
assert(count != 1, "NOT IMPLEMENTED: currently can initialize with 1 value only")
self.initialize(newValue)
}
/// De-initialize the `count` `Pointee`s starting at `self`, returning
/// their memory to an uninitialized state.
///
/// - Precondition: The `Pointee`s at `self..<self + count` are
/// initialized.
///
/// - Postcondition: The memory is uninitialized.
public func deinitialize(count count: Int = 1) {
self.destroy(count)
}
}
/// Returns an `UnsafePointer` to the storage used for `object`. There's
/// not much you can do with this other than use it to identify the
/// object.
public func unsafeAddress(of object: AnyObject) -> UnsafePointer<Swift.Void> {
return unsafeAddressOf(object)
}
/// Returns the bits of `x`, interpreted as having type `U`.
///
/// - Warning: Breaks the guarantees of Swift's type system; use
/// with extreme care. There's almost always a better way to do
/// anything.
///
public func unsafeBitCast<T, U>(x: T, to: U.Type) -> U {
return unsafeBitCast(x, to)
}
/// - returns: `x as T`.
///
/// - Precondition: `x is T`. In particular, in -O builds, no test is
/// performed to ensure that `x` actually has dynamic type `T`.
///
/// - Warning: Trades safety for performance. Use `unsafeDowncast`
/// only when `x as T` has proven to be a performance problem and you
/// are confident that, always, `x is T`. It is better than an
/// `unsafeBitCast` because it's more restrictive, and because
/// checking is still performed in debug builds.
public func unsafeDowncast<T : AnyObject>(x: AnyObject, to: T.Type) -> T {
return unsafeDowncast(x)
}
#endif | mit | 67692bb6cb808b1411227bf79d1dace6 | 35.306452 | 93 | 0.577205 | 4.834586 | false | false | false | false |
devlucky/Kakapo | README.playground/Contents.swift | 1 | 3734 | import Foundation
import Kakapo // NOTE: Build "Kakapo iOS" for a 64 bit simulator to successfully import the dynamic framework
/*:
# Kakapo
## Serializable
Serializable objects are mirrored to be converted to a `Dictionary`
*/
struct Parrot: Serializable {
let name: String
}
let kakapo = Parrot(name: "Kakapo")
kakapo.serialized()
/*:
All properties are recursively serialized when needed. Only primitive values, arrays, dictionaries and string are allowed to be converted to json so other values must also be `Serializable`
*/
struct Zoo: Serializable {
let parrots: [Parrot]
}
let zoo = Zoo(parrots: [kakapo])
let json = String(data: zoo.toData()!, encoding: .utf8)!
//: ## CustomSerializable
struct CustomZoo: CustomSerializable {
let parrots: [Parrot]
// this is a really simple `CustomSerializable` that could be achieved with `Serializable` by just using a property "species" (dictionary).
// See JSONAPI implementation for more complex, real life, examples.
func customSerialized(transformingKeys keyTransformer: KeyTransformer?) -> Any? {
// transformer will be not nill when this object is wrapped into a `SerializationTransformer` (e.g. `SnakeCaseTransformer`)... if the object doesn't need key transformation just ignore it
let key: (String) -> (String) = { (key) in
return keyTransformer?(key) ?? key
}
let species = [key("parrot"): parrots.serialized() ?? []]
return [key("species"): species]
}
}
let customZoo = CustomZoo(parrots: [kakapo])
let customZooJson = String(data: customZoo.toData()!, encoding: .utf8)!
//: ## JSON API
struct Dog: JSONAPIEntity {
let id: String
let name: String
}
struct Person: JSONAPIEntity {
let id: String
let name: String
let dog: Dog
}
let person = Person(id: "1", name: "Alex", dog: Dog(id: "2", name: "Joan"))
let serializable = JSONAPISerializer(person, topLevelMeta: ["foo": "bar"])
let personJson = String(data: serializable.toData()!, encoding: .utf8)!
//: ## Router
let router = Router.register("https://kakapo.com/api/v1")
router.get("zoo/:animal") { (request) -> Serializable? in
if let animal = request.components["animal"], animal == "parrot" {
return Parrot(name: "Kakapo") // or use Store for dynamic stuff!
}
return Response(statusCode: 404, body: ["error": "Animal not found"])
}
//: request **GET** `https://kakapo.com/api/v1/parrot`
//: will return `{"name": "Kakapo"}`
//: ## Store
let store = Store()
struct Author: Storable, Serializable {
let id: String
let name: String
init(id: String, store: Store) {
self.id = id
self.name = String(arc4random()) // use Fakery!
}
}
struct Article: Storable, Serializable {
let id: String
let text: String
let author: Author
init(id: String, store: Store) {
self.id = id
self.text = String(arc4random()) // use Fakery!
author = store.insert { (id) -> Author in
return Author(id: id, store: store) // id must always come from the store
}
}
}
//: Create 10 random article
let articles = store.create(Article.self, number: 10)
//: Get all articles
router.get("articles") { (request) -> Serializable? in
return store.findAll(Article.self)
}
//: Get all articles from the given author
router.get("articles/:author_id") { (request) -> Serializable? in
return store.filter(Article.self) { (article) -> Bool in
return article.author.id == request.components["author_id"]
}
}
//: Create an article
router.post("article") { (request) -> Serializable? in
return store.insert { (id) -> Article in
return Article(id: id, store: store)
}
}
| mit | 934f1e1e3d5290a97ec7d876b2b71c3b | 29.859504 | 195 | 0.660418 | 3.752764 | false | false | false | false |
practicalswift/swift | test/expr/capture/top-level-guard.swift | 34 | 1297 | // RUN: %target-swift-frontend -dump-ast %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir %s > /dev/null
// RUN: %target-swift-frontend -dump-ast -DVAR %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir -DVAR %s > /dev/null
// CHECK: (top_level_code_decl
// CHECK: (guard_stmt
#if VAR
guard var x = Optional(0) else { fatalError() }
#else
guard let x = Optional(0) else { fatalError() }
#endif
// CHECK: (top_level_code_decl
_ = 0 // intervening code
// CHECK-LABEL: (func_decl{{.*}}"function()" interface type='() -> ()' access=internal captures=(x<direct>)
func function() {
_ = x
}
// CHECK-LABEL: (closure_expr
// CHECK: location={{.*}}top-level-guard.swift:[[@LINE+3]]
// CHECK: captures=(x<direct>)
// CHECK: (var_decl{{.*}}"closure"
let closure: () -> Void = {
_ = x
}
// CHECK-LABEL: (capture_list
// CHECK: location={{.*}}top-level-guard.swift:[[@LINE+5]]
// CHECK: (closure_expr
// CHECK: location={{.*}}top-level-guard.swift:[[@LINE+3]]
// CHECK: captures=(x<direct>)
// CHECK: (var_decl{{.*}}"closureCapture"
let closureCapture: () -> Void = { [x] in
_ = x
}
// CHECK-LABEL: (defer_stmt
// CHECK-NEXT: (func_decl{{.*}}implicit "$defer()" interface type='() -> ()' access=fileprivate captures=(x<direct><noescape>)
defer {
_ = x
}
#if VAR
x = 5
#endif
| apache-2.0 | 33a5b215dbef9cbd4032658399f82f04 | 25.469388 | 126 | 0.61835 | 2.974771 | false | false | false | false |
Acumen004/MovieTime | Movies/NetworkController.swift | 1 | 1256 | //
// NetworkController.swift
// ImageSearch
//
// Created by Appinventiv on 21/02/17.
// Copyright © 2017 Appinventiv. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
typealias JSONDictionary = [String:Any]
class NetworkController {
func GET(URL : String,
parameters : JSONDictionary,
headers : JSONDictionary? = nil,
success : @escaping (_ json : JSON) -> (),
failure : @escaping (_ error : Error) -> ()) {
Alamofire.request(URL,
method: .get,
parameters: parameters,
encoding: URLEncoding.default,
headers: nil).responseJSON { (response :DataResponse<Any>) in
if let value = response.value as? [String:Any] {
let json = JSON(value)
success(json)
} else if let error = response.error {
failure(error)
}
}
}
}
| mit | 9d01c1b3e9ac07fbe45ae434d7d27d0e | 28.880952 | 87 | 0.427092 | 6.004785 | false | false | false | false |
anas10/AABlurModalView | Source/AABlurModalView.swift | 1 | 5186 | //
// AABlurModalView.swift
// AABlurModalView
//
// Created by Anas Ait Ali on 30/08/2016.
// Copyright © 2016 Anas AIT ALI. All rights reserved.
//
import UIKit
enum AABlurModalViewError: Error {
case nibViewNotFound
}
open class AABlurModalView: UIView {
// TODO : Allow a contentSize change after init
open var contentSize : CGSize?
open var blurEffectStyle: UIBlurEffectStyle = .dark
open var identifier: String?
open var contentView : UIView!
fileprivate var backgroundImage : UIImageView!
public init(nibName: String, bundle: Bundle?) throws {
super.init(frame: UIScreen.main.bounds)
let nib = UINib(nibName: nibName, bundle: bundle)
let nibObjs = nib.instantiate(withOwner: nil, options: nil)
guard let nibView = nibObjs.last as? UIView else { throw AABlurModalViewError.nibViewNotFound }
commonInit(nibView, contentSize: nil)
}
public init(contentView: UIView, contentSize: CGSize? = nil) {
super.init(frame: UIScreen.main.bounds)
commonInit(contentView, contentSize: contentSize)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit(UIView(), contentSize: nil)
}
open func show(_ view: UIView?? = UIApplication.shared.delegate?.window) {
self.frame = UIScreen.main.bounds
setupContentView()
// TODO : Add alternative solution if the snapshot fails
backgroundImage.image = snapshot()
let blurEffect = UIBlurEffect(style: blurEffectStyle)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = backgroundImage.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
vibrancyEffectView.frame = backgroundImage.bounds
vibrancyEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
blurEffectView.contentView.addSubview(vibrancyEffectView)
backgroundImage.addSubview(blurEffectView)
view??.addSubview(self)
}
open func hide() {
self.backgroundImage.subviews.forEach { $0.removeFromSuperview() }
self.removeFromSuperview()
}
open static func hideBlurModalView(_ identifier: String?) {
if let identifier = identifier {
UIApplication.shared.delegate?.window??.subviews
.filter { $0.isKind(of: AABlurModalView.self) }
.filter { ($0 as? AABlurModalView)?.identifier == identifier }
.forEach { $0.hideBlurModalView() }
}
}
fileprivate func commonInit(_ contentView: UIView, contentSize: CGSize? = nil) {
self.isOpaque = true
self.alpha = 1
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.backgroundImage = UIImageView(frame: self.bounds)
self.backgroundImage.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.addSubview(backgroundImage)
self.contentView = contentView
self.identifier = contentView.accessibilityIdentifier
self.contentSize = contentSize
}
fileprivate func setupContentView() {
contentView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(contentView)
let viewDict : [String: Any] = ["cV":contentView, "view":self]
let cSize = contentSize ?? contentView.frame.size
let metrics = ["cVHeight": cSize.height, "cVWidth": cSize.width]
[NSLayoutConstraint.constraints(withVisualFormat: "V:[cV(cVHeight)]", options: [], metrics: metrics, views: viewDict),
NSLayoutConstraint.constraints(withVisualFormat: "H:[cV(cVWidth)]", options: [], metrics: metrics, views: viewDict),
NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-(<=1)-[cV]", options: NSLayoutFormatOptions.alignAllCenterY, metrics: nil, views: viewDict),
NSLayoutConstraint.constraints(withVisualFormat: "V:[view]-(<=1)-[cV]", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: viewDict)
].forEach { NSLayoutConstraint.activate($0) }
}
fileprivate func snapshot() -> UIImage? {
let appDelegate = UIApplication.shared.delegate
guard let window = appDelegate?.window else { return nil }
UIGraphicsBeginImageContextWithOptions(window!.bounds.size, false, window!.screen.scale)
window!.drawHierarchy(in: window!.bounds, afterScreenUpdates: false)
let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return snapshotImage
}
}
public extension UIView {
public func hideBlurModalView(_ identifier: String? = nil) {
if identifier != nil {
AABlurModalView.hideBlurModalView(identifier)
} else {
if let blurModal = self.superview as? AABlurModalView {
blurModal.hide()
} else if let blurModal = self as? AABlurModalView {
blurModal.hide()
}
}
}
}
| mit | 41b6d3f1c27fbb2176a53d25138c4a0e | 37.407407 | 163 | 0.675217 | 5.019361 | false | false | false | false |
crossroadlabs/ExpressCommandLine | swift-express/Commands/Version.swift | 1 | 1344 | //===--- Version.swift --------------------------------------------------------===//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express Command Line
//
//Swift Express Command Line 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.
//
//Swift Express Command Line 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 Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>.
//
//===---------------------------------------------------------------------------===//
import Commandant
import Result
import Foundation
struct VersionCommand: CommandType {
let verb = "version"
let function = "Display the current version of Swift Express Command Line"
func run(options: NoOptions<SwiftExpressError>) -> Result<(), SwiftExpressError> {
print("Swift Express Command Line \(CMD_LINE_VERSION)")
return .Success(())
}
}
| gpl-3.0 | cedc16c22748a25c6206ee9fe94a5561 | 38.529412 | 86 | 0.653274 | 4.905109 | false | false | false | false |
mzaks/FlatBuffersSwift | FlatBuffersSwiftTests/FBReaderTest.swift | 2 | 12335 | //
// ReaderTest.swift
// FBSwift3
//
// Created by Maxim Zaks on 28.10.16.
// Copyright © 2016 Maxim Zaks. All rights reserved.
//
import XCTest
@testable import FlatBuffersSwift
class FlatBuffersReaderTest: XCTestCase {
func testReadDirect() {
let data = createSimpleObject()
let reader = FlatBuffersMemoryReader(data: data)
let objectOffset = reader.rootObjectOffset
XCTAssertEqual(objectOffset, 16)
let stringOffset = reader.offset(objectOffset: objectOffset!, propertyIndex: 1)
XCTAssertEqual(stringOffset, 28)
let stringBuffer = reader.stringBuffer(stringOffset: stringOffset)
XCTAssertEqual(stringBuffer?§, "max")
let booleanValue1 : Bool? = reader.get(objectOffset: objectOffset!, propertyIndex: 0)
XCTAssertTrue(booleanValue1!)
let booleanValue2 : Bool? = reader.get(objectOffset: objectOffset!, propertyIndex: 2)
XCTAssertNil(booleanValue2)
let booleanValueDefault : Bool = reader.get(objectOffset: objectOffset!, propertyIndex: 2, defaultValue: false)
XCTAssertFalse(booleanValueDefault)
}
func testReadDirectWithoutCopy() {
let data = createSimpleObject()
let reader = FlatBuffersMemoryReader(data: data, withoutCopy: true)
let objectOffset = reader.rootObjectOffset
XCTAssertEqual(objectOffset, 16)
let stringOffset = reader.offset(objectOffset: objectOffset!, propertyIndex: 1)
XCTAssertEqual(stringOffset, 28)
let stringBuffer = reader.stringBuffer(stringOffset: stringOffset)
XCTAssertEqual(stringBuffer?§, "max")
let booleanValue1 : Bool? = reader.get(objectOffset: objectOffset!, propertyIndex: 0)
XCTAssertTrue(booleanValue1!)
let booleanValue2 : Bool? = reader.get(objectOffset: objectOffset!, propertyIndex: 2)
XCTAssertNil(booleanValue2)
let booleanValueDefault : Bool = reader.get(objectOffset: objectOffset!, propertyIndex: 2, defaultValue: false)
XCTAssertFalse(booleanValueDefault)
}
func testReadDirectWithVector() {
let data = createObjectWithVectors()
let reader = FlatBuffersMemoryReader(data: data)
let objectOffset = reader.rootObjectOffset
XCTAssertEqual(objectOffset, 12)
let sVectorOffset = reader.offset(objectOffset: objectOffset!, propertyIndex: 0)
XCTAssertEqual(sVectorOffset, 32)
let sVectorLength = reader.vectorElementCount(vectorOffset: sVectorOffset)
XCTAssertEqual(sVectorLength, 3)
let sOffset1 = reader.vectorElementOffset(vectorOffset: sVectorOffset!, index: 0)
XCTAssertEqual(sOffset1, 48)
let sOffset2 = reader.vectorElementOffset(vectorOffset: sVectorOffset!, index: 1)
XCTAssertEqual(sOffset2, 56)
let sOffset3 = reader.vectorElementOffset(vectorOffset: sVectorOffset!, index: 2)
XCTAssertEqual(sOffset3, 64)
let stringBuffer1 = reader.stringBuffer(stringOffset: sOffset1)
XCTAssertEqual(stringBuffer1?§, "max3")
let stringBuffer2 = reader.stringBuffer(stringOffset: sOffset2)
XCTAssertEqual(stringBuffer2?§, "max2")
let stringBuffer3 = reader.stringBuffer(stringOffset: sOffset3)
XCTAssertEqual(stringBuffer3?§, "max1")
let bVectorOffset = reader.offset(objectOffset: objectOffset!, propertyIndex: 1)
XCTAssertEqual(bVectorOffset, 24)
let bVectorLength = reader.vectorElementCount(vectorOffset: bVectorOffset)
XCTAssertEqual(bVectorLength, 2)
let b1 : Bool? = reader.vectorElementScalar(vectorOffset: bVectorOffset!, index: 0)
XCTAssertEqual(b1, false)
let b2 : Bool? = reader.vectorElementScalar(vectorOffset: bVectorOffset!, index: 1)
XCTAssertEqual(b2, true)
}
func testReadInvalidRootDirect() {
let data : [UInt8] = [12]
let reader = FlatBuffersMemoryReader(buffer: UnsafeRawPointer(data), count: data.count)
let objectOffset = reader.rootObjectOffset
XCTAssertNil(objectOffset)
}
func testReadPropertyWithHighPropertyIndex() {
let data = createObjectWithVectors()
let reader = FlatBuffersMemoryReader(data: Data(data))
let root = reader.rootObjectOffset
let i : Int? = reader.get(objectOffset: root!, propertyIndex: 10)
XCTAssertNil(i)
}
func testReadPropertyWithLowPropertyIndex() {
let data = createObjectWithVectors()
let reader = FlatBuffersMemoryReader(data: data)
let root = reader.rootObjectOffset
let i : Int? = reader.get(objectOffset: root!, propertyIndex: -1)
XCTAssertNil(i)
}
func testReadPropertyOffestWithWrongPropertyIndex() {
let data = createObjectWithVectors()
let reader = FlatBuffersMemoryReader(data: data)
let root = reader.rootObjectOffset
let o = reader.offset(objectOffset: root!, propertyIndex: -1)
XCTAssertNil(o)
}
func testReadPropertyWhereVTableReferenceIsBroken() {
let data : [UInt8] = [4,0,0,0,5]
let reader = FlatBuffersMemoryReader(data: Data(data))
let root = reader.rootObjectOffset
let i : Int? = reader.get(objectOffset: root!, propertyIndex: 0)
XCTAssertNil(i)
}
func testReadFromFile() {
var data = createSimpleObject()
let (fh, fileUrl) = createTempFileHandle()
defer {
fh.closeFile()
try!FileManager.default.removeItem(at: fileUrl as URL)
}
fh.write(data)
let reader = FlatBuffersFileReader(fileHandle : fh)
let objectOffset = reader.rootObjectOffset
XCTAssertEqual(objectOffset, 16)
let stringOffset = reader.offset(objectOffset: objectOffset!, propertyIndex: 1)
XCTAssertEqual(stringOffset, 28)
let stringBuffer = reader.stringBuffer(stringOffset: stringOffset)
XCTAssertEqual(stringBuffer?§, "max")
let booleanValue1 : Bool? = reader.get(objectOffset: objectOffset!, propertyIndex: 0)
XCTAssertTrue(booleanValue1!)
let booleanValue2 : Bool? = reader.get(objectOffset: objectOffset!, propertyIndex: 2)
XCTAssertNil(booleanValue2)
// XCTAssertFalse(reader.hasProperty(objectOffset!, propertyIndex: 2))
let booleanValueDefault : Bool = reader.get(objectOffset: objectOffset!, propertyIndex: 2, defaultValue: false)
XCTAssertFalse(booleanValueDefault)
}
func testFromFileWithVector() {
let data = createObjectWithVectors()
let (fh, fileUrl) = createTempFileHandle()
defer {
fh.closeFile()
try!FileManager.default.removeItem(at: fileUrl as URL)
}
fh.write(data)
let reader = FlatBuffersFileReader(fileHandle : fh)
let objectOffset = reader.rootObjectOffset
XCTAssertEqual(objectOffset, 12)
let sVectorOffset = reader.offset(objectOffset: objectOffset!, propertyIndex: 0)
XCTAssertEqual(sVectorOffset, 32)
let sVectorLength = reader.vectorElementCount(vectorOffset: sVectorOffset)
XCTAssertEqual(sVectorLength, 3)
let sOffset1 = reader.vectorElementOffset(vectorOffset: sVectorOffset!, index: 0)
XCTAssertEqual(sOffset1, 48)
let sOffset2 = reader.vectorElementOffset(vectorOffset: sVectorOffset!, index: 1)
XCTAssertEqual(sOffset2, 56)
let sOffset3 = reader.vectorElementOffset(vectorOffset: sVectorOffset!, index: 2)
XCTAssertEqual(sOffset3, 64)
let stringBuffer1 = reader.stringBuffer(stringOffset: sOffset1)
XCTAssertEqual(stringBuffer1?§, "max3")
let stringBuffer2 = reader.stringBuffer(stringOffset: sOffset2)
XCTAssertEqual(stringBuffer2?§, "max2")
let stringBuffer3 = reader.stringBuffer(stringOffset: sOffset3)
XCTAssertEqual(stringBuffer3?§, "max1")
let bVectorOffset = reader.offset(objectOffset: objectOffset!, propertyIndex: 1)
XCTAssertEqual(bVectorOffset, 24)
let bVectorLength = reader.vectorElementCount(vectorOffset: bVectorOffset)
XCTAssertEqual(bVectorLength, 2)
let b1 : Bool? = reader.vectorElementScalar(vectorOffset: bVectorOffset!, index: 0)
XCTAssertEqual(b1, false)
let b2 : Bool? = reader.vectorElementScalar(vectorOffset: bVectorOffset!, index: 1)
XCTAssertEqual(b2, true)
}
func testReadInvalidRootFromFile() {
let data : [UInt8] = [12]
let (fh, fileUrl) = createTempFileHandle()
defer {
fh.closeFile()
try!FileManager.default.removeItem(at: fileUrl as URL)
}
fh.write(Data(bytes: data))
let reader = FlatBuffersFileReader(fileHandle : fh)
let objectOffset = reader.rootObjectOffset
XCTAssertNil(objectOffset)
}
func createSimpleObject() -> Data {
let fbb = FlatBuffersBuilder(options:FlatBuffersBuilderOptions(
initialCapacity : 1,
uniqueStrings : true,
uniqueTables : true,
uniqueVTables : true,
forceDefaults : false,
nullTerminatedUTF8 : false)
)
let sOffset = try! fbb.insert(value: "max")
try! fbb.startObject(withPropertyCount: 3)
try! fbb.insert(value: true, defaultValue: false, toStartedObjectAt: 0)
try! fbb.insert(offset: sOffset, toStartedObjectAt: 1)
let oOffset = try! fbb.endObject()
try! fbb.finish(offset: oOffset, fileIdentifier: nil)
let data = fbb.makeData
return data
}
func createObjectWithVectors() -> Data{
let fbb = FlatBuffersBuilder(options:FlatBuffersBuilderOptions(
initialCapacity : 1,
uniqueStrings : true,
uniqueTables : true,
uniqueVTables : true,
forceDefaults : false,
nullTerminatedUTF8 : false)
)
let sOffset1 = try! fbb.insert(value: "max1")
let sOffset2 = try! fbb.insert(value: "max2")
let sOffset3 = try! fbb.insert(value: "max3")
try! fbb.startVector(count: 3, elementSize: 4)
try!fbb.insert(offset: sOffset1)
try!fbb.insert(offset: sOffset2)
try!fbb.insert(offset: sOffset3)
let sVectorOffset = fbb.endVector()
try! fbb.startVector(count: 2, elementSize: 1)
fbb.insert(value: true)
fbb.insert(value: false)
let bVectorOffset = fbb.endVector()
try! fbb.startObject(withPropertyCount: 2)
try! fbb.insert(offset: sVectorOffset, toStartedObjectAt: 0)
try! fbb.insert(offset: bVectorOffset, toStartedObjectAt: 1)
let oOffset = try! fbb.endObject()
try! fbb.finish(offset: oOffset, fileIdentifier: nil)
let data = fbb.makeData
return data
}
func createTempFileHandle() -> (handle : FileHandle, url : NSURL){
// The template string:
let template = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("file.XXXXXX") as NSURL
// Fill buffer with a C string representing the local file system path.
var buffer = [Int8](repeating: 0, count: Int(PATH_MAX))
template.getFileSystemRepresentation(&buffer, maxLength: buffer.count)
// Create unique file name (and open file):
let fd = mkstemp(&buffer)
let url = NSURL(fileURLWithFileSystemRepresentation: buffer, isDirectory: false, relativeTo: nil)
print(url.path!)
return (FileHandle(fileDescriptor: fd, closeOnDealloc: true), url)
}
}
| mit | ef1438045b9536379272680314ed15ce | 36.012012 | 119 | 0.632373 | 4.95577 | false | false | false | false |
yaakov-h/AirportSign | Airport Sign/SignViewController.swift | 1 | 2062 | import UIKit
class SignViewController: UIViewController, UIGestureRecognizerDelegate {
var statusBarVisible = false
@IBOutlet weak var label : UILabel?
override func viewDidLoad() {
super.viewDidLoad()
if let label = label {
if let text = loadText() {
label.text = text
}
else if let text = label.text {
saveText(text)
}
}
}
func loadText() -> String? {
let defaults = NSUserDefaults.standardUserDefaults()
if let value = defaults.stringForKey("SignageText") {
if !value.isEmpty {
return value
}
}
return nil
}
func saveText(text : String) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(text, forKey: "SignageText")
defaults.synchronize()
}
@IBAction func handleLongPress(recognizer: UIGestureRecognizer) {
self.performSegueWithIdentifier("ShowEditController", sender: self)
}
@IBAction func toggleStatusBarVisible(recognizer: UIGestureRecognizer) {
statusBarVisible = !statusBarVisible
self .setNeedsStatusBarAppearanceUpdate()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
if
identifier == "ShowEditController",
let navigationController = segue.destinationViewController as? UINavigationController,
let editController = navigationController.topViewController as? SignEditViewController {
editController.delegate = self
}
}
}
override func prefersStatusBarHidden() -> Bool {
return !statusBarVisible
}
}
extension SignViewController : SignEditViewControllerDelegate {
func getExistingText(controller: SignEditViewController) -> String {
return loadText() ?? ""
}
func controller(controller: SignEditViewController, didFinishedEditingWithText text: String) {
saveText(text)
if let label = label {
label.text = text
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func controllerDidCancelEditing(controller: SignEditViewController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | 0b50d166806e2ace159da8d44035a5f4 | 24.45679 | 95 | 0.742483 | 4.295833 | false | false | false | false |
xmartlabs/Swift-Project-Template | Project-iOS/XLProjectName/XLProjectName/Networking/Routes/UserRoute.swift | 1 | 1711 | //
// NetworkUser.swift
// XLProjectName
//
// Created by XLAuthorName ( XLAuthorWebsite )
// Copyright © 2020 XLOrganizationName. All rights reserved.
//
import Foundation
import Alamofire
struct Route {}
extension Route {
struct User {
struct Login: RouteType, CustomUrlRequestSetup {
let username: String
let password: String
let method = Alamofire.HTTPMethod.get
let path = ""
// MARK: - CustomUrlRequestSetup
func urlRequestSetup(_ request: inout URLRequest) {
let utf8 = "\(username):\(password)".data(using: String.Encoding.utf8)
let base64 = utf8?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
guard let encodedString = base64 else {
return
}
request.setValue("Basic \(encodedString)", forHTTPHeaderField: "Authorization")
}
}
struct GetInfo: RouteType {
let username: String
let method = Alamofire.HTTPMethod.get
var path: String { return "users/\(username)" }
}
struct Followers: RouteType {
let username: String
let method = Alamofire.HTTPMethod.get
var path: String { return "users/\(username)/followers" }
}
struct Repositories: RouteType {
let username: String
let method = Alamofire.HTTPMethod.get
var path: String { return "users/\(username)/repos" }
}
}
}
| mit | f5c50c8aaa78548fa00bf2f71159480c | 28.482759 | 106 | 0.532749 | 5.463259 | false | false | false | false |
seamgen/SeamgenKit-Swift | SeamgenKit/Classes/UI/MKMapSnapshot+Extensions.swift | 1 | 1266 | //
// MKMapSnapshot+Extensions.swift
// SeamgenKit
//
// Created by Sam Gerardi on 12/13/16.
// Copyright © 2016 Seamgen. All rights reserved.
//
import UIKit
import MapKit
extension MKMapSnapshot {
/// Draws a standard pin annotation at a given coordinate.
///
/// - Parameter coordinate: The location of the pin in the image.
/// - Returns: The snapshot image with the pin annotation.
public func imageWithAnnotation(atCoordinate coordinate: CLLocationCoordinate2D) -> UIImage? {
let pin = MKPinAnnotationView(annotation: nil, reuseIdentifier: "")
guard let pinImage = pin.image else { return image }
UIGraphicsBeginImageContextWithOptions(image.size, true, image.scale)
image.draw(at: CGPoint.zero)
var annotationPoint = point(for: coordinate)
annotationPoint.x -= pin.bounds.width / 2.0
annotationPoint.y -= pin.bounds.height / 2.0
annotationPoint.x += pin.centerOffset.x
annotationPoint.y += pin.centerOffset.y
pinImage.draw(at: annotationPoint)
let annotatedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return annotatedImage
}
}
| mit | 252936f76c82426d1f2903a4acc609a0 | 29.853659 | 98 | 0.660079 | 4.755639 | false | false | false | false |
notonthehighstreet/swift-mysql | Sources/MySQL/MySQLConnection.swift | 1 | 6909 | import Foundation
import CMySQLClient
// Represents an active connection to a MySQL database.
public class MySQLConnection : MySQLConnectionProtocol {
private var uuid: Double
private var connection: UnsafeMutablePointer<MYSQL>? = nil
private var result:UnsafeMutablePointer<MYSQL_RES>? = nil
public init() {
uuid = NSDate().timeIntervalSince1970
}
}
extension MySQLConnection {
public func equals(otherObject: MySQLConnectionProtocol) -> Bool {
return uuid == (otherObject as! MySQLConnection).uuid
}
/**
Does the current connection have an open connection to the database?
- Returns: true if active connection, false if connection closed
*/
public func isConnected() -> Bool {
if (mysql_ping(connection) != 0) {
return false
} else {
return true
}
}
/**
Open a connection to the database with the given parameters, in the instance of a failed connection the connect method throws MySQLError.
- Parameters:
- host: The host name or ip address of the database.
- user: The username to use for the connection.
- password: The password to use for the connection.
*/
public func connect(host: String, user: String, password: String) throws {
return try connect(host: host, user: user, password: password, port: 3306, database: "")
}
/**
Open a connection to the database with the given parameters, in the instance of a failed connection the connect method throws MySQLError.
- Parameters:
- host: The host name or ip address of the database.
- user: The username to use for the connection.
- password: The password to use for the connection.
- port: The port to be used for the connection
*/
public func connect(host: String, user: String, password: String, port: Int) throws {
return try connect(host: host, user: user, password: password, port: port, database: "")
}
/**
Open a connection to the database with the given parameters, in the instance of a failed connection the connect method throws MySQLError.
- Parameters:
- host: The host name or ip address of the database
- user: The username to use for the connection
- password: The password to use for the connection
- port: The port to be used for the connection
- database: The database to connect to
*/
public func connect(host: String, user: String, password: String, port: Int, database: String) throws {
connection = CMySQLClient.mysql_init(nil);
if connection == nil {
print("Error: Unable to create connection")
throw MySQLError.UnableToCreateConnection
}
if CMySQLClient.mysql_real_connect(connection, host, user, password, database, UInt32(port), nil, CMySQLClient.CLIENT_MULTI_STATEMENTS) == nil {
print("Error: Unable to connect to database")
close()
throw MySQLError.UnableToCreateConnection
}
}
/**
Close the connection.
*/
public func close() {
clearResult()
CMySQLClient.mysql_close(connection)
}
/**
Retrieve information for the underlying client library version.
- Returns: String representing the current client version.
*/
public func client_info() -> String? {
return String(cString: CMySQLClient.mysql_get_client_info())
}
/**
Retrieve the version for the underlying client library version.
- Returns: UInt representing the current client version.
*/
public func client_version() -> UInt {
return CMySQLClient.mysql_get_client_version();
}
/**
Execute the given SQL query against the database.
- Parameters:
- query: valid TSQL statement to execute.
- Returns: Tuple consiting of an optional CMySQLResult, array of CMySQLField and MySQLError. If the query fails then an error object will be returned and CMySQLResult and [CMySQLField] will be nil. Upon success MySQLError will be nil however it is still possible for no results to be returned as some queries do not return results.
*/
public func execute(query: String) -> (CMySQLResult?, [CMySQLField]?, MySQLError?) {
clearResult() // clear any memory allocated to a previous result
if (CMySQLClient.mysql_query(connection, query) == 1) {
let error = String(cString: CMySQLClient.mysql_error(connection))
print("Error executing query: " + query)
print(error)
return (nil, nil, MySQLError.UnableToExecuteQuery(message: error))
}
print("total affected rows: " + String(mysql_affected_rows(connection)))
return getResults()
}
/**
Return the next result from executing a query.
- Parameters:
- result: CMySQLResult instance returned from execute.
- Returns: A pointer to an array of strings.
*/
public func nextResult(result: CMySQLResult) -> CMySQLRow? {
let row = CMySQLClient.mysql_fetch_row(result)
if row != nil {
return row
} else {
// no more results free any memory and return
clearResult()
return nil
}
}
/**
Return the next result set after executing a query, this might be used when you
specify a multi statement query.
- Returns: Tuple consiting of an optional CMySQLResult, array of CMySQLField and MySQLError. If the query fails then an error object will be returned and CMySQLResult and [CMySQLField] will be nil. Upon success MySQLError will be nil however it is still possible for no results to be returned as some queries do not return results.
```
var result = connection.execute("SELECT * FROM table1; SELECT * FROM table2;")
var row = connection.nextResult(result) // use rows from table1
result = connection.nextResultSet()
row = connection.nextResult(result) // use rows from table2
```
*/
public func nextResultSet() -> (CMySQLResult?, [CMySQLField]?, MySQLError?) {
if mysql_next_result(connection) < 1 {
return getResults()
} else {
print("No more results")
return (nil, nil, MySQLError.NoMoreResults)
}
}
private func getResults() -> (CMySQLResult?, [CMySQLField]?, MySQLError?){
clearResult()
result = CMySQLClient.mysql_store_result(connection)
if (result == nil) {
print("Error getting results")
print(String(cString: CMySQLClient.mysql_error(connection)))
return (nil, nil, nil)
} else {
return (result, getHeaders(resultPointer: result!), nil)
}
}
/**
Clears any memory which has been allocated to a mysql result
*/
private func clearResult() {
if result != nil {
CMySQLClient.mysql_free_result(result)
result = nil
}
}
private func getHeaders(resultPointer: CMySQLResult) -> [CMySQLField] {
let num_fields = CMySQLClient.mysql_num_fields(resultPointer);
var fields = [CMySQLField]()
for _ in 0..<num_fields {
fields.append(mysql_fetch_field(resultPointer))
}
return fields
}
}
| mit | cc39bfb2efb07259c76f3aac78b2b0e8 | 31.9 | 337 | 0.686785 | 4.28598 | false | false | false | false |
trill-lang/trill | Sources/AST/Values.swift | 2 | 8469 | ///
/// Values.swift
///
/// Copyright 2016-2017 the Trill project authors.
/// Licensed under the MIT License.
///
/// Full license text available at https://github.com/trill-lang/trill
///
import Foundation
import Source
public class Expr: ASTNode {
public var type: DataType = .error
/// Looks through syntactic sugar expressions like `ParenExpr` to find the
/// underlying expression that informs the semantics of this expression.
public var semanticsProvidingExpr: Expr {
return self
}
public override func attributes() -> [String : Any] {
var attrs = super.attributes()
if type != .error {
attrs["type"] = type.description
}
return attrs
}
}
public class ConstantExpr: Expr {
public override init(sourceRange: SourceRange? = nil) {
super.init(sourceRange: sourceRange)
}
public var text: String { return "" }
}
public class VoidExpr: Expr {
public override init(sourceRange: SourceRange? = nil) {
super.init(sourceRange: sourceRange)
self.type = .void
}
}
public class NilExpr: ConstantExpr {
public override init(sourceRange: SourceRange? = nil) {
super.init(sourceRange: sourceRange)
self.type = .pointer(type: .int8)
}
}
public class NumExpr: ConstantExpr { // 1234567
public let value: Int64
public let raw: String
public init(value: Int64, raw: String, sourceRange: SourceRange? = nil) {
self.value = value
self.raw = raw
super.init(sourceRange: sourceRange)
self.type = .int64
}
public override var text: String {
return raw
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["value"] = value
superAttrs["raw"] = raw
return superAttrs
}
}
public class ParenExpr: Expr {
public let value: Expr
public init(value: Expr, sourceRange: SourceRange? = nil) {
self.value = value
super.init(sourceRange: sourceRange)
}
public override var semanticsProvidingExpr: Expr {
return value.semanticsProvidingExpr
}
}
public class TupleExpr: Expr {
public let values: [Expr]
public init(values: [Expr], sourceRange: SourceRange? = nil) {
self.values = values
super.init(sourceRange: sourceRange)
}
}
public class ArrayExpr: Expr {
public let values: [Expr]
public init(values: [Expr], sourceRange: SourceRange? = nil) {
self.values = values
super.init(sourceRange: sourceRange)
}
}
public class TupleFieldLookupExpr: Expr {
public let lhs: Expr
public let field: Int
public let fieldRange: SourceRange
public init(lhs: Expr, field: Int, fieldRange: SourceRange, sourceRange: SourceRange? = nil) {
self.lhs = lhs
self.field = field
self.fieldRange = fieldRange
super.init(sourceRange: sourceRange)
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["field"] = field
return superAttrs
}
}
public class FloatExpr: ConstantExpr {
public override var type: DataType {
get { return .double } set { }
}
public let value: Double
public init(value: Double, sourceRange: SourceRange? = nil) {
self.value = value
super.init(sourceRange: sourceRange)
}
public override var text: String {
return "\(value)"
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["value"] = value
return superAttrs
}
}
public class BoolExpr: ConstantExpr {
public override var type: DataType {
get { return .bool } set { }
}
public let value: Bool
public init(value: Bool, sourceRange: SourceRange? = nil) {
self.value = value
super.init(sourceRange: sourceRange)
}
public override var text: String {
return value.description
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["value"] = value
return superAttrs
}
}
public class StringExpr: ConstantExpr {
public var value: String
public init(value: String, sourceRange: SourceRange? = nil) {
self.value = value
super.init(sourceRange: sourceRange)
}
public override var text: String {
return value
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["value"] = value
return superAttrs
}
}
public class StringInterpolationExpr: Expr {
public let segments: [Expr]
public init(segments: [Expr], sourceRange: SourceRange? = nil) {
self.segments = segments
super.init(sourceRange: sourceRange)
}
}
public class PoundFunctionExpr: StringExpr {
public init(sourceRange: SourceRange? = nil) {
super.init(value: "", sourceRange: sourceRange)
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["value"] = value
return superAttrs
}
}
public class PoundFileExpr: StringExpr {}
public class CharExpr: ConstantExpr {
public override var type: DataType {
get { return .int8 } set { }
}
public let value: UInt8
public init(value: UInt8, sourceRange: SourceRange? = nil) {
self.value = value
super.init(sourceRange: sourceRange)
}
public override var text: String {
return value.description
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["value"] = value
return superAttrs
}
}
public protocol LValue {}
public class GenericContainingExpr: Expr {
public var genericParams: [GenericParam]
public init(genericParams: [GenericParam],
sourceRange: SourceRange? = nil) {
self.genericParams = genericParams
super.init(sourceRange: sourceRange)
}
}
public class VarExpr: GenericContainingExpr, LValue {
public let name: Identifier
public var isTypeVar = false
public var isSelf = false
public var decl: Decl? = nil
public init(name: Identifier,
genericParams: [GenericParam] = [],
sourceRange: SourceRange? = nil) {
self.name = name
super.init(genericParams: genericParams, sourceRange: sourceRange ?? name.range)
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["name"] = name.name
if isTypeVar {
superAttrs["isTypeVar"] = true
}
return superAttrs
}
}
public class SizeofExpr: Expr {
public var value: Expr?
public var valueType: DataType?
public init(value: Expr, sourceRange: SourceRange? = nil) {
self.value = value
super.init(sourceRange: sourceRange)
self.type = .int64
}
}
public class SubscriptExpr: FuncCallExpr, LValue {}
public class PropertyRefExpr: GenericContainingExpr, LValue {
public let lhs: Expr
public var decl: Decl? = nil
public var typeDecl: TypeDecl? = nil
public let name: Identifier
public let dotLoc: SourceLocation?
public init(lhs: Expr, name: Identifier, genericParams: [GenericParam] = [],
dotLoc: SourceLocation? = nil,
sourceRange: SourceRange? = nil) {
self.lhs = lhs
self.name = name
self.dotLoc = dotLoc
super.init(genericParams: genericParams, sourceRange: sourceRange)
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["fieldName"] = name.name
return superAttrs
}
}
public class TernaryExpr: Expr {
public let condition: Expr
public let trueCase: Expr
public let falseCase: Expr
public init(condition: Expr, trueCase: Expr,
falseCase: Expr, sourceRange: SourceRange? = nil) {
self.condition = condition
self.trueCase = trueCase
self.falseCase = falseCase
super.init(sourceRange: sourceRange)
}
}
/// <expr> as <expr>
public class CoercionExpr: Expr {
public let lhs: Expr
public let rhs: TypeRefExpr
public let asRange: SourceRange?
public init(lhs: Expr, rhs: TypeRefExpr,
asRange: SourceRange? = nil,
sourceRange: SourceRange? = nil) {
self.lhs = lhs
self.asRange = asRange
self.rhs = rhs
super.init(sourceRange: sourceRange)
}
}
/// <expr> is <expr>
public class IsExpr: Expr {
public let lhs: Expr
public let rhs: TypeRefExpr
public let isRange: SourceRange?
public init(lhs: Expr, rhs: TypeRefExpr,
isRange: SourceRange? = nil,
sourceRange: SourceRange? = nil) {
self.lhs = lhs
self.isRange = isRange
self.rhs = rhs
super.init(sourceRange: sourceRange)
}
}
| mit | 6b52d9a846b79fb7828195bc05968c77 | 25.219814 | 96 | 0.6806 | 4.087355 | false | false | false | false |
nodes-ios/NStackSDK | NStackSDK/NStackSDK/Views/Proposals/ProposalPresenter.swift | 1 | 3461 | //
// ProposalPresenter.swift
// NStackSDK
//
// Created by Nicolai Harbo on 06/08/2019.
// Copyright © 2019 Nodes ApS. All rights reserved.
//
import Foundation
class ProposalPresenter {
// MARK: - Properties
let interactor: ProposalInteractorInput
weak var output: ProposalPresenterOutput?
var proposals: [Proposal] = []
var proposalsGrouped: [(key: String, value: [Proposal])] = []
var listingAllProposals = false
var currentItem: NStackLocalizable?
// MARK: - Init
init(interactor: ProposalInteractorInput,
proposals: [Proposal],
listingAllProposals: Bool, currentItem: NStackLocalizable? = nil) {
self.interactor = interactor
self.proposals = proposals
self.listingAllProposals = listingAllProposals
self.currentItem = currentItem
setupList()
}
private func setupList() {
if listingAllProposals {
proposalsGrouped = Array(Dictionary(grouping: proposals, by: { $0.key })).sorted { (item1, item2) -> Bool in
item1.key < item2.key
}
} else {
if let item = currentItem {
proposals = proposals.filter({$0.section == item.translationIdentifier?.section && $0.key == item.translationIdentifier?.key})
}
}
}
}
// MARK: - User Events -
extension ProposalPresenter: ProposalPresenterInput {
func canDeleteProposal(in section: Int, for index: Int) -> Bool {
return listingAllProposals ? proposalsGrouped[section].value[index].canDelete : proposals[index].canDelete
}
var numberOfSections: Int {
return listingAllProposals ? proposalsGrouped.count : 1
}
func numberOfRows(in section: Int) -> Int {
return listingAllProposals ? proposalsGrouped[section].value.count : proposals.count
}
func configure(item: ProposalCellProtocol, in section: Int, for index: Int) {
let proposal = listingAllProposals ? proposalsGrouped[section].value[index] : proposals[index]
if proposal.canDelete {
item.setTextColor(.blue)
}
item.setTextLabel(with: proposal.value)
}
func titleForHeader(in section: Int) -> String? {
return listingAllProposals ? proposalsGrouped[section].key : nil
}
func viewCreated() {
setTitle()
checkIfEmpty()
}
func handle(_ action: Proposals.Action) {
switch action {
case .deleteProposal(let section, let index):
let proposalToDelete = listingAllProposals ? proposalsGrouped[section].value[index] : proposals[index]
interactor.perform(Proposals.Request.DeleteProposal(proposal: proposalToDelete))
}
}
func setTitle() {
if listingAllProposals {
output?.setTitle("All proposals")
} else {
if let keyName = proposals.first?.key {
output?.setTitle("Proposals for \(keyName)")
} else {
output?.setTitle("Proposals")
}
}
}
func checkIfEmpty() {
if (proposals.isEmpty && !listingAllProposals) || (proposalsGrouped.isEmpty && listingAllProposals) {
output?.setupEmptyCaseLabel()
}
}
}
// MARK: - Presentation Logic -
// INTERACTOR -> PRESENTER (indirect)
extension ProposalPresenter: ProposalInteractorOutput {
func present(_ response: Proposals.Response.ProposalDeleted) {
}
}
| mit | 0e8011745dced15811f1ce3a77386e38 | 28.827586 | 142 | 0.634971 | 4.402036 | false | false | false | false |
brave/browser-ios | Client/Frontend/Browser/PrintHelper.swift | 2 | 1361 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebKit
class PrintHelper: BrowserHelper {
fileprivate weak var browser: Browser?
required init(browser: Browser) {
self.browser = browser
if let path = Bundle.main.path(forResource: "PrintHelper", ofType: "js"), let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String {
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: false)
browser.webView!.configuration.userContentController.addUserScript(userScript)
}
}
class func scriptMessageHandlerName() -> String? {
return "printHandler"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let browser = browser, let webView = browser.webView {
let printController = UIPrintInteractionController.shared
printController.printFormatter = webView.viewPrintFormatter()
printController.present(animated: true, completionHandler: nil)
}
}
}
| mpl-2.0 | ef42f7e4bab6b204c52e59029792cd5a | 42.903226 | 183 | 0.717855 | 5.05948 | false | false | false | false |
manavgabhawala/swift | test/IRGen/dllimport.swift | 1 | 3560 | // RUN: %swift -target thumbv7--windows-itanium -emit-ir -parse-as-library -parse-stdlib -module-name dllimport %s -o - -enable-source-import -I %S | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-NO-OPT
// RUN: %swift -target thumbv7--windows-itanium -O -emit-ir -parse-as-library -parse-stdlib -module-name dllimport -primary-file %s -o - -enable-source-import -I %S | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-OPT
// REQUIRES: CODEGENERATOR=ARM
import dllexport
public func get_ci() -> dllexport.c {
return dllexport.ci
}
public func get_c_type() -> dllexport.c.Type {
return dllexport.c
}
public class d : c {
override init() {
super.init()
}
@inline(never)
func f(_ : dllexport.c) { }
}
struct s : p {
func f() { }
}
func f(di : d) {
di.f(get_ci())
}
func blackhole<F>(_ : F) { }
public func g() {
blackhole({ () -> () in })
}
// CHECK-NO-OPT-DAG: @_swift_allocObject = external dllimport global %swift.refcounted* (%swift.type*, i32, i32)*
// CHECK-NO-OPT-DAG: @_swift_deallocObject = external dllimport global void (%swift.refcounted*, i32, i32)*
// CHECK-NO-OPT-DAG: @_swift_release = external dllimport global void (%swift.refcounted*)
// CHECK-NO-OPT-DAG: @_swift_retain = external dllimport global void (%swift.refcounted*)
// CHECK-NO-OPT-DAG: @_swift_slowAlloc = external dllimport global i8* (i32, i32)*
// CHECK-NO-OPT-DAG: @_swift_slowDealloc = external dllimport global void (i8*, i32, i32)*
// CHECK-NO-OPT-DAG: @_TMC9dllexport1c = external dllimport global %swift.type
// CHECK-NO-OPT-DAG: @_TMp9dllexport1p = external dllimport global %swift.protocol
// CHECK-NO-OPT-DAG: @_TMT_ = external dllimport global %swift.full_type
// CHECK-NO-OPT-DAG: @_TWVBo = external dllimport global i8*
// CHECK-NO-OPT-DAG: declare dllimport swiftcc i8* @_TF9dllexportau2ciCS_1c()
// CHECK-NO-OPT-DAG: declare dllimport swiftcc %swift.refcounted* @_TFC9dllexport1cd(%T9dllexport1cC* swiftself)
// CHECK-NO-OPT-DAG: declare dllimport %swift.type* @_TMaC9dllexport1c()
// CHECK-NO-OPT-DAG: declare dllimport void @swift_deallocClassInstance(%swift.refcounted*, i32, i32)
// CHECK-NO-OPT-DAG: define linkonce_odr hidden i8* @swift_rt_swift_slowAlloc(i32, i32)
// CHECK-NO-OPT-DAG: define linkonce_odr hidden void @swift_rt_swift_release(%swift.refcounted*)
// CHECK-NO-OPT-DAG: define linkonce_odr hidden void @swift_rt_swift_retain(%swift.refcounted*)
// CHECK-NO-OPT-DAG: define linkonce_odr hidden void @swift_rt_swift_slowDealloc(i8*, i32, i32)
// CHECK-OPT-DAG: @_swift_retain = external dllimport local_unnamed_addr global void (%swift.refcounted*)
// CHECK-OPT-DAG: @_TWVBo = external dllimport global i8*
// CHECK-OPT-DAG: @_TMC9dllexport1c = external dllimport global %swift.type
// CHECK-OPT-DAG: @_TMp9dllexport1p = external dllimport global %swift.protocol
// CHECK-OPT-DAG: @_swift_slowAlloc = external dllimport local_unnamed_addr global i8* (i32, i32)*
// CHECK-OPT-DAG: @_swift_slowDealloc = external dllimport local_unnamed_addr global void (i8*, i32, i32)*
// CHECK-OPT-DAG: declare dllimport swiftcc i8* @_TF9dllexportau2ciCS_1c()
// CHECK-OPT-DAG: declare dllimport %swift.type* @_TMaC9dllexport1c()
// CHECK-OPT-DAG: declare dllimport void @swift_deallocClassInstance(%swift.refcounted*, i32, i32)
// CHECK-OPT-DAG: declare dllimport swiftcc %swift.refcounted* @_TFC9dllexport1cd(%T9dllexport1cC* swiftself)
// CHECK-OPT-DAG: define linkonce_odr hidden i8* @swift_rt_swift_slowAlloc(i32, i32)
// CHECK-OPT-DAG: define linkonce_odr hidden void @swift_rt_swift_slowDealloc(i8*, i32, i32)
| apache-2.0 | c3522417c9f947da955e5ef0e88b4208 | 49.857143 | 224 | 0.72191 | 3.125549 | false | false | false | false |
Killectro/RxGrailed | RxGrailed/Pods/AlgoliaSearch-Client-Swift/Source/AsyncOperation.swift | 1 | 5191 | //
// Copyright (c) 2015-2016 Algolia
// http://www.algolia.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
/// An asynchronous operation.
///
/// This class provides its subclasses the way to manually control `Operation`'s standard properties:
///
/// - `executing`
/// - `finished`
/// - `cancel`
///
internal class AsyncOperation: Operation {
// Mark this operation as aynchronous.
override var isAsynchronous: Bool {
get {
return true
}
}
// NOTE: Overriding `Operation`'s properties
// -----------------------------------------
// These properties are defined as read-only by `Operation`. As a consequence, they must be computed properties.
// But they must also fire KVO notifications, which are crucial for `OperationQueue` to work.
// This is why we use a private (underscore-prefixed) property to store the state.
var _executing : Bool = false {
willSet {
self.willChangeValue(forKey: "isExecuting")
}
didSet {
self.didChangeValue(forKey: "isExecuting")
}
}
override var isExecuting: Bool {
get {
return _executing
}
}
var _finished : Bool = false {
willSet {
self.willChangeValue(forKey: "isFinished")
}
didSet {
self.didChangeValue(forKey: "isFinished")
}
}
override var isFinished: Bool {
get {
return _finished
}
}
var _cancelled : Bool = false {
willSet {
self.willChangeValue(forKey: "isCancelled")
}
didSet {
self.didChangeValue(forKey: "isCancelled")
}
}
override var isCancelled: Bool {
get {
return _cancelled
}
}
override func start() {
assert(!_executing)
self._executing = true
}
override func cancel() {
_cancelled = true
finish()
}
/// Mark the operation as finished.
func finish() {
_executing = false
_finished = true
}
}
/// A specific type of async operation with a completion handler.
///
internal class AsyncOperationWithCompletion: AsyncOperation {
/// User completion block to be called.
let completion: CompletionHandler?
/// Dispatch queue used to execute the completion handler.
var completionQueue: DispatchQueue?
init(completionHandler: CompletionHandler?) {
self.completion = completionHandler
}
/// Finish this operation.
/// This method should be called exactly once per operation.
internal func callCompletion(content: JSONObject?, error: Error?) {
if _cancelled {
return
}
if let completionQueue = completionQueue {
completionQueue.async {
self._callCompletion(content: content, error: error)
}
} else {
_callCompletion(content: content, error: error)
}
}
internal func _callCompletion(content: JSONObject?, error: Error?) {
// WARNING: In case of asynchronous dispatch, the request could have been cancelled in the meantime
// => check again.
if !_cancelled {
if let completion = completion {
completion(content, error)
}
finish()
}
}
}
/// An asynchronous operation whose body is specified as a block.
///
internal class AsyncBlockOperation: AsyncOperationWithCompletion {
typealias OperationBlock = () -> (content: JSONObject?, error: Error?)
/// The block that will be executed as part of the operation.
let block: OperationBlock
internal init(completionHandler: CompletionHandler?, block: @escaping OperationBlock) {
self.block = block
super.init(completionHandler: completionHandler)
}
/// Start this request.
override func start() {
super.start()
let (content, error) = block()
self.callCompletion(content: content, error: error)
}
}
| mit | f0a72d655b7eb4578c3a3f7e0d7dc81c | 29.535294 | 116 | 0.621075 | 4.957975 | false | false | false | false |
gvzq/iOS-Twitter | BackUp/Twitter/TweetCell.swift | 1 | 2931 | //
// TweetCell.swift
// Twitter
//
// Created by Gerardo Vazquez on 2/17/16.
// Copyright © 2016 Gerardo Vazquez. All rights reserved.
//
import UIKit
class TweetCell: UITableViewCell {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var tweetTextLabel: UILabel!
@IBOutlet weak var timeStampLabel: UILabel!
@IBOutlet weak var favoriteCountLabel: UILabel!
@IBOutlet weak var retweetCountLabel: UILabel!
@IBAction func onFavorite(sender: AnyObject) {
if (tweet.favorited!) {
TwitterClient.sharedInstance.destroyFavorite(tweet.id!)
tweet.favouritesCount!--
tweet.favorited = false
} else {
TwitterClient.sharedInstance.createFavorite(tweet.id!)
tweet.favouritesCount!++
tweet.favorited = true
}
favoriteCountLabel.text = "\(tweet.favouritesCount!)"
}
@IBAction func onRetweet(sender: AnyObject) {
if (tweet.retweeted!) {
TwitterClient.sharedInstance.unretweet(tweet.id!)
tweet.retweetCount!--
tweet.retweeted = false
} else {
TwitterClient.sharedInstance.retweet(tweet.id!)
tweet.retweetCount!++
tweet.retweeted = true
print("\(tweet.id!)")
}
retweetCountLabel.text = "\(tweet.retweetCount!)"
}
var tweet: Tweet! {
didSet {
profileImageView.setImageWithURL(NSURL(string: (tweet.user?.profileImageUrl)!)!)
nameLabel.text = tweet.user?.name
tweetTextLabel.text = tweet.text
timeStampLabel.text = tweet.createdAtString
let hourDifference = NSCalendar.currentCalendar().components(.Hour, fromDate: tweet.createdAt!, toDate: NSDate(), options: []).hour
let minDifference = NSCalendar.currentCalendar().components(.Minute, fromDate: tweet.createdAt!, toDate: NSDate(), options: []).minute
if (hourDifference == 0) {
timeStampLabel.text = "\(minDifference)Min"
} else if (hourDifference <= 24) {
timeStampLabel.text = "\(hourDifference)H"
} else {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
timeStampLabel.text = dateFormatter.stringFromDate(tweet.createdAt!)
}
favoriteCountLabel.text = "\(tweet.favouritesCount!)"
retweetCountLabel.text = "\(tweet.retweetCount!)"
print("Retweet: \(tweet.retweetCount!)")
}
}
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
}
}
| apache-2.0 | 0fe09b4179185498c4efe7788acdcb12 | 35.17284 | 147 | 0.612628 | 5.222816 | false | false | false | false |
Valine/mri | SwiftVersion/Inspiration/Inspiration/DIgitalMozart.swift | 2 | 2713 |
// Created by Lukas Valine
import Foundation
class DigitalMozart {
static func writeSong(key:Tone, meter: Int, length: Int) -> Song {
let song: Song = Song(key: key, meter: meter)
for _ in 0...length * meter - 1 {
var chord: Array<Note> = [Note]()
for _ in 0...0 {
chord.append(generateRandomNote())
}
song.addNote(Note(positions:chord))
}
return song;
}
static func writeSong(key:Tone, meter: Meter, length: Int) -> Song {
return writeSong(key, meter: Song.getBeatsInMeasure(meter), length: length);
}
static func playSong() {
/// TODO
}
static func songToSring(song: Song) -> String{
var songString: String = "|"
for (i, note) in song.notes.enumerate() {
songString += String(note.position)
if i % song.meter == song.meter - 1 {
songString += "|"
}
}
return songString
}
func dumpSongs() {
for song in modelController.songs.enumerate() {
print("song size: " + String(song.element.notes.count))
print(" song key " + String(song.element.key))
print(" song meter " + String(song.element.meter))
print(" song notes: " + DigitalMozart.songToSring(song.element))
print(" song name: " + song.element.name)
}
}
static func calculateMeasureBreaks(song: Song) -> Array<Int> {
var measureBreaks = [0]
var meterTotal: Float = 1
if song.meter == 4 {
meterTotal = 1
} else if song.meter == 3{
meterTotal = 0.75
} else if song.meter == 2{
meterTotal = 0.5
} else if song.meter == 6 {
meterTotal = 1
} else if song.meter == 5 {
meterTotal = 1.25
}
var beatSum: Float = 0
for note in song.notes.enumerate() {
beatSum += Song.beatToFloat(note.element.beat)
if beatSum == meterTotal {
measureBreaks.append(note.index + 1)
beatSum = 0
}
}
//measureBreaks.append(song.notes.count)
return measureBreaks
}
/// Create a new note with a random tone
private static func generateRandomNote() -> Note{ return Note.init(beat: .Quarter, position: Int(arc4random_uniform(13))) }
}
| gpl-2.0 | 24805d4b5aaea04bae7ed1a1f9961311 | 25.086538 | 127 | 0.48028 | 4.552013 | false | false | false | false |
rrunfa/StreamRun | Libraries/Alamofire/Download.swift | 1 | 8497 | // Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
dispatch_sync(queue) {
downloadTask = self.session.downloadTaskWithRequest(request)
}
case .ResumeData(let resumeData):
dispatch_sync(queue) {
downloadTask = self.session.downloadTaskWithResumeData(resumeData)
}
}
let request = Request(session: session, task: downloadTask)
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in
return destination(URL, downloadTask.response as! NSHTTPURLResponse)
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: Request
/**
Creates a download request using the shared manager instance for the specified method and URL string.
:param: method The HTTP method.
:param: URLString The URL string.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(method: Method, _ URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
return download(URLRequest(method, URLString), destination: destination)
}
/**
Creates a request for downloading from the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return download(.Request(URLRequest.URLRequest), destination: destination)
}
// MARK: Resume Data
/**
Creates a request for downloading from the resume data produced from a previous request cancellation.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
// MARK: -
extension Request {
/**
A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved.
*/
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL
/**
Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask.
:param: directory The search path directory. `.DocumentDirectory` by default.
:param: domain The search path domain mask. `.UserDomainMask` by default.
:returns: A download file destination closure.
*/
public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination {
return { temporaryURL, response -> NSURL in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)[0] as? NSURL {
return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
}
return temporaryURL
}
}
// MARK: - DownloadTaskDelegate
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData?
override var data: NSData? { return resumeData }
// MARK: - NSURLSessionDownloadDelegate
// MARK: Override Closures
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)?
var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: Delegate Methods
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if let downloadTaskDidFinishDownloadingToURL = self.downloadTaskDidFinishDownloadingToURL {
let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
var fileManagerError: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
if fileManagerError != nil {
error = fileManagerError
}
}
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let downloadTaskDidWriteData = self.downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let downloadTaskDidResumeAtOffset = self.downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
}
| mit | 6855b215b9913f6f4194853171379a40 | 44.918919 | 327 | 0.706298 | 5.932263 | false | false | false | false |
Farteen/firefox-ios | Client/Frontend/Browser/Browser.swift | 3 | 11545 | /* 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 WebKit
import Storage
import Shared
protocol BrowserHelper {
static func name() -> String
func scriptMessageHandlerName() -> String?
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
}
@objc
protocol BrowserDelegate {
func browser(browser: Browser, didAddSnackbar bar: SnackBar)
func browser(browser: Browser, didRemoveSnackbar bar: SnackBar)
optional func browser(browser: Browser, didCreateWebView webView: WKWebView)
optional func browser(browser: Browser, willDeleteWebView webView: WKWebView)
}
class Browser: NSObject {
var webView: WKWebView? = nil
var browserDelegate: BrowserDelegate? = nil
var bars = [SnackBar]()
var favicons = [Favicon]()
var sessionData: SessionData?
var screenshot: UIImage?
private var helperManager: HelperManager? = nil
var lastRequest: NSURLRequest? = nil
private var configuration: WKWebViewConfiguration? = nil
init(configuration: WKWebViewConfiguration) {
self.configuration = configuration
}
class func toTab(browser: Browser) -> RemoteTab? {
if let displayURL = browser.displayURL {
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: browser.displayTitle,
history: browser.historyList,
lastUsed: Timestamp(),
icon: nil)
} else {
return nil
}
}
weak var navigationDelegate: WKNavigationDelegate? {
didSet {
if let webView = webView {
webView.navigationDelegate = navigationDelegate
}
}
}
func createWebview() {
if webView == nil {
assert(configuration != nil, "Create webview can only be called once")
configuration!.userContentController = WKUserContentController()
configuration!.preferences = WKPreferences()
configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false
let webView = WKWebView(frame: CGRectZero, configuration: configuration!)
configuration = nil
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.allowsBackForwardNavigationGestures = true
webView.backgroundColor = UIColor.lightGrayColor()
// Turning off masking allows the web content to flow outside of the scrollView's frame
// which allows the content appear beneath the toolbars in the BrowserViewController
webView.scrollView.layer.masksToBounds = false
webView.navigationDelegate = navigationDelegate
helperManager = HelperManager(webView: webView)
// Pulls restored session data from a previous SavedTab to load into the Browser. If it's nil, a session restore
// has already been triggered via custom URL, so we use the last request to trigger it again; otherwise,
// we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL
// to trigger the session restore via custom handlers
if let sessionData = self.sessionData {
var updatedURLs = [String]()
for url in sessionData.urls {
let updatedURL = WebServer.sharedInstance.updateLocalURL(url)!.absoluteString!
updatedURLs.append(updatedURL)
}
let currentPage = sessionData.currentPage
self.sessionData = nil
var jsonDict = [String: AnyObject]()
jsonDict["history"] = updatedURLs
jsonDict["currentPage"] = currentPage
let escapedJSON = JSON.stringify(jsonDict, pretty: false).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let restoreURL = NSURL(string: "\(WebServer.sharedInstance.base)/about/sessionrestore?history=\(escapedJSON)")
webView.loadRequest(NSURLRequest(URL: restoreURL!))
} else if let request = lastRequest {
webView.loadRequest(request)
}
self.webView = webView
browserDelegate?.browser?(self, didCreateWebView: webView)
}
}
deinit {
if let webView = webView {
browserDelegate?.browser?(self, willDeleteWebView: webView)
}
}
var loading: Bool {
return webView?.loading ?? false
}
var estimatedProgress: Double {
return webView?.estimatedProgress ?? 0
}
var backList: [WKBackForwardListItem]? {
return webView?.backForwardList.backList as? [WKBackForwardListItem]
}
var forwardList: [WKBackForwardListItem]? {
return webView?.backForwardList.forwardList as? [WKBackForwardListItem]
}
var historyList: [NSURL] {
func listToUrl(item: WKBackForwardListItem) -> NSURL { return item.URL }
var tabs = self.backList?.map(listToUrl) ?? [NSURL]()
tabs.append(self.url!)
return tabs
}
var title: String? {
return webView?.title
}
var displayTitle: String {
if let title = webView?.title {
if !title.isEmpty {
return title
}
}
return displayURL?.absoluteString ?? ""
}
var displayFavicon: Favicon? {
var width = 0
var largest: Favicon?
for icon in favicons {
if icon.width > width {
width = icon.width!
largest = icon
}
}
return largest
}
var url: NSURL? {
return webView?.URL ?? lastRequest?.URL
}
var displayURL: NSURL? {
if let url = webView?.URL ?? lastRequest?.URL {
if !AboutUtils.isAboutHomeURL(url) {
if ReaderModeUtils.isReaderModeURL(url) {
return ReaderModeUtils.decodeURL(url)
}
if ErrorPageHelper.isErrorPageURL(url) {
return ErrorPageHelper.decodeURL(url)
}
return url
}
}
return nil
}
var canGoBack: Bool {
return webView?.canGoBack ?? false
}
var canGoForward: Bool {
return webView?.canGoForward ?? false
}
func goBack() {
webView?.goBack()
}
func goForward() {
webView?.goForward()
}
func goToBackForwardListItem(item: WKBackForwardListItem) {
webView?.goToBackForwardListItem(item)
}
func loadRequest(request: NSURLRequest) -> WKNavigation? {
lastRequest = request
if let webView = webView {
return webView.loadRequest(request)
}
return nil
}
func stop() {
webView?.stopLoading()
}
func reload() {
webView?.reload()
}
func addHelper(helper: BrowserHelper, name: String) {
helperManager!.addHelper(helper, name: name)
}
func getHelper(#name: String) -> BrowserHelper? {
return helperManager!.getHelper(name: name)
}
func hideContent(animated: Bool = false) {
webView?.userInteractionEnabled = false
if animated {
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.webView?.alpha = 0.0
})
} else {
webView?.alpha = 0.0
}
}
func showContent(animated: Bool = false) {
webView?.userInteractionEnabled = true
if animated {
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.webView?.alpha = 1.0
})
} else {
webView?.alpha = 1.0
}
}
func addSnackbar(bar: SnackBar) {
bars.append(bar)
browserDelegate?.browser(self, didAddSnackbar: bar)
}
func removeSnackbar(bar: SnackBar) {
if let index = find(bars, bar) {
bars.removeAtIndex(index)
browserDelegate?.browser(self, didRemoveSnackbar: bar)
}
}
func removeAllSnackbars() {
// Enumerate backwards here because we'll remove items from the list as we go.
for var i = bars.count-1; i >= 0; i-- {
let bar = bars[i]
removeSnackbar(bar)
}
}
func expireSnackbars() {
// Enumerate backwards here because we may remove items from the list as we go.
for var i = bars.count-1; i >= 0; i-- {
let bar = bars[i]
if !bar.shouldPersist(self) {
removeSnackbar(bar)
}
}
}
}
private class HelperManager: NSObject, WKScriptMessageHandler {
private var helpers = [String: BrowserHelper]()
private weak var webView: WKWebView?
init(webView: WKWebView) {
self.webView = webView
}
@objc func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
for helper in helpers.values {
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
if scriptMessageHandlerName == message.name {
helper.userContentController(userContentController, didReceiveScriptMessage: message)
return
}
}
}
}
func addHelper(helper: BrowserHelper, name: String) {
if let existingHelper = helpers[name] {
assertionFailure("Duplicate helper added: \(name)")
}
helpers[name] = helper
// If this helper handles script messages, then get the handler name and register it. The Browser
// receives all messages and then dispatches them to the right BrowserHelper.
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
webView?.configuration.userContentController.addScriptMessageHandler(self, name: scriptMessageHandlerName)
}
}
func getHelper(#name: String) -> BrowserHelper? {
return helpers[name]
}
}
extension WKWebView {
func runScriptFunction(function: String, fromScript: String, callback: (AnyObject?) -> Void) {
if let path = NSBundle.mainBundle().pathForResource(fromScript, ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String {
evaluateJavaScript(source, completionHandler: { (obj, err) -> Void in
if let err = err {
println("Error injecting \(err)")
return
}
self.evaluateJavaScript("__firefox__.\(fromScript).\(function)", completionHandler: { (obj, err) -> Void in
self.evaluateJavaScript("delete window.__firefox__.\(fromScript)", completionHandler: { (obj, err) -> Void in })
if let err = err {
println("Error running \(err)")
return
}
callback(obj)
})
})
}
}
}
}
| mpl-2.0 | 0379fd379339df3f4614ecfb5bc3f95d | 33.056047 | 171 | 0.599913 | 5.495002 | false | false | false | false |
cdmx/MiniMancera | miniMancera/Model/Option/PollutedGarden/Bubble/Item/Strategy/MOptionPollutedGardenBubbleItemStrategyExploded.swift | 1 | 1248 | import SpriteKit
class MOptionPollutedGardenBubbleItemStrategyExploded:MGameStrategy<
MOptionPollutedGardenBubbleItem,
MOptionPollutedGarden>
{
private var startingTime:TimeInterval?
private let kDuration:TimeInterval = 1.5
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionPollutedGarden>)
{
if let startingTime:TimeInterval = self.startingTime
{
let deltaTime:TimeInterval = elapsedTime - startingTime
if deltaTime > kDuration
{
model.view?.explodeEnded()
scene.controller.model.bubble.bubbleExplodeFinished(
bubbleItem:model)
}
}
else
{
startingTime = elapsedTime
let explodeAnimation:SKAction = scene.controller.model.actions.actionBubbleAnimation
model.view?.explodeStart(animation:explodeAnimation)
guard
let scene:VOptionPollutedGardenScene = scene as? VOptionPollutedGardenScene
else
{
return
}
scene.bubbleExploded()
}
}
}
| mit | 5d4dbcebb8e3ca2a7914c68f6f31860f | 28.023256 | 96 | 0.579327 | 5.942857 | false | false | false | false |
lseeker/HeidiKit | HeidiKit/HDIPCSelectedListViewController.swift | 1 | 6377 | //
// HDIPCSelectedListViewController.swift
// HeidiKit
//
// Created by Yun-young LEE on 2015. 2. 9..
// Copyright (c) 2015년 inode.kr. All rights reserved.
//
import UIKit
import Photos
class HDIPCSelectedListViewController: UITableViewController, PHPhotoLibraryChangeObserver {
var assets: [PHAsset]!
var imageAssets = [HDIPCSelectedAsset]()
override func viewDidLoad() {
super.viewDidLoad()
PHPhotoLibrary.shared().register(self)
for asset in assets {
let imageAsset = HDIPCSelectedAsset(asset)
self.imageAssets.append(imageAsset)
self.downloadImageAsset(imageAsset)
}
isEditing = true
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return assets.count
}
@IBAction func dismiss() {
PHPhotoLibrary.shared().unregisterChangeObserver(self)
self.dismiss(animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SelectedAssetCell", for: indexPath) as! HDIPCSelectedAssetCell
// Configure the cell...
let asset = imageAssets[indexPath.row]
if let fileName = asset.fileName {
cell.nameLabel.text = fileName
} else {
cell.nameLabel.text = "Loading..."
}
cell.dateLabel.text = asset.formattedDate
if asset.needLoading {
cell.resolutionLabel.text = "Downloading... \(asset.resolution)"
cell.fileSizeLabel.text = nil
cell.downloadIndicatorView.startAnimating()
} else {
cell.resolutionLabel.text = asset.resolution
if let fileSize = asset.fileSize {
cell.fileSizeLabel.text = String(format: "%0.2fMB", Double(fileSize) / 1024.0 / 1024.0)
} else {
cell.fileSizeLabel.text = nil
}
cell.downloadIndicatorView.stopAnimating()
}
if let thumbnail = asset.thumbnail {
cell.thumnailImageView.image = thumbnail
} else {
cell.thumnailImageView.image = nil
asset.loadThumbnail({ (asset) -> Void in
if let index = self.imageAssets.index(of: asset) {
if let cell = self.tableView.cellForRow(at: IndexPath(row: index, section: 0)) as? HDIPCSelectedAssetCell {
cell.thumnailImageView.image = asset.thumbnail
}
}
})
}
return cell
}
/*
// 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 func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
return "Deselect"
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
imageAssets.remove(at: indexPath.row)
assets.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to toIndexPath: IndexPath) {
let asset = assets.remove(at: fromIndexPath.row)
assets.insert(asset, at: toIndexPath.row)
let iAsset = imageAssets.remove(at: fromIndexPath.row)
imageAssets.insert(iAsset, at: toIndexPath.row)
}
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
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.
}
*/
func photoLibraryDidChange(_ changeInstance: PHChange) {
DispatchQueue.main.async {
for (index, imageAsset) in self.imageAssets.enumerated() {
if let details = changeInstance.changeDetails(for: imageAsset.asset) {
if details.assetContentChanged {
let afterAsset = HDIPCSelectedAsset(details.objectAfterChanges as! PHAsset)
self.imageAssets[index] = afterAsset
self.downloadImageAsset(afterAsset)
self.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: UITableViewRowAnimation.automatic)
}
}
}
}
}
fileprivate func downloadImageAsset(_ imageAsset : HDIPCSelectedAsset) {
imageAsset.downloadFullsizeImage({ (asset) -> Void in
if let index = self.imageAssets.index(of: asset) {
if let cell = self.tableView.cellForRow(at: IndexPath(row: index, section: 0)) as? HDIPCSelectedAssetCell {
cell.resolutionLabel.text = asset.resolution
if let fileSize = asset.fileSize {
cell.fileSizeLabel.text = String(format: "%0.2fMB", Double(fileSize) / 1024.0 / 1024.0)
} else {
cell.fileSizeLabel.text = nil
}
cell.downloadIndicatorView.stopAnimating()
}
}
})
}
}
| apache-2.0 | bbf37a519bfbe5091eb8788f8c9866fc | 36.721893 | 136 | 0.601569 | 5.170316 | false | false | false | false |
kimar/Camira | CamiraTests/TestGame.swift | 1 | 2383 | //
// TestGame.swift
// Camira
//
// Created by Marcus Kida on 22/10/16.
// Copyright © 2016 Marcus Kida. All rights reserved.
//
import Foundation
import Camira
extension Action {
static func hallwayToDiningRoom() -> Action {
return Action(text: "Go to dining room", nextScene: Scene.diningRoom())
}
static func escapeThroughWindow() -> Action {
return Action(text: "Escape through window", nextScene: Scene.outside())
}
static func backToDiningRoom() -> Action {
return Action(text: "Head back to dining room", nextScene: Scene.diningRoomBack())
}
static func goToBathroom() -> Action {
return Action(text: "Go to bathroom", nextScene: Scene.bathroom())
}
}
extension Scene {
static func start() -> Scene {
return Scene(text: "You're standing in a giant hallway.", actions: [Action.hallwayToDiningRoom()], npcs: nil, nextScene: nil)
}
static func itsATrap() -> Scene {
let p = Scene(text: "It's a trap...", actions: nil, npcs: nil, nextScene: Scene.damnTrapped())
p.notBefore = Date(timeIntervalSinceNow: 10)
return p
}
static func damnTrapped() -> Scene {
let p = Scene(text: "Damn you're trapped..it's over 😌", actions: nil, npcs: nil, nextScene: nil)
p.notBefore = Date(timeIntervalSinceNow: 13)
return p
}
static func diningRoom() -> Scene {
return Scene(text: "Oh, a dining room.", actions: [Action.goToBathroom()], npcs: nil, nextScene: nil)
}
static func diningRoomBack() -> Scene {
return Scene(text: "Oh, a dining room. Again.", actions: nil, npcs: nil, nextScene: Scene.itsATrap())
}
static func bathroom() -> Scene {
return Scene(text: "Smelly old bathroom", actions: [Action.escapeThroughWindow(), Action.backToDiningRoom()], npcs: nil, nextScene: nil)
}
static func outside() -> Scene {
return Scene(text: "You're outside, it's over now!", actions: nil, npcs: nil, nextScene: Scene.gameOver())
}
static func gameOver() -> Scene {
let p = Scene(text: "Really, over!", actions: nil, npcs: nil, nextScene: nil)
p.notBefore = Date(timeIntervalSinceNow: 15)
return p
}
}
extension Player {
static func main() -> Player {
return Player(name: "Marcus")
}
}
| mit | b34f9ad55df0f57ec29749fe06643328 | 31.148649 | 144 | 0.619168 | 3.705607 | false | false | false | false |
agrippa1994/iOS-FH-Widget | Pods/EVReflection/EVReflection/pod/EVExtensions.swift | 2 | 5034 | //
// EVExtensions.swift
// EVReflection
//
// Created by Edwin Vermeer on 9/2/15.
// Copyright © 2015 evict. All rights reserved.
//
import Foundation
/**
Implementation for Equatable ==
- parameter lhs: The object at the left side of the ==
- parameter rhs: The object at the right side of the ==
:returns: True if the objects are the same, otherwise false.
*/
public func ==(lhs: EVObject, rhs: EVObject) -> Bool {
return EVReflection.areEqual(lhs, rhs: rhs)
}
/**
Implementation for Equatable !=
- parameter lhs: The object at the left side of the ==
- parameter rhs: The object at the right side of the ==
:returns: False if the objects are the the same, otherwise true.
*/
public func !=(lhs: EVObject, rhs: EVObject) -> Bool {
return !EVReflection.areEqual(lhs, rhs: rhs)
}
/**
Extending the NSObject
*/
public extension NSObject {
/**
Convenience init for creating an object whith the property values of a dictionary.
*/
public convenience init(dictionary:NSDictionary) {
self.init()
EVReflection.setPropertiesfromDictionary(dictionary, anyObject: self)
}
/**
Convenience init for creating an object whith the contents of a json string.
*/
public convenience init(json:String?) {
self.init()
let jsonDict = EVReflection.dictionaryFromJson(json)
EVReflection.setPropertiesfromDictionary(jsonDict, anyObject: self)
}
/**
Returns the dictionary representation of this object.
:parameter: performKeyCleanup set to true if you want to cleanup the keys
:returns: The dictionary
*/
final public func toDictionary(performKeyCleanup:Bool = false) -> NSDictionary {
let (reflected, _) = EVReflection.toDictionary(self, performKeyCleanup: performKeyCleanup)
return reflected
}
/**
Convert this object to a json string
:parameter: performKeyCleanup set to true if you want to cleanup the keys
:returns: The json string
*/
final public func toJsonString(performKeyCleanup:Bool = false) -> String {
return EVReflection.toJsonString(self, performKeyCleanup: performKeyCleanup)
}
/**
Convenience method for instantiating an array from a json string.
:parameter: json The json string
:returns: An array of objects
*/
public class func arrayFromJson<T where T:NSObject>(json:String?) -> [T] {
return EVReflection.arrayFromJson(T(), json: json)
}
/**
Auto map an opbject to an object of an other type.
Properties with the same name will be mapped automattically.
Automattic cammpelCase, PascalCase, snake_case conversion
Supports propperty mapping and conversion when using EVObject as base class
- returns: The targe object with the mapped values
*/
public func mapObjectTo<T where T:NSObject>() -> T {
let nsobjectype : NSObject.Type = T.self as NSObject.Type
let nsobject: NSObject = nsobjectype.init()
let dict = self.toDictionary()
let result = EVReflection.setPropertiesfromDictionary(dict, anyObject: nsobject)
return result as! T
}
}
/**
Extending Array with an initializer with a json string
*/
public extension Array {
/**
Initialize an array based on a json string
:parameter: json The json string
:returns: The array of objects
*/
public init(json:String?){
self.init()
let arrayTypeInstance = getArrayTypeInstance(self)
let newArray = EVReflection.arrayFromJson(arrayTypeInstance, json: json)
for item in newArray {
self.append(item)
}
}
/**
Get the type of the object where this array is for
:parameter: arr this array
:returns: The object type
*/
public func getArrayTypeInstance<T>(arr:Array<T>) -> T {
return arr.getTypeInstance()
}
/**
Get the type of the object where this array is for
:returns: The object type
*/
public func getTypeInstance<T>(
) -> T {
let nsobjectype : NSObject.Type = T.self as! NSObject.Type
let nsobject: NSObject = nsobjectype.init()
return nsobject as! T
}
/**
Convert this array to a json string
:parameter: performKeyCleanup set to true if you want to cleanup the keys
:returns: The json string
*/
public func toJsonString(performKeyCleanup:Bool = false) -> String {
return "[\n" + self.map({($0 as! NSObject).toJsonString(performKeyCleanup)}).joinWithSeparator(", \n") + "\n]"
}
/**
Returns the dictionary representation of this array.
:parameter: performKeyCleanup set to true if you want to cleanup the keys
:returns: The array of dictionaries
*/
public func toDictionaryArray(performKeyCleanup:Bool = false) -> NSArray {
return self.map({($0 as! NSObject).toDictionary(performKeyCleanup)})
}
}
| mit | f882688c365fc30f3cc1926c69a68721 | 28.092486 | 118 | 0.655275 | 4.49375 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/ConversationV1/Models/CreateValue.swift | 2 | 3990 | /**
* Copyright IBM Corporation 2018
*
* 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
/** CreateValue. */
public struct CreateValue: Encodable {
/// Specifies the type of value.
public enum ValueType: String {
case synonyms = "synonyms"
case patterns = "patterns"
}
/// The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters.
public var value: String
/// Any metadata related to the entity value.
public var metadata: [String: JSON]?
/// An array containing any synonyms for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A synonym must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters.
public var synonyms: [String]?
/// An array of patterns for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A pattern is a regular expression no longer than 128 characters. For more information about how to specify a pattern, see the [documentation](https://console.bluemix.net/docs/services/conversation/entities.html#creating-entities).
public var patterns: [String]?
/// Specifies the type of value.
public var valueType: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case value = "value"
case metadata = "metadata"
case synonyms = "synonyms"
case patterns = "patterns"
case valueType = "type"
}
/**
Initialize a `CreateValue` with member variables.
- parameter value: The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters.
- parameter metadata: Any metadata related to the entity value.
- parameter synonyms: An array containing any synonyms for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A synonym must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer than 64 characters.
- parameter patterns: An array of patterns for the entity value. You can provide either synonyms or patterns (as indicated by **type**), but not both. A pattern is a regular expression no longer than 128 characters. For more information about how to specify a pattern, see the [documentation](https://console.bluemix.net/docs/services/conversation/entities.html#creating-entities).
- parameter valueType: Specifies the type of value.
- returns: An initialized `CreateValue`.
*/
public init(value: String, metadata: [String: JSON]? = nil, synonyms: [String]? = nil, patterns: [String]? = nil, valueType: String? = nil) {
self.value = value
self.metadata = metadata
self.synonyms = synonyms
self.patterns = patterns
self.valueType = valueType
}
}
| mit | 992057ae03457351f87c289f6669fdee | 55.197183 | 386 | 0.719799 | 4.65035 | false | false | false | false |
kylestew/p5native.js | p5native/p5ViewController.swift | 1 | 5819 | import UIKit
import WebKit
public protocol p5PropsDelegate {
func p5PropUpdated(key: String, value: AnyObject)
func p5PropBound(binding: NSDictionary)
}
public class p5ViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler {
public var propsDelegate:p5PropsDelegate?
var webView:WKWebView?
var canvasSize = CGSizeZero
public override func viewDidLoad() {
super.viewDidLoad()
let controller = WKUserContentController()
controller.addScriptMessageHandler(self, name: "debugLog")
controller.addScriptMessageHandler(self, name: "props")
controller.addScriptMessageHandler(self, name: "propRegistration")
let config = WKWebViewConfiguration()
config.userContentController = controller
webView = WKWebView(frame: self.view.bounds, configuration: config)
webView?.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
if let wv = webView {
wv.navigationDelegate = self
view.addSubview(wv)
wv.scrollView.bounces = false // lock down scroll
}
}
var script:String?
public override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
canvasSize = view.bounds.size
if let script = script {
loadScript(script)
}
}
public func loadp5Script(javascript: String) {
// save until we have proper view size
script = javascript
}
func loadScript(var script: String) {
// basic html5 environment with p5js
if let webView = webView {
if let indexURL = NSBundle(forClass: self.dynamicType).URLForResource("index", withExtension: "html") {
webView.loadFileURL(indexURL, allowingReadAccessToURL: indexURL)
// inject view size into p5 script via the arcane magics on REGEX
if let match = script.rangeOfString("(createCanvas\\s?)(\\([^\\)]*\\))", options: .RegularExpressionSearch) {
var str = script.substringWithRange(match)
str = str.stringByReplacingOccurrencesOfString(" ", withString: "")
str = str.stringByReplacingOccurrencesOfString("createCanvas(", withString: "")
str = str.stringByReplacingOccurrencesOfString(")", withString: "")
let args = str.componentsSeparatedByString(",")
var replace:String
if (args.count == 3) {
replace = "createCanvas(\(Int(canvasSize.width)),\(Int(canvasSize.height)),\(args[2]))"
} else {
replace = "createCanvas(\(Int(canvasSize.width)),\(Int(canvasSize.height)))"
}
script.replaceRange(match, with: replace)
} else {
let inject = "\n\tcreateCanvas(\(Int(canvasSize.width)),\(Int(canvasSize.height)));\n"
// coder did not provide createCanvas() call, add one in setup block
if let match = script.rangeOfString("(setup\\s?[^\\{]*\\{)", options: .RegularExpressionSearch) {
let before = Range(start: script.startIndex, end: match.endIndex)
let after = Range(start: match.endIndex, end: script.endIndex)
script = script[before] + inject + script[after]
} else {
// no setup() function exists, just inject one
script = "function setup(){\(inject)}\n" + script
}
}
webView.evaluateJavaScript(script, completionHandler: { (object, error) -> Void in
print("p5 script loaded")
if (error != nil) {
print("SKETCH ERROR: \(error)")
let alert = UIAlertController(title: "Sketch Error", message: "Could not run your JavaScript sketch, check those codes.", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
})
}
}
}
public func setProp(key: String, value: AnyObject) {
webView?.evaluateJavaScript("receivePropUpdate(\"\(key)\", \(value))") { (value, error) in
print(error)
}
}
public func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let delegate = propsDelegate {
if (message.name == "debugLog") {
// pass to console
if let msg = message.body as? String {
print(msg)
}
} else if message.name == "propRegistration" {
if let binding = message.body as? NSDictionary {
delegate.p5PropBound(binding)
}
} else {
if let props = message.body as? [String:AnyObject] {
for (key, value) in props {
delegate.p5PropUpdated(key, value: value)
}
}
}
}
}
public func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
print(error)
assert(true)
}
} | lgpl-2.1 | ca5f79335a9fe249ce09230613a6d3f1 | 40.276596 | 169 | 0.537206 | 5.605973 | false | false | false | false |
eflyjason/astro-daily | Astro Daily - APP/Astro Daily/WebPageViewController.swift | 1 | 3723 | //
// WebPageViewController.swift
// 星座運勢
//
// Created by Arefly on 21/1/2015.
// Copyright (c) 2015年 Arefly. All rights reserved.
//
import UIKit
import CoreData
import Foundation
class WebPageViewController: UIViewController { //网页浏览视图
@IBOutlet var day_webView: UIWebView!
@IBOutlet var week_webView: UIWebView!
@IBOutlet var disposition_webView: UIWebView!
@IBOutlet var barnum_webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.sharedApplication().applicationIconBadgeNumber = 0; //清除Home图标右上角的未读次数
let defaults = NSUserDefaults.standardUserDefaults()
var name = defaults.stringForKey("name") as String!
var birthday = defaults.stringForKey("birthday") as String!
if (name == nil) {
var vc = self.storyboard?.instantiateViewControllerWithIdentifier("startView") as OptionViewController
self.presentViewController(vc, animated: true, completion: nil)
}
if (birthday == nil) {
var vc = self.storyboard?.instantiateViewControllerWithIdentifier("startView") as OptionViewController
self.presentViewController(vc, animated: true, completion: nil)
}
if (name == nil) || (birthday == nil) {
//DO NOTHING
}else{
if self.restorationIdentifier == "astro_day" {
let day_url = NSURL(string: "http://file.arefly.com/astro/astro.php?type=day&birthday=" + birthday + "&name=" + name.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
let day_url_request = NSURLRequest(URL: day_url!,
cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 60*60*6)
day_webView.loadRequest(day_url_request)
} else if self.restorationIdentifier == "astro_week" {
let week_url = NSURL(string: "http://file.arefly.com/astro/astro.php?type=week&birthday=" + birthday + "&name=" + name.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
let week_url_request = NSURLRequest(URL: week_url!,
cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 60*60*24*3)
week_webView.loadRequest(week_url_request)
} else if self.restorationIdentifier == "astro_disposition" {
let disposition_url = NSURL(string: "http://file.arefly.com/astro/astro.php?type=disposition&birthday=" + birthday + "&name=" + name.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
let disposition_url_request = NSURLRequest(URL: disposition_url!,
cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 60*60*24*7)
disposition_webView.loadRequest(disposition_url_request)
} else if self.restorationIdentifier == "barnum_effect" {
let barnum_url = NSURL(string: "http://file.arefly.com/astro/astro.php?type=barnum&birthday=" + birthday + "&name=" + name.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
let barnum_url_request = NSURLRequest(URL: barnum_url!)
barnum_webView.loadRequest(barnum_url_request)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 40ec5220bebb66e871e4a6d2c3a212af | 45.544304 | 214 | 0.6421 | 4.968919 | false | false | false | false |
ranacquat/fish | Shared/Results.swift | 1 | 471 | //
// Result.swift
// KYCMobile
//
// Created by Jan ATAC on 27/10/2016.
// Copyright © 2016 Vialink. All rights reserved.
//
import Foundation
class Results{
var id:Int = 0
var data:[String:Any] = [String:Any]()
var score:Int = 0
init(){
self.id = Generator().newId()
}
init(with globalResult:GlobalResult){
self.score = globalResult.scoring.confidenceIndex
}
}
| mit | 9a6b962bfb6eeefe57d10eb82adcbc0f | 17.076923 | 57 | 0.544681 | 3.560606 | false | false | false | false |
brentsimmons/Evergreen | Mac/MainWindow/AddFeed/AddFeedController.swift | 1 | 5566 | //
// AddFeedController.swift
// NetNewsWire
//
// Created by Brent Simmons on 8/28/16.
// Copyright © 2016 Ranchero Software, LLC. All rights reserved.
//
import AppKit
import RSCore
import RSCoreResources
import RSTree
import Articles
import Account
import RSParser
// Run add-feed sheet.
// If it returns with URL and optional name,
// run FeedFinder plus modal progress window.
// If FeedFinder returns feed,
// add feed.
// Else,
// display error sheet.
class AddFeedController: AddFeedWindowControllerDelegate {
private let hostWindow: NSWindow
private var addFeedWindowController: AddFeedWindowController?
private var foundFeedURLString: String?
private var titleFromFeed: String?
init(hostWindow: NSWindow) {
self.hostWindow = hostWindow
}
func showAddFeedSheet(_ type: AddFeedWindowControllerType, _ urlString: String? = nil, _ name: String? = nil, _ account: Account? = nil, _ folder: Folder? = nil) {
let folderTreeControllerDelegate = FolderTreeControllerDelegate()
let folderTreeController = TreeController(delegate: folderTreeControllerDelegate)
switch type {
case .webFeed:
addFeedWindowController = AddWebFeedWindowController(urlString: urlString ?? urlStringFromPasteboard,
name: name,
account: account,
folder: folder,
folderTreeController: folderTreeController,
delegate: self)
case .redditFeed:
addFeedWindowController = AddRedditFeedWindowController(folderTreeController: folderTreeController,
delegate: self)
case .twitterFeed:
addFeedWindowController = AddTwitterFeedWindowController(folderTreeController: folderTreeController,
delegate: self)
}
addFeedWindowController!.runSheetOnWindow(hostWindow)
}
// MARK: AddFeedWindowControllerDelegate
func addFeedWindowController(_: AddFeedWindowController, userEnteredURL url: URL, userEnteredTitle title: String?, container: Container) {
closeAddFeedSheet(NSApplication.ModalResponse.OK)
guard let accountAndFolderSpecifier = accountAndFolderFromContainer(container) else {
return
}
let account = accountAndFolderSpecifier.account
if account.hasWebFeed(withURL: url.absoluteString) {
showAlreadySubscribedError(url.absoluteString)
return
}
account.createWebFeed(url: url.absoluteString, name: title, container: container, validateFeed: true) { result in
DispatchQueue.main.async {
self.endShowingProgress()
}
switch result {
case .success(let feed):
NotificationCenter.default.post(name: .UserDidAddFeed, object: self, userInfo: [UserInfoKey.webFeed: feed])
case .failure(let error):
switch error {
case AccountError.createErrorAlreadySubscribed:
self.showAlreadySubscribedError(url.absoluteString)
case AccountError.createErrorNotFound:
self.showNoFeedsErrorMessage()
default:
DispatchQueue.main.async {
NSApplication.shared.presentError(error)
}
}
}
}
beginShowingProgress()
}
func addFeedWindowControllerUserDidCancel(_: AddFeedWindowController) {
closeAddFeedSheet(NSApplication.ModalResponse.cancel)
}
}
private extension AddFeedController {
var urlStringFromPasteboard: String? {
if let urlString = NSPasteboard.urlString(from: NSPasteboard.general) {
return urlString.normalizedURL
}
return nil
}
struct AccountAndFolderSpecifier {
let account: Account
let folder: Folder?
}
func accountAndFolderFromContainer(_ container: Container) -> AccountAndFolderSpecifier? {
if let account = container as? Account {
return AccountAndFolderSpecifier(account: account, folder: nil)
}
if let folder = container as? Folder, let account = folder.account {
return AccountAndFolderSpecifier(account: account, folder: folder)
}
return nil
}
func closeAddFeedSheet(_ returnCode: NSApplication.ModalResponse) {
if let sheetWindow = addFeedWindowController?.window {
hostWindow.endSheet(sheetWindow, returnCode: returnCode)
}
}
// MARK: Errors
func showAlreadySubscribedError(_ urlString: String) {
let alert = NSAlert()
alert.alertStyle = .informational
alert.messageText = NSLocalizedString("Already subscribed", comment: "Feed finder")
alert.informativeText = NSLocalizedString("Can’t add this feed because you’ve already subscribed to it.", comment: "Feed finder")
alert.beginSheetModal(for: hostWindow)
}
func showInitialDownloadError(_ error: Error) {
let alert = NSAlert()
alert.alertStyle = .informational
alert.messageText = NSLocalizedString("Download Error", comment: "Feed finder")
let formatString = NSLocalizedString("Can’t add this feed because of a download error: “%@”", comment: "Feed finder")
let errorText = NSString.localizedStringWithFormat(formatString as NSString, error.localizedDescription)
alert.informativeText = errorText as String
alert.beginSheetModal(for: hostWindow)
}
func showNoFeedsErrorMessage() {
let alert = NSAlert()
alert.alertStyle = .informational
alert.messageText = NSLocalizedString("Feed not found", comment: "Feed finder")
alert.informativeText = NSLocalizedString("Can’t add a feed because no feed was found.", comment: "Feed finder")
alert.beginSheetModal(for: hostWindow)
}
// MARK: Progress
func beginShowingProgress() {
runIndeterminateProgressWithMessage(NSLocalizedString("Finding feed…", comment:"Feed finder"))
}
func endShowingProgress() {
stopIndeterminateProgress()
hostWindow.makeKeyAndOrderFront(self)
}
}
| mit | 5342ecb2f838e9d6a093420ecb30eec8 | 30.185393 | 164 | 0.748334 | 4.18312 | false | false | false | false |
natecook1000/swift | test/SILGen/decls.swift | 1 | 6540 | // RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle -parse-as-library -enable-sil-ownership %s | %FileCheck %s
// CHECK-LABEL: sil hidden @$S5decls11void_returnyyF
// CHECK: = tuple
// CHECK: return
func void_return() {
}
// CHECK-LABEL: sil hidden @$S5decls14typealias_declyyF
func typealias_decl() {
typealias a = Int
}
// CHECK-LABEL: sil hidden @$S5decls15simple_patternsyyF
func simple_patterns() {
_ = 4
var _ : Int
}
// CHECK-LABEL: sil hidden @$S5decls13named_patternSiyF
func named_pattern() -> Int {
var local_var : Int = 4
var defaulted_var : Int // Defaults to zero initialization
return local_var + defaulted_var
}
func MRV() -> (Int, Float, (), Double) {}
// CHECK-LABEL: sil hidden @$S5decls14tuple_patternsyyF
func tuple_patterns() {
var (a, b) : (Int, Float)
// CHECK: [[ABOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[AADDR:%[0-9]+]] = mark_uninitialized [var] [[ABOX]]
// CHECK: [[PBA:%.*]] = project_box [[AADDR]]
// CHECK: [[BBOX:%[0-9]+]] = alloc_box ${ var Float }
// CHECK: [[BADDR:%[0-9]+]] = mark_uninitialized [var] [[BBOX]]
// CHECK: [[PBB:%.*]] = project_box [[BADDR]]
var (c, d) = (a, b)
// CHECK: [[CADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBC:%.*]] = project_box [[CADDR]]
// CHECK: [[DADDR:%[0-9]+]] = alloc_box ${ var Float }
// CHECK: [[PBD:%.*]] = project_box [[DADDR]]
// CHECK: [[READA:%.*]] = begin_access [read] [unknown] [[PBA]] : $*Int
// CHECK: copy_addr [[READA]] to [initialization] [[PBC]]
// CHECK: [[READB:%.*]] = begin_access [read] [unknown] [[PBB]] : $*Float
// CHECK: copy_addr [[READB]] to [initialization] [[PBD]]
// CHECK: [[EADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBE:%.*]] = project_box [[EADDR]]
// CHECK: [[FADDR:%[0-9]+]] = alloc_box ${ var Float }
// CHECK: [[PBF:%.*]] = project_box [[FADDR]]
// CHECK: [[GADDR:%[0-9]+]] = alloc_box ${ var () }
// CHECK: [[HADDR:%[0-9]+]] = alloc_box ${ var Double }
// CHECK: [[PBH:%.*]] = project_box [[HADDR]]
// CHECK: [[EFGH:%[0-9]+]] = apply
// CHECK: ([[E:%[0-9]+]], [[F:%[0-9]+]], [[H:%[0-9]+]]) = destructure_tuple
// CHECK: store [[E]] to [trivial] [[PBE]]
// CHECK: store [[F]] to [trivial] [[PBF]]
// CHECK: store [[H]] to [trivial] [[PBH]]
var (e,f,g,h) : (Int, Float, (), Double) = MRV()
// CHECK: [[IADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBI:%.*]] = project_box [[IADDR]]
// CHECK-NOT: alloc_box ${ var Float }
// CHECK: [[READA:%.*]] = begin_access [read] [unknown] [[PBA]] : $*Int
// CHECK: copy_addr [[READA]] to [initialization] [[PBI]]
// CHECK: [[READB:%.*]] = begin_access [read] [unknown] [[PBB]] : $*Float
// CHECK: [[B:%[0-9]+]] = load [trivial] [[READB]]
// CHECK-NOT: store [[B]]
var (i,_) = (a, b)
// CHECK: [[JADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBJ:%.*]] = project_box [[JADDR]]
// CHECK-NOT: alloc_box ${ var Float }
// CHECK: [[KADDR:%[0-9]+]] = alloc_box ${ var () }
// CHECK-NOT: alloc_box ${ var Double }
// CHECK: [[J_K_:%[0-9]+]] = apply
// CHECK: ([[J:%[0-9]+]], [[K:%[0-9]+]], {{%[0-9]+}}) = destructure_tuple
// CHECK: store [[J]] to [trivial] [[PBJ]]
var (j,_,k,_) : (Int, Float, (), Double) = MRV()
}
// CHECK-LABEL: sil hidden @$S5decls16simple_arguments{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : @trivial $Int, %1 : @trivial $Int):
// CHECK: [[X:%[0-9]+]] = alloc_box ${ var Int }
// CHECK-NEXT: [[PBX:%.*]] = project_box [[X]]
// CHECK-NEXT: store %0 to [trivial] [[PBX]]
// CHECK-NEXT: [[Y:%[0-9]+]] = alloc_box ${ var Int }
// CHECK-NEXT: [[PBY:%[0-9]+]] = project_box [[Y]]
// CHECK-NEXT: store %1 to [trivial] [[PBY]]
func simple_arguments(x: Int, y: Int) -> Int {
var x = x
var y = y
return x+y
}
// CHECK-LABEL: sil hidden @$S5decls14tuple_argument{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : @trivial $Int, %1 : @trivial $Float):
// CHECK: [[UNIT:%[0-9]+]] = tuple ()
// CHECK: [[TUPLE:%[0-9]+]] = tuple (%0 : $Int, %1 : $Float, [[UNIT]] : $())
func tuple_argument(x: (Int, Float, ())) {
}
// CHECK-LABEL: sil hidden @$S5decls14inout_argument{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : @trivial $*Int, %1 : @trivial $Int):
// CHECK: [[X_LOCAL:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBX:%.*]] = project_box [[X_LOCAL]]
func inout_argument(x: inout Int, y: Int) {
var y = y
x = y
}
var global = 42
// CHECK-LABEL: sil hidden @$S5decls16load_from_global{{[_0-9a-zA-Z]*}}F
func load_from_global() -> Int {
return global
// CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @$S5decls6globalSivau
// CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]()
// CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]]
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int
// CHECK: [[VALUE:%[0-9]+]] = load [trivial] [[READ]]
// CHECK: return [[VALUE]]
}
// CHECK-LABEL: sil hidden @$S5decls15store_to_global{{[_0-9a-zA-Z]*}}F
func store_to_global(x: Int) {
var x = x
global = x
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBX:%.*]] = project_box [[XADDR]]
// CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @$S5decls6globalSivau
// CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]()
// CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBX]] : $*Int
// CHECK: [[COPY:%.*]] = load [trivial] [[READ]] : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int
// CHECK: assign [[COPY]] to [[WRITE]] : $*Int
// CHECK: end_access [[WRITE]] : $*Int
// CHECK: return
}
struct S {
var x:Int
// CHECK-LABEL: sil hidden @$S5decls1SVACycfC
init() {
x = 219
}
init(a:Int, b:Int) {
x = a + b
}
}
// CHECK-LABEL: StructWithStaticVar.init
// rdar://15821990 - Don't emit default value for static var in instance init()
struct StructWithStaticVar {
static var a : String = ""
var b : String = ""
init() {
}
}
// Make sure unbound method references on class hierarchies are
// properly represented in the AST
class Base {
func method1() -> Self { return self }
func method2() -> Self { return self }
}
class Derived : Base {
override func method2() -> Self { return self }
}
func generic<T>(arg: T) { }
func unboundMethodReferences() {
generic(arg: Derived.method1)
generic(arg: Derived.method2)
_ = type(of: Derived.method1)
_ = type(of: Derived.method2)
}
// CHECK-LABEL: sil_vtable EscapeKeywordsInDottedPaths
class EscapeKeywordsInDottedPaths {
// CHECK: #EscapeKeywordsInDottedPaths.`switch`!getter.1
var `switch`: String = ""
}
| apache-2.0 | b3f3fd174f139b5a9fbaa75642e71385 | 32.71134 | 118 | 0.561162 | 2.94197 | false | false | false | false |
Johennes/firefox-ios | Client/Frontend/Home/ActivityStreamTopSitesCell.swift | 1 | 19302 | import Foundation
import Shared
import WebImage
import Storage
struct TopSiteCellUX {
static let TitleHeight: CGFloat = 32
static let TitleBackgroundColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 0.7)
static let TitleTextColor = UIColor.blackColor()
static let TitleFont = DynamicFontHelper.defaultHelper.DefaultSmallFont
static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25)
static let CellCornerRadius: CGFloat = 4
static let TitleOffset: CGFloat = 5
static let OverlayColor = UIColor(white: 0.0, alpha: 0.25)
static let IconSize = CGSize(width: 32, height: 32)
static let BorderColor = UIColor(white: 0, alpha: 0.1)
static let BorderWidth: CGFloat = 0.5
}
/*
* The TopSite cell that appears in the ASHorizontalScrollView.
*/
class TopSiteItemCell: UICollectionViewCell {
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.layer.masksToBounds = true
return imageView
}()
lazy private var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.layer.masksToBounds = true
titleLabel.textAlignment = .Center
titleLabel.font = TopSiteCellUX.TitleFont
titleLabel.textColor = TopSiteCellUX.TitleTextColor
titleLabel.backgroundColor = UIColor.clearColor()
return titleLabel
}()
lazy var selectedOverlay: UIView = {
let selectedOverlay = UIView()
selectedOverlay.backgroundColor = TopSiteCellUX.OverlayColor
selectedOverlay.hidden = true
return selectedOverlay
}()
lazy var titleBorder: CALayer = {
let border = CALayer()
border.backgroundColor = TopSiteCellUX.BorderColor.CGColor
return border
}()
override var selected: Bool {
didSet {
self.selectedOverlay.hidden = !selected
}
}
override init(frame: CGRect) {
super.init(frame: frame)
isAccessibilityElement = true
accessibilityIdentifier = "TopSite"
contentView.layer.cornerRadius = TopSiteCellUX.CellCornerRadius
contentView.layer.masksToBounds = true
contentView.layer.borderWidth = TopSiteCellUX.BorderWidth
contentView.layer.borderColor = TopSiteCellUX.BorderColor.CGColor
let titleWrapper = UIView()
titleWrapper.backgroundColor = TopSiteCellUX.TitleBackgroundColor
titleWrapper.layer.masksToBounds = true
contentView.addSubview(titleWrapper)
contentView.addSubview(titleLabel)
contentView.addSubview(imageView)
contentView.addSubview(selectedOverlay)
titleLabel.snp_makeConstraints { make in
make.left.equalTo(self).offset(TopSiteCellUX.TitleOffset)
make.right.equalTo(self).offset(-TopSiteCellUX.TitleOffset)
make.height.equalTo(TopSiteCellUX.TitleHeight)
make.bottom.equalTo(self)
}
imageView.snp_makeConstraints { make in
make.size.equalTo(TopSiteCellUX.IconSize)
// Add an offset to the image to make it appear centered with the titleLabel
make.center.equalTo(self.snp_center).offset(UIEdgeInsets(top: -TopSiteCellUX.TitleHeight/2, left: 0, bottom: 0, right: 0))
}
selectedOverlay.snp_makeConstraints { make in
make.edges.equalTo(contentView)
}
titleWrapper.snp_makeConstraints { make in
make.left.right.bottom.equalTo(self)
make.height.equalTo(TopSiteCellUX.TitleHeight)
}
// The titleBorder must appear ABOVE the titleLabel. Meaning it must be 0.5 pixels above of the titleWrapper frame.
titleBorder.frame = CGRectMake(0, CGRectGetHeight(self.frame) - TopSiteCellUX.TitleHeight - TopSiteCellUX.BorderWidth, CGRectGetWidth(self.frame), TopSiteCellUX.BorderWidth)
self.contentView.layer.addSublayer(titleBorder)
}
override func layoutSubviews() {
super.layoutSubviews()
titleBorder.frame = CGRectMake(0, frame.height - TopSiteCellUX.TitleHeight - TopSiteCellUX.BorderWidth, frame.width, TopSiteCellUX.BorderWidth)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
contentView.backgroundColor = UIColor.lightGrayColor()
imageView.image = nil
titleLabel.text = ""
}
private func setImageWithURL(url: NSURL) {
imageView.sd_setImageWithURL(url) { [unowned self] (img, err, type, url) -> Void in
guard let img = img else {
self.contentView.backgroundColor = FaviconFetcher.getDefaultColor(url)
self.imageView.image = FaviconFetcher.getDefaultFavicon(url)
return
}
img.getColors(CGSize(width: 25, height: 25)) { colors in
self.contentView.backgroundColor = colors.backgroundColor ?? UIColor.lightGrayColor()
}
}
}
func configureWithTopSiteItem(site: Site) {
titleLabel.text = site.tileURL.extractDomainName()
accessibilityLabel = titleLabel.text
if let suggestedSite = site as? SuggestedSite {
let img = UIImage(named: suggestedSite.faviconImagePath!)
imageView.image = img
// This is a temporary hack to make amazon/wikipedia have white backrounds instead of their default blacks
// Once we remove the old TopSitesPanel we can change the values of amazon/wikipedia to be white instead of black.
contentView.backgroundColor = suggestedSite.backgroundColor.isBlackOrWhite ? UIColor.whiteColor() : suggestedSite.backgroundColor
} else {
guard let url = site.icon?.url, favURL = url.asURL else {
let siteURL = site.url.asURL!
self.contentView.backgroundColor = FaviconFetcher.getDefaultColor(siteURL)
self.imageView.image = FaviconFetcher.getDefaultFavicon(siteURL)
return
}
setImageWithURL(favURL)
}
}
}
struct ASHorizontalScrollCellUX {
static let TopSiteCellIdentifier = "TopSiteItemCell"
static let TopSiteItemSize = CGSize(width: 99, height: 99)
static let BackgroundColor = UIColor.whiteColor()
static let PageControlRadius: CGFloat = 3
static let PageControlSize = CGSize(width: 30, height: 15)
static let PageControlOffset: CGFloat = -20
}
/*
The View that describes the topSite cell that appears in the tableView.
*/
class ASHorizontalScrollCell: UITableViewCell {
lazy var collectionView: UICollectionView = {
let layout = HorizontalFlowLayout()
layout.itemSize = ASHorizontalScrollCellUX.TopSiteItemSize
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.registerClass(TopSiteItemCell.self, forCellWithReuseIdentifier: ASHorizontalScrollCellUX.TopSiteCellIdentifier)
collectionView.backgroundColor = ASHorizontalScrollCellUX.BackgroundColor
collectionView.showsHorizontalScrollIndicator = false
collectionView.isAccessibilityElement = false
collectionView.pagingEnabled = true
return collectionView
}()
lazy private var pageControl: FilledPageControl = {
let pageControl = FilledPageControl()
pageControl.tintColor = UIColor.grayColor()
pageControl.indicatorRadius = ASHorizontalScrollCellUX.PageControlRadius
pageControl.userInteractionEnabled = true
pageControl.isAccessibilityElement = true
pageControl.accessibilityIdentifier = "pageControl"
pageControl.accessibilityLabel = Strings.ASPageControlButton
pageControl.accessibilityTraits = UIAccessibilityTraitButton
return pageControl
}()
lazy private var pageControlPress: UITapGestureRecognizer = {
let press = UITapGestureRecognizer(target: self, action: #selector(ASHorizontalScrollCell.handlePageTap(_:)))
press.delegate = self
return press
}()
weak var delegate: ASHorizontalScrollCellManager? {
didSet {
collectionView.delegate = delegate
collectionView.dataSource = delegate
delegate?.pageChangedHandler = { [weak self] progress in
self?.currentPageChanged(progress)
}
dispatch_async(dispatch_get_main_queue()) {
self.collectionView.reloadData()
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
isAccessibilityElement = false
accessibilityIdentifier = "TopSitesCell"
backgroundColor = ASHorizontalScrollCellUX.BackgroundColor
contentView.addSubview(collectionView)
contentView.addSubview(pageControl)
self.selectionStyle = UITableViewCellSelectionStyle.None
pageControl.addGestureRecognizer(self.pageControlPress)
collectionView.snp_makeConstraints { make in
make.edges.equalTo(contentView).offset(UIEdgeInsets(top: 0, left: 0, bottom: ASHorizontalScrollCellUX.PageControlOffset, right: 0))
}
pageControl.snp_makeConstraints { make in
make.size.equalTo(ASHorizontalScrollCellUX.PageControlSize)
make.top.equalTo(collectionView.snp_bottom)
make.centerX.equalTo(self.snp_centerX)
}
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! HorizontalFlowLayout
pageControl.pageCount = layout.numberOfPages()
pageControl.hidden = pageControl.pageCount <= 1
}
func currentPageChanged(currentPage: CGFloat) {
pageControl.progress = currentPage
if currentPage == floor(currentPage) {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
self.setNeedsLayout()
}
}
func handlePageTap(gesture: UITapGestureRecognizer) {
guard pageControl.pageCount > 1 else {
return
}
if pageControl.pageCount > pageControl.currentPage + 1 {
pageControl.progress = CGFloat(pageControl.currentPage + 1)
} else {
pageControl.progress = CGFloat(pageControl.currentPage - 1)
}
let swipeCoordinate = CGFloat(pageControl.currentPage) * self.collectionView.frame.size.width
self.collectionView.setContentOffset(CGPointMake(swipeCoordinate, 0), animated: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/*
A custom layout used to show a horizontal scrolling list with paging. Similar to iOS springboard.
A modified version of http://stackoverflow.com/a/34167915
*/
class HorizontalFlowLayout: UICollectionViewLayout {
var itemSize = CGSize.zero
private var cellCount = 0
private var boundsSize = CGSize.zero
private var insets = UIEdgeInsetsZero
private let minimumInsets: CGFloat = 20
override func prepareLayout() {
super.prepareLayout()
cellCount = self.collectionView!.numberOfItemsInSection(0)
boundsSize = self.collectionView!.bounds.size
}
func numberOfPages() -> Int {
let itemsPerPage = maxVerticalItemsCount() * maxHorizontalItemsCount()
// Sometimes itemsPerPage is 0. In this case just return 0. We dont want to try dividing by 0.
return itemsPerPage == 0 ? 0 : Int(ceil(Double(cellCount) / Double(itemsPerPage)))
}
override func collectionViewContentSize() -> CGSize {
let contentSize = boundsSize
let horizontalItemsCount = maxHorizontalItemsCount()
let verticalItemsCount = maxVerticalItemsCount()
// Take the number of cells and subtract its space in the view from the height. The left over space is the white space.
// The left over space is then devided evenly into (n + 1) parts to figure out how much space should be inbetween a cell
var verticalInsets = (contentSize.height - (CGFloat(verticalItemsCount) * itemSize.height)) / CGFloat(verticalItemsCount + 1)
var horizontalInsets = (contentSize.width - (CGFloat(horizontalItemsCount) * itemSize.width)) / CGFloat(horizontalItemsCount + 1)
// We want a minimum inset to make things not look crowded. We also don't want uneven spacing.
// If we dont have this. Set a minimum inset and recalculate the size of a cell
if horizontalInsets < minimumInsets || horizontalInsets != verticalInsets {
verticalInsets = minimumInsets
horizontalInsets = minimumInsets
itemSize.width = (contentSize.width - (CGFloat(horizontalItemsCount + 1) * horizontalInsets)) / CGFloat(horizontalItemsCount)
itemSize.height = itemSize.width
}
insets = UIEdgeInsets(top: verticalInsets, left: horizontalInsets, bottom: verticalInsets, right: horizontalInsets)
var size = contentSize
size.width = CGFloat(numberOfPages()) * contentSize.width
return size
}
func maxVerticalItemsCount() -> Int {
let verticalItemsCount = Int(floor(boundsSize.height / (itemSize.height + insets.top)))
if let delegate = self.collectionView?.delegate as? ASHorizontalLayoutDelegate {
return delegate.numberOfVerticalItems()
} else {
return verticalItemsCount
}
}
func maxHorizontalItemsCount() -> Int {
let horizontalItemsCount = Int(floor(boundsSize.width / (itemSize.width + insets.left)))
if let delegate = self.collectionView?.delegate as? ASHorizontalLayoutDelegate {
return delegate.numberOfHorizontalItems()
} else {
return horizontalItemsCount
}
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
super.layoutAttributesForElementsInRect(rect)
var allAttributes = [UICollectionViewLayoutAttributes]()
for i in 0 ..< cellCount {
let indexPath = NSIndexPath(forRow: i, inSection: 0)
let attr = self.computeLayoutAttributesForCellAtIndexPath(indexPath)
allAttributes.append(attr)
}
return allAttributes
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
return self.computeLayoutAttributesForCellAtIndexPath(indexPath)
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
// Sometimes when the topsiteCell isnt on the screen the newbounds that it tries to layout in is very tiny
// Resulting in incorrect layouts. So only layout when the width is greater than 320.
return newBounds.width <= 320
}
func computeLayoutAttributesForCellAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes {
let row = indexPath.row
let bounds = self.collectionView!.bounds
let verticalItemsCount = maxVerticalItemsCount()
let horizontalItemsCount = maxHorizontalItemsCount()
let itemsPerPage = verticalItemsCount * horizontalItemsCount
let columnPosition = row % horizontalItemsCount
let rowPosition = (row / horizontalItemsCount) % verticalItemsCount
let itemPage = Int(floor(Double(row)/Double(itemsPerPage)))
let attr = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
var frame = CGRect.zero
frame.origin.x = CGFloat(itemPage) * bounds.size.width + CGFloat(columnPosition) * (itemSize.width + insets.left) + insets.left
frame.origin.y = CGFloat(rowPosition) * (itemSize.height + insets.top) + insets.top
frame.size = itemSize
attr.frame = frame
return attr
}
}
/*
Defines the number of items to show in topsites for different size classes.
*/
struct ASTopSiteSourceUX {
static let verticalItemsForTraitSizes = [UIUserInterfaceSizeClass.Compact : 1, UIUserInterfaceSizeClass.Regular : 2, UIUserInterfaceSizeClass.Unspecified: 0]
static let horizontalItemsForTraitSizes = [UIUserInterfaceSizeClass.Compact : 3, UIUserInterfaceSizeClass.Regular : 5, UIUserInterfaceSizeClass.Unspecified: 0]
static let maxNumberOfPages = 2
static let CellIdentifier = "TopSiteItemCell"
}
protocol ASHorizontalLayoutDelegate {
func numberOfVerticalItems() -> Int
func numberOfHorizontalItems() -> Int
}
/*
This Delegate/DataSource is used to manage the ASHorizontalScrollCell's UICollectionView.
This is left generic enough for it to be re used for other parts of Activity Stream.
*/
class ASHorizontalScrollCellManager: NSObject, UICollectionViewDelegate, UICollectionViewDataSource, ASHorizontalLayoutDelegate {
var content: [Site] = []
var urlPressedHandler: ((NSURL, NSIndexPath) -> Void)?
var pageChangedHandler: ((CGFloat) -> Void)?
// The current traits that define the parent ViewController. Used to determine how many rows/columns should be created.
var currentTraits: UITraitCollection?
// Size classes define how many items to show per row/column.
func numberOfVerticalItems() -> Int {
guard let traits = currentTraits else {
return 0
}
return ASTopSiteSourceUX.verticalItemsForTraitSizes[traits.verticalSizeClass]!
}
func numberOfHorizontalItems() -> Int {
guard let traits = currentTraits else {
return 0
}
// An iPhone 5 in both landscape/portrait is considered compactWidth which means we need to let the layout determine how many items to show based on actual width.
if traits.horizontalSizeClass == .Compact && traits.verticalSizeClass == .Compact {
return ASTopSiteSourceUX.horizontalItemsForTraitSizes[.Regular]!
}
return ASTopSiteSourceUX.horizontalItemsForTraitSizes[traits.horizontalSizeClass]!
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.content.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ASTopSiteSourceUX.CellIdentifier, forIndexPath: indexPath) as! TopSiteItemCell
let contentItem = content[indexPath.row]
cell.configureWithTopSiteItem(contentItem)
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let contentItem = content[indexPath.row]
guard let url = contentItem.url.asURL else {
return
}
urlPressedHandler?(url, indexPath)
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let pageWidth = CGRectGetWidth(scrollView.frame)
pageChangedHandler?(scrollView.contentOffset.x / pageWidth)
}
}
| mpl-2.0 | 54ca10fb8cde2b9564717908e41b3f18 | 40.688985 | 182 | 0.696664 | 5.288219 | false | false | false | false |
sprint84/TabbedCollectionView | TabbedCollectionView/TabButton.swift | 1 | 2957 | //
// TabButton.swift
// TabbedCollectionView
//
// Created by Guilherme Moura on 12/1/15.
// Copyright © 2015 Reefactor, Inc. All rights reserved.
//
import UIKit
class TabButton: UIButton {
var bgColor = UIColor(white: 0.95, alpha: 1.0) {
didSet {
backgroundColor = bgColor
}
}
var selectionColor = UIColor(red:0.9, green:0.36, blue:0.13, alpha:1)
var titleColor = UIColor.darkTextColor() {
didSet {
buildAttributedTitle()
}
}
private var title = ""
private var image = UIImage()
private var attributedTitle = NSAttributedString()
init(title: String, image: UIImage, color: UIColor) {
self.title = title
self.image = image
super.init(frame: CGRectZero)
buildAttributedTitle()
backgroundColor = bgColor
tintColor = color
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = bgColor
}
override var highlighted: Bool {
get {
return super.highlighted
}
set {
if newValue || selected {
backgroundColor = UIColor(white: 0.87, alpha: 1.0)
} else {
backgroundColor = bgColor
}
super.highlighted = newValue
}
}
override var selected: Bool {
get {
return super.selected
}
set {
if newValue {
backgroundColor = UIColor(white: 0.87, alpha: 1.0)
} else {
backgroundColor = bgColor
}
super.selected = newValue
setNeedsDisplay()
}
}
override func drawRect(rect: CGRect) {
if selected {
let underscore = UIBezierPath()
underscore.lineWidth = 3.0
underscore.moveToPoint(CGPoint(x:rect.origin.x, y:rect.size.height))
underscore.addLineToPoint(CGPoint(x:rect.size.width, y:rect.size.height))
selectionColor.setStroke()
underscore.stroke()
}
let imageFrame = CGRect(x: rect.width/2.0 - 8.0, y: 3, width: 16, height: 16)
self.tintColor.setFill()
image.drawInRect(imageFrame)
let textFrame = CGRect(x: 4, y: 20, width: rect.width - 8, height: 14)
attributedTitle.drawInRect(textFrame)
}
func buildAttributedTitle() {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .Center
paragraphStyle.lineBreakMode = .ByTruncatingMiddle
let attributes: [String: AnyObject] = [NSForegroundColorAttributeName: titleColor,
NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 8)!,
NSParagraphStyleAttributeName: paragraphStyle]
self.attributedTitle = NSAttributedString(string: title, attributes: attributes)
}
}
| mit | 37d9e1076b8010fa4c0a8e5ebee0376a | 29.474227 | 90 | 0.578823 | 4.822186 | false | false | false | false |
4jchc/4jchc-BaiSiBuDeJie | 4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/FriendTrends-关注/Controller/XMGRecommendViewController.swift | 1 | 12053 | //
// XMGRecommendViewController.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/2/16.
// Copyright © 2016年 蒋进. All rights reserved.
//
import UIKit
// Recommend推荐 ViewController
import SVProgressHUD
import MJExtension
import MJRefresh
class XMGRecommendViewController: UIViewController {
/** 左边的类别数据 */
var categorieS:NSArray?
/** 请求参数 */
var params:NSMutableDictionary?
/** 右边的用户数据 */
// var users:NSArray?
/** 左边的类别表格 */
@IBOutlet weak var categoryTableView: UITableView!
/** 右边的用户表格 */
@IBOutlet weak var userTableView: UITableView!
let XMGcategoryId:String = "category"
let XMGUserId:String = "user"
override func viewDidLoad() {
super.viewDidLoad()
// 控件的初始化
setupTableView()
// 添加刷新控件
setupRefresh()
// 加载左侧的类别数据
self.loadCategories()
}
//
//MARK: 加载左侧的类别数据
/// 加载左侧的类别数据
func loadCategories(){
// 显示指示器
SVProgressHUD.showInfoWithStatus("正在加载...", maskType: SVProgressHUDMaskType.Black)
// 1.定义URL路径
let path = "api/api_open.php"
// 2.封装参数
let params = NSMutableDictionary()
params["a"] = "category";
params["c"] = "subscribe";
NetworkTools.shareNetworkTools().sendGET(path, params: params, successCallback: { (responseObject) -> () in
// 隐藏指示器
SVProgressHUD.dismiss()
// 服务器返回的JSON数据
self.categorieS = XMGRecommendCategory.mj_objectArrayWithKeyValuesArray(responseObject["list"])
// 刷新表格
self.categoryTableView.reloadData()
// 默认选中首行
self.categoryTableView.selectRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), animated: true, scrollPosition: UITableViewScrollPosition.Top)
// 让用户表格进入下拉刷新状态
self.userTableView.mj_header.beginRefreshing()
printLog("responseObject1\(responseObject)")
}) { (error) -> () in
// 显示失败信息
SVProgressHUD.showErrorWithStatus("加载推荐信息失败!")
}
}
//MARK: 控件的初始化
/// 控件的初始化
func setupTableView(){
// 注册cell
categoryTableView.registerNib(UINib(nibName: "XMGRecommendCategoryCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: XMGcategoryId)
userTableView.registerNib(UINib(nibName: "XMGRecommendUserCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: XMGUserId)
// 设置automatically自动地 Adjusts调整 ScrollView Insets嵌入
self.automaticallyAdjustsScrollViewInsets = false
self.categoryTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
self.userTableView.contentInset = self.categoryTableView.contentInset;
self.userTableView.rowHeight = 70;
// 设置标题
self.title = "推荐关注";
// 设置背景色
self.view.backgroundColor = XMGGlobalBg;
}
//MARK: 添加刷新控件
/// 添加刷新控件
func setupRefresh(){
self.userTableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: Selector("loadNewUsers"))
self.userTableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: Selector("loadMoreUsers"))
}
func loadNewUsers(){
let category = self.checkCategories()!
// 1.定义URL路径
let path = "api/api_open.php"
// 2.封装参数
let params = NSMutableDictionary()
params["a"] = "list";
params["c"] = "subscribe";
params["category_id"] = (category.id);
//.存储请求参数.判断2次请求参数是否相同.不同就直接返回
self.params = params
NetworkTools.shareNetworkTools().sendGET(path, params: params, successCallback: { (responseObject) -> () in
printLog("params1\(params)")
// 服务器返回的JSON数据- 字典数组 -> 模型数组
let users:NSArray = XMGRecommendUser.mj_objectArrayWithKeyValuesArray(responseObject["list"])
// 不是最后一次请求
//if (self.params != params) {return}
// 刷新表格
// 设置当前页码为1
category.currentPage = 1
// 清除所有旧数据
category.users!.removeAllObjects()
// 添加到当前类别对应的用户数组中
category.users!.addObjectsFromArray(users as [AnyObject])
// 保存总数
category.total = responseObject["total"] as! Int
// 不是最后一次请求
if (self.params != params) {return}
self.userTableView.reloadData()
self.userTableView.mj_header.endRefreshing()
// 让底部控件结束刷新
self.checkFooterState()
}) { (error) -> () in
// 不是最后一次请求
if (self.params != params) {return}
// 显示失败信息
SVProgressHUD.showErrorWithStatus("加载推荐信息失败!")
// 让底部控件结束刷新
self.userTableView.mj_footer.endRefreshing()
}
}
func loadMoreUsers(){
let category = self.checkCategories()!
// 发送请求给服务器, 加载右侧的数据
//self.params = params;
// 1.定义URL路径
let path = "api/api_open.php"
// 2.封装参数
let params = NSMutableDictionary()
params["a"] = "list";
params["c"] = "subscribe";
params["category_id"] = category.id
params["page"] = (++category.currentPage);
//.存储请求参数.判断2次请求参数是否相同.不同就直接返回
self.params = params
NetworkTools.shareNetworkTools().sendGET(path, params: params, successCallback: { (responseObject) -> () in
printLog("params2\(params)")
// 服务器返回的JSON数据- 字典数组 -> 模型数组
let users:NSArray = XMGRecommendUser.mj_objectArrayWithKeyValuesArray(responseObject["list"])
// 刷新表格
// 添加到当前类别对应的用户数组中
category.users!.addObjectsFromArray(users as [AnyObject])
// 不是最后一次请求
if (self.params != params) {return}
// 刷新右边的表格
self.userTableView.reloadData()
// 让底部控件结束刷新
self.checkFooterState()
}) { (error) -> () in
// 不是最后一次请求
if (self.params != params) {return}
// 显示失败信息
SVProgressHUD.showErrorWithStatus("加载推荐信息失败!")
// 让底部控件结束刷新
self.userTableView.mj_footer.endRefreshing()
}
}
//MARK: - 时刻监测footer的状态(加载完毕--显示已经加载完毕.还有数据就显示-下拉刷新)
/// 时刻监测footer的状态(加载完毕--显示已经加载完毕.还有数据就显示-下拉刷新)
func checkFooterState() {
// 拿出的是那一段
let category = checkCategories()
// 让底部控件结束刷新
if (category?.users?.count) == (category?.total){// 全部数据已经加载完毕
self.userTableView.mj_footer.endRefreshingWithNoMoreData()
}else{
// 还没有加载完毕
self.userTableView.mj_footer.endRefreshing()
}
// 每次刷新右边数据时, 都控制footer显示或者隐藏
self.userTableView.tableFooterView?.hidden = (category?.users!.count == 0)
}
//MARK: - 监测右边的数据--获取左边的是哪一行所持有的数据
/// 监测右边的数据--获取左边的是哪一行所持有的数据
func checkCategories()->XMGRecommendCategory?{
return self.categorieS?[(self.categoryTableView.indexPathsForSelectedRows?.last?.row)!] as? XMGRecommendCategory
}
/*
//MARK: - 监测是哪个cell
/// 监测是哪个cell
func checkCell(tableView: UITableView,Identifier:String)->UITableViewCell?{
if Identifier == XMGcategoryId{
return tableView.dequeueReusableCellWithIdentifier(XMGcategoryId) as! XMGRecommendCategoryCell
}else{
return tableView.dequeueReusableCellWithIdentifier(XMGUserId) as! XMGRecommendUserCell
}
}
*/
//MARK: - 控制器的销毁
/// 控制器的销毁
deinit{
print("\(super.classForCoder)--❤️已销毁")
// 停止所有操作
NetworkTools.shareNetworkTools().operationQueue.cancelAllOperations()
}
}
extension XMGRecommendViewController: UITableViewDataSource,UITableViewDelegate{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (tableView == self.categoryTableView) { // 左边的类别表格
return self.categorieS?.count ?? 0
} else { // 右边的用户表格
/*
let category = self.categorieS?[(self.categoryTableView.indexPathsForSelectedRows?.last?.row)!] as? XMGRecommendCategory
if (category?.users?.count) == (category?.total){
self.userTableView.mj_footer.endRefreshingWithNoMoreData()
}else{
self.userTableView.mj_footer.endRefreshing()
}
// 每次刷新右边数据时, 都控制footer显示或者隐藏
self.userTableView.tableFooterView?.hidden = (category?.users!.count == 0)
*/
checkFooterState()
return self.checkCategories()?.users?.count ?? 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (tableView == self.categoryTableView) { // 左边的类别表格
let cell = tableView.dequeueReusableCellWithIdentifier(XMGcategoryId) as! XMGRecommendCategoryCell
cell.category = self.categorieS![indexPath.row] as? XMGRecommendCategory
return cell
} else { // 右边的用户表格--来自左边的模型
let cell = tableView.dequeueReusableCellWithIdentifier(XMGUserId) as! XMGRecommendUserCell
let c = self.categorieS?[(self.categoryTableView.indexPathsForSelectedRows?.last?.row)!] as? XMGRecommendCategory
cell.user = c!.users![indexPath.row] as? XMGRecommendUser;
return cell;
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// 每次点击cell都要结束刷新
self.userTableView.mj_footer.endRefreshing()
self.userTableView.mj_header.endRefreshing()
let c:XMGRecommendCategory = self.categorieS![indexPath.row] as! XMGRecommendCategory
printLog("\(c.users?.count)")
if ((c.users?.count) != 0) {
// 显示曾经的数据
self.userTableView.reloadData()
} else {
self.userTableView.reloadData()
self.userTableView.mj_header.beginRefreshing()
}
}
}
| apache-2.0 | 56c87e914be56582195d2b361de29267 | 32.210031 | 157 | 0.579762 | 4.681396 | false | false | false | false |
Witcast/witcast-ios | Pods/Material/Sources/Frameworks/Motion/Sources/Extensions/Motion+CAMediaTimingFunction.swift | 1 | 2180 | /*
* The MIT License (MIT)
*
* Copyright (C) 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Original Inspiration & Author
* Copyright (c) 2016 Luke Zhao <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
public extension CAMediaTimingFunction {
// Default
static let linear = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
static let easeIn = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
static let easeOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
static let easeInOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Material
static let standard = CAMediaTimingFunction(controlPoints: 0.4, 0.0, 0.2, 1.0)
static let deceleration = CAMediaTimingFunction(controlPoints: 0.0, 0.0, 0.2, 1)
static let acceleration = CAMediaTimingFunction(controlPoints: 0.4, 0.0, 1, 1)
static let sharp = CAMediaTimingFunction(controlPoints: 0.4, 0.0, 0.6, 1)
// Easing.net
static let easeOutBack = CAMediaTimingFunction(controlPoints: 0.175, 0.885, 0.32, 1.75)
}
| apache-2.0 | 39e3463801092de46513005862967f37 | 46.391304 | 91 | 0.75 | 4.504132 | false | false | false | false |
yikaraman/iOS8-day-by-day | 13-coreimage-detectors/LiveDetection/LiveDetection/ViewController.swift | 3 | 4554 | //
// Copyright 2014 Scott Logic
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var qrDecodeLabel: UILabel!
@IBOutlet var detectorModeSelector: UISegmentedControl!
var videoFilter: CoreImageVideoFilter?
var detector: CIDetector?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Create the video filter
videoFilter = CoreImageVideoFilter(superview: view, applyFilterCallback: nil)
// Simulate a tap on the mode selector to start the process
detectorModeSelector.selectedSegmentIndex = 0
handleDetectorSelectionChange(detectorModeSelector)
}
@IBAction func handleDetectorSelectionChange(sender: UISegmentedControl) {
if let videoFilter = videoFilter {
videoFilter.stopFiltering()
self.qrDecodeLabel.hidden = true
switch sender.selectedSegmentIndex {
case 0:
detector = prepareRectangleDetector()
videoFilter.applyFilter = {
image in
return self.performRectangleDetection(image)
}
case 1:
self.qrDecodeLabel.hidden = false
detector = prepareQRCodeDetector()
videoFilter.applyFilter = {
image in
let found = self.performQRCodeDetection(image)
dispatch_async(dispatch_get_main_queue()) {
if found.decode != "" {
self.qrDecodeLabel.text = found.decode
}
}
return found.outImage
}
default:
videoFilter.applyFilter = nil
}
videoFilter.startFiltering()
}
}
//MARK: Utility methods
func performRectangleDetection(image: CIImage) -> CIImage? {
var resultImage: CIImage?
if let detector = detector {
// Get the detections
let features = detector.featuresInImage(image)
for feature in features as [CIRectangleFeature] {
resultImage = drawHighlightOverlayForPoints(image, topLeft: feature.topLeft, topRight: feature.topRight,
bottomLeft: feature.bottomLeft, bottomRight: feature.bottomRight)
}
}
return resultImage
}
func performQRCodeDetection(image: CIImage) -> (outImage: CIImage?, decode: String) {
var resultImage: CIImage?
var decode = ""
if let detector = detector {
let features = detector.featuresInImage(image)
for feature in features as [CIBarcodeFeature] {
resultImage = drawHighlightOverlayForPoints(image, topLeft: feature.topLeft, topRight: feature.topRight,
bottomLeft: feature.bottomLeft, bottomRight: feature.bottomRight)
decode = feature.codeString
}
}
return (resultImage, decode)
}
func prepareRectangleDetector() -> CIDetector {
let options = [CIDetectorAccuracy: CIDetectorAccuracyHigh, CIDetectorAspectRatio: 1.0]
return CIDetector(ofType: CIDetectorTypeRectangle, context: nil, options: options)
}
func prepareQRCodeDetector() -> CIDetector {
let options = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
return CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: options)
}
func drawHighlightOverlayForPoints(image: CIImage, topLeft: CGPoint, topRight: CGPoint,
bottomLeft: CGPoint, bottomRight: CGPoint) -> CIImage {
var overlay = CIImage(color: CIColor(red: 1.0, green: 0, blue: 0, alpha: 0.5))
overlay = overlay.imageByCroppingToRect(image.extent())
overlay = overlay.imageByApplyingFilter("CIPerspectiveTransformWithExtent",
withInputParameters: [
"inputExtent": CIVector(CGRect: image.extent()),
"inputTopLeft": CIVector(CGPoint: topLeft),
"inputTopRight": CIVector(CGPoint: topRight),
"inputBottomLeft": CIVector(CGPoint: bottomLeft),
"inputBottomRight": CIVector(CGPoint: bottomRight)
])
return overlay.imageByCompositingOverImage(image)
}
}
| apache-2.0 | 79a4d5c1ee01681c9b51f570517635de | 35.432 | 117 | 0.684014 | 4.84984 | false | false | false | false |
lieonCX/Live | Live/View/User/Setting/ModifyPhoneViewController.swift | 1 | 9882 | //
// ModifyPhoneViewController.swift
// Live
//
// Created by fanfans on 2017/7/13.
// Copyright © 2017年 ChengDuHuanLeHui. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import PromiseKit
class ModifyPhoneViewController: BaseViewController {
fileprivate lazy var phoneNumTF: UITextField = {
let textField = UITextField()
textField.placeholder = "请输入新手机号码"
textField.font = UIFont.sizeToFit(with: 13)
textField.textColor = UIColor(hex: 0x333333)
textField.keyboardType = .numberPad
textField.tintColor = UIColor(hex: CustomKey.Color.mainColor)
return textField
}()
fileprivate lazy var pwdTF: UITextField = {
let pwdTF = UITextField()
pwdTF.placeholder = "请输入收到的验证码"
pwdTF.textColor = UIColor(hex: 0x333333)
pwdTF.font = UIFont.sizeToFit(with: 13)
pwdTF.tintColor = UIColor(hex: CustomKey.Color.mainColor)
pwdTF.returnKeyType = .done
return pwdTF
}()
fileprivate lazy var userLog: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "user_phone_num"))
imageView.contentMode = .center
return imageView
}()
fileprivate lazy var pwdLog: UIImageView = {
let pwdLog = UIImageView(image: UIImage(named: "user_center_captch"))
pwdLog.contentMode = .center
return pwdLog
}()
fileprivate lazy var line0: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hex: 0xe6e6e6)
return view
}()
fileprivate lazy var line1: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hex: 0xe6e6e6)
return view
}()
fileprivate lazy var line2: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hex: 0xe6e6e6)
return view
}()
fileprivate lazy var getVerifiedCodeBtn: UIButton = {
let getVerifiedCodeBtn = UIButton()
getVerifiedCodeBtn.sizeToFit()
getVerifiedCodeBtn.titleLabel?.font = UIFont.sizeToFit(with: 12)
getVerifiedCodeBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
getVerifiedCodeBtn.setTitle("获取验证码", for: .normal)
getVerifiedCodeBtn.setTitleColor(UIColor.gray, for: .disabled)
getVerifiedCodeBtn.setTitleColor(UIColor(hex: CustomKey.Color.mainColor), for: .normal)
return getVerifiedCodeBtn
}()
fileprivate lazy var loginBtn: UIButton = {
let loginBtn = UIButton()
loginBtn.setBackgroundImage(UIImage(named: "loginBtn_normal"), for: .normal)
loginBtn.setBackgroundImage(UIImage(named: "loginBtn_highlighted"), for: .highlighted)
loginBtn.setBackgroundImage(UIImage(named: "loginBtn_highlighted"), for: .disabled)
loginBtn.titleLabel?.font = UIFont.sizeToFit(with: 16)
loginBtn.setTitle("确认更换", for: .normal)
loginBtn.setTitleColor(UIColor.white, for: .normal)
loginBtn.layer.cornerRadius = 22.5
loginBtn.layer.masksToBounds = true
loginBtn.isEnabled = false
return loginBtn
}()
fileprivate lazy var descLabel: UILabel = {
let descLabel = UILabel()
descLabel.font = UIFont.systemFont(ofSize: CGFloat(11))
descLabel.textColor = UIColor(hex: CustomKey.Color.mainColor)
descLabel.text = "更换手机号,原手机号不能登录"
return descLabel
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupAction()
}
}
extension ModifyPhoneViewController {
fileprivate func setupUI() {
title = "更换手机号"
view.backgroundColor = .white
view.addSubview(userLog)
view.addSubview(phoneNumTF)
view.addSubview(line0)
view.addSubview(pwdLog)
view.addSubview(pwdTF)
view.addSubview(line1)
view.addSubview(getVerifiedCodeBtn)
view.addSubview(line2)
view.addSubview(loginBtn)
view.addSubview(descLabel)
userLog.snp.makeConstraints { (maker) in
maker.top.equalTo(80)
maker.left.equalTo(30)
maker.width.equalTo(20)
}
phoneNumTF.snp.makeConstraints { (maker) in
maker.left.equalTo(userLog.snp.right).offset(20)
maker.centerY.equalTo(userLog.snp.centerY)
maker.right.equalTo(-30)
}
line0.snp.makeConstraints { (maker) in
maker.left.equalTo(20)
maker.top.equalTo(userLog.snp.bottom).offset(12)
maker.right.equalTo(-20)
maker.height.equalTo(0.5)
}
pwdLog.snp.makeConstraints { (maker) in
maker.left.equalTo(userLog.snp.left).offset(2)
maker.top.equalTo(line0.snp.bottom).offset(12)
maker.width.equalTo(20)
}
getVerifiedCodeBtn.snp.makeConstraints { (maker) in
maker.right.equalTo(-35)
maker.centerY.equalTo(pwdLog.snp.centerY)
}
line1.snp.makeConstraints { (maker) in
maker.right.equalTo(getVerifiedCodeBtn.snp.left).offset(-12)
maker.width.equalTo(1)
maker.height.equalTo(20)
maker.centerY.equalTo(pwdLog.snp.centerY)
}
pwdTF.snp.makeConstraints { (maker) in
maker.left.equalTo(phoneNumTF.snp.left)
maker.right.equalTo(phoneNumTF.snp.right)
maker.top.equalTo(line0.snp.bottom).offset(12)
}
line2.snp.makeConstraints { (maker) in
maker.top.equalTo(pwdLog.snp.bottom).offset(12)
maker.left.equalTo(line0.snp.left)
maker.right.equalTo(line0.snp.right)
maker.height.equalTo(0.5)
}
loginBtn.snp.makeConstraints { (maker) in
maker.left.equalTo(10)
maker.right.equalTo(-10)
maker.height.equalTo(45)
maker.top.equalTo(line2.snp.bottom).offset(50)
}
descLabel.snp.makeConstraints { (maker) in
maker.left.equalTo(10)
maker.top.equalTo(loginBtn.snp.bottom).offset(26)
}
}
fileprivate func setupAction() {
let usernameValid = phoneNumTF.rx.text.orEmpty
.map { $0.characters.count >= 11}
.shareReplay(1)
let passwordValid = pwdTF.rx.text.orEmpty
.map { $0.characters.count >= 4 }
.shareReplay(1)
let everythingValid = Observable.combineLatest(usernameValid, passwordValid) { $0 && $1 }
.shareReplay(1)
usernameValid
.bind(to: getVerifiedCodeBtn.rx.isEnabled)
.disposed(by: disposeBag)
everythingValid
.bind(to: loginBtn.rx.isEnabled)
.disposed(by: disposeBag)
pwdTF.rx.text.orEmpty
.map { (text) -> String in
return text.characters.count <= 4 ? text: text.substring(to: "0123".endIndex)
}
.shareReplay(1)
.bind(to: pwdTF.rx.text)
.disposed(by: disposeBag)
phoneNumTF.rx.text.orEmpty
.map { (text) -> String in
return text.characters.count <= 11 ? text: text.substring(to: "15608006621".endIndex)
}
.shareReplay(1)
.bind(to: phoneNumTF.rx.text)
.disposed(by: disposeBag)
loginBtn.rx.tap
.subscribe (onNext: { [weak self] in
let modifyVM = UserSessionViewModel()
HUD.show(true, show: "", enableUserActions: false, with: self)
let param = UserRequestParam()
param.phone = self?.phoneNumTF.text ?? ""
param.code = self?.pwdTF.text ?? ""
modifyVM.requestExchangePhoneNum(with: param)
.then(execute: { (_) -> Void in
guard let navigationVC = self?.navigationController else {
return
}
for vcc in navigationVC.viewControllers {
if vcc is SettingViewController {
navigationVC.popToViewController(vcc, animated: true)
}
}
})
.always {
HUD.show(false, show: "", enableUserActions: false, with: self)
}
.catch(execute: { error in
if let error = error as? AppError {
self?.view.makeToast(error.message)
}
})
})
.disposed(by: disposeBag)
getVerifiedCodeBtn.rx.tap
.subscribe(onNext: { [weak self] in
let verfiedVM = UserSessionViewModel()
HUD.show(true, show: "", enableUserActions: false, with: self)
verfiedVM.sendCaptcha(phoneNum: self?.phoneNumTF.text ?? "", type: .changePhoneNum)
.then(execute: { (_) -> Void in
self?.getVerifiedCodeBtn.start(withTime: 120, title: "获取验证码", countDownTitle: "S后重发", mainColor: self?.view.backgroundColor ?? .red, count: self?.view.backgroundColor ?? .red)
})
.always {
HUD.show(false, show: "", enableUserActions: false, with: self)
}
.catch(execute: { error in
if let error = error as? AppError {
self?.view.makeToast(error.message)
}
})
})
.disposed(by: disposeBag)
}
}
| mit | 603bd86b52bcdb8fca34bac7a8f2fb1f | 37.936255 | 199 | 0.567584 | 4.456452 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Code snippets.swift | 1 | 314650 | //
// Code snippets.swift
// XGCommandLineTools
//
// Created by StarsMmd on 20/03/2017.
// Copyright © 2017 StarsMmd. All rights reserved.
//
import Foundation
// infinite TMs
//infiniteUseTMs()
//let pelipper = pokemon("pelipper").stats
//pelipper.ability1 = ability("drizzle")
//pelipper.save()
//
//let torkoal = pokemon("torkoal").stats
//torkoal.ability1 = ability("drought")
//torkoal.save()
//let rage_powder = move("rage powder").data
//rage_powder.priority = 2
//rage_powder.save()
//
//let xg001 = pokemon("xg001").stats
//xg001.modelIndex = 0x1A1
//xg001.save()
//
//let typhlosion = pokemon("typhlosion").stats
//typhlosion.levelUpMoves[1].move = move("heat wave")
//typhlosion.save()
//let cyndaquil = pokemon("cyndaquil").stats
//cyndaquil.levelUpMoves[6].move = move("heat wave")
//cyndaquil.save()
//
//let blaziken = pokemon("blaziken").stats
//blaziken.learnableTMs[24] = true
//blaziken.save()
//
//
//for deck in TrainerDecksArray {
// if deck != .DeckVirtual {
// for poke in deck.allPokemon {
// if poke.species.index == pokemon("wobbuffet").index {
// poke.moves = [move("mirror coat"), move("counter"), move("safeguard"), move("destiny bond")]
// poke.save()
// }
// if poke.isShadowPokemon {
// if poke.species.stats.evolutions[0].evolutionMethod == .maxHappiness {
// poke.happiness = 120
// poke.save()
// }
// }
// }
// }
//}
//let scizor = pokemon("scizor").stats
//scizor.learnableTMs[30] = false
//scizor.save()
//
//XGTMs.tm(41).replaceWithMove(move("thunder"))
//
//let thunderLearners = [19,20,25,26,29,30,31,32,33,34,35,36,39,40,52,53,56,57,81,82,83,88,89,92,93,94,100,101,109,110,111,112,113,115,120,121,122,125,128,130,131,135,137,143,145,147,148,149,150,151,162,170,171,172,179,180,181,200,203,206,209,210,233,234,239,241,242,243,248,249,250,260,261,262,265,267,288,289,315,316,317,320,337,338,353,354,364,365,366,376,377,378,380,384,385,386,387,401,402,403,404,406,407,408,409,410]
//for i in 1..<kNumberOfPokemon {
// let poke = XGPokemon.pokemon(i).stats
// if thunderLearners.contains(i) {
// poke.learnableTMs[40] = true
// } else {
// poke.learnableTMs[40] = false
// }
// poke.save()
//}
//
//let banette = pokemon("banette").stats
//for i in [8,27,36,42] {
// banette.learnableTMs[i] = false
//}
//for i in [3,4,5,6] {
// banette.tutorMoves[i] = false
//}
//banette.save()
//
//
//let normaliseMoves = [20,32,40,51,54,80]
//
//var normalised = [XGTrainerPokemon]()
//for deck in TrainerDecksArray {
// if deck != .DeckVirtual {
// for poke in deck.allPokemon {
// for m in normaliseMoves {
// if poke.moves.contains(where: { (m1) -> Bool in
// return m1.index == m
// }) {
// normalised.append(poke)
// break
// }
// }
// }
// }
//}
//
//normalised[0].moves[1] = XGMoves.move(0)
//normalised[1].moves[0] = move("tackle")
//normalised[2].moves[0] = move("absorb")
//normalised[3].moves[0] = move("rock throw")
//normalised[4].moves[2] = move("taunt")
//normalised[5].moves[1] = move("thunderwave")
//normalised[6].moves[3] = move("rock throw")
//normalised[7].moves[3] = move("poison jab")
//normalised[8].moves[3] = move("rock throw")
//normalised[9].moves[2] = move("tackle")
//normalised[10].moves[1] = move("megahorn")
//normalised[11].moves[2] = move("giga drain")
//normalised[12].moves[2] = move("spikes")
//normalised[13].moves[2] = move("giga drain")
//normalised[14].moves[2] = move("iron head")
//normalised[14].moves[3] = move("bulldoze")
//normalised[15].moves[2] = move("ice shard")
//normalised[16].moves[2] = move("poison fang")
//normalised[17].moves[3] = move("ice beam")
//normalised[18].moves[3] = move("ice beam")
//
//
//for pokemon in normalised {
// pokemon.save()
//}
//loadAllStrings()
//let bigd = XGDecks.DeckColosseum
//var strs = [XGString]()
//for i in 41 ... 68 {
// let trainer = XGTrainer(index: i, deck: bigd)
// let name = trainer.name.string
// let trclass = trainer.trainerClass.name.string
// let pre = getStringSafelyWithID(id: trainer.preBattleTextID)
// let vic = getStringSafelyWithID(id: trainer.victoryTextID)
// let def = getStringSafelyWithID(id: trainer.defeatTextID)
// strs += [pre, vic, def]
//}
//
//let replacementStrs = [
// "[Speaker]: Cipher Green here!", "[Speaker]: You got weeded out![6d]", "[Speaker]: I got rooted.[6d]", // sage
// "[Speaker]: I'll show you why they call[New Line]me the gatekeeper of Pyrite.", "[Speaker]: Don't come back, punk![6d]", "[Speaker]: Locked out...[6d]", // kane
// "[Speaker]: Sylvia'll chew me out if[New Line]I lose again.", "[Speaker]: I did it![6d]", "[Speaker]: I'm in so much trouble.[6d]", // mark
// "[Speaker]: Did you Mark lose again?[New Line]I'll have to #PunishHim later but[New Line]now it's #MyTurn!", "[Speaker]: #GetRekt![6d]", "[Speaker]: #NoFair![6d]", // sylvia
// "[Speaker]: Do you know what they call[New Line]me?[New Line]They call me the storm bringer!", "[Speaker]: I stormed to victory![6d]", "[Speaker]: Darn![New Line]My feelings are stormy after this loss![6d]", // luthor
// "[Speaker]: Let me show you what a[New Line]Gym Leader can do!", "[Speaker]: You need more training.[6d]", "[Speaker]: I need more training.[6d]", // derek
// "[Speaker]: I'll crush you this time!", "[Speaker]: My muscles show my strength![6d]", "[Speaker]: I-I Lost?.[6d]", // ray
// "[Speaker]: I've got some secret techs[New Line]to catch you off guard!", "[Speaker]: You're too predictable.[6d]", "[Speaker]: You saw through my tactics.[6d]", // blaine
// "[Speaker]: Check out my seismic moves.", "[Speaker]: Hit the road.[6d]", "[Speaker]: You really ground me up.[6d]", // sandy
// "[Speaker]: I'll stall you out of[New Line]all your pp.", "[Speaker]: Guess you got impatient![6d]", "[Speaker]: You broke our defenses!?.[6d]", // dexter
// "[Speaker]: YOU AGAIN?!", "[Speaker]: I'm the greatest![6d]", "[Speaker]: You're crampin' my style.[6d]", // zeke
// "[Speaker]: This time, I will crush you and pulverize you!", "[Speaker]: That's for wrecking my[New Line]factory![New Line]Don't you forget it![6d]", "[Speaker]: Why?[New Line]Why can't I ever beat you?![6d]", // bruce
// "[Speaker]: Roar, my dragons!", "[Speaker]: Did my dragons scare you?[6d]", "[Speaker]: You weren't scared at all.[6d]", // drake
// "[Speaker]: Run away while you can.", "[Speaker]: I told you to run.[6d]", "[Speaker]: I should have run away![6d]", // ryder
// "[Speaker]: I held back last time.[New Line]You won't win this one.", "[Speaker]: This is how I play for real.[6d]", "[Speaker]: I can't catch a break![6d]", // nick
// "[Speaker]: I won't let you keep ruining[New Line]Sangem Gang's reputation like this.", "[Speaker]: Don't cross Snagem Gang again.[6d]", "[Speaker]: I'll admit it. You're tough[New Line]kid. Snagem Gang could really[New Line]use someone competent like you.[6d]", // duncan
// "[Speaker]: I'll sink you.", "[Speaker]: You're all washed up.[6d]", "[Speaker]: You rinsed me.[6d]", // azure
// "[Speaker]: We meet again, buddy.[New Line]Yeeehah. We're burning up!", "[Speaker]: It's my win this time![6d]", "[Speaker]: whew, you smoked my team.[6d]", // will
// "[Speaker]: Hohoho. It's you again.[New Line]Ready for my sweet, sweet moves[New Line]darling? Try and keep up!", "[Speaker]: I'm in the groove.[6d]", "[Speaker]: The tempo was too fast![6d]", // mirror b.
// "[Speaker]: I'll flood the whole arena[New Line]to defeat you this time.", "[Speaker]: I'm unstoppable in the rain.[6d]", "[Speaker]: You made my deluge look[New Line]like a puddle. You're strong.[New Line]I concede to you.[6d]", // Troy
// "[Speaker]: Time to get hot and sweaty.", "[Speaker]: Can't stand the heat?[6d]", "[Speaker]: I got burned.[6d]", // blaze
// "[Speaker]: You won't get past me again.", "[Speaker]: I finally stopped you.[6d]", "[Speaker]: It's like I'm not even here![6d]", // nate
// "[Speaker]: I may be old but I have[New Line]a lot of experience.[New Line]Don't hold back!", "[Speaker]: I told you not to go[New Line]easy on me.[6d]", "[Speaker]: You went all out.[New Line]We didn't stand a chance![6d]", // ash
// "[Speaker]: I've been to Mt.Battle to hone[New Line]my skills since our last encounter.[New Line]I won't lose!", "[Speaker]: Your team lacks discipline.[6d]", "[Speaker]: I still need more training.[6d]", // des
// "[Speaker]: Chobin fine tuned the machines.[New Line]They're oiled up and charged to 100%.", "[Speaker]: I collected some useful data.[6d]", "[Speaker]: There was still some input lag.[New Line]I must return to the lab![6d]", // zack
// "[Speaker]: I have to hold back on Mt.Battle.[New Line]I come here to go all out!", "[Speaker]: Come to Mt.Battle some time.[New Line]You need more training.[6d]", "[Speaker]: Maybe I should train on[New Line]Mt.Battle myself![6d]", // mick
// "[Speaker]: You took everything from me![New Line]Years of hard work down the drain![New Line]I'll make you pay for your[New Line]insolence.", "[Speaker]: Crushing your team is so[New Line]satisfying.[6d]", "[Speaker]: aarrghh![6d]", // tyrion
// "[Speaker]: Welcome to Orre Colosseum's[New Line]final challenge.[New Line]Let me show you what a hacker[New Line]can do!", "[Speaker]: I made the game.[New Line]What did you really expect?[6d]", "[Speaker]: Thanks for playing XG![New Line]Don't forget to check out Mt.Battle.[New Line]There's a surprise at the top. ;)[6d]", // stars
//]
//for i in 0..<replacementStrs.count {
// strs[i].duplicateWithString(replacementStrs[i]).replace()
//}
// convert ability list to add more abilities
//increaseNumberOfAbilities()
//var unused = [Int]()
//for string in XGFiles.common_rel.stringTable.allStrings() {
// if string.string == "_" {
// unused.append(string.id)
// }
//}
//let dol = XGFiles.dol.data!
//var nextUnused = 0
////
//let abNames = ["Hard Shell","Magic Bounce", "Pure Heart", "Adaptability","Multilayered","Solar Power","Regenerator","Snow Warning","Refrigerate","Slush Rush","Tough Claws","Prankster","Sand Force","Sand Rush","Amplifier", "No Guard"]
//let abDes = ["Blocks projectile moves.", "Reflects status moves.","Weakens evil moves.","Powers same type moves.", "Max HP halves Damage.","Sunlight powers moves.", "Heals when switching out.","Summons hail in battle.","Makes normal moves ice.","Hail doubles speed.","Powers up contact moves.","Status moves go first.","Sandstorm powers moves.","Raises speed in sandstorm.","Powers sound moves.", "Moves always hit."]
//
//
//var nextAb = 0
//var nextDe = 0
//for i in 78 ..< (0x3A8 / 8) {
//
// if !(nextUnused < unused.count) {
// break
// }
//
// if !(nextAb < abNames.count) {
// break
// }
//
// let start = 0x3FCC50 + (i * 8)
//
// if dol.getWordAtOffset(start) == 0 {
// dol.replaceWordAtOffset(start, withBytes: UInt32(unused[nextUnused]))
// XGFiles.common_rel.stringTable.stringWithID(unused[nextUnused])!.duplicateWithString(abNames[nextAb]).replace()
// nextAb += 1
// nextUnused += 1
// }
//
// if dol.getWordAtOffset(start + 4) == 0 {
// dol.replaceWordAtOffset(start + 4, withBytes: UInt32(unused[nextUnused]))
// XGFiles.common_rel.stringTable.stringWithID(unused[nextUnused])!.duplicateWithString(abDes[nextDe]).replace()
// nextDe += 1
// nextUnused += 1
// }
//
//
//}
//
//dol.save()
//let plus = ability("plus")
//plus.name.duplicateWithString("Battery").replace()
//plus.adescription.duplicateWithString("Powers ally special moves.").replace()
//let minus = XGAbilities.ability(58)
//minus.name.duplicateWithString("Shadow Aura").replace()
//minus.adescription.duplicateWithString("Powers ally shadow moves.").replace()
//let plus = ability("plus")
//plus.name.duplicateWithString("Battery").replace()
//plus.adescription.duplicateWithString("Powers ally special moves.").replace()
//let minus = XGAbilities.ability(58)
//minus.name.duplicateWithString("Shadow Aura").replace()
//minus.adescription.duplicateWithString("Powers ally shadow moves.").replace()
//
//let anonyItems = [42,43,46,47,48,49,50,51,81,80,83,84,85,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,254,255,256,257,258]
//for i in anonyItems {
// let item = XGItems.item(i)
// item.descriptionString.duplicateWithString("_").replace()
// item.name.duplicateWithString("_").replace()
// let data = item.data
// data.nameID = 0
// data.descriptionID = 0
// data.save()
//}
//
//
//var nextUnused = 0
//var unused = [item("stick"), item("metal powder"), item("lucky punch"), item("up-grade"), item("dragon scale"), item("deepseascale"), item("deepseatooth"), item("repel"), item("blue flute"), item("yellow flute"), item("red flute")]
//
//let itNames = ["Choice Scarf","Choice Specs","Eviolite","Wise Glasses","Muscle Band","Pixie Plate","Aura Amplifier","Aura Booster","Aura Limiter","Aura Filter","Life Orb"]
//
//let itDes = ["Raises speed[New Line]but permits only[New Line]one move.","Raises sp.atk[New Line]but permits only[New Line]one move.","Raises defenses of[New Line]Pokemon that can[New Line]Evolve.","Slightly boosts special[New Line]moves' power.","Slightly boosts physical[New Line]moves' power.","A hold item that[New Line]raises the power of[New Line]Fairy-type moves.","Boosts the power[New Line]of a pokemon's[New Line]shadow moves.","Boosts the power[New Line]of a shadow pokemon's[New Line]moves.","The wearer takes[New Line]half the damage from[New Line]shadow pokemon.","The wearer takes[New Line]half the damage from[New Line]shadow moves.","Powers up moves but the[New Line]holder loses health."]
//
//item("choice band").descriptionString.duplicateWithString("Raises attack[New Line]but permits only[New Line]one move.").replace()
//item("focus band").descriptionString.duplicateWithString("Prevents fainting at[New Line]max HP.").replace()
//item("focus band").name.duplicateWithString("Focus Sash").replace()
//
//
//var itNext = 0
//for i in 0 ..< itNames.count {
//
// let old = unused[i].data
// let name = old.name
// let desc = old.descriptionString
//
// let item = XGItems.item(i + 52).data
// item.nameID = name.id
// name.duplicateWithString(itNames[itNext]).replace()
//
// item.descriptionID = desc.id
// desc.duplicateWithString(itDes[itNext]).replace()
// nextUnused += 1
// itNext += 1
// item.save()
//
// old.nameID = 0
// old.descriptionID = 0
// old.save()
//
//
//}
//for i in 1 ..< kNumberOfMoves {
//
// let data = XGMove(index: i)
//
// data.mirrorMoveFlag = false
// data.HMFlag = data.isShadowMove ? true : false
// data.snatchFlag = false
//
// data.save()
//
//}
//
//
//let auramoves = [move("aura sphere"), move("water pulse"), move("dragon pulse"), move("dark pulse"),move("shadow pulse")]
//for move in auramoves {
// let data = move.data
// data.mirrorMoveFlag = true
// data.save()
//}
//
//// shadow moves use HM flag
//let shadowMovesCheckStartAddress = 0x8013d03c - kDolToRAMOffsetDifference
//let shadowCheckInstructions : [UInt32] = [0x9421fff0,0x7c0802a6,0x90010014,0x480014cd,0x80010014,0x7c0803a6,0x38210010,0x4e800020]
//let adol = XGFiles.dol.data!
//for i in 0 ..< shadowCheckInstructions.count {
//
// adol.replaceWordAtOffset(shadowMovesCheckStartAddress + (i * 4), withBytes: shadowCheckInstructions[i])
//
//}
//
////remove move flag depedencies
//let li_r3_0 : UInt32 = 0x38600000
//let dependentOffsets = [0x8021aafc,0x801bd9e0,0x80210628,0x802187b0]
//for offset in dependentOffsets {
// adol.replaceWordAtOffset(offset - kDolToRAMOffsetDifference, withBytes: li_r3_0)
//}
//
//adol.save()
////snow warning
//let snowWarningIndex = kNumberOfAbilities + 8
//let bdol = XGFiles.dol.data!
//let nops = [0x80225d24 - kDolToRAMOffsetDifference, 0x80225d54 - kDolToRAMOffsetDifference]
//for offset in nops {
// bdol.replaceWordAtOffset(offset, withBytes: kNopInstruction)
//}
//bdol.replaceWordAtOffset(0x80225d4c - kDolToRAMOffsetDifference, withBytes: UInt32(0x2c000000 + snowWarningIndex))
//
//let rainToSnow : UInt32 = 0x80225e90 - 0x80225d7c
//let weatherStarter : [UInt32] = [0x38600000, 0x38800053, 0x4BFCD1F9 - rainToSnow, 0x5460063E, 0x28000002, 0x40820188 - rainToSnow, 0x38600000, 0x38800053, 0x38A00000, 0x4BFCD189 - rainToSnow, 0x7FE4FB78, 0x38600000, 0x4BFD09D5 - rainToSnow, 0x3C608041, 0x3863783C, 0x4BFFD8F1 - rainToSnow, kNopInstruction]
//
//let snowstart = 0x80225e90 - kDolToRAMOffsetDifference
//for i in 0 ..< weatherStarter.count {
// bdol.replaceWordAtOffset(snowstart + (i * 4), withBytes: weatherStarter[i])
//}
//
//loadAllStrings()
//getStringWithID(id: 0x4eea)!.duplicateWithString("[1e]'s [1c][New Line]activated!").replace()
//// snow warning uses hail animation
//let snowRoutineStart = 0xB9AC60
//let snowWarningRoutine = [0x46, 0x19, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x29, 0x80, 0x41, 0x78, 0x43]
//let rel = XGFiles.common_rel.data!
//rel.replaceBytesFromOffset(snowRoutineStart - kRELtoRAMOffsetDifference, withByteStream: snowWarningRoutine)
//rel.save()
//
//let snowRoutineBranch = 0x225ec4
//XGAssembly.replaceASM(startOffset: snowRoutineBranch - kDolToRAMOffsetDifference, newASM: [
// .lis(.r3, 0x80ba),
// .subi(.r3, .r3, 0x10000 - 0xac60),
//])
//let dugtrio = pokemon("dugtrio").stats
//dugtrio.attack = 100
//dugtrio.save()
//
//let dodrio = pokemon("dodrio").stats
//dodrio.speed = 110
//dodrio.save()
//
//let electrode = pokemon("electrode").stats
//electrode.speed = 150
//electrode.save()
//
//let pelipper = pokemon("pelipper").stats
//pelipper.specialAttack = 95
//pelipper.save()
//
//let mantine = pokemon("mantine").stats
//mantine.hp = 85
//mantine.save()
//
//let lunatone = pokemon("lunatone").stats
//lunatone.hp = 100
//lunatone.attack = 50
//lunatone.defense = 65
//lunatone.specialDefense = 85
//lunatone.specialAttack = 105
//lunatone.speed = 50
//lunatone.save()
//
//let solrock = pokemon("solrock").stats
//solrock.hp = 100
//solrock.attack = 50
//solrock.defense = 85
//solrock.specialDefense = 65
//solrock.specialAttack = 105
//solrock.speed = 50
//solrock.save()
//
//let masquerain = pokemon("masquerain").stats
//masquerain.specialAttack = 100
//masquerain.speed = 80
//masquerain.save()
//let cdol = XGFiles.dol.data!
//
////crit multipliers
//let critOffsets = [0x8020dd7c,0x8020dd8c,0x8020dd9c,0x801f0968]
//let critValues : [UInt32] = [0x38800003,0x38800002,0x38800002,0x38800002]
//
//for i in 0 ..< critOffsets.count {
// cdol.replaceWordAtOffset(critOffsets[i] - kDolToRAMOffsetDifference, withBytes: critValues[i])
//}
//
//// reverse mode residual
//cdol.replaceWordAtOffset(0x8022811c - kDolToRAMOffsetDifference, withBytes: 0x38800008)
//
//// paralysis to halve speed
//cdol.replaceWordAtOffset(0x80203adc - kDolToRAMOffsetDifference, withBytes: 0x56f7f87e)
//
//// choice scarf
//let choicescarfindex : UInt32 = 52
//let choiceStart = 0x80203ab4 - kDolToRAMOffsetDifference
//let choiceInstructions : [UInt32] = [kNopInstruction,0x7f43d378,0x4bfffdb5,0x28030000 + choicescarfindex,0x4082000C,0x1EF70003,0x56f7f87e]
//for i in 0 ..< choiceInstructions.count {
// cdol.replaceWordAtOffset(choiceStart + (i * 4), withBytes: choiceInstructions[i])
//}
//
//// move maintenance
//
// new shadow moves
//for m in [197,330,346] {
// let mov = XGMoves.move(m).data
// mov.HMFlag = true
// mov.save()
// let rel = XGFiles.common_rel.data!
// rel.replaceWordAtOffset(mov.startOffset + 0x14, withBytes: 0x00023101)
// rel.save()
//
//}
//
//var currentDescs = [Int]()
//var currentNames = [Int]()
//
//for m in 1 ..< kNumberOfMoves {
// let move = XGMoves.move(m)
// currentDescs.append(move.descriptionID)
// currentNames.append(move.nameID)
//}
//
//loadAllStrings()
//// hard shell flag
//let hardshells = ["aura sphere", "seed bomb","focus blast","pin missile","rock throw","energy ball","ice shard","icicle crash","explosion","sludge","sludgebomb","gunk shot","rock slide","zap cannon","shadow ball","leech seed","bullet seed","icicle spear","mud shot","rock blast","shadow pulse"]
//for name in hardshells {
// let mo = move(name).data
// mo.snatchFlag = true
// mo.save()
//}
//
////magic bounce
//let magicBounceBranchAddress = 0x8021855c
//let magicBounceCompareAddress = 0x80218564
//let magicBounceIndex : UInt32 = UInt32(kNumberOfAbilities + 2)
//let magicBounceBranchInstruction : UInt32 = 0x4bf3033d
//let magicBounceCompareInstruction : UInt32 = 0x28000000 + magicBounceIndex
//
//cdol.replaceWordAtOffset(magicBounceBranchAddress - kDolToRAMOffsetDifference, withBytes: magicBounceBranchInstruction)
//cdol.replaceWordAtOffset(magicBounceCompareAddress - kDolToRAMOffsetDifference, withBytes: magicBounceCompareInstruction)
//
//cdol.save()
//let ddol = XGFiles.dol.data!
//// sheer force
//let sheerForceStart = 0x80213d6c
//let sheerForceInstructions : [UInt32] = [0x7C7C1B78,0x7FA3EB78,0x4BFF1855,0x28030023,0x4082000C,0x3BA00000,0x48000024,0x7C7D1B78,0x7F83E378,0x4BF2A925,0x281D0020,0x7C7D1B78,0x4082000C,0x54600DFC,0x7C1D0378]
//
//for i in 0 ..< sheerForceInstructions.count {
// let offset = sheerForceStart + (i * 4) - kDolToRAMOffsetDifference
// ddol.replaceWordAtOffset(offset, withBytes: sheerForceInstructions[i])
//}
//
//// -ate abilities types
//let ateStart = 0x802c8648 - kDolToRAMOffsetDifference
//let ateInstructions = [0x7F83E378,0x4BE76225,0x28030000,0x408200E0,0x7FA3EB78,0x4BF3CF6D,0x28030056,0x4082000C,0x3860000F,0x480000DC,0x28030044,0x4082000C,0x38600009,0x480000CC,0x28030001,0x4082000C,0x38600002,0x480000BC,0x480000A4]
//
//for i in 0 ..< ateInstructions.count {
// let offset = ateStart + (i * 4)
// ddol.replaceWordAtOffset(offset, withBytes: UInt32(ateInstructions[i]))
//}
//
//let priorityAbilitiesStart = 0x8015224c - kDolToRAMOffsetDifference
//let priorityAbilitiesInstructions : [UInt32] = [0x9421fff0,0x7C0802A6,0x90010014,0x93E1000C,0x93C10008,0x7C7F1B78,0x48000074,0x4BFEC551,0x28030000,0x40820050,0x7FE3FB78,0x480B3351,0x28030059,0x41820024,0x28030043,0x40820034,0x7FC3F378,0x4BFEC5e1,0x28030002,0x40820024,0x38600001,0x48000020,0x7FC3F378,0x4bfec549,0x28030000,0x4082000C,0x38600001,0x48000008,0x38600000,0x80010014,0x83E1000C,0x83C10008,0x7C0803A6,0x38210010,0x4E800020,0x480B22DD,0x7C7E1B78,0x4BFFFF88]
//
//for i in 0 ..< priorityAbilitiesInstructions.count {
// let offset = priorityAbilitiesStart + (i * 4)
// ddol.replaceWordAtOffset(offset, withBytes: priorityAbilitiesInstructions[i])
//}
//
//let determineOrderOffsets = [0x801f43e8,0x801f43ec,0x801f43f4,0x801f43f8]
//let determineOrderInstructions : [UInt32] = [0x7f23cb78,0x4bf5de61,0x7f43d378,0x4bf5de55]
//
//for i in 0 ..< determineOrderOffsets.count {
// ddol.replaceWordAtOffset(determineOrderOffsets[i] - kDolToRAMOffsetDifference, withBytes: determineOrderInstructions[i])
//}
//
//ddol.save()
//let dol2 = XGFiles.dol.data!
//// hard shell ability
//let hardshellindex = 78
//let hardoffset1 = 0x8022580c - kDolToRAMOffsetDifference
//let hardcomparison : UInt32 = 0x2c00004e
//let hardoffset2 = 0x8022582c - kDolToRAMOffsetDifference
//let hardbranch : UInt32 = 0x4bf18db9
//
//dol2.replaceWordAtOffset(hardoffset1, withBytes: hardcomparison)
//dol2.replaceWordAtOffset(hardoffset2, withBytes: hardbranch)
//
//// regenerator
//let naturalcurechangestart = 0x8021c5cc - kDolToRAMOffsetDifference
//let naturalcurechanges : [UInt32] = [0x7C7E1B78,0x48002559,0x7fe3fb78]
//for i in 0 ... 2 {
// dol2.replaceWordAtOffset(naturalcurechangestart + (i * 4), withBytes: naturalcurechanges[i])
//}
//
//let regenStart = 0x8021eb28 - kDolToRAMOffsetDifference
//let regenCode : [UInt32] = [0x7fe3fb78,0xa063080c,0x28030054,0x41820008,0x4e800020,0x7fe3fb78,0x80630000,0x38630004,0xA0830090,0xa0630004,0x38000003, 0x7C0403D6,0x7C630214,0x7C032040,0x40810014,0x7fe3fb78,0x80630000,0x38630004,0xA0630090,0x7C641B78,0x7fe3fb78,0x80630000,0x38630004,0xb0830004,0x4e800020]
//for i in 0 ..< regenCode.count {
// dol2.replaceWordAtOffset(regenStart + (i * 4), withBytes: regenCode[i])
//}
//dol2.save()
//
//
//
//// effect accuracies
//for m in ["baby doll eyes","toxic","brave bird","head smash","short circuit","snore","outrage","swagger","knock off","overheat","psycho boost","shadow star"] {
// let mov = move(m).data
// mov.effectAccuracy = 0
// mov.save()
//}
//let newPokespotStart = 0x73300
//relocatePokespots(startOffset: UInt32(newPokespotStart), numberOfEntries: 25)
//
//let spotmons : [ [(name: String, minLevel: Int, maxLevel: Int, encounterPercentage: Int, stepsPerSnack: Int)] ] = [
// // rock
// [
// ("entei" , 25, 25, 2, 75),
// ("jirachi" , 10, 10, 1, 25),
// ("aerodactyl" , 24, 27, 9, 150),
// ("ponyta" , 15, 22, 5, 300),
// ("larvitar" , 19, 23, 9, 100),
// ("miltank" , 27, 32, 2, 400),
// ("sandshrew" , 18, 23, 7, 300),
// ("sandslash" , 28, 31, 2, 100),
// ("cacnea" , 26, 29, 8, 400),
// ("trapinch" , 21, 25, 6, 300),
// ("vibrava" , 35, 35, 2, 80),
// ("onix" , 21, 26, 2, 400),
// ("numel" , 23, 26, 5, 400),
// ("camerupt" , 33, 34, 1, 100),
// ("dugtrio" , 28, 29, 2, 100),
// ("hitmontop" , 22, 26, 8, 200),
// ("gligar" , 23, 26, 3, 400),
// ("graveler" , 25, 27, 2, 200),
// ("kecleon" , 23, 25, 3, 250),
// ("electrode" , 30, 32, 2, 150),
// ("cubone" , 18, 23, 4, 400),
// ("marowak" , 28, 29, 3, 100),
// ("kangaskhan" , 22, 26, 2, 300),
// ("tauros" , 23, 26, 4, 200),
// ("seviper" , 24, 27, 6, 400)
// ],
//
// // oasis
// [
// ("suicune" , 25, 26, 3, 50),
// ("celebi" , 15, 15, 1, 25),
// ("chansey" , 17, 22, 9, 100),
// ("roselia" , 26, 29, 2, 300),
// ("eevee" , 5, 13, 7, 400),
// ("lanturn" , 27, 28, 6, 200),
// ("gloom" , 21, 24, 2, 300),
// ("persian" , 28, 29, 2, 300),
// ("bellsprout" , 21, 26, 6, 250),
// ("weepinbell" , 22, 23, 2, 150),
// ("kingler" , 28, 29, 2, 250),
// ("scyther" , 23, 27, 7, 150),
// ("ninjask" , 22, 28, 2, 250),
// ("exeggcute" , 21, 26, 8, 200),
// ("feebas" , 1, 1, 3, 100),
// ("magikarp" , 1, 1, 8, 400),
// ("tangela" , 24, 28, 2, 300),
// ("tentacool" , 22, 25, 3, 400),
// ("tentacruel" , 30, 32, 2, 150),
// ("octillery" , 25, 27, 3, 250),
// ("vulpix" , 18, 22, 5, 350),
// ("ninetales" , 23, 26, 2, 150),
// ("jumpluff" , 27, 29, 2, 200),
// ("tropius" , 26, 29, 4, 250),
// ("swablu" , 21, 26, 7, 350)
// ],
//
// // cave
// [
// ("raikou" , 25, 25, 2, 100),
// ("mew" , 5, 5, 1, 25),
// ("dratini" , 11, 22, 9, 150),
// ("absol" , 24, 26, 7, 250),
// ("golbat" , 22, 25, 6, 400),
// ("porygon2" , 24, 26, 7, 300),
// ("mantine" , 23, 25, 2, 300),
// ("wailmer" , 22, 24, 2, 400),
// ("omanyte" , 23, 26, 7, 150),
// ("kabuto" , 22, 27, 7, 150),
// ("psyduck" , 19, 24, 5, 300),
// ("golduck" , 33, 34, 1, 100),
// ("poliwhirl" , 25, 26, 2, 250),
// ("abra" , 17, 21, 6, 350),
// ("kadabra" , 19, 24, 2, 150),
// ("horsea" , 21, 24, 3, 400),
// ("seadra" , 32, 33, 2, 50),
// ("shellder" , 21, 23, 5, 400),
// ("cloyster" , 22, 25, 2, 150),
// ("crawdaunt" , 30, 30, 7, 100),
// ("ditto" , 20, 23, 5, 300),
// ("wooper" , 18, 22, 3, 400),
// ("quagsire" , 21, 24, 2, 200),
// ("mr. mime" , 24, 26, 2, 250),
// ("qwilfish" , 25, 27, 3, 300)
// ],
//
// // all
// [
// ("bonsly" , 10, 10, 35, 100),
// ("munchlax" , 10, 10, 5, 50),
// ],
//]
//
//for i in 0 ... 3 {
// let spot = XGPokeSpots(rawValue: i)!
// let monList = spotmons[i]
//
// var percentageTotal = 0
//
// for j in 0 ..< monList.count {
// let (name, minLevel, maxLevel, encounterPercentage, stepsPerSnack) = monList[j]
// let mon = XGPokeSpotPokemon(index: j, pokespot: spot)
// mon.pokemon = pokemon(name)
// mon.minLevel = minLevel
// mon.maxLevel = maxLevel
// mon.encounterPercentage = encounterPercentage
// mon.stepsPerSnack = stepsPerSnack
// mon.save()
//
// percentageTotal += encounterPercentage
// }
//
// if percentageTotal != 100 && spot != .all {
// printg("wrong percentage total for spot: " + spot.string, percentageTotal)
// }
//}
//let kFirstFieldEffectEntry = 0x03fc3e0
//let kSizeOfFieldEffectEntry = 0x14
//let kNumberOfFieldEffects = 0x57
//
//let kFieldEffectDurationOffset = 0x4
//let kFieldEffectStringIDOffset = 0x12
//
//let rel = XGFiles.nameAndFolder("xg ram.raw", .Documents).data
//for i in 0 ..< kNumberOfFieldEffects {
// let effect = kFirstFieldEffectEntry + (i * kSizeOfFieldEffectEntry)
// let stringID = rel.get2BytesAtOffset(effect + kFieldEffectStringIDOffset)
// let duration = rel.getByteAtOffset(effect + kFieldEffectDurationOffset)
// print(i,getStringSafelyWithID(id: stringID),"duration: ", duration)
//}
//let iso = XGISO()
//
//for file in ["kyogre","ootachi","hanecco","groudon","kongpang","kyukon","garagara","sleeper"].map({ (str) -> String in
// return "pkx_" + str + ".fsys"
// }).sorted(by: { (s1, s2) -> Bool in
// return iso.sizeForFile(s1)! < iso.sizeForFile(s2)!
// }) {
// print(file, iso.sizeForFile(file)!)
//}
//
//let replacements = [("robo_groudon","hanecco"),("robo_kyogre","sleeper"),("alolan_marowak","kongpang"),("alolan_ninetales","ootachi")]
//for (new,old) in replacements {
// let oldFile = "pkx_" + old + ".fsys"
// let oldFsys = iso.dataForFile(filename: oldFile)!
// let fsys = XGFiles.fsys(oldFile)
// oldFsys.file = fsys
// oldFsys.save()
// fsys.fsysData.shiftAndReplaceFileWithIndex(0, withFile: XGFiles.nameAndFolder(new + ".fdat", .TextureImporter).compress())
// iso.importFiles([fsys])
//}
//let ldol = XGFiles.dol.data!
//
//// old stat booster (r3 index of stat to boost, r4 battle pokemon)
//let statBoosterStart = 0x8015258c - kDolToRAMOffsetDifference
//let statBoosterCode : [UInt32] = [0x9421ffe0,0x7c0802a6,0x90010024,0x93e1001c,0x93c10018,0x93a10014,0x93810010,
//0x7C9F2378,0x480cfed9,0x7c601b78,0x7fe3fb78,0x7c1d0378,0x38800000,0x7fa5eb78,0x38c00000,0x4bff08b5,
//0x7c7c0774,0x2c1c000c,0x4080006c,//------
//0x7fe3fb78,0x4bff64bd,0x5460043e,0x28000002,0x41820058, // ------
//0x7fe4fb78,0x38600000,0x480a418d,0x381c0001,0x7fe3fb78,0x7c070774,0x7fa5eb78,0x38800000,0x38c00000,
//0x4bfef705,0x808dbb04,0x3c608041,0x38a00011,0x38000000,0x3c840001,0x38637957,
//0x98a460a4,0x808dbb04,0x3c840001,0x980460a5,0x480d106d,
//0x80010024,0x83e1001c,0x83c10018,0x83a10014,0x83810010,0x7c0803a6,0x38210020,0x4e800020
//]
//
//for i in 0 ..< statBoosterCode.count {
// ldol.replaceWordAtOffset(statBoosterStart + (i * 4), withBytes: statBoosterCode[i])
//}
//
//// tailwind and trick room
//let safeguards = [0x80214040,0x8021bd6c,0x8022cd90,0x8022d538,0x8022d94c,0x8022e0fc,0x8022e244,0x8022ee48,0x80230154,0x802302f4,0x802306b8,0x80230bd0,0x802314e8,0x802ccf60,0x802de1b4]
//let mists = [0x8022c910,0x802cc790,0x802ccab4,0x802cccf8,0x802ccf40,0x802220a4,0x80210990]
//for offset in safeguards + mists {
// ldol.replaceWordAtOffset(offset - kDolToRAMOffsetDifference, withBytes: 0x38600000)
//}
//
//let tailBranchOffset = 0x801f4430 - kDolToRAMOffsetDifference
//let tailBranchInstruction = 0x4bf5e04d
//ldol.replaceWordAtOffset(tailBranchOffset, withBytes: UInt32(tailBranchInstruction))
//
//let tailStart = 0x8015247c - kDolToRAMOffsetDifference
//let tailCode : [UInt32] = [0x9421ffe0,0x7c0802a6,0x90010024,0x93e1001c,0x93c10018,0x93a10014,0x93810010,
//0x7f23cb78,0x3880004b,0x480a6041,0x28030001,0x40820008,0x57BD083C,
//0x7f43d378,0x3880004b,0x480a6029,0x28030001,0x40820008,0x57DE083C,
//0x7f23cb78,0x3880004c,0x480a6011,0x28030001,0x40820008,0x48000018,
//0x7f43d378,0x3880004c,0x480a5ff9,0x28030001,0x4082000c,0x7C1EE840,0x48000008,0x7c1df040,
//0x80010024,0x83e1001c,0x83c10018,0x83a10014,0x83810010,0x7c0803a6,0x38210020,0x4e800020
//]
//
//for i in 0 ..< tailCode.count {
// ldol.replaceWordAtOffset(tailStart + (i * 4), withBytes: tailCode[i])
//}
//
//
// assault vest status moves
//
//let avBranchOffset = 0x802014ac - kDolToRAMOffsetDifference
//let avBranchInstruction : UInt32 = 0x4bf16619
//
//ldol.replaceWordAtOffset(avBranchOffset, withBytes: avBranchInstruction)
//
//let assaultVestStart = 0x80117ac4 - kDolToRAMOffsetDifference
//let assaultVestCode : [UInt32] = [0x28030001,0x40820008,0x4e800020,0x281f004c,0x4082000c,0x38600001,0x4e800020,0x38600000,0x4e800020]
//
//for i in 0 ..< assaultVestCode.count {
// ldol.replaceWordAtOffset(assaultVestStart + (i * 4), withBytes: assaultVestCode[i])
//}
//ldol.replaceWordAtOffset(0x802014b0 - kDolToRAMOffsetDifference, withBytes: 0x28030001)
//
//
//// allow shadow moves to use hm flag
//let shadowBranchOffsetsR0 = [0x8001c60c,0x8001c7ec,0x8001e314,0x80036c60]
//for offset in shadowBranchOffsetsR0 {
// ldol.replaceWordAtOffset(offset - kDolToRAMOffsetDifference, withBytes: createBranchAndLinkFrom(offset: offset - 0x80000000, toOffset: 0x21eb8c))
//}
//
//let shadowStart = 0x8021eb8c - kDolToRAMOffsetDifference
//let shadowCode : [UInt32] = [0x7C030378,0x9421fff0,0x7c0802a6,0x90010014,
//0x4bf1e4a1,0x28030001,
//0x80010014,0x7c0803a6,0x38210010,0x38000165,0x4e800020,
//0x7C641B78,
//0x1c030038,0x806d89d4,0x7c630214,//pointer to move
//0x88630012,0x28030001,0x7C832378,
//0x4d800020,0x38600000,0x4e800020
//]
//
//for i in 0 ..< shadowCode.count {
// ldol.replaceWordAtOffset(shadowStart + (i * 4), withBytes: shadowCode[i])
//}
//
//let shadowR3Offsets = [0x8007e6dc,0x80034e98]
//for offset in shadowR3Offsets {
// ldol.replaceWordAtOffset(offset - kDolToRAMOffsetDifference, withBytes: createBranchFrom(offset: offset - 0x80000000, toOffset: 0x21ebb8))
//}
//
//ldol.save()
//
//let origin = XGStringTable.common_relOriginal()
//var newIDs = [Int]()
//
//loadAllStrings()
//for str in allStrings {
// if str.table == XGFiles.common_rel {
// if str.string == "*" || str.string == "_" {
// if str.id > 0x1000 {
// if origin.stringSafelyWithID(str.id).string.characters.count > 3 {
// newIDs.append(str.id)
// }
// }
// }
// }
//}
//
//let newAbs = ["Motor Drive", "Storm Drain", "Sap Sipper", "Justified","Reckless","Download","Scrappy","Skill Link","Defiant","Competitive","Snow Cloak","Magic Guard"]
//let newDescs = ["Electricity raises speed.","Water raises sp.atk.","Grass raises attack.","Dark raises attack.","Powers recoil moves.","Raises sp.atk in battle.", "Can hit ghosts.","Always 5 hits.","Drops raise attack.", "Drops raise sp.atk.","Hail boosts evasion.","Prevents side damage."]
//
//
//for i in 0 ..< newAbs.count {
// let ab = XGAbilities.ability(95 + i)
// ab.replaceNameID(newID: newIDs[i * 2])
// ab.replaceDescriptionID(newID: newIDs[(i * 2) + 1])
// getStringSafelyWithID(id: newIDs[i * 2]).duplicateWithString(newAbs[i]).replace()
// getStringSafelyWithID(id: newIDs[(i * 2) + 1]).duplicateWithString(newDescs[i]).replace()
//}
//// trick room tailwind part 2
//let kdol = XGFiles.dol.data!
//
//let tr2BranchOffset = 0x80152498 - kDolToRAMOffsetDifference
//let tr2BranchInstr = createBranchFrom(offset: 0x152498, toOffset: 0x152520)
//kdol.replaceWordAtOffset(tr2BranchOffset, withBytes: tr2BranchInstr)
//
//let tr2Start = 0x80152520 - kDolToRAMOffsetDifference
//let tr2Instructions : [UInt32] = [
// 0x7F24CB78,0x38600002,createBranchAndLinkFrom(offset: 0x152528, toOffset: 0x1efcac),0x7C7C1B78,
// 0x7F44D378,0x38600002,createBranchAndLinkFrom(offset: 0x152538, toOffset: 0x1efcac),0x7c7f1b78,
// 0x7F83E378,createBranchFrom(offset: 0x152544, toOffset: 0x15249c) // mr r3, r28 to continue original tr code
//]
//
//
//for i in 0 ..< tr2Instructions.count {
// kdol.replaceWordAtOffset(tr2Start + (i * 4), withBytes: tr2Instructions[i])
//}
//
//kdol.replaceWordAtOffset(0x801524c8 - kDolToRAMOffsetDifference, withBytes: 0x7F83E378)
//for offset in [0x801524b0,0x801524e0] {
// kdol.replaceWordAtOffset(offset - kDolToRAMOffsetDifference, withBytes: 0x7FE3FB78)
//}
//// No guard
//let noguardindex = 93
//let noguardstart = 0x802178d4 - kDolToRAMOffsetDifference
//let noguardinstructions : [UInt32] = [kNopInstruction,0x2819005D,
// 0x4182000C,
// 0x281A005D,
// 0x4082000C,
// 0x3AC00064,
// 0x480000CC
//]
//
//for i in 0 ..< noguardinstructions.count {
// kdol.replaceWordAtOffset(noguardstart + (i * 4), withBytes: noguardinstructions[i])
//}
//
//kdol.save()
//
//switchNextPokemonAtEndOfTurn()
//paralysisHalvesSpped()
//for mon in XGDecks.DeckDarkPokemon.allPokemon.sorted(by: { (p1, p2) -> Bool in
// return p1.shadowFleeValue < p2.shadowFleeValue
//}).filter({ (p) -> Bool in
// return p.species.index > 0
//}) {
// let tabs = 11 - (mon.species.name.string.characters.count)
// var nameTab = " "
// for t in 0 ..< tabs {
// nameTab += " "
// }
//
// print(mon.species.name, nameTab, mon.shadowFleeValue.hex(), "\t", mon.shadowAggression, "\t", mon.shadowUnknown2,"\t")
//}
//for mon in XGDecks.DeckStory.allPokemon.filter({ (p1) -> Bool in
// return p1.unknown1 > 0
//}) {
// let tabs = 11 - (mon.species.name.string.characters.count)
// var nameTab = " "
// for t in 0 ..< tabs {
// nameTab += " "
// }
// let tab = "\t"
//
// var binary = String(mon.unknown1, radix: 2)
// for i in 0 ..< (8 - binary.characters.count) {
// binary = "0" + binary
// }
//
// print(mon.species.name,nameTab,String(format:"%2d",mon.level),tab,String(format:"%2x",mon.unknown1),binary)
//}
// skill link part 2
//let dol = XGFiles.dol.data!
//
//dol.replaceWordAtOffset(0x80221d70 - kDolToRAMOffsetDifference, withBytes: createBranchAndLinkFrom(offset: 0x221d70, toOffset: 0x152548))
//
//dol.save()
//let skillLinkStart = 0x80152548 - kDolToRAMOffsetDifference
//let skillLinkBranchOffset = 0x80221d98 - kDolToRAMOffsetDifference
//let skillLinkBranchInstruction = createBranchAndLinkFrom(offset: skillLinkBranchOffset, toOffset: skillLinkStart)
//let skillLinkCode : [UInt32] = [
//0x5404063e, // rlwinm r4, r0, 0, 24, 31 (000000ff) like original code
//0x387F0648, // addi r3, r31, 1608 turns r31 back to battle pokemon pointer
//0xa063080c, // lhz r3, 0x080C (r3) get the pokemon's ability
//0x28030066, // compare with skill link
//0x41820008, // beq 0x8 if skill link then continue
//0x4e800020, // else return
//0x38800005, // li r4,5 load 5 turns
//0x4e800020, // return
//]
//
//let bdol = XGFiles.dol.data!
//bdol.replaceWordAtOffset(skillLinkBranchOffset, withBytes: skillLinkBranchInstruction)
//for i in 0 ..< skillLinkCode.count {
// bdol.replaceWordAtOffset(skillLinkStart + (i * 4), withBytes: skillLinkCode[i])
//}
//
//// foes can enter reverse mode
//let reverseOffset = 0x80226754 - kDolToRAMOffsetDifference
//bdol.replaceWordAtOffset(reverseOffset, withBytes: kNopInstruction)
//
//
////// no infinite weather
//let infiniteOffsets = [0x80225dc4, 0x80225ddc,0x80225d80,0x80225d98,0x80225e20,0x80225e08]
//let infiniteReplacements : [UInt32] = [0x38800056,0x38800055,0x38800054]
//for i in 0 ..< infiniteReplacements.count {
// let index = i * 2
// bdol.replaceWordAtOffset(infiniteOffsets[index] - kDolToRAMOffsetDifference, withBytes: infiniteReplacements[i])
// bdol.replaceWordAtOffset(infiniteOffsets[index + 1] - kDolToRAMOffsetDifference, withBytes: infiniteReplacements[i])
//}
//bdol.save()
//
//let sm = move("shadow massacre").data
//sm.priority = 0x100 - 7
//sm.save()
//var unused = [Int]()
//
//for m in 1 ..< XGDecks.DeckStory.DPKMEntries {
// if unused.count < 8 {
// let mon = XGTrainerPokemon(DeckData: XGDeckPokemon.dpkm(m, .DeckStory))
// if mon.species.index == 0 {
// unused.append(m)
// print(m)
// }
// }
//}
//let newSpecs = ["marowak","nosepass"]
//let newCatch = [45,160]
//let newCount = [2500,1500]
//let newLevs = [54,29]
//let newItems = ["thick club",""]
//
//for i in 0 ..< 2 {
// let index = 107 + i
//
// let ddpk = XGDeckPokemon.ddpk(index)
// let poke = ddpk.data
// poke.shadowCatchRate = newCatch[i]
// let spec = pokemon(newSpecs[i])
// poke.species = spec
// poke.shadowCounter = newCount[i]
// let lev = newLevs[i]
// poke.level = lev
// poke.moves = spec.movesForLevel(lev)
// if newItems[i] != "" {
// poke.item = item(newItems[i])
// }
// poke.shadowFleeValue = 0x80
// poke.shadowAggression = 3
// poke.ShadowDataInUse = true
//
// poke.save()
//}
//let kdol = XGFiles.dol.data!
//// trick room part 3
//
//let get_pointer_index_func = 0x801f3f3c - kDolToRAMOffsetDifference
//let get_pointer_general_func = 0x801efcac - kDolToRAMOffsetDifference
//let check_status_func = 0x801f848c - kDolToRAMOffsetDifference
//let set_status_function = 0x801f8438 - kDolToRAMOffsetDifference
//let end_status_function = 0x801f8534 - kDolToRAMOffsetDifference
//
//let mist_start = 0x80220f94 - kDolToRAMOffsetDifference
//let mist_continue = 0x80220ff4 - kDolToRAMOffsetDifference
//let tr_start = 0x8021c268 - kDolToRAMOffsetDifference
//
//let label_set_status = tr_start + 0x28
//let label_end_status = tr_start + 0x5c
//let label_end = tr_start + 0x84
//
//kdol.replaceWordAtOffset(mist_start, withBytes: createBranchFrom(offset: mist_start, toOffset: tr_start))
//
//let mistCode : [UInt32] = [
//
// 0x38600000, //0x00 li r3, 0
// //0x04 bl get_pointer_index
// createBranchAndLinkFrom(offset: tr_start + 0x04, toOffset: get_pointer_index_func),
// 0x7C641B78, //0x08 mr r4, r3
// 0x38600002, //0x0c li r3, 2
// //0x10 bl get_pointer_general
// createBranchAndLinkFrom(offset: tr_start + 0x10, toOffset: get_pointer_general_func),
// 0x7C7F1B78, //0x14 mr r31, r3
// 0x3880004C, //0x18 li r4, 76
// //0x1c bl check_status
// createBranchAndLinkFrom(offset: tr_start + 0x1C, toOffset: check_status_func),
// 0x28030002, //0x20 cmpwi r3, 2
// powerPCBranchNotEqualFromOffset(from: tr_start + 0x24, to: label_end_status),
// // set_status: ---------------- 0x28
// 0x7fe3fb78, //0x28 mr r3, r31
// 0x3880004C, //0x2c li r4, 76
// 0x38a00000, //0x30 li r5, 0
// createBranchAndLinkFrom(offset: tr_start + 0x34, toOffset: set_status_function),
// //0x34 bl set_status
// 0x38600001, //0x38 li r3, 1
// createBranchAndLinkFrom(offset: tr_start + 0x3c, toOffset: get_pointer_index_func),
// //0x3c bl get_pointer_index
// 0x7C641B78, //0x40 mr r4, r3
// 0x38600002, //0x44 li r3, 2
// createBranchAndLinkFrom(offset: tr_start + 0x48, toOffset: get_pointer_general_func),
// //0x48 bl get_pointer_general
// 0x3880004C, //0x4c li r4, 76
// 0x38a00000, //0x50 li r5, 0
// createBranchAndLinkFrom(offset: tr_start + 0x54, toOffset: set_status_function),
// //0x54 bl set_status
// createBranchFrom(offset: tr_start + 0x58, toOffset: label_end),
// //0x58 b end:
// // end_status: ---------------- 0x5c
// 0x7fe3fb78, //0x5c mr r3, r31
// 0x3880004C, //0x60 li r4, 76
// createBranchAndLinkFrom(offset: tr_start + 0x64, toOffset: end_status_function),
// //0x64 bl end_status
// 0x38600001, //0x68 li r3, 1
// createBranchAndLinkFrom(offset: tr_start + 0x6c, toOffset: get_pointer_index_func),
// //0x6c bl get_pointer_index
// 0x7C641B78, //0x70 mr r4, r3
// 0x38600002, //0x74 li r3, 2
// createBranchAndLinkFrom(offset: tr_start + 0x78, toOffset: get_pointer_general_func),
// //0x78 bl get_pointer_general
// 0x3880004C, //0x7c li r4, 76
// createBranchAndLinkFrom(offset: tr_start + 0x80, toOffset: end_status_function),
// //0x80 bl end_status
// // end: ------------------------ 0x84
// createBranchFrom(offset: tr_start + 0x84, toOffset: mist_continue)
// //0x84 b mist_continue
//]
//
//for i in 0 ..< mistCode.count {
// let offset = i * 4
// let instruction = mistCode[i]
// kdol.replaceWordAtOffset(tr_start + offset, withBytes: instruction)
//}
//
//
//// tailwind part 3
//// removes some code to do with safeguard
//let tw_start = 0x8021342c - kDolToRAMOffsetDifference
//let tw_end = 0x80213450 - kDolToRAMOffsetDifference
//let tw_code : [UInt32] = [
// 0xa09f0002,
// 0x2804004b,
// powerPCBranchEqualFromOffset(from: tw_start + 8, to: tw_end),
// 0x4BFE50A9,
// 0x28030001,
// 0x40820010,
// 0x807F0004
//]
//
//for i in 0 ..< tw_code.count {
// let offset = i * 4
// let inst = tw_code[i]
// kdol.replaceWordAtOffset(tw_start + offset, withBytes: inst)
//}
//
// kdol.save()
//
//
//// magic coat mirror match check
//let magicBranch = 0x80218568 - kDolToRAMOffsetDifference
//let magicCheckStart = 0x80152568 - kDolToRAMOffsetDifference
//let magicTrueOffset = 0x8021856c - kDolToRAMOffsetDifference
//let magicFalseOffset = 0x802185dc - kDolToRAMOffsetDifference
//let get_ability_func = 0x80148898 - kDolToRAMOffsetDifference
//
//replaceASM(startOffset: magicBranch, newASM: [createBranchFrom(offset: magicBranch, toOffset: magicCheckStart)])
//
//let magicCode : ASM = [
// powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x18), // bne magic false
// 0x7fa3eb78, // mr r3, r29
// createBranchAndLinkFrom(offset: magicCheckStart + 0x8, toOffset: get_ability_func), // bl battle_pokemon_get_ability
// 0x2803004f, // cmpwi r3, 79
// powerPCBranchEqualFromOffset(from: 0x10, to: 0x18), // beq magic flase
// createBranchFrom(offset: magicCheckStart + 0x14, toOffset: magicTrueOffset), // b magic true
// createBranchFrom(offset: magicCheckStart + 0x18, toOffset: magicFalseOffset) // b magic false
//]
//replaceASM(startOffset: magicCheckStart, newASM: magicCode)
//
//// old ability activate function
//let abilityActivateStart = 0x80220708 - kDolToRAMOffsetDifference
//let messageParams = 0x801f6780 - kDolToRAMOffsetDifference
//let animSoundCallBack = 0x802236a8 - kDolToRAMOffsetDifference
//replaceASM(startOffset: abilityActivateStart, newASM: [
// // code extract of animation from speed boost activation code
// 0x9421fff0,
// 0x7c0802a6,
// 0x90010014,
// 0x7C641B78, // mr r4, r3
// 0x38600000, // li r3, 0
// createBranchAndLinkFrom(offset: abilityActivateStart + 0x14, toOffset: messageParams),
// 0x808dbb04,
// 0x3c608041,
// 0x38a00011,
// 0x38000000,
// 0x3c840001,
// 0x38637957,
// 0x98a460a4,
// 0x808dbb04,
// 0x3c840001,
// 0x980460a5,
// createBranchAndLinkFrom(offset: abilityActivateStart + 0x40, toOffset: animSoundCallBack),
// 0x80010014,
// 0x7c0803a6,
// 0x38210010,
// 0x4e800020 // blr
// ])
//
//
//
//
//// rough skin residual
//replaceASM(startOffset: 0x80225234 - kDolToRAMOffsetDifference, newASM: [0x38800008])
//
//
//
//// shadow max belly drum effect
//let bellyBranch = 0x8021e724 - kDolToRAMOffsetDifference
//let bellyStart = 0x802226f4 - kDolToRAMOffsetDifference
//let checkShadowPokemon = 0x80149014 - kDolToRAMOffsetDifference
//replaceASM(startOffset: bellyBranch, newASM: [createBranchFrom(offset: bellyBranch, toOffset: bellyStart)])
//replaceASM(startOffset: bellyStart, newASM: [
// 0x80630000, // lw r3, 0 (r3)
// 0x38630004, // addi r3, 4
// createBranchAndLinkFrom(offset: bellyStart + 0x8, toOffset: checkShadowPokemon),
// 0x28030000, // cmpwi r3, 0 check not shadow
// powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x38800002, // li r4, 2
// createBranchFrom(offset: 0x0, toOffset: 0x8),
// 0x38800003, // li r4, 3
// 0x7f83e378, // mr r3, r28
// createBranchFrom(offset: bellyStart + 0x24, toOffset: bellyBranch + 0x4)
// ])
//
//// freeze dry
//let freezeBranches = [0x80216828,0x80216858]
//let freezeStart = 0x8022271c - kDolToRAMOffsetDifference
//let effectCheck = 0x80117a2c - kDolToRAMOffsetDifference
//for i in 0 ..< freezeBranches.count {
// let branch = freezeBranches[i] - kDolToRAMOffsetDifference
// replaceASM(startOffset: branch, newASM: [createBranchAndLinkFrom(offset: branch, toOffset: freezeStart)])
//}
//replaceASM(startOffset: freezeStart, newASM: [
// 0x281500c6, // cmpwi r21, freeze dry
// powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x14), //bne 0x14
// 0x2804000b, // cmpwi r4, water type
// powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc), //bne 0xc
// 0x38600041, // li r3, super effective
// 0x4e800020, // blr
// // get type matchup
// 0x1ca30030,
// 0x5480083c,
// 0x80cd89ac,
// 0x7ca50214,
// 0x3805000c,
// 0x7c66022e,
// 0x4e800020, // blr
// ])
//
//
//// shadow hunter shadow seeker
//let hunterBranch = 0x80216da0 - kDolToRAMOffsetDifference
//let hunterStart = 0x80222750 - kDolToRAMOffsetDifference
//replaceASM(startOffset: hunterBranch, newASM: [createBranchAndLinkFrom(offset: hunterBranch, toOffset: hunterStart)])
//replaceASM(startOffset: hunterStart, newASM: [
// 0x28030000, // cmpwi r3, 0
// powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc), //bne 0xc
// 0x38000000, // li r0, 0
// 0x4e800020, // blr
// 0x7f43d378, // mr r3, r26
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0xa063001c, // lhz 0x001c(r3) (get move effect)
// 0x28030015, // cmpwi r3, move effect 21 (shadow seeker/hunter)
// powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x38000000, // li r0, 0
// 0x4e800020, // blr
// 0x38000001, // li r0, 1
// 0x4e800020, // blr
// ])
//
//// feint
//let feintBranch = 0x80216708 - kDolToRAMOffsetDifference
//let feintStart = 0x8022075c - kDolToRAMOffsetDifference
//let feintEnd = 0x80216728 - kDolToRAMOffsetDifference
//let endStatus = 0x802026a0 - kDolToRAMOffsetDifference
//replaceASM(startOffset: feintBranch, newASM: [createBranchFrom(offset: feintBranch, toOffset: feintStart)])
//replaceASM(startOffset: feintStart, newASM: [
// 0x7ea3ab78, // mr r3, r21
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0xa063001c, // lhz 0x001c(r3) (get move effect)
// 0x28030016, // cmpwi r3, move effect 22 (feint)
// powerPCBranchNotEqualFromOffset(from: feintStart + 0x18, to: feintStart + 0x28),
// 0x7ec3b378, // mr r3, r22
// 0x3880002b, // li r4, protect status
// createBranchAndLinkFrom(offset: feintStart + 0x24, toOffset: endStatus),
// createBranchFrom(offset: feintStart + 0x28, toOffset: feintEnd),
// ])
//
//
//// foul play
//let foulBranch = 0x8022a188 - kDolToRAMOffsetDifference
//let foulStart = 0x8022278c - kDolToRAMOffsetDifference
//let foulEnd = foulBranch + 0x8
//replaceASM(startOffset: foulBranch, newASM: [createBranchFrom(offset: foulBranch, toOffset: foulStart), kNopInstruction])
//replaceASM(startOffset: foulStart, newASM: [
// 0x7c140378, // mr r20, r0
// 0x7e238b78, // mr r3, r17
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0xa063001c, // lhz 0x001c(r3) (get move effect)
// 0x2803000f, // cmpwi r3, move effect 15 (foul play)
// powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x14),
// 0x7e439378, // mr r3, r18
// 0xa0630092, // lhz r3, 0x0092(r3) (get attack)
// 0x7c601b78, // mr r0, r3
// 0x7c150378, // mr r21, r0
// 0x7e439378, // mr r3, r18
// createBranchFrom(offset: foulStart + 0x34, toOffset: foulEnd)
// ])
//
//// facade with burn
//let facadeBranch = 0x8022a5c4 - kDolToRAMOffsetDifference
//let facadeStart = 0x8021e998 - kDolToRAMOffsetDifference
//let checkStatus = 0x802025f0 - kDolToRAMOffsetDifference
//replaceASM(startOffset: facadeBranch, newASM: [createBranchFrom(offset: facadeBranch, toOffset: facadeStart)])
//replaceASM(startOffset: facadeStart, newASM: [
// 0x7de37b78, // mr r3, r15
// 0x38800006, // mr r4, burn
// createBranchAndLinkFrom(offset: facadeStart + 0x8, toOffset: checkStatus),
// 0x28030001, // cmpwi r3, 1
// powerPCBranchNotEqualFromOffset(from: 0x10, to: 0x18),
// 0x56b50c3c, // r21 *= 2 double attack
// 0x56a3043e, // rlwinm r3, r21 (overwritted code)
// createBranchFrom(offset: facadeStart + 0x1c, toOffset: facadeBranch + 0x4)
// ])
//
//// acrobatics
//let acroBranch = 0x8022a110 - kDolToRAMOffsetDifference
//let acroStart = 0x8021e9b8 - kDolToRAMOffsetDifference
//let acroEnd = acroBranch + 0x4
//replaceASM(startOffset: acroBranch, newASM: [createBranchFrom(offset: acroBranch, toOffset: acroStart)])
//replaceASM(startOffset: acroStart, newASM: [
// 0x7de37b78, // mr r3, r15
// 0x80630000, // lw r3, 0 (r3)
// 0x38630004, // addi r3, 4
// 0xa0630002, // lhz r3, 0x0002(r3) get item
// 0x28030000, // cmpwi r3, 0
// powerPCBranchEqualFromOffset(from: 0x0, to: 0x8),
// createBranchFrom(offset: 0x18, toOffset: 0x2c),
// 0x7e238b78, // mr r3, r17
// 0x280300b2, // cmpwi r3, acrobatics
// powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x56b50c3c, // r21 *= 2 double attack
// 0x7de47b78, // mr r4, r15 overwritten code
// createBranchFrom(offset: acroStart + 0x30, toOffset: acroEnd)
// ])
//
//// thick club alolan marowak
//replaceASM(startOffset: 0x8022a4c8 - kDolToRAMOffsetDifference, newASM: [0x28000109])
//
//// shadow sky residual damage
//replaceASM(startOffset:0x80221320 - kDolToRAMOffsetDifference, newASM: [0x38800008])
//
//// remove explosion defense halving
//replaceASM(startOffset: 0x8022a780 - kDolToRAMOffsetDifference, newASM: [kNopInstruction])
//
//// psyshock psystrike
//let psyBranch = 0x8022a97c - kDolToRAMOffsetDifference
//let psyStart = 0x8021e9fc - kDolToRAMOffsetDifference
//let psyTrue = 0x8022a7fc - kDolToRAMOffsetDifference
//let psyfalse = 0x8022a980 - kDolToRAMOffsetDifference
//let psy2Start = 0x8021ea2c - kDolToRAMOffsetDifference
//let psy2Branch = 0x8022a85c - kDolToRAMOffsetDifference
//let psy2End = psy2Branch + 0x4
//replaceASM(startOffset: psyBranch, newASM: [createBranchFrom(offset: psyBranch, toOffset: psyStart)])
//replaceASM(startOffset: psyStart, newASM: [
// 0x7c6303d6, // divw r3, r3, r0 (overwritten by branch)
// 0x7C641B78, // mr r4, r3
// 0x7e238b78, // mr r3, r17
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0xa063001c, // lhz 0x001c(r3) (get move effect)
// 0x2803000e, // cmpwi r3, move effect 14 (psyshock)
// 0x7c832378, // mr r3, r4 (overwritten by branch)
// powerPCBranchEqualFromOffset(from: 0x0, to: 0x8),
// createBranchFrom(offset: psyStart + 0x20, toOffset: psyfalse),
// createBranchFrom(offset: psyStart + 0x24, toOffset: psyTrue),
// ])
//replaceASM(startOffset: psy2Branch, newASM: [createBranchFrom(offset: psy2Branch, toOffset: psy2Start)])
//replaceASM(startOffset: psy2Start, newASM: [
// 0x28030000, // cmpwi r3, 0
// powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x38000000, // li r0,0
// createBranchFrom(offset: psy2Start + 0xc, toOffset: psy2End),
// 0x7e238b78, // mr r3, r17
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0xa063001c, // lhz 0x001c(r3) (get move effect)
// 0x2803000e, // cmpwi r3, move effect 14 (psyshock)
// powerPCBranchEqualFromOffset(from: 0x0, to: 0xc),
// 0x38000001, // li r0, 1
// createBranchFrom(offset: psy2Start + 0x30, toOffset: psy2End),
// 0x38000000, // li r0, 0
// createBranchFrom(offset: psy2Start + 0x38, toOffset: psy2End),
// ])
//
//// lightball attack boost
//replaceASM(startOffset: 0x8022a48c - kDolToRAMOffsetDifference, newASM: [
// 0x281d0019, // cmpwi r29, pikachu
// 0x4082000c, // bne 0xc
// 0x56b50c3c, // r21 *= 2 (double attack)
// ])
//
//
//// sand spdef boost for rock types
//let sandBranch = 0x8022a1c4 - kDolToRAMOffsetDifference
//let sandEnd = sandBranch + 0x4
//let sandStart = 0x8021db34 - kDolToRAMOffsetDifference
//let checkHasType = 0x802054fc - kDolToRAMOffsetDifference
////replaceASM(startOffset: sandBranch, newASM: [createBranchFrom(offset: sandBranch, toOffset: sandStart)])
//replaceASM(startOffset: sandStart, newASM: [
// // sandstorm spdef boost for rock types
// 0x80010010, // lwz r0, 0x0010(sp) (load weather)
// 0x28000003, // cmpwi r0, sandstorm
// powerPCBranchNotEqualFromOffset(from: 0x8, to: 0x34),
// 0x7e038378, // mr r3, r16
// 0x38800005, // li r4, rock type
// createBranchAndLinkFrom(offset: sandStart + 0x14, toOffset: checkHasType),
// 0x28030001, // cmpwi r0, 1
// powerPCBranchNotEqualFromOffset(from: 0x1c, to: 0x34),
// // spdef x 1.5
// 0x5643043e, // rlwinm r3, r18
// 0x38000064, // li r0, 100
// 0x1c630096, // mulli r3, r3, 150
// 0x7c0303d6, // divw r0, r3, r0
// 0x5412043e, // rlwinm r18, r0
// 0x7e058378, // mr r5, r16 (overwritten by branch)
// createBranchFrom(offset: sandStart + 0x38, toOffset: sandEnd)
// ])
//
// sheer force sand force amplifier tough claws adaptability technician solar power mega launcher
//let abilityBranch = 0x8022a66c - kDolToRAMOffsetDifference
//let abilityStart = 0x80220cec - kDolToRAMOffsetDifference
//let abilityEnd = abilityBranch + 0x4
//let checkHasType = 0x802054fc - kDolToRAMOffsetDifference
//let noBoost = 0xa8
//let boost33 = 0x94
//let noBoost50 = 0x120
//let boost50 = 0x10c
//let sandCheck = 0x80220ec0 - kDolToRAMOffsetDifference
//replaceASM(startOffset: abilityBranch, newASM: [createBranchFrom(offset: abilityBranch, toOffset: abilityStart)]
// + ASM(repeating: kNopInstruction, count: 63))
//replaceASM(startOffset: abilityStart, newASM: [
// 0x7e238b78, // mr r3, r17
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0x7C641B78, // mr r4, r3
// 0x7f63db78, // mr r3, r27
// 0x28030023, // cmpwi r3, sheer force
// powerPCBranchNotEqualFromOffset(from: 0x1c, to: 0x34),
// 0x7c832378, // mr r3, r4
// 0x88630005, // lbz r3, 0x0005 (r3) (get effect accuracy)
// 0x28030000, // cmpwi r3, 0
// powerPCBranchEqualFromOffset(from: 0x2c, to: noBoost),
// createBranchFrom(offset: 0x30, toOffset: boost33),
// kNopInstruction, //0x2803005c, // cmpwi r3, amplifier
// kNopInstruction, // powerPCBranchNotEqualFromOffset(from: 0x38, to: 0x50),
// kNopInstruction, // 0x7c832378, // mr r3, r4
// kNopInstruction, // 0x8863000b, // lbz r3, 0x000b (r3) (get sound flag)
// kNopInstruction, // 0x28030000, // cmpwi r3, 0
// kNopInstruction, // powerPCBranchEqualFromOffset(from: 0x48, to: noBoost),
// kNopInstruction, // createBranchFrom(offset: 0x4c, toOffset: boost33),
// 0x28030058, // cmpwi r3, tough claws
// powerPCBranchNotEqualFromOffset(from: 0x54, to: 0x6c),
// 0x7c832378, // mr r3, r4
// 0x88630006, // lbz r3, 0x0006 (r3) (get contact flag)
// 0x28030000, // cmpwi r3, 0
// powerPCBranchEqualFromOffset(from: 0x64, to: noBoost),
// createBranchFrom(offset: 0x68, toOffset: boost33),
// 0x2803005a, // cmpwi r3, sand force
// powerPCBranchEqualFromOffset(from: abilityStart + 0x70, to: sandCheck),
// 0x28030051, // cmpwi r3, adaptability
// powerPCBranchNotEqualFromOffset(from: 0x78, to: noBoost),
// 0x7f23cb78, // mr r3, r25
// 0x7C641B78, // mr r4, r3
// 0x7de37b78, // mr r3, r15
// createBranchAndLinkFrom(offset: abilityStart + 0x88, toOffset: checkHasType),
// 0x28030001, // cmpwi r3, 1
// powerPCBranchNotEqualFromOffset(from: 0x90, to: noBoost),
// // boost power 33%
// 0x56c3043e, // rlwinm r3, r22
// 0x38000064, // li r0, 100
// 0x1c630085, // mulli r3, 133
// 0x7c0303d6, // div r0, r3, r0
// 0x5416043e, // rlwinm r22, r0
// // no boost
// // 50% boosts
// 0x7f63db78, // mr r3, r27
// 0x28030042, // cmpwi r3, technician
// powerPCBranchNotEqualFromOffset(from: 0xb0, to: 0xc4),
// 0x56c3043e, // rlwinm r3, r22
// 0x2803003c, // cmpwi r3, 60
// powerPCBranchLessThanOrEqualFromOffset(from: 0xbc, to: boost50),
// createBranchFrom(offset: 0xc0, toOffset: noBoost50),
// 0x28030041, // cmpwi r3, mega launcher
// powerPCBranchNotEqualFromOffset(from: 0xc8, to: 0xe0),
// 0x7c832378, // mr r3, r4
// 0x8863000a, // lbz r3, 0x000a (r3) (get mirror move flag)
// 0x28030000, // cmpwi r3, 0
// powerPCBranchEqualFromOffset(from: 0xd8, to: noBoost50),
// createBranchFrom(offset: 0xdc, toOffset: boost50),
// 0x28030053, // cmpwi r3, solar power
// powerPCBranchNotEqualFromOffset(from: 0xe4, to: noBoost50),
// 0x80010010, // lwz r0, 0x0010(sp) (load weather)
// 0x28000001, // cmpwi r0, sun
// powerPCBranchNotEqualFromOffset(from: 0xf0, to: noBoost50),
// // sp.atk boost 50%
// 0x5663043e, // rlwinm r3, r19
// 0x38000064, // li r0, 100
// 0x1c630096, // mulli r3, 150
// 0x7c0303d6, // div r0, r3, r0
// 0x5413043e, // rlwinm r19, r0
// createBranchFrom(offset: 0x108, toOffset: noBoost50),
// // boost power 50%
// 0x56c3043e, // rlwinm r3, r22
// 0x38000064, // li r0, 100
// 0x1c630096, // mulli r3, 150
// 0x7c0303d6, // div r0, r3, r0
// 0x5416043e, // rlwinm r22, r0
// // no boost 50 - 0x120
// createBranchFrom(offset: abilityStart + 0x120, toOffset: abilityEnd)
// ])
//// forgot to check for sand with sand force
//replaceASM(startOffset: sandCheck, newASM: [
// 0x80010010, // lwz r0, 0x0010(sp) (load weather)
// 0x28000003, // cmpwi r0, sandstorm
// powerPCBranchNotEqualFromOffset(from: sandCheck + 0x8, to: abilityStart + noBoost),
// createBranchFrom(offset: sandCheck + 0xc, toOffset: abilityStart + boost33)
// ])
//
//// aerilate, pixilate, refrigerate, reckless
//let ability2Branch = 0x8022a670 - kDolToRAMOffsetDifference
//let ability2Start = 0x8022190c - kDolToRAMOffsetDifference
//let ability2End = ability2Branch + 0x4
//let noBoost20 = 0x88
//let boost20 = 0x74
//let reckless = 0x48
//replaceASM(startOffset: ability2Branch, newASM: [createBranchFrom(offset: ability2Branch, toOffset: ability2Start)])
//replaceASM(startOffset: ability2Start, newASM: [
// 0x7e238b78, // mr r3, r17
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0x7C641B78, // mr r4, r3
// 0x88630002, // lbz r3, 0x0002 (r3) (get move type)
// 0x28030000, // cmpwi r3, normal type
// powerPCBranchNotEqualFromOffset(from: 0x1c, to: reckless),
// 0x7c832378, // mr r3, r4
// 0x88630012, // lbz r3, 0x0012 (r3) (check if shadow move)
// powerPCBranchEqualFromOffset(from: 0x28, to: reckless),
// 0x7f63db78, // mr r3, r27
// 0x28030001, // cmpwi r3, aerilate
// powerPCBranchEqualFromOffset(from: 0x34, to: boost20),
// 0x28030044, // cmpwi r3, pixilate
// powerPCBranchEqualFromOffset(from: 0x3c, to: boost20),
// 0x28030056, // cmpwi r3, refrigerate
// powerPCBranchEqualFromOffset(from: 0x44, to: boost20),
// // reckless - 0x48
// 0x7f63db78, // mr r3, r27
// 0x28030063, // cmpwi r3, reckless
// powerPCBranchNotEqualFromOffset(from: 0x50, to: noBoost20),
// 0x7c832378, // mr r3, r4
// 0xa063001c, // lhz 0x001c(r3) (get move effect)
// // recoil move effects
// 0x2803002d, // cmpwi r3, 45
// powerPCBranchEqualFromOffset(from: 0x60, to: boost20),
// 0x28030030, // cmpwi r3, 48
// powerPCBranchEqualFromOffset(from: 0x68, to: boost20),
// 0x280300c6, // cmpwi r3, 198
// powerPCBranchNotEqualFromOffset(from: 0x70, to: noBoost20),
// // boost power 20%
// 0x56c3043e, // rlwinm r3, r22
// 0x38000064, // li r0, 100
// 0x1c630078, // mulli r3, 120
// 0x7c0303d6, // div r0, r3, r0
// 0x5416043e, // rlwinm r22, r0
// // no boost 20
// createBranchFrom(offset: ability2Start + 0x88, toOffset: ability2End)
// ])
//
//// multiscale fur coat pure heart
//let ability3Branch = 0x8022a674 - kDolToRAMOffsetDifference
//let ability3Start = 0x802227f4 - kDolToRAMOffsetDifference
//let ability3End = ability3Branch + 0x4
//let halfDamage = 0x7c
//let noHalfDamage = 0x90
//let checkFullHP = 0x80201d20 - kDolToRAMOffsetDifference
//replaceASM(startOffset: ability3Branch, newASM: [createBranchFrom(offset: ability3Branch, toOffset: ability3Start)])
//replaceASM(startOffset: ability3Start, newASM: [
// 0x7e238b78, // mr r3, r17
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0x7C641B78, // mr r4, r3
// 0x80010030, // lwz r0, 0x0030 (sp) (load defending ability)
// 0x28000050, // cmpwi r0, pure heart ability
// powerPCBranchNotEqualFromOffset(from: 0x1c, to: 0x48),
// 0x7c832378, // mr r3, r4
// 0x88630002, // lbz r3, 0x0002 (r3) (get move type)
// 0x28030011, // cmpwi r3, dark type
// powerPCBranchEqualFromOffset(from: 0x2c, to: halfDamage),
// 0x28030007, // cmpwi r3, ghost type
// powerPCBranchEqualFromOffset(from: 0x34, to: halfDamage),
// 0x7c832378, // mr r3, r4
// 0x88630012, // lbz r3, 0x0012 (r3) (check if shadow move)
// powerPCBranchEqualFromOffset(from: 0x40, to: halfDamage),
// createBranchFrom(offset: 0x44, toOffset: noHalfDamage),
// 0x2800005e, // cmpwi r0, fur coat
// powerPCBranchNotEqualFromOffset(from: 0x4c, to: 0x64),
// 0x7c832378, // mr r3, r4
// 0x88630006, // lbz r3, 0x0006 (r3) (get contact flag)
// 0x28030001, // cmpwi r3, 1
// powerPCBranchEqualFromOffset(from: 0x5c, to: halfDamage),
// createBranchFrom(offset: 0x60, toOffset: noHalfDamage),
// 0x28000052, // cmpwi r0, multiscale
// powerPCBranchNotEqualFromOffset(from: 0x68, to: noHalfDamage),
// 0x7e038378, // mr r3, r16
// createBranchAndLinkFrom(offset: ability3Start + 0x70, toOffset: checkFullHP),
// 0x28030000, // cmpwi r3, 0
// powerPCBranchEqualFromOffset(from: 0x78, to: noHalfDamage),
// // half damage - 0x7c
// 0x56c3043e, // rlwinm r3, r22
// 0x38000064, // li r0, 100
// 0x1c630032, // mulli r3, 50
// 0x7c0303d6, // div r0, r3, r0
// 0x5416043e, // rlwinm r22, r0
// // no half damage - 0x90
// createBranchFrom(offset: ability3Start + 0x90, toOffset: ability3End)
// ])
//
//// storm drain
//let stormBranch = 0x80218a70 - kDolToRAMOffsetDifference
//let stormStart = 0x8022288c - kDolToRAMOffsetDifference
//let rodFalseOffset = 0x80218b54 - kDolToRAMOffsetDifference
//let rodCheckOffset = 0x80218a84 - kDolToRAMOffsetDifference
//let rodFalse = 0x48
//let rodCheck = 0x4c
//let getFoeWithAbility = 0x801f38d8 - kDolToRAMOffsetDifference
//let changeTarget = 0x80218aa4 - kDolToRAMOffsetDifference
//replaceASM(startOffset: stormBranch, newASM: [createBranchFrom(offset: stormBranch, toOffset: stormStart)])
//replaceASM(startOffset: stormStart, newASM: [
// 0x281b000d, // cmpwi r27, electric type
// powerPCBranchNotEqualFromOffset(from: 0x4, to: 0x14),
// 0x281d001f, // cmpwi r29, lightning rod
// powerPCBranchEqualFromOffset(from: 0xc, to: rodFalse),
// createBranchFrom(offset: 0x10, toOffset: rodCheck),
// 0x281b000b, // cmpwi r27, water type
// powerPCBranchNotEqualFromOffset(from: 0x18, to: rodFalse),
// 0x281d0060, // cmpwi r29, storm drain
// powerPCBranchEqualFromOffset(from: 0x20, to: rodFalse),
// // check if either foe has storm drain
// 0x7fc7f378, // mr r7, r30
// 0x38600000, // li r3, 0
// 0x38800060, // li r4, storm drain
// 0x38a00001, // li r5, 1
// 0x38c00002, // li r6, 2
// createBranchAndLinkFrom(offset: stormStart + 0x38, toOffset: getFoeWithAbility),
// 0x28030000, // cmpwi r3, 0
// powerPCBranchEqualFromOffset(from: 0x40, to: rodFalse),
// // change target - 0x44
// createBranchFrom(offset: stormStart + 0x44, toOffset: changeTarget),
// // rod false - 0x48
// createBranchFrom(offset: stormStart + 0x48, toOffset: rodFalseOffset),
// // rod check - 0x4c
// createBranchFrom(offset: stormStart + 0x4c, toOffset: rodCheckOffset),
// ])
//
//// remove old choice band
//replaceASM(startOffset: 0x8022a3a0 - kDolToRAMOffsetDifference, newASM: ASM(repeating: kNopInstruction, count: 8))
//
//
//
//// ddpk fix up
//let noFlee = [3,4,5,6,7,14,22,73,74,75,76,77,78,79,80]
//let aggro = [15,28,30,37,40,44,62,89,]
//let rage = [11,18,31,32,46,38,43,55,82,100,106,107,]
//let happy = [1,29,27,46,81,83,103]
//for mon in XGDecks.DeckDarkPokemon.allPokemon.filter({ (p) -> Bool in
// return p.deckData.index != 0
//}) {
//
// let data = mon.deckData
// mon.shadowFleeValue = noFlee.contains(mon.deckData.index) ? 0 : 0x80
//
// let index = mon.deckData.index
// if index == 12 {
// mon.shadowFleeValue = 80
// }
//
// if index == 27 || index == 15 {
// mon.shadowFleeValue = 70
// }
//
// if index == 49 || index == 94 || index == 85 {
// mon.shadowFleeValue = 60
// }
//
// if index == 48 || index == 91 {
// mon.shadowFleeValue = 50
// }
//
// if index == 105 || index == 67 || index == 86 {
// mon.shadowFleeValue = 40
// }
//
// if index == 62 || index == 87 || index == 66 {
// mon.shadowFleeValue = 30
// }
//
// if index == 63 || index == 64 || index == 65 || index == 98 {
// mon.shadowFleeValue = 20
// }
//
// if index == 69 || index == 70 || index == 71 || index == 72 {
// mon.shadowFleeValue = 10
// }
//
// if aggro.contains(mon.deckData.index) {
// mon.shadowAggression = 1
// } else if rage.contains(mon.deckData.index) {
// mon.shadowAggression = 2
// } else if happy.contains(mon.deckData.index) {
// mon.shadowAggression = 5
// } else {
// mon.shadowAggression = mon.shadowCounter <= 2000 ? 5 : (mon.shadowCounter <= 4000 ? 4 : (mon.shadowCounter <= 6000 ? 3 : (mon.shadowCounter <= 10000 ? 2 : 1)))
// }
//
// mon.save()
//
// print(mon.deckData.index,mon.deckData.pokemon.name,mon.shadowAggression,mon.shadowFleeValue)
//}
//getStringSafelyWithID(id: 41308).duplicateWithString("[07]{01}Sun Stone").replace()
//item("moon shard").name.duplicateWithString("Moon Stone").replace()
//item("sun shard").name.duplicateWithString("Sun Stone").replace()
// allow shadow moves to use hm flag
//let shadow355Start = 0x8021e380 - kDolToRAMOffsetDifference
//let shadowBranchOffset355 = 0x80146eb4 - kDolToRAMOffsetDifference
//let shadow355End = 0x80146ebc - kDolToRAMOffsetDifference
//let shadowSkip = 0x80146ecc - kDolToRAMOffsetDifference
//
//replaceASM(startOffset: shadowBranchOffset355, newASM: [createBranchFrom(offset: shadowBranchOffset355, toOffset: shadow355Start)])
//
//replaceASM(startOffset: shadow355Start, newASM: [
//0x28030163, // cmpwi r3, 0x163
//powerPCBranchEqualFromOffset(from: 0x4, to: 0x24),
//// get move data pointer
//0x1c030038,
//0x806d89d4,
//0x7c630214,
//0x88630012, // lbz r3, 0x0012 (r3) (check if shadow move)
//0x28030001, // cmpwi r3, 1
//powerPCBranchEqualFromOffset(from: 0, to: 8),
//createBranchFrom(offset: shadow355Start + 0x20, toOffset: shadow355End),
//createBranchFrom(offset: shadow355Start + 0x24, toOffset: shadowSkip),
//])
//
//let shadow355Start2 = 0x8021db70 - kDolToRAMOffsetDifference
//let shadowBranchOffset3552 = 0x80146f28 - kDolToRAMOffsetDifference
//let shadow355End2 = 0x80146f30 - kDolToRAMOffsetDifference
//let shadowSkip2 = 0x80146f50 - kDolToRAMOffsetDifference
//replaceASM(startOffset: shadowBranchOffset3552, newASM: [createBranchFrom(offset: shadowBranchOffset3552, toOffset: shadow355Start2)])
//
//replaceASM(startOffset: shadow355Start2, newASM: [
//0x7C641B78, // mr r4, r3
//0x28030163, // cmpwi r3, 0x163
//powerPCBranchEqualFromOffset(from: 0x8, to: 0x2c),
//// get move data pointer
//0x1c030038,
//0x806d89d4,
//0x7c630214,
//0x88630012, // lbz r3, 0x0012 (r3) (check if shadow move)
//0x28030000, // cmpwi r3, 0
//0x7c832378, // mr r3, r4
//powerPCBranchEqualFromOffset(from: 0, to: 8),
//createBranchFrom(offset: shadow355Start2 + 0x28, toOffset: shadow355End2),
//createBranchFrom(offset: shadow355Start2 + 0x2c, toOffset: shadowSkip2),
//])
//
//replaceASM(startOffset: 0x80146f38 - kDolToRAMOffsetDifference, newASM: [
//0x7c601b78, // mr r0, r3
//0x3c6080b9, // lis r3, 0x80b9
//0x5404103a, // rlwinm r4, r0 (x4)
//0x3803c500, // subi r0, r3, 0x3b00
//])
// calc damage 2
//let calc_boosts = 0x80229fe4 - kDolToRAMOffsetDifference
//let boostOffsets = [0x802dcc14,0x8020daec]
//for offset in boostOffsets {
// replaceASM(startOffset: offset - kDolToRAMOffsetDifference, newASM: [createBranchAndLinkFrom(offset: offset - kDolToRAMOffsetDifference, toOffset: calc_boosts)])
//}
//// pixilate aerilate refrigerate
//let ateBranch = 0x802183dc - kDolToRAMOffsetDifference
//let ateStart = 0x8021dba0 - kDolToRAMOffsetDifference
//let ateEnd = 0x802183e0 - kDolToRAMOffsetDifference
//let storeType = 0x8013e064 - kDolToRAMOffsetDifference
//let getRoutine = 0x80148da8 - kDolToRAMOffsetDifference
//replaceASM(startOffset: ateBranch, newASM: [createBranchFrom(offset: ateBranch, toOffset: ateStart),])
//replaceASM(startOffset: ateStart, newASM: [
//0x7c791b78, // mr r3, r25
//// get move data pointer
//0x1c030038,
//0x806d89d4,
//0x7c630214,
//0x88630002, // lbz r3, 0x0002 (r3) (get move type)
//0x28030000, // cmpwi r3, 0
//powerPCBranchEqualFromOffset(from: 0x0, to: 0x8),
//createBranchFrom(offset: 0x1c, toOffset: 0x68),
//0x7fa3eb78, // mr r3, r29 (battle pokemon)
//createBranchAndLinkFrom(offset: ateStart + 0x24, toOffset: getRoutine),
//0x7c601b78, // mr r0, r3
//0x7fa3eb78, // mr r3, r29 (battle pokemon)
//0xa063080c, // lhz r3, 0x80c(r3) (get ability)
//0x28030056, // cmpwi r3, refrigerate
//powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
//0x3880000f, // li r4, 15
//createBranchFrom(offset: 0x40, toOffset: 0x60),
//0x28030044, // cmpwi r3, pixilate
//powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
//0x38800009, // li r4, 9
//createBranchFrom(offset: 0x50, toOffset: 0x60),
//0x28030001, // cmpwi r3, aerilate
//powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x10),
//0x38800002, // li r4, 2
//0x7C030378, // mr r3, r0
//createBranchAndLinkFrom(offset: ateStart + 0x64, toOffset: storeType),
//0x7f23cb78, // mr r3, r25
//createBranchFrom(offset: ateStart + 0x6c, toOffset: ateEnd)
//])
// type 9 dependencies
//let type9Offsets : [(offset: Int, lenght: Int)] = [(0x802c6ecc,3),(0x802c6f7c,2),(0x802c8a9c,2),(0x802c8e28,2),(0x802cb90c,2),(0x802cb9f8,2),(0x802d9228,2),(0x802d9324,2),]
//for (offset, length) in type9Offsets {
// removeASM(startOffset: offset - kDolToRAMOffsetDifference, length: length)
//}
//// calc damage boosts
//let calcOffsets = [0x802dcc14,0x8020daec,0x8021e224,0x802db020,0x8022713c,0x80216d0c]
//let calcDamageBoosts = 0x80229fe4 - kDolToRAMOffsetDifference
//let calcStart = 0x80220e10 - kDolToRAMOffsetDifference
//replaceASM(startOffset: calcStart, newASM: [
//0x9421fef0, // stwu sp, -0x0110 (sp)
//0x7c0802a6, // mflr r0
//0x90010114, // stw r0, 0x0114 (sp)
//0xbdc1004c, // stmw r14, 0x004c (sp)
//0xBDE10008, // 15
//0xBE01000c, // 16
//0xBE210010, // 17
//0xBE410014, // 18
//0xBE610018, // 19
//0xBE81001c, // 20
//0xBEA10020, // 21
//0xBEC10024, // 22
//0xBEE10028, // 23
//0xBF01002c, // 24
//0xBF210030, // 25
//0xBF410034, // 26
//0xBF610038, // 27
//0xBF81003c, // 28
//0xBFA10040, // 29
//0xBFC10044, // 30
//0xBFE10048, // 31
//createBranchAndLinkFrom(offset: calcStart + 0x54, toOffset: calcDamageBoosts),
//0xb9c1004c, // lmw r14, 0x004c (sp)
//0xB9E10008, // 15
//0xBa01000c, // 16
//0xBa210010, // 17
//0xBa410014, // 18
//0xBa610018, // 19
//0xBa81001c, // 20
//0xBaA10020, // 21
//0xBaC10024, // 22
//0xBaE10028, // 23
//0xBb01002c, // 24
//0xBb210030, // 25
//0xBb410034, // 26
//0xBb610038, // 27
//0xBb81003c, // 28
//0xBbA10040, // 29
//0xBbC10044, // 30
//0xBbE10048, // 31
//0x80010114, // lwz r0, 0x0114 (sp)
//0x7c0803a6, // mtlr r0
//0x38210110, // addi sp, sp, 272
//0x4e800020, // blr
//])
//
//
//for offset in calcOffsets {
// let o = offset - kDolToRAMOffsetDifference
// replaceASM(startOffset: o, newASM: [createBranchAndLinkFrom(offset: o, toOffset: calcStart)])
//}
////sturdy and focus sash
//let sashstart = 0x80216010 - kDolToRAMOffsetDifference
//replaceASM(startOffset: sashstart, newASM: [0x28170027,0x41820014,0x7fa3eb78,0x4bf3287d,0x28030005,0x40820024,0x7fa3eb78,0x4bfebcf5,0x5460063f,0x41820014,0x7fa3eb78,0x38800001,kNopInstruction])
//replaceASM(startOffset: 0x80216140 - kDolToRAMOffsetDifference, newASM: [0x388000c4]) // pretend pokemon is holding focus sash
//
//// sash/sturdy shedinja check
////
//let shedinjaBranch = 0x80216010 - kDolToRAMOffsetDifference
//let shedinjaTrueBranch = 0x80216048 - kDolToRAMOffsetDifference
//let shedinjaFalseBranch = 0x80216014 - kDolToRAMOffsetDifference
//let shedinjaCheckStart = 0x80152660 - kDolToRAMOffsetDifference
//
//let shedinjaCode : ASM = [
// 0x281f0001, // cmpwi r31, 1
// powerPCBranchEqualFromOffset(from: 0x4, to: 0x10),
// 0x28170027, // cmpwi r23,39 (code that we overwrote with the branch)
// createBranchFrom(offset: shedinjaCheckStart + 0xC, toOffset: shedinjaFalseBranch),
// createBranchFrom(offset: shedinjaCheckStart + 0x10, toOffset: shedinjaTrueBranch)
//]
//
//replaceASM(startOffset: shedinjaCheckStart, newASM: shedinjaCode)
//replaceASM(startOffset: shedinjaBranch, newASM: [createBranchFrom(offset: shedinjaBranch, toOffset: shedinjaCheckStart)])
//
//
//
//
//let tmList : [[Int]] = [
// [6,17,18,22,42,142,144,145,146,149,164,169,176,178,189,193,198,207,226,227,212,12,123,245,249,250,252,304,305,310,333,334,359,369,397,406,407,408,151,302], // tailwind
// [406,405,397,396,395,379,376,372,371,366,359,340,339,334,333,321,317,282,281,280,265,252,250,248,244,242,240,229,228,224,199,176,157,156,146,143,142,136,130,128,126,115,113,110,89,80,78,77,59,53,38,37,36,35,34,31,6,151,241,], // fire blast
// [9,18,25,26,35,36,38,65,73,81,82,101,113,120,121,122,124,125,128,134,135,136,137,147,148,149,150,151,154,171,175,176,180,181,196,233,242,243,249,250,251,264,317,319,337,338,347,358,359,372,392,393,394,400,406,407,408,409,410,53], // light pulse
// [408,407,406,397,369,359,334,310,305,302,300,252,250,249,227,226,176,169,151,149,146,145,144,142,42,18,12,6,302], // hurricane
// [3,9,15,31,33,34,42,44,45,53,61,62,69,70,71,72,73,89,94,110,117,151,154,157,169,193,195,207,211,213,221,224,229,230,233,248,252,265,279,285,287,300,299,306,307,317,321,334,340,344,345,362,363,366,372,376,378,405,410,339,340,301,302,303], // sludgewave
// [409,392,393,394,363,359,358,355,264,251,242,210,200,196,189,182,175,176,151,124,122,121,120,113,94,171,344,354,302,73,72,65,64,63,36,35,18], // dazzling gleam
// [15,37,38,53,151,157,169,185,413,197,198,200,215,228,229,252,264,286,287,299,300,317,322,345,355,376,378,18], // foul play
// [409,403,400,399,384,355,320,227,208,181,151,82,81,9,], // flash cannon
// [25,26,31,33,34,35,36,53,54,55,63,64,65,80,81,82,94,101,113,115,120,121,122,125,128,130,135,137,145,147,148,149,150,151,171,175,176,180,181,182,189,193,196,197,198,199,200,205,210,224,233,241,243,242,248,249,252,264,265,279,278,287,286,296,297,317,319,320,322,337,338,345,355,358,359,362,366,372,376,378,384,392,393,394,401,402,403,404,406,407,408,409,410,302,303], // thunder wave
// [9,31,33,34,35,36,53,54,55,61,62,72,73,79,80,90,91,99,104,105,112,113,115,116,117,120,121,122,124,128,130,131,134,138,139,140,141,143,144,147,148,149,150,151,159,160,171,175,176,183,184,186,194,195,199,211,215,217,221,224,226,230,233,241,242,245,248,249,252,264,265,283,284,285,297,310,314,317,327,329,330,331,343,347,359,355,358,362,366,372,376,378,380,384,319,402,404,406,407,408,410,362], // ice beam
// [410,405,392,393,394,378,376,362,340,339,322,321,280,281,282,265,250,244,228,229,200,157,156,155,151,150,146,136,126,110,94,78,77,65,64,63,59,38,37,6,122,303,], // will-o-wisp
// [25,26,53,57,59,76,77,78,81,82,101,105,115,125,128,135,143,145,150,151,156,157,171,180,181,210,217,241,243,252,265,287,286,304,305,317,337,338,355,366,372,376,380,384,400,403,406,409,], // wild charge
// [410,409,408,407,400,399,394,393,392,378,376,362,357,356,319,252,251,249,233,200,199,196,317,151,150,124,121,103,102,94,80,65,64,63,122,303], // trick room
// [9,54,55,61,62,72,73,80,99,116,117,120,121,130,134,138,139,140,141,151,159,160,171,183,184,186,194,195,199,211,224,226,230,245,252,283,284,285,297,310,314,327,329,330,331,404,], // scald
// [408,407,406,405,397,396,395,379,378,376,372,366,359,358,340,339,338,337,334,333,321,317,282,281,280,265,252,250,244,242,241,233,229,298,224,199,176,175,157,156,151,150,149,148,147,146,143,142,136,128,126,115,113,112,110,89,80,78,77,76,59,53,38,37,36,35,34,31,6], // flamethrower
// [3,6,9,25,26,27,28,31,33,34,51,53,54,55,57,59,61,62,68,76,77,78,75,81,82,104,105,106,107,110,112,113,115,125,126,127,128,130,142,141,143,149,150,151,153,154,157,156,159,160,181,183,184,185,205,208,210,212,214,217,221,224,227,231,232,237,241,242,244,246,247,248,251,252,265,283,284,285,286,287,299,300,306,307,314,317,319,320,321,322,330,331,332,333,334,336,337,338,339,340,343,345,347,355,356,357,359,366,369,372,376,378,379,380,384,391,395,396,397,398,399,400,401,402,403,404,405,406,409,410], // iron head
// [410,409,408,407,406,404,403,402,401,400,394,393,392,384,380,379,378,376,373,366,362,359,358,357,355,338,337,320,319,317,287,286,265,252,248,243,242,241,233,217,210,200,181,180,176,175,171,151,150,149,148,147,145,143,135,131,130,128,125,121,120,115,113,112,105,101,94,82,81,53,36,35,34,31,25,26,], // thunderbolt
// [90,91,124,131,144,151,221,264,343,347,402,], // freeze dry
// [410,405,401,400,391,379,378,376,372,366,363,362,345,340,339,334,331,330,321,319,317,307,306,300,299,287,286,285,284,283,279,278,277,265,252,249,241,232,231,230,229,228,224,221,217,215,214,213,211,207,200,195,193,185,169,157,154,153,151,143,141,140,139,138,136,128,127,117,115,114,112,110,105,94,91,89,76,73,72,71,70,69,62,61,53,51,45,44,42,38,34,31,28,27,15,3,9,301,302,303], // sludgebomb
// [3,38,44,45,53,65,64,63,78,89,102,103,114,151,150,153,154,156,157,182,189,193,196,228,229,233,241,251,252,277,278,279,297,299,300,306,307,317,321,334,344,345,363,369,376,392,393,394,405,407,408,410,], // energy ball
// [410,409,408,407,406,405,404,403,402,401,400,399,398,397,396,395,394,393,392,380,376,372,366,356,357,355,347,331,330,319,317,252,249,251,241,233,200,199,196,176,175,151,150,149,148,143,142,128,124,122,115,113,80,65,64,63,53,36,35,], // zen headbutt
// [15,123,127,151,193,205,212,333,334,301,302,303], // bug buzz
// [6,9,115,130,131,142,147,148,149,151,154,160,193,230,248,252,278,277,279,333,334,359,369,372,379,384,395,396,397,406,407,408,224], // dragon pulse
// [31,34,57,62,68,76,107,112,115,127,128,136,142,143,150,151,157,160,185,184,208,210,212,214,217,221,232,237,241,242,248,252,282,285,307,319,336,340,355,357,366,380,384,400,401,402,403,405,410], // super power
// [408,407,406,405,403,402,401,400,399,397,391,384,372,369,366,359,347,343,340,339,336,334,333,332,321,320,319,314,285,284,252,248,247,246,241,232,231,221,217,214,210,208,207,195,185,413,160,159,157,154,153,151,150,149,143,142,128,115,112,105,104,103,76,75,68,62,51,34,31,28,27,9,6,3], // earthquake
// [31,34,128,139,141,142,151,157,208,251,252,285,195,319,320,321,334,333,339,340,401,402,403,405,], // earth power
// [405,372,339,340,338,334,321,305,304,282,281,280,252,250,244,229,228,198,176,157,156,151,146,142,136,126,77,78,59,38,37,18,9,], // heat wave
// [9,31,33,34,35,36,53,54,55,61,62,72,73,80,90,91,99,113,115,116,117,120,121,124,128,130,131,134,138,139,140,141,143,144,151,159,160,171,175,176,183,184,186,194,195,199,211,215,221,224,226,230,233,241,242,245,248,249,252,264,283,284,285,287,297,310,314,317,327,329,330,331,343,347,366,372,376,380,402,404,407,408,410], // blizzard
// [25,26,31,33,34,50,51,53,57,71,94,107,115,151,185,413,198,210,215,228,229,237,252,286,287,299,300,317,322,344,345,355,362,363,366,376,378,379,380,301,302], // sucker punch
// [3,28,31,33,34,45,53,73,89,110,151,241,252,285,287,317,366,379,], // gunk shot
// [410,409,408,407,400,399,394,393,392,376,362,357,356,319,264,252,251,249,242,233,200,198,196,193,199,176,151,150,124,121,103,102,94,65,64,63,36,35,], // psyshock
// [37,38,42,53,63,64,65,89,91,94,115,124,128,143,150,151,169,193,196,197,198,199,200,210,215,217,224,228,229,233,241,243,248,252,265,264,287,286,300,299,317,319,322,327,330,331,345,347,357,362,366,372,376,378,379,380,392,393,394,400,410,303], // shadow ball
// [405,403,402,401,400,397,391,384,366,355,347,340,339,336,334,321,320,319,285,284,252,248,247,246,241,237,232,231,221,217,210,208,205,195,185,413,160,159,157,154,151,143,142,141,140,139,138,128,127,115,112,105,104,99,76,75,68,57,51,34,31,28,27,279], // rock slide
// [3,6,31,33,34,35,36,37,38,44,45,53,59,69,70,71,77,78,89,102,103,114,128,136,146,148,149,151,153,154,156,157,176,175,181,182,189,193,217,228,229,233,241,244,250,251,252,277,278,279,280,281,282,297,299,300,306,307,317,321,333,334,338,339,340,344,345,359,363,366,369,372,376,379,405,407,408,409,], // solar beam
// [410,409,405,403,402,401,394,393,384,380,378,372,366,357,356,336,319,317,307,282,281,252,251,242,241,237,232,224,217,215,214,210,200,181,176,160,157,154,151,150,143,136,128,127,126,125,124,122,115,112,107,106,94,89,68,65,64,63,62,18,279], // focus blast
// [15,27,28,53,99,123,127,141,151,169,212,277,278,279,300,327,380,391,301,302,303], // x-scissor
// [410,409,408,407,406,404,403,402,401,400,384,380,376,372,366,359,355,338,337,319,317,287,286,265,252,248,243,242,241,233,217,210,200,181,176,171,151,150,149,148,147,145,143,135,128,125,121,122,113,115,112,105,104,101,82,81,53,34,31,26,25,], // thunder
// [6,15,18,42,53,127,142,144,145,146,151,169,176,189,193,198,207,227,249,250,252,282,279,300,304,305,310,359,302,303], // acrobatics
// [408,407,404,406,343,331,330,329,327,314,310,297,285,284,283,252,249,245,230,226,224,211,199,195,194,186,183,184,171,160,159,151,149,148,147,139,138,134,131,130,121,120,117,116,80,73,72,62,61,54,55,9], // waterfall
// [6,31,34,28,53,112,115,142,149,151,157,159,160,248,252,277,278,279,317,334,359,369,376,380,384,395,396,397,405,406,407,408,], // dragon claw
// [], // toxic all except ditto
// [6,31,33,34,37,38,53,59,77,78,126,128,136,146,151,156,157,228,229,244,250,252,265,280,281,282,287,286,304,305,317,321,339,340,376,405,406,], // wild flare
// [410,400,391,380,379,378,376,366,363,357,356,355,336,327,317,307,300,299,297,287,285,284,279,278,277,252,241,237,229,217,215,214,212,211,210,207,185,184,182,181,169,159,160,157,151,150,143,141,139,128,127,126,125,123,115,114,112,107,105,99,94,89,76,78,73,72,75,71,70,69,68,65,62,61,59,57,55,53,51,45,44,42,31,33,34,28,15,3,301,302,303], // poison jab
// [391,380,376,366,355,345,331,330,327,317,300,299,287,286,279,278,252,229,228,217,215,212,198,169,42,160,159,156,157,151,150,143,142,141,127,123,115,94,53,51,28,27,15,6,301,302,303], // night slash
// [9,18,25,26,35,36,37,38,53,55,63,64,65,73,82,94,101,102,103,121,124,122,150,151,153,154,171,175,176,180,181,182,196,197,198,199,200,233,242,249,252,251,264,317,319,320,322,347,376,378,392,393,394,399,400,401,402,403,407,408,409,410,303,245,], // reflect
// [9,18,25,26,35,36,37,38,53,55,63,64,65,73,82,94,101,102,103,121,124,122,150,151,153,154,171,175,176,180,181,182,196,197,198,199,200,233,242,249,252,251,264,317,319,320,322,347,376,378,392,393,394,399,400,401,402,403,407,408,409,410,303,245,], // light screen
// [408,407,406,404,343,330,331,329,327,317,314,310,297,285,284,283,252,249,245,242,241,230,226,224,211,199,195,194,186,184,183,176,175,171,160,159,151,149,148,147,139,138,134,131,130,128,121,120,117,116,115,112,99,90,91,80,72,73,61,62,54,55,53,31,34,9], // surf
// [3,6,9,27,28,31,34,51,53,57,59,62,68,75,76,91,99,104,105,106,107,112,115,125,126,127,128,138,139,140,141,142,143,149,151,150,154,157,159,160,181,184,185,413,194,195,205,207,208,210,211,212,213,214,215,217,221,224,227,232,231,237,241,242,244,246,247,248,252,265,282,283,284,285,287,307,314,319,320,331,332,333,334,336,339,340,347,355,357,366,369,372,376,378,380,384,391,397,400,401,402,403,405,406,409,410], // stone edge
// [410,409,408,407,404,403,402,401,400,399,394,393,392,378,376,372,362,357,356,347,345,329,322,319,317,300,264,252,251,249,245,242,233,224,200,198,199,196,193,186,176,175,151,150,124,122,121,120,113,103,102,94,80,65,64,63,55,36,35,303], // psychic
// [9,31,33,34,37,38,42,53,63,64,65,59,91,94,110,115,124,126,128,150,151,169,176,193,197,198,200,215,224,228,229,233,243,248,252,265,264,286,287,299,300,317,319,322,327,330,331,345,347,357,362,366,372,376,378,379,380,394,410,303], // dark pulse
//
//]
//
//let tutList : [[Int]] = [
// [], // draco meteor
// [], // protect ------------------------------
// [], // substitute --------------------------
// [410,409,394,378,376,372,366,363,362,355,347,336,297,287,279,264,251,242,241,237,217,215,213,200,198,197,196,193,189,186,413,185,182,176,175,154,151,136,135,134,133,124,122,121,120,115,113,107,101,94,78,65,55,53,38,37,51,36,35,25,26,18,301,302,303], // encore
// [6,31,34,57,65,68,76,89,94,105,107,112,115,126,149,150,151,157,35,36,125,185,210,217,237,241,248,265,281,282,334,336,355,356,357,362,366,372,378,380,401,405,409,410,], // fire punch
// [31,34,57,65,68,76,89,94,105,107,112,115,125,149,150,151,25,26,35,36,126,6,157,181,185,210,217,237,241,248,265,279,297,336,355,356,357,362,366,372,378,380,384,400,403,409,410,],// thunder punch
// [31,34,55,57,62,65,68,76,89,94,105,107,112,115,124,149,150,151,159,160,35,36,184,183,185,210,215,217,237,241,248,284,285,297,336,355,356,357,362,366,372,378,380,384,400,402,409,410,], // ice punch
// [410,409,404,402,362,347,343,331,330,329,327,317,314,310,297,287,286,283,284,285,264,252,249,248,245,242,241,230,226,224,221,215,211,200,199,195,194,186,184,183,176,175,171,160,159,151,144,139,138,140,141,134,131,130,128,124,121,120,117,116,115,113,112,99,94,91,90,80,73,72,62,61,55,54,53,36,35,31,33,34,9], // icy wind
// [6,18,31,33,34,37,38,53,59,105,104,110,112,115,128,130,142,151,157,159,160,154,197,215,217,228,229,198,89,210,243,244,245,248,252,264,265,278,279,284,285,286,287,299,300,322,330,331,337,338,347,355,359,366,372,376,380,384,397,405,406,], // snarl
// [410,394,380,379,378,376,366,363,362,355,347,345,344,336,331,330,327,322,317,372,384,320,393,392,300,299,297,287,286,285,279,278,277,265,264,252,251,250,249,248,247,246,244,243,241,237,232,231,229,228,227,217,215,212,211,210,207,200,198,197,189,413,185,184,183,176,169,160,159,157,156,151,150,142,141,136,130,128,127,126,125,124,123,122,115,110,107,105,104,101,99,94,89,78,76,73,72,71,70,69,68,62,59,57,55,53,51,42,38,37,36,35,28,27,25,26,18,15,9,6,3,301,302,303], // taunt
// [9,15,18,25,26,31,33,34,35,36,53,54,55,61,62,72,73,80,81,82,90,91,99,101,113,114,115,116,117,120,121,125,128,130,131,134,135,138,139,140,141,145,147,148,149,151,159,160,171,175,176,181,180,183,184,186,189,194,195,198,199,200,210,217,224,226,227,230,233,241,242,243,245,249,252,251,277,278,279,283,284,285,286,287,297,304,305,310,314,317,322,327,329,330,331,337,338,355,358,359,362,366,372,376,378,380,384,391,392,393,394,403,404,406,407,408,409,410,303], // rain dance
// [3,6,15,18,31,33,34,35,36,37,38,44,45,53,59,69,70,71,77,78,102,103,110,113,114,115,126,128,136,142,146,147,148,149,151,153,154,156,157,175,176,182,189,183,196,198,200,210,213,217,228,229,233,241,242,244,250,251,265,277,278,279,280,281,282,286,287,299,300,304,305,306,307,317,321,322,339,340,355,358,359,362,363,366,369,372,376,378,379,380,384,392,393,394,403,405,406,407,408,409,410,303], // sunny day
//
//]
//
//for i in tmList {
// for t in i {
// if t > 415 {
// print("tm typo: ", i, t)
// }
// }
//}
//
//for i in tutList {
// for t in i {
// if t > 415 {
// print("tutor typo: ", i, t)
// }
// }
//}
//
//for tut in 0 ..< tutList.count {
// for i in 1 ..< kNumberOfPokemon {
// let mon = XGPokemonStats(index: i)
//
// if mon.index == 151 {
// mon.tutorMoves[tut] = true
// } else if (tut == 2) || (tut == 1) {
// mon.tutorMoves[tut] = (mon.index != 132) && (mon.index != 398)
// } else if tut == 0 {
// mon.tutorMoves[tut] = (mon.type1 == .dragon) || (mon.type2 == .dragon) || (mon.index == 151)
// } else {
// mon.tutorMoves[tut] = tutList[tut].contains(i)
// }
//
// mon.save()
// }
//}
//
//for tm in 0 ..< tmList.count {
// for i in 1 ..< kNumberOfPokemon {
// let mon = XGPokemonStats(index: i)
//
// if mon.index == 151 {
// mon.learnableTMs[tm] = true
// } else if tm == 40 {
// mon.learnableTMs[tm] = (mon.index != 132) && (mon.index != 398)
// } else {
// mon.learnableTMs[tm] = tmList[tm].contains(i)
// }
//
// mon.save()
// }
//}
//// aurora veil shadow veil
//let veilStart = 0x8021c7e0 - kDolToRAMOffsetDifference
//
//let moveRoutineSetPosition = 0x802236d4 - kDolToRAMOffsetDifference
//let moveRoutineUpdatePosition = 0x802236dc - kDolToRAMOffsetDifference
//
//let getPokemonPointer = 0x801efcac - kDolToRAMOffsetDifference
//let setFieldStatus = 0x801f8438 - kDolToRAMOffsetDifference
//let getCurrentMove = 0x80148d64 - kDolToRAMOffsetDifference
//let getWeather = 0x801f45d0 - kDolToRAMOffsetDifference
//
//replaceASM(startOffset: veilStart, newASM: [
// 0x7C7E1B78, // mr r30, r3
// createBranchAndLinkFrom(offset: veilStart + 0x4, toOffset: getCurrentMove),
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0x88630012, // lbz r3, 0x0012 (r3) (check if shadow move)
// 0x28030001, // cmpwi r3, 1
// powerPCBranchEqualFromOffset(from: 0x1c, to: 0x40),
// 0x38600000, // li r3, 0
// 0x38800001, // li r4, 1
// createBranchAndLinkFrom(offset: veilStart + 0x28, toOffset: getWeather),
// 0x28030004, // cmpwi r3, hail
// powerPCBranchEqualFromOffset(from: 0x30, to: 0x40),
// 0x807f0001, // lwz r3, 0x0001 (r31)
// createBranchAndLinkFrom(offset: veilStart + 0x38, toOffset: moveRoutineSetPosition),
// createBranchFrom(offset: 0x3c, toOffset: 0x70),
// 0x7FC4F378, // mr r4, r30
// 0x38600002, // li r3, 2
// createBranchAndLinkFrom(offset: veilStart + 0x48, toOffset: getPokemonPointer),
// 0x7C7E1B78, // mr r30, r3
// 0x38800049, // li r4, light screen
// 0x38a00000, // li r5, 0
// createBranchAndLinkFrom(offset: veilStart + 0x58, toOffset: setFieldStatus),
// 0x7fc3f378, // mr r3, r30
// 0x38800048, // li r4, reflect
// createBranchAndLinkFrom(offset: veilStart + 0x64, toOffset: setFieldStatus),
// 0x38600005, // li r3, 5
// createBranchAndLinkFrom(offset: veilStart + 0x6c, toOffset: moveRoutineUpdatePosition),
//])
//
//// new dpkm structure
//replaceASM(startOffset: 0x8028bac0 - kDolToRAMOffsetDifference, newASM: [0x8863001f, kNopInstruction])
//
//
//let mtbattleprizes : [XGItems] = [
// item("expert belt"),
// item("life orb"),
// item("focus sash"),
// item("leftovers"),
// item("king's rock"),
// item("scope lens"),
// item("choice band"),
// item("choice specs"),
// item("choice scarf"),
// item("assault vest"),
// item("eviolite"),
// item("bright powder"),
// item("quick claw"),
// XGTMs.tm(1).item,
// XGTMs.tm(27).item,
// XGTMs.tm(28).item,
// XGTMs.tm(37).item,
// XGTMs.tm(47).item
//]
//
//for i in 0 ..< mtbattleprizes.count {
// let offset = 1098 + (i * 2)
// let item = mtbattleprizes[i]
// replaceMartItemAtOffset(offset, withItem: item)
//}
//
//// 100% accuracy in weather
//
//let weatherBranch = 0x802180e0 - kDolToRAMOffsetDifference
//let weatherStart = 0x802296E4 - kDolToRAMOffsetDifference
//
//let accurate = 0x802180f8 - kDolToRAMOffsetDifference
//let inaccurate = 0x80218100 - kDolToRAMOffsetDifference
//
//let rainCheck = 0x1c
//let hailCheck = 0x30
//let skyCheck = 0x3c
//
//let aBranch = 0x48
//let iBranch = 0x44
//
//replaceASM(startOffset: weatherBranch, newASM: [createBranchFrom(offset: weatherBranch, toOffset: weatherStart)])
//replaceASM(startOffset: weatherStart, newASM: [
// 0x28030002, // cmpwi r3, rain
// powerPCBranchEqualFromOffset(from: 0x4, to: rainCheck),
// 0x28030004, // cmpwi r3, hail
// powerPCBranchEqualFromOffset(from: 0xc, to: hailCheck),
// 0x28030005, // cmpwi r3, shadow sky
// powerPCBranchEqualFromOffset(from: 0x14, to: skyCheck),
// createBranchFrom(offset: weatherStart + 0x18, toOffset: inaccurate),
// // rain check 0x1c
// 0x281f0057, // cmpwi r31, thunder
// powerPCBranchEqualFromOffset(from: 0x20, to: aBranch),
// 0x281f00ef, // cmpwi r31, hurricane
// powerPCBranchEqualFromOffset(from: 0x28, to: aBranch),
// createBranchFrom(offset: 0x2c, toOffset: iBranch),
// // hail check 0x30
// 0x281f003b, // cmpwi r31, blizzard
// powerPCBranchEqualFromOffset(from: 0x34, to: aBranch),
// createBranchFrom(offset: 0x38, toOffset: iBranch),
// // shadow sky check 0x3c
// 0x281f016a, // cmpwi r31, shadow storm
// powerPCBranchEqualFromOffset(from: 0x40, to: aBranch),
// //inaccurate branch 0x44
// createBranchFrom(offset: weatherStart + iBranch, toOffset: inaccurate),
// // accurate branch 0x48
// createBranchFrom(offset: weatherStart + aBranch, toOffset: accurate)
//])
//replaceASM(startOffset: 0x21502c, newASM: [kNopInstruction]) // start offset is from dol not ram
//
//
//getStringSafelyWithID(id: 36811).duplicateWithString("[Speaker]: I'd like you to have these as[New Line]mementos of our battle.[Dialogue End]").replace()
//getStringSafelyWithID(id: 36816).duplicateWithString("[Player F] received Rare Candies and TM32.[Dialogue End]").replace()
//
//
//let null = XGDeckPokemon.dpkm(0, .DeckStory).data
//null.level = 0
//null.save()
//
//switchNextPokemonAtEndOfTurn()
//
//// burn residual damage to 1/16
//replaceASM(startOffset: 0x80227e64 - kDolToRAMOffsetDifference, newASM: [0x38800010])
//
//
//// filter tinted lens expert belt
//
//// tinted lens
//let oldLensBranch = 0x80216ac4 - kDolToRAMOffsetDifference
//
//let lens2Start = 0x8021c2f0 - kDolToRAMOffsetDifference
//replaceASM(startOffset: lens2Start, newASM: [
//
// 0x9421ffe0, // stwu sp, -0x0020 (sp)
// 0x7c0802a6, // mflr r0
// 0x90010024, // stw r0, 0x0024 (sp)
// 0xbfa10014, // stmw r29, 0x0014 (sp)
// 0x83B2009C, // lwz r29, 0x009C (r18)
//
// 0x38600011, // li r3, 17 (attacking pokemon)
// 0x38800000, // li r4, 0
// createBranchAndLinkFrom(offset: lens2Start + 0x1c, toOffset: 0x801efcac - kDolToRAMOffsetDifference), // get pokemon pointer
// 0xa063080c, // lhz r3, 0x80c(r3)
// 0x2803006a, // cmpwi r3, tinted lens
// powerPCBranchNotEqualFromOffset(from: 0x28, to: 0x38), // bne lens end
//
// 0x1C7D0014, // mulli r3, r29, 20
// 0x3800000a, // li r0, 10
// 0x7FA303D7, // divw r29, r3, r0
//
// 0x93B2009C, // stw r29, 0x009C (r18)
// 0xbba10014, // lmw r29, 0x0014 (sp)
// 0x80010024, // lwz r0, 0x0024 (sp)
// 0x7c0803a6, // mtlr r0
// 0x38210020, // addi sp, sp, 32
// 0x4e800020, // blr
//])
//
//// old filter
//let oldFilterBranch = 0x80216ad4 - kDolToRAMOffsetDifference
//revertDolInstructionAtOffsets(offsets: [oldFilterBranch, oldLensBranch])
//
//// filter + expert belt
//let filter2Start = 0x802295F8 - kDolToRAMOffsetDifference
//
//let getItem = 0x8020384c - kDolToRAMOffsetDifference
//
//replaceASM(startOffset: filter2Start, newASM: [
//
// 0x9421ffe0, // stwu sp, -0x0020 (sp)
// 0x7c0802a6, // mflr r0
// 0x90010024, // stw r0, 0x0024 (sp)
// 0xbfa10014, // stmw r29, 0x0014 (sp)
// 0x83B2009C, // lwz r29, 0x009C (r18)
//
// 0x38600012, // li r3, 18 (defending pokemon)
// 0x38800000, // li r4, 0
// createBranchAndLinkFrom(offset: filter2Start + 0x1c, toOffset: 0x801efcac - kDolToRAMOffsetDifference), // get pokemon pointer
// 0xa063080c, // lhz r3, 0x80c(r3) (get ability)
// 0x28030065, // cmpwi r3, filter
// powerPCBranchNotEqualFromOffset(from: 0x28, to: 0x38),
//
// 0x1C7D004B, // mulli r3, r29, 75
// 0x38000064, // li r0, 100
// 0x7FA303D7, // divw r29, r3, r0
//
// 0x38600011, //li r3, 17 (attacking pokemon)
// 0x38800000, // li r4, 0
// createBranchAndLinkFrom(offset: filter2Start + 0x40, toOffset: 0x801efcac - kDolToRAMOffsetDifference), // get pokemon pointer
// createBranchAndLinkFrom(offset: filter2Start + 0x44, toOffset: getItem), // get item's hold item id
// 0x28030047, // cmpwi r3, 71 (compare with expert belt)
// powerPCBranchNotEqualFromOffset(from: 0x4c, to: 0x5c),
//
// 0x1C7D0078, // mulli r3, r29, 120
// 0x38000064, // li r0, 100
// 0x7FA303D7, // divw r29, r3, r0
//
// 0x93B2009C, // stw r29, 0x009C (r18)
// 0xbba10014, // lmw r29, 0x0014 (sp)
// 0x80010024, // lwz r0, 0x0024 (sp)
// 0x7c0803a6, // mtlr r0
// 0x38210020, // addi sp, sp, 32
// 0x4e800020, // blr
//])
//let getEffectiveness = 0x8022271c - kDolToRAMOffsetDifference
//
//let effectiveEnd = 0x78
//let filterCheckStart = 0x58
//let tintedCheckStart = 0x44
//let filterStart = 0x6c
//let tintedStart = 0x74
//
//let effectiveStart = 0x80229578 - kDolToRAMOffsetDifference
//let effectiveBranch = 0x80216840 - kDolToRAMOffsetDifference
//let effectiveReturn = effectiveBranch + 0x4
//
//replaceASM(startOffset: effectiveBranch, newASM: [createBranchFrom(offset: effectiveBranch, toOffset: effectiveStart)])
//replaceASM(startOffset: effectiveStart, newASM: [
// 0x7e83a378, // mr r3, r20 (move type)
// 0x7f24cb78, // mr r4, r25 (target type 1)
// createBranchAndLinkFrom(offset: effectiveStart + 0x8, toOffset: getEffectiveness),
// 0x28030043, // cmpwi r3, no effect
// powerPCBranchEqualFromOffset(from: 0x10, to: effectiveEnd),
// 0x28030041, // cmpwi r3, super effective
// powerPCBranchEqualFromOffset(from: 0x18, to: filterCheckStart),
// 0x28030042, // cmpwi r3, not very effective
// powerPCBranchEqualFromOffset(from: 0x20, to: tintedCheckStart),
// // neutral 0x24
// 0x7e83a378, // mr r3, r20 (move type)
// 0x7f04c378, // mr r4, r24 (target type 2)
// createBranchAndLinkFrom(offset: effectiveStart + 0x2c, toOffset: getEffectiveness),
// 0x28030041, // cmpwi r3, super effective
// powerPCBranchEqualFromOffset(from: 0x34, to: filterStart),
// 0x28030042, // cmpwi r3, not very effective
// powerPCBranchEqualFromOffset(from: 0x3c, to: tintedStart),
// createBranchFrom(offset: 0x40, toOffset: effectiveEnd),
// // tinted check start 0x44
// 0x7e83a378, // mr r3, r20 (move type)
// 0x7f04c378, // mr r4, r24 (target type 2)
// createBranchAndLinkFrom(offset: effectiveStart + 0x4c, toOffset: getEffectiveness),
// 0x28030041, // cmpwi r3, super effective
// powerPCBranchNotEqualFromOffset(from: 0x54, to: tintedStart),
// // filter check start 0x58
// 0x7e83a378, // mr r3, r20 (move type)
// 0x7f04c378, // mr r4, r24 (target type 2)
// createBranchAndLinkFrom(offset: effectiveStart + 0x60, toOffset: getEffectiveness),
// 0x28030042, // cmpwi r3, not very effective
// powerPCBranchEqualFromOffset(from: 0x68, to: effectiveEnd),
// // filter expert belt start 0x6c
// createBranchAndLinkFrom(offset: effectiveStart + 0x6c, toOffset: filter2Start),
// createBranchFrom(offset: 0x70, toOffset: effectiveEnd),
// // tinted lens start 0x74
// createBranchAndLinkFrom(offset: effectiveStart + 0x74, toOffset: lens2Start),
// // effectiveEnd 0x78
// 0x5723043e, // rlwinm r3, r25 overwritten code
// createBranchFrom(offset: effectiveStart + 0x7c, toOffset: effectiveReturn),
//])
//
//
//// expert belt tinted lens filter on shadow moves
//let shadowTintedBranch = 0x216dd0
//let shadowFilterBranch = 0x216e00
//let shadowTintedStart = 0xB99FA8
//let shadowFilterStart = 0xB99FC4
//XGAssembly.replaceASM(startOffset: shadowTintedBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: shadowTintedBranch, toOffset: shadowTintedStart)])
//XGAssembly.replaceASM(startOffset: shadowFilterBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: shadowFilterBranch, toOffset: shadowFilterStart)])
//XGAssembly.replaceRELASM(startOffset: shadowTintedStart - kRELtoRAMOffsetDifference, newASM: [
// 0x7f83e378, // mr r3, r28 (attacking pokemon)
// 0xa063080c, // lhz r3, 0x80c(r3) (get ability)
// 0x2803006a, // cmpwi r3, tinted lens
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8), // bne lens end
// 0x5739083c, // rlwinm r25, r25, 1, 0, 30 (7fffffff) (25 << 1)
// 0x7fe3fb78, // mr r3, r31 (overwritten code)
// XGAssembly.createBranchFrom(offset: shadowTintedStart + 0x18, toOffset: shadowTintedBranch + 0x4)
//])
//let getItem2 = 0x20384c
//XGAssembly.replaceRELASM(startOffset: shadowFilterStart - kRELtoRAMOffsetDifference, newASM: [
//
// 0x7f63db78, // mr r3, r27 (defending pokemon)
// 0xa063080c, // lhz r3, 0x80c(r3) (get ability)
// 0x28030065, // cmpwi r3, filter
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x10), // bne filter end
// 0x1cb9004B, // mulli r5, r25, 75
// 0x38000064, // li r0, 100
// 0x7f2503d6, // divw r25, r5, r0
//
// 0x7f83e378, // mr r3, r28 (attacking pokemon)
// XGAssembly.createBranchAndLinkFrom(offset: shadowFilterStart + 0x20, toOffset: getItem2), // get item's hold item id
// 0x28030047, // cmpwi r3, 71 (compare with expert belt)
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x10), // bne expert belt end
// 0x1cb90078, // mulli r5, r25, 120
// 0x38000064, // li r0, 100
// 0x7f2503d6, // divw r25, r5, r0
//
// 0x7fe3fb78, // mr r3, r31 (overwritten code)
// XGAssembly.createBranchFrom(offset: shadowFilterStart + 0x3c, toOffset: shadowFilterBranch + 0x4),
// // filler
// kNopInstruction,
// kNopInstruction,
// kNopInstruction,
// kNopInstruction,
// kNopInstruction,
//])
//
//// expert belt fix
//let filter2Start = 0x2295F8 - kDolToRAMOffsetDifference
//let getItem = 0x20384c - kDolToRAMOffsetDifference
//XGAssembly.replaceASM(startOffset: filter2Start, newASM: [
//
// 0x9421ffe0, // stwu sp, -0x0020 (sp)
// 0x7c0802a6, // mflr r0
// 0x90010024, // stw r0, 0x0024 (sp)
// 0xbfa10014, // stmw r29, 0x0014 (sp)
// 0x83B2009C, // lwz r29, 0x009C (r18)
//
// 0x38600012, // li r3, 18 (defending pokemon)
// 0x38800000, // li r4, 0
// XGAssembly.createBranchAndLinkFrom(offset: filter2Start + 0x1c, toOffset: 0x1efcac - kDolToRAMOffsetDifference), // get pokemon pointer
// 0xa063080c, // lhz r3, 0x80c(r3) (get ability)
// 0x28030065, // cmpwi r3, filter
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x28, to: 0x38),
//
// 0x1C7D004B, // mulli r3, r29, 75
// 0x38000064, // li r0, 100
// 0x7FA303D7, // divw r29, r3, r0
//
// 0x38600011, //li r3, 17 (attacking pokemon)
// 0x38800000, // li r4, 0
// XGAssembly.createBranchAndLinkFrom(offset: filter2Start + 0x40, toOffset: 0x1efcac - kDolToRAMOffsetDifference), // get pokemon pointer
// XGAssembly.createBranchAndLinkFrom(offset: filter2Start + 0x44, toOffset: getItem), // get item's hold item id
// 0x28030047, // cmpwi r3, 71 (compare with expert belt)
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x4c, to: 0x5c),
//
// 0x1C7D0078, // mulli r3, r29, 120
// 0x38000064, // li r0, 100
// 0x7FA303D7, // divw r29, r3, r0
//
// 0x93B2009C, // stw r29, 0x009C (r18)
// 0xbba10014, // lmw r29, 0x0014 (sp)
// 0x80010024, // lwz r0, 0x0024 (sp)
// 0x7c0803a6, // mtlr r0
// 0x38210020, // addi sp, sp, 32
// 0x4e800020, // blr
//])
//
//
//// timer ball update to closer to gen V+ mechanics (maxes in 15 turns)
//XGAssembly.replaceASM(startOffset: 0x219444 - kDolToRAMOffsetDifference, newASM: [
// 0x54630C3C, // r3 = r3 * 2
// 0x3B83000A, // r28 = r3 + 10
//])
//
//renameZaprong(newName: "BonBon")
//
//// shadow terrain
//let terrainBranch = 0x8022a60c - kDolToRAMOffsetDifference
//let terrainStart = 0x8021e9ec - kDolToRAMOffsetDifference
//let terrainTrue = 0x8022a618 - kDolToRAMOffsetDifference
//let terrainFalse = 0x8022a63c - kDolToRAMOffsetDifference
//let checkShadowMove = 0x8013d03c - kDolToRAMOffsetDifference
//replaceASM(startOffset: terrainBranch, newASM: [
// 0x7e238b78, // mr r3, r17
// createBranchAndLinkFrom(offset: terrainBranch + 0x4, toOffset: checkShadowMove),
// createBranchFrom(offset: terrainBranch + 0x8, toOffset: terrainStart),
// ])
//replaceASM(startOffset: terrainStart, newASM: [
// 0x28030001, // cmpwi r3, 1 check shadow move
// powerPCBranchEqualFromOffset(from: 0x0, to: 0x8),
// createBranchFrom(offset: terrainStart + 0x8, toOffset: terrainTrue),
// createBranchFrom(offset: terrainStart + 0xc, toOffset: terrainFalse)
// ])
//
//
//let lastShadow = XGDeckPokemon.ddpk(108).data
//lastShadow.ShadowDataInUse = false
//lastShadow.shadowAggression = 0
//lastShadow.shadowFleeValue = 0
//lastShadow.save()
//
//let nosepass = XGDeckPokemon.ddpk(89).data
//nosepass.shadowAggression = 5
//nosepass.save()
//let gen4Evos = ["murkrow","electabuzz","magmar","gligar","sneasel","piloswine","yanma","rhydon","roselia","dusclops","aipom","magneton",
// "misdreavus","nosepass","porygon2","tangela","togetic","lickitung"]
//
//for mon in gen4Evos {
// let stats = pokemon(mon).stats
//// stats.evolutions[0] = XGEvolution(evolutionMethod: XGEvolutionMethods.Gen4.rawValue, condition: 0, evolvedForm: 0)
// print(stats.evolutions[0].toInts())
//// stats.save()
//}
//// items
//let checkShadowPokemon = 0x80149014 - kDolToRAMOffsetDifference
//let itemBranch = 0x8022a678 - kDolToRAMOffsetDifference
//let itemStart = 0x802219e0 - kDolToRAMOffsetDifference
//let itemEnd = itemBranch + 0x4
//let itemBuff = 0x68
//let itemNerf = 0x104
//let defenderStart = 0x80
//let defenderEnd = 0x118
//let getStats = 0x80146078 - kDolToRAMOffsetDifference
//let getEvolutionMethod = 0x80145c18 - kDolToRAMOffsetDifference
//let getItemParameter = 0x80203828 - kDolToRAMOffsetDifference
//replaceASM(startOffset: itemBranch, newASM: [createBranchFrom(offset: itemBranch, toOffset: itemStart)])
//replaceASM(startOffset: itemStart, newASM: [
// // attacker items
// 0x281c0046, // cmpwi r28, pixie plate
// powerPCBranchNotEqualFromOffset(from: 0x4, to: 0x10),
// 0x28190009, // cmpwi r25, fairy type
// powerPCBranchEqualFromOffset(from: 0xc, to: itemBuff),
// 0x281c004b, // cmpwi r28, life orb
// powerPCBranchEqualFromOffset(from: 0x14, to: itemBuff),
// 0x281c0048, // cmpwi r28, aura booster
// powerPCBranchNotEqualFromOffset(from: 0x1c, to: 0x38),
// 0x7de37b78, // mr r3, r15
// 0x80630000, // lw r3, 0 (r3)
// 0x38630004, // addi r3, 4
// createBranchAndLinkFrom(offset: itemStart + 0x2c, toOffset: checkShadowPokemon),
// 0x28030001, // cmpwi r3, 1
// powerPCBranchEqualFromOffset(from: 0x34, to: itemBuff),
// // get raw item index
// 0x7de37b78, // mr r3, r15
// 0x80630000, // lw r3, 0 (r3)
// 0x38630004, // addi r3, 4
// 0xa0630002, // lhz r3, 0x0002 (r3) // get item index
// 0x280300ba, // cmpwi r3, choice band
// powerPCBranchNotEqualFromOffset(from: 0x4c, to: 0x58),
// 0x28180001, // cmpwi r24, physical
// powerPCBranchEqualFromOffset(from: 0x54, to: itemBuff),
// 0x28030035, // cmpwi r3, choice specs
// powerPCBranchNotEqualFromOffset(from: 0x5c, to: defenderStart),
// 0x28180002, // cmpwi r24, special
// powerPCBranchNotEqualFromOffset(from: 0x64, to: defenderStart),
// // item buff - 0x68
// 0x80810020, // lwz r4, 0x0020 (sp)
// 0x56c6043e, // rlwinm r6, r22
// 0x7cc621d6, // mullw r6, r6, r4
// 0x38800064, // li r4, 100
// 0x7c8623d6, // divw r4, r6, r4
// 0x5496043E, // rlwinm r22, r4
// // defender start - 0x80
// 0x281e004c, // cmpwi r30, assault vest
// powerPCBranchNotEqualFromOffset(from: 0x84, to: 0x94),
// 0x1E520096, // mulli r18, r18, 150
// 0x38000064, // li r0, 100
// 0x7E5203D6, // divw r18, r18, r0
// 0x281e0049, // cmpwi r30, aura filter
// powerPCBranchNotEqualFromOffset(from: 0x98, to: 0xb4),
// 0x7de37b78, // mr r3, r15
// // 0xa0
// 0x80630000, // lw r3, 0 (r3)
// 0x38630004, // addi r3, 4
// createBranchAndLinkFrom(offset: itemStart + 0xa8, toOffset: checkShadowPokemon),
// 0x28030001, // cmpwi r3, 1
// powerPCBranchEqualFromOffset(from: 0xb0, to: itemNerf),
// 0x281e004a, // cmpwi r30, aura armour
// powerPCBranchNotEqualFromOffset(from: 0xb8, to: 0xdc),
// 0x28180001, // cmpwi r24, physical
// powerPCBranchNotEqualFromOffset(from: 0xc0, to: 0xdc),
// 0x7e038378, // mr r3, r16
// 0x80630000, // lw r3, 0 (r3)
// 0x38630004, // addi r3, 4
// createBranchAndLinkFrom(offset: itemStart + 0xd0, toOffset: checkShadowPokemon),
// 0x28030001, // cmpwi r3, 1
// powerPCBranchEqualFromOffset(from: 0xd8, to: itemNerf),
// 0x281e0043, // cmpwi r30, eviolite
// powerPCBranchNotEqualFromOffset(from: 0xe0, to: defenderEnd),
// 0x7e038378, // mr r3, r16
// 0x80630000, // lw r3, 0 (r3)
// 0xa0630004, // lhz r3, 0x0004 (r3) // get species
// createBranchAndLinkFrom(offset: itemStart + 0xf0, toOffset: getStats),
// 0x38800000, // li r4, 0
// createBranchAndLinkFrom(offset: itemStart + 0xf8, toOffset: getEvolutionMethod),
// 0x28030000, // cmpwi r3, 0
// powerPCBranchEqualFromOffset(from: 0x100, to: defenderEnd),
// // item nerf - 0x104
// 0x7e038378, // mr r3, r16
// createBranchAndLinkFrom(offset: itemStart + 0x108, toOffset: getItemParameter),
// 0x7ED619D6, // mullw r22, r22, r3
// 0x38800064, // li r4, 100
// 0x7ED623D6, // divw r22, r22, r4
// // defender end - 0x118
// createBranchFrom(offset: itemStart + 0x118, toOffset: itemEnd)
//])
//// aura animation
//let auraAnimation = 0x80205c9c - kDolToRAMOffsetDifference
//
//let auraStart = 0x80229734 - kDolToRAMOffsetDifference
//
//let auraBranch = 0x80215e08 - kDolToRAMOffsetDifference
//
//let checkStatus = 0x802025f0 - kDolToRAMOffsetDifference
//let getCurrentMove = 0x80148d64 - kDolToRAMOffsetDifference
//
//replaceASM(startOffset: auraBranch, newASM: [createBranchAndLinkFrom(offset: auraBranch, toOffset: auraStart)])
//replaceASM(startOffset: auraStart, newASM: [
//
// 0x9421ffe0, // stwu sp, -0x0020 (sp)
// 0x7c0802a6, // mflr r0
// 0x90010024, // stw r0, 0x0024 (sp)
// 0xbfa10014, // stmw r29, 0x0014 (sp)
//
// 0x38600011, // li r3, 17 (attacking pokemon)
// 0x38800000, // li r4, 0
// createBranchAndLinkFrom(offset: auraStart + 0x18, toOffset: 0x801efcac - kDolToRAMOffsetDifference), // get pokemon pointer
// 0x7C7D1B78, // mr r29, r3
//
// 0x3880003e, // li r4, reverse mode
// createBranchAndLinkFrom(offset: auraStart + 0x24, toOffset: checkStatus),
// 0x28030001, // cmpwi r3, 1
// powerPCBranchNotEqualFromOffset(from: 0x2c, to: 0x5c),
//
// 0x7fa3eb78, // mr r3, r29
// 0x38800001,
// 0x38a00001,
// 0x38c00000,
// createBranchAndLinkFrom(offset: auraStart + 0x40, toOffset: auraAnimation),
//
// 0x7fa3eb78, // mr r3, r29
// 0x38800001,
// 0x38a00001,
// 0x38c00001,
// createBranchAndLinkFrom(offset: auraStart + 0x54, toOffset: auraAnimation),
// createBranchFrom(offset: 0x58, toOffset: 0xa4),
//
// 0x7fa3eb78, // mr r3, r29
// createBranchAndLinkFrom(offset: auraStart + 0x60, toOffset: getCurrentMove),
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0x88630012, // lbz r3, 0x0012 (r3) (check if shadow move)
// 0x28030001, // cmpwi r3, 1
// powerPCBranchNotEqualFromOffset(from: 0x78, to: 0xa4),
//
// 0x7fa3eb78, // mr r3, r29
// 0x38800000,
// 0x38a00000,
// 0x38c00000,
// createBranchAndLinkFrom(offset: auraStart + 0x8c, toOffset: auraAnimation),
//
// 0x7fa3eb78, // mr r3, r29
// 0x38800000,
// 0x38a00000,
// 0x38c00001,
// createBranchAndLinkFrom(offset: auraStart + 0xa0, toOffset: auraAnimation),
//
// 0xbba10014, // lmw r29, 0x0014 (sp)
// 0x80010024, // lwz r0, 0x0024 (sp)
// 0x7c0803a6, // mtlr r0
// 0x38210020, // addi sp, sp, 32
//
// 0x800dbb18, // lwz r0, -0x44E8 (r13) overwritten code
//
// 0x4e800020, // blr
//])
//let suicune = XGISO().dataForFile(filename: "pkx_suikun.fsys")!
//let entei = XGISO().dataForFile(filename: "pkx_entei.fsys")!
//let raikou = XGISO().dataForFile(filename: "pkx_raikou.fsys")!
//
//let shedinja = XGISO().dataForFile(filename: "pkx_nukenin.fsys")!
//
//let models = [suicune,entei,raikou, shedinja]
//
//for model in models {
// model.save()
// let fsys = model.file.fsysData
// let pkx = fsys.decompressedDataForFileWithIndex(index: 0)!
// pkx.save()
// let file = pkx.file.data
// let ow = XGUtility.exportDatFromPKX(pkx: file)
// ow.file = .nameAndFolder(pkx.file.fileName + " OW", .Documents)
// ow.save()
//
//}
//let shade = XGFiles.nameAndFolder("diveball_open.fdat", .TextureImporter).compress()
//XGFiles.fsys("wzx_diveball_open.fsys").fsysData.replaceFile(file: shade)
//XGUtility.compileForRelease(XG: true)
//let faces = XGFiles.fsys("poke_face.fsys").fsysData
//let marowak = XGFiles.nameAndFolder("face048.fdat", .Output).compress()
//let ninetails = XGFiles.nameAndFolder("face162.fdat", .Output).compress()
//faces.replaceFile(file: marowak)
//faces.replaceFile(file: ninetails)
//
//
//let wak = XGPokemon.pokemon(265).stats
//let tails = XGPokemon.pokemon(264).stats
//wak.faceIndex = 48
//tails.faceIndex = 162
//wak.save()
//tails.save()
//
// XGFiles.fsys("field_common.fsys").fsysData.shiftAndReplaceFileWithIndex(8, withFile: .lzss("uv_icn_type_big_00.fdat.lzss"))
// XGFiles.fsys("field_common.fsys").fsysData.shiftAndReplaceFileWithIndex(9, withFile: .lzss("uv_icn_type_small_00.fdat.lzss"))
// XGFiles.fsys("fight_common.fsys").fsysData.shiftAndReplaceFileWithIndex(15, withFile: .lzss("uv_icn_type_big_00.fdat.lzss"))
// XGFiles.fsys("fight_common.fsys").fsysData.shiftAndReplaceFileWithIndex(16, withFile: .lzss("uv_icn_type_small_00.fdat.lzss"))
// XGFiles.nameAndFolder("title.fsys",.MenuFSYS).fsysData.shiftAndReplaceFileWithIndex(4, withFile: .lzss("title_start_bg.fdat.lzss"))
// XGFiles.nameAndFolder("title.fsys",.MenuFSYS).fsysData.shiftAndReplaceFileWithIndex(12, withFile: .lzss("title_start_00.fdat.lzss"))
// turn pokedance textures into regular textures
//for tex in ["garagara","kyukon","kongpang","ootachi"] {
// for name in [tex + ".fdat", tex + "_c.fdat"] {
// let file = XGFiles.texture(name).data
// file.deleteBytes(start: 0, count: 0xa0)
// file.save()
// }
//}
//let diveballfsys = ["wzx_snatch_attack_dive.fsys","wzx_snatch_ball_land_dive.fsys","wzx_snatch_miss_dive.fsys","wzx_snatch_shake_dive.fsys","wzx_throw_dive.fsys","wzx_yasei_ball_land_dive.fsys","wzx_yasei_get_dive.fsys","wzx_yasei_poke_out_dive.fsys","wzx_yasei_shake_dive.fsys"]
//let diveballfdat = ["snatch_attack_dive.fdat","snatch_ball_land_dive.fdat","snatch_miss_dive.fdat","snatch_shake_dive.fdat","throw_dive.fdat","yasei_ball_land_dive.fdat","yasei_get_dive.fdat","yasei_poke_out_dive.fdat","yasei_shake_dive.fdat"]
//for i in 0 ..< diveballfsys.count {
// let fsys = XGFiles.fsys(diveballfsys[i]).fsysData
// let fdat = XGFiles.nameAndFolder(diveballfdat[i], .TextureImporter).compress()
// fsys.replaceFile(file: fdat)
//}
//let a = XGFiles.nameAndFolder("esaba_A.fsys", .AutoFSYS).fsysData
//let b = XGFiles.nameAndFolder("esaba_B.fsys", .AutoFSYS).fsysData
//let c = XGFiles.nameAndFolder("esaba_C.fsys", .AutoFSYS).fsysData
//let shedinja = XGFiles.nameAndFolder("nukenin_ow.fdat", .TextureImporter).compress()
//for i in [5,6,10] {
// a.replaceFileWithIndex(i, withFile: shedinja)
// c.replaceFileWithIndex(i, withFile: shedinja)
//}
//for i in [5,6,8] {
// b.replaceFileWithIndex(i, withFile: shedinja)
//}
//
//for file in [a,b,c] {
// file.shiftUpFileWithIndex(index: 2)
//}
//for i in 5 ... 10 {
// a.shiftUpFileWithIndex(index: i)
// c.shiftUpFileWithIndex(index: i)
// if i < 9 {
// b.shiftUpFileWithIndex(index: i)
// }
//}
//let suicune = XGFiles.nameAndFolder("suikun_ow.fdat", .TextureImporter).compress()
//let entei = XGFiles.nameAndFolder("entei_ow.fdat", .TextureImporter).compress()
//let raikou = XGFiles.nameAndFolder("raikou_ow.fdat", .TextureImporter).compress()
//a.replaceFileWithIndex(10, withFile: entei)
//b.replaceFileWithIndex(8, withFile: suicune)
//c.replaceFileWithIndex(10, withFile: raikou)
//let photo = item("bonsly photo")
//photo.name.duplicateWithString("XG000 Photo").replace()
//photo.descriptionString.duplicateWithString("An ominous photo...").replace()
//let deck = XGDecks.DeckStory
//let new = deck.unusedPokemonCount(14)
//
//let species = [12,20,24,40,47,83,108,178,203,206,219,226,289,292,308,312,316,348,349,389]
//
//for i in 0 ... 13 {
// let dd = XGDeckPokemon.ddpk(108 + i)
// dd.setDPKMIndexForDDPK(newIndex: new[i].DPKMIndex)
// let d = dd.data
// d.shadowAggression = 1
// d.shadowCounter = 5000
// d.shadowFleeValue = 0
// d.level = 60
// d.shadowCatchRate = 30
// d.ShadowDataInUse = true
// d.shadowUnknown2 = XGDeckPokemon.ddpk(80).data.shadowUnknown2
// d.shadowMoves[0] = move("shadow rush")
// d.species = .pokemon(species[i])
// d.moves[0] = move("latent power")
// d.save()
//}
//let tmList : [[Int]] = [
// [12,83,178,226,292,312,], // tailwind
// [20,24,40,108,203,219,289,308,316,349,], // fire blast
// [12,20,108,178,203,206,289,292,308,316,348,349,], // light pulse
// [12,178,226,292,312,], // hurricane
// [12,20,24,47,219,289,389,], // sludgewave
// [12,40,108,203,206,292,316,348,349,], // dazzling gleam
// [20,24,40,83,108,203,206,289,308,316,], // foul play
// [108,203,292,348,349,], // flash cannon
// [12,20,24,40,83,108,178,203,206,219,226,289,292,308,312,316,348,349,389,], // thunder wave
// [20,40,108,203,206,226,289,308,316,348,], // ice beam
// [178,203,219,348,349,], // will-o-wisp
// [20,108,203,289,308,316,], // wild charge
// [12,178,203,348,349,], // trick room
// [226,312,], // scald
// [20,24,40,108,203,206,219,289,308,316,349,], // flamethrower
// [12,20,24,40,47,83,108,178,203,206,219,289,308,312,316,348,349,389,], // iron head
// [20,40,108,203,206,289,308,316,348,349,], // thunderbolt
// [316,], // freeze dry
// [12,20,24,47,108,206,219,289,292,308,312,316,389,], // sludgebomb
// [12,47,108,178,203,206,219,292,312,316,348,349,389,], // energy ball
// [12,47,206,292,312,], // bug buzz
// [24,206,], // dragon pulse
// [20,24,108,289,308,], // super power
// [108,203,219,308,348,349,389,], // earthquake
// [206,219,348,349,389,], // earth power
// [83,178,206,219,349,], // heat wave
// [20,40,108,203,206,226,289,308,316,348,], // blizzard
// [12,20,24,83,108,203,289,308,316,], // sucker punch
// [20,24,47,108,219,289,316,389,], // gunk shot
// [12,40,178,203,206,292,312,316,348,349,], // psyshock
// [12,20,24,40,108,178,203,206,219,289,308,312,316,348,349,], // shadow ball
// [20,108,206,219,289,308,316,348,349,389,], // rock slide
// [12,20,40,47,108,203,206,219,289,292,308,316,349,389,], // solar beam
// [12,20,40,108,178,203,289,308,316,], // focus blast
// [47,83,312,], // x-scissor
// [20,40,108,203,206,289,308,316,], // thunder
// [12,24,83,178,206,226,289,292,308,312,316,], // acrobatics
// [108,226,289,312,316,], // waterfall
// [289,], // dragon claw
// [], // toxic all except ditto
// [20,108,203,219,289,308,316,349,], // wild flare
// [12,20,24,47,83,108,206,289,292,308,316,389,], // poison jab
// [20,47,83,289,316,], // night slash
// [12,40,108,178,203,206,219,226,292,308,312,316,348,349,389,], // reflect
// [12,40,108,178,203,206,219,226,292,308,312,316,348,349,389,], // light screen
// [40,108,203,226,289,308,312,316,], // surf
// [20,219,289,308,348,349,389,], // stone edge
// [12,40,108,178,203,206,292,312,316,348,349,], // psychic
// [24,108,178,203,289,316,348,349,], // dark pulse
//
//]
//
//let tutList : [[Int]] = [
// [], // draco meteor
// [], // protect ------------------------------
// [], // substitute --------------------------
// [40,108,308,], // fire punch
// [40,108,308,],// thunder punch
// [40,108,308,], // ice punch
// [40,108,203,206,226,289,308,312,348,], // icy wind
// [108,203,289,], // snarl
// [12,24,40,47,83,108,178,203,219,226,289,292,308,312,348,349,389,], // taunt
// [12,24,40,47,83,108,178,203,206,226,289,292,308,312,348,389,], // rain dance
// [12,24,40,47,83,108,178,203,206,219,289,292,308,312,348,349,389,], // sunny day
//
//]
//
//for i in tmList {
// for t in i {
// if t > 415 {
// print("tm typo: ", i, t)
// }
// }
//}
//
//for i in tutList {
// for t in i {
// if t > 415 {
// print("tutor typo: ", i, t)
// }
// }
//}
//
//let tmMons = [12,20,24,40,47,83,108,178,203,206,219,226,289,292,308,312,316,348,349,389,]
//
//for tut in 0 ..< tutList.count {
// for i in tmMons {
// let mon = XGPokemonStats(index: i)
//
// if (tut == 2) || (tut == 1) {
// mon.tutorMoves[tut] = (mon.index != 132) && (mon.index != 398)
// } else if tut == 0 {
// mon.tutorMoves[tut] = (mon.type1 == .dragon) || (mon.type2 == .dragon)
// } else {
// mon.tutorMoves[tut] = tutList[tut].contains(i)
// }
//
// mon.save()
// }
//}
//
//for tm in 0 ..< tmList.count {
// for i in tmMons {
// let mon = XGPokemonStats(index: i)
//
// if tm == 40 {
// mon.learnableTMs[tm] = (mon.index != 132) && (mon.index != 398)
// } else {
// mon.learnableTMs[tm] = tmList[tm].contains(i)
// }
//
// mon.save()
// }
//}
//// copy level up moves
//for (to, from) in [(1,3),(2,3),(7,9),(8,9),(16,18),(17,18),(19,20),(23,24),(30,31),(33,34),(39,40),(41,42),(43,44),(46,47),(50,51),(52,53),(56,57),(58,59),(60,61),(66,67),(74,75),(98,99),(100,101),(109,110),(111,112),(137,233),(152,153),(155,156),(158,159),(163,164),(170,171),(177,178),(179,180),(188,189),(204,205),(209,210),(216,217),(218,219),(288,289),(295,297),(296,297),(309,310),(313,314),(315,316),(318,319),(335,336),(341,343),(342,343),(364,366),(365,366),(370,372),(371,372),(382,384),(383,384),(388,389),(390,391),] {
// let f = XGPokemonStats(index: from)
// let t = XGPokemonStats(index: to)
// t.levelUpMoves = f.levelUpMoves
// t.learnableTMs = f.learnableTMs
// t.tutorMoves = f.tutorMoves
// t.save()
//}
//// shadow shake
//let shakeBranch = 0x216d94 - kDolToRAMOffsetDifference
//let shakeStart = 0x21fe38 - kDolToRAMOffsetDifference
//let groundTrue = 0x216e10 - kDolToRAMOffsetDifference
//let groundFalse = shakeBranch + 0x4
//let setEffect = 0x1f057c - kDolToRAMOffsetDifference
//let checkForType = 0x2054fc - kDolToRAMOffsetDifference
//replaceASM(startOffset: shakeBranch, newASM: [XGUtility.createBranchFrom(offset: shakeBranch, toOffset: shakeStart)])
//replaceASM(startOffset: shakeStart, newASM: [
// 0x7f43d378, // mr r3, r26 (move)
// 0x28030084, // cmpwi r3, shadow shake
// 0x7f63db78, // mr r3, r27 (defending pokemon)
// XGUtility.powerPCBranchEqualFromOffset(from: 0x0, to: 0x8),
// XGUtility.createBranchFrom(offset: shakeStart + 0x10, toOffset: groundFalse),
// 0xa063080c, // lhz r3, 0x080C (r3) get ability
// 0x2803001a, // cmpwi r3, levitate
// XGUtility.powerPCBranchEqualFromOffset(from: 0x0, to: 0x18),
// 0x7f63db78, // mr r3, r27 (defending pokemon)
// 0x38800002, // li r4, flying type
// XGUtility.createBranchAndLinkFrom(offset: shakeStart + 0x28, toOffset: checkForType),
// 0x28030001, // cmpwi r3, 1
// XGUtility.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x18),
// 0x7fe3fb78, // mr r3, r31
// 0x38800043, // li r4, 67 (doesn't affect the target)
// 0x38a00000, // li r5, 0
// XGUtility.createBranchAndLinkFrom(offset: shakeStart + 0x40, toOffset: setEffect),
// XGUtility.createBranchFrom(offset: shakeStart + 0x44, toOffset: groundTrue),
// 0x7f63db78, // mr r3, r27 (overwritten code)
// XGUtility.createBranchFrom(offset: shakeStart + 0x4c, toOffset: groundFalse),
//])
//// sucker punch
//let suckerBranch = 0x216e10 - kDolToRAMOffsetDifference
//let suckerStart = 0x21fe88 - kDolToRAMOffsetDifference
//let suckerEnd = suckerBranch + 0x4
////let setEffect = 0x1f057c - kDolToRAMOffsetDifference
//let getCurrentMove = 0x148d64 - kDolToRAMOffsetDifference
//let getMovePower = 0x13e71c - kDolToRAMOffsetDifference
//let getMoveOrder = 0x1f4300 - kDolToRAMOffsetDifference
//replaceASM(startOffset: suckerBranch, newASM: [XGUtility.createBranchFrom(offset: suckerBranch, toOffset: suckerStart)])
//replaceASM(startOffset: suckerStart, newASM: [
// 0x7f43d378, // mr r3, r26 (move)
// 0x28030015, // cmpwi r3, sucker punch
// XGUtility.powerPCBranchEqualFromOffset(from: 0x0, to: 0xc),
// 0x7fe3fb78, // mr r3, r31 (overwritten code)
// XGUtility.createBranchFrom(offset: suckerStart + 0x10, toOffset: suckerEnd),
// 0x7f63db78, // mr r3, r27 (defending pokemon)
// XGUtility.createBranchAndLinkFrom(offset: suckerStart + 0x18, toOffset: getCurrentMove),
// XGUtility.createBranchAndLinkFrom(offset: suckerStart + 0x1c, toOffset: getMovePower),
// 0x28030000, // cmpwi r3, 0
// XGUtility.powerPCBranchEqualFromOffset(from: 0x0, to: 0x28),
// 0x38600000, // li r3, 0
// 0x38c00000, // li r6, 0
// 0x7f64dB78, // mr r4, r27 (defending pokemon)
// 0x7f85e378, // mr r5, r28 (attacking pokemon)
// XGUtility.createBranchAndLinkFrom(offset: suckerStart + 0x38, toOffset: getMoveOrder),
// 0x28030001, // cmpwi r3, 1
// XGUtility.powerPCBranchEqualFromOffset(from: 0x0, to: 0xc),
// 0x7fe3fb78, // mr r3, r31 (overwritten code)
// XGUtility.createBranchFrom(offset: suckerStart + 0x48, toOffset: suckerEnd),
// 0x7fe3fb78, // mr r3, r31 (overwritten code)
// 0x38800045, // li r4, 69 (the move failed)
// 0x38a00000, // li r5, 0
// XGUtility.createBranchAndLinkFrom(offset: suckerStart + 0x58, toOffset: setEffect),
// 0x7fe3fb78, // mr r3, r31 (overwritten code)
// XGUtility.createBranchFrom(offset: suckerStart + 0x60, toOffset: suckerEnd)
//])
//// skill link
//let skillBranch1 = 0x221d70 - kDolToRAMOffsetDifference
//let skillBranch2 = 0x221d98 - kDolToRAMOffsetDifference
//let skillStart = 0x152548 - kDolToRAMOffsetDifference
//replaceASM(startOffset: skillBranch1, newASM: [XGUtility.createBranchAndLinkFrom(offset: skillBranch1, toOffset: skillStart)])
//replaceASM(startOffset: skillBranch2, newASM: [XGUtility.createBranchAndLinkFrom(offset: skillBranch2, toOffset: skillStart)])
//replaceASM(startOffset: skillStart, newASM: [
//0x5404063e, // rlwinm r4, r0, 0, 24, 31 (replaced code)
//0x387FF9B8, // subi r3, r31, 1608 (turns move routine pointer back to battle pokemon pointer)
//0xa063080c, // lhz r3, 0x080C (r3) get ability
//0x28030066, // cmpwi r3, 102 (skill link)
//0x41820008, // beq 0x8
//0x4e800020, // blr
//0x38800005, // li r4, 5
//0x4e800020, // blr
//])
//// shade ball
//let shadeStart = 0x219380 - kDolToRAMOffsetDifference
//let checkShadow = 0x13efec - kDolToRAMOffsetDifference
//replaceASM(startOffset: shadeStart, newASM: [
// 0x7f43d378, // mr r3, r26 defending pokemon stats
// XGUtility.createBranchAndLinkFrom(offset: shadeStart + 0x4, toOffset: checkShadow),
// 0x28030001, // cmpwi r3, 1
// XGUtility.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x14),
// kNopInstruction,
// kNopInstruction,
// 0x3b800032, // li r28, 50
//])
//
//// net ball buff
//replaceASM(startOffset: 0x219370 - kDolToRAMOffsetDifference, newASM: [0x3b800023])
//
//// magic bounce 2
//let setStatus = 0x2024a4 - kDolToRAMOffsetDifference
//let getMove = 0x148d64 - kDolToRAMOffsetDifference
//let coatBranch = 0x218590 - kDolToRAMOffsetDifference
//let coatReturn = coatBranch + 0x4
//let coatStart = 0x21ea68 - kDolToRAMOffsetDifference
//replaceASM(startOffset: coatBranch, newASM: [XGUtility.createBranchFrom(offset: coatBranch, toOffset: coatStart)])
//replaceASM(startOffset: coatStart, newASM: [
// 0x38a00000, // li r5, 0
// XGUtility.createBranchAndLinkFrom(offset: coatStart + 0x4, toOffset: setStatus),
// 0x7f83e378, // mr r3, r28 (defending pokemon)
// XGUtility.createBranchAndLinkFrom(offset: coatStart + 0xc, toOffset: getMove),
// 0x7C641B78, // mr r4, r3
// 0x7f83e378, // mr r3, r28 (defending pokemon)
// 0xb0830008, // sth r4, 0x0008 (r3)
// XGUtility.createBranchFrom(offset: coatStart + 0x1c, toOffset: coatReturn)
//])
//let coatCheckBranch = 0x20e3c4 - kDolToRAMOffsetDifference
//let coatCheckReturn = coatCheckBranch + 0x4
//let coatCheckStart = 0x21dc10 - kDolToRAMOffsetDifference
//let checkStatus = 0x2025f0 - kDolToRAMOffsetDifference
//let getPokemon = 0x1efcac - kDolToRAMOffsetDifference
//let setMove = 0x14774c - kDolToRAMOffsetDifference
//replaceASM(startOffset: coatCheckBranch, newASM: [XGUtility.createBranchFrom(offset: coatCheckBranch, toOffset: coatCheckStart)])
//replaceASM(startOffset: coatCheckStart, newASM: [
// 0x38600011, // li r3, 17
// 0x38800000, // li r4, 0
// XGUtility.createBranchAndLinkFrom(offset: coatCheckStart + 0x8, toOffset: getPokemon),
// 0x38800037, // li r4, magic coat (set after magic bounce activates)
// XGUtility.createBranchAndLinkFrom(offset: coatCheckStart + 0x10, toOffset: checkStatus),
// 0x28030001, // cmpwi r3, 1
// XGUtility.powerPCBranchNotEqualFromOffset(from: 0x18, to: 0x30),
// 0x38600011, // li r3, 17
// 0x38800000, // li r4, 0
// XGUtility.createBranchAndLinkFrom(offset: coatCheckStart + 0x24, toOffset: getPokemon),
// 0xa0830008, // lhz r4, 0x0008 (r3)
// XGUtility.createBranchAndLinkFrom(offset: coatCheckStart + 0x2c, toOffset: setMove),
// 0xbb410008, // lmw r26, 0x0008 (sp)
// XGUtility.createBranchFrom(offset: coatCheckStart + 0x34, toOffset: coatCheckReturn),
//
//])
//let coatChangeBranch = 0x209bac - kDolToRAMOffsetDifference
//let coatChangeReturn = coatChangeBranch + 0x4
//let coatNopOffset = 0x209bb4 - kDolToRAMOffsetDifference
//let coatChangeStart = 0x21bc80 - kDolToRAMOffsetDifference
//replaceASM(startOffset: coatNopOffset, newASM: [kNopInstruction])
//replaceASM(startOffset: coatChangeBranch, newASM: [XGUtility.createBranchFrom(offset: coatChangeBranch, toOffset: coatChangeStart)])
//replaceASM(startOffset: coatChangeStart, newASM: [
// 0x7C7A1B78, // mr r26, r3
// 0x7f83e378, // mr r3, r28 (attacking pokemon)
// 0x38800037, // li r4, magic coat (set after magic bounce activates)
// XGUtility.createBranchAndLinkFrom(offset: coatChangeStart + 0xc, toOffset: checkStatus),
// 0x28030001, // cmpwi r3, 1
// XGUtility.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x10),
// 0x7f83e378, // mr r3, r28 (attacking pokemon)
// 0xa0630008, // lhz r3, 0x0008 (r3)
// 0x7C7A1B78, // mr r26, r3
// XGUtility.createBranchFrom(offset: coatChangeStart + 0x24, toOffset: coatChangeReturn)
//])
//
//// sand rush/force immune to sandstorm
//let sarfissBranch = 0x221238 - kDolToRAMOffsetDifference
//let sarfissStart = 0x221998 - kDolToRAMOffsetDifference
//let sarfissReturn = sarfissBranch + 0x8
//let sarfissNoDamage = 0x22127c - kDolToRAMOffsetDifference
//replaceASM(startOffset: sarfissBranch, newASM: [XGUtility.createBranchFrom(offset: sarfissBranch, toOffset: sarfissStart)])
//replaceASM(startOffset: sarfissStart, newASM: [
// 0x28000008, // cmpwi r0, sand veil
// XGUtility.powerPCBranchEqualFromOffset(from: 0x4, to: 0x18),
// 0x2800005a, // cmpwi r0, sand force
// XGUtility.powerPCBranchEqualFromOffset(from: 0xc, to: 0x18),
// 0x2800005b, // cmpwi r0, sand rush
// XGUtility.powerPCBranchNotEqualFromOffset(from: 0x14, to: 0x1c),
// XGUtility.createBranchFrom(offset: sarfissStart + 0x18, toOffset: sarfissNoDamage),
// XGUtility.createBranchFrom(offset: sarfissStart + 0x1c, toOffset: sarfissReturn)
//])
////Sand rush
//let sandstart = 0x2009c0
//// slush rush speed
//let slushBranch = sandstart + 0x10
//let slushstart = XGAssembly.ASMfreeSpacePointer()
//XGAssembly.replaceDOLASM(startOffset: slushstart - kDOLtoRAMOffsetDifference, newASM: [
// 0x2817005b, // cmpwi r23, sand rush
// 0x40820008, // bne 0x8
// XGAssembly.createBranchFrom(offset: slushstart + 0x8, toOffset: sandstart + 0x1c),
// 0x28170057, // cmpwi r23, slush rush
// 0x41820008, // beq 0x8
// XGAssembly.createBranchFrom(offset: slushstart + 0x14, toOffset: sandstart + 0x24),
// 0x281C0004, // cmpwi r28, hail
// 0x41820008, // beq 0x8
// XGAssembly.createBranchFrom(offset: slushstart + 0x20, toOffset: sandstart + 0x24),
// XGAssembly.createBranchFrom(offset: slushstart + 0x24, toOffset: sandstart + 0x3c),
//])
//
//// slush rush and snow cloak immune to hail
//let slimStart = 0x22129c - kDolToRAMOffsetDifference
//XGAssembly.replaceASM(startOffset: slimStart, newASM: [
// 0x57e0043e, // rlwinm r0, r31, 0, 16, 31 (0000ffff)
// 0x28000069, // cmpwi r0, snow cloak
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x8, to: 0x3c),
// 0x28000057, // cmpwi r0, slush rush
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x10, to: 0x3c),
//])
//
//// aura filter immune to shadow sky
//let afissBranch = 0x2212e4 - kDolToRAMOffsetDifference
//let afissReturn = afissBranch + 0x4
//let afissNoDamage = 0x221330 - kDolToRAMOffsetDifference
//let afissStart = 0x2219b8 - kDolToRAMOffsetDifference
//replaceASM(startOffset: afissBranch, newASM: [XGUtility.createBranchFrom(offset: afissBranch, toOffset: afissStart)])
//replaceASM(startOffset: afissStart, newASM: [
// 0x7f43d378, // defending pokemon stats pointer
// 0xa0630002, // lhz r3, 0x0002(r3) get item
// 0x2803003c, // cmpwi r3, aura filter
// XGUtility.powerPCBranchEqualFromOffset(from: 0x0, to: 0xc),
// 0x7f43d378, // overwritten by branch
// XGUtility.createBranchFrom(offset: afissStart + 0x14, toOffset: afissReturn),
// XGUtility.createBranchFrom(offset: afissStart + 0x18, toOffset: afissNoDamage),
//])
//
//
//// rage mode boost
////let checkStatus = 0x2025f0 - kDolToRAMOffsetDifference
//let rageStart = 0x22a67c - kDolToRAMOffsetDifference
//replaceASM(startOffset: rageStart, newASM: [
// 0x7de37b78, // mr r3, r15
// 0x3880003e, // li r4, reverse mode
// XGUtility.createBranchAndLinkFrom(offset: rageStart + 0x8, toOffset: checkStatus),
// 0x28030001, // cmpwi r3, 1
// XGUtility.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x18),
// 0x7ec3b378, // mr r3, r22
// 0x38000064, // li r0, 100
// 0x1c630082, // mulli r3, 130
// 0x7c0303d6, // div r0, r3, r0
// 0x5416043e, // rlwinm r22, r0
// ])
//
//for offset in stride(from: 770, through: 800, by: 2) {
// XGUtility.replaceMartItemAtOffset(offset, withItem: XGUtility.getMartItemAtOffset(offset + 2))
//}
//XGUtility.replaceMartItemAtOffset(800, withItem: .item(333))
//let aurora = move("aurora veil").data
//aurora.pp = 10
//aurora.save()
//
//let omanyte = pokemon("omanyte").stats
//omanyte.levelUpMoves[0].move = move("rock throw")
//omanyte.save()
//
//let rest = move("rest").data
//rest.effect = 37
//rest.save()
//
//let veil = move("shadow veil").data
//veil.pp = 5
//veil.save()
//
//let feebas = pokemon("feebas").stats
//feebas.evolutions[0].evolutionMethod = .levelUp
//feebas.evolutions[0].condition = 20
//feebas.save()
//let tmList : [[Int]] = [
// [], // tailwind
// [], // fire blast
// [], // light pulse
// [], // hurricane
// [], // sludgewave
// [], // dazzling gleam
// [], // foul play
// [], // flash cannon
// [286], // thunder wave
// [], // ice beam
// [], // will-o-wisp
// [], // wild charge
// [], // trick room
// [], // scald
// [], // flamethrower
// [], // iron head
// [], // thunderbolt
// [], // freeze dry
// [], // sludgebomb
// [], // energy ball
// [], // zen headbutt
// [], // bug buzz
// [], // dragon pulse
// [142], // super power
// [279], // earthquake
// [], // earth power
// [], // heat wave
// [], // blizzard
// [], // sucker punch
// [], // gunk shot
// [], // psyshock
// [], // shadow ball
// [279], // rock slide
// [], // solar beam
// [279], // focus blast
// [], // x-scissor
// [], // thunder
// [], // acrobatics
// [], // waterfall
// [], // dragon claw
// [], // toxic all except ditto
// [], // wild flare
// [], // poison jab
// [], // night slash
// [245], // reflect
// [245], // light screen
// [], // surf
// [], // stone edge
// [], // psychic
// [], // dark pulse
//
//]
//
//for i in tmList {
// for t in i {
// if t > 415 {
// print("tm typo: ", i, t)
// }
// }
//}
//
//for tm in 0 ..< tmList.count {
// if tmList[tm].count > 0 {
// let mon = XGPokemon.pokemon(tmList[tm][0]).stats
// mon.learnableTMs[tm] = true
// mon.save()
// }
//}
//
//
//let gyarados = XGTrainer(index: 199, deck: .DeckStory).pokemon[1].data
//let gyarados2 = XGTrainer(index: 67, deck: .DeckColosseum).pokemon[3].data
//for mon in [gyarados, gyarados2] {
// mon.shinyness = .always
// mon.save()
//}
//// make taunt last 4 turns
//let dol = XGFiles.dol.data!
//dol.replaceByteAtOffset(0x3f93e0 + (48 * 0x14) + 4, withByte: 4)
//
//// make tail wind last 4 turns
////let dol = XGFiles.dol.data!
//dol.replaceByteAtOffset(0x3f93e0 + (75 * 0x14) + 4, withByte: 4)
//
//for tm in XGTMs.allTMs() {
//
// tm.updateItemDescription()
//
//}
// binding moves residual damage to 1/8 (whirpool, firespin, etc.)
//XGAssembly.replaceASM(startOffset: 0x22807c - kDolToRAMOffsetDifference, newASM: [0x38800008])
//let dive = XGFiles.nameAndFolder("ball_dive.fdat", .TextureImporter).compress()
//XGFiles.fsys("people_archive.fsys").fsysData.replaceFile(file: dive)
//// sash/sturdy 2 (multihit moves work)
//let sash2Branch = 0x216038
//let sash2Start = 0xb99350
//let getMoveEffect = 0x13e6e8
//XGAssembly.replaceASM(startOffset: sash2Branch - kDolToRAMOffsetDifference, newASM: [
// XGAssembly.createBranchFrom(offset: sash2Branch, toOffset: sash2Start),
// // overwritten code
// 0x7fa3eb78, // mr r3, r29
// 0x38800001, // li r4, 1
//])
//XGAssembly.replaceRELASM(startOffset: sash2Start - kRELtoRAMOffsetDifference, newASM: [
// 0x7f83e378, // mr r3, r28
// XGAssembly.createBranchAndLinkFrom(offset: sash2Start + 0x4, toOffset: getMoveEffect),
// 0x2803001d, // cmpwi r3, 29 (2-5 hits)
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0x28), // beq 0x28
// 0x2803002c, // cmpwi r3, 44 (2 hits)
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0x20), // beq 0x20
// 0x2803004d, // cmpwi r3, 77 (2 hits + poison)
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0x18), // beq 0x18
// 0x28030068, // cmpwi r3, 104 (3 hits)
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0x10), // beq 0x10
// 0x2803009a, // cmpwi r3, 154 (beat up)
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0x08), // beq 0x8
// XGAssembly.createBranchFrom(offset: sash2Start + 0x30, toOffset: sash2Branch + 0x4), // b branch + 0x4
// XGAssembly.createBranchFrom(offset: sash2Start + 0x34, toOffset: sash2Branch + 0x10), // b branch + 0x10
//])
//
//
//// shadow hunter/slayer
//let hunterStart = 0x22a6a4 - kDolToRAMOffsetDifference
//let checkShadowPokemon = 0x149014 - kDolToRAMOffsetDifference
//XGAssembly.replaceASM(startOffset: hunterStart, newASM: [
// 0x7e038378, // mr r3, r16 (defending mon)
// 0x80630000, // lw r3, 0 (r3)
// 0x38630004, // addi r3, 4
// XGAssembly.createBranchAndLinkFrom(offset: hunterStart + 0xc, toOffset: checkShadowPokemon),
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x34),
// 0x7e238b78, // mr r3, r17
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0xa063001c, // lhz 0x001c(r3) (get move effect)
// 0x28030015, // cmpwi r3, shadow hunter/slayer
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x18),
// // boost 50%
// 0x56c3043e, // rlwinm r3, r22
// 0x38000064, // li r0, 100
// 0x1c630096, // mulli r3, 150
// 0x7c0303d6, // div r0, r3, r0
// 0x5416043e, // rlwinm r22, r0
//])
//
//
//// hex
//let hexStart = 0x22a6ec - kDolToRAMOffsetDifference
//let checkNoStatus = 0x203744 - kDolToRAMOffsetDifference
//XGAssembly.replaceASM(startOffset: hexStart, newASM: [
// 0x7e038378, // mr r3, r16 (defending pokemon)
// XGAssembly.createBranchAndLinkFrom(offset: hexStart + 0x4, toOffset: checkNoStatus),
// 0x28030001, // if has no status effect
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0x28),
// 0x7e238b78, // mr r3, r17
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0xa063001c, // lhz 0x001c(r3) (get move effect)
// 0x2803000c, // cmpwi r3, move effect 12 (hex)
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x38600002, // li r3, 2
// 0x7ED619D6, // mullw r22, r22, r3
//])
//// aoe moves (e.g. bulldoze discharge)
// need to test how moves being absorbed affects aoe moves before investing time
// into making this work.
// it seems some abilities completely end the move after absorbing it.
//let activateSecondary = 0x213d20
//let getRoutinePos = 0x806dbb10 // lwz r3, -0x44F0 (r13)
//let setRoutinePos = 0x906dbb10 // stw r3, -0x44F0 (r13)
//
//// change effect to eq in use move
//let effectBranch = 0x20f068
//let effectStart = 0x0
//
//let getTargets = 0x13e784
//
//let effectCode : ASM = [
//
// 0x7c791b78, // mr r25, r3
// 0x7f03c378, // mr r3, r24
// XGAssembly.createBranchAndLinkFrom(offset: effectStart + 0x8, toOffset: getTargets),
// 0x28030006, // cmpwi r3, both foes and ally
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x38600093, // li r3, earthquake effect
// 0x7c791b78, // mr r25, r3
// // overwritten code
// 0x38000000, // li r0, 0
//
//]
//// disable/encore lasts 4 turns
//XGStatusEffects.disabled.setDuration(turns: 4)
//XGStatusEffects.encored.setDuration(turns: 4)
//
//// remove follow me redirection so can be used for wide guard
//XGAssembly.replaceASM(startOffset: 0x218bb4 - kDolToRAMOffsetDifference, newASM: [0x4800003c])
////Sand rush
//let sandstart = 0x2009c0
//let sinstructions : ASM = [
// 0x5464043e, // rlwinm r4, r3, 0, 16, 31 (0000ffff)
// 0x28170021, // cmpwi r23, swift swim
// 0x41820020, // beq 0x20
// 0x28170022, // cmpwi r23, chlorophyll
// 0x41820024, // beq 0x24
// 0x2817005b, // cmpwi r23, sand rush
// 0x40820028, // bne 0x28
// 0x281C0003, // cmpwi r28, sandstorm
// 0x4182001C, // beq 0x1c
// 0x4800001C, // b 0x1c
// 0x281C0002, // cmpwi r28, rain
// 0x41820010, // beq 0x10
// 0x48000010, // b 0x10
// 0x281C0001, // cmpwi r28, sun
// 0x40820008 // bne 0x8
//]
//XGAssembly.replaceASM(startOffset: sandstart, newASM: sinstructions)
////Sand rush
//let sandstart = 0x2009c0 + kDolToRAMOffsetDifference
//// slush rush speed
//let slushBranch = sandstart + 0x14
//let slushstart = 0xB99ED8
//XGAssembly.replaceASM(startOffset: slushBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: slushBranch, toOffset: slushstart)])
//XGAssembly.replaceRELASM(startOffset: slushstart - kRELtoRAMOffsetDifference, newASM: [
// 0x2817005b, // cmpwi r23, sand rush
// 0x40820008, // bne 0x8
// XGAssembly.createBranchFrom(offset: slushstart + 0x8, toOffset: sandstart + 0x1c),
// 0x28170057, // cmpwi r23, slush rush
// 0x41820008, // beq 0x8
// XGAssembly.createBranchFrom(offset: slushstart + 0x14, toOffset: sandstart + 0x24),
// 0x281C0004, // cmpwi r28, hail
// 0x41820008, // beq 0x8
// XGAssembly.createBranchFrom(offset: slushstart + 0x20, toOffset: sandstart + 0x24),
// XGAssembly.createBranchFrom(offset: slushstart + 0x24, toOffset: sandstart + 0x3c),
//])
//
//// slush rush and snow cloak immune to hail
//let slimStart = 0x22129c - kDolToRAMOffsetDifference
//XGAssembly.replaceASM(startOffset: slimStart, newASM: [
// 0x57e0043e, // rlwinm r0, r31, 0, 16, 31 (0000ffff)
// 0x28000069, // cmpwi r0, snow cloak
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x8, to: 0x3c),
// 0x28000057, // cmpwi r0, slush rush
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x10, to: 0x3c),
//])
//// shadow terrain residual hp healing for shadow pokemon
//let terrainBranch = 0x227ac8 //(ram)
//let terrainStart = 0xb99388
//
//let healTrue = 0x227ad4
//let healFalse = 0x227b0c
//
//let checkField = 0x1f3824
//let checkShadow = 0x149014
//
//let terrainCode : ASM = [
//
// 0x28030001, // cmpwi r3, 1 (overwritten check for ingrain)
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// XGAssembly.createBranchFrom(offset: terrainStart + 0x8, toOffset: healTrue),
//
// 0x38600000, // li r3, 0
// 0x38800038, // li r4, 56
// XGAssembly.createBranchAndLinkFrom(offset: terrainStart + 0x14, toOffset: checkField),
// 0x5460043f, // rlwinm. r0, r3, 0, 16, 31 (0000ffff)
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// XGAssembly.createBranchFrom(offset: terrainStart + 0x20, toOffset: healFalse),
//
// 0x7fe3fb78, // mr r3, r31 (battle pokemon)
// // get stats pointer
// 0x80630000, // lwz r3, 0 (r3)
// 0x38630004, // addi r3, r3, 4
//
// XGAssembly.createBranchAndLinkFrom(offset: terrainStart + 0x30, toOffset: checkShadow),
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// XGAssembly.createBranchFrom(offset: terrainStart + 0x3c, toOffset: healTrue),
// XGAssembly.createBranchFrom(offset: terrainStart + 0x40, toOffset: healFalse),
//
//]
//
//XGAssembly.replaceASM(startOffset: terrainBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: terrainBranch, toOffset: terrainStart),kNopInstruction])
//XGAssembly.replaceRELASM(startOffset: terrainStart - kRELtoRAMOffsetDifference, newASM: terrainCode)
//// shadow terrain residual healing to 1/10
//XGAssembly.replaceASM(startOffset: 0x227ae8 - kDolToRAMOffsetDifference, newASM: [0x3880000A])
//
//// regular moves doe 75% damage in shadow terrain
//XGAssembly.replaceASM(startOffset: 0x22a62c - kDolToRAMOffsetDifference, newASM: [
// 0x1C160003, // mulli r0, r22, 3
// 0x7C001670, // srawi r0, r0,2
//])
//// allow endured the hit message to be set elsewhere (effectiveness 70) (interferes with focus sash message)
//for offset in [0x2160f8, 0x2160e0] {
// XGAssembly.replaceASM(startOffset: offset - kDolToRAMOffsetDifference, newASM: [0x38800047])
//}
//
//// spiky shield 1 (replaces endure effect)
//XGAssembly.replaceASM(startOffset: 0x223514 - kDolToRAMOffsetDifference, newASM: [0x28000113])
//XGAssembly.replaceASM(startOffset: 0x223570 - kDolToRAMOffsetDifference, newASM: [kNopInstruction])
//XGAssembly.replaceASM(startOffset: 0x2235dc - kDolToRAMOffsetDifference, newASM: [kNopInstruction,kNopInstruction, kNopInstruction])
//let endureRemove = 0x21607c - kDolToRAMOffsetDifference
//XGAssembly.replaceASM(startOffset: endureRemove, newASM: [kNopInstruction,kNopInstruction,kNopInstruction,kNopInstruction,kNopInstruction])
//XGAssembly.replaceASM(startOffset: 0x2160d8 - kDolToRAMOffsetDifference, newASM: [0x48000030])
//
////rocky helmet & spiky shield 2
//let rockyBranch = 0x2250bc
//let rockyStart = 0xb993cc
//
//let checkStatus = 0x2025f0
//let getMoveEffectiveness = 0x1f0684
//let getItem = 0x20384c
//
//let getHPFraction = 0x203688
//let storeHP = 0x13e094
//let animSoundCallBack = 0x2236a8
//let clearEffectiveness = 0x1f06d8
//
//let rockyCode : ASM = [
//
// // check contact
// 0x28190001, // cmpwi r25, 1
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0x8), // beq 8
// XGAssembly.createBranchFrom(offset: 0x8, toOffset: 0x88),
//
// // check spiky shield (status 44)
// 0x7fe3fb78, // mr r3, r31 (defending mon)
// 0x3880002c, // li r4, spiky shield (originally endure flag)
// XGAssembly.createBranchAndLinkFrom(offset: rockyStart + 0x14, toOffset: checkStatus),
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x1c, to: 0x48),
//
// // check protected
// 0x7e439378, // mr r3, r18 move routine pointer
// 0x38800040, // li r4, 64 (protected)
// XGAssembly.createBranchAndLinkFrom(offset: rockyStart + 0x28, toOffset: getMoveEffectiveness),
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0x8),
// XGAssembly.createBranchFrom(offset: 0x0, toOffset: 0x14),
// 0x7e439378, // mr r3, r18 move routine pointer
// 0x38800040, // li r4, failed (rough skin won't work if the move failed)
// XGAssembly.createBranchAndLinkFrom(offset: rockyStart + 0x40, toOffset: clearEffectiveness),
// XGAssembly.createBranchFrom(offset: 0x44, toOffset: 0x64),
//
// // check failed
// 0x281a0001, // cmpwi r26, 1
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0x8),
// XGAssembly.createBranchFrom(offset: 0x50, toOffset: 0x88),
//
// // check item rocky helmet (hold item id 77)
// 0x7fe3fb78, // mr r3, r31 (defending mon)
// XGAssembly.createBranchAndLinkFrom(offset: rockyStart + 0x58, toOffset: getItem),
// 0x2803004d, // cmplwi r3, rocky helmet
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x60, to: 0x88),
//
// // rough skin code
// 0x7fc3f378, // mr r3, r30 (attacking mon)
// 0x38800006, // li r4, 6
// XGAssembly.createBranchAndLinkFrom(offset: rockyStart + 0x6c, toOffset: getHPFraction),
// 0x5464043e, // rlwinm r4, r3, 0, 16, 31 (0000ffff)
// 0x7e439378, // mr r3, r18
// XGAssembly.createBranchAndLinkFrom(offset: rockyStart + 0x78, toOffset: storeHP),
// 0x3c608041, // lis r3, 0x8041
// 0x38637be1, // addi r3, r3, 31713
// XGAssembly.createBranchAndLinkFrom(offset: rockyStart + 0x84, toOffset: animSoundCallBack),
//
// 0x7fc3f378, // mr r3, r30 (overwritten code)
// XGAssembly.createBranchFrom(offset: rockyStart + 0x8c, toOffset: rockyBranch + 0x4),
//]
//XGAssembly.replaceASM(startOffset: rockyBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: rockyBranch, toOffset: rockyStart)])
//XGAssembly.replaceRELASM(startOffset: rockyStart - kRELtoRAMOffsetDifference, newASM: rockyCode)
//// checks if defending pokemon has hp before allowing attack
//// helps with chaining move routines where an effect is applied after attacking
//// but need to check that the pokemon hasn't fainted
//let hpCheckBranch = 0x218370
//let hpCheckStart = 0x22244c
//let checkHP = 0x204a70
//let hpFail = 0x218380
//let hpCode : ASM = [
// 0x7f83e378, // mr r3, r28
// XGAssembly.createBranchAndLinkFrom(offset: hpCheckStart + 0x4, toOffset: checkHP),
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0x8),
// XGAssembly.createBranchFrom(offset: hpCheckStart + 0x10, toOffset: hpFail),
// 0x7fa3eb78, // mr r3, r29
// XGAssembly.createBranchFrom(offset: hpCheckStart + 0x18, toOffset: hpCheckBranch + 0x4)
//]
//XGAssembly.replaceASM(startOffset: hpCheckBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: hpCheckBranch, toOffset: hpCheckStart)])
//XGAssembly.replaceASM(startOffset: hpCheckStart - kDolToRAMOffsetDifference, newASM: hpCode)
//// foul play 2, include stat boosts on foe
//let fpBranch = 0x22a120 - kDolToRAMOffsetDifference
//let fpStart = 0x2209cc - kDolToRAMOffsetDifference
//
//XGAssembly.replaceASM(startOffset: fpBranch, newASM: [
// 0x9001000c, // overwritten code
// XGAssembly.createBranchFrom(offset: fpBranch + 0x4, toOffset: fpStart)
// ])
//XGAssembly.replaceASM(startOffset: fpStart, newASM: [
// 0x7e238b78, // mr r3, r17
// // get move data pointer
// 0x1c030038,
// 0x806d89d4,
// 0x7c630214,
// 0xa063001c, // lhz 0x001c(r3) (get move effect)
// 0x2803000f, // cmpwi r3, move effect 15 (foul play)
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x7e038378, // mr r3, r16
// XGAssembly.createBranchFrom(offset: 0x0, toOffset: 0x8),
// 0x7de37b78, // mr r3, r15
// XGAssembly.createBranchFrom(offset: fpStart + 0x28, toOffset: fpBranch + 0x8)
//])
//// roar move effect doesn't require higher level
//let roarStart = 0x221c54 - kDolToRAMOffsetDifference
//XGAssembly.replaceASM(startOffset: roarStart, newASM: [0x7c7f1b78,kNopInstruction,kNopInstruction])
//
//// roar move routine doesn't show animation etc.
//let roarRoutineStart = 0x413f45
//let dol = XGFiles.dol.data!
//dol.replaceBytesFromOffset(roarRoutineStart, withByteStream: [0x3b,0x3b,0x3b])
//dol.save()
//// learnable SMs
//let lsms = [
// [0], // shadow rush
// [0], // shadow pulse
// [0], // shadow bully
// [20,31,34,57,62,68,76,83,94,99,101,108,115,125,126,127,143,184,185,210,214,217,289,287,320,321,324,336,340,345,343,347,366,378,391,410,413], // shadow max
// [413,410,406,380,376,378,347,345,338,337,330,331,322,316,315,312,307,304,305,303,302,301,299,300,289,287,286,283,284,285,282,281,280,279,278,277,264,250,249,241,237,234,232,231,228,229,215,212,207,203,200,198,197,193,190,189,184,183,176,169,168,166,164,150,149,142,141,133,134,135,136,128,127,126,125,124,123,121,120,119,106,107,101,94,93,92,89,88,85,83,77,78,59,57,56,53,51,42,37,38,28,27,26,25,22,20,18,15,12,], // shadow stealth
// [0], // shadow sky
// [410,409,408,407,394,386,387,379,378,376,363,362,349,348,347,345,329,322,319,317,312,303,302,292,265,264,249,233,206,203,201,202,200,198,197,196,178,176,175,169,166,164,150,144,137,196,124,122,121,103,94,80,73,65,64,55,49,38,12,], // shadow madness
// [0], // shadow guard
//]
//
//for i in 1 ..< kNumberOfPokemon {
// let mon = XGPokemon.pokemon(i).stats
//
// for j in [3,4,6]{
//
// mon.learnableTMs[50 + j] = lsms[j].contains(i) || (i == 151)
//
// }
//
// for j in [0,1,2,5,7] {
// mon.learnableTMs[50 + j] = mon.index != 251
// }
//
// mon.save()
//}
//
//
//let sms = ["Shadow Rush","Shadow Pulse","Shadow Bully","Shadow Max","Shadow Stealth","Shadow Sky","Shadow Madness","Shadow Guard"]
//for i in 0 ... 7 {
// let sm = XGTMs.tm(51 + i)
// sm.replaceWithMove(move(sms[i]))
//}
//
//for i in 0 ..< 8 {
// let cd = XGItem(index: i + 0x164)
// let sm = XGItem(index: i + 0x153)
// sm.nameID = cd.nameID
// sm.friendshipEffects = [129,129,129]
// sm.save()
//}
//
//for i in 0x1b4 ... 0x1bb {
// let item = XGItem(index: i)
// item.nameID = 0
// item.save()
//}
//let key = XGItem(index: 0x15e)
//for i in 0x153 ... 0x15a {
// let sm = XGItem(index: i)
// sm.descriptionID = key.descriptionID
// sm.save()
//}
//key.descriptionID = 0
//key.save()
//// allow stats to increase/decrease by up to 6
//let statBranch = 0x222428
//let statStart = 0x8069c + kRELtoRAMOffsetDifference
//
//XGAssembly.replaceASM(startOffset: statBranch - kDolToRAMOffsetDifference, newASM: [
// 0x9421ffe0, // stwu sp, -0x0020 (sp)
// 0x7c0802a6, // mflr r0
// 0x90010024, // stw r0, 0x0024 (sp)
// XGAssembly.createBranchAndLinkFrom(offset: statBranch + 0xc, toOffset: statStart),
// 0x80010024, // lwz r0, 0x0024 (sp)
// 0x7c0803a6, // mtlr r0
// 0x38210020, // addi sp, sp, 32
// XGAssembly.powerPCBranchLinkReturn(),kNopInstruction,
//])
//
//XGAssembly.replaceRELASM(startOffset: statStart - kRELtoRAMOffsetDifference, newASM: [
//
// 0x28030010, // cmpwi r3, +1
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x38600001, // li r3, 1
// XGAssembly.powerPCBranchLinkReturn(),
//
// 0x28030020, // cmpwi r3, +2
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x38600002, // li r3, 2
// XGAssembly.powerPCBranchLinkReturn(),
//
// 0x28030030, // cmpwi r3, +3
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x38600003, // li r3, 3
// XGAssembly.powerPCBranchLinkReturn(),
//
// 0x28030040, // cmpwi r3, +4
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x38600004, // li r3, 4
// XGAssembly.powerPCBranchLinkReturn(),
//
// 0x28030050, // cmpwi r3, +5
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x38600005, // li r3, 5
// XGAssembly.powerPCBranchLinkReturn(),
//
// 0x28030060, // cmpwi r3, +6
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x38600006, // li r3, 6
// XGAssembly.powerPCBranchLinkReturn(),
//
// 0x28030090, // cmpwi r3, -1
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x3860ffff, // li r3, -1
// XGAssembly.powerPCBranchLinkReturn(),
//
// 0x280300a0, // cmpwi r3, -2
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x3860fffe, // li r3, -2
// XGAssembly.powerPCBranchLinkReturn(),
//
// 0x280300b0, // cmpwi r3, -3
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x3860fffd, // li r3, -3
// XGAssembly.powerPCBranchLinkReturn(),
//
// 0x280300c0, // cmpwi r3, -4
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x3860fffc, // li r3, -4
// XGAssembly.powerPCBranchLinkReturn(),
//
// 0x280300d0, // cmpwi r3, -5
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x3860fffb, // li r3, -5
// XGAssembly.powerPCBranchLinkReturn(),
//
// 0x280300e0, // cmpwi r3, -6
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x3860fffa, // li r3, -6
// XGAssembly.powerPCBranchLinkReturn(),
//
// 0x38600000, // li r3, 0
// XGAssembly.powerPCBranchLinkReturn(),
//
//])
//// might help with some issues with animating custom stat boost stages which are > +2 or < -2
//let nerfBranch = 0x210ce4 - kDolToRAMOffsetDifference
//let buffBranch = 0x210cd4 - kDolToRAMOffsetDifference
//XGAssembly.replaceASM(startOffset: nerfBranch, newASM: [0x48000024])
//XGAssembly.replaceASM(startOffset: buffBranch, newASM: [0x40800024])
//var bingoMons = [XGBattleBingoPokemon]()
//for i in 0 ..< kNumberOfBingoCards {
// let card = XGBattleBingoCard(index: i)
//
// bingoMons.append(card.startingPokemon)
// for p in card.panels {
// switch p {
// case .pokemon(let poke):
// bingoMons.append(poke)
// default:
// break
// }
// }
//}
//
//
//
//let bingo : [ (XGPokemon,XGMoves,XGNatures,XGMoveTypes,Int) ] = [
// //card 1
// (pokemon("bagon"),move("dragonbreath"),.modest,.dragon,0),
// (pokemon("bulbasaur"),move("absorb"),.hardy,.grass,0),
// (pokemon("mudkip"),move("water gun"),.hardy,.water,0),
// (pokemon("chikorita"),move("absorb"),.hardy,.grass,0),
// (pokemon("cyndaquil"),move("ember"),.hardy,.fire,0),
// (pokemon("sunkern"),move("leech seed"),.hardy,.grass,0),
// (pokemon("totodile"),move("water gun"),.hardy,.water,0),
// (pokemon("charmander"),move("ember"),.adamant,.fire,0),
// (pokemon("marill"),move("draining kiss"),.hardy,.water,0),
// (pokemon("magby"),move("will-o-wisp"),.hardy,.fire,0),
// (pokemon("squirtle"),move("water gun"),.hardy,.water,0),
// (pokemon("treecko"),move("absorb"),.hardy,.grass,0),
// (pokemon("goldeen"),move("baby doll eyes"),.hardy,.water,0),
// (pokemon("torchic"),move("ember"),.hardy,.fire,0),
// //card 2
// (pokemon("magnemite"),move("shockwave"),.modest,.electric,0),
// (pokemon("machop"),move("bullet punch"),.hardy,.fighting,0),
// (pokemon("pidgey"),move("air slash"),.hardy,.flying,0),
// (pokemon("gligar"),move("bulldoze"),.hardy,.flying,0),
// (pokemon("nosepass"),move("rock tomb"),.hardy,.rock,0),
// (pokemon("makuhita"),move("ice punch"),.hardy,.fighting,0),
// (pokemon("swablu"),move("dragonbreath"),.hardy,.flying,0),
// (pokemon("anorith"),move("aerial ace"),.hardy,.rock,0),
// (pokemon("meditite"),move("zen headbutt"),.hardy,.fighting,0),
// (pokemon("lunatone"),move("psybeam"),.hardy,.rock,0),
// (pokemon("larvitar"),move("rock slide"),.hardy,.rock,0),
// (pokemon("zubat"),move("air slash"),.hardy,.flying,0),
// (pokemon("mankey"),move("power-up punch"),.hardy,.fighting,0),
// (pokemon("rhyhorn"),move("bulldoze"),.hardy,.rock,0),
// //card 3
// (pokemon("nuzleaf"),move("mega drain"),.modest,.grass,0),
// (pokemon("lanturn"),move("scald"),.hardy,.water,0), // ability 0 for volt absorb
// (pokemon("steelix"),move("iron head"),.hardy,.ground,0),
// (pokemon("magneton"),move("flash cannon"),.hardy,.electric,0),
// (pokemon("graveler"),move("bulldoze"),.hardy,.ground,0),
// (pokemon("spheal"),move("ice beam"),.hardy,.water,0),
// (pokemon("flaaffy"),move("thunderbolt"),.hardy,.electric,0),
// (pokemon("marshtomp"),move("earth power"),.hardy,.water,0),
// (pokemon("pupitar"),move("rock slide"),.hardy,.ground,0),
// (pokemon("pikachu"),move("volt tackle"),.hardy,.electric,0),
// (pokemon("manectric"),move("overheat"),.hardy,.electric,0),
// (pokemon("gyarados"),move("bounce"),.hardy,.water,0),
// (pokemon("piloswine"),move("icicle crash"),.hardy,.ground,0),
// (pokemon("lombre"),move("giga drain"),.hardy,.water,0),
// //card 4
// (pokemon("alakazam"),move("psychic"),.modest,.psychic,0),
// (pokemon("claydol"),move("psychic"),.hardy,.psychic,0),
// (pokemon("grumpig"),move("psyshock"),.modest,.psychic,0),
// (pokemon("muk"),move("gunk shot"),.hardy,.poison,0),
// (pokemon("shiftry"),move("sucker punch"),.hardy,.dark,0),
// (pokemon("sharpedo"),move("crunch"),.hardy,.dark,0),
// (pokemon("medicham"),move("drain punch"),.hardy,.psychic,0),
// (pokemon("victreebel"),move("leaf storm"),.hardy,.poison,0),
// (pokemon("metang"),move("meteor mash"),.hardy,.psychic,0),
// (pokemon("seviper"),move("sucker punch"),.adamant,.poison,0),
// (pokemon("gardevoir"),move("moonblast"),.hardy,.psychic,0),
// (pokemon("crobat"),move("brave bird"),.adamant,.poison,0),
// (pokemon("absol"),move("dark pulse"),.hardy,.dark,0),
// (pokemon("sneasel"),move("ice punch"),.hardy,.dark,0),
// //card 5
// (pokemon("sableye"),move("toxic"),.brave,.ghost,0),
// (pokemon("wigglytuff"),move("play rough"),.adamant,.normal,0),
// (pokemon("gengar"),move("sludge bomb"),.adamant,.ghost,0),
// (pokemon("misdreavus"),move("shadow ball"),.modest,.ghost,0),
// (pokemon("blaziken"),move("blaze kick"),.hardy,.fighting,0),
// (pokemon("pidgeot"),move("hurricane"),.hardy,.normal,0),
// (pokemon("machamp"),move("cross chop"),.hardy,.fighting,0),
// (pokemon("banette"),move("sucker punch"),.adamant,.ghost,0),
// (pokemon("slaking"),move("giga impact"),.brave,.normal,0),
// (pokemon("exploud"),move("boomburst"),.hardy,.normal,0),
// (pokemon("breloom"),move("sky uppercut"),.jolly,.fighting,0),
// (pokemon("dusclops"),move("destiny bond"),.hardy,.ghost,0),
// (pokemon("hariyama"),move("knock off"),.adamant,.fighting,0),
// (pokemon("zangoose"),move("night slash"),.jolly,.normal,0),
// //card 6
// (pokemon("butterfree"),move("bug buzz"),.modest,.bug,0),
// (pokemon("armaldo"),move("stone edge"),.hardy,.bug,0),
// (pokemon("beedrill"),move("poison jab"),.hardy,.bug,0),
// (pokemon("scizor"),move("bullet punch"),.timid,.bug,0),
// (pokemon("scyther"),move("air slash"),.hardy,.bug,0),
// (pokemon("heracross"),move("rock blast"),.jolly,.bug,0),
// (pokemon("parasect"),move("seed bomb"),.hardy,.bug,0),
// (pokemon("ninjask"),move("aerial ace"),.hardy,.bug,0),
// (pokemon("shedinja"),move("shadow claw"),.hardy,.bug,0),
// (pokemon("ariados"),move("sucker punch"),.adamant,.bug,0),
// (pokemon("beautifly"),move("hurricane"),.hardy,.bug,0),
// (pokemon("masquerain"),move("scald"),.hardy,.bug,0),
// (pokemon("pinsir"),move("seismic toss"),.bold,.bug,0),
// (pokemon("shuckle"),move("toxic"),.hardy,.bug,0),
// //card 7
// (pokemon("pidgeot"),move("hurricane"),.modest,.flying,0),
// (pokemon("aggron"),move("iron tail"),.hardy,.steel,0),
// (pokemon("tyranitar"),move("stone edge"),.hardy,.rock,0),
// (pokemon("steelix"),move("earthquake"),.adamant,.steel,0),
// (pokemon("sneasel"),move("brick break"),.adamant,.ice,0),
// (pokemon("regirock"),move("stone edge"),.hardy,.rock,0),
// (pokemon("golem"),move("earthquake"),.relaxed,.rock,0),
// (pokemon("skarmory"),move("iron head"),.hardy,.steel,0),
// (pokemon("glalie"),move("ice beam"),.hardy,.ice,0),
// (pokemon("rhydon"),move("drill run"),.hardy,.rock,0),
// (pokemon("regice"),move("blizzard"),.hardy,.ice,0),
// (pokemon("registeel"),move("superpower"),.hardy,.steel,0),
// (pokemon("omastar"),move("scald"),.hardy,.rock,0),
// (pokemon("lapras"),move("hydro pump"),.hardy,.ice,0),
// //card 8
// (pokemon("dragonite"),move("dragon claw"),.jolly,.dragon,0),
// (pokemon("aggron"),move("metal claw"),.adamant,.rock,0),
// (pokemon("dragonite"),move("iron tail"),.adamant,.flying,0),
// (pokemon("tyranitar"),move("stone edge"),.adamant,.rock,0),
// (pokemon("altaria"),move("disarming voice"),.hardy,.dragon,0),
// (pokemon("flygon"),move("iron tail"),.jolly,.dragon,0),
// (pokemon("sceptile"),move("dragon pulse"),.adamant,.dragon,0),
// (pokemon("latias"),move("ice beam"),.adamant,.dragon,0),
// (pokemon("feraligatr"),move("ice punch"),.adamant,.water,0),
// (pokemon("salamence"),move("aerial ace"),.adamant,.flying,0),
// (pokemon("kingdra"),move("hydro pump"),.timid,.water,0),
// (pokemon("aerodactyl"),move("stone edge"),.timid,.rock,0),
// (pokemon("latios"),move("thunderbolt"),.brave,.dragon,0),
// (pokemon("charizard"),move("dragon claw"),.adamant,.flying,0),
// //card 9
// (pokemon("slaking"),move("body slam"),.brave,.normal,0),
// (pokemon("suicune"),move("hydro pump"),.bold,.water,0),
// (pokemon("regice"),move("blizzard"),.modest,.ice,0),
// (pokemon("zapdos"),move("thunder"),.relaxed,.electric,0),
// (pokemon("entei"),move("flare blitz"),.adamant,.fire,0),
// (pokemon("metagross"),move("meteor mash"),.adamant,.steel,0),
// (pokemon("regirock"),move("stone edge"),.adamant,.rock,0),
// (pokemon("registeel"),move("iron head"),.adamant,.steel,0),
// (pokemon("moltres"),move("fire blast"),.timid,.fire,0),
// (pokemon("raikou"),move("thunder"),.jolly,.normal,0),
// (pokemon("salamence"),move("outrage"),.brave,.dragon,0),
// (pokemon("tyranitar"),move("stone edge"),.impish,.rock,0),
// (pokemon("dragonite"),move("dragon claw"),.jolly,.dragon,0),
// (pokemon("articuno"),move("blizzard"),.timid,.ice,0),
// //card 10
// (pokemon("mew"),move("psychic"),.modest,.psychic,0),
// (pokemon("kyogre"),move("surf"),.modest,.water,0),
// (pokemon("mew"),move("sucker punch"),.adamant,.psychic,0),
// (pokemon("latias"),move("draco meteor"),.modest,.dragon,0),
// (pokemon("lugia"),move("aeroblast"),.hasty,.flying,0),
// (pokemon("groudon"),move("stone edge"),.adamant,.ground,0),
// (pokemon("mew"),move("ice beam"),.modest,.psychic,0),
// (pokemon("celebi"),move("leaf storm"),.modest,.psychic,0),
// (pokemon("latios"),move("dracometeor"),.modest,.dragon,0),
// (pokemon("jirachi"),move("iron head"),.adamant,.psychic,0),
// (pokemon("ho-oh"),move("sacred fire"),.hasty,.flying,0),
// (pokemon("rayquaza"),move("outrage"),.adamant,.dragon,0),
// (pokemon("mewtwo"),move("psystrike"),.modest,.psychic,0),
// (pokemon("deoxys"),move("psychoboost"),.modest,.psychic,0),
// //card 11
// (pokemon("bonsly"),move("stone edge"),.adamant,.rock,0),
// (pokemon("vulpix"),move("fire blast"),.modest,.fire,0),
// (pokemon("shroomish"),move("wood hammer"),.adamant,.grass,0),
// (pokemon("poliwag"),move("hydro pump"),.modest,.water,0),
// (pokemon("dratini"),move("draco meteor"),.modest,.dragon,0),
// (pokemon("mareep"),move("thunder"),.modest,.electric,0),
// (pokemon("snorunt"),move("blizzard"),.modest,.ice,0),
// (pokemon("phanpy"),move("earthquake"),.adamant,.ground,0),
// (pokemon("poochyena"),move("sucker punch"),.adamant,.dark,0),
// (pokemon("taillow"),move("brave bird"),.adamant,.flying,0),
// (pokemon("whismur"),move("boomburst"),.modest,.normal,0),
// (pokemon("tyrogue"),move("superpower"),.adamant,.fighting,0),
// (pokemon("grimer"),move("gunk shot"),.adamant,.poison,0),
// (pokemon("abra"),move("psychic"),.modest,.psychic,0)
//
//]
//
//for j in 0 ..< bingo.count {
// let mon = bingoMons[j]
// let nw = bingo[j]
//
// mon.species = nw.0
// mon.move = nw.1
// mon.nature = nw.2
// mon.typeOnCard = nw.3 == mon.species.type1 ? 0 : 1
// mon.ability = nw.4
//
// mon.save()
//}
//let names = ["Starter Card", "Match-Up Card", "Mix-Up Card", "Edgy Card", "Immunity Card", "Bug Card", "Solid Card", "Dragon Card", "Legend Card", "Myth Card", "Bonsly Card"]
//let descs = ["A simple Card for learning the rules.",
// "Watch out for unexpected match-ups!",
// "This one will try to trick you.",
// "Type advantage isn't a guarantee.",
// "Good luck landing any hits...",
// "No strategy here. Are you adaptable?",
// "Your starter is no good. Get Catching!",
// "All strong but which have the best moves?",
// "Legendary pokemon come out to play!",
// "Can you handle the strongest pokemon?",
// "Little pokemon with big moves."]
//
//for i in 0 ..< CommonIndexes.NumberOfBingoCards.value {
// let card = XGBattleBingoCard(index: i)
// print("Bingo Card \(i)")
// getStringSafelyWithID(id: card.detailsID).duplicateWithString("[07]{01}" + descs[i]).replace()
// getStringSafelyWithID(id: card.nameID).duplicateWithString(names[i]).replace()
//}
//let earthquakeStart = 0x4158fb - kDolTableToRAMOffsetDifference
//let earthquakeRoutine = [
//
// // intro 0x4158fb
// 0x00, 0x32, 0x80, 0x22, 0x0a, 0x17, 0x80, 0x4e, 0x85, 0xc3, 0x1, 0x02, 0x3b,
//
// // next target 0x415908
// 0xc2,
//
// // reset 0x415909
// 0x26,
// 0x32, 0x80, 0x4e, 0x85, 0xc3, 0x80, 0x22, 0x0a, 0x17, 0x1,
//
// // check if should work and check accuracy 0x415914
// 0x00, 0x01, 0x80, 0x41, 0x59, 0x8e, 0x00, 0x00,
// 0x29, 0x80, 0x41, 0x59, 0x34,
//
// // filler 0x415922
// 0x00, 0x00, 0x00, 0x00, 0x00,
// 0x00, 0x00, 0x00, 0x00, 0x00,
// 0x00, 0x00, 0x00, 0x00, 0x00,
// 0x00, 0x00, 0x00, 0x00,
//
// // set damage multiplier to 1 0x415934
// 0x39, 0x80, 0x4e, 0xb9, 0x38, 0x00, 0x02, 0x00, 0x00,
// 0x2f, 0x80, 0x4e, 0xb9, 0x5e, 0x01,
//
// // start move 0x415943
// 0xfc, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x39, 0x00, 0x00, 0x00, 0x00, 0x80, 0x4e, 0xb9, 0x5e,
//
// // start damage routine 0x415957
// 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, // filler
// 0x05, 0x06, 0x07, 0x08, // calcs
// 0x0a, 0x0b, 0x00, // animations
// 0x0f, 0x5d, 0x12, 0x3b, 0x0c, 0x12, 0x0e, 0x13, 0x00, 0x40, 0x10, 0x13, 0x00, 0x50, // messages
// 0x0d, 0x12, 0x0b, 0x04, 0x1a, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, // animations 2
// 0x2f, 0x80, 0x4e, 0xb9, 0x47, 0x00, 0x16, 0x4a, 0x02, 0x10, // after move
// 0x7c, 0x80, 0x41, 0x59, 0x09, 0x01, // jump while valid target
// 0x04, 0x3e, // end move
//
// // attack missed 0x41598e
// 0x3a, 0x00, 0x20, 0x07, 0x46, 0x12, 0x17, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x10, 0x13, 0x00, 0x50, 0x0b, 0x04, 0x2f, 0x80, 0x4e, 0xb9, 0x47, 0x00, 0x4a, 0x02, 0x10, 0x7c, 0x80, 0x41, 0x59, 0x09, 0x01, 0x3e,]
//
//let dol = XGFiles.dol.data!
//dol.replaceBytesFromOffset(earthquakeStart, withByteStream: earthquakeRoutine)
//dol.save()
//// new uturn routine using update jump if status so volt switch won't trigger on ground types
//let uturnRoutine = XGAssembly.routineRegularHitOpenEnded() + [
// // baton pass routine
// 0x77, 0x11, 0x07, 0x51, 0x11, 0x80, 0x41, 0x5c, 0xb4, 0xe1, 0x11, 0x3b, 0x52, 0x11, 0x02, 0x59, 0x11, 0x4d, 0x11,
// 0x4e, 0x11, 0x02, // 0x02 prevents passing statuses effect from baton pass (use 0x01 if you want the effect)
// 0x74, 0x11, 0x14, 0x80, 0x2f, 0x90, 0xe0, 0x4f, 0x11, 0x01, 0x13, 0x00, 0x00, 0x3b, 0x53, 0x11, 0x3b, 0x3e,
//]
//let uturnOffset = 0xB9B634
//XGAssembly.setMoveEffectRoutine(effect: 57, fileOffset: uturnOffset - kRELtoRAMOffsetDifference, moveToREL: true, newRoutine: uturnRoutine)
//
//// dragon tail
//let dragonTailRoutine = XGAssembly.routineRegularHitOpenEnded() + [
// // roar routine
// 0x1f, 0x12, 0x15, 0x80, 0x41, 0x7a, 0x7f,
// 0x90, 0x80, 0x41, 0x5c, 0xb4,
//]
//// use this one to remove suction cups as an ability
//let dragonTailRoutine2 = XGAssembly.routineRegularHitOpenEnded() + [
// // roar
// 0x90, 0x80, 0x41, 0x5c, 0xb4,
//]
//
//let dragontailOffset = 0xB9B7D0
//XGAssembly.setMoveEffectRoutine(effect: move("dragon tail").data.effect, fileOffset: dragontailOffset - kRELtoRAMOffsetDifference, moveToREL: true, newRoutine: dragonTailRoutine2)
//
//let shadowAnalysisRoutine = XGAssembly.routineRegularHitOpenEnded() + [0xa4, 0x80, 0x41, 0x5c, 0xb4, 0x11, 0x00, 0x00, 0x4e, 0xa0, 0x13, 0x00, 0x60, 0x0b, 0x04, 0x29, 0x80, 0x41, 0x41, 0x0f,]
//let analysisOffset = 0xB9B81C
//XGAssembly.setMoveEffectRoutine(effect: move("shadow analysis").data.effect, fileOffset: analysisOffset - kRELtoRAMOffsetDifference, moveToREL: true, newRoutine: shadowAnalysisRoutine)
//
//let shadowGiftRoutine = [0x00, 0x02, 0x04, 0x50, 0x11, 0x80, 0x41, 0x5c, 0x93, 0x00, 0x0a, 0x0b, 0x04, 0x77, 0x11, 0x07, 0x51, 0x11, 0x80, 0x41, 0x5c, 0x93, 0xe1, 0x11, 0x3b, 0x52, 0x11, 0x02, 0x59, 0x11, 0x4d, 0x11, 0x4e, 0x11, 0x01, 0x74, 0x11, 0x14, 0x80, 0x2f, 0x90, 0xe0, 0x4f, 0x11, 0x01, 0x13, 0x00, 0x00, 0x3b, 0x53, 0x11,
//// branch cosmic power boosts
//0x29, 0x80, 0x41, 0x66, 0x8d,]
//
//let skillSwap = [0x00, 0x02, 0x04, 0x01, 0x80, 0x41, 0x5c, 0x93, 0xff, 0xff, 0xd9, 0x80, 0x41, 0x5c, 0x93, 0x0a, 0x0b, 0x04, 0x0a, 0x0b, 0x00, 0x11, 0x00, 0x00, 0x4e, 0xd2, 0x13, 0x00, 0x60, 0x0b, 0x04, 0x53, 0x11, 0x53, 0x12, 0x29, 0x80, 0x41, 0x41, 0x0f,]
//
//
//
//let shadowFreezeRoutine = [0x00, 0x02, 0x04, 0x1e, 0x12, 0x00, 0x00, 0x00, 0x14, 0x80, 0x41, 0x5c, 0x93, 0x1d, 0x12, 0x00, 0x00, 0x00, 0x07, 0x80, 0x41, 0x5e, 0xb9, 0x23, 0x12, 0x0f, 0x80, 0x41, 0x5c, 0xc6, 0x1f, 0x12, 0x28, 0x80, 0x41, 0x5e, 0x81, 0x3b, 0x12, 0x2f, 0x80, 0x41, 0x5e, 0x81, 0x1f, 0x12, 0x31, 0x80, 0x41, 0x5e, 0x81, 0x1d, 0x12, 0x00, 0x00, 0x00, 0x01, 0x80, 0x41, 0x5c, 0x93, 0x01, 0x80, 0x41, 0x5c, 0x93, 0x00, 0x00, 0x20, 0x12, 0x00, 0x4b, 0x80, 0x41, 0x6d, 0xb2, 0x0a, 0x0b, 0x04, 0x2f, 0x80, 0x4e, 0x85, 0xc3, 0x04, 0x17, 0x0b, 0x04, 0x29, 0x80, 0x41, 0x41, 0x0f,]
//
// without magma armour
////let shadowFreezeRoutine = [0x00, 0x02, 0x04, 0x1e, 0x12, 0x00, 0x00, 0x00, 0x14, 0x80, 0x41, 0x5c, 0x93, 0x1d, 0x12, 0x00, 0x00, 0x00, 0x07, 0x80, 0x41, 0x5e, 0xb9, 0x23, 0x12, 0x0f, 0x80, 0x41, 0x5c, 0xc6, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x1f, 0x12, 0x2f, 0x80, 0x41, 0x5e, 0x81, 0x1f, 0x12, 0x31, 0x80, 0x41, 0x5e, 0x81, 0x1d, 0x12, 0x00, 0x00, 0x00, 0x01, 0x80, 0x41, 0x5c, 0x93, 0x01, 0x80, 0x41, 0x5c, 0x93, 0x00, 0x00, 0x20, 0x12, 0x00, 0x4b, 0x80, 0x41, 0x6d, 0xb2, 0x0a, 0x0b, 0x04, 0x2f, 0x80, 0x4e, 0x85, 0xc3, 0x04, 0x17, 0x0b, 0x04, 0x29, 0x80, 0x41, 0x41, 0x0f,]
//
//let routines : [(effect: Int, routine: [Int], offset: Int)] = [
//
// (28,dragonTailRoutine, 0xb99524),
// (57, uturnRoutine, 0xb9a670),
// (213, shadowGiftRoutine, 0xb995c2),
// (191, skillSwap, 0xb995fa),
// (122, shadowAnalysisRoutine, 0xb99622),
//
// (55, XGAssembly.routineForMultipleStatBoosts(RAMOffset: 0x80b9966a, boosts: [(stat: XGStats.accuracy, stages: XGStatStages.plus_1), (stat: XGStats.attack, stages: XGStatStages.plus_1)], isSecondaryEffect: false), 0xb9966a), // hone claws
//
// (56, XGAssembly.routineForMultipleStatBoosts(RAMOffset: 0x80b996d4, boosts: [(stat: XGStats.special_attack, stages: XGStatStages.plus_1), (stat: XGStats.special_defense, stages: XGStatStages.plus_1), (stat: XGStats.speed, stages: XGStatStages.plus_1)], isSecondaryEffect: false), 0xb996d4), // quiver dance
//
// (61, XGAssembly.routineForMultipleStatBoosts(RAMOffset: 0x80b99766, boosts: [(stat: XGStats.attack, stages: XGStatStages.plus_1), (stat: XGStats.defense, stages: XGStatStages.plus_1), (stat: XGStats.accuracy, stages: XGStatStages.plus_1)], isSecondaryEffect: false), 0xb99766), // coil
//
// (135, XGAssembly.routineForMultipleStatBoosts(RAMOffset: 0x80b997f8, boosts: [(stat: XGStats.speed, stages: XGStatStages.plus_1), (stat: XGStats.evasion, stages: XGStatStages.plus_1),], isSecondaryEffect: false), 0xb997f8), // shadow haste
//
// (203, XGAssembly.routineForMultipleStatBoosts(RAMOffset: 0x80b99862, boosts: [(stat: XGStats.attack, stages: XGStatStages.plus_1), (stat: XGStats.speed, stages: XGStatStages.plus_2),], isSecondaryEffect: false), 0xb99862), // shift gear
//
// (154, XGAssembly.routineForMultipleStatBoosts(RAMOffset: 0x80b998cc, boosts: [(stat: XGStats.attack, stages: XGStatStages.plus_1), (stat: XGStats.accuracy, stages: XGStatStages.plus_2),], isSecondaryEffect: false), 0xb998cc), // shadow focus
//
// (74, XGAssembly.routineForMultipleStatBoosts(RAMOffset: 0x80b99936, boosts: [(stat: XGStats.attack, stages: XGStatStages.plus_2), (stat: XGStats.special_attack, stages: XGStatStages.plus_2), (stat: XGStats.speed, stages: XGStatStages.plus_2), (stat: XGStats.defense, stages: XGStatStages.minus_1), (stat: XGStats.special_defense, stages: XGStatStages.minus_1)], isSecondaryEffect: false), 0xb99936), // shell smash
//
// (163, XGAssembly.routineForMultipleStatBoosts(RAMOffset: 0x80b99a06, boosts: [(stat: XGStats.attack, stages: XGStatStages.plus_1), (stat: XGStats.defense, stages: XGStatStages.plus_1), (stat: XGStats.speed, stages: XGStatStages.plus_1), (stat: XGStats.special_attack, stages: XGStatStages.plus_1), (stat: XGStats.special_defense, stages: XGStatStages.plus_1)], isSecondaryEffect: false), 0xb99a06), // latent power
//
// (145, XGAssembly.routineForMultipleStatBoosts(RAMOffset: 0x80b99ae8, boosts: [(stat: XGStats.evasion, stages: XGStatStages.minus_1), (stat: XGStats.special_defense, stages: XGStatStages.plus_3)], isSecondaryEffect: false), 0xb99ae8), // shadow barrier
//
// (63, XGAssembly.routineForSingleStatBoost(stat: .defense, stages: .plus_3), 0xb99b49), // cotton guard
//
// (64, XGAssembly.routineForSingleStatBoost(stat: .special_attack, stages: .plus_3), 0xb99b54), // tail glow
//
// (96, XGAssembly.routineHitWithSecondaryEffect(effect: 0x51), 0xb99b5f), // flame charge
//
// (110, XGAssembly.routineHitWithSecondaryEffect(effect: 0xd8), 0xb99b70), // hammer arm
//
// (131, XGAssembly.routineHitAndStatChange(routineOffsetRAM: 0x80b99b7b, boosts: [(stat: XGStats.defense, stages: XGStatStages.minus_1), (stat: XGStats.special_defense, stages: XGStatStages.minus_1)]), 0xb99b7b), // close combat
//
// (184, XGAssembly.routineHitAndStatChange(routineOffsetRAM: 0x80b99c01, boosts: [(stat: XGStats.defense, stages: XGStatStages.minus_1), (stat: XGStats.special_defense, stages: XGStatStages.minus_1), (stat: XGStats.speed, stages: XGStatStages.minus_1)]), 0xb99c01), // v-create
//
// (141, XGAssembly.routineHitWithSecondaryEffect(effect: 0x52), 0xb99ca6), // charge beam
//
// (93, XGAssembly.routineHitAllWithSecondaryEffect(effect: 0x18), 0xb99cb7), // bulldoze
//
// (34, XGAssembly.routineHitAllWithSecondaryEffect(effect: 0x03), 0xb99cc8), // lava plume
//
// (81, XGAssembly.routineHitAllWithSecondaryEffect(effect: 0x05), 0xb99cd3), // discharge
//
// (88, XGAssembly.routineHitAllWithSecondaryEffect(effect: 0x02), 0xb99cde), // sludge wave
//
// (162, shadowFreezeRoutine, 0xb99ce9), // shadow freeze
//
//]
//
////var currentOffset = XGAssembly.ASMfreeSpacePointer()
//for routine in routines {
//
//// // run first to generate offsets
//// print("effect \(routine.effect) - \(currentOffset.hexString())")
//// currentOffset += routine.routine.count
//
// // fill in offsets then run this to actually add them
// XGAssembly.setMoveEffectRoutine(effect: routine.effect, fileOffset: routine.offset - kDOLtoRAMOffsetDifference, moveToREL: false, newRoutine: routine.routine)
//
//}
//// make orre colosseum 6 vs. 6
//for offset in [0x0a1d48, 0x0a1d94] {
// XGAssembly.replaceASM(startOffset: offset - kDolToRAMOffsetDifference, newASM: [0x28000000])
//}
//XGAssembly.replaceASM(startOffset: 0x0a183c - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: 0x0a183c, toOffset: 0x0a1d24)])
//for b in 87 ... 114 {
// let battle = XGBattle(index: b)
// battle.pokemonPerPlayer = 6
// battle.save()
//}
//// shadow pokemon can't be battled after being captured 2
//// remove old shadow generation code
//XGAssembly.replaceASM(startOffset: 0x1fabf0 - kDolToRAMOffsetDifference, newASM: [0x7f03c378])
//let checkCaught = 0x14b024 - kDolToRAMOffsetDifference
//let checkPurified = 0x14b058 - kDolToRAMOffsetDifference
//
//let shadowBattleBranch2 = 0x1faa90 - kDolToRAMOffsetDifference
//let shadowBattleStart2 = 0x220f10 - kDolToRAMOffsetDifference
//// r20 stored shadow data start
////
//XGAssembly.replaceASM(startOffset: shadowBattleBranch2, newASM: [
// XGAssembly.createBranchFrom(offset: shadowBattleBranch2, toOffset: shadowBattleStart2),
// ])
//XGAssembly.replaceASM(startOffset: shadowBattleStart2, newASM: [
//
// 0x7c741b78, // mr r20, r3 overwritten code
//
// // exclude greevil's shadow pokemon ids (decimal 0x4a - 0x4f)
// 0x281A004a, // cmpwi r26, 0x4a
// XGAssembly.powerPCBranchLessThanFromOffset(from: 0x0, to: 0x10), // blt check generate
// 0x281A0050, // cmpwi r26, 0x50
// XGAssembly.powerPCBranchGreaterThanOrEqualFromOffset(from: 0x0, to: 0x8), // bgteq check generate
// XGAssembly.createBranchFrom(offset: 0x14, toOffset: 0x40), //---- normal exec
//
// // check should generate 0x18
//
// // check if shadow id has been caught
// 0x7e83a378, // mr r3, r20
// XGAssembly.createBranchAndLinkFrom(offset: shadowBattleStart2 + 0x1c, toOffset: checkCaught),
// 0x5460063f, //rlwinm. r0, r3, 0, 24, 31 (000000ff)
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x24, to: 0x38), // don't generate
//
// // also need to check if shadow id has been purified in case those don't fall under caught
// 0x7e83a378, // mr r3, r20
// XGAssembly.createBranchAndLinkFrom(offset: shadowBattleStart2 + 0x2c, toOffset: checkPurified),
// 0x5460063f, //rlwinm. r0, r3, 0, 24, 31 (000000ff)
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x34, to: 0x40), // normal exec
//
// // don't generate 0x38
// 0x3B200000, // li r25, 0
// 0x3B400000, // li r26, 0
//
// // return to normal execution 0x40
// 0x7f43d378, // mr r3, r26 (overwritten code)
// XGAssembly.createBranchFrom(offset: shadowBattleStart2 + 0x44, toOffset: shadowBattleBranch2 + 0x4)// branch back
// ])
//// wild battles for groudon, kyogre and rayquaza
//let wildbattle = XGBattle(index: 9)
//let wild = wildbattle.trainer!
//let fields = [104,182,163]
//for index in 212 ... 214 {
// let trainer = XGTrainer(index: index, deck: .DeckStory)
// let battle = XGBattle.battleForTrainer(index: index, deck: .DeckStory)!
// trainer.nameID = wild.nameID
// trainer.trainerModel = wild.trainerModel
// trainer.trainerClass = wild.trainerClass
// trainer.cameraEffects = wild.cameraEffects
// trainer.save()
//
// battle.BGMusicID = 1252
// battle.battleField = XGTrainer(index: fields[index - 212], deck: .DeckStory).battleData?.battleField
// battle.battleStyle = XGBattleStyles.single
// battle.setToWildPokemon()
// battle.save()
//}
//let relk = XGMapRel(file: .rel("M1_water_colo_field.rel"))
//let kyogre = relk.characters[6]
//kyogre.characterID = 0
//kyogre.model = XGCharacterModel(index: 42)
//kyogre.xCoordinate = 0.0
//kyogre.yCoordinate = 0.0
//kyogre.zCoordinate = 0.0
//kyogre.angle = 0
//kyogre.movementType = XGCharacterMovements.index(0x10)
//kyogre.save()
//let relg = XGMapRel(file: .rel("D6_fort_3F_1.rel"))
//let groudon = relg.characters[3]
//groudon.characterID = 0
//groudon.model = XGCharacterModel(index: 103)
//groudon.xCoordinate = 75.0
//groudon.yCoordinate = 0
//groudon.zCoordinate = 11.9
//groudon.angle = 0
//groudon.movementType = XGCharacterMovements.index(0x10)
//groudon.scriptIndex = 11
//groudon.save()
//let relr = XGMapRel(file: .rel("D5_factory_top.rel"))
//let rayquaza = relr.characters[0]
//rayquaza.characterID = 0
//rayquaza.model = XGCharacterModel(index: 41)
//rayquaza.xCoordinate = -79.0
//rayquaza.yCoordinate = 29.99
//rayquaza.zCoordinate = 118.0
//rayquaza.angle = 0
//rayquaza.movementType = XGCharacterMovements.index(0x10)
//rayquaza.save()
//let models = ["mewtwo", "suicune", "entei", "raikou", "rayquaza", "kyogre", "groudon"]
//let indices = [52,53,54,55,56,57,132]
//let anims = [0,0,0,0,0,0,2]
//let archive = XGFiles.fsys("people_archive.fsys").fsysData
//
//for i in 0 ..< models.count {
// let model = XGFiles.nameAndFolder(models[i] + "_ow.dat", .TextureImporter)
// copyOWPokemonIdleAnimationFromIndex(index: anims[i], forModel: model)
// archive.shiftAndReplaceFileWithIndex(indices[i], withFile: model.compress())
// let modelData = XGCharacterModel(index: i)
// modelData.boundBox = [22.00, 52.00, 8.00, -300.00, 300.00, -120.00, 120.00, 6.00]
// modelData.save()
//}
//archive.save()
//XGISO().shiftAndReplaceFile(archive.file)
//let wildbattle = XGBattle(index: 9)
//let wild = wildbattle.trainer!
//wildbattle.rawData.byteString.println()
//let fields = [330,217,441]
//for index in 209 ... 211 {
// let trainer = XGTrainer(index: index, deck: .DeckStory)
// let battle = XGBattle.battleForTrainer(index: index, deck: .DeckStory)!
// trainer.nameID = wild.nameID
// trainer.trainerModel = wild.trainerModel
// trainer.trainerClass = wild.trainerClass
// trainer.cameraEffects = wild.cameraEffects
// trainer.save()
//
// battle.BGMusicID = 1252
// battle.battleField = XGBattle(index: fields[index - 209]).battleField
// battle.battleStyle = XGBattleStyles.single
// battle.setToWildPokemon()
// battle.save()
//}
//let rel = XGMapRel(file: .rel("D5_out.rel"))
//let raikou = rel.characters[10]
//raikou.characterID = 0
//raikou.model = XGCharacterModel(index: 40)
//raikou.scriptIndex = 7
//raikou.zCoordinate = -160
//raikou.save()
//let rel = XGMapRel(file: .rel("D3_ship_deck.rel"))
//let entei = rel.characters[5]
//entei.characterID = 0
//entei.model = XGCharacterModel(index: 39)
//entei.xCoordinate = 0
//entei.save()
//let rel = XGMapRel(file: .rel("M1_out.rel"))
//let suicune = rel.characters[13]
//suicune.characterID = 0
//suicune.model = XGCharacterModel(index: 38)
//suicune.xCoordinate = 0.0
//suicune.yCoordinate = 66.04
//suicune.zCoordinate = -210.0
//suicune.scriptIndex = 19
//suicune.save()
//let jiji = rel.characters[10]
//jiji.xCoordinate = 0.0
//jiji.yCoordinate = 66.04
//jiji.zCoordinate = -170.0
//jiji.save()
//let boy = rel.characters[11]
//boy.scriptIndex = 21
//boy.save()
//let seedot = rel.characters[30]
//let jiji2 = rel.characters[29]
//seedot.xCoordinate = -14.0
//seedot.yCoordinate = 34.0
//seedot.zCoordinate = -110
//jiji2.xCoordinate = -14.0
//jiji2.yCoordinate = 34.0
//jiji2.zCoordinate = -115
//seedot.save()
//jiji.save()
//let newItems : [(index: Int, name: String, quantity: Int)] = [
// (8,"TM11",1), // wisp
// (1,"TM41",1), // toxic
// (20,"TM03",1), // u-turn
// (96,"TM21",1), // zen headbutt
// (32,"TM36",1), // x-scissor
// (99,"TM44",1), // night slash
// (94,"TM07",1), // foul play
// (5,"TM19",1), // sludgebomb
// (108,"TM48",1), // stone edge
// (64,"TM02",1), // fire blast
// (59,"TM23",1), // dragon pulse
// (27,"TM22",1), // discharge
// (87,"TM39",1), // waterfall
// (52,"TM40",1), // dragon claw
// (29,"TM08",1), // flash cannon
// (12,"TM06",1), // dazzling gleam
// (90,"TM18",1), // freeze dry
// (40,"TM04",1), // hurricane
// (39,"TM34",1), // solar beam
// (31,"timer ball",3),
// (34,"thick club",1),
//]
//
//for (index, name, quantity) in newItems {
// let treasure = XGTreasure(index: index)
// treasure.itemID = item(name).index
// treasure.quantity = quantity
// treasure.save()
//}
//getStringSafelyWithID(id: 34076).duplicateWithString("[Speaker]: Rooooaaaaarrr!![Dialogue End]").replace()
//getStringSafelyWithID(id: 34077).duplicateWithString("[Speaker]: I think that was...[Clear Window]a Raikou![Dialogue End]").replace()
//getStringSafelyWithID(id: 34078).duplicateWithString("[Speaker]: I'm not lying. I swear![New Line]I saw it.[New Line]It ran away but maybe[New Line]it will probably return soon.[Clear Window][Speaker]: Hmm...[New Line]I wonder if the other two[New Line]legendary beasts are around Orre too![Dialogue End]").replace()
//getStringSafelyWithID(id: 34079).duplicateWithString("[Speaker]: I wonder if he really[New Line]saw a legendary pokémon.[Clear Window][Speaker]: They rarely stay still so[New Line]they're hard to catch[New Line]but maybe if you come back later...[Clear Window]Nah, forget it.[Clear Window]A little kid like you[New Line]can't catch a legendary pokémon![Dialogue End]").replace()
//XGAssembly.replaceASM(startOffset: 0x1faf50 - kDolToRAMOffsetDifference, newASM: [0x280a0032]) // compare with 50 pokespot entries so that "cave" runs into "all" where the static encounters are stored
//
// hard code ow wild pokemon for each map
//let owMonStart = 0x1fae4c
//let owCodeStart = 0xB99D48
//let owReturn = 0x1fae88
//XGAssembly.replaceASM(startOffset: owMonStart - kDolToRAMOffsetDifference, newASM: [
// 0x2c170039, // cmpwi r23, esaba A
// 0x41820018, // beq
// 0x2c17003b, // cmpwi r23, esaba C
// 0x41820020, // beq
// 0x3b600002, // li r27, 2
// XGAssembly.createBranchFrom(offset: owMonStart + 0x14, toOffset: owCodeStart), // load species into r0
// kNopInstruction,
//])
//XGAssembly.replaceRELASM(startOffset: owCodeStart - kRELtoRAMOffsetDifference, newASM: [
// 0x2c17002d, // cmpwi r23, D5 out
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x380000f3, // li r0, raikou
// 0x2c17002a, // cmpwi r23, D3_ship_deck
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x380000f4, // li r0, entei
// 0x2c170007, // cmpwi r23, M1_out
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x380000f5, // li r0, suicune
// 0x2c170000, // cmpwi r23, -
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x38000194, // li r0, kyogre
// 0x2c170000, // cmpwi r23, -
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x38000195, // li r0, groudon
// 0x2c170000, // cmpwi r23, -
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x38000196, // li r0, rayquaza
// 0x2c170000, // cmpwi r23, -
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x38000096, // li r0, mewtwo
//
// // for future expansion
// 0x2c170000, // cmpwi r23, -
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x38000000, // li r0, --
// 0x2c170000, // cmpwi r23, -
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x38000000, // li r0, -
// 0x2c170000, // cmpwi r23, -
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x38000000, // li r0, --
// 0x2c170000, // cmpwi r23, -
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x38000000, // li r0, --
// 0x2c170000, // cmpwi r23, -
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x38000000, // li r0, --
// kNopInstruction,
// kNopInstruction,
//
// XGAssembly.createBranchFrom(offset: owCodeStart + 0x98, toOffset: owReturn),
//
// ])
//
//XGPokeSpots.all.setEntries(entries: 15)
//// sitrus berry
//let sitrusBranch = 0x223efc
//let sitrusStart = 0xB9A018
//
//let getHPFraction = 0x203688
//let sitrusCode : ASM = [
//
// 0x281b00fc, // cmpwi r27, 0xfd
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x1c),
// 0x7fe3fb78, // mr r3, r31
// 0x38800004, // li r4, 4
// XGAssembly.createBranchAndLinkFrom(offset: sitrusStart + 0x10, toOffset: getHPFraction),
// 0x7c601b78, // mr r0, r3
// 0x7c1b0378, // mr r27, r0
// XGAssembly.createBranchFrom(offset: 0x0, toOffset: 0x20),
// 0x281b00fe, // cmpwi r27, 0xfe
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x18),
// 0x7fe3fb78, // mr r3, r31
// 0x38800002, // li r4, 2
// XGAssembly.createBranchAndLinkFrom(offset: sitrusStart + 0x30, toOffset: getHPFraction),
// 0x7c601b78, // mr r0, r3
// 0x7c1b0378, // mr r27, r0
//
// 0x57a3043e, // rlwinm r3, r29, 0, 16, 31 (0000ffff) overwritten code
// XGAssembly.createBranchFrom(offset: sitrusStart + 0x40, toOffset: sitrusBranch + 0x4)
//]
//
//XGAssembly.replaceASM(startOffset: sitrusBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: sitrusBranch, toOffset: sitrusStart)])
//XGAssembly.replaceRELASM(startOffset: sitrusStart - kRELtoRAMOffsetDifference, newASM: sitrusCode)
//
//let sb = item("sitrus berry").data
//sb.parameter = 0xfd
//sb.save()
//// wide guard
//let wideGuardBranchLinks = [0x218204, 0x218184]
//let wideGuardStart = 0xb99de4
//
//for offset in wideGuardBranchLinks {
// XGAssembly.replaceASM(startOffset: offset - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchAndLinkFrom(offset: offset, toOffset: wideGuardStart), 0x28030001])
//}
//
//let getPokemonPointer = 0x1efcac
//let getFieldEffect = 0x1f84e0
//let getCurrentMove = 0x148d64
//let getMoveTargets = 0x13e784
//
//let wideEndOffset = 0x78
//
//XGAssembly.replaceRELASM(startOffset: wideGuardStart - kRELtoRAMOffsetDifference, newASM: [
// // allow blr
// 0x9421ffe0, // stwu sp, -0x0020 (sp)
// 0x7c0802a6, // mflr r0
// 0x90010024, // stw r0, 0x0024 (sp)
// 0xbfa10014, // stmw r29, 0x0014 (sp) (just in case I wanted to use r29 for something)
//
// // check regular protect
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
//
// // regular protect so go to end
// 0x38600001, // li r3, 1
// XGAssembly.createBranchFrom(offset: 0x1c, toOffset: wideEndOffset),
//
// // no regular protect so check wide guard
//
// // get field pointer
// 0x7fc3f378, // mr r3, r30
// 0x7c641b78, // mr r4, r3
// 0x38600002, // li r3, 2
// XGAssembly.createBranchAndLinkFrom(offset: wideGuardStart + 0x2c, toOffset: getPokemonPointer),
//
// // check wide guard
// 0x3880004d, // li r4, 77
// XGAssembly.createBranchAndLinkFrom(offset: wideGuardStart + 0x34, toOffset: getFieldEffect),
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0xc),
// 0x38600000, // li r3, 0
// XGAssembly.createBranchFrom(offset: 0x44, toOffset: wideEndOffset),
//
// // check current move target
// 0x38600011, // li r3, 17
// 0x38800000, // li r4, 0
// XGAssembly.createBranchAndLinkFrom(offset: wideGuardStart + 0x50, toOffset: getPokemonPointer),
// XGAssembly.createBranchAndLinkFrom(offset: wideGuardStart + 0x54, toOffset: getCurrentMove),
// XGAssembly.createBranchAndLinkFrom(offset: wideGuardStart + 0x58, toOffset: getMoveTargets),
// 0x28030006, // cmpwi r3, both foes and ally
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0xc),
// 0x28030004, // cmpwi r3, both foes
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
// 0x38600001, // li r3, 1
// XGAssembly.createBranchFrom(offset: 0x0, toOffset: 0x8),
// 0x38600000, // li r3, 0
//
// // wide end 0x78
// 0xbba10014, // lmw r29, 0x0014 (sp)
// 0x80010024, // lwz r0, 0x0024 (sp)
// 0x7c0803a6, // mtlr r0
// 0x38210020, // addi sp, sp, 32
// XGAssembly.powerPCBranchLinkReturn()
//
//])
//let dol = XGFiles.dol.data!
//
//let spreadAbsorbedStart = 0x2209f8 - kDolToRAMOffsetDifference
//let spreadA : UInt32 = 0x8022
//let spreadB : UInt32 = 0x09f8
//let spreadC : UInt32 = 0x0000
//let spreadMoveAbsorbedRoutine = [0x3A, 0x00, 0x20, 0x46, 0x12, 0x17, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x11, 0x00, 0x00, 0x4E, 0xFC, 0x78, 0x12, 0x13, 0x00, 0x50, 0x0B, 0x04, 0x29, 0x80, 0x41, 0x59, 0xa8, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00]
//
//dol.replaceBytesFromOffset(spreadAbsorbedStart, withByteStream: spreadMoveAbsorbedRoutine)
//dol.save()
//
//let spreadCheckStart = 0x2209a4 - kDolToRAMOffsetDifference
//let spreadCheckBranch = 0x22586c - kDolToRAMOffsetDifference
//let getTargets = 0x13e784 - kDolToRAMOffsetDifference
//
//let spreadCode : ASM = [
// 0x7fe3fb78, // mr r3, r31 (move)
// XGAssembly.createBranchAndLinkFrom(offset: spreadCheckStart + 0x4, toOffset: getTargets),
// 0x28030006, // cmpwi r3, both foes and ally
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x14),
// 0x3c600000 + spreadA, // lis r3, spread a
// 0x38630000 + spreadB, // addi r3, r3, spread b
// 0x38630000 + spreadC, // addi r3, r3, spread c
// 0x906dbb10, // move routine set position
// 0x3bc00001, // li r30, 1 (over written code)
// XGAssembly.createBranchFrom(offset: spreadCheckStart + 0x24, toOffset: spreadCheckBranch + 0x4)
//]
//XGAssembly.replaceASM(startOffset: spreadCheckBranch, newASM: [XGAssembly.createBranchFrom(offset: spreadCheckBranch, toOffset: spreadCheckStart)])
//XGAssembly.replaceASM(startOffset: spreadCheckStart, newASM: spreadCode)
//// all colosseum battles are single battles except mirror b
//for trainer in XGDecks.DeckColosseum.allTrainers where trainer.index > 8 {
// let battle = trainer.battleData!
// battle.battleStyle = .single
// battle.save()
//}
// print all treasure locations
//var treasures = [XGTreasure]()
//for i in 0 ..< CommonIndexes.NumberTreasureBoxes.value {
// treasures.append(XGTreasure(index: i))
//}
//
//for tr in treasures.sorted(by: { (t1, t2) -> Bool in
// return t1.room.name < t2.room.name
//}) {
// print(tr.index.hexString() + ":",tr.item.name, "x" + tr.quantity.string,"\n" + tr.room.name, "flag:", tr.flag)
// print(tr.xCoordinate, tr.yCoordinate, tr.zCoordinate, tr.angle,"\n")
//}
//let indexes = [0x16, 0x26, 0x22, 0x2d, 0x3d, 064, 0x5d, 0xd, 0x1, 0x69, 0x71, 0x29, 0x36]
//let newitems = ["great ball", "TM51", "Rare Candy", "potion", "white herb", "TM24", "TM55", "rare candy", "TM52", "TM53", "rare candy", "TM54", "SM01"]
//let quants = [2, 1, 1, 6, 4, 1, 1, 1, 1, 1, 3, 1, 1]
//
//for i in 0 ..< indexes.count {
// let tr = XGTreasure(index: indexes[i])
// tr.itemID = item(newitems[i]).index
// tr.quantity = quants[i]
// tr.save()
//}
//let firstImpression = [0x00, 0x83, 0x80, 0x41, 0x5c, 0x91, 0x29, 0x80, 0x41, 0x40, 0x90]
//
//var currentOffset = XGAssembly.ASMfreeSpacePointer()
//print(currentOffset.hex())
//XGAssembly.setMoveEffectRoutine(effect: 47, fileOffset: currentOffset - kDOLtoRAMOffsetDifference, moveToREL: false, newRoutine: firstImpression)
//// create over world models for pokespot pokemon
//let file = XGFiles.fsys("people_archive.fsys")
//let fsys = file.fsysData
//
//for i in 0 ... 2 {
// let spot = XGPokeSpots(rawValue: i)!
//
// for j in 0 ..< spot.numberOfEntries() {
// let mon = XGPokeSpotPokemon(index: j, pokespot: spot).pokemon.stats
// let data = mon.pkxData!
//
// let ow = XGUtility.exportDatFromPKX(pkx: data)
// ow.file = .nameAndFolder(mon.name.string, .TOC)
// ow.save()
//
// let model = ow.file
// XGUtility.copyOWPokemonIdleAnimationFromIndex(index: 0, forModel: model)
//
// let identifier = mon.index * 0x10000 + 0x0400
// let index = fsys.indexForIdentifier(identifier: identifier)
// fsys.shiftAndReplaceFileWithIndex(index, withFile: ow.file.compress())
//// fsys.addFile(ow, fileType: .dat, compress: true, shortID: mon.index)
// print("added file:", ow.file.fileName, i, "-", j)
//
// }
//}
//fsys.save()
//
//// increase number of tms by replacing hms
//let dol = XGFiles.dol.data!
//dol.replaceWordAtOffset(0x15e92c - kDolToRAMOffsetDifference, withBytes: 0x28030038)
//dol.replaceWordAtOffset(0x15e948 - kDolToRAMOffsetDifference, withBytes: 0x3803ffc8)
//dol.save()
//
//// remove amplifier ability code
//XGAssembly.replaceASM(startOffset: 0x220d20 - kDolToRAMOffsetDifference, newASM: [kNopInstruction, kNopInstruction, kNopInstruction, kNopInstruction, kNopInstruction, kNopInstruction, kNopInstruction])
// replace "but it already has a burn"
//getStringSafelyWithID(id: 20041).duplicateWithString("But it failed!").replace()
//// pokespot pokemon's pid is randomly generated at start of encounter rather than at spawn
//XGAssembly.replaceASM(startOffset: 0x1fb054 - kDolToRAMOffsetDifference, newASM: [kNopInstruction])
//
//
//
//// life orb
//let lifeBranch = 0x2250f4
//let lifeStart = 0xB9A1E8
//let lifeEnd = lifeBranch + 0x4 // oh wow, what a grim variable name XD
//let lifeCodeEnd = 0xa4
//
//let getMovePower = 0x13e71c
//let getItem = 0x20384c
//let checkStatus = 0x2025f0
//let animSoundCallBack = 0x2236a8
//
//XGAssembly.replaceASM(startOffset: lifeBranch - kDolToRAMOffsetDifference, newASM: [
// XGAssembly.createBranchFrom(offset: lifeBranch, toOffset: lifeStart),
//])
//
//XGAssembly.replaceRELASM(startOffset: lifeStart - kRELtoRAMOffsetDifference, newASM: [
// 0x7fc3f378, // mr r3, r30 (pokemon pointer)
// XGAssembly.createBranchAndLinkFrom(offset: lifeStart + 0x4, toOffset: getItem), // get item's hold item id
// 0x2803004b, // cmpwi r3, 75 (compare with life orb)
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0xc, to: lifeCodeEnd),
// 0x7fc3f378, // mr r3, r30 (pokemon pointer)
// 0xa063080c, // lhz r3, 0x80c(r3) (get ability)
// 0x28030023, // cmpwi r3, sheer force
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x1c, to: lifeCodeEnd),
// 0x281a0000, // cmpwi r26, 0 (check if move failed),
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x24, to: lifeCodeEnd),
// 0x7ea3ab78, // mr r3, r21 (current move)
// XGAssembly.createBranchAndLinkFrom(offset: lifeStart + 0x2c, toOffset: getMovePower),
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchLessThanOrEqualFromOffset(from: 0x34, to: lifeCodeEnd),
//
// 0x7fc3f378, // mr r3, r30 (pokemon pointer)
// 0x38800007, // li r4, frozen
// XGAssembly.createBranchAndLinkFrom(offset: lifeStart + 0x40, toOffset: checkStatus),
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x48, to: lifeCodeEnd),
//
// 0x7fc3f378, // mr r3, r30 (pokemon pointer)
// 0x38800008, // li r4, sleep
// XGAssembly.createBranchAndLinkFrom(offset: lifeStart + 0x54, toOffset: checkStatus),
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x5c, to: lifeCodeEnd),
//
// 0xa07e000c, // lhz r3, 0x000c(r30)
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x68, to: lifeCodeEnd),
//
// // set life orb activated flag
// 0x7fc3f378, // mr r3, r30 (pokemon pointer)
// 0x38800001, // li r4, 1
// 0xb083000c, // sth r4, 0x000c (r3)
//
// 0x7fc3f378, // mr r3, r30 (pokemon pointer)
// 0x80630000, // lw r3, 0 (r3)
// 0x38630004, // addi r3, 4
// 0xa0830090, // lhz r4, 0x0090 (r3) (get max hp)
// 0x3800000a, // li r0, 10
// 0x7C8403D6, // divw r4, r4, r0 (max hp / 10)
// 0x7e439378, // mr r3, r18 (move routine pointer)
// 0x9083009c, // store hp to lose
// 0x3c608041, // lis r3, 8041
// 0x386374df, // addi r3, r3, 29919 (reverse mode residual damage animation
// XGAssembly.createBranchAndLinkFrom(offset: lifeStart + 0xa0, toOffset: animSoundCallBack),
// // life code end
// 0x38600000, // lir3, 0 (code that was overwritten by branch)
// XGAssembly.createBranchFrom(offset: lifeStart + 0xa8, toOffset: lifeEnd)
//])
//
//// remove life orb activated flags
//let lifeOrb2Branch = 0x2172b8 - kDolToRAMOffsetDifference
//let lifeOrb2Start = 0x220f58 - kDolToRAMOffsetDifference
//XGAssembly.replaceASM(startOffset: lifeOrb2Branch, newASM: [
//0x7C7F1B78, // mr r31, r3
//XGAssembly.createBranchAndLinkFrom(offset: lifeOrb2Branch + 0x4, toOffset: lifeOrb2Start),
//0x38600000, // li r3, 0
//])
//XGAssembly.replaceASM(startOffset: lifeOrb2Start, newASM: [
//0x38800000, // li r4, 0
//0xb083000c, // sth r4, 0x000c (r3)
//XGAssembly.powerPCBranchLinkReturn()
//])
//// flinch status remains set for whole move routine
//// may need to end flinch status at end of turn but seems to happen automatically in testing
//// just look out for edge cases
//XGAssembly.replaceASM(startOffset: 0x226ed0 - kDolToRAMOffsetDifference, newASM: [.nop])
//
//
//// life orb on flinch
//let lifeOrbFlinchBranch = 0xb9a208
//let lifeFlinchTrue = 0xb9a28c
//let lifeOrbFlinchStart = 0xB9AE9C
//let checkStatus = 0x2025f0
//XGAssembly.replaceRELASM(startOffset: lifeOrbFlinchBranch - kRELtoRAMOffsetDifference, newASM: [.b(lifeOrbFlinchStart), .nop])
//XGAssembly.replaceRELASM(startOffset: lifeOrbFlinchStart - kRELtoRAMOffsetDifference, newASM: [
// .cmpwi(.r26, 0), // overwritten - check move didn't miss or fail
// .bne_f(0, 8),
// .b(lifeFlinchTrue),
// .mr(.r3, .r30),
// .li(.r4, 17), // flinched status
// .bl(checkStatus),
// .cmpwi(.r3, 1),
// .bne_f(0, 8),
// .b(lifeFlinchTrue),
// .b(lifeOrbFlinchBranch + 4)
//])
//
//// snow cloak
//let snowBranch = 0x21793c - kDolToRAMOffsetDifference
//let snowStart = 0x220f64 - kDolToRAMOffsetDifference
//let evasion = 0x217954 - kDolToRAMOffsetDifference
//XGAssembly.replaceASM(startOffset: snowBranch, newASM: [
//XGAssembly.createBranchFrom(offset: snowBranch, toOffset: snowStart),
//0x281d0003, // cmplwi r29, sandstorm
//])
//XGAssembly.replaceASM(startOffset: snowStart, newASM: [
//0x281d0004, // cmplwi r29, hail
//XGAssembly.powerPCBranchEqualFromOffset(from: 0x4, to: 0xc),
//XGAssembly.createBranchFrom(offset: snowStart + 0x8, toOffset: snowBranch + 0x4),
//
//0x281a0069, // cmpwi r26, snow cloak
//XGAssembly.powerPCBranchEqualFromOffset(from: 0x10, to: 0x18),
//XGAssembly.createBranchFrom(offset: snowStart + 0x14, toOffset: snowBranch + 0x4),
//XGAssembly.createBranchFrom(offset: snowStart + 0x18, toOffset: evasion),
//])
//// freeze dry, scrappy
//let freezeBranches = [0x216828,0x216858]
//let freezeStarts = [0xB99F00,0xb9a2cc]
//let getAbility = 0x2055c8
//for i in 0 ..< freezeBranches.count {
// let branch = freezeBranches[i]
// XGAssembly.replaceASM(startOffset: branch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchAndLinkFrom(offset: branch, toOffset: freezeStarts[i])])
//}
//let typeRegisters : ASM = [
//0x7f24cb78, // mr r4, r25
//0x7f04c378, // mr r4, r24
//]
//for i in 0 ..< freezeStarts.count {
// let freezeStart = freezeStarts[i]
// let typeRegister = typeRegisters[i]
// XGAssembly.replaceRELASM(startOffset: freezeStart - kRELtoRAMOffsetDifference, newASM: [
//
// 0x281500c6, // cmpwi r21, freeze dry
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x14), //bne 0x14
// 0x2804000b, // cmpwi r4, water type
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc), //bne 0xc
// 0x38600041, // li r3, super effective
// 0x4e800020, // blr
//
// 0x9421fff0, // stwu sp, -0x0010 (sp)
// 0x7c0802a6, // mflr r0
// 0x90010014, // stw r0, 0x0014 (sp)
//
// 0x28040007, // cmpwi r4, ghost type
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x34), //bne 0x34
// 0x7ee3bb78, // mr r3, r23
// XGAssembly.createBranchAndLinkFrom(offset: freezeStart + 0x30, toOffset: getAbility),
// 0x2803005c, // cmpwi r3, scrappy
//
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x24), //bne 0x24
//
// // check normal or fighting type move
// 0x5680043e, // rlwinm r0, r20, 0, 16, 31 (0000ffff)
// 0x28000002, // cmplwi r0, flying type
// XGAssembly.powerPCBranchGreaterThanOrEqualFromOffset(from: 0x0, to: 0x18),
//
// 0x3860003F, // li r3, neutral
// 0x80010014, // lwz r0, 0x0014 (sp)
// 0x7c0803a6, // mtlr r0
// 0x38210010, // addi sp, sp, 16
// 0x4e800020, // blr
//
// 0x7e83a378, // mr r3, r20
// typeRegister,
//
// // get type matchup
// 0x1ca30030,
// 0x5480083c,
// 0x80cd89ac,
// 0x7ca50214,
// 0x3805000c,
// 0x7c66022e,
//
// 0x80010014, // lwz r0, 0x0014 (sp)
// 0x7c0803a6, // mtlr r0
// 0x38210010, // addi sp, sp, 16
//
// 0x4e800020, // blr
// ])
//}
//// orre colosseum single/double battle options (also need to edit script)
//XGDecks.DeckColosseum.addPokemonEntries(count: 28 * 6)
//XGDecks.DeckColosseum.addTrainerEntries(count: 28)
//
//
//let rel = XGFiles.common_rel.data!
//var oldbattles = [Int]()
//var newbattles = [Int]()
//for i in 41 ... 68 {
// let orre = XGTrainer(index: i, deck: .DeckColosseum).battleData!
// let new = XGBattle(index: orre.index - 0x48)
//
// let start = new.startOffset
// let oldData = orre.rawData
// rel.replaceBytesFromOffset(start, withByteStream: oldData)
//
// oldbattles.append(orre.index)
// newbattles.append(new.index)
//
//}
//rel.save()
//for i in 41 ... 68 {
// let oldt = XGTrainer(index: i , deck: .DeckColosseum)
// let newt = XGTrainer(index: i + 28, deck: .DeckColosseum)
// let new = XGBattle(index: newbattles[i - 41])
//
// new.battleStyle = .double
// new.trainerID = i + 28
// new.save()
//
// newt.cameraEffects = oldt.cameraEffects
// newt.defeatTextID = oldt.defeatTextID
// newt.nameID = oldt.nameID
// newt.preBattleTextID = oldt.preBattleTextID
// newt.trainerClass = oldt.trainerClass
// newt.trainerModel = oldt.trainerModel
// newt.victoryTextID = oldt.victoryTextID
// newt.AI = oldt.AI
// newt.trainerStringID = oldt.trainerStringID
// newt.save()
//
//}
//
//
//
//for i in 69 ... 69 + 27 {
// let t = XGTrainer(index: i, deck: .DeckColosseum)
// for p in 0 ... 5 {
// if t.pokemon[p].index == 0 {
// t.pokemon[p] = XGDecks.DeckColosseum.unusedPokemon()
// if t.pokemon[p].index != 0 {
// let poke = t.pokemon[p].data
// poke.species = XGPokemon.pokemon(1)
// poke.level = 60
// poke.IVs = 31
// poke.save()
// t.save()
// }
// }
// }
//}
//
//for i in 41 ... 68 {
// let oldt = XGTrainer(index: i, deck: .DeckColosseum)
// let newt = XGTrainer(index: i + 28, deck: .DeckColosseum)
// for j in 0 ... 5 {
// let old = oldt.pokemon[j].data
// let new = newt.pokemon[j].data
// new.species = old.species
// new.ability = old.ability
// new.gender = old.gender
// new.EVs = old.EVs
// new.happiness = old.happiness
// new.item = old.item
// new.moves = old.moves
// new.nature = old.nature
// new.shinyness = old.shinyness
// new.save()
// }
//}
//
//
//
//
//
//getStringSafelyWithID(id: 0x8ABE).duplicateWithString("[Speaker]: At the Orre Colosseum, battles[New Line]are conducted.[New Line]You are permitted to battle with 6 Pokémon.[Clear Window][Speaker]: Battles are held in knockout style.[New Line]You must beat four trainers in a row to win [New Line]the challenge.[Clear Window][Speaker]: If you win a challenge, you may advance to[New Line]the next group of opponents.[Clear Window][Speaker]: If you manage to win a round, you will be[New Line]awarded Poké Coupons.[Clear Window][Speaker]: You can choose to compete in[New Line]single or double battles through[New Line]this menu.[Dialogue End]").replace()
//
//getStringSafelyWithID(id: 0x8ABF).duplicateWithString("[Speaker]: Battle Style set to Single.[Dialogue End]").replace()
//getStringSafelyWithID(id: 0x8AC0).duplicateWithString("[Speaker]: Battle Style set to Double.[Dialogue End]").replace()
//
//getStringSafelyWithID(id: 0x8abc).duplicateWithString("Set Style: Single").replace()
//getStringSafelyWithID(id: 0x8abd).duplicateWithString("Set Style: Double").replace()
//// mt. battle prize names
//// chikorita
//getStringSafelyWithID(id: 31305).duplicateWithString("Mew").replace()
//// cyndaquil
//getStringSafelyWithID(id: 31306).duplicateWithString("Celebi").replace()
//// totodile
//getStringSafelyWithID(id: 31307).duplicateWithString("Jirachi").replace()
//let mart = XGPokemart(index: 3)
//mart.items.append(item("Poké Snack"))
//mart.firstItemIndex = 59
//mart.save()
//
//for m in [2, 1] {
// let mart = XGPokemart(index: m)
// mart.firstItemIndex += 11
// mart.save()
//}
//for m in [16, 17, 18] {
// let mart = XGPokemart(index: m)
// mart.firstItemIndex = 19
// mart.items = [2,3,4,9,13,17,25,26,30].map({ (i) -> XGItems in
// return XGBattleCD(index: i).getItem()
// })
// mart.save()
//}
//
//var marts = [XGPokemart]()
//for i in 0 ..< PocketIndexes.numberOfMarts.value {
// marts.append(XGPokemart(index: i))
//
//}
//marts.sort { (m1, m2) -> Bool in
// m1.firstItemIndex < m2.firstItemIndex
//}
//for mart in marts {
// printg("mart:",mart.index, " used item indexes:", mart.firstItemIndex, "-", mart.firstItemIndex + mart.items.count," start offset:", mart.itemsStartOffset.hexString())
// printg(mart.items.map({ (i) -> String in
// return i.name.string
// }))
// printg("")
//}
//getStringSafelyWithID(id: 24177).duplicateWithString("[Speaker]: Aarrghh![Wait Input]").replace()
//getStringSafelyWithID(id: 24180).duplicateWithString("[Speaker]: Thanks for playing XG![New Line]Don't forget to check out Mt.Battle.[New Line]There's a surprise at the top.[Wait Input]").replace()
//
//
//
//
//
//// repeat ball catch rate to 3.5x
//XGAssembly.replaceASM(startOffset: 0x21942c - kDolToRAMOffsetDifference, newASM: [0x3b800023])
//
// multi battle with gonzap to enter key lair
//let oldGonzap = XGTrainer(index: 145, deck: .DeckStory)
//let oldBodyBuilder = XGTrainer(index: 22, deck: .DeckStory)
//let oldBodyBuilder2 = XGTrainer(index: 111, deck: .DeckStory)
//let gonzap = XGTrainer(index: 225, deck: .DeckStory)
//let b1 = XGTrainer(index: 209, deck: .DeckStory)
//let b2 = XGTrainer(index: 210, deck: .DeckStory)
//
//for trainer in [gonzap, b1, b2] {
// trainer.AI = XGAI.offensive.rawValue
// trainer.defeatTextID = 0
// trainer.preBattleTextID = 0
// trainer.victoryTextID = 0
//}
//b1.nameID = oldBodyBuilder.nameID
//b2.nameID = oldBodyBuilder2.nameID
//gonzap.trainerModel = oldGonzap.trainerModel
//gonzap.cameraEffects = oldGonzap.cameraEffects
//gonzap.nameID = oldGonzap.nameID
//gonzap.trainerClass = oldGonzap.trainerClass
//gonzap.save()
//for trainer in [b1, b2] {
// trainer.trainerModel = oldBodyBuilder.trainerModel
// trainer.cameraEffects = oldBodyBuilder.cameraEffects
// trainer.trainerClass = oldBodyBuilder.trainerClass
// trainer.save()
//}
//
//let gonzapMultiBattle = gonzap.battleData!
//let oldBattle = oldGonzap.battleData!
//let zookBattle = XGTrainer(index: 147, deck: .DeckStory).battleData!
//gonzapMultiBattle.p3TID = 209
//gonzapMultiBattle.p3Deck = .DeckStory
//gonzapMultiBattle.p3Controller = .AI
//gonzapMultiBattle.p4TID = 210
//gonzapMultiBattle.p4Deck = .DeckStory
//gonzapMultiBattle.p4Controller = .AI
//gonzapMultiBattle.pokemonPerPlayer = 6
//gonzapMultiBattle.trainersPerSide = 2
//gonzapMultiBattle.battleStyle = .single
//gonzapMultiBattle.BGMusicID = oldBattle.BGMusicID
//gonzapMultiBattle.battleField = zookBattle.battleField
//gonzapMultiBattle.battleType = .story
//gonzapMultiBattle.unknown = oldBattle.unknown
//gonzapMultiBattle.unknown2 = oldBattle.unknown2
//gonzapMultiBattle.save()
//// herbal medicine fix
//let hp = item("heal powder").data
//hp.parameter = item("full heal").data.parameter
//hp.save()
//let rh = item("revival herb").data
//rh.parameter = item("max revive").data.parameter
//rh.save()
//let ep = item("energy powder").data
//ep.parameter = item("super potion").data.parameter
//ep.save()
//let er = item("energy root").data
//er.parameter = item("hyper potion").data.parameter
//er.save()
//
//// sitrus berry fix
//XGAssembly.replaceRELASM(startOffset: 0xb9a018 - kRELtoRAMOffsetDifference, newASM: [0x281b00fc])
//
//let sitrus2Branch = 0x15f2fc
//let sitrus2Start = 0xB9A358
//XGAssembly.replaceASM(startOffset: sitrus2Branch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: sitrus2Branch, toOffset: sitrus2Start)])
//XGAssembly.replaceRELASM(startOffset: sitrus2Start, newASM: [
// 0x2c0000fc, // cmpwi r0, 252
// XGAssembly.powerPCBranchEqualFromOffset(from: 0, to: 8), // beq 8
// XGAssembly.createBranchFrom(offset: sitrus2Start + 0x8, toOffset: 0x15f32c), // b 0x15f32c
// 0x5463FC7F, // rlwinm. r3, r3, 31, 17, 31 (0000fffe) divide by 2, divided by 2 again after branch
// XGAssembly.createBranchFrom(offset: sitrus2Start + 0x10, toOffset: 0x15f310), // b 15f310
//])
//
//let sb = item("sitrus berry").data
//sb.parameter = 0xfc
//sb.save()
//// paralysis moves don't affect electric types
//let thunderwaveRoutine = [0x00, 0x02, 0x04, 0x1f, 0x12, 0x07, 0x80, 0x41, 0x4d, 0x01, 0x23, 0x12, 0x0d, 0x80, 0x41, 0x5c, 0xc6, 0x1e, 0x12, 0x00, 0x00, 0x00, 0x14, 0x80, 0x41, 0x5c, 0x93, 0x07, 0xf9, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x00, 0x00, 0x80, 0x4e, 0xb9, 0x5e, 0x2a, 0x00, 0x80, 0x4e, 0xb9, 0x5e, 0x00, 0x80, 0x41, 0x5c, 0x93, 0x1d, 0x12, 0x00, 0x00, 0x00, 0x05, 0x80, 0x41, 0x4c, 0xe8, 0x1d, 0x12, 0x00, 0x00, 0x00, 0x01, 0x80, 0x41, 0x5c, 0x93, 0x01, 0x80, 0x41, 0x5c, 0x93, 0x00, 0x00, 0x20, 0x12, 0x00, 0x4b, 0x80, 0x41, 0x6d, 0xb2, 0x0a, 0x0b, 0x04, 0x2f, 0x80, 0x4e, 0x85, 0xc3, 0x05, 0x17, 0x10, 0x13, 0x00, 0x50, 0x0b, 0x04, 0x29, 0x80, 0x41, 0x41, 0x0f,]
//
//let routines : [(effect: Int, routine: [Int], offset: Int)] = [
// (67, thunderwaveRoutine, 0xB9A4AC),
//]
//
////var currentOffset = XGAssembly.ASMfreeSpacePointer()
//for routine in routines {
//// // run first to generate offsets
//// print("effect \(routine.effect) - \(currentOffset.hexString())")
//// currentOffset += routine.routine.count
//
// // fill in offsets then run this to actually add them
// XGAssembly.setMoveEffectRoutine(effect: routine.effect, fileOffset: routine.offset - kDOLtoRAMOffsetDifference, moveToREL: false, newRoutine: routine.routine)
//}
//// secondary move effects can't paralyse electric types
//let paraStart = 0xB9A520
//let paraBranch = 0x213dbc
//let checkHasType = 0x2054fc
//let getPointer = 0x1efcac
//XGAssembly.replaceASM(startOffset: paraBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: paraBranch, toOffset: paraStart)])
//XGAssembly.replaceRELASM(startOffset: paraStart - kRELtoRAMOffsetDifference, newASM: [
// 0x3bed87a0, // overwritten code
// 0x881f0003, // lbz r0, 0x0003 (r31) get move secondary effect index
// 0x28000005, // cmpwi r0, paralysis chance
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0x8),
// XGAssembly.createBranchFrom(offset: paraStart + 0x10, toOffset: paraBranch + 0x4),
// 0x38600012, // li r3, 18
// 0x38800000, // li r4, 0
// XGAssembly.createBranchAndLinkFrom(offset: paraStart + 0x1c, toOffset: getPointer),
// 0x3880000d, // li r4, electric
// XGAssembly.createBranchAndLinkFrom(offset: paraStart + 0x24, toOffset: checkHasType),
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x8),
// 0x3ba00000, // li r29, 0
// XGAssembly.createBranchFrom(offset: paraStart + 0x34, toOffset: paraBranch + 0x4)
//
//])
//// spore/powder moves don't affect grass types prankster doesn't affect dark types
//let sporeBranch = 0x225870
//let sporeStart = 0xB9A558
//let moveGetTargets = 0x13e784
//let checkHasType = 0x2054fc
//let getPointer = 0x1efcac
//let getCurrentMove = 0x148d64
//let getAbility = 0x2055c8
//let moveGetCategory = 0x13e7f0
//let moveGetPriority = 0x13e7b8
//let moveRoutineSetPosition = 0x2236d4
//
//let sporeEnd = 0x58
//let sporeBlocked = 0x44
//let pranksterEnd = 0xf0
//let pranksterBlocked = 0xe0
//
//XGAssembly.replaceASM(startOffset: sporeBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: sporeBranch, toOffset: sporeStart)])
//XGAssembly.replaceRELASM(startOffset: sporeStart - kRELtoRAMOffsetDifference, newASM: [
//
// 0x38600012, // li r3, 18 (defending pokemon)
// 0x38800000, // li r4, 0
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0x8, toOffset: getPointer), // get pokemon pointer
// 0x3880000c, // li r4, grass
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0x10, toOffset: checkHasType),
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x18, to: sporeEnd),
//
// 0x38600011, // li r3, 17 (attacking pokemon)
// 0x38800000, // li r4, 0
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0x24, toOffset: getPointer), // get pokemon pointer
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0x28, toOffset: getCurrentMove),
// 0x28030093, // cmpwi r3, spore
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x30, to: sporeBlocked),
// 0x2803004e, // cmpwi r3, stun spore
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x38, to: sporeBlocked),
// 0x2803004f, // cmpwi r3, sleep powder
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x40, to: sporeEnd),
//
// // spore blocked 0x44
// 0x3c6080ba, // lis r3, 0x80ba
// 0x3863a650, // subi r3, r3, 0x59b0
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0x4c, toOffset: moveRoutineSetPosition),
// 0x3bc00001, // li r30, 1
// XGAssembly.createBranchFrom(offset: 0x54, toOffset: pranksterEnd),
//
// // spore end 0x58
// 0x38600012, // li r3, 18 (defending pokemon)
// 0x38800000, // li r4, 0
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0x60, toOffset: getPointer), // get pokemon pointer
// 0x38800011, // li r4, dark
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0x68, toOffset: checkHasType),
// 0x28030001, // cmpwi r3, 1
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x70, to: pranksterEnd),
//
// 0x38600011, // li r3, 17 (attacking pokemon)
// 0x38800000, // li r4, 0
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0x7c, toOffset: getPointer), // get pokemon pointer
// 0xa063080c, // lhz r3, 0x080C (r3) get ability
// 0x28030059, // cmpwi r3, prankster
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x88, to: pranksterEnd),
//
// 0x38600011, // li r3, 17 (attacking pokemon)
// 0x38800000, // li r4, 0
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0x94, toOffset: getPointer), // get pokemon pointer
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0x98, toOffset: getCurrentMove),
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0x9c, toOffset: moveGetCategory),
// 0x28030000, // cmpwi r3, status
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0xa4, to: pranksterEnd),
//
// 0x38600011, // li r3, 17 (attacking pokemon)
// 0x38800000, // li r4, 0
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0xb0, toOffset: getPointer), // get pokemon pointer
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0xb4, toOffset: getCurrentMove),
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0xb8, toOffset: moveGetPriority),
// 0x28030000, // cmpwi r3, 0
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0xc0, to: pranksterEnd),
//
// 0x38600011, // li r3, 17 (attacking pokemon)
// 0x38800000, // li r4, 0
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0xcc, toOffset: getPointer), // get pokemon pointer
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0xd0, toOffset: getCurrentMove),
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0xd4, toOffset: moveGetTargets),
// 0x28030005, // cmpwi r3, user
// XGAssembly.powerPCBranchEqualFromOffset(from: 0xdc, to: pranksterEnd),
//
// // prankster blocked 0xe0
// 0x3c6080ba, // lis r3, 0x80ba
// 0x3863a650, // subi r3, r3, 0x59b0
// 0x3bc00001, // li r30, 1
// XGAssembly.createBranchAndLinkFrom(offset: sporeStart + 0xec, toOffset: moveRoutineSetPosition),
//
// // prankster end 0xf0
// 0x7fc3f378, // mr r3, r30 overwritten code
// XGAssembly.createBranchFrom(offset: sporeStart + 0xf4, toOffset: sporeBranch + 0x4)
//])
//XGAssembly.replaceRELASM(startOffset: 0xb9a650 - kRELtoRAMOffsetDifference, newASM: [ 0x02298041, 0x5cc60000, ])
//// spread moves damage reduced by 25% when hitting multiple targets
//let spreadBranches = [0x22aa4c, 0x22a8f4]
//let spreadStart = 0xB9A658
//let spreadMaths = [0x22aa60, 0x22a908]
//for offset in spreadBranches {
// XGAssembly.replaceASM(startOffset: offset - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchAndLinkFrom(offset: offset, toOffset: spreadStart)])
//}
//for offset in spreadMaths {
// XGAssembly.replaceASM(startOffset: offset - kDolToRAMOffsetDifference, newASM: [
// 0x1dce0003, // mulli r14, r14, 3 (r14 * 3)
// 0x7dce1670, // srawi r14, r14, 2 ( r14 >> 2 == r14 / 4)
// ])
//}
//XGAssembly.replaceRELASM(startOffset: spreadStart - kRELtoRAMOffsetDifference, newASM: [
// 0x28000004, // cmpwi r0, both foes spread move
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0xc),
//
// // if it passes first test then we can return without checking the second condition
// // we simply do the comparison again so the next line will do the right jump after returning
// 0x28000004, // cmpwi r0, both foes spread move
// XGAssembly.powerPCBranchLinkReturn(),
//
// // otherwise we check the second condition and once we return the jump will be based on that
// // as the first comparison no longer affects the results
// 0x28000006, // cmpwi r0, both foes and ally spread move
// XGAssembly.powerPCBranchLinkReturn(),
//])
//// move effect 203 always neutral damage addition to freeze dry and scrappy code
//let neutralStart = 0xB9A834
//let neutralBranch = 0x216d80
//let getMoveEffect = 0x13e6e8
//let neutralSkip = 0x216e10
//let setEffectiveness = 0x1f057c
//let checkSetEffectiveness = 0x1f05d0
//XGAssembly.setMoveEffectRoutineRAMOffset(effect: 203, RAMOffset: 0x80414b23)
//XGAssembly.replaceASM(startOffset: neutralBranch - kDolToRAMOffsetDifference, newASM: [
// .b(neutralStart),
// // overwritten code
// .mr(.r3, .r26),
// .bl(0x13d03c),
// .cmpwi(.r3, 1),
//])
//XGAssembly.replaceRELASM(startOffset: neutralStart - kRELtoRAMOffsetDifference, newASM: [
// .mr(.r3, .r26), // move id
// .bl(getMoveEffect),
// .cmpwi(.r3, 203), // new effect always neutral damage
// .beq_f(0, 8),
// .b(neutralBranch + 0x4),
//
// // neutral damage
// .mr(.r3, .r31),
// .li(.r4, XGEffectivenessValues.neutral.rawValue),
// .bl(checkSetEffectiveness),
// .cmpwi(.r3, 2),
// .beq_f(0, 8),
// .b(neutralSkip),
// .mr(.r3, .r31),
// .li(.r4, XGEffectivenessValues.neutral.rawValue),
// .li(.r5, 0),
// .bl(setEffectiveness),
// .b(neutralSkip),
//
//])
//// ghost types can't be trapped
//let ghostBranch = 0x20f7b0
//let ghostStart = 0xB9A874
//let checkHasType = 0x2054fc
//let ghostSkip = 0x20f980
//
//XGAssembly.replaceASM(startOffset: ghostBranch - kDolToRAMOffsetDifference, newASM: [
// .b(ghostStart),
// .cmpwi(.r31, 50), // compare ability with runaway (overwritten code)
//])
//XGAssembly.replaceRELASM(startOffset: ghostStart - kRELtoRAMOffsetDifference, newASM: [
// .mr(.r3, .r28),
// .li(.r4, XGMoveTypes.ghost.rawValue),
// .bl(checkHasType),
// .cmpwi(.r3, 1),
// .beq_f(0, 8),
// .b(ghostBranch + 0x4),
// .li(.r3, 0),
// .b(ghostSkip),
//])
//let toxicBranch = 0x2178d4
//let toxicStart = 0xB9A894
//let checkHasType = 0x2054fc
//let toxicSkip = 0x2179b8
//XGAssembly.replaceASM(startOffset: toxicBranch - kDolToRAMOffsetDifference, newASM: [
// .b(toxicStart)
//])
//XGAssembly.replaceRELASM(startOffset: toxicStart - kRELtoRAMOffsetDifference, newASM: [
// .mr(.r3, .r23),
// .li(.r4, XGMoveTypes.poison.rawValue),
// .bl(checkHasType),
// .cmpwi(.r3, 1),
// .beq_f(0, 8),
// .b(toxicBranch + 0x4),
// .li(.r22, 100), // set accuracy
// .b(toxicSkip)
//])
//// ghosts can't be trapped 2
//let ghost2Branch = 0x1f279c
//let ghost2Start = 0xB9AA58
//let checkType = 0x2054fc
//XGAssembly.replaceASM(startOffset: ghost2Branch - kDolToRAMOffsetDifference, newASM: [.b(ghost2Start)])
//XGAssembly.replaceRELASM(startOffset: ghost2Start - kRELtoRAMOffsetDifference, newASM: [
//
// .stwu(.sp, .sp, -0x20),
// .stmw(.r31, .sp, 0x10),
// .mr(.r31, .r3),
//
// .mr(.r3, .r25),
// .li(.r4, XGMoveTypes.ghost.rawValue),
// .bl(checkType),
// .cmpwi(.r3, 1),
// .bne_f(0, 8),
// .li(.r31, 0),
//
// .mr(.r3, .r31),
// .lmw(.r31, .sp, 0x10),
// .addi(.sp, .sp, 0x20),
//
// .lmw(.r25, .sp, 0x14), // overwritten
// .b(ghost2Branch + 4)
//])
//
//// flame orb / toxic orb poison heal
//
//XGAbilities.ability(50).name.duplicateWithString("Poison Heal").replace()
//XGAbilities.ability(50).adescription.duplicateWithString("Heals when poisoned.").replace()
//
//// remove runaway effect
//XGAssembly.replaceASM(startOffset: 0x20f7b0 - kDolToRAMOffsetDifference, newASM: [
// .b(0x20f7c4),
// .nop,
// .nop
//])
//
//let flameOrb = XGItem(index: 190)
//let toxicOrb = XGItem(index: 185)
//flameOrb.name.duplicateWithString("Flame Orb").replace()
//toxicOrb.name.duplicateWithString("Toxic Orb").replace()
//flameOrb.descriptionID = toxicOrb.descriptionID
//toxicOrb.descriptionString.duplicateWithString("Inflicts the holder with[New Line]a status at the[New Line]of the turn.").replace()
//
//flameOrb.holdItemID = 78
//toxicOrb.holdItemID = 79
//for orb in [flameOrb, toxicOrb] {
// orb.bagSlot = .items
// orb.canBeHeld = true
// orb.couponPrice = 200
// orb.price = 500
// orb.friendshipEffects = [0,0,0]
// orb.inBattleUseID = 0
// orb.parameter = 0
// orb.save()
//}
//
//let badPoisonResidualBranch = 0x227d88
//let poisonResidualBranch = 0x227d0c
//let badPoisonSkip = 0x227e08
//let poisonSkip = 0x227d58
//let poisonHealStart1 = 0xB9AA30
//let poisonHealStart2 = 0xB9AA44
//
//XGAssembly.replaceASM(startOffset: poisonResidualBranch - kDolToRAMOffsetDifference, newASM: [.b(poisonHealStart1)])
//XGAssembly.replaceRELASM(startOffset: poisonHealStart1, newASM: [
// .cmpwi(.r28, ability("poison heal").index),
// .bne_f(0, 8),
// .b(poisonSkip),
// .lwz(.r0, .r13, -0x44e8), // overwritten
// .b(poisonResidualBranch + 4)
//])
//XGAssembly.replaceASM(startOffset: badPoisonResidualBranch - kDolToRAMOffsetDifference, newASM: [.b(poisonHealStart2)])
//XGAssembly.replaceRELASM(startOffset: poisonHealStart2, newASM: [
// .cmpwi(.r28, ability("poison heal").index),
// .bne_f(0, 8),
// .b(badPoisonSkip),
// .lwz(.r0, .r13, -0x44e8), // overwritten
// .b(badPoisonResidualBranch + 4)
//])
//
//
//let orbBranch = 0x225ab4
//let orbStart = 0xB9A8B4
//let checkFullHP = 0x201d20
//let checkStatus = 0x2025f0
//let checkSetStatus = 0x20254c
//let checkHasType = 0x2054fc
//let setStatus = 0x2024a4
//let checkNoStatus = 0x203744
//let getHPFraction = 0x203688
//let storeHPLoss = 0x13e094
//let animSoundCallback = 0x2236a8
//let getItem = 0x20384c // get item's hold item id
//
//let healOffset = orbStart + 0x34
//let flameOrbOffset = orbStart + 0x6c
//let toxicOrbOffset = orbStart + 0xec
//let returnOffset = orbStart + 0x174
//XGAssembly.replaceASM(startOffset: orbBranch - kDolToRAMOffsetDifference, newASM: [ .b(orbStart) ])
//XGAssembly.replaceRELASM(startOffset: orbStart - kRELtoRAMOffsetDifference, newASM: [
//
// .lhz(.r3, .r31, 0x80c), // get ability
// .cmpwi(.r3, ability("poison heal").index),
// .bne(flameOrbOffset),
// .mr(.r3, .r31),
// .li(.r4, 3), // poison
// .bl(checkStatus),
// .cmpwi(.r3, 1),
// .beq(healOffset),
// .mr(.r3, .r31),
// .li(.r4, 4), // bad poison
// .bl(checkStatus),
// .cmpwi(.r3, 1),
// .bne(flameOrbOffset),
//
// //heal offset 0x34
// .mr(.r3, .r31),
// .bl(checkFullHP),
// .cmpwi(.r3, 1),
// .beq(flameOrbOffset),
// .mr(.r3, .r31),
// .li(.r4, 8), // 1/8 max hp
// .bl(getHPFraction),
// .rlwinm(.r0, .r3, 0, 16, 31),
// .neg(.r4, .r0),
// .mr(.r3, .r30),
// .bl(storeHPLoss),
// .lis(.r3, 0x8041),
// .addi(.r3, .r3, 31004),
// .bl(animSoundCallback),
//
// // flame orb offset 0x6c
// .mr(.r3, .r31),
// .bl(getItem),
// .cmpwi(.r3, item("flame orb").data.holdItemID),
// .bne(toxicOrbOffset),
//
// .mr(.r3, .r31),
// .li(.r4, XGMoveTypes.fire.rawValue),
// .bl(checkHasType),
// .cmpwi(.r3, 1),
// .beq(returnOffset),
//
// .mr(.r3, .r31),
// .bl(checkNoStatus),
// .cmpwi(.r3, 1),
// .bne(returnOffset),
//
// .lhz(.r3, .r31, 0x80c), // get ability
// .cmpwi(.r3, ability("water veil").index),
// .beq(returnOffset),
//
// // activate burn
// .mr(.r3, .r31),
// .li(.r4, 6), // burn
// .bl(checkSetStatus),
// .cmpwi(.r3, 2),
// .bne(returnOffset),
// .mr(.r3, .r31),
// .li(.r4, 6), // burn
// .li(.r5, 0),
// .bl(setStatus),
//
// .nop, // .li(.r4, 3), // burn chance secondary effect
// .nop, // .lis(.r3, 0x8042),
// .nop, // .rlwinm(.r0, .r4, 2, 0, 29),
// .nop, // .subi(.r3, .r3, 31568),
// .nop, // .lwzx(.r3, .r3, .r0),
// .nop, // .bl(animSoundCallback),
//
// .b(returnOffset),
//
//
// // toxic orb offset 0xec
// .cmpwi(.r3, item("toxic orb").data.holdItemID),
// .bne(returnOffset),
//
// .mr(.r3, .r31),
// .li(.r4, XGMoveTypes.poison.rawValue),
// .bl(checkHasType),
// .cmpwi(.r3, 1),
// .beq(returnOffset),
//
// .mr(.r3, .r31),
// .li(.r4, XGMoveTypes.steel.rawValue),
// .bl(checkHasType),
// .cmpwi(.r3, 1),
// .beq(returnOffset),
//
// .mr(.r3, .r31),
// .bl(checkNoStatus),
// .cmpwi(.r3, 1),
// .bne(returnOffset),
//
// .lhz(.r3, .r31, 0x80c), // get ability
// .cmpwi(.r3, ability("immunity").index),
// .beq(returnOffset),
//
// // activate poison
//
// .mr(.r3, .r31),
// .li(.r4, 4), // badly poisoned
// .bl(checkSetStatus),
// .cmpwi(.r3, 2),
// .bne(returnOffset),
// .mr(.r3, .r31),
// .li(.r4, 4), // badly poisoned
// .li(.r5, 0),
// .bl(setStatus),
//
// .nop, // .li(.r4, 6), // badly poison chance secondary effect
// .nop, // .lis(.r3, 0x8042),
// .nop, // .rlwinm(.r0, .r4, 2, 0, 29),
// .nop, // .subi(.r3, .r3, 31568),
// .nop, // .lwzx(.r3, .r3, .r0),
// .nop, // .bl(animSoundCallback),
//
// // return offset 0x174
// .lmw(.r28, .sp, 0x10), // overwritten code
// .b(orbBranch + 0x4)
//])
//// ability capsule
//
//let capsuleFuncStart = 0xB9AB08
//let selectPokemon = 0x2420c
//let storePokemonPointer = 0x24148
//let displayMessage = 0x117468 // r3 : 2 | r4 : message string id | r5 & r6: 0
//let waitMessage = 0x1173a8 // r3 = 1
//let getName = 0x149584 // param index 0x16
//let setMessageParam = 0x2370ec // r3 = param index, r4 = value
//let getAbility = 0x1416a4 // param indexes 0x1a & 0x1b
//let abilityGetPointer = 0x144298
//let abilityPointerGetNameID = 0x144280
//let stringIDGetPointer = 0x107300
//let getAbilityIndex = 0x1491d0
//let itemMessage = 0xa481c
//let closeWindow = 0x241e0
//let getSpecies = 0x1470c4
//let speciesGetStats = 0x146078
//let statsGetAbilityWithIndex = 0x145c80
//
//XGAssembly.replaceRELASM(startOffset: capsuleFuncStart - kRELtoRAMOffsetDifference, newASM: [
//
// .stwu(.sp, .sp, -0x40),
// .mflr(.r0),
// .stw(.r0, .sp, 0x44),
// .stmw(.r23, .sp, 0x1c),
// .mr(.r23, .r4),
//
// // select party pokemon
// .li(.r3, 0),
// .li(.r4, 1),
// .bl(selectPokemon),
// .cmpwi(.r3, 0),
// .bge_f(0, 0x20),
//
// // return
// .bl(closeWindow),
// .li(.r3, 1),
// .lmw(.r23, .sp, 0x1c),
// .lwz(.r0, .sp, 0x44),
// .mtlr(.r0),
// .addi(.sp, .sp, 0x40),
// .blr,
//
// // store pokemon pointer
// .mr(.r27, .r3),
// .addi(.r4, .sp, 12),
// .addi(.r5, .sp, 8),
// .bl(storePokemonPointer),
// .lwz(.r3, .sp, 12),
// .mr(.r31, .r3),
//
// // check if has second ability
// .bl(getSpecies),
// .bl(speciesGetStats),
// .li(.r4, 1),
// .bl(statsGetAbilityWithIndex),
// .cmpwi(.r3, 0),
// .bne_f(0, 0x30),
//
// // ability capsule useless
//
// .lis(.r3, 0x1),
// .subi(.r3, .r3, (0x10000 - 0xe2c4)),
// .bl(itemMessage),
// .mr(.r3, .r27),
// .bl(closeWindow),
//
// // return
// .li(.r3, 1),
// .lmw(.r23, .sp, 0x1c),
// .lwz(.r0, .sp, 0x44),
// .mtlr(.r0),
// .addi(.sp, .sp, 0x40),
// .blr,
//
// // get pokemon name
// .mr(.r3, .r31),
// .bl(getName),
// .mr(.r30, .r3),
//
// // get ability before
// .mr(.r3, .r31),
// .bl(getAbility),
// .bl(abilityGetPointer),
// .bl(abilityPointerGetNameID),
// .bl(stringIDGetPointer),
// .mr(.r29, .r3),
//
// // switch abilities
// .mr(.r3, .r31),
// .bl(getAbilityIndex),
// .cmpwi(.r3, 1),
//
// .lbz(.r3, .r31, 0x1d),
// .beq_f(0, 0xc),
//
// .addi(.r3, .r3, 0x40),
// .b_f(0, 8),
// .subi(.r3, .r3, 0x40),
// .stb(.r3, .r31, 0x1d),
//
// // get ability after
// .mr(.r3, .r31),
// .bl(getAbility),
// .bl(abilityGetPointer),
// .bl(abilityPointerGetNameID),
// .bl(stringIDGetPointer),
// .mr(.r28, .r3),
//
// // set message params
// .li(.r3, 0x16),
// .mr(.r4, .r30),
// .bl(setMessageParam),
// .li(.r3, 0x1a),
// .mr(.r4, .r29),
// .bl(setMessageParam),
// .li(.r3, 0x1b),
// .mr(.r4, .r28),
// .bl(setMessageParam),
//
// // display message
// .lis(.r3, 0x1),
// .subi(.r3, .r3, (0x10000 - 0xe2c3)),
// .bl(itemMessage),
// .mr(.r3, .r27),
// .bl(closeWindow),
//
// // return
// .li(.r0, 1),
// .stw(.r0, .r23, 0),
// .li(.r3, 0),
// .lmw(.r23, .sp, 0x1c),
// .lwz(.r0, .sp, 0x44),
// .mtlr(.r0),
// .addi(.sp, .sp, 0x40),
// .blr,
//
//])
//// set used capsule strings in start.dol string table by replacing unused string
//getStringSafelyWithID(id: 0xe2c3).duplicateWithString("[16]'s ability changed from [1a][New Line]to [1b]![Dialogue End]").replace()
//getStringSafelyWithID(id: 0xe2c4).duplicateWithString("The ability could not be changed.[Dialogue End]").replace()
//
//let ac = XGItem(index: 55)
//ac.name.duplicateWithString("Ability Capsule").replace()
//ac.descriptionString.duplicateWithString("Switches a[New Line]Pokémon's ability.").replace()
//ac.holdItemID = 0
//ac.bagSlot = .items
//ac.canBeHeld = true
//ac.couponPrice = 500
//ac.price = 2000
//ac.friendshipEffects = [0,0,0]
//ac.inBattleUseID = 0
//ac.parameter = 0
//ac.function1 = UInt32(capsuleFuncStart) + 0x80000000
//ac.function2 = ac.function1
//ac.save()
//// remove white smoke ability
//XGAssembly.replaceASM(startOffset: 0x222170 - kDolToRAMOffsetDifference, newASM: [
// .b(0x2221f8),
// .nop
//])
//// remove shield dust ability
//XGAssembly.replaceASM(startOffset: 0x214004 - kDolToRAMOffsetDifference, newASM: [
// .b(0x214038),
// .nop
//])
//
//// remove water veil ability
//let wispRoutine = [0x00, 0x02, 0x04, 0x1e, 0x12, 0x00, 0x00, 0x00, 0x14, 0x80, 0x41, 0x5c, 0x93, 0x1d, 0x12, 0x00, 0x00, 0x00, 0x06, 0x80, 0x41, 0x5e, 0xb9, 0x23, 0x12, 0x0a, 0x80, 0x41, 0x5c, 0xc6, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x1d, 0x12, 0x00, 0x00, 0x00, 0x01, 0x80, 0x41, 0x5c, 0x93, 0x01, 0x80, 0x41, 0x5c, 0x93, 0x00, 0x00, 0x20, 0x12, 0x00, 0x4b, 0x80, 0x41, 0x6d, 0xb2, 0x0a, 0x0b, 0x04, 0x2f, 0x80, 0x4e, 0x85, 0xc3, 0x03, 0x17, 0x0b, 0x04, 0x29, 0x80, 0x41, 0x41, 0x0f,]
//XGAssembly.setMoveEffectRoutine(effect: move("will-o-wisp").data.effect, fileOffset: 0x415e32 - kDolTableToRAMOffsetDifference, moveToREL: false, newRoutine: wispRoutine)
//XGAssembly.replaceASM(startOffset: 0x214304 - kDolToRAMOffsetDifference, newASM: [
// .b(0x21436c),
// .nop
//])
//
//// remove oblivious ability
//XGAssembly.replaceASM(startOffset: 0x225518 - kDolToRAMOffsetDifference, newASM: [
// .nop,
// .nop
//])
//XGAssembly.replaceASM(startOffset: 0x2210e8 - kDolToRAMOffsetDifference, newASM: [
// .b(0x221100),
// .nop
//])
//
//// remove own tempo ability
//let dol = XGFiles.dol.data!
//dol.replaceBytesFromOffset(0x411B31 , withByteStream: [0x3b,0x3b,0x3b,0x3b,0x3b,0x3b,0x3b,])
//dol.save()
//XGAssembly.replaceASM(startOffset: 0x21479c - kDolToRAMOffsetDifference, newASM: [
// .nop,
// .nop
//])
//
//// remove magnet pull ability
//XGAssembly.replaceASM(startOffset: 0x20f8a4 - kDolToRAMOffsetDifference, newASM: [
// .b(0x20f910),
// .nop
//])
//
//// remove magnet pull ability
//XGAssembly.replaceASM(startOffset: 0x1f2678 - kDolToRAMOffsetDifference, newASM: [
// .li(.r31, 0),
// .b(0x1f2694),
// .nop
//])
//
//let unaware = XGAbilities.ability(21)
//let sniper = XGAbilities.ability(42)
//unaware.name.duplicateWithString("Unaware").replace()
//unaware.adescription.duplicateWithString("Ignores stat changes.")
//sniper.name.duplicateWithString("Sniper").replace()
//sniper.adescription.duplicateWithString("Stronger critical hits.")
//
//// unaware, sniper
//XGAssembly.replaceASM(startOffset: 0x22a720 - kDolToRAMOffsetDifference, newASM: [
// .li(.r4, 6),
// .lwz(.r3, .sp, 0x30), // defending ability
// .cmpwi(.r3, ability("unaware").index),
// .bne_f(0, 0xc),
// .stw(.r4, .sp, 0x24),
// .stw(.r4, .sp, 0x28),
// .cmpwi(.r27, ability("unaware").index), // attacking ability
// .bne_f(0, 0xc),
// .stw(.r4, .sp, 0x34),
// .stw(.r4, .sp, 0x38),
// .cmpwi(.r27, ability("sniper").index),
// .bne_f(0, 0x14),
// .cmpwi(.r26, 3), // critical hit
// .bne_f(0, 0xc),
// .mulli(.r14, .r14, 3),
// .srawi(.r14, .r14, 1),
//
//])
//
//
//// faster weather animations
//let fasterWeatherAnimationsBranch = 0x211a3c
//let fastWeatherStart = 0xB9AC6C
//let weatherAnimation = 0x210d4c
//// compare r4 with weather indexes and only if not weather, branch link to animation
//XGAssembly.replaceASM(startOffset: fasterWeatherAnimationsBranch - kDolToRAMOffsetDifference, newASM: [.b(fastWeatherStart)])
//XGAssembly.replaceRELASM(startOffset: fastWeatherStart - kRELtoRAMOffsetDifference, newASM: [
// .cmpwi(.r4, 0xc), // sand storm
// .beq_f(0, 0x18),
// .cmpwi(.r4, 0xd), // hail
// .beq_f(0, 0x10),
// .cmpwi(.r4, 0x25), // shadow sky
// .beq_f(0, 0x8),
// .bl(weatherAnimation),
// .b(fasterWeatherAnimationsBranch + 4)
//])
//// 50% berries figy, wiki, mago, aguav, iapapa
//XGAssembly.replaceASM(startOffset: 0x22498c - kDolToRAMOffsetDifference, newASM: [.li(.r4, 4)])
//for i in 143 ... 147 {
// let berry = XGItem(index: i)
// berry.parameter = 2
// berry.save()
//}
//
//// berries after move
//let berryStart = 0x223734
//let berryBranch = 0x2275d0
//XGAssembly.replaceASM(startOffset: berryBranch - kDolToRAMOffsetDifference, newASM: [.bl(berryStart)])
//
//// copied from end turn item activation but ammended to only factor in berries
//XGAssembly.replaceASM(startOffset: berryStart - kDolToRAMOffsetDifference, newASM: [
// .li(.r4, 0),
// .stwu(.sp, .sp, -0x60),
// .mflr(.r0),
// .stw(.r0, .sp, 0x64),
// .stmw(.r20, .sp, 0x30),
// .mr(.r21, .r4),
// .mr(.r31, .r3),
// .li(.r30, 0),
// .li(.r26, 0),
// .mr(.r3, .r31),
// .bl(0x204a70), // check has hp
// .rlwinm_(.r0, .r3, 0, 24, 31),
// .bne_f(0, 0xc),
// .li(.r3, 0),
// .b(0x2247e0),
// .mr(.r3, .r31),
// .bl(0x203870), // get item
// .mr(.r25, .r3),
// .mr(.r3, .r31),
// .bl(0x20384c), // get held item id
// .mr(.r20, .r3),
// .mr(.r3, .r31),
// .bl(0x203828), // get parameter
// .mr(.r27, .r3),
// .mr(.r3, .r31),
// .bl(0x148da8), // get move routine pointer
// .mr(.r22, .r3),
// .mr(.r3, .r31),
// .bl(0x20489c), // get stats
// .mr(.r23, .r3),
// .bl(0x149410), // get hp
// .mr(.r29, .r3),
// .mr(.r3, .r23),
// .bl(0x1493f0), // get max hp
// .mr(.r4, .r25),
// .mr(.r25, .r3),
// .li(.r3, 0),
// .bl(0x1f65bc), // set message param 41 to item
// .rlwinm(.r0, .r20, 0, 16, 31),
// .cmplwi(.r0, 23), // adjusted to max held item id for berries and white herb)
// .ble_f(0, 8),
// .b(0x224774),
// .lis(.r3, 0x8042),
// .rlwinm(.r0, .r0, 2, 0, 29),
// .subi(.r3, .r3, 31296),
// .lwzx(.r0, .r3, .r0),
// .mtctr(.r0),
// .bctr
//
//
//])
//// electric types can't be paralysed 2
//let paraBranch = 0x2144e0
//let paraStart = 0xB9AC8C
//let paraSkip = 0x214660
//let paraTrue = paraBranch + 0x8
//let checkHasType = 0x2054fc
//// compare ability in r22 to limber and compare type to electric battle pokemon in r19
//XGAssembly.replaceASM(startOffset: paraBranch - kDolToRAMOffsetDifference, newASM: [.b(paraStart)])
//XGAssembly.replaceRELASM(startOffset: paraStart - kRELtoRAMOffsetDifference, newASM: [
// .cmpwi(.r0, ability("limber").index),
// .bne_f(0, 8),
// .b(paraSkip),
//
// .mr(.r3, .r19), // battle pokemon
// .li(.r4, XGMoveTypes.electric.rawValue),
// .bl(checkHasType),
// .cmpwi(.r3, 1),
// .bne_f(0, 8),
// .b(paraSkip),
//
// .b(paraTrue)
//
//])
//
//
//// foul play
//let foulBranch = 0x22a188
//let foulStart = 0x22278c
//let foulEnd = foulBranch + 0x8
//let getAttackStat = 0x1493d0
//XGAssembly.replaceASM(startOffset: foulBranch - kDolToRAMOffsetDifference, newASM: [.b(foulStart), .nop])
//XGAssembly.replaceASM(startOffset: foulStart - kDolToRAMOffsetDifference, newASM: [
// .mr(.r20, .r0), // overwritten code
// .mr(.r3, .r17),
//
// // get move data pointer
// .mulli(.r0, .r3, 56),
// .lwz(.r3, .r13, -0x762c),
// .add(.r3, .r3, .r0),
// .lhz(.r3, .r3, 0x1c),
// .cmplwi(.r3, 15),
// .bne_f(0x0, 0x14),
//
// .mr_(.r3, .r18),
// .beq_f(0, 0xc),
//
// .bl(getAttackStat),
// .mr(.r21, .r3),
//
// // return
// .mr(.r3, .r18), // overwritten code
// .b(foulEnd)
//])
//// fix animation inconsistencies 2 for +3 and higher stat boosts
//XGAssembly.replaceASM(startOffset: 0x2117e4 - kDolToRAMOffsetDifference, newASM: [0x40800028])
//
//// unaware, sniper
//XGAssembly.replaceASM(startOffset: 0x22a720 - kDolToRAMOffsetDifference, newASM: [
//
// .li(.r4, 6),
// .lwz(.r3, .sp, 0x30), // defending ability
// .cmpwi(.r3, ability("unaware").index),
// .bne_f(0, 0xc),
// .stw(.r4, .sp, 0x24),
// .stw(.r4, .sp, 0x28),
// .cmpwi(.r27, ability("unaware").index), // attacking ability
// .bne_f(0, 0xc),
// .stw(.r4, .sp, 0x34),
// .stw(.r4, .sp, 0x38),
// .cmpwi(.r27, ability("sniper").index),
// .bne_f(0, 0x14),
// .cmpwi(.r26, 3), // critical hit
// .bne_f(0, 0xc),
// .mulli(.r14, .r14, 3),
// .srawi(.r14, .r14, 1),
//
//])
//
//
//let statBoostAnimationRoutineStart = 0xB9ADE4
//let statBoostAnimationRoutine = [0x2f, 0xff, 0x01, 0x60, 0x1e, 0x00, 0x2f, 0x80, 0x4e, 0x85, 0xc3, 0x00, 0x29, 0x80, 0x41, 0x79, 0x63, 0x3b, 0x3b, 0x3b]
//let rel = XGFiles.common_rel.data!
//rel.replaceBytesFromOffset(statBoostAnimationRoutineStart - kRELtoRAMOffsetDifference, withByteStream: statBoostAnimationRoutine)
//rel.save()
//
//// store value at address
//
//// ability stat booster (r3 index of stat to boost + stages, r4 battle pokemon)
//let statBoosterStart = 0xB9ACC0 //old at 0xB9A6F8
//let getStatIndex = 0x222484
//let getValueWithIndex = 0x142e7c
//let unknownFunc = 0x148a98
//let setParams = 0x1f6780
//let setValueWithIndex = 0x141d14
//let animSoundCallback = 0x2236a8
//
//XGAssembly.replaceRELASM(startOffset: statBoosterStart - kRELtoRAMOffsetDifference, newASM: [
// .stwu(.sp, .sp, -0x50),
// .mflr(.r0),
// .stw(.r0, .sp, 0x54),
// .stmw(.r20, .sp, 0x10),
//
// .mr(.r24, .r3),
// .rlwinm(.r3, .r3, 0, 28, 31), // 0x0000000f stat index to boost
// .mr(.r20, .r3),
// .mr(.r31, .r4),
// .bl(getStatIndex),
//
// .mr(.r29, .r3),
// .mr(.r3, .r31),
// .li(.r4, 0),
// .mr(.r5, .r29),
// .li(.r6, 0),
// .bl(getValueWithIndex),
//
// .cmpwi(.r3, 12),
// .bge_f(0, 0xcc),
//
// .extsb(.r28, .r3),
// .mr(.r3, .r31),
// .bl(unknownFunc),
// .cmplwi(.r3, 2),
// .beq_f(0, 0xb8),
//
// .mr(.r4, .r31),
// .li(.r3, 0),
// .bl(setParams),
//
// .rlwinm(.r3, .r24, 0, 24, 27), // 0x000000f0 stat boost stages
// .srawi(.r21, .r3, 4),
// .add(.r7, .r28, .r21),
// .cmpwi(.r7, 12),
// .ble_f(0, 8),
// .li(.r7, 12),
// .mr(.r3, .r31),
// .mr(.r5, .r29),
// .li(.r4, 0),
// .li(.r6, 0),
// .bl(setValueWithIndex),
//
// .lwz(.r23, .r13, -0x44fc),
// .addis(.r23, .r23, 1),
// .lbz(.r25, .r23, 0x60a4),
// .lbz(.r26, .r23, 0x60a5),
// .lbz(.r27, .r23, 0x601e),
// .lis(.r3, 0x804f),
// .subi(.r3, .r3, 0x10_000 - 0x85C3),
// .lbz(.r22, .r3, 0),
//
// .lis(.r6, 0x80BA),
// .subi(.r6, .r6, 0x10_000 - 0xADE9),
// .stb(.r24, .r6, 0),
//
// .li(.r5, 14),
// .cmpwi(.r21, 1),
// .ble_f(0, 8),
// .nop,
// .add(.r5, .r5, .r20),
//
// .lis(.r3, 0x80BA),
// .subi(.r3, .r3, 0x10_000 - 0xADEF),
// .stb(.r5, .r3, 0),
//
// .li(.r0, 0),
// .stb(.r5, .r23, 0x60a4),
// .stb(.r0, .r23, 0x60a5),
// .lis(.r3, 0x80BA),
// .subi(.r3, .r3, 0x10_000 - 0xADE4),
// .bl(animSoundCallback),
//
// .stb(.r25, .r23, 0x60a4),
// .stb(.r26, .r23, 0x60a5),
// .stb(.r27, .r23, 0x601e),
// .lis(.r3, 0x804f),
// .subi(.r3, .r3, 0x10_000 - 0x85C3),
// .stb(.r22, .r3, 0),
//
// .lmw(.r20, .sp, 0x10),
// .lwz(.r0, .sp, 0x54),
// .mtlr(.r0),
// .addi(.sp, .sp, 0x50),
// .blr,
// .nop
//
//])
//
//// defiant competitive
//let defiantBranch = 0x2223d0
//let defiantStart = 0xB9A7D8
//XGAssembly.replaceASM(startOffset: defiantBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: defiantBranch, toOffset: defiantStart)])
//XGAssembly.replaceRELASM(startOffset: defiantStart - kRELtoRAMOffsetDifference, newASM: [
// 0x7f800774, // extsb r0, r28 (stat change stages)
// 0x28000080, // cmplwi r0, 0x80 // treats negative as big number
// XGAssembly.powerPCBranchGreaterThanOrEqualFromOffset(from: 0x0, to: 0xc),
// 0x3a6d87a0, // overwritten code
// XGAssembly.createBranchFrom(offset: defiantStart + 0x10, toOffset: defiantBranch + 4),
//
// 0x57200673, // rlwinm. r0, r25, 0, 25, 25 (00000040) affects user mask
// XGAssembly.powerPCBranchEqualFromOffset(from: 0x0, to: 0xc),
// 0x3a6d87a0, // overwritten code
// XGAssembly.createBranchFrom(offset: defiantStart + 0x20, toOffset: defiantBranch + 4),
//
// 0x281a0067, // cmpwi r26, defiant
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x18),
//
// 0x38600021, // li r3, attack, 2 stages
// 0x7f04c378, // mr r4, r24
// XGAssembly.createBranchAndLinkFrom(offset: defiantStart + 0x34, toOffset: statBoosterStart),
// 0x3a6d87a0, // overwritten code
// XGAssembly.createBranchFrom(offset: defiantStart + 0x3c, toOffset: defiantBranch + 4),
//
// 0x281a0068, // cmpwi r26, competitive
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x0, to: 0x10),
//
// 0x38600024, // li r3, sp. attack, 2 stages
// 0x7f04c378, // mr r4, r24
// XGAssembly.createBranchAndLinkFrom(offset: defiantStart + 0x50, toOffset: statBoosterStart),
// 0x3a6d87a0, // overwritten code
// XGAssembly.createBranchFrom(offset: defiantStart + 0x58, toOffset: defiantBranch + 4),
//
//])
//
//
//// immune to moves abilities r31 current move r3 defending ability
//let originOffset = 0x225804
//let originNopOffset = 0x225838
//let immunitiesStart = 0xB9A05C
//let statBoost = 0xB9ACC0
//
//let moveGetSnatchFlag = 0x13e5e4
//let moveGetSoundFlag = 0x13e548
//let moveGetType = 0x13e870
//let moveCheckShadow = 0x13e514
//
//let powerupImmune = 0x14c
//let immune = 0x154
//let powerupNotImmune = 0x15c
//let notImmune = 0x164
//
//XGAssembly.replaceASM(startOffset: originOffset - kDolToRAMOffsetDifference, newASM: [0x3bc00000,XGAssembly.createBranchAndLinkFrom(offset: originOffset + 0x4, toOffset: immunitiesStart),0x28030001])
//XGAssembly.replaceASM(startOffset: originNopOffset - kDolToRAMOffsetDifference, newASM: [kNopInstruction])
//XGAssembly.replaceRELASM(startOffset: immunitiesStart - kRELtoRAMOffsetDifference, newASM: [
//0x9421ffdc, 0x7c0802a6, 0x90010028, 0x93e1001c, 0x93c10018, 0x93a10014, 0x93810010, 0x93610020,
//
//// 0x20
//0x7c7c1b78, // mr r28,r3
//0x7fe3fb78, // mr r3, r31
//XGAssembly.createBranchAndLinkFrom(offset: immunitiesStart + 0x28, toOffset: moveGetSnatchFlag),
//0x7c7e1b78, // mr r30, r3
//0x7fe3fb78, // mr r3, r31
//XGAssembly.createBranchAndLinkFrom(offset: immunitiesStart + 0x34, toOffset: moveGetSoundFlag),
//0x7C7D1B78, // mr r29, r3
//0x7fe3fb78, // mr r3, r31
//XGAssembly.createBranchAndLinkFrom(offset: immunitiesStart + 0x40, toOffset: moveCheckShadow),
//0x7c7b1b78, // mr r27, r3
//0x7fe3fb78, // mr r3, r31
//XGAssembly.createBranchAndLinkFrom(offset: immunitiesStart + 0x4c, toOffset: moveGetType),
//0x7C7F1B78, // mr r31, r3
//0x7f83e378, //mr r3,r28
//
//// 0x58 bulletproof
//0x2803004e,0x4082000c,0x281e0001,XGAssembly.powerPCBranchEqualFromOffset(from: 0x64, to: immune),
//
//// 0x68 soundproof
//0x2803002b,0x40820010,0x281d0001,0x40820008,XGAssembly.createBranchFrom(offset: 0x78, toOffset: immune),
//
//// 0x7c lightning rod
//0x2803001f,0x40820014,0x281f000d,0x4082000c,0x38600014,XGAssembly.createBranchFrom(offset: 0x90, toOffset: powerupImmune),
//
//// 0x94 motor drive
//0x2803005f,0x40820014,0x281f000d,0x4082000c,0x38600013,XGAssembly.createBranchFrom(offset: 0xa8, toOffset: powerupImmune),
//
//// 0xac storm drain
//0x28030060,0x40820014,0x281f000b,0x4082000c,0x38600014,XGAssembly.createBranchFrom(offset: 0xc0, toOffset: powerupImmune),
//
//// 0xc4 sap sipper
//0x28030061,0x40820014,0x281f000c,0x4082000c,0x38600011,XGAssembly.createBranchFrom(offset: 0xd8, toOffset: powerupImmune),
//
//// 0xdc justified on dark moves
//0x28030062,0x40820024,0x281f0011,0x4082000c,0x38600011,XGAssembly.createBranchFrom(offset: 0xf0, toOffset: powerupNotImmune),
//
//// 0xf4 justified on shadow moves
//0x281b0001,0x4082000c,0x38600021,XGAssembly.createBranchFrom(offset: 0x100, toOffset: powerupNotImmune),
//
//// 0x104 rattled on bug moves
//0x2803003c,0x4082005c,0x281f0006,0x4082000c,0x38600013,XGAssembly.createBranchFrom(offset: 0x118, toOffset: powerupNotImmune),
//// 0x11c rattled on ghost moves
//0x281f0007,0x4082000c,0x38600013,XGAssembly.createBranchFrom(offset: 0x128, toOffset: powerupNotImmune),
//// 0x12c rattled on dark moves
//0x281f0011,0x4082000c,0x38600013,XGAssembly.createBranchFrom(offset: 0x138, toOffset: powerupNotImmune),
//// 0x13c rattled on shadow moves
//0x281b0001,0x40820024,0x38600013,XGAssembly.createBranchFrom(offset: 0x148, toOffset: powerupNotImmune),
//
//
//
//// 0x14c power up immune
//0x80810014,
//XGAssembly.createBranchAndLinkFrom(offset: immunitiesStart + 0x150, toOffset: statBoost),
//
//// 0x154 immune
//0x38600001,
//0x48000010,
//
//// 0x15c power up not immune
//0x80810014,
//XGAssembly.createBranchAndLinkFrom(offset: immunitiesStart + 0x160, toOffset: statBoost),
//
//// 0x164 not immune
//0x38600000,
//
//// 0x168
//0x80010028, 0x83e1001c, 0x83c10018, 0x83a10014, 0x83810010, 0x83610020, 0x7c0803a6, 0x38210024, 0x4e800020
//])
//
//// check if move immune ability is being activated on user
//let immuneSelfBranch = 0x2257f4
//let immuneSelfStart = 0xB99F8C
//let getMoveTargets = 0x13e784
//let selfReturn = 0x22580c
//let notSelfReturn = 0x225800
//XGAssembly.replaceASM(startOffset: immuneSelfBranch - kDolToRAMOffsetDifference, newASM: [
// 0x7C7F1B78, // mr r31, r3
// XGAssembly.createBranchAndLinkFrom(offset: immuneSelfBranch + 0x4, toOffset: getMoveTargets),
// XGAssembly.createBranchFrom(offset: immuneSelfBranch + 0x8, toOffset: immuneSelfStart),
//])
//XGAssembly.replaceRELASM(startOffset: immuneSelfStart - kRELtoRAMOffsetDifference, newASM: [
//
// 0x28030005, // cmpwi r3, move user
// 0x40820010, // bne 0x10
// 0x38600000, // li r3, 0
// 0x3bc00000, // li r30, 0
// XGAssembly.createBranchFrom(offset: immuneSelfStart + 0x10, toOffset: selfReturn),
// 0x7fa3eb78, // mr r3, r29
// XGAssembly.createBranchFrom(offset: immuneSelfStart + 0x18, toOffset: notSelfReturn),
//
//])
//
//
//
//// moxie
//let moxieBranch = 0x225108
//let moxieStart = 0xb9a294
//let checkHP = 0x204a70
////let statBoost = 0xB9ACC0
//
//XGAssembly.replaceASM(startOffset: moxieBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: moxieBranch, toOffset: moxieStart)])
//XGAssembly.replaceRELASM(startOffset: moxieStart - kRELtoRAMOffsetDifference, newASM: [
//0x7fe3fb78, // mr r3, r31 (defending pokemon pointer)
//XGAssembly.createBranchAndLinkFrom(offset: moxieStart + 0x4, toOffset: checkHP),
//0x28030001, // cmpwi r3, 1
//XGAssembly.powerPCBranchEqualFromOffset(from: 0xc, to: 0x2c),
//
//0x7fc3f378, // mr r3, r30 (attacking pokemon pointer)
//0xa063080c, // lhz r3, 0x80c(r3) (get ability)
//0x2803003a, // cmpwi r3, moxie
//XGAssembly.powerPCBranchNotEqualFromOffset(from: 0x1c, to: 0x2c),
//
//0x38600011, // li r3, attack stat, 1 stage
//0x7fc4f378, // mr r4, r30 battle pokemon
//XGAssembly.createBranchAndLinkFrom(offset: moxieStart + 0x28, toOffset: statBoost),
//
//0x5704043e, // rlwinm r4, r24, 0, 16, 31 (0000ffff) overwritten code
//XGAssembly.createBranchFrom(offset: moxieStart + 0x30, toOffset: moxieBranch + 0x4),
//
//])
//
//
//
//// ability activation animation
//let abilityActivateStart = 0xB9ADF8
////let getStatIndex = 0x222484
////let getValueWithIndex = 0x142e7c
////let unknownFunc = 0x148a98
////let setParams = 0x1f6780
////let setValueWithIndex = 0x141d14
////let animSoundCallback = 0x2236a8
//
//XGAssembly.replaceRELASM(startOffset: abilityActivateStart - kRELtoRAMOffsetDifference, newASM: [
// .stwu(.sp, .sp, -0x50),
// .mflr(.r0),
// .stw(.r0, .sp, 0x54),
// .stmw(.r20, .sp, 0x10),
//
// .mr(.r4, .r3),
// .li(.r3, 0),
// .bl(setParams),
//
// .lwz(.r23, .r13, -0x44fc),
// .addis(.r23, .r23, 1),
// .lbz(.r25, .r23, 0x60a4),
// .lbz(.r26, .r23, 0x60a5),
// .lbz(.r27, .r23, 0x601e),
// .lis(.r3, 0x804f),
// .subi(.r3, .r3, 0x10_000 - 0x85C3),
// .lbz(.r22, .r3, 0),
//
// .lis(.r6, 0x80BA),
// .subi(.r6, .r6, 0x10_000 - 0xADE9),
//
// .li(.r24, 0x16),
// .stb(.r24, .r6, 0),
//
// .lis(.r3, 0x80BA),
// .subi(.r3, .r3, 0x10_000 - 0xADEF),
// .li(.r5, 20),
// .stb(.r5, .r3, 0),
//
// .li(.r0, 0),
// .stb(.r5, .r23, 0x60a4),
// .stb(.r0, .r23, 0x60a5),
// .lis(.r3, 0x80BA),
// .subi(.r3, .r3, 0x10_000 - 0xADE4),
// .bl(animSoundCallback),
//
// .stb(.r25, .r23, 0x60a4),
// .stb(.r26, .r23, 0x60a5),
// .stb(.r27, .r23, 0x601e),
// .lis(.r3, 0x804f),
// .subi(.r3, .r3, 0x10_000 - 0x85C3),
// .stb(.r22, .r3, 0),
//
// .lmw(.r20, .sp, 0x10),
// .lwz(.r0, .sp, 0x54),
// .mtlr(.r0),
// .addi(.sp, .sp, 0x50),
// .blr,
// .nop
//
// ])
//
//
//// natural cure activation message
//let naturalBranch = 0x21c5fc
//let naturalStart = 0x2226e4
//let naturalEnd = naturalBranch + 0x4
//XGAssembly.replaceASM(startOffset: naturalBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: naturalBranch, toOffset: naturalStart)])
//XGAssembly.replaceASM(startOffset: naturalStart - kDolToRAMOffsetDifference, newASM: [
// 0x7fe3fb78, // mr r3, r31
// XGAssembly.createBranchAndLinkFrom(offset: naturalStart + 0x4, toOffset: abilityActivateStart),
// 0x7fe3fb78, // mr r3, r31
// XGAssembly.createBranchFrom(offset: naturalStart + 0xc, toOffset: naturalEnd)
//])
//
//// trace, download, trickster
//let get_pointer_index_func = 0x1f3f3c
//let get_pointer_general_func = 0x1efcac
//let check_status_func = 0x1f848c
//let set_status_function = 0x1f8438
//let end_status_function = 0x1f8534
//
//let entryBranch = 0x225d18
//let entryStart = 0x222554
//let entryEnd = 0x225d1c
//let traceStart = entryStart + 0x20
//let downloadStart = traceStart + 0x44
//let tricksterStart = downloadStart + 0x14
//let traceIndex : UInt32 = 36
//let downloadIndex : UInt32 = 100
//let tricksterIndex : UInt32 = 57
//let checkSetStatus = 0x20254c
//let setStatus = 0x2024a4
//let activate = abilityActivateStart
//XGAssembly.replaceASM(startOffset: entryBranch - kDolToRAMOffsetDifference, newASM: [XGAssembly.createBranchFrom(offset: entryBranch, toOffset: entryStart)])
//XGAssembly.replaceASM(startOffset: entryStart - kDolToRAMOffsetDifference, newASM: [
// 0x5460043e, // rlwinm r0, r3
// 0x28000000 + traceIndex, // cmpwi r0, trace
// XGAssembly.powerPCBranchEqualFromOffset(from: entryStart + 0x8, to: traceStart), // beq traceStart:
// 0x28000000 + downloadIndex, // cmpwi r0, download
// XGAssembly.powerPCBranchEqualFromOffset(from: entryStart + 0x10, to: downloadStart), // beq downloadStart:
// 0x28000000 + tricksterIndex, // cmpwi r0, trickster
// XGAssembly.powerPCBranchEqualFromOffset(from: entryStart + 0x18, to: tricksterStart), // beq tricksterStart:
// XGAssembly.createBranchFrom(offset: entryStart + 0x1c, toOffset: entryEnd), // b entryEnd
// //traceStart: 0x20 -------->
// 0x7fe3fb78, // mr r3, r31
// 0x8863084d, // lbz r3, 0x084d(r3)
// 0x5460063f, // rlwinm r0, r3
// XGAssembly.powerPCBranchNotEqualFromOffset(from: traceStart + 0xc, to: entryEnd), // bne entryEnd
// 0x7fe3fb78, // mr r3, r31
// 0x3880003c, // li r4, 60
// XGAssembly.createBranchAndLinkFrom(offset:traceStart + 0x18, toOffset: checkSetStatus),// bl checkIfCanSetStatus
// 0x28030002, // cmpwi r3, 2
// XGAssembly.powerPCBranchNotEqualFromOffset(from: 0, to: 0x14), // bne don't set
// 0x7fe3fb78, // mr r3, r31
// 0x3880003c, // li r4, 60
// 0x38a00000, // li r5, 0
// XGAssembly.createBranchAndLinkFrom(offset: traceStart + 0x30, toOffset: setStatus), // bl set status
// 0x7fe3fb78, // mr r3, r31
// 0x38800001, // li r4, 1
// 0x9883084d, // stb r4, 0x084d(r3)
// XGAssembly.createBranchFrom(offset: traceStart + 0x40, toOffset: entryEnd), // b entryEnd
// //downloadStart: 0x64 -------->
// 0x7fe3fb78, // mr r3, r31
// 0x7C641B78, // mr r4, r3
// 0x38600004, // li r3, 4
// XGAssembly.createBranchAndLinkFrom(offset: downloadStart + 0xc, toOffset: activate), // bl activate ability (stat boost)
// XGAssembly.createBranchFrom(offset: downloadStart + 0x10, toOffset: entryEnd), // b entry end
// //tricksterStart: 0x78 -------->
// 0x7fe3fb78, // mr r3, r31
// XGAssembly.createBranchAndLinkFrom(offset: tricksterStart + 0x4, toOffset: abilityActivateStart),
// 0x38600000, // li r3, 0
// XGAssembly.createBranchAndLinkFrom(offset: tricksterStart + 0x0c, toOffset: get_pointer_index_func), // bl get_pointer_index
// 0x7C641B78, // mr r4, r3
// 0x38600002, // li r3, 2
// XGAssembly.createBranchAndLinkFrom(offset: tricksterStart + 0x18, toOffset: get_pointer_general_func), // bl get_pointer_general
// 0x7C7F1B78, // mr r31, r3
// 0x3880004C, // li r4, 76
// XGAssembly.createBranchAndLinkFrom(offset: tricksterStart + 0x24, toOffset: check_status_func), // bl check_status
// 0x28030002, // cmpwi r3, 2
// XGAssembly.powerPCBranchNotEqualFromOffset(from: tricksterStart + 0x2c, to: entryEnd),
// 0x7fe3fb78, //0x28 mr r3, r31
// 0x3880004C, //0x2c li r4, 76
// 0x38a00000, //0x30 li r5, 0
// XGAssembly.createBranchAndLinkFrom(offset: tricksterStart + 0x3c, toOffset: set_status_function), //0x34 bl set_status
// 0x38600001, //0x38 li r3, 1
// XGAssembly.createBranchAndLinkFrom(offset: tricksterStart + 0x44, toOffset: get_pointer_index_func), //0x3c bl get_pointer_index
// 0x7C641B78, //0x40 mr r4, r3
// 0x38600002, //0x44 li r3, 2
// XGAssembly.createBranchAndLinkFrom(offset: tricksterStart + 0x50, toOffset: get_pointer_general_func), //0x48 bl get_pointer_general
// 0x3880004C, //0x4c li r4, 76
// 0x38a00000, //0x50 li r5, 0
// XGAssembly.createBranchAndLinkFrom(offset: tricksterStart + 0x5c, toOffset: set_status_function), //0x54 bl set_status
// XGAssembly.createBranchFrom(offset: tricksterStart + 0x60, toOffset: entryEnd), //0x58 b entry end:
//])
//// one trick room expiry message
//getStringSafelyWithID(id: 20099).duplicateWithString("The [0d] wore off!").replace()
//let trickExpireBranch = 0x228dc4
//let trickExpireStart = 0xB9AEC4
//let trickExpireSkip = 0x228dd0
//XGAssembly.replaceASM(startOffset: trickExpireBranch - kDolToRAMOffsetDifference, newASM: [.b(trickExpireStart)])
//XGAssembly.replaceRELASM(startOffset: trickExpireStart - kRELtoRAMOffsetDifference, newASM: [
// .cmplwi(.r28, 1),
// .bne_f(0, 8),
// .b(trickExpireSkip),
// .lis(.r3, 0x8041), // overwritten code
// .b(trickExpireBranch + 4)
//])
//// moves thaw from frozen
//let thawBranch = 0x226d6c
//let thawStart = 0xB9AED8
//let thawTrue = thawStart + 0x38
//let thawFalse = thawStart + 0x3c
//XGAssembly.replaceASM(startOffset: thawBranch - kDolToRAMOffsetDifference, newASM: [.b(thawStart), .nop, .nop])
//XGAssembly.replaceRELASM(startOffset: thawStart - kRELtoRAMOffsetDifference, newASM: [
// .cmpwi(.r30, move("flame wheel").index),
// .beq(thawTrue),
// .cmpwi(.r30, move("flare blitz").index),
// .beq(thawTrue),
// .cmpwi(.r30, move("scald").index),
// .beq(thawTrue),
// .cmpwi(.r30, move("sacred fire").index),
// .beq(thawTrue),
// .cmpwi(.r30, move("shadow blaze").index),
// .beq(thawTrue),
// .cmpwi(.r30, move("shadow tribute").index),
// .beq(thawTrue),
// .cmpwi(.r26, 125), // move effect burn chance and thaw from frozen
// .bne(thawFalse),
// // thaw true 0x38
// .b(0x226da4),
// // thaw false 0x3c
// .b(0x226d78)
//])
// lode stone evolution item
//let linkItem = XGItems.item(99).data
//linkItem.function1 = 0x800a54ac
//linkItem.function2 = 0x800a54ac
//linkItem.inBattleUseID = 53
//linkItem.save()
//// set confusion chance to hurt user to 1 in 3
//let confusionStart = 0x2270f0
//XGAssembly.replaceASM(startOffset: confusionStart - kDolToRAMOffsetDifference, newASM: [
// .cmplwi(.r3, 0x5555), // 1 in 3
// .bgt(0x227110), // not confused
//])
//// item activation function
//let itemActivationStringID = 1426
//let table = XGFiles.msg("fight")
//let string = XGString(string: "[Pokemon 0x10]'s [Item 0x29] activated.", file: table, sid: itemActivationStringID)
//_ = table.stringTable.addString(string, increaseSize: true, save: true)
//
//let itemActivationStart = 0xB9B3C0
//let setMessageParam = 0x2370ec // r3 = param index, r4 = value
//let getItemID = 0x203870
//let getItemName = 0x15ef7c
//let getString = 0x107300
//let displayMessage = 0x20f568
//let pause = 0x1ef5a4
//let displayBattleMessage = 0xB9B41C
//
//// display an msg id in battle
//let displayMessageStart = 0xB9B41C
//XGAssembly.replaceRamASM(RAMOffset: displayMessageStart, newASM: [
// .stwu(.sp, .sp, -0x10),
// .mflr(.r0),
// .stw(.r0, .sp, 0x14),
// .bl(displayMessage),
// .li(.r3, 32),
// .bl(pause),
// .lwz(.r0, .sp, 0x14),
// .mtlr(.r0),
// .addi(.sp, .sp, 0x10),
// .blr
//])
//XGAssembly.replaceRamASM(RAMOffset: itemActivationStart, newASM: [
// .stwu(.sp, .sp, -0x10),
// .mflr(.r0),
// .stw(.r0, .sp, 0x14),
// .stmw(.r30, .sp, 0x8),
// .mr(.r31, .r3),
//
// .mr(.r4, .r3),
// .li(.r3, 0x10),
// .bl(setMessageParam),
//
// .mr(.r3, .r31),
// .bl(getItemID),
// .bl(getItemName),
// .bl(getString),
// .mr(.r4, .r3),
// .li(.r3, 0x29),
// .bl(setMessageParam),
//
// .li(.r3, itemActivationStringID),
// .bl(displayBattleMessage),
// .nop,
//
// .lmw(.r30, .sp, 0x8),
// .lwz(.r0, .sp, 0x14),
// .mtlr(.r0),
// .addi(.sp, .sp, 0x10),
// .blr
//])
//
//// new trick room tailwind
//let trickStart = 0xB9B51C
//let trickBranch = 0x1f4430
//let getPokemonPointer = 0x1efcac
//let getFieldEffect = 0x1f84e0
//XGAssembly.replaceRamASM(RAMOffset: trickBranch, newASM: [.bl(trickStart)])
//XGAssembly.replaceRamASM(RAMOffset: trickStart, newASM: [
// .stwu(.sp, .sp, -0x10),
// .mflr(.r0),
// .stw(.r0, .sp, 0x14),
// .stw(.r28, .sp, 0x8),
// .stw(.r31, .sp, 0xc),
//
// .mr(.r4, .r26),
// .li(.r3, 2),
// .bl(getPokemonPointer),
// .mr(.r31, .r3),
//
// .mr(.r4, .r25),
// .li(.r3, 2),
// .bl(getPokemonPointer),
// .mr(.r28, .r3),
//
// .label("tail wind checks"),
// .li(.r4, XGStatusEffects.safeguard.rawValue), // edited to tailwind
// .bl(getFieldEffect),
// .cmpwi(.r3, 1),
// .bne_f(0, 8),
// .rlwinm(.r29, .r29, 1, 0, 30), // double speed
//
// .mr(.r3, .r31),
// .li(.r4, XGStatusEffects.safeguard.rawValue), // edited to tailwind
// .bl(getFieldEffect),
// .cmpwi(.r3, 1),
// .bne_f(0, 8),
// .rlwinm(.r30, .r30, 1, 0, 30), // double speed
//
// .label("trick room checks"),
// .mr(.r3, .r28),
// .li(.r4, XGStatusEffects.mist.rawValue), // edited to trick room
// .bl(getFieldEffect),
// .cmpwi(.r3, 1),
// .beq_l("compare reversed"),
//
// .mr(.r3, .r31),
// .li(.r4, XGStatusEffects.mist.rawValue), // edited to trick room
// .bl(getFieldEffect),
// .cmpwi(.r3, 1),
// .beq_l("compare reversed"),
//
// .label("compare normal"),
// .cmplw(.r29, .r30),
// .b_l("return"),
//
// .label("compare reversed"),
// .cmplw(.r30, .r29),
//
// .label("return"),
// .lwz(.r28, .sp, 0x8),
// .lwz(.r31, .sp, 0xc),
// .lwz(.r0, .sp, 0x14),
// .mtlr(.r0),
// .addi(.sp, .sp, 0x10),
// .blr
//])
//
//// rewrite original code
//XGAssembly.replaceRamASM(RAMOffset: 0x225ab4, newASM: [.lmw(.r28, .sp, 0x10)])
//
//// flame orb toxic orb poison heal
//let orbBranch = 0x227eb4
//let orbStart = 0xB9A8B4
//let checkFullHP = 0x201d20
//let checkStatus = 0x2025f0
//let checkSetStatus = 0x20254c
//let checkHasType = 0x2054fc
//let setStatus = 0x2024a4
//let checkNoStatus = 0x203744
//let getHPFraction = 0x203688
//let storeHPLoss = 0x13e094
//let animSoundCallback = 0x2236a8
//let getItem = 0x20384c // get item's hold item id
//let itemMessage = 0xB9B3C0
//
//let healOffset = orbStart + 0x34
//let flameOrbOffset = orbStart + 0x6c
//let toxicOrbOffset = orbStart + 0xec
//let returnOffset = orbStart + 0x174
//
//XGAssembly.replaceASM(startOffset: orbBranch - kDolToRAMOffsetDifference, newASM: [ .b(orbStart) ])
//XGAssembly.replaceRELASM(startOffset: orbStart - kRELtoRAMOffsetDifference, newASM: [
//
// .lhz(.r3, .r31, 0x80c), // get ability
// .cmpwi(.r3, ability("poison heal").index),
// .bne(flameOrbOffset),
// .mr(.r3, .r31),
// .li(.r4, 3), // poison
// .bl(checkStatus),
// .cmpwi(.r3, 1),
// .beq(healOffset),
// .mr(.r3, .r31),
// .li(.r4, 4), // bad poison
// .bl(checkStatus),
// .cmpwi(.r3, 1),
// .bne(flameOrbOffset),
//
// //heal offset 0x34
// .mr(.r3, .r31),
// .bl(checkFullHP),
// .cmpwi(.r3, 1),
// .beq(flameOrbOffset),
// .mr(.r3, .r31),
// .li(.r4, 8), // 1/8 max hp
// .bl(getHPFraction),
// .rlwinm(.r0, .r3, 0, 16, 31),
// .neg(.r4, .r0),
// .mr(.r3, .r30),
// .bl(storeHPLoss),
// .lis(.r3, 0x8041),
// .addi(.r3, .r3, 31004),
// .bl(animSoundCallback),
//
// // flame orb offset 0x6c
// .mr(.r3, .r31),
// .bl(getItem),
// .cmpwi(.r3, item("flame orb").data.holdItemID),
// .bne(toxicOrbOffset),
//
// .mr(.r3, .r31),
// .li(.r4, XGMoveTypes.fire.rawValue),
// .bl(checkHasType),
// .cmpwi(.r3, 1),
// .beq(returnOffset),
//
// .mr(.r3, .r31),
// .bl(checkNoStatus),
// .cmpwi(.r3, 1),
// .bne(returnOffset),
//
// .nop,
// .nop,
// .nop,
//
// // activate burn
// .mr(.r3, .r31),
// .li(.r4, 6), // burn
// .bl(checkSetStatus),
// .cmpwi(.r3, 2),
// .bne(returnOffset),
// .mr(.r3, .r31),
// .li(.r4, 6), // burn
// .li(.r5, 0),
// .bl(setStatus),
//
//
// .nop,
// .nop,
// .nop,
// .nop,
// .mr(.r3, .r31),
// .bl(itemMessage),
// .b(returnOffset),
//
//
// // toxic orb offset 0xec
// .cmpwi(.r3, item("toxic orb").data.holdItemID),
// .bne(returnOffset),
//
// .mr(.r3, .r31),
// .li(.r4, XGMoveTypes.poison.rawValue),
// .bl(checkHasType),
// .cmpwi(.r3, 1),
// .beq(returnOffset),
//
// .mr(.r3, .r31),
// .li(.r4, XGMoveTypes.steel.rawValue),
// .bl(checkHasType),
// .cmpwi(.r3, 1),
// .beq(returnOffset),
//
// .mr(.r3, .r31),
// .bl(checkNoStatus),
// .cmpwi(.r3, 1),
// .bne(returnOffset),
//
// .lhz(.r3, .r31, 0x80c), // get ability
// .cmpwi(.r3, ability("immunity").index),
// .beq(returnOffset),
//
// // activate poison
//
// .mr(.r3, .r31),
// .li(.r4, 4), // badly poisoned
// .bl(checkSetStatus),
// .cmpwi(.r3, 2),
// .bne(returnOffset),
// .mr(.r3, .r31),
// .li(.r4, 4), // badly poisoned
// .li(.r5, 0),
// .bl(setStatus),
//
// .nop,
// .nop,
// .nop,
// .nop,
// .mr(.r3, .r31),
// .bl(itemMessage),
//
// // return offset 0x174
// .lwz(.r0, .r13, -0x44e8), // overwritten code
// .b(orbBranch + 0x4)
//])
//
//// sound moves hit through substitute
//let subJumpBranch = 0x2135ac
//let subJumpStart = 0xB9AF18
//let getPokemonPointer = 0x1efcac
//let getCurrentMove = 0x148d64
//let moveGetSoundFlag = 0x13e548
//let moveRoutineGetPosition = 0x2236f8
//XGAssembly.replaceRamASM(RAMOffset: subJumpBranch, newASM: [
// .b(subJumpStart),
// .cmpwi(.r3, 1)
//])
//XGAssembly.replaceRamASM(RAMOffset: subJumpStart, newASM: [
// .cmpwi(.r3, 1),
// .beq_f(0, 8),
// .b(subJumpBranch + 4),
// .lwz(.r0, .r13, -0x44F0),
// .lwz(.r0, .r0, 2),
// .cmpwi(.r0, XGStatusEffects.substitute.rawValue),
// .beq_f(0, 8),
// .b(subJumpBranch + 4),
// .li(.r3, 17), // attacking pokemon
// .li(.r4, 0),
// .bl(getPokemonPointer),
// .bl(getCurrentMove),
// .bl(moveGetSoundFlag),
// .cmpwi(.r3, 1),
// .beq_f(0, 0xc),
// .li(.r3, 1),
// .b(subJumpBranch + 4),
// .li(.r3, 0),
// .b(subJumpBranch + 4),
//
//])
//let subDamageBranch = 0x216054
//let subDamageStart = 0xB9AF64
////let moveGetSoundFlag = 0x13e548
//XGAssembly.replaceRamASM(RAMOffset: subDamageBranch, newASM: [
// .b(subDamageStart),
// .nop
//])
//XGAssembly.replaceRamASM(RAMOffset: subDamageStart, newASM: [
// .cmpwi(.r3, 1),
// .beq_f(0, 0xc),
// .b(subDamageBranch + 8),
// // sound check
// .mr(.r3, .r28),
// .bl(moveGetSoundFlag),
// .cmpwi(.r3, 1),
// .bne_f(0, 8),
// // sound move so count as no sub
// .b(subDamageBranch + 8),
// // not sound move so count sub as normal
// .b(0x21614c)
//])
//let subReduceHPBranch = 0x215868
//let subReduceHPStart = 0xB9AF88
////let moveGetSoundFlag = 0x13e548
//XGAssembly.replaceRamASM(RAMOffset: subReduceHPBranch, newASM: [
// .mr(.r18, .r3),
// .b(subReduceHPStart)
//])
//XGAssembly.replaceRamASM(RAMOffset: subReduceHPStart, newASM: [
// .cmpwi(.r3, 0),
// .bne_f(0, 8),
// .b(0x2158e0),
//
// .mr(.r3, .r25),
// .bl(moveGetSoundFlag),
// .cmpwi(.r3, 1),
// .bne_f(0, 0xc),
//
// .li(.r18, 0),
// .b(0x2158e0),
//
// .b(subReduceHPBranch + 8)
//
//])
//
//// super effective type damage reducing berries
//
//for i in item("chople berry").index ... item("colbur berry").index {
// let itemData = XGItems.item(i).data
// let type = XGMoveTypes(rawValue: i - item("chilan berry").index) ?? .normal
// itemData.parameter = type.rawValue
// itemData.save()
// _ = itemData.descriptionString.duplicateWithString("Weakens one[New Line]super effective[New Line]\(type.name.lowercased()) type move.").replace()
//}
//var itemData = item("chilan berry").data
//itemData.parameter = XGMoveTypes.normal.rawValue
//itemData.save()
//_ = itemData.descriptionString.duplicateWithString("A hold item[New Line]that weakens one[New Line]normal type move.").replace()
//
//itemData = item("dosha berry").data
//itemData.parameter = 255
//itemData.save()
//_ = itemData.descriptionString.duplicateWithString("A hold item[New Line]that weakens one[New Line]shadow move.").replace()
//
//for i in item("chilan berry").index ... item("dosha berry").index {
// let itemData = XGItems.item(i).data
// itemData.holdItemID = 81
// itemData.friendshipEffects = [2,1,0]
// itemData.inBattleUseID = 0
// itemData.canBeHeld = true
// itemData.couponPrice = 50
// itemData.price = 20
// itemData.bagSlot = .berries
// itemData.save()
//}
//
//let typeBerriesBranch = 0x215ffc
//let typeBerriesStart = 0xB9B020
//let getAdjustedMoveType = 0x13e134
//let checkShadowMove = 0x13d03c
//let getEffectiveness = 0x1f0684
//let checkSetEffectiveness = 0x1f05d0
//let setEffectiveness = 0x1f057c
//let getStatsPointer = 0x148e0c
////let getPokemonPointer = 0x1efcac
//let getMoveRoutinePointer = 0x148da8
//// set message id 20148 to pokemon's berry activated param 41 item
//XGAssembly.replaceRamASM(RAMOffset: typeBerriesBranch, newASM: [.b(typeBerriesStart), .nop])
//XGAssembly.replaceRamASM(RAMOffset: typeBerriesStart, newASM: [
// .cmpwi(.r23, item("haban berry").data.holdItemID), // all type berries use same id
// .bne_l("return"),
//
// .mr(.r3, .r28),
// .bl(checkShadowMove),
// .cmpwi(.r3, 1),
// .bne_l("type check"),
//
// .cmpwi(.r30, 0xff), // shadow berry parameter
// .beq_l("reduce damage"),
// .b_l("return"),
//
// .label("type check"),
// .li(.r3, 17), // attacking pokemon
// .li(.r4, 0),
// .bl(getPokemonPointer),
// .bl(getMoveRoutinePointer),
// .bl(getAdjustedMoveType),
// .cmpw(.r3, .r30), // compare with item parameter
// .bne_l("return"),
//
// .cmpwi(.r30, XGMoveTypes.normal.rawValue),
// .beq_l("reduce damage"),
//
// .li(.r3, 17), // attacking pokemon
// .li(.r4, 0),
// .bl(getPokemonPointer),
// .bl(getMoveRoutinePointer),
// .li(.r4, XGStatusEffects.super_effective.rawValue),
// .bl(getEffectiveness),
// .cmpwi(.r3, 1),
// .bne_l("return"),
//
// .label("reduce damage"),
// .mr(.r3, .r26),
// .li(.r4, XGStatusEffects.endured.rawValue),
// .bl(checkSetEffectiveness),
// .cmpwi(.r3, 2),
// .bne_l("return"),
//
// .mr(.r3, .r26),
// .li(.r4, XGStatusEffects.endured.rawValue),
// .li(.r5, 0),
// .bl(setEffectiveness),
//
// .li(.r3, 2),
// .divw(.r25, .r25, .r3), // halve damage
//
// .label("return"),
// .cmpwi(.r25, 0),
// .bne_f(0, 8),
// .li(.r25, 1),
// .b(typeBerriesBranch + 4),
//
//])
//let typeBerryRemoveBranches = [0x2152f0, 0x2153ec]
//let typeBerryRemoveStart = 0xB9B0E8
//let typeBerryRemoveEnd = 0x215470 // branch here when done
//for branch in typeBerryRemoveBranches {
// XGAssembly.replaceRamASM(RAMOffset: branch, newASM: [
// .b(typeBerryRemoveStart),
// .nop
// ])
//}
//XGAssembly.replaceRamASM(RAMOffset: typeBerryRemoveStart, newASM: [
// .li(.r28, 20148), // "[pokemon 0x10] endured the hit", changed to "[pokemon 0x10]'s [Item 0x29][New Line]weakened the move!"
// .li(.r3, 18), // defending pokemon
// .li(.r4, 0),
// .bl(getPokemonPointer),
// .lwz(.r3, .r3, 0),
// .li(.r4, 0),
// .sth(.r4, .r3, 6), // delete pokemon's item
// .b(typeBerryRemoveEnd)
//])
//
//// Super luck
//let superLuck = XGAbilities.ability(12)
//_ = superLuck.name.duplicateWithString("Super Luck").replace()
//_ = superLuck.adescription.duplicateWithString("Increases critical rate.").replace()
//
//let superLuckBranch = 0x216fa0
//let superLuckStart = 0xB9B108
//let getAbility = 0x2055c8
////let getPokemonPointer = 0x1efcac
//XGAssembly.replaceRamASM(RAMOffset: superLuckBranch, newASM: [.b(superLuckStart)])
//XGAssembly.replaceRamASM(RAMOffset: superLuckStart, newASM: [
// .rlwinm(.r25, .r0, 0, 16, 31), // overwritten code
// .li(.r3, 17), // attacking pokemon
// .li(.r4, 0),
// .bl(getPokemonPointer),
// .bl(getAbility),
// .cmpwi(.r3, ability("super luck").index),
// .bne_f(0, 8),
// .addi(.r25, .r25, 1),
// .b(superLuckBranch + 4),
//])
//
//// wide lens aura stabiliser
//let lensBranch = 0x217968
//let lensStart = 0xB9B12C
////let getItemID = 0x203870
//let getItemParameter = 0x15eee0
////let getItem = 0x20384c // get item's hold item id
////let getPokemonPointer = 0x1efcac
////let checkShadowMove = 0x13d03c
//XGAssembly.replaceRamASM(RAMOffset: lensBranch, newASM: [.b(lensStart)])
//XGAssembly.replaceRamASM(RAMOffset: lensStart, newASM: [
//
// .li(.r3, 17), // attacking pokemon
// .li(.r4, 0),
// .bl(getPokemonPointer),
// .bl(getItem),
// .cmpwi(.r3, item("wide lens").data.holdItemID),
// .beq_l("accuracy boost"),
//
// .cmpwi(.r3, item("aura stabiliser").data.holdItemID),
// .bne_l("return"),
//
// .mr(.r3, .r20), // current move
// .bl(checkShadowMove),
// .cmpwi(.r3, 1),
// .bne_l("return"),
//
// .label("accuracy boost"),
// .li(.r3, 17), // attacking pokemon
// .li(.r4, 0),
// .bl(getPokemonPointer),
// .bl(getItemID),
// .bl(getItemParameter),
// .mullw(.r22, .r22, .r3),
// .li(.r3, 100),
// .divw(.r22, .r22, .r3),
//
// .label("return"),
// .rlwinm(.r0, .r25, 0, 16, 31), // overwritten
// .b(lensBranch + 4)
//])
//// aura stabiliser prevents reverse mode
//let reverseBranch = 0x226818
//let reverseStart = 0xB9B614
//let getItem = 0x20384c // get item's hold item id
//XGAssembly.replaceRamASM(RAMOffset: reverseBranch, newASM: [.b(reverseStart)])
//XGAssembly.replaceRamASM(RAMOffset: reverseStart, newASM: [
//
// .mr(.r3, .r30), // pokemon
// .bl(getItem),
// .cmpwi(.r3, item("aura stabiliser").data.holdItemID),
// .beq_l("skip"),
//
// .label("no skip"),
// .mr(.r3, .r30), // overwritten
// .b(reverseBranch + 4),
//
// .label("skip"),
// .li(.r3, 0),
// .b(0x226b20)
//])
//
//// function check if move was successful
//// check flinched, frozen, sleep, move failed, missed, protected, etc.
//let checkAttackedStart = 0xB9B300
//let checkMoveDidntFail = 0x1f04fc
////let getMoveRoutinePointer = 0x148da8
////let checkStatus = 0x2025f0
////let getPokemonPointer = 0x1efcac
//XGAssembly.replaceRamASM(RAMOffset: checkAttackedStart, newASM: [
// .stwu(.sp, .sp, -0x20),
// .mflr(.r0),
// .stw(.r0, .sp, 0x24),
// .stmw(.r30, .sp, 0x10),
//
// .li(.r3, 17), // attacking pokemon
// .li(.r4, 0),
// .bl(getPokemonPointer),
// .mr(.r30, .r3),
//
// .li(.r4, XGStatusEffects.freeze.rawValue),
// .bl(checkStatus),
// .cmpwi(.r3, 1),
// .bne_f(0, 0xc),
// .li(.r3, 0),
// .b_l("return"),
//
// .mr(.r3, .r30),
// .li(.r4, XGStatusEffects.sleep.rawValue),
// .bl(checkStatus),
// .cmpwi(.r3, 1),
// .bne_f(0, 0xc),
// .li(.r3, 0),
// .b_l("return"),
//
// .mr(.r3, .r30),
// .li(.r4, XGStatusEffects.flinched.rawValue),
// .bl(checkStatus),
// .cmpwi(.r3, 1),
// .bne_f(0, 0xc),
// .li(.r3, 0),
// .b_l("return"),
//
// .mr(.r3, .r30),
// .li(.r4, XGStatusEffects.must_recharge.rawValue),
// .bl(checkStatus),
// .cmpwi(.r3, 1),
// .bne_f(0, 0xc),
// .li(.r3, 0),
// .b_l("return"),
//
// .lbz(.r3, .r30, 0x83c), // check fully paralysed
// .cmpwi(.r3, 1),
// .bne_f(0, 0xc),
// .li(.r3, 0),
// .b_l("return"),
//
//
// .mr(.r3, .r30),
// .bl(getMoveRoutinePointer),
// .bl(checkMoveDidntFail),
//
// .label("return"),
// .lmw(.r30, .sp, 0x10),
// .lwz(.r0, .sp, 0x24),
// .mtlr(.r0),
// .addi(.sp, .sp, 0x20),
// .blr
//])
//// muscle band, wise glasses and knock off damage boost
//let calcDamageBoostsBranch = 0x22a760
//let calcDamageStart = 0xB9AFB0
//let getItemID = 0x203870
//let getMoveEffect = 0x13e6e8
////let getItemID = 0x203870
//XGAssembly.replaceRamASM(RAMOffset: calcDamageBoostsBranch, newASM: [
// .b(calcDamageStart)
//])
//XGAssembly.replaceRamASM(RAMOffset: calcDamageStart, newASM: [
// .label("muscle band check"),
// .cmpwi(.r28, item("muscle band").data.holdItemID),
// .bne_l("wise glasses check"),
// .cmpwi(.r24, XGMoveCategories.physical.rawValue),
// .bne_l("wise glasses check"),
// .lwz(.r3, .sp, 0x20), // item parameter
// .mullw(.r14, .r14, .r3),
// .li(.r3, 100),
// .divw(.r14, .r14, .r3),
//
// .label("wise glasses check"),
// .cmpwi(.r28, item("wise glasses").data.holdItemID),
// .bne_l("knock off check"),
// .cmpwi(.r24, XGMoveCategories.special.rawValue),
// .bne_l("knock off check"),
// .lwz(.r3, .sp, 0x20), // item parameter
// .mullw(.r14, .r14, .r3),
// .li(.r3, 100),
// .divw(.r14, .r14, .r3),
//
// .label("knock off check"),
// .mr(.r3, .r17),
// .bl(getMoveEffect), // get move effect
// .cmpwi(.r3, move("knock off").data.effect),
// .bne_l("return"),
//
// .mr(.r3, .r16), // defending pokemon
// .bl(getItemID),
// .cmpwi(.r3, 0),
// .beq_l("return"),
//
// .mulli(.r14, .r14, 150),
// .li(.r3, 100),
// .divw(.r14, .r14, .r3),
//
// .label("return"),
// .b(calcDamageBoostsBranch + 4)
//])
// poison touch ability
//
//// remove magma armour
//XGAbilities.ability(40).name.duplicateWithString("Poison Touch").replace()
//XGAbilities.ability(40).adescription.duplicateWithString("Contact may poison.").replace()
//
//let shadowFreezeRoutine = [0x00, 0x02, 0x04, 0x1e, 0x12, 0x00, 0x00, 0x00, 0x14, 0x80, 0x41, 0x5c, 0x93, 0x1d, 0x12, 0x00, 0x00, 0x00, 0x07, 0x80, 0x41, 0x5e, 0xb9, 0x23, 0x12, 0x0f, 0x80, 0x41, 0x5c, 0xc6, 0x1f, 0x12, 0x19, 0x80, 0x41, 0x5e, 0x81, 0x1f, 0x12, 0x2f, 0x80, 0x41, 0x5e, 0x81, 0x1f, 0x12, 0x31, 0x80, 0x41, 0x5e, 0x81, 0x1d, 0x12, 0x00, 0x00, 0x00, 0x01, 0x80, 0x41, 0x5c, 0x93, 0x01, 0x80, 0x41, 0x5c, 0x93, 0x00, 0x00, 0x20, 0x12, 0x00, 0x4b, 0x80, 0x41, 0x6d, 0xb2, 0x0a, 0x0b, 0x04, 0x2f, 0x80, 0x4e, 0x85, 0xc3, 0x04, 0x17, 0x0b, 0x04, 0x29, 0x80, 0x41, 0x41, 0x0f,]
//
//let routine : (effect: Int, routine: [Int], offset: Int) = (162, shadowFreezeRoutine, 0xb99ce9)
//XGAssembly.setMoveEffectRoutine(effect: routine.effect, fileOffset: routine.offset - kRELtoRAMOffsetDifference, moveToREL: true, newRoutine: routine.routine)
//let magmaArmourOffset = 0x21443c - kDolToRAMOffsetDifference
//XGAssembly.replaceASM(startOffset: magmaArmourOffset, newASM: [.nop,.nop,.nop])
//
//let poisonTouchBranch = 0x225580
//let poisonTouchStart = 0xB9B1D8
//let RNG16Bit = 0x25ca08
////let animSoundCallback = 0x2236a8
//let checkHasHP = 0x204a70
//let checkAttackSuccess = 0xB9B300
//XGAssembly.replaceASM(startOffset: poisonTouchBranch - kDolToRAMOffsetDifference, newASM: [.b(poisonTouchStart)])
//XGAssembly.replaceRamASM(RAMOffset: poisonTouchStart, newASM: [
//
// .cmpwi(.r26, 1), // check move succeeded
// .bne_l("return"),
//
// .bl(checkAttackSuccess),
// .cmpwi(.r3, 1), // check wasn't prevented by status
// .bne_l("return"),
//
// .mr(.r3, .r31), // defending pokemon
// .bl(checkHasHP),
// .cmpwi(.r3, 1),
// .bne_l("return"),
//
// .cmpwi(.r25, 1), // contact check
// .bne_l("return"),
//
// .cmpwi(.r16, ability("poison touch").index),
// .bne_l("return"),
//
// // get random number
// .bl(RNG16Bit),
//
// // calculate random number % 10 (remainder)
// // result is random number between 0 and 9
// .li(.r4, 10),
// .divw(.r0, .r3, .r4),
// .mullw(.r0, .r0, .r4),
// .sub(.r0, .r3, .r0),
//
// // activate if random number less than 3 (30% chance)
// .cmpwi(.r0, 2),
// .bgt_l("return"),
//
// // activate poison
// .lwz(.r0, .r13, -0x44e8),
// .ori(.r0, .r0, 0x2000),
// .stw(.r0, .r13, -0x44e8),
// .subi(.r5, .r13, 30816),
// .li(.r4, 2), // poison secondary effect
// .stb(.r4, .r5, 3),
// .lis(.r3, 0x8041),
// .addi(.r3, .r3, 31755),
// .bl(animSoundCallback),
// .li(.r17, 1),
//
// .label("return"),
// .mr(.r3, .r17),
// .b(poisonTouchBranch + 4)
//])
//
//// rocky helmet, spiky shield fix
//let rockyHelmetFixBranch = 0xb99414
//let rockyHelmetFixStart = 0xB9B2A8
////let checkAttackSuccess = 0xB9B300
//XGAssembly.replaceRamASM(RAMOffset: rockyHelmetFixBranch, newASM: [.b(rockyHelmetFixStart)])
//XGAssembly.replaceRamASM(RAMOffset: rockyHelmetFixStart, newASM: [
// .cmpwi(.r26, 1),
// .bne_l("fail"),
// .bl(checkAttackSuccess),
// .cmpwi(.r3, 1),
// .bne_l("fail"),
//
// .mr(.r3, .r30), // attacking pokemon
// .bl(checkHasHP),
// .cmpwi(.r3, 1),
// .bne_l("fail"),
//
// .label("success"),
// .b(rockyHelmetFixBranch + 0xc),
// .label("fail"),
// .b(rockyHelmetFixBranch + 8),
//
//])
//
// checks if attacking pokemon has hp
//let hpCheckStart = 0xB9B27C
////let getPokemonPointer = 0x1efcac
//XGAssembly.replaceRamASM(RAMOffset: hpCheckStart, newASM: [
// .stwu(.sp, .sp, -0x10),
// .mflr(.r0),
// .stw(.r0, .sp, 0x14),
//
// .li(.r3, 17),
// .li(.r4, 0),
// .bl(getPokemonPointer),
// .bl(checkHasHP),
//
// .lwz(.r0, .sp, 0x14),
// .mtlr(.r0),
// .addi(.sp, .sp, 0x10),
// .blr
//
//])
//// life orb fix
//let fixBranch = 0xb9a208
//let lifeOrbFixStart = 0xB9B2D4
//XGAssembly.replaceRamASM(RAMOffset: fixBranch, newASM: [
// .b(lifeOrbFixStart)
//])
//XGAssembly.replaceRamASM(RAMOffset: lifeOrbFixStart, newASM: [
// .cmpwi(.r26, 1),
// .bne_l("fail"),
// .bl(checkAttackSuccess),
// .cmpwi(.r3, 1),
// .bne_l("fail"),
//
// .mr(.r3, .r30), // attacking pokemon
// .bl(checkHasHP),
// .cmpwi(.r3, 1),
// .bne_l("fail"),
//
// .label("success"),
// .b(0xb9a20c),
// .label("fail"),
// .b(0xb9a28c),
//])
//
//// remove sleep talk and snore
//XGAssembly.replaceRamASM(RAMOffset: 0x226cdc, newASM: [
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
//])
//
//// set confusion chance to hurt user to 1 in 3
//let confusionStart = 0x2270f0
//XGAssembly.replaceASM(startOffset: confusionStart - kDolToRAMOffsetDifference, newASM: [
// .cmplwi(.r3, 0xaaaa), // 1 in 3
// .blt(0x227110), // not confused
//])
//
//// spread moves on water absorb, volt absorb, flash fire
//XGAssembly.replaceRamASM(RAMOffset: 0x2255a4, newASM: [.stmw(.r23, .sp, 0x8)])
//XGAssembly.replaceRamASM(RAMOffset: 0x2257bc, newASM: [.lmw(.r23, .sp, 0x8)])
//XGAssembly.replaceRamASM(RAMOffset: 0x2255f0, newASM: [
// .mr(.r29, .r3),
// .li(.r23, 0),
// .mr(.r3, .r28),
//])
//for offset in [0x22566c, 0x22567c, 0x2256ac, 0x2256bc, 0x22573c, 0x22574c, 0x225784, 0x225794] {
// XGAssembly.replaceRamASM(RAMOffset: offset, newASM: [.mr(.r23, .r3)])
//}
//let absorbRoutineBranch = 0x2257b8
//let absorbStart = 0xB9B444
//let getTargets = 0x13e784
//let setMoveRoutinePosition = 0x2236d4
////let animSoundCallback = 0x2236a8
//XGAssembly.replaceRamASM(RAMOffset: absorbRoutineBranch, newASM: [.b(absorbStart)])
//XGAssembly.replaceRamASM(RAMOffset: absorbStart, newASM: [
//
// .cmpwi(.r23, 0),
// .beq_l("return false"),
// .mr(.r3, .r23),
// .bl(animSoundCallback),
//
// .mr(.r3, .r24),
// .bl(getTargets),
// .cmpwi(.r3, XGMoveTargets.bothFoesAndAlly.rawValue),
// .bne_l("end routine"),
//
// .lis(.r3, 0x8041),
// .addi(.r3, .r3, 0x59a9),
// .bl(setMoveRoutinePosition),
// .b_l("return true"),
//
// .label("end routine"),
// .lis(.r3, 0x8041),
// .addi(.r3, .r3, 0x4119),
// .bl(setMoveRoutinePosition),
//
// .label("return true"),
// .li(.r3, 1),
// .b(absorbRoutineBranch + 4),
//
// .label("return false"),
// .li(.r3, 0),
// .b(absorbRoutineBranch + 4)
//])
//// new gale wings, prankster
//let priorityAbilitiesBranches = [0x1f43ec, 0x1f43f8]
//let priorityAbilitiesStart = 0xB9B490
//let getCurrentMove = 0x2045b4
//let getPriority = 0x13e7b8
//let getAbility = 0x2055c8
//let getType = 0x13e870
//let getCategory = 0x13e7f0
//for branch in priorityAbilitiesBranches {
// XGAssembly.replaceRamASM(RAMOffset: branch, newASM: [.bl(priorityAbilitiesStart)])
//}
//XGAssembly.replaceRamASM(RAMOffset: priorityAbilitiesStart, newASM: [
// .stwu(.sp, .sp, -0x10),
// .mflr(.r0),
// .stw(.r0, .sp, 0x14),
// .stmw(.r30, .sp, 0x8),
//
// .mr(.r31, .r3),
// .bl(getCurrentMove),
// .mr(.r30, .r3),
// .bl(getPriority),
// .cmpwi(.r3, 0),
// .bne_l("no boost"),
//
// .mr(.r3, .r31),
// .bl(getAbility),
// .cmpwi(.r3, ability("prankster").index),
// .beq_l("prankster check"),
// .cmpwi(.r3, ability("gale wings").index),
// .bne_l("no boost"),
//
// .label("gale wings check"),
// .mr(.r3, .r30),
// .bl(getType),
// .cmpwi(.r3, XGMoveTypes.flying.rawValue),
// .beq_l("boost priority"),
// .b_l("no boost"),
//
// .label("prankster check"),
// .mr(.r3, .r30),
// .bl(getCategory),
// .cmpwi(.r3, XGMoveCategories.none.rawValue),
// .beq_l("boost priority"),
// .b_l("no boost"),
//
// .label("boost priority"),
// .li(.r3, 1),
// .b_l("return"),
//
// .label("no boost"),
// .mr(.r3, .r30),
// .bl(getPriority),
//
// .label("return"),
// .lmw(.r30, .sp, 0x8),
// .lwz(.r0, .sp, 0x14),
// .mtlr(.r0),
// .addi(.sp, .sp, 0x10),
// .blr
//])
//
//
//// fix type damage reducing berries ending multi hit moves
//let dol = XGFiles.dol.data!
//dol.replaceWordAtOffset(0x414659 - kDolTableToRAMOffsetDifference, withBytes: 0x80414659)
//dol.save()
//
// fix berry glitch on moves like earthquake
//XGAssembly.replaceRamASM(RAMOffset: 0x210214, newASM: [.nop])
//
//
//// new skill link
//let skillBranches = [0x221d70, 0x221d98]
//let skillStart = 0xB9B5C8
//for branch in skillBranches {
// XGAssembly.replaceRamASM(RAMOffset: branch, newASM: [.bl(skillStart)])
//}
//XGAssembly.replaceRamASM(RAMOffset: skillStart, newASM: [
// .rlwinm(.r4, .r0, 0, 24, 31),
// .subi(.r3, .r31, 1608),
// .lhz(.r3, .r3, 0x80c),
// .cmpwi(.r3, ability("skill link").index),
// .bne_l("return"),
// .li(.r4, 5),
//
// .label("return"),
// .blr
//])
//
//// new magic coat mirror match check
//// prevents infinite loops of magic bounce
//// if user has magic bounce then ignore target magic bounce
//let magicBranch = 0x218568
//let magicCheckStart = 0xB9B5E4
//let magicTrueOffset = 0x21856c
//let magicFalseOffset = 0x2185dc
//let getAbilityb = 0x148898
//XGAssembly.replaceRamASM(RAMOffset: magicBranch, newASM: [.b(magicCheckStart)])
//XGAssembly.replaceRamASM(RAMOffset: magicCheckStart, newASM: [
//
// .bne_l("magic false"),
// .mr(.r3, .r29),
// .bl(getAbilityb),
// .cmpwi(.r3, ability("magic bounce").index),
// .beq_l("magic false"),
//
// .label("magic true"),
// .b(magicTrueOffset),
//
// .label("magic false"),
// .b(magicFalseOffset)
//])
//
//// new sash/sturdy shedinja check
//// prevents focus sash from activating on shedinja since sash is infinite
//// works by skipping focus sash checks if pokemon has 1hp
////
//let shedinjaBranch = 0x216010
//let shedinjaTrueBranch = 0x216048
//let shedinjaFalseBranch = 0x216014
//let shedinjaCheckStart = 0xB9B600
//XGAssembly.replaceRamASM(RAMOffset: shedinjaBranch, newASM: [.b(shedinjaCheckStart)])
//XGAssembly.replaceRamASM(RAMOffset: shedinjaCheckStart, newASM: [
// .cmpwi(.r31, 1), // current hp
// .beq_l("skip sash"),
//
// .cmpwi(.r23, item("focus sash").data.holdItemID),
// .label("check sash"),
// .b(shedinjaBranch + 4),
//
// .label("skip sash"),
// .b(0x216048)
//])
//
//// move routine jump if status >0xff will jump if move failed (protect, type immunity, flinched, etc.), and if move target is set, will jump if target doesn't have hp
//let jumpBranch = 0x21354c
//let jumpStart = 0xB9B6A4
//let checkAttackSuccess = 0xB9B300
//let checkHasHP = 0x204a70
//XGAssembly.replaceRamASM(RAMOffset: jumpBranch, newASM: [.b(jumpStart)])
//XGAssembly.replaceRamASM(RAMOffset: jumpStart, newASM: [
// .cmpwi(.r4, 1),
// .bne_l("check custom"),
// .b(jumpBranch + 8),
//
// .label("check custom"),
// .cmplwi(.r4, 0x80),
// .bge_l("custom status"),
// .b(0x213578),
//
// .label("custom status"),
// .cmplwi(.r4, 0xff),
// .bne_l("reserved for future expansion"),
//
// .bl(checkAttackSuccess),
// .cmpwi(.r3, 1),
// .beq_l("check hp"),
// .b_l("jump"),
//
// .label("check hp"),
// .mr(.r3, .r31),
// .bl(checkHasHP),
// .cmpwi(.r3, 1),
// .bne_l("jump"),
// .b_l("no jump"),
//
// .label("reserved for future expansion"),
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
// .nop,
//
// .label("no jump"),
// .b(0x2135d8),
// .label("jump"),
// .b(0x213560),
// .nop,
// .nop
//])
//
//
//let poisonTouchBranch = 0x225580
//let poisonTouchStart = 0xB9B1D8
//let RNG16Bit = 0x25ca08
//let animSoundCallback = 0x2236a8
////let checkHasHP = 0x204a70
////let checkAttackSuccess = 0xB9B300
//XGAssembly.replaceASM(startOffset: poisonTouchBranch - kDolToRAMOffsetDifference, newASM: [.b(poisonTouchStart)])
//XGAssembly.replaceRamASM(RAMOffset: poisonTouchStart, newASM: [
//
// .cmpwi(.r26, 1), // check move succeeded
// .bne_l("return"),
//
// .bl(checkAttackSuccess),
// .cmpwi(.r3, 1), // check wasn't prevented by status
// .bne_l("return"),
//
// .mr(.r3, .r31), // defending pokemon
// .bl(checkHasHP),
// .cmpwi(.r3, 1),
// .bne_l("return"),
//
// .cmpwi(.r25, 1), // contact check
// .bne_l("return"),
//
// .cmpwi(.r16, ability("poison touch").index),
// .bne_l("return"),
//
// // get random number
// .bl(RNG16Bit),
//
// // calculate random number % 10 (remainder)
// // result is random number between 0 and 9
// .li(.r4, 10),
// .divw(.r0, .r3, .r4),
// .mullw(.r0, .r0, .r4),
// .sub(.r0, .r3, .r0),
//
// // activate if random number less than 3 (30% chance)
// .cmpwi(.r0, 2),
// .bgt_l("return"),
//
// // activate poison
// .lwz(.r0, .r13, -0x44e8),
// .ori(.r0, .r0, 0x2000),
// .stw(.r0, .r13, -0x44e8),
// .subi(.r5, .r13, 30816),
// .li(.r4, 2), // poison secondary effect
// .stb(.r4, .r5, 3),
// .lis(.r3, 0x8041),
// .addi(.r3, .r3, 31755),
// .bl(animSoundCallback),
// .li(.r17, 1),
//
// .label("return"),
// .mr(.r3, .r17),
// .b(poisonTouchBranch + 4)
//])
//
//// rocky helmet, spiky shield fix
//let rockyHelmetFixBranch = 0xb99414
//let rockyHelmetFixStart = 0xB9B2A8
////let checkAttackSuccess = 0xB9B300
//XGAssembly.replaceRamASM(RAMOffset: rockyHelmetFixBranch, newASM: [.b(rockyHelmetFixStart)])
//XGAssembly.replaceRamASM(RAMOffset: rockyHelmetFixStart, newASM: [
// .cmpwi(.r26, 1),
// .bne_l("fail"),
// .bl(checkAttackSuccess),
// .cmpwi(.r3, 1),
// .bne_l("fail"),
//
// .mr(.r3, .r30), // attacking pokemon
// .bl(checkHasHP),
// .cmpwi(.r3, 1),
// .bne_l("fail"),
//
// .label("success"),
// .b(rockyHelmetFixBranch + 0xc),
// .label("fail"),
// .b(rockyHelmetFixBranch + 8),
//
//])
//
//let hpCheckStart = 0xB9B27C
//let getPokemonPointer = 0x1efcac
//XGAssembly.replaceRamASM(RAMOffset: hpCheckStart, newASM: [
// .stwu(.sp, .sp, -0x10),
// .mflr(.r0),
// .stw(.r0, .sp, 0x14),
//
// .li(.r3, 17),
// .li(.r4, 0),
// .bl(getPokemonPointer),
// .bl(checkHasHP),
//
// .lwz(.r0, .sp, 0x14),
// .mtlr(.r0),
// .addi(.sp, .sp, 0x10),
// .blr
//
//])
//// life orb fix
//let fixBranch = 0xb9a208
//let lifeOrbFixStart = 0xB9B2D4
//XGAssembly.replaceRamASM(RAMOffset: fixBranch, newASM: [
// .b(lifeOrbFixStart)
//])
//XGAssembly.replaceRamASM(RAMOffset: lifeOrbFixStart, newASM: [
// .cmpwi(.r26, 1),
// .bne_l("fail"),
// .bl(checkAttackSuccess),
// .cmpwi(.r3, 1),
// .bne_l("fail"),
//
// .mr(.r3, .r30), // attacking pokemon
// .bl(checkHasHP),
// .cmpwi(.r3, 1),
// .bne_l("fail"),
//
// .label("success"),
// .b(0xb9a20c),
// .label("fail"),
// .b(0xb9a28c),
//])
//// remove sticky hold on knock off
//XGAssembly.replaceRamASM(RAMOffset: 0x214f1c, newASM: [.b(0x214f48)])
//
//// shadow pokemon receive full exp instead of 80%
//XGAssembly.replaceRamASM(RAMOffset: 0x212eac, newASM: [
// .mr(.r0, .r18),
// .nop,
// .nop
//])
//// scale experience based on level
//// defeating a higher level pokemon than the player's pokemon yields more exp
//// defeating a lower level pokemon yields less exp
//// makes it easier to stay on the level curve of the game
//let expBranch = 0x212df0
//let expStart = 0xB9B788
//let getLevel = 0x2037d0 // from main pointer (fainted pokemon)
//let getStatsLevel = 0x2037f4 // from stats pointer (recipient)
//// r30 fainted pokemon
//// r19 receiving pokemon
//// r15 usable
//// r18 experience
//XGAssembly.replaceRamASM(RAMOffset: expBranch, newASM: [.b(expStart), .mr(.r3, .r19),])
//XGAssembly.replaceRamASM(RAMOffset: expStart, newASM: [
//
// .lwz(.r18, .sp, 0xc),
//
// // get exp recipient level
// .mr(.r3, .r19),
// .bl(getStatsLevel),
// .mr(.r15, .r3),
//
// // get fainted pokemon level
// .mr(.r3, .r30),
// .bl(getLevel),
//
// // create multiplier
// // (2 x fainted level) ^ 3 (normally power 2.5 but too much stress in ASM plus 3x makes the multiplier more powerful)
// // ------------------------
// // (recipient level + fainted level) ^ 3 (same here)
//
// .add(.r15, .r15, .r3), // recipient level + fainted level
// .mulli(.r3, .r3, 2), // fainted level x 2
// // watch out for integer overflow
// // do each individual multiplication and division in pairs 3 times
//
// .mullw(.r18, .r18, .r3), // exp x fainted
// .divw(.r18, .r18, .r15), // exp / rec+faint
//
// .mullw(.r18, .r18, .r3), // exp x fainted
// .divw(.r18, .r18, .r15), // exp / rec+faint
//
// .mullw(.r18, .r18, .r3), // exp x fainted
// .divw(.r18, .r18, .r15), // exp / rec+faint
//
// // if exp drops to 0 due to integer division then set it to 1
// .cmpwi(.r18, 0),
// .bne_f(0, 8),
// .li(.r18, 1),
//
// // return
// .b(expBranch + 4)
//])
// Don't forget to update the custom script classes JSON to include the new class and functions before compiling scripts
//// Create custom class in scripting engine
//XGDolPatcher.zeroForeignStringTables()
//let freeSpacePointer = XGAssembly.ASMfreeSpacePointer()
//printg(freeSpacePointer.hexString())
//XGScriptClass.createCustomClass(withIndex: 34, atRAMOffset: freeSpacePointer, numberOfFunctions: 256)
//// Add ASM for functions for custom class
//// Make sure to add these after code above is run before adding the class functions
//// The first chunk of code will print out the offsets. Write them down somewhere for future use.
//let jumpTableRAMOffset = 0x80B99390
//let customClassReturnOffset: UInt32 = 0x80B99378
//
//// Add custom class functions for reading from z, r and l triggers
//for i in 0 ... 2 {
// let freeSpacePointer2 = XGAssembly.ASMfreeSpacePointer()
// let p1PadButtonPressMaskOffset: UInt32 = 0x80444b20
// let buttonMask: UInt32 = UInt32(1 << (i + 4))
//
// XGScriptClass.addASMFunctionToCustomClass(jumpTableRAMOffset: jumpTableRAMOffset, functionIndex: i, codeOffsetInRAM: freeSpacePointer2, code: [
// XGASM.loadImmediateShifted32bit(register: .r3, value: p1PadButtonPressMaskOffset).0,
// XGASM.loadImmediateShifted32bit(register: .r3, value: p1PadButtonPressMaskOffset).1,
// .lha(.r3, .r3, 0),
// .andi_(.r3, .r3, buttonMask),
// .srawi(.r3, .r3, UInt32(i) + 4),
// .stw(.r3, .r4, 4),
// .li(.r3, 1),
// .sth(.r3, .r4, 0),
// XGASM.loadImmediateShifted32bit(register: .r4, value: customClassReturnOffset).0,
// XGASM.loadImmediateShifted32bit(register: .r4, value: customClassReturnOffset).1,
// .mr(.r0, .r4),
// .mtctr(.r0),
// .bctr
// ])
//}
////Auto add pov code to all scripts in XDS folder
//for file in XGFolders.XDS.files where file.fileType == .xds {
// var text = file.text
// text = text.replacingOccurrences(of: "// Macro defintions\n", with: "// Macro defintions\ndefine #enablePOVFlag 983\n")
// text = text.replacingOccurrences(of: "\nfunction @preprocess() {\n", with: "global enablePOV = NO\n\nfunction @preprocess() {\n\tenablePOV = getFlag(#enablePOVFlag)\n")
// text = text.replacingOccurrences(of: "function @hero_main() {\n", with: """
// function @hero_main() {
//
// \tcameraXRotation = 0.0
// \tcurrentCameraBounce = 0.0
// \tcameraBounceRadius = 0.5
// \tcameraBounceFramesPerCycle = 0
// \tcameraBounceMINFramesPerCycle = 15.0
// \tcameraHeight = 12.0
// \tfieldOfView = 60
// \tcameraXRotationPerFrameDegrees = 5.0
// \tcameraRadius = 5 // how far away the camera should be so it isn't inside michael
//
//
// """)
//
// let cameraControlText = """
// \n\nif (Controller.isZButtonPressed() = YES) {
// enablePOV = enablePOV ^ YES
// if (enablePOV = NO) {
// Camera.reset()
// setFlagToFalse(#enablePOVFlag)
// }
//
// if (enablePOV = YES) {
// setFlagToTrue(#enablePOVFlag)
// }
// }
//
// if (enablePOV = YES) {
// position = #player.getPosition()
// angle = #player.getRotation()
// pi = 3.141592
// angleRadians = -((((180 - angle) * 2) * pi) / 360.0)
//
// cameraXRotationPerFrameRadians = ((cameraXRotationPerFrameDegrees * 2) * pi) / 360.0
//
// playerSpeed = #player.getMovementSpeed()
// isWalking = playerSpeed > 0.0
//
// if (isWalking = YES) {
// cameraBounceFramesPerCycle = cameraBounceMINFramesPerCycle / playerSpeed
// if (cameraBounceFramesPerCycle > 0) {
// currentCameraBounce = currentCameraBounce + (360.0 / cameraBounceFramesPerCycle)
// }
// }
//
// if (isWalking = NO) {
// currentCameraBounce = 0
// }
// if (currentCameraBounce > 360) {
// currentCameraBounce = currentCameraBounce - 360
// }
//
// cameraBounceSinDisplacement = sin(currentCameraBounce)
// currentCameraBounceAdjusted = cameraBounceRadius * cameraBounceSinDisplacement
//
// if ((Controller.isRButtonPressed()) and (cameraXRotation <= (pi / 2))) {
// cameraXRotation = cameraXRotation + cameraXRotationPerFrameRadians
// }
// if ((Controller.isLButtonPressed()) and (cameraXRotation >= -((pi / 2)))) {
// cameraXRotation = cameraXRotation - cameraXRotationPerFrameRadians
// }
// //if (Controller.isZButtonPressed()) { // maybe use a d-pad button here for resetting the camera
// // cameraXRotation = 0
// //}
//
// // Use trig to figure out how far away the camera should be from michael in the x and z axes
// if (angle < 90) {
// vx = cameraRadius * sin(angle)
// vz = cameraRadius * cos(angle)
// goto @angleEnd
// }
// if (angle < 180) {
// vx = cameraRadius * sin((180 - angle))
// vz = 0 - (cameraRadius * cos((180 - angle)))
// goto @angleEnd
// }
// if (angle < 270) {
// vx = 0 - (cameraRadius * sin((angle - 180)))
// vz = 0 - (cameraRadius * cos((angle - 180)))
// goto @angleEnd
// }
// vx = -(cameraRadius * sin((360 - angle)))
// vz = cameraRadius * cos((360 - angle))
// @angleEnd
//
// Camera.function48() // don't know what this does yet
// Camera.setPosition2((getvx(position) + vx) ((getvy(position) + cameraHeight) + currentCameraBounceAdjusted) (getvz(position) + vz))
// Camera.setRotationAboutAxesRadians(cameraXRotation angleRadians 0)
// Camera.setFieldOfView(fieldOfView)
// }
//
// Player.processEvents()
// yield(1)
// """.replacingOccurrences(of: "\n", with: "\n ")
//
// text = text.replacingOccurrences(of:
// "\n Player.processEvents()\n yield(1)", with: cameraControlText)
//
// text = text.replacingOccurrences(of:
// "\n var_1.Player.processEvents()\n yield(1)", with: cameraControlText.replacingOccurrences(of: "Player.processEvents()", with: "var_1.Player.processEvents()"))
//
// text = text.replacingOccurrences(of:
// "\n var_2.Player.processEvents()\n yield(1)", with: cameraControlText.replacingOccurrences(of: "Player.processEvents()", with: "var_1.Player.processEvents()"))
//
// XGUtility.saveString(text, toFile: file)
//}
// free cam with c stick
//XGPatcher.disableCStickMovement()
//
//// Don't forget to update the custom script classes JSON to include the new class and functions before compiling scripts
//// Create custom class in scripting engine
//if let freeSpacePointer = XGAssembly.ASMfreeSpaceRAMPointer(),
// let (_, jumpTableRAMOffset, customClassReturnOffset) = XGScriptClass.createCustomClass(withIndex: 34, atRAMOffset: freeSpacePointer, numberOfFunctions: 2) {
//
// // Add custom class function for reading c stick inputs
// let cstickXFunctionRAMOffset = 0x8010409c
// let cstickYFunctionRAMOffset = 0x80104040
// let functions = [cstickXFunctionRAMOffset, cstickYFunctionRAMOffset]
// for i in 0 ... 1 {
// let functionOffset = functions[i]
// guard let freeSpacePointer2 = XGAssembly.ASMfreeSpaceRAMPointer() else {
// continue
// }
//
// XGScriptClass.addASMFunctionToCustomClass(jumpTableRAMOffset: jumpTableRAMOffset, functionIndex: i, codeOffsetInRAM: freeSpacePointer2, code: [
// .stwu(.sp, .sp, -8),
// .stw(.r31, .sp, 4),
// .mr(.r31, .r4),
// .li(.r3, 1), // controller index
// .li(.r4, 0), // not sure what this does
// .bl(functionOffset),
// .extsb(.r3, .r3),
// .stw(.r3, .r31, 4),
// .li(.r3, 1),
// .sth(.r3, .r31, 0),
// .lwz(.r31, .sp, 4),
// .addi(.sp, .sp, 8),
// XGASM.loadImmediateShifted32bit(register: .r4, value: customClassReturnOffset).0,
// XGASM.loadImmediateShifted32bit(register: .r4, value: customClassReturnOffset).1,
// .mr(.r0, .r4),
// .mtctr(.r0),
// .bctr
// ])
// }
//}
//XGUtility.importFileToISO(.dol, save: false)
//XGUtility.importFileToISO(.fsys("M2_out"), encode: true, save: true, importFiles: nil)
// String ids for stat names used in pokemon summary screen
// in order to show which stats are affected by a pokemon's nature
// in the pokemon summary screen loop, every time the current pokemon is queried
// check its nature and based on that update the strings
// starting with msg id 0x3ada at offset 0x31c860 in start.dol
// Each subsequent stat msg id is stored 0x1c bytes after the previous one
// The string itself starts with a predefined colour special flag
// Make copies of each string with the colour set to red and blue using the custom colour special character
// e.g. [8]{FF0000FF} for hard red
// Then each loop overwrite those addresses so the msg id that gets used will match the current pokemon's nature
// Bonus, reset them when summary screen is closed
//// Use output from dolmatch program by mparisi to copy the symbols from one symbol map to a new symbol map for another dol
//
//// RAM Dumps which include the dol file
//let gxxj = XGFiles.nameAndFolder("GXXP01.raw", .Documents).data!
//let nxxj = XGFiles.nameAndFolder("NXXJ01.raw", .Documents).data!
//
//var matchMap = XGFiles.nameAndFolder("matches.txt", .Documents).text.split(separator: "\n")
//let nxMap = XGFiles.nameAndFolder("NXXJ01.map", .Documents).text.split(separator: "\n")
//let outFile = XGFiles.nameAndFolder("GXXP01.map", .Documents)
//var outText = ""
//var isInDataSection = false
//var lastDataMatchOffset = 0x0
//for line in nxMap {
// if line.starts(with: ".rodata") {
// isInDataSection = true
// }
//
// if !line.starts(with: " ") {
// outText += "\n\n"
// }
//
// guard !line.starts(with: " UNUSED") else {
// continue
// }
// guard line.starts(with: " 0") else {
// outText += line + "\n"
// continue
// }
//
// var newLine = String(line).replacingOccurrences(of: "\t", with: " ")
// let parts = line.replacingOccurrences(of: " ", with: " 0 ").replacingOccurrences(of: " ", with: " ").split(separator: " ").map { String($0) }
// let symbolLength = ("0x" + parts[1]).integerValue ?? 0
// let virtualAddress = parts[2]
// let fileOffset = parts[3]
// let alignment = parts[4]
//
// guard alignment != "1",
// alignment != "0" else {
// continue
// }
//
// let symbolName = parts[5]
//
// for part in parts where part.contains("\\") {
// if let finalPathComponent = part.split(separator: "\\").last {
// newLine = newLine.replacingOccurrences(of: part, with: String(finalPathComponent))
// }
// }
//
// if !isInDataSection {
// if let matchLineIndex = matchMap.firstIndex(where: { matchLine in
// let line = String(matchLine)
// return line.contains(symbolName)
// }) {
// let matchLine = String(matchMap[matchLineIndex])
// let matchParts = matchLine.split(separator: " ")
// let matchReleaseAddress = String(matchParts[2])
// newLine = newLine.replacingOccurrences(of: virtualAddress, with: matchReleaseAddress)
// newLine = newLine.replacingOccurrences(of: fileOffset, with: "00000000")
// outText += newLine + "\n"
//
// matchMap.remove(at: matchLineIndex)
// }
// } else {
// guard !symbolName.starts(with: "*"),
// !symbolName.starts(with: "."),
// symbolLength > 0 else {
// continue
// }
//
// // Subtract 0x80000000 from the virtual address by removing leading digit
// let nxRamOffset = ("0x" + virtualAddress.substring(from: 1, to: virtualAddress.length)).integerValue ?? 0
// guard nxRamOffset > 0 else {
// continue
// }
// let subData = nxxj.getSubDataFromOffset(nxRamOffset, length: symbolLength)
// if !subData.isNull,
// let matchOffset = gxxj.search(for: subData, fromOffset: lastDataMatchOffset) {
// lastDataMatchOffset = matchOffset + symbolLength
// var matchOffsetString = matchOffset.hex()
// while matchOffsetString.length < 7 {
// matchOffsetString = "0" + matchOffsetString
// }
// matchOffsetString = "8" + matchOffsetString
// newLine = newLine.replacingOccurrences(of: virtualAddress, with: matchOffsetString)
// newLine = newLine.replacingOccurrences(of: fileOffset, with: "00000000")
// outText += newLine + "\n"
// }
// }
//}
//outText.save(toFile: outFile)
// For the official symbols which had previously been named, append the modders determined name to the symbol name
// so we can still search for them using the pevious terms we used; especially since a lot of official names are broken english/japanese
// Any which aren't matched in the official map don't need to be added in as we can load the official map in dolphin after loading
// the previous map and then save the new combined map
//let officialMap = XGFiles.nameAndFolder("GXXE01.map", .Documents).text.split(separator: "\n")
//var moddersMap = XGFiles.nameAndFolder("modders.map", .Documents).text.split(separator: "\n").filter { str in
// return !str.contains("zz_0") && !str.contains("?")
//}
//let outFile = XGFiles.nameAndFolder("GXXE01 combined.map", .Documents)
//var outText = ""
//
//for line in officialMap {
// var outLine = String(line)
//
// guard outLine.starts(with: " 0") else {
// outText += outLine + "\n"
// continue
// }
//
// let officialParts = outLine.split(separator: " ").map { String($0) }
// let virtualAddress = officialParts[2]
//
// if let matchLineIndex = moddersMap.firstIndex(where: { matchLine in
// let line = String(matchLine)
// return line.contains(virtualAddress)
// }) {
// let matchLine = String(moddersMap[matchLineIndex])
// let matchParts = matchLine.split(separator: " ")
// let matchModdersName = String(matchParts[4])
// outLine = outLine + " (\(matchModdersName.replacingOccurrences(of: "zz_", with: "")))"
//
// moddersMap.remove(at: matchLineIndex)
// }
//
// outText += outLine + "\n"
//}
//outText.save(toFile: outFile)
// Map battle sequence command addresses to function names from symbol map
//let NXXJRam = XGFiles.nameAndFolder("NXXJ RAM.raw", .Documents).data!
//let NXXJMap = XGFiles.nameAndFolder("NXXJ.map", .Documents).text
//let mapLines = NXXJMap.split(separator: "\n").filter({ str in
// return String(str).contains(" 4 ") && String(str).contains("fightSeq")
//}).map { str -> (name: String, address: Int) in
// let string = String(str).replacingOccurrences(of: " 0", with: "0").replacingOccurrences(of: " ", with: " ")
// let parts = string.split(separator: " ")
// let virtualAddress = String(parts[2]).hexValue ?? 0
// let name = String(parts[5])
// return (name: name, address: virtualAddress)
//
//}
//
//let battleSequenceSwitchTableRamOffset = 0x02f582c
//
//for i in 0 ..< 253 {
// let nextCommandOffset = NXXJRam.read4Bytes(atAddress: battleSequenceSwitchTableRamOffset + (i * 4))!
// if let commandInfo = mapLines.first(where: { info in
// info.address == nextCommandOffset
// }) {
// printg((i + 1).hexString().spaceLeftToLength(5), commandInfo.name)
// }
//}
//// xds script for pokespots to only load models that are available
//// prevents randomised versions from crashing
//
//var models = [Int]()
//for i in 0 ... 2 {
//
// let spot = XGPokeSpots(rawValue: i)!
// for index in 0 ..< spot.numberOfEntries {
// let mon = XGPokeSpotPokemon(index: index, pokespot: spot)
// let species = mon.pokemon.index
// if species != 414 && species != 415 && species != 0 {
// models.append(species)
// }
// }
//}
//
//var string = "global pokemonModels = ["
//for species in models.sorted() {
// string += " \(species)"
//}
//string += " ]"
//printg(models.count)
//printg(string)
//// import nintendon't gci save to dolphin gci to import into mem card
//let to = XGFiles.nameAndFolder("GXXE.raw", .Resources).data
//let from = XGFiles.nameAndFolder("GXXE.gci", .Resources).data
//let toStart = 0xB2000
//let fromStart = 0x40
//let save = from.getByteStreamFromOffset(fromStart, length: 0x56000)
//to.replaceBytesFromOffset(toStart, withByteStream: save)
//to.save()
//// import dolphin gci save to nintendon't gci file
//let from = XGFiles.nameAndFolder("GXXE.raw", .Resources).data
//let to = XGFiles.nameAndFolder("GXXE.gci", .Resources).data
//let fromStart = 0xB2000
//let toStart = 0x40
//let save = from.getByteStreamFromOffset(fromStart, length: 0x56000)
//to.replaceBytesFromOffset(toStart, withByteStream: save)
//to.save()
//for m in XGMoves.allMoves().filter({ (m) -> Bool in
// return (m.index < kNumberOfMoves - 1)
//}).sorted(by: { (m1, m2) -> Bool in
// return XGAssembly.getRoutineStartForMoveEffect(index: m1.data.effect) < XGAssembly.getRoutineStartForMoveEffect(index: m2.data.effect)
//}) {
// let start = XGAssembly.getRoutineStartForMoveEffect(index: m.data.effect)
//
// let routine = XGAssembly.routineDataForMove(move: m)
//
// print(m.name.string + " " + start.hexString() + " - " + (start + routine.count).hexString() + ":")
//
// for i in 0 ..< routine.count {
// print(String(format: "0x%02x,", routine[i]), terminator: " ")
// }
// print("\n")
//}
//let fileName = "B1_1.fsys"
////let fileName = "D3_ship_B2_2.fsys"
//let new = iso.dataForFile(filename: fileName)!
//let fsys = iso.fsysForFile(filename: fileName)!
//new.file = .fsys("S1_out.fsys")
//new.save()
//
//iso.importFiles([new.file])
//
//for i in 0 ..< fsys.numberOfEntries {
// let data = fsys.decompressedDataForFileWithIndex(index: i)!
// data.file = .nameAndFolder(fsys.fileNames[i], .Documents)
// data.save()
//}
//
//let fileName = "B1_1.fsys"
////let fileName = "D3_ship_B2_2.fsys"
//let new = iso.dataForFile(filename: fileName)!
//let fsys = iso.fsysForFile(filename: fileName)!
//new.file = .fsys("S1_out.fsys")
//new.save()
//
//iso.importFiles([new.file])
//
//for i in 0 ..< fsys.numberOfEntries {
// let data = fsys.decompressedDataForFileWithIndex(index: i)!
// data.file = .nameAndFolder(fsys.fileNames[i], .Documents)
// data.save()
//}
//compileForRelease()
// copy nintendon't save to dolphin gci to import into mem card
//let from = XGFiles.nameAndFolder("GXXE.raw", .Reference).data
//let to = XGFiles.nameAndFolder("GXXE_PokemonXD.gci", .Reference).data
//let fromStart = 0xB2000
//let toStart = 0x40
//let save = from.getByteStreamFromOffset(fromStart, length: 0x56000)
//to.replaceBytesFromOffset(toStart, withByteStream: save)
//to.save()
//printRoutineForMove(move: move("nature power"))
//getFunctionPointerWithIndex(index: 96).hex().println()
//for file in XGFolders.Rels.files where file.fileType == .rel {
// let rel = file.mapData
// print(file.fileName)
// for chara in rel.characters {
// print("id:", chara.characterID.hexString(), "model", chara.model.hexString(), (XGCharacterModel(rawValue: chara.model) ?? .none).name, "script:", chara.scriptIndex.hexString(), chara.scriptName)
// }
// print("")
//}
//XGUtility.importTextures()
//XGUtility.exportTextures()
//let bingotex = XGFiles.texture("uv_str_bingo_00.fdat")
//XGFiles.fsys("bingo_menu").fsysData.replaceFile(file: bingotex.compress())
// manually change shinyness using hex editor
//let shinyStart = 0x1fa930
//let getTrainerData = 0x1cefb4
//let trainerGetTID = 0x14e118
//print("shiny glitch")
//(shinyStart - kDolToRAMOffsetDifference + kDolToISOOffsetDifference).hexString().println()
//print("shiny glitch branch links")
//// 0x38600000, // li r3, 0
//// 0x38800002, // li r4, 2
//XGAssembly.createBranchAndLinkFrom(offset: shinyStart + 0x8, toOffset: getTrainerData).hexString().println()
//XGAssembly.createBranchAndLinkFrom(offset: shinyStart + 0xc, toOffset: trainerGetTID).hexString().println()
//
//
//
//print("shiny glitch")
//(0x1248a8 - kDolToRAMOffsetDifference + kDolToISOOffsetDifference).hexString().println()
//// 0x3B800000
//
| gpl-2.0 | 0b5056e0b30cd3f948fb0d247722cfce | 37.064723 | 719 | 0.687834 | 2.485607 | false | false | false | false |
austinzheng/swift | test/stdlib/BridgeStorage.swift | 7 | 5208 | //===--- BridgeStorage.swift.gyb ------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Bridged types are notionally single-word beasts that either store
// an objc class or a native Swift class. We'd like to be able to
// distinguish these cases efficiently.
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-stdlib-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Swift
//===--- Code mimics the stdlib without using spare pointer bits ----------===//
import SwiftShims
protocol BridgeStorage {
associatedtype Native : AnyObject
associatedtype ObjC : AnyObject
init(native: Native, isFlagged: Bool)
init(native: Native)
init(objC: ObjC)
mutating func isUniquelyReferencedNative() -> Bool
mutating func isUniquelyReferencedUnflaggedNative() -> Bool
var isNative: Bool {get}
var isObjC: Bool {get}
var nativeInstance: Native {get}
var unflaggedNativeInstance: Native {get}
var objCInstance: ObjC {get}
}
extension _BridgeStorage : BridgeStorage {}
//===----------------------------------------------------------------------===//
//===--- Testing code -----------------------------------------------------===//
//===----------------------------------------------------------------------===//
import StdlibUnittest
var allTests = TestSuite("DiscriminatedBridgeObject")
class C {
deinit {
print("bye C!")
}
}
import Foundation
func isOSAtLeast(_ major: Int, _ minor: Int, patch: Int = 0) -> Bool {
// isOperatingSystemAtLeastVersion() is unavailable on some OS versions.
if #available(iOS 8.0, OSX 10.10, *) {
let procInfo: AnyObject = ProcessInfo.processInfo
return procInfo.isOperatingSystemAtLeast(
OperatingSystemVersion(majorVersion: major, minorVersion: minor,
patchVersion: patch))
}
return false
}
func expectTagged(_ s: NSString, _ expected: Bool) -> NSString {
#if arch(x86_64)
let mask: UInt = 0x8000000000000001
#elseif arch(arm64)
let mask: UInt = 0x8000000000000000
#else
let mask: UInt = 0
#endif
var osSupportsTaggedStrings: Bool
#if os(iOS)
// NSTaggedPointerString is enabled starting in iOS 9.0.
osSupportsTaggedStrings = isOSAtLeast(9,0)
#elseif os(tvOS) || os(watchOS)
// NSTaggedPointerString is supported in all versions of TVOS and watchOS.
osSupportsTaggedStrings = true
#elseif os(OSX)
// NSTaggedPointerString is enabled starting in OS X 10.10.
osSupportsTaggedStrings = isOSAtLeast(10,10)
#endif
let taggedStringsSupported = osSupportsTaggedStrings && mask != 0
let tagged = unsafeBitCast(s, to: UInt.self) & mask != 0
if taggedStringsSupported && expected == tagged {
// okay
} else if !taggedStringsSupported && !tagged {
// okay
} else {
let un = !tagged ? "un" : ""
fatalError("Unexpectedly \(un)tagged pointer for string \"\(s)\"")
}
return s
}
var taggedNSString : NSString {
return expectTagged(NSString(format: "foo"), true)
}
var unTaggedNSString : NSString {
return expectTagged("fûtbōl" as NSString, false)
}
allTests.test("_BridgeStorage") {
typealias B = _BridgeStorage<C>
let oy: NSString = "oy"
expectTrue(B(objC: oy).objCInstance === oy)
for flag in [false, true] {
do {
var b = B(native: C(), isFlagged: flag)
expectFalse(b.isObjC)
expectTrue(b.isNative)
expectEqual(!flag, b.isUnflaggedNative)
expectTrue(b.isUniquelyReferencedNative())
if !flag {
expectTrue(b.isUniquelyReferencedUnflaggedNative())
}
}
do {
let c = C()
var b = B(native: c, isFlagged: flag)
expectFalse(b.isObjC)
expectTrue(b.isNative)
expectFalse(b.isUniquelyReferencedNative())
expectEqual(!flag, b.isUnflaggedNative)
expectTrue(b.nativeInstance === c)
if !flag {
expectTrue(b.unflaggedNativeInstance === c)
expectFalse(b.isUniquelyReferencedUnflaggedNative())
}
}
}
var b = B(native: C(), isFlagged: false)
expectTrue(b.isUniquelyReferencedNative())
// Add a reference and verify that it's still native but no longer unique
var c = b
expectFalse(b.isUniquelyReferencedNative())
_fixLifetime(c) // make sure c is not killed early
let n = C()
var bb = B(native: n)
expectTrue(bb.nativeInstance === n)
expectTrue(bb.isNative)
expectTrue(bb.isUnflaggedNative)
expectFalse(bb.isObjC)
var d = B(objC: taggedNSString)
expectFalse(d.isUniquelyReferencedNative())
expectFalse(d.isNative)
expectFalse(d.isUnflaggedNative)
expectTrue(d.isObjC)
d = B(objC: unTaggedNSString)
expectFalse(d.isUniquelyReferencedNative())
expectFalse(d.isNative)
expectFalse(d.isUnflaggedNative)
expectTrue(d.isObjC)
}
runAllTests()
| apache-2.0 | 9e62bf6197a85d9e644382fdff81d112 | 27.604396 | 80 | 0.639262 | 4.341952 | false | false | false | false |
austinzheng/swift | test/Parse/ConditionalCompilation/sequence_version.swift | 33 | 1057 | // RUN: %target-typecheck-verify-swift -swift-version 4 -D FOO
#if !swift(>=2.2)
// There should be no error here.
foo bar
#else
let _: Int = 1
#endif
#if (swift(>=2.2))
let _: Int = 1
#else
// There should be no error here.
foo bar
#endif
#if swift(>=99.0) || swift(>=88.1.1)
// There should be no error here.
foo bar baz
#else
undefinedElse() // expected-error {{use of unresolved identifier 'undefinedElse'}}
#endif
#if swift(>=99.0) || FOO
undefinedIf() // expected-error {{use of unresolved identifier 'undefinedIf'}}
#else
undefinedElse()
#endif
#if swift(>=99.0) && FOO
// There should be no error here.
foo bar baz
#else
undefinedElse() // expected-error {{use of unresolved identifier 'undefinedElse'}}
#endif
#if FOO && swift(>=2.2)
undefinedIf() // expected-error {{use of unresolved identifier 'undefinedIf'}}
#else
// There should be no error here.
foo bar baz
#endif
#if swift(>=2.2) && swift(>=1)
undefinedIf() // expected-error {{use of unresolved identifier 'undefinedIf'}}
#else
// There should be no error here.
foo bar baz
#endif
| apache-2.0 | 30852374a4db0d629ad0e6d5d2c47977 | 20.571429 | 82 | 0.68685 | 3.303125 | false | false | false | false |
uxmstudio/UXMPDFKit | Pod/Classes/View/ResizeableView.swift | 1 | 17734 | //
// ResizeableView.swift
// Pods
//
// Created by Chris Anderson on 5/9/17.
//
//
import UIKit
struct ResizableViewAnchorPoint {
var adjustsX: CGFloat
var adjustsY: CGFloat
var adjustsH: CGFloat
var adjustsW: CGFloat
init(_ adjustsX: CGFloat, _ adjustsY: CGFloat, _ adjustsH: CGFloat, _ adjustsW: CGFloat) {
self.adjustsX = adjustsX
self.adjustsY = adjustsY
self.adjustsH = adjustsH
self.adjustsW = adjustsW
}
}
struct CGPointResizableViewAnchorPointPair {
var point: CGPoint
var anchorPoint: ResizableViewAnchorPoint
}
protocol ResizableViewDelegate {
func resizableViewDidBeginEditing(view: ResizableView)
func resizableViewDidEndEditing(view: ResizableView)
func resizableViewDidSelectAction(view: ResizableView, action: String)
}
open class ResizableView: UIView {
lazy var borderView: ResizableBorderView = {
return ResizableBorderView(frame: self.bounds.insetBy(dx: ResizableView.globalInset, dy: ResizableView.globalInset))
}()
var touchStart: CGPoint?
var minWidth: CGFloat = 48.0
var minHeight: CGFloat = 48.0
var anchorPoint: ResizableViewAnchorPoint?
var delegate: ResizableViewDelegate?
var preventsPositionOutsideSuperview: Bool = true
var isLocked = false {
didSet {
self.borderView.isLocked = isLocked
}
}
var menuItems: [UIMenuItem] {
return [
UIMenuItem(
title: "Delete",
action: #selector(ResizableView.menuActionDelete(_:))
)
]
}
override open var frame: CGRect {
didSet {
self.borderView.frame = self.bounds
self.borderView.setNeedsDisplay()
}
}
var isEditing: Bool {
get {
return !self.borderView.isHidden
}
}
var isResizing: Bool {
get {
guard let anchorPoint = self.anchorPoint else { return false }
return anchorPoint.adjustsH != 0.0
|| anchorPoint.adjustsW != 0.0
|| anchorPoint.adjustsX != 0.0
|| anchorPoint.adjustsY != 0.0
}
}
static let globalInset: CGFloat = 0.0
static let noResizeAnchorPoint = ResizableViewAnchorPoint( 0.0, 0.0, 0.0, 0.0 )
static let upperLeftAnchorPoint = ResizableViewAnchorPoint( 1.0, 1.0, -1.0, 1.0 )
static let middleLeftAnchorPoint = ResizableViewAnchorPoint( 1.0, 0.0, 0.0, 1.0 )
static let lowerLeftAnchorPoint = ResizableViewAnchorPoint( 1.0, 0.0, 1.0, 1.0 )
static let upperMiddleAnchorPoint = ResizableViewAnchorPoint( 0.0, 1.0, -1.0, 0.0 )
static let upperRightAnchorPoint = ResizableViewAnchorPoint( 0.0, 1.0, -1.0, -1.0 )
static let middleRightAnchorPoint = ResizableViewAnchorPoint( 0.0, 0.0, 0.0, -1.0 )
static let lowerRightAnchorPoint = ResizableViewAnchorPoint( 0.0, 0.0, 1.0, -1.0 )
static let lowerMiddleAnchorPoint = ResizableViewAnchorPoint( 0.0, 0.0, 1.0, 0.0 )
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
func setup() {
self.borderView.isHidden = true
self.addSubview(self.borderView)
self.clipsToBounds = false
}
func hideEditingHandles() {
self.borderView.isHidden = true
self.isLocked = false
self.hideMenuController()
}
func showEditingHandles() {
self.borderView.isHidden = false
self.showMenuController()
}
func anchorPoint(touch: CGPoint) -> ResizableViewAnchorPoint {
let upperLeft = CGPointResizableViewAnchorPointPair(
point: CGPoint(x: 0.0, y: 0.0),
anchorPoint: ResizableView.upperLeftAnchorPoint
)
let upperMiddle = CGPointResizableViewAnchorPointPair(
point: CGPoint(x: self.bounds.size.width/2, y: 0.0),
anchorPoint: ResizableView.upperMiddleAnchorPoint
)
let upperRight = CGPointResizableViewAnchorPointPair(
point: CGPoint(x: self.bounds.size.width, y: 0.0),
anchorPoint: ResizableView.upperRightAnchorPoint
)
let middleRight = CGPointResizableViewAnchorPointPair(
point: CGPoint(x: self.bounds.size.width, y: self.bounds.size.height/2),
anchorPoint: ResizableView.middleRightAnchorPoint
)
let lowerRight = CGPointResizableViewAnchorPointPair(
point: CGPoint(x: self.bounds.size.width, y: self.bounds.size.height),
anchorPoint: ResizableView.lowerRightAnchorPoint
)
let lowerMiddle = CGPointResizableViewAnchorPointPair(
point: CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height),
anchorPoint: ResizableView.lowerMiddleAnchorPoint
)
let lowerLeft = CGPointResizableViewAnchorPointPair(
point: CGPoint(x: 0, y: self.bounds.size.height),
anchorPoint: ResizableView.lowerLeftAnchorPoint
)
let middleLeft = CGPointResizableViewAnchorPointPair(
point: CGPoint(x: 0, y: self.bounds.size.height/2),
anchorPoint: ResizableView.middleLeftAnchorPoint
)
let centerPoint = CGPointResizableViewAnchorPointPair(
point: CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2),
anchorPoint: ResizableView.noResizeAnchorPoint
)
let allPoints = [ upperLeft, upperRight, lowerRight, lowerLeft,
upperMiddle, lowerMiddle, middleLeft, middleRight, centerPoint ]
var smallestDistance: CGFloat = CGFloat(MAXFLOAT)
var closestPoint = centerPoint
for pointPair in allPoints {
let distance = touch.distance(point: pointPair.point)
if distance < smallestDistance {
closestPoint = pointPair
smallestDistance = distance
}
}
return closestPoint.anchorPoint
}
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
super.touchesBegan(touches, with: event)
if self.isLocked { return }
self.delegate?.resizableViewDidBeginEditing(view: self)
self.borderView.isHidden = false
self.anchorPoint = self.anchorPoint(touch: touch.location(in: self))
self.touchStart = touch.location(in: self.superview)
if !self.isResizing {
self.touchStart = touch.location(in: self)
}
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
if self.isLocked { return }
/// Call delegate method
self.delegate?.resizableViewDidEndEditing(view: self)
super.touchesEnded(touches, with: event)
self.showMenuController()
}
override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
if self.isLocked { return }
/// Call delegate method
self.delegate?.resizableViewDidEndEditing(view: self)
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first,
let superview = self.superview else { return }
super.touchesMoved(touches, with: event)
self.hideMenuController()
if self.isLocked { return }
if self.isResizing {
var touch = touch.location(in: superview)
self.resize(using: &touch)
}
else {
var touch = touch.location(in: self)
self.translate(using: &touch)
}
}
func resize(using touch: inout CGPoint) {
guard let superview = self.superview,
let touchStart = self.touchStart,
let anchorPoint = self.anchorPoint else { return }
// (1) Update the touch point if we're outside the superview.
if self.preventsPositionOutsideSuperview {
let border = ResizableView.globalInset + ResizableBorderView.borderSize / 2.0
if touch.x < border {
touch.x = border
}
if touch.x > superview.bounds.size.width - border {
touch.x = superview.bounds.size.width - border
}
if touch.y < border {
touch.y = border
}
if touch.y > superview.bounds.size.height - border {
touch.y = superview.bounds.size.height - border
}
}
// (2) Calculate the deltas using the current anchor point.
var deltaW = anchorPoint.adjustsW * (touchStart.x - touch.x)
let deltaX = anchorPoint.adjustsX * (-1.0 * deltaW)
var deltaH = anchorPoint.adjustsH * (touch.y - touchStart.y)
let deltaY = anchorPoint.adjustsY * (-1.0 * deltaH)
// (3) Calculate the new frame.
var newX = self.frame.origin.x + deltaX
var newY = self.frame.origin.y + deltaY
var newWidth = self.frame.size.width + deltaW
var newHeight = self.frame.size.height + deltaH
// (4) If the new frame is too small, cancel the changes.
if newWidth < self.minWidth {
newWidth = self.frame.size.width
newX = self.frame.origin.x
}
if newHeight < self.minHeight {
newHeight = self.frame.size.height
newY = self.frame.origin.y
}
// (5) Ensure the resize won't cause the view to move offscreen.
if self.preventsPositionOutsideSuperview {
if newX < superview.bounds.origin.x {
deltaW = self.frame.origin.x - superview.bounds.origin.x
newWidth = self.frame.size.width + deltaW
newX = superview.bounds.origin.x
}
if newX + newWidth > superview.bounds.origin.x + superview.bounds.size.width {
newWidth = superview.bounds.size.width - newX
}
if newY < superview.bounds.origin.y {
deltaH = self.frame.origin.y - superview.bounds.origin.y
newHeight = self.frame.size.height + deltaH
newY = superview.bounds.origin.y
}
if newY + newHeight > superview.bounds.origin.y + superview.bounds.size.height {
newHeight = superview.bounds.size.height - newY
}
}
self.frame = CGRect(x: newX, y: newY, width: newWidth, height: newHeight)
self.touchStart = touch
}
func translate(using touch: inout CGPoint) {
guard let superview = self.superview,
let touchStart = self.touchStart else { return }
var newCenter = CGPoint(
x: self.center.x + touch.x - touchStart.x,
y: self.center.y + touch.y - touchStart.y
)
if self.preventsPositionOutsideSuperview {
// Ensure the translation won't cause the view to move offscreen.
let midPointX = self.bounds.minX
if newCenter.x > superview.bounds.size.width - midPointX {
newCenter.x = superview.bounds.size.width - midPointX
}
if newCenter.x < midPointX {
newCenter.x = midPointX
}
let midPointY = self.bounds.midY
if newCenter.y > superview.bounds.size.height - midPointY {
newCenter.y = superview.bounds.size.height - midPointY
}
if newCenter.y < midPointY {
newCenter.y = midPointY
}
}
self.center = newCenter
}
//MARK: Context Menu Methods
func showMenuController() {
self.becomeFirstResponder()
UIMenuController.shared.setTargetRect(self.frame, in: self.superview!)
UIMenuController.shared.menuItems = self.menuItems
UIMenuController.shared.setMenuVisible(true, animated: true)
}
func hideMenuController() {
self.resignFirstResponder()
}
@objc func menuActionDelete(_ sender: Any!) {
self.delegate?.resizableViewDidSelectAction(view: self, action: "delete")
}
override open func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(menuActionDelete(_:)) {
return true
}
return false
}
}
class ResizableBorderView: UIView {
static let borderSize: CGFloat = 10.0
static let handleSize: CGFloat = 10.0
var isLocked: Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
self.clipsToBounds = false
self.layer.masksToBounds = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
context.saveGState()
context.setLineWidth(1.0)
context.setStrokeColor(UIColor.blue.cgColor)
context.addRect(self.bounds.insetBy(dx: ResizableBorderView.borderSize/2, dy: ResizableBorderView.borderSize/2))
context.strokePath()
let upperLeft = CGRect(
x: -ResizableBorderView.handleSize/2 + ResizableBorderView.borderSize/2,
y: -ResizableBorderView.handleSize/2 + ResizableBorderView.borderSize/2,
width: ResizableBorderView.handleSize,
height: ResizableBorderView.handleSize
)
let upperRight = CGRect(
x: self.bounds.size.width - ResizableBorderView.handleSize/2 - ResizableBorderView.borderSize/2,
y: -ResizableBorderView.handleSize/2 + ResizableBorderView.borderSize/2,
width: ResizableBorderView.handleSize,
height: ResizableBorderView.handleSize
)
let lowerRight = CGRect(
x: self.bounds.size.width - ResizableBorderView.handleSize/2 - ResizableBorderView.borderSize/2,
y: self.bounds.size.height - ResizableBorderView.handleSize/2 - ResizableBorderView.borderSize/2,
width: ResizableBorderView.handleSize,
height: ResizableBorderView.handleSize
)
let lowerLeft = CGRect(
x: -ResizableBorderView.handleSize/2 + ResizableBorderView.borderSize/2,
y: self.bounds.size.height - ResizableBorderView.handleSize/2 - ResizableBorderView.borderSize/2,
width: ResizableBorderView.handleSize,
height: ResizableBorderView.handleSize
)
let upperMiddle = CGRect(
x: (self.bounds.size.width - ResizableBorderView.borderSize)/2,
y: -ResizableBorderView.handleSize/2 + ResizableBorderView.borderSize/2,
width: ResizableBorderView.handleSize,
height: ResizableBorderView.handleSize
)
let lowerMiddle = CGRect(
x: (self.bounds.size.width - ResizableBorderView.handleSize)/2,
y: self.bounds.size.height - ResizableBorderView.handleSize/2 - ResizableBorderView.borderSize/2,
width: ResizableBorderView.handleSize,
height: ResizableBorderView.handleSize
)
let middleLeft = CGRect(
x: -ResizableBorderView.handleSize/2 + ResizableBorderView.borderSize/2,
y: (self.bounds.size.height - ResizableBorderView.handleSize)/2,
width: ResizableBorderView.handleSize,
height: ResizableBorderView.handleSize
)
let middleRight = CGRect(
x: self.bounds.size.width - ResizableBorderView.handleSize/2 - ResizableBorderView.borderSize/2,
y: (self.bounds.size.height - ResizableBorderView.handleSize)/2,
width: ResizableBorderView.handleSize,
height: ResizableBorderView.handleSize
)
let colors: [CGFloat] = [0.4, 0.8, 1.0, 1.0,
0.0, 0.0, 1.0, 1.0]
let baseSpace = CGColorSpaceCreateDeviceRGB()
guard let gradient = CGGradient(
colorSpace: baseSpace,
colorComponents: colors,
locations: nil,
count: 2) else { return }
context.setLineWidth(1.0)
context.setShadow(offset: CGSize(width: 0.5, height: 0.5), blur: 1)
context.setStrokeColor(UIColor.white.cgColor)
let allPoints = [ upperLeft, upperRight, lowerRight, lowerLeft,
upperMiddle, lowerMiddle, middleLeft, middleRight ]
if !isLocked {
for point in allPoints {
context.saveGState()
context.addEllipse(in: point)
context.clip()
let startPoint = CGPoint(x: point.midX, y: point.minY)
let endPoint = CGPoint(x: point.midX, y: point.maxY)
context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0))
context.restoreGState()
context.strokeEllipse(in: point.insetBy(dx: 1, dy: 1))
}
}
context.restoreGState()
}
}
| mit | b47b205b4f2bec1824825819dbd6d445 | 36.413502 | 134 | 0.60494 | 4.570619 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/Interactors/Tasks/TaskRepeatablesSummaryInteractor.swift | 1 | 9503 | //
// TaskRepeatablesSummaryInteractor.swift
// Habitica
//
// Created by Phillip Thelen on 20/03/2017.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import Foundation
import ReactiveSwift
import Habitica_Models
private enum RepeatType {
case never
case daily
case weekly
case monthly
case yearly
func string(_ everyX: Int) -> String {
if self == .never {
return L10n.neverLowerCase
}
if everyX == 1 {
return self.everyName()
} else {
return L10n.Tasks.everyX(everyX, self.repeatName())
}
}
private func everyName() -> String {
switch self {
case .daily:
return L10n.Tasks.Repeats.daily
case .weekly:
return L10n.Tasks.Repeats.weekly
case .monthly:
return L10n.Tasks.Repeats.monthly
case .yearly:
return L10n.Tasks.Repeats.yearly
default:
return ""
}
}
private func repeatName() -> String {
switch self {
case .daily:
return L10n.days
case .weekly:
return L10n.weeks
case .monthly:
return L10n.months
case .yearly:
return L10n.years
default:
return ""
}
}
}
struct RepeatableTask {
var frequency: String?
var everyX = 1
var monday = false
var tuesday = false
var wednesday = false
var thursday = false
var friday = false
var saturday = false
var sunday = false
var startDate: Date?
var daysOfMonth = [Int]()
var weeksOfMonth = [Int]()
init(task: TaskProtocol) {
self.frequency = task.frequency
self.everyX = task.everyX
self.monday = task.weekRepeat?.monday ?? false
self.tuesday = task.weekRepeat?.tuesday ?? false
self.wednesday = task.weekRepeat?.wednesday ?? false
self.thursday = task.weekRepeat?.thursday ?? false
self.friday = task.weekRepeat?.friday ?? false
self.saturday = task.weekRepeat?.saturday ?? false
self.sunday = task.weekRepeat?.sunday ?? false
self.startDate = task.startDate
self.daysOfMonth = task.daysOfMonth
self.weeksOfMonth = task.weeksOfMonth
}
init(frequency: String?,
everyX: Int?,
monday: Bool?,
tuesday: Bool?,
wednesday: Bool?,
thursday: Bool?,
friday: Bool?,
saturday: Bool?,
sunday: Bool?,
startDate: Date?,
daysOfMonth: [Int]?,
weeksOfMonth: [Int]?) {
self.frequency = frequency
self.everyX = everyX ?? 1
self.monday = monday ?? false
self.tuesday = tuesday ?? false
self.wednesday = wednesday ?? false
self.thursday = thursday ?? false
self.friday = friday ?? false
self.saturday = saturday ?? false
self.sunday = sunday ?? false
self.startDate = startDate
if let daysOfMonth = daysOfMonth {
self.daysOfMonth = daysOfMonth
}
if let weeksOfMonth = weeksOfMonth {
self.weeksOfMonth = weeksOfMonth
}
}
func allWeekdaysInactive() -> Bool {
return !monday && !tuesday && !wednesday && !thursday && !friday && !saturday && !sunday
}
}
class TaskRepeatablesSummaryInteractor: NSObject {
let dateFormatter: DateFormatter
let yearlyFormat: String
let monthlyFormat: String
override init() {
let yearlyTemplate = "ddMMMM"
if let yearlyFormat = DateFormatter.dateFormat(fromTemplate: yearlyTemplate, options: 0, locale: NSLocale.current) {
self.yearlyFormat = yearlyFormat
} else {
self.yearlyFormat = ""
}
let monthlyTemplate = "FEEEE"
if let monthlyFormat = DateFormatter.dateFormat(fromTemplate: monthlyTemplate, options: 0, locale: NSLocale.current) {
self.monthlyFormat = monthlyFormat
} else {
self.monthlyFormat = ""
}
self.dateFormatter = DateFormatter()
super.init()
}
//swiftlint:disable function_parameter_count
func repeatablesSummary(frequency: String?,
everyX: Int?,
monday: Bool?,
tuesday: Bool?,
wednesday: Bool?,
thursday: Bool?,
friday: Bool?,
saturday: Bool?,
sunday: Bool?,
startDate: Date?,
daysOfMonth: [Int]?,
weeksOfMonth: [Int]?) -> String {
let task = RepeatableTask(frequency: frequency,
everyX: everyX,
monday: monday,
tuesday: tuesday,
wednesday: wednesday,
thursday: thursday,
friday: friday,
saturday: saturday,
sunday: sunday,
startDate: startDate,
daysOfMonth: daysOfMonth,
weeksOfMonth: weeksOfMonth)
return self.repeatablesSummary(task)
}
//swiftlint:enable function_parameter_count
@objc
func repeatablesSummary(_ task: TaskProtocol) -> String {
return self.repeatablesSummary(RepeatableTask(task: task))
}
func repeatablesSummary(_ task: RepeatableTask) -> String {
let everyX = task.everyX
var repeatType = RepeatType.daily
var repeatOnString: String?
switch task.frequency ?? "" {
case "daily":
repeatType = .daily
case "weekly":
if task.allWeekdaysInactive() {
repeatType = .never
} else {
repeatType = .weekly
}
repeatOnString = weeklyRepeatOn(task)
case "monthly":
repeatType = .monthly
repeatOnString = monthlyRepeatOn(task)
case "yearly":
repeatType = .yearly
repeatOnString = yearlyRepeatOn(task)
default:
break
}
if task.everyX == 0 {
repeatType = .never
}
if let repeatOnString = repeatOnString, repeatType != .never {
return L10n.Tasks.Repeats.repeatsEveryOn(repeatType.string(everyX), repeatOnString)
} else {
return L10n.Tasks.Repeats.repeatsEvery(repeatType.string(everyX))
}
}
private func weeklyRepeatOn(_ task: RepeatableTask) -> String? {
if task.allWeekdaysInactive() {
return nil
} else if task.monday &&
task.tuesday &&
task.wednesday &&
task.thursday &&
task.friday &&
task.saturday &&
task.sunday {
return L10n.Tasks.Repeats.everyDay
} else if task.monday &&
task.tuesday &&
task.wednesday &&
task.thursday &&
task.friday &&
!task.saturday &&
!task.sunday {
return L10n.Tasks.Repeats.weekdays
} else if !task.monday &&
!task.tuesday &&
!task.wednesday &&
!task.thursday &&
!task.friday &&
task.saturday &&
task.sunday {
return L10n.Tasks.Repeats.weekends
} else {
return assembleActiveDaysString(task)
}
}
private func assembleActiveDaysString(_ task: RepeatableTask) -> String {
var repeatOnComponents = [String]()
if task.monday {
repeatOnComponents.append(L10n.monday)
}
if task.tuesday {
repeatOnComponents.append(L10n.tuesday)
}
if task.wednesday {
repeatOnComponents.append(L10n.wednesday)
}
if task.thursday {
repeatOnComponents.append(L10n.thursday)
}
if task.friday {
repeatOnComponents.append(L10n.friday)
}
if task.saturday {
repeatOnComponents.append(L10n.saturday)
}
if task.sunday {
repeatOnComponents.append(L10n.sunday)
}
return repeatOnComponents.joined(separator: ", ")
}
private func monthlyRepeatOn(_ task: RepeatableTask) -> String? {
if task.daysOfMonth.isEmpty == false {
var days = [String]()
for day in task.daysOfMonth {
days.append(String(day))
}
return L10n.Tasks.Repeats.monthlyThe(days.joined(separator: ", "))
}
if task.weeksOfMonth.isEmpty == false {
if let startDate = task.startDate {
self.dateFormatter.dateFormat = monthlyFormat
return L10n.Tasks.Repeats.monthlyThe(dateFormatter.string(from: startDate))
}
}
return nil
}
private func yearlyRepeatOn(_ task: RepeatableTask) -> String? {
if let startDate = task.startDate {
self.dateFormatter.dateFormat = yearlyFormat
return dateFormatter.string(from: startDate)
} else {
return nil
}
}
}
| gpl-3.0 | 8880681c65e553ba1a4e2dbc8bacde7a | 30.568106 | 126 | 0.532099 | 4.857873 | false | false | false | false |
yarshure/Surf | Surf/TwoLableCell.swift | 1 | 638 | //
// TwoLableCell.swift
// Surf
//
// Created by yarshure on 16/1/25.
// Copyright © 2016年 yarshure. All rights reserved.
//
import Foundation
import UIKit
import SFSocket
import XRuler
class TwoLableCell: UITableViewCell {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var cellLabel: UILabel!
func wwdcStyle(){
let style = ProxyGroupSettings.share.wwdcStyle
if style {
label.textColor = UIColor.white
cellLabel.textColor = UIColor.white
}else {
label.textColor = UIColor.black
cellLabel.textColor = UIColor.black
}
}
}
| bsd-3-clause | 77b41857faee9789e1ad25c3c0cb64b3 | 21.678571 | 54 | 0.634646 | 4.150327 | false | false | false | false |
stowy/LayoutKit | Sources/Views/ReloadableViewLayoutAdapter+UITableView.swift | 5 | 2893 | // Copyright 2016 LinkedIn Corp.
// 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.
import UIKit
// MARK: - UITableViewDelegate
extension ReloadableViewLayoutAdapter: UITableViewDelegate {
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return currentArrangement[indexPath.section].items[indexPath.item].frame.height
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return currentArrangement[section].header?.frame.height ?? 0
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return currentArrangement[section].footer?.frame.height ?? 0
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return renderLayout(currentArrangement[section].header, tableView: tableView)
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return renderLayout(currentArrangement[section].footer, tableView: tableView)
}
private func renderLayout(_ layout: LayoutArrangement?, tableView: UITableView) -> UIView? {
guard let layout = layout else {
return nil
}
let view = dequeueHeaderFooterView(tableView: tableView)
layout.makeViews(in: view)
return view
}
private func dequeueHeaderFooterView(tableView: UITableView) -> UITableViewHeaderFooterView {
if let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: reuseIdentifier) {
return view
} else {
return UITableViewHeaderFooterView(reuseIdentifier: reuseIdentifier)
}
}
}
// MARK: - UITableViewDataSource
extension ReloadableViewLayoutAdapter: UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return currentArrangement.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return currentArrangement[section].items.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = currentArrangement[indexPath.section].items[indexPath.item]
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
item.makeViews(in: cell.contentView)
return cell
}
}
| apache-2.0 | f92fc385adc78e64934a5da0bd91ee75 | 39.746479 | 131 | 0.723816 | 5.308257 | false | false | false | false |
BoutFitness/Concept2-SDK | Pod/Classes/Models/RowingWorkoutSummaryData.swift | 1 | 3070 | //
// RowingWorkoutSummaryData.swift
// Pods
//
// Created by Jesse Curry on 10/27/15.
//
//
struct RowingWorkoutSummaryData: CharacteristicModel, CustomDebugStringConvertible {
let DataLength = 20
/*
Data bytes packed as follows:
Log Entry Date Lo,
Log Entry Date Hi,
Log Entry Time Lo,
Log Entry Time Hi,
Elapsed Time Lo (0.01 sec lsb),
Elapsed Time Mid,
Elapsed Time High,
Distance Lo (0.1 m lsb),
Distance Mid,
Distance High,
Average Stroke Rate,
Ending Heartrate,
Average Heartrate,
Min Heartrate,
Max Heartrate,
Drag Factor Average,
Recovery Heart Rate, (zero = not valid data. Updated after 1 minute of rest/recovery)
Workout Type,
Avg Pace Lo (0.1 sec lsb)
Avg Pace Hi
*/
var logEntryDate:C2Date
var logEntryTime:C2Time
var elapsedTime:C2TimeInterval
var distance:C2Distance
var averageStrokeRate:C2StrokeRate
var endingHeartRate:C2HeartRate
var averageHeartRate:C2HeartRate
var minimumHeartRate:C2HeartRate
var maximumHeartRate:C2HeartRate
var dragFactorAverage:C2DragFactor
var recoveryHeartRate:C2HeartRate
var workoutType:WorkoutType?
var averagePace:C2Pace
init(fromData data: Data) {
var arr = [UInt8](repeating: 0, count: DataLength)
(data as NSData).getBytes(&arr, length: DataLength)
logEntryDate = 0 // TODO: find date/time format
logEntryTime = 0
elapsedTime = C2TimeInterval(timeWithLow: UInt32(arr[4]), mid: UInt32(arr[5]), high: UInt32(arr[6]))
distance = C2Distance(distanceWithLow: UInt32(arr[7]), mid: UInt32(arr[8]), high: UInt32(arr[9]))
averageStrokeRate = C2StrokeRate(arr[10])
endingHeartRate = C2HeartRate(arr[11])
averageHeartRate = C2HeartRate(arr[12])
minimumHeartRate = C2HeartRate(arr[13])
maximumHeartRate = C2HeartRate(arr[14])
dragFactorAverage = C2DragFactor(arr[15])
recoveryHeartRate = C2HeartRate(arr[16])
workoutType = WorkoutType(rawValue: Int(arr[17]))
averagePace = C2Pace(paceWithLow: UInt16(arr[18]), high: UInt16(arr[19]))
}
// MARK: PerformanceMonitor
func updatePerformanceMonitor(performanceMonitor:PerformanceMonitor) {
// performanceMonitor.logEntryDate.value = logEntryDate
// performanceMonitor.logEntryTime.value = logEntryTime
performanceMonitor.elapsedTime.value = elapsedTime
performanceMonitor.distance.value = distance
performanceMonitor.averageStrokeRate.value = averageStrokeRate
performanceMonitor.endingHeartRate.value = endingHeartRate
performanceMonitor.averageHeartRate.value = averageHeartRate
performanceMonitor.minimumHeartRate.value = minimumHeartRate
performanceMonitor.maximumHeartRate.value = maximumHeartRate
performanceMonitor.dragFactorAverage.value = dragFactorAverage
performanceMonitor.recoveryHeartRate.value = recoveryHeartRate
performanceMonitor.workoutType.value = workoutType
performanceMonitor.averagePace.value = averagePace
}
// MARK: -
var debugDescription:String {
return "[RowingWorkoutSummaryData]"
}
}
| mit | 8fd78ed43e31b54501c520b265e8abae | 33.111111 | 104 | 0.740065 | 4.120805 | false | false | false | false |
SandcastleApps/partyup | PartyUP/AcceptSampleController.swift | 1 | 16428 | //
// AcceptSampleController.swift
// PartyUP
//
// Created by Fritz Vander Heide on 2015-10-02.
// Copyright © 2015 Sandcastle Application Development. All rights reserved.
//
import UIKit
import VIMVideoPlayer
import ActionSheetPicker_3_0
import SCLAlertView
import Flurry_iOS_SDK
class AcceptSampleController: UIViewController, VIMVideoPlayerViewDelegate, UITextViewDelegate {
var videoUrl: NSURL? {
didSet {
prepareOverlayFor(videoUrl)
}
}
var transitionStartY: CGFloat = 0.0
var venues = [Venue]() {
didSet {
venueButtonState()
}
}
private var selectedLocal = 0
private var selectedAlias = 0
@IBOutlet weak var comment: UITextView! {
didSet {
comment.delegate = self
setCommentPlaceholder()
}
}
@IBOutlet weak var naviBar: UINavigationBar!
@IBOutlet weak var shareButton: UIButton!
@IBOutlet weak var encodingProgress: UIActivityIndicatorView!
@IBOutlet weak var review: UIView!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var sendView: UIView!
private let playView = VIMVideoPlayerView()
private var waiting: SCLAlertViewResponder?
private var exporter: AVAssetExportSession?
override func viewDidLoad() {
super.viewDidLoad()
naviBar.topItem?.titleView = PartyUpConstants.TitleLogo()
if let exporter = exporter where exporter.status == .Exporting {
encodingProgress.startAnimating()
shareButton.hidden = true
shareButton.enabled = false
}
playView.translatesAutoresizingMaskIntoConstraints = false
playView.layer.cornerRadius = 10
playView.layer.masksToBounds = true
playView.player.looping = true
review.insertSubview(playView, atIndex: 0)
review.addConstraint(NSLayoutConstraint(
item: playView,
attribute: .CenterX,
relatedBy: .Equal,
toItem: review,
attribute: .CenterX,
multiplier: 1.0,
constant: 0))
review.addConstraint(NSLayoutConstraint(
item: playView,
attribute: .Width,
relatedBy: .Equal,
toItem: review,
attribute: .Width,
multiplier: 1.0,
constant: 0))
review.addConstraint(NSLayoutConstraint(
item: playView,
attribute: .Height,
relatedBy: .Equal,
toItem: playView,
attribute: .Width,
multiplier: 1.0,
constant: 0))
review.addConstraint(NSLayoutConstraint(
item: playView,
attribute: .Bottom,
relatedBy: .Equal,
toItem: review,
attribute: .Bottom,
multiplier: 1.0,
constant: 0))
let notify = NSNotificationCenter.defaultCenter()
notify.addObserver(self, selector: #selector(AcceptSampleController.observeApplicationBecameActive), name: UIApplicationDidBecomeActiveNotification, object: nil)
notify.addObserver(self, selector: #selector(AcceptSampleController.observeApplicationEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
deinit {
prepareOverlayFor(nil)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
private func prepareOverlayFor(url: NSURL?) {
exporter?.cancelExport()
exporter = nil
if let input = url {
shareButton?.hidden = true
encodingProgress?.startAnimating()
let output = input.URLByDeletingLastPathComponent!.URLByAppendingPathComponent("PartyUp.mp4")
let _ = try? NSFileManager.defaultManager().removeItemAtURL(output!)
exporter = applyToVideo(fromInput: input, toOutput: output!, effectApplicator: AcceptSampleController.generateOverlayOnComposition(self), exportCompletionHander: { status in
self.encodingProgress?.stopAnimating()
self.shareButton?.hidden = false
self.shareButton?.enabled = status == .Completed
} )
}
if exporter == nil {
encodingProgress?.stopAnimating()
shareButton?.hidden = false
shareButton?.enabled = false
}
}
// MARK: - View Lifecycle
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
review.hidden = true
comment.hidden = true
alias.hidden = true
venue.hidden = true
sendView.hidden = true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let offset = transitionStartY - review.frame.origin.y
review.transform = CGAffineTransformMakeTranslation(0, offset)
comment.transform = CGAffineTransformMakeTranslation(0, offset)
venue.transform = CGAffineTransformMakeTranslation(0, offset)
alias.transform = CGAffineTransformMakeTranslation(0, offset)
sendView.transform = CGAffineTransformMakeTranslation(0, sendView.bounds.height)
sendButton.transform = CGAffineTransformMakeTranslation(-sendButton.bounds.width, 0)
review.hidden = false
comment.hidden = false
venue.hidden = false
alias.hidden = false
sendView.hidden = false
UIView.animateWithDuration(0.5,
delay: 0,
usingSpringWithDamping: 0.85,
initialSpringVelocity: 10,
options: [],
animations: {
self.review.transform = CGAffineTransformIdentity
self.sendView.transform = CGAffineTransformIdentity
},
completion: nil)
UIView.animateWithDuration(0.5,
delay: 0.2,
usingSpringWithDamping: 0.75,
initialSpringVelocity: 10,
options: [],
animations: {
self.sendButton.transform = CGAffineTransformIdentity
},
completion: nil)
UIView.animateWithDuration(0.5,
delay: 0.1,
usingSpringWithDamping: 0.85,
initialSpringVelocity: 10,
options: [],
animations: {
self.alias.transform = CGAffineTransformIdentity
},
completion: nil)
UIView.animateWithDuration(0.5,
delay: 0.2,
usingSpringWithDamping: 0.85,
initialSpringVelocity: 10,
options: [],
animations: {
self.venue.transform = CGAffineTransformIdentity
},
completion: nil)
UIView.animateWithDuration(0.5,
delay: 0.3,
usingSpringWithDamping: 0.85,
initialSpringVelocity: 10,
options: [],
animations: {
self.comment.transform = CGAffineTransformIdentity
},
completion: { done in if done { self.tutorial.start(self) } })
}
//MARK: - Alias Picker
private let aliases = [NSLocalizedString("Post Anonymously", comment: "anonymous user moniker")] + AuthenticationManager.shared.user.aliases.values
@IBOutlet weak var alias: UIButton! {
didSet {
aliasButtonState()
}
}
func aliasButtonState() {
var label = "Anonymous"
if selectedAlias < aliases.count {
label = aliases[selectedAlias]
}
alias?.setTitle(label, forState: .Disabled)
if aliases.count > 1 {
label += " ▼"
alias?.setTitle(label, forState: .Normal)
} else {
alias?.enabled = false
}
}
@IBAction func selectAlias(sender: UIButton) {
view.endEditing(false)
let sheet = ActionSheetStringPicker(title: NSLocalizedString("Alias", comment: "Title of the alias picker"),
rows: aliases,
initialSelection: 0,
doneBlock: { (_, row, _) in
self.selectedAlias = row
self.aliasButtonState()
},
cancelBlock: { _ in
// cancelled
},
origin: sender)
sheet.toolbarButtonsColor = UIColor(r: 247, g: 126, b: 86, alpha: 255)
sheet.showActionSheetPicker()
}
// MARK: - Venue Picker
@IBOutlet weak var venue: UIButton! {
didSet {
venueButtonState()
}
}
private func venueButtonState() {
var label = NSLocalizedString("No Venues Available", comment: "Label used in sample acceptance when the user is not near any venues")
if selectedLocal < venues.count {
label = venues[selectedLocal].name
}
venue?.setTitle(label, forState: .Disabled)
if venues.count > 1 {
label += " ▼"
venue?.setTitle(label, forState: .Normal)
} else {
venue?.enabled = false
}
}
@IBAction func selectVenue(sender: UIButton) {
view.endEditing(false)
let sheet = ActionSheetStringPicker(title: NSLocalizedString("Venue", comment: "Title of the venue picker"),
rows: venues.map { $0.name },
initialSelection: 0,
doneBlock: { (_, row, _) in
self.selectedLocal = row
self.venueButtonState()
},
cancelBlock: { _ in
// cancelled
},
origin: sender)
sheet.toolbarButtonsColor = UIColor(r: 247, g: 126, b: 86, alpha: 255)
sheet.showActionSheetPicker()
}
// MARK: - Text View
private func setCommentPlaceholder() {
comment.text = NSLocalizedString("How goes the party?", comment: "Comment placeholder text")
comment.textColor = UIColor.lightGrayColor()
}
func textViewDidBeginEditing(textView: UITextView) {
if textView.textColor != UIColor.blackColor() {
textView.text.removeAll()
textView.textColor = UIColor.blackColor()
}
}
func textViewDidEndEditing(textView: UITextView) {
if comment.text.isEmpty {
setCommentPlaceholder()
}
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
var acceptText = true
if text == "\n" {
view.endEditing(false)
acceptText = false
}
return acceptText
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(false)
}
// MARK: - Navigation
@IBAction func shareSample(sender: UIButton) {
if let url = exporter?.outputURL {
var statement = "Shared from PartyUP!"
if let addendum = commentCleanUp() {
statement += "\n\n" + addendum
}
let share = UIActivityViewController(activityItems: [statement, url], applicationActivities: nil)
share.popoverPresentationController?.sourceView = sender
share.popoverPresentationController?.sourceRect = sender.bounds
self.presentViewController(share, animated: true, completion: nil)
Flurry.logEvent("Sample_Shared_Externally")
}
}
@IBAction func rejectSample(sender: UIBarButtonItem) {
view.endEditing(false)
#if !((arch(i386) || arch(x86_64)) && os(iOS))
do {
if let url = videoUrl {
try NSFileManager.defaultManager().removeItemAtURL(url)
}
} catch {
NSLog("Failed to delete rejected video: \(videoUrl) with error: \(error)")
}
#endif
Flurry.logEvent("Sample_Rejected")
host?.rejectedSample()
}
func commentCleanUp() -> String? {
var statement: String? = comment.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
statement = statement?.isEmpty ?? true || comment.textColor != UIColor.blackColor() ? nil : statement
return statement
}
@IBAction func acceptSample(sender: UIButton) {
view.endEditing(false)
do {
if let url = videoUrl {
waiting = alertWaitWithTitle(NSLocalizedString("Uploading Party Post", comment: "Hud title while uploading a post"), closeButton: nil)
let statement = commentCleanUp()
let place = venues[selectedLocal]
let alias: String? = selectedAlias > 0 ? aliases[selectedAlias] : nil
let sample = Sample(event: place, alias: alias, comment: statement)
Flurry.logEvent("Sample_Accepted", withParameters: ["timestamp" : sample.time, "comment" : sample.comment?.characters.count ?? 0, "venue" : place.unique, "alias" : alias ?? "Anon"], timed: true)
#if (arch(i386) || arch(x86_64)) && os(iOS)
try NSFileManager.defaultManager().copyItemAtURL(url, toURL: NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(sample.media.path!)!)
#else
try NSFileManager.defaultManager().moveItemAtURL(url, toURL: NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(sample.media.path!)!)
#endif
let submission = Submission(sample: sample)
submission.submitWithCompletionHander(completionHandlerForSubmission)
} else {
alertFailureWithTitle(NSLocalizedString("Upload Failed", comment: "Hud title when failed due to no video"),
andDetail: NSLocalizedString("No video available.", comment: "Hud detail indicating no video available")) { self.host?.acceptedSample() }
}
} catch {
self.waiting?.close()
Flurry.logError("Submission_Failed", message: "\(error)", error: nil)
alertFailureWithTitle(NSLocalizedString("Video Missing", comment: "Hud title when failed due to no video"),
andDetail: NSLocalizedString("Couldn't queue post for upload.", comment: "Hud title when failed due to no video")) { self.host?.acceptedSample() }
}
}
private func completionHandlerForSubmission(submission: Submission) {
if let error = submission.error {
Flurry.logError("Submission_Failed", message: "\(error)", error: nil)
let alert = SCLAlertView(appearance: SCLAlertView.SCLAppearance(showCloseButton: false))
alert.addButton(NSLocalizedString("Discard", comment: "Submission discard alert button")) {
Flurry.endTimedEvent("Sample_Accepted", withParameters: ["status" : false])
self.waiting?.close()
self.host?.rejectedSample()
}
alert.addButton(NSLocalizedString("Retry", comment: "Submission retry alert button")) {
submission.submitWithCompletionHander(self.completionHandlerForSubmission)
}
alert.showWarning(NSLocalizedString("Submission Failed", comment: "Alert title after unsuccessfully uploaded sample"),
subTitle: NSLocalizedString("You may discard the post or try submitting it again.", comment: "Alert detail after unsuccessfully uploaded sample"),
colorStyle: 0xf77e56)
} else {
self.waiting?.close()
Flurry.endTimedEvent("Sample_Accepted", withParameters: ["status" : true])
alertSuccessWithTitle(NSLocalizedString("Submission Done", comment: "Hud title after successfully uploaded sample"),
andDetail: NSLocalizedString("Party On!", comment: "Hud detail after successfully uploaded sample")) { self.host?.acceptedSample() }
UIView.animateWithDuration(2.0,
delay: 0.2,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 10,
options: [],
animations: {
self.sendButton.transform = CGAffineTransformMakeTranslation(self.sendView.bounds.width, 0)
},
completion: nil)
self.venues[self.selectedLocal].fetchSamples()
}
}
// MARK: - Hosted
private weak var host: BakeRootController?
override func didMoveToParentViewController(parent: UIViewController?) {
super.didMoveToParentViewController(parent)
host = parent as? BakeRootController
if host == nil {
selectedLocal = 0
setCommentPlaceholder()
playView.player.reset()
} else {
if let url = videoUrl {
playView.player.setURL(url)
playView.player.play()
}
}
}
// MARK: - Application Lifecycle
func observeApplicationBecameActive() {
playView.player.play()
}
func observeApplicationEnterBackground() {
playView.player.pause()
}
// MARK: - Overlay
func generateOverlayOnComposition(composition: AVMutableVideoComposition) {
if let logo = UIImage(named: "Watermark") {
let size = composition.renderSize
let over = CALayer()
over.contents = logo.CGImage
over.frame = CGRectMake(size.width - logo.size.width - 10, logo.size.height - 10, logo.size.width, logo.size.height)
over.masksToBounds = true
over.opacity = 0.65
let parent = CALayer()
parent.frame = CGRectMake(0, 0, size.width, size.height)
let video = CALayer()
video.frame = CGRectMake(0, 0, size.width, size.height)
parent.addSublayer(video)
parent.addSublayer(over)
composition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: video, inLayer: parent)
}
}
// MARK: - Tutorial
private enum CoachIdentifier: Int {
case Greeting = -2100, Comment = 2101, Venue, Submit, Alias
}
private static let availableCoachMarks = [
TutorialMark(identifier: CoachIdentifier.Venue.rawValue, hint: NSLocalizedString("Tap to select where\nyou are partying.", comment: "Accept video venue selection coachmark")),
TutorialMark(identifier: CoachIdentifier.Alias.rawValue, hint: NSLocalizedString("Tap to select one of\nyour social aliases.", comment: "Accept video alias selection coachmark"))]
private let tutorial = TutorialOverlayManager(marks: AcceptSampleController.availableCoachMarks)
}
extension AcceptSampleController: UIBarPositioningDelegate {
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return .TopAttached
}
}
| mit | 25ae6ccd383764ddf44251dd2be508ea | 30.827519 | 198 | 0.699507 | 4.202405 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/DeepLink/CustomSchemeURLParser.swift | 1 | 2327 | //
// Copyright 2020 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
enum CustomSchemeURLParserError: Error {
case unknownHost
case invalidParameters
case unknown
}
/// CustomSchemeURLParser enables to parse custom scheme URL
class CustomSchemeURLParser {
func parse(url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) throws -> DeepLinkOption {
guard let host = url.host else {
throw CustomSchemeURLParserError.unknownHost
}
guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
throw CustomSchemeURLParserError.unknown
}
let deepLinkOption: DeepLinkOption
switch host {
case CustomSchemeURLConstants.Hosts.connect:
if let deepLinkOpt = self.buildDeepLinkConnect(from: urlComponents) {
deepLinkOption = deepLinkOpt
} else {
throw CustomSchemeURLParserError.invalidParameters
}
default:
throw CustomSchemeURLParserError.unknownHost
}
return deepLinkOption
}
private func buildDeepLinkConnect(from urlComponents: URLComponents) -> DeepLinkOption? {
guard let queryItems = urlComponents.queryItems, queryItems.isEmpty == false else {
return nil
}
guard let loginToken = urlComponents.vc_getQueryItemValue(for: SSOURLConstants.Parameters.callbackLoginToken) else {
return nil
}
guard let txnId = urlComponents.vc_getQueryItemValue(for: CustomSchemeURLConstants.Parameters.transactionId) else {
return nil
}
return DeepLinkOption.connect(loginToken, txnId)
}
}
| apache-2.0 | b0a9f3e84fb8430c553f167da636be03 | 33.220588 | 125 | 0.669961 | 5.080786 | false | false | false | false |
sanzhong538/SZChoosePictrue | SZChoosePictrue/SZChoosePictrue/SZImage.swift | 2 | 1736 | //
// SZImage.swift
// SZChoosePictrue
//
// Created by 吴三忠 on 16/6/21.
// Copyright © 2016年 吴三忠. All rights reserved.
//
import UIKit
class SZImage: UIImage {
func clipImageWithImage(image: UIImage) -> UIImage {
let imageWidth = image.size.width
let imageHeight = image.size.height
let minSize = min(imageWidth, imageHeight)
let newRect: CGRect = CGRect(x: 0, y: 0, width: minSize, height: minSize)
let imageRef = CGImageCreateWithImageInRect(image.CGImage, newRect)
UIGraphicsBeginImageContext(newRect.size)
let ref = UIGraphicsGetCurrentContext()
CGContextDrawImage(ref, newRect, imageRef)
let newImage = UIImage(CGImage: imageRef!)
UIGraphicsEndImageContext()
return newImage
}
func clipImageWithImage(image: UIImage, count: Int) -> [UIImage] {
var imageArray = [UIImage]()
let imageSize = image.size.width
let newImageWidth: CGFloat = imageSize / CGFloat(count)
for i in 0..<count {
for j in 0..<count {
let newImageRect = CGRect(x: CGFloat(j) * newImageWidth, y:CGFloat(i) * newImageWidth, width: newImageWidth, height: newImageWidth)
let ref = UIGraphicsGetCurrentContext()
let imageRef = CGImageCreateWithImageInRect(image.CGImage, newImageRect)
UIGraphicsBeginImageContext(newImageRect.size)
CGContextDrawImage(ref, newImageRect, imageRef)
let newImage = UIImage(CGImage: imageRef!)
UIGraphicsEndImageContext()
imageArray.append(newImage)
}
}
return imageArray
}
}
| apache-2.0 | fe7e8de0a1c5c18b186e14a30ebdcb44 | 34.854167 | 147 | 0.622894 | 4.889205 | false | false | false | false |
FRA7/FJWeibo | FJWeibo/Classes/Compose/ComposeViewController.swift | 1 | 2234 | //
// ComposeViewController.swift
// FJWeibo
//
// Created by Francis on 16/3/22.
// Copyright © 2016年 FRAJ. All rights reserved.
//
import UIKit
class ComposeViewController: UIViewController {
//MARK: - 懒加载
@IBOutlet weak var customTextView: ComposeTextView!
private lazy var titleView : ComposeTitleView = ComposeTitleView()
override func viewDidLoad() {
super.viewDidLoad()
setupNav()
//监听键盘的弹出
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillChangeFrame), name: UIKeyboardWillChangeFrameNotification, object: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
customTextView.becomeFirstResponder()
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
// MARK:- 设置UI相关
extension ComposeViewController{
private func setupNav(){
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: #selector(ComposeViewController.cancelBtnClick))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: #selector(ComposeViewController.sendBtnClick))
navigationItem.rightBarButtonItem?.enabled = false
//设置标题栏
titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 36)
navigationItem.titleView = titleView
}
}
// MARK:- 事件监听函数
extension ComposeViewController{
@objc private func cancelBtnClick(){
dismissViewControllerAnimated(true, completion: nil)
}
@objc private func sendBtnClick(){
FJLog("sendBtnClick")
}
//监听键盘的弹出
@objc private func keyboardWillChangeFrame(note: NSNotification){
}
}
//MARK: - UITextViewDelegate
extension ComposeViewController:UITextViewDelegate{
func textViewDidChange(textView: UITextView) {
customTextView.placeHolderLabel.hidden = textView.hasText()
navigationItem.rightBarButtonItem?.enabled = textView.hasText()
}
} | mit | 156ecb06c27bb240c438da29ed93a8bb | 25.341463 | 166 | 0.67346 | 5.253041 | false | false | false | false |
mwsrp/i3s-classic-swift | Sources/I3s/GaussianElimination.swift | 1 | 1549 | private func fillArray(i :Int, n :Int, v :Double) -> [Double] {
var a = [Double]()
var b = i
while (b < n) {
a.append(v)
b += 1
}
return a
}
/**
* Gaussian elimination
* @param array a matrix
* @param array x vector
* @return array x solution vector
*/
public func gauss(a : inout [[Double]], x :[Double]) -> [Double] {
var i = 0
var k = 0
var j = 0
// Just make a single matrix
i = 0
while (i < a.count) {
a[i].append(x[i])
i += 1
}
let n = a.count
i = 0
while(i < n) {
// Search for maximum in this column
var maxEl = abs(a[i][i]),
maxRow = i
k = i + 1
while (k < n) {
if (abs(a[k][i]) > maxEl) {
maxEl = abs(a[k][i])
maxRow = k
}
k += 1
}
// Swap maximum row with current row (column by column)
k = i
while (k < n + 1) {
let tmp = a[maxRow][k]
a[maxRow][k] = a[i][k]
a[i][k] = tmp
k += 1
}
// Make all rows below this one 0 in current column
k = i + 1
while (k < n) {
let c = -a[k][i]/a[i][i]
j = i
while (j < n + 1) {
if (i == j) {
a[k][j] = 0
} else {
a[k][j] += c * a[i][j]
}
j += 1
}
k += 1
}
i += 1
}
// Solve equation ax=b for an upper triangular matrix a
var z = fillArray(i: 0, n: n, v: 0)
i = n - 1
while (i > -1) {
z[i] = a[i][n]/a[i][i]
k = i
while (k > -1 ) {
a[k][n] -= a[k][i] * z[i]
k -= 1
}
i -= 1
}
return z
}
| gpl-3.0 | 460790bf572e6c3b367660cddc6952a9 | 17.011628 | 66 | 0.425436 | 2.741593 | false | false | false | false |
xedin/swift | test/SILGen/extensions.swift | 8 | 3473 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
class Foo {
// CHECK-LABEL: sil hidden [ossa] @$s10extensions3FooC3zim{{[_0-9a-zA-Z]*}}F
func zim() {}
}
extension Foo {
// CHECK-LABEL: sil hidden [ossa] @$s10extensions3FooC4zang{{[_0-9a-zA-Z]*}}F
func zang() {}
// CHECK-LABEL: sil hidden [ossa] @$s10extensions3FooC7zippitySivg
var zippity: Int { return 0 }
}
struct Bar {
// CHECK-LABEL: sil hidden [ossa] @$s10extensions3BarV4zung{{[_0-9a-zA-Z]*}}F
func zung() {}
}
extension Bar {
// CHECK-LABEL: sil hidden [ossa] @$s10extensions3BarV4zoom{{[_0-9a-zA-Z]*}}F
func zoom() {}
}
// CHECK-LABEL: sil hidden [ossa] @$s10extensions19extensionReferencesyyAA3FooCF
func extensionReferences(_ x: Foo) {
// Non-objc extension methods are statically dispatched.
// CHECK: function_ref @$s10extensions3FooC4zang{{[_0-9a-zA-Z]*}}F
x.zang()
// CHECK: function_ref @$s10extensions3FooC7zippitySivg
_ = x.zippity
}
func extensionMethodCurrying(_ x: Foo) {
_ = x.zang
}
// CHECK-LABEL: sil shared [thunk] [ossa] @$s10extensions3FooC4zang{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @$s10extensions3FooC4zang{{[_0-9a-zA-Z]*}}F
// Extensions of generic types with stored property initializers
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s10extensions3BoxV1txSgvpfi : $@convention(thin) <T> () -> @out Optional<T>
// CHECK: bb0(%0 : $*Optional<T>):
// CHECK: inject_enum_addr %0 : $*Optional<T>, #Optional.none!enumelt
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
struct Box<T> {
let t: T? = nil
}
// CHECK-LABEL: sil hidden [ossa] @$s10extensions3BoxV1tACyxGx_tcfC : $@convention(method) <T> (@in T, @thin Box<T>.Type) -> @out Box<T>
// CHECK: [[SELF_BOX:%.*]] = alloc_box $<τ_0_0> { var Box<τ_0_0> } <T>
// CHECK-NEXT: [[UNINIT_SELF_BOX:%.*]] = mark_uninitialized [rootself] [[SELF_BOX]]
// CHECK-NEXT: [[SELF_ADDR:%.*]] = project_box [[UNINIT_SELF_BOX]] : $<τ_0_0> { var Box<τ_0_0> } <T>
// CHECK: [[INIT:%.*]] = function_ref @$s10extensions3BoxV1txSgvpfi : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0>
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<T>
// CHECK-NEXT: apply [[INIT]]<T>([[RESULT]]) : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0>
// CHECK-NEXT: [[T_ADDR:%.*]] = struct_element_addr [[SELF_ADDR]] : $*Box<T>, #Box.t
// CHECK-NEXT: copy_addr [take] [[RESULT]] to [[T_ADDR]] : $*Optional<T>
// CHECK-NEXT: dealloc_stack [[RESULT]] : $*Optional<T>
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<T>
// CHECK-NEXT: [[RESULT_ADDR:%.*]] = init_enum_data_addr [[RESULT]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: copy_addr %1 to [initialization] %14 : $*T
// CHECK-NEXT: inject_enum_addr [[RESULT]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*Box<T>
// CHECK-NEXT: [[T_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*Box<T>, #Box.t
// CHECK-NEXT: copy_addr [take] [[RESULT]] to [[T_ADDR:%.*]] : $*Optional<T>
// CHECK-NEXT: end_access [[WRITE]]
// CHECK-NEXT: dealloc_stack [[RESULT]] : $*Optional<T>
// CHECK-NEXT: copy_addr [[SELF_ADDR]] to [initialization] %0 : $*Box<T>
// CHECK-NEXT: destroy_addr %1 : $*T
// CHECK-NEXT: destroy_value [[UNINIT_SELF_BOX]] : $<τ_0_0> { var Box<τ_0_0> } <T>
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
extension Box {
init(t: T) {
self.t = t
}
}
| apache-2.0 | a35e70fe87556b4752f169de9d70d3ca | 40.22619 | 136 | 0.619116 | 2.852554 | false | false | false | false |
XWJACK/Music | Music/Modules/Player/MusicPlayerSlider.swift | 1 | 1823 | //
// MusicPlayerSlider.swift
// Music
//
// Created by Jack on 4/28/17.
// Copyright © 2017 Jack. All rights reserved.
//
import UIKit
class MusicPlayerSlider: UISlider {
let thumbImageSize = CGSize(width: 20, height: 20)
private let indicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
private let progressView = UIProgressView(progressViewStyle: .default)
override init(frame: CGRect) {
super.init(frame: frame)
progressView.trackTintColor = .clear
progressView.progressTintColor = UIColor.white.withAlphaComponent(0.25)
addSubview(progressView)
indicator.isHidden = true
indicator.isUserInteractionEnabled = false
addSubview(indicator)
bringSubview(toFront: indicator)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func trackRect(forBounds bounds: CGRect) -> CGRect {
let superRect = super.trackRect(forBounds: bounds)
progressView.frame = superRect
return superRect
}
override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect {
let superRect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value)
indicator.frame = superRect
return superRect
}
func buffProgress(_ progress: Progress) {
progressView.setProgress(progress.fractionCompleted.float, animated: true)
}
func resetProgress() {
progressView.setProgress(0, animated: false)
}
func loading(_ isLoading: Bool) {
indicator.isHidden = !isLoading
if isLoading { indicator.startAnimating() }
else { indicator.stopAnimating() }
}
}
| mit | 47abfbb16e80b8363311429b837d5cd8 | 28.868852 | 103 | 0.655324 | 5.047091 | false | false | false | false |
MetalPetal/MetalPetal | Frameworks/MetalPetal/MTICorner.swift | 1 | 696 | //
// MTICorner.swift
// Pods
//
// Created by YuAo on 2021/4/28.
//
import Foundation
#if SWIFT_PACKAGE
import MetalPetalObjectiveC.Core
#endif
extension MTICornerRadius: Equatable {
public static func == (lhs: MTICornerRadius, rhs: MTICornerRadius) -> Bool {
return lhs.topLeft == rhs.topLeft &&
lhs.topRight == rhs.topRight &&
lhs.bottomLeft == rhs.bottomLeft &&
lhs.bottomRight == rhs.bottomRight
}
}
extension MTICornerRadius: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(topLeft)
hasher.combine(topRight)
hasher.combine(bottomLeft)
hasher.combine(bottomRight)
}
}
| mit | 0dec4fb339751423902d8ebcd978d378 | 22.2 | 80 | 0.647989 | 3.866667 | false | false | false | false |
yossan4343434/TK_15 | src/app/Visy/Pods/Spring/Spring/TransitionZoom.swift | 32 | 3313 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class TransitionZoom: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
var isPresenting = true
var duration = 0.4
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView()!
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
if isPresenting {
container.addSubview(fromView)
container.addSubview(toView)
toView.alpha = 0
toView.transform = CGAffineTransformMakeScale(2, 2)
SpringAnimation.springEaseInOut(duration) {
fromView.transform = CGAffineTransformMakeScale(0.5, 0.5)
fromView.alpha = 0
toView.transform = CGAffineTransformIdentity
toView.alpha = 1
}
}
else {
container.addSubview(toView)
container.addSubview(fromView)
SpringAnimation.springEaseInOut(duration) {
fromView.transform = CGAffineTransformMakeScale(2, 2)
fromView.alpha = 0
toView.transform = CGAffineTransformMakeScale(1, 1)
toView.alpha = 1
}
}
delay(duration, closure: {
transitionContext.completeTransition(true)
})
}
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = true
return self
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = false
return self
}
} | mit | 9f6e2bd0f1568ad9590ba047f41daf85 | 40.949367 | 224 | 0.692122 | 5.937276 | false | false | false | false |
neoneye/SwiftyFORM | Source/Cells/OptionViewControllerCell.swift | 1 | 3393 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import UIKit
public struct OptionViewControllerCellModel {
var title: String = ""
var placeholder: String = ""
var titleFont: UIFont = .preferredFont(forTextStyle: .body)
var detailFont: UIFont = .preferredFont(forTextStyle: .body)
var titleTextColor: UIColor = Colors.text
var detailTextColor: UIColor = Colors.secondaryText
var optionField: OptionPickerFormItem?
var selectedOptionRow: OptionRowModel?
var valueDidChange: (OptionRowModel?) -> Void = { (value: OptionRowModel?) in
SwiftyFormLog("value \(String(describing: value))")
}
}
public class OptionViewControllerCell: UITableViewCell, SelectRowDelegate {
fileprivate let model: OptionViewControllerCellModel
fileprivate var selectedOptionRow: OptionRowModel?
fileprivate weak var parentViewController: UIViewController?
public init(parentViewController: UIViewController, model: OptionViewControllerCellModel) {
self.parentViewController = parentViewController
self.model = model
self.selectedOptionRow = model.selectedOptionRow
super.init(style: .value1, reuseIdentifier: nil)
accessoryType = .disclosureIndicator
textLabel?.text = model.title
textLabel?.font = model.titleFont
textLabel?.textColor = model.titleTextColor
detailTextLabel?.font = model.detailFont
detailTextLabel?.textColor = model.detailTextColor
updateValue()
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func humanReadableValue() -> String? {
if let option = selectedOptionRow {
return option.title
} else {
return model.placeholder
}
}
fileprivate func updateValue() {
let s = humanReadableValue()
SwiftyFormLog("update value \(String(describing: s))")
detailTextLabel?.text = s
}
public func setSelectedOptionRowWithoutPropagation(_ option: OptionRowModel?) {
SwiftyFormLog("set selected option: \(String(describing: option?.title)) \(String(describing: option?.identifier))")
selectedOptionRow = option
updateValue()
}
fileprivate func viaOptionList_userPickedOption(_ option: OptionRowModel) {
SwiftyFormLog("user picked option: \(option.title) \(option.identifier)")
if selectedOptionRow === option {
SwiftyFormLog("no change")
return
}
selectedOptionRow = option
updateValue()
model.valueDidChange(option)
}
public func form_didSelectRow(indexPath: IndexPath, tableView: UITableView) {
SwiftyFormLog("will invoke")
guard let vc: UIViewController = parentViewController else {
SwiftyFormLog("Expected a parent view controller")
return
}
guard let nc: UINavigationController = vc.navigationController else {
SwiftyFormLog("Expected parent view controller to have a navigation controller")
return
}
guard let optionField = model.optionField else {
SwiftyFormLog("Expected model to have an optionField")
return
}
// hide keyboard when the user taps this kind of row
tableView.form_firstResponder()?.resignFirstResponder()
let childViewController = OptionListViewController(optionField: optionField) { [weak self] (selected: OptionRowModel) in
self?.viaOptionList_userPickedOption(selected)
nc.popViewController(animated: true)
}
nc.pushViewController(childViewController, animated: true)
SwiftyFormLog("did invoke")
}
}
| mit | 5f54187fc6d074fe9ca5d9d0e84250fa | 31.625 | 122 | 0.758031 | 4.333333 | false | false | false | false |
neoneye/SwiftyFORM | Source/Form/FormViewController.swift | 1 | 2119 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import UIKit
open class FormViewController: UIViewController {
public var dataSource: TableViewSectionArray?
public var keyboardHandler: KeyboardHandler?
private(set) public var tableViewStyle: FormTableViewStyle
public init() {
SwiftyFormLog("super init")
self.tableViewStyle = .grouped
super.init(nibName: nil, bundle: nil)
}
public init(style tableViewStyle: FormTableViewStyle) {
SwiftyFormLog("super init")
self.tableViewStyle = tableViewStyle
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
SwiftyFormLog("super init")
self.tableViewStyle = .grouped
super.init(coder: aDecoder)
}
override open func loadView() {
SwiftyFormLog("super loadview")
view = tableView
keyboardHandler = KeyboardHandler(tableView: tableView)
populateAndSetup()
}
open func populateAndSetup() {
populate(formBuilder)
title = formBuilder.navigationTitle
dataSource = formBuilder.result(self)
tableView.dataSource = dataSource
tableView.delegate = dataSource
}
open func reloadForm() {
DispatchQueue.global(qos: .userInteractive).async {
self.formBuilder.removeAll()
DispatchQueue.main.async {
self.populateAndSetup()
self.tableView.reloadData()
}
}
}
open func populate(_ builder: FormBuilder) {
SwiftyFormLog("subclass must implement populate()")
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
keyboardHandler?.addObservers()
// Fade out, so that the user can see what row has been updated
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPath, animated: true)
}
}
override open func viewDidDisappear(_ animated: Bool) {
self.keyboardHandler?.removeObservers()
super.viewDidDisappear(animated)
}
public lazy var formBuilder: FormBuilder = FormBuilder()
public lazy var tableView: FormTableView = FormTableView(style: tableViewStyle)
}
| mit | 2bf815ac14f1ef0f4a2a93b8f5d33a4c | 27.253333 | 80 | 0.717791 | 4.298174 | false | false | false | false |
SwiftGFX/SwiftMath | Sources/Angle.swift | 1 | 4553 | // Copyright 2016 Stuart Carnie.
// License: https://github.com/SwiftGFX/SwiftMath#license-bsd-2-clause
//
/// A floating point value that represents an angle
@frozen
public struct Angle {
/// The value of the angle in degrees
public let degrees: Float
/// The value of the angle in radians
public var radians: Float {
return degrees * Float.pi / 180.0
}
/// Creates an instance using the value in radians
public init(radians val: Float) {
degrees = val / Float.pi * 180.0
}
/// Creates an instance using the value in degrees
public init(degrees val: Float) {
degrees = val
}
internal init(_ val: Float) {
degrees = val
}
// MARK: Constants
public static let zero = 0°
public static let pi_6 = 30°
public static let pi_4 = 45°
public static let pi_3 = 60°
public static let pi_2 = 90°
public static let pi2_3 = 120°
public static let pi = 180°
public static let pi3_2 = 270°
public static let pi2 = 360°
}
extension Angle: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return "\(degrees)°"
}
public var debugDescription: String {
return "\(degrees)°"
}
}
extension Angle: CustomPlaygroundDisplayConvertible {
public var playgroundDescription: Any {
return degrees
}
}
extension Int {
/// Returns the integer value as an angle in degrees
public var degrees: Angle {
return Angle(degrees: Float(self))
}
}
extension Angle {
// MARK: - operators
// MARK: multiplication (scaling)
public static func *=(lhs: inout Angle, rhs: Float) {
lhs = Angle(lhs.degrees * rhs)
}
public static func *(lhs: Angle, rhs: Float) -> Angle {
return Angle(lhs.degrees * rhs)
}
public static func *(lhs: Float, rhs: Angle) -> Angle {
return Angle(rhs.degrees * lhs)
}
// MARK: division (scaling)
public static func /=(lhs: inout Angle, rhs: Float) {
lhs = Angle(lhs.degrees / rhs)
}
public static func /(lhs: Angle, rhs: Float) -> Angle {
return Angle(lhs.degrees / rhs)
}
// MARK: addition
public static func +=(lhs: inout Angle, rhs: Angle) {
lhs = Angle(lhs.degrees + rhs.degrees)
}
public static func +(lhs: Angle, rhs: Angle) -> Angle {
return Angle(lhs.degrees + rhs.degrees)
}
// MARK: subtraction
public static func -=(lhs: inout Angle, rhs: Angle) {
lhs = Angle(lhs.degrees - rhs.degrees)
}
public static func -(lhs: Angle, rhs: Angle) -> Angle {
return Angle(lhs.degrees - rhs.degrees)
}
// MARK: Modulus
public static func %(lhs: Angle, rhs: Angle) -> Angle {
return Angle(lhs.degrees.truncatingRemainder(dividingBy: rhs.degrees))
}
// MARK: Unary
public static prefix func -(lhs: Angle) -> Angle {
return Angle(-lhs.degrees)
}
}
// MARK: - Equatable
extension Angle: Equatable {
public static func ==(lhs: Angle, rhs: Angle) -> Bool {
return lhs.degrees == rhs.degrees
}
}
// MARK: - Comparable
extension Angle: Comparable {
public static func <(lhs: Angle, rhs: Angle) -> Bool {
return lhs.degrees < rhs.degrees
}
public static func <=(lhs: Angle, rhs: Angle) -> Bool {
return lhs.degrees <= rhs.degrees
}
public static func >(lhs: Angle, rhs: Angle) -> Bool {
return lhs.degrees > rhs.degrees
}
public static func >=(lhs: Angle, rhs: Angle) -> Bool {
return lhs.degrees >= rhs.degrees
}
}
// MARK: - Degrees
/// Degree operator, unicode symbol U+00B0 DEGREE SIGN
postfix operator °
/// The degree operator constructs an `Angle` from the specified floating point value in degrees
///
/// - remark:
/// * Degree operator is the unicode symbol U+00B0 DEGREE SIGN
/// * macOS shortcut is ⌘+⇧+8
public postfix func °(lhs: Float) -> Angle {
return Angle(degrees: lhs)
}
/// Constructs an `Angle` from the specified `Int` value in degrees
public postfix func °(lhs: Int) -> Angle {
return Angle(degrees: Float(lhs))
}
// MARK: - Convenience functions
/// Constructs an `Angle` from the specified floating point value in degrees
public func deg(_ a: Float) -> Angle {
return Angle(degrees: a)
}
/// Constructs an `Angle` from the specified floating point value in radians
public func rad(_ a: Float) -> Angle {
return Angle(radians: a)
}
| bsd-2-clause | e8647638d8ce32df5f17027bc9e89182 | 23.781421 | 96 | 0.619846 | 3.936632 | false | false | false | false |
Shivol/Swift-CS333 | playgrounds/persistence/notes-core-data/notes-core-data/MasterViewController.swift | 3 | 5367 | //
// MasterViewController.swift
// notes-core-data
//
// Created by Илья Лошкарёв on 22.03.17.
// Copyright © 2017 Илья Лошкарёв. All rights reserved.
//
import UIKit
import CoreData
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var detailViewController: DetailViewController? = nil
var fetchController : NSFetchedResultsController<Note>!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem
// Button setup
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:)))
self.navigationItem.rightBarButtonItem = addButton
// Split View Controller
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
// Fetched Results Controller
fetchController = Note.fetchResults(for: Note.fetchRequest(),
withDelegate: self as NSFetchedResultsControllerDelegate)
do {
try fetchController.performFetch()
} catch {
let nserror = error as NSError
fatalError("Fetch error \(nserror), \(nserror.userInfo)")
}
}
override func viewWillAppear(_ animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
func insertNewObject(_ sender: Any) {
let input = UIAlertController(title: "New Note", message: "", preferredStyle: .alert)
input.addTextField {
textField in
textField.placeholder = "What's up?"
}
let ok = UIAlertAction(title: "OK", style: .default) {
[weak input] action in
if let text = input?.textFields?.first?.text {
let _ = Note(content: text)
// CoreDataContainer.saveContext()
} else {
print("no valid input")
}
}
let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
input.addAction(cancel)
input.addAction(ok)
present(input, animated: true)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = self.fetchController.object(at: indexPath)
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return self.fetchController.sections?.count ?? 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchController.sections![section]
return sectionInfo.numberOfObjects
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let note = self.fetchController.object(at: indexPath)
self.configureCell(cell, withData: note)
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
CoreDataContainer.context.delete(self.fetchController.object(at: indexPath))
// CoreDataContainer.saveContext()
}
}
func configureCell(_ cell: UITableViewCell, withData data: Note) {
cell.textLabel!.text = data.content!
cell.detailTextLabel!.text = Note.dateFormatter.string(from: data.date as! Date)
cell.backgroundColor = data.color!
}
// MARK: - Fetched Results Controller
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .delete:
self.tableView.deleteRows(at: [indexPath!], with: .automatic)
case .insert:
self.tableView.insertRows(at: [newIndexPath!], with: .left)
case .update:
configureCell(self.tableView.cellForRow(at: indexPath!)!, withData: anObject as! Note)
case .move:
self.tableView.moveRow(at: indexPath!, to: newIndexPath!)
}
}
}
| mit | 0c6f8f6c4cc19026630154d0ba98c144 | 37.431655 | 200 | 0.646574 | 5.507216 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Insurance | PerchReadyApp/apps/Perch/iphone/native/Perch/Controllers/ProfileViewController.swift | 1 | 7372 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/**
ProfileViewController displays the profile information of the current user. This includes their insurance agent info, as well as their policy number.
The CoverageViewController is also embedded in this view.
*/
class ProfileViewController: PageItemViewController {
// Views on the screen
@IBOutlet weak var navBar: UINavigationBar!
@IBOutlet weak var policyNumberLabel: UILabel!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var coverageButton: UIButton!
var arrowImageView: UIImageView!
@IBOutlet weak var companyName: UILabel!
@IBOutlet weak var agentName: UILabel!
@IBOutlet weak var agentImageView: UIImageView!
// Constraints for the agent info views. Changed when on the 6+
@IBOutlet weak var agentViewHeight: NSLayoutConstraint!
@IBOutlet weak var agentViewLeftMargin: NSLayoutConstraint!
@IBOutlet weak var agentViewRightMargin: NSLayoutConstraint!
@IBOutlet weak var topOfficeHoursMargin: NSLayoutConstraint!
@IBOutlet weak var leftOfficeHoursMargin: NSLayoutConstraint!
@IBOutlet weak var rightOfficeHoursMargin: NSLayoutConstraint!
// Constraint to show and hide the converage view
@IBOutlet weak var containedViewBottom: NSLayoutConstraint!
var onLoad: Bool = true
var coverageShown: Bool = false
let currentUser = CurrentUser.sharedInstance
let configManager = ConfigManager.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
updateInsuranceInfo()
// Apply kerning to the coverage button
let coverageString = NSAttributedString(string: NSLocalizedString("COVERAGE", comment: ""), attributes: [NSKernAttributeName:3.0, NSForegroundColorAttributeName: UIColor.perchOrange(1.0)])
coverageButton.setAttributedTitle(coverageString, forState: UIControlState.Normal)
// Add arrow image view to the coverage button
arrowImageView = UIImageView()
arrowImageView.contentMode = UIViewContentMode.Center
coverageButton.addSubview(arrowImageView)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// if iPhone 6+, increase the margins of the elements on the screen
if UIScreen.mainScreen().bounds.size.height == 736 {
let newAgentViewHeight: CGFloat = 150
agentViewHeight.constant = newAgentViewHeight
agentViewLeftMargin.constant = configManager.largeMargin
agentViewRightMargin.constant = configManager.largeMargin
topOfficeHoursMargin.constant = configManager.largeMargin
leftOfficeHoursMargin.constant = configManager.largeMargin
rightOfficeHoursMargin.constant = configManager.largeMargin
view.updateConstraints()
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Setup the coverage button
updateCoverageButton()
if onLoad {
// Make sure the 'hidden' table view is formatted correctly, then shrink and bring to front
containedViewBottom.constant = containerView.frame.size.height - 1
self.view.setNeedsUpdateConstraints()
self.view.layoutIfNeeded()
view.bringSubviewToFront(containerView)
onLoad = false
}
}
/** Make sure status bar text black */
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.Default
}
// MARK: Button actions
/**
Goes back to the asset overview page
*/
@IBAction func navigateLeftToAssets(sender: AnyObject) {
self.pageHandlerViewController.navigateToIndex(1, fromIndex:self.pageIndex, animated: true)
}
/**
When the coverage button is tapped, either show or hide the coverage info and update the button info
*/
@IBAction func coverageButtonTapped(sender: AnyObject) {
coverageShown = !coverageShown
// Show/hide the coverage view but updating constraints
if coverageShown {
containedViewBottom.constant = 0
} else {
containedViewBottom.constant = containerView.frame.height - 1
}
self.view.setNeedsUpdateConstraints()
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.view.layoutIfNeeded()
self.updateCoverageButton()
})
}
/**
Action that will open the Phone app and call the phone number associated with the insurance agent
*/
@IBAction func phoneButtonTapped(sender: AnyObject) {
Utils.openPhone()
}
/**
Action that will open the default Mail app on the phone and inserts the agent's email address in the 'To' line in the email.
*/
@IBAction func mailButtonTapped(sender: AnyObject) {
Utils.openEmail()
}
/**
Action that will open the default Maps app on the phone and finds the location of the insurance agent based on the address
*/
@IBAction func mapButtonTapped(sender: AnyObject) {
Utils.openMaps()
}
// MARK: Helper functions
/**
Updates the labels on the screen based on the info in the Current User object
*/
func updateInsuranceInfo() {
policyNumberLabel.text = currentUser.insurance.policyNumber
companyName.text = currentUser.insurance.companyName
agentName.text = currentUser.insurance.agentName
agentImageView.image = currentUser.insurance.agentImage
}
/**
Changes the text and the direction of the arrow image in the Coverage button on the screen
*/
func updateCoverageButton() {
var coverageString: NSAttributedString!
// Update the button label and arrow image
if coverageShown {
arrowImageView.image = UIImage(named: "arrow_up_orange")
coverageString = NSAttributedString(string: NSLocalizedString("CLOSE", comment: ""), attributes: [NSKernAttributeName:3.0, NSForegroundColorAttributeName: UIColor.perchOrange(1.0)])
coverageButton.setAttributedTitle(coverageString, forState: UIControlState.Normal)
} else {
arrowImageView.image = UIImage(named: "arrow_down_orange")
coverageString = NSAttributedString(string: NSLocalizedString("COVERAGE", comment: ""), attributes: [NSKernAttributeName:3.0, NSForegroundColorAttributeName: UIColor.perchOrange(1.0)])
coverageButton.setAttributedTitle(coverageString, forState: UIControlState.Normal)
}
// Move the arrow image accordingly
if let stringWidth = coverageButton.attributedTitleForState(UIControlState.Normal)?.size().width {
let imageX: CGFloat = (coverageButton.frame.width / 2) + (stringWidth / 2) - 10
arrowImageView.frame = CGRectMake(imageX, 0, coverageButton.frame.height, coverageButton.frame.height)
}
}
}
// Have the nav bar extend below the status bar
extension ProfileViewController: UINavigationBarDelegate {
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return UIBarPosition.TopAttached
}
}
| epl-1.0 | dae930b0247aa411ebbc1f436eec2e5c | 39.5 | 196 | 0.689323 | 5.341304 | false | false | false | false |
othierry/future | FutureSwift/Pods/Quick/Sources/Quick/NSString+C99ExtendedIdentifier.swift | 1 | 898 | #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Foundation
public extension NSString {
fileprivate static var invalidCharacters: CharacterSet = {
var invalidCharacters = CharacterSet()
let invalidCharacterSets: [CharacterSet] = [
.whitespacesAndNewlines,
.illegalCharacters,
.controlCharacters,
.punctuationCharacters,
.nonBaseCharacters,
.symbols,
]
for invalidSet in invalidCharacterSets {
invalidCharacters.formUnion(invalidSet)
}
return invalidCharacters
}()
@objc(qck_c99ExtendedIdentifier)
var c99ExtendedIdentifier: String {
let validComponents = components(separatedBy: NSString.invalidCharacters)
let result = validComponents.joined(separator: "_")
return result.isEmpty ? "_" : result
}
}
#endif
| mit | 5785f7ea540a78534ad9b033966eb1d2 | 26.212121 | 81 | 0.632517 | 5.345238 | false | false | false | false |
adamastern/decked | Source/LayoutNotificationView.swift | 1 | 3743 | //
// UILayoutNotifyView.swift
// pinch
//
// Created by Adam Stern on 19/04/2016.
// Copyright © 2016 TurboPython. All rights reserved.
//
import UIKit
private struct LayoutNotificationViewKVOKeys{
static let ContentInset = "contentInset"
static let ContentOffset = "contentOffset"
static let Sublayers = "sublayers"
}
internal enum LayoutNotificationViewChange{
case Layout
case ContentOffset
case ContentInset
}
internal class LayoutNotificationView: UIView {
let layoutChangeHandler: (change: LayoutNotificationViewChange) -> Void
let subviewChangeHandler: () -> Void
var superviewContentOffset: CGPoint = CGPointZero
var superviewContentInset: UIEdgeInsets = UIEdgeInsetsZero
private var observersAttached = false
init(frame: CGRect, layoutChangeHandler: (change: LayoutNotificationViewChange) -> Void, subviewChangeHandler:() -> Void){
self.layoutChangeHandler = layoutChangeHandler
self.subviewChangeHandler = subviewChangeHandler
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit{
unbindSuperviewObservers()
}
override func layoutSubviews() {
super.layoutSubviews()
layoutChangeHandler(change: .Layout)
}
override func didMoveToSuperview() {
if let view = superview as? UIScrollView {
superviewContentInset = view.contentInset
superviewContentOffset = view.contentOffset
}
bindSuperviewObservers()
}
override func willMoveToSuperview(newSuperview: UIView?) {
unbindSuperviewObservers()
}
private func bindSuperviewObservers() {
if !observersAttached && superview != nil {
observersAttached = true
superview!.layer.addObserver(self, forKeyPath: LayoutNotificationViewKVOKeys.Sublayers, options: [.New], context: nil)
if superview! is UIScrollView {
superview!.addObserver(self, forKeyPath: LayoutNotificationViewKVOKeys.ContentInset, options: [.New], context: nil)
superview!.addObserver(self, forKeyPath: LayoutNotificationViewKVOKeys.ContentOffset, options: [.New], context: nil)
}
}
}
private func unbindSuperviewObservers() {
if observersAttached && superview != nil{
observersAttached = false
superview!.layer.removeObserver(self, forKeyPath: LayoutNotificationViewKVOKeys.Sublayers)
if superview! is UIScrollView {
superview!.removeObserver(self, forKeyPath: LayoutNotificationViewKVOKeys.ContentInset)
superview!.removeObserver(self, forKeyPath: LayoutNotificationViewKVOKeys.ContentOffset)
}
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if let superview = self.superview, let keyPath = keyPath {
if keyPath == LayoutNotificationViewKVOKeys.Sublayers {
subviewChangeHandler()
}
if let superview = superview as? UIScrollView{
if keyPath == LayoutNotificationViewKVOKeys.ContentOffset {
superviewContentOffset = superview.contentOffset
layoutChangeHandler(change: .ContentOffset)
} else if keyPath == LayoutNotificationViewKVOKeys.ContentInset {
superviewContentInset = superview.contentInset
layoutChangeHandler(change: .ContentInset)
}
}
}
}
}
| mit | 4a975036aeeed4ef9e5433d3f511abdf | 36.049505 | 157 | 0.66248 | 5.560178 | false | false | false | false |
MukeshKumarS/Swift | test/1_stdlib/ErrorHandling.swift | 1 | 8070 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
//
// Tests for error handling in standard library APIs.
//
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
var NoisyCount = 0
class Noisy {
init() { NoisyCount++ }
deinit { NoisyCount-- }
}
enum SillyError: ErrorType { case JazzHands }
var ErrorHandlingTests = TestSuite("ErrorHandling")
ErrorHandlingTests.test("ErrorHandling/withUnsafeMutableBufferPointer restores array on throw") {
var x = [1, 2, 3]
do {
// Check that the array buffer is restored when an error is thrown
// inside withUnsafeMutableBufferPointer
try x.withUnsafeMutableBufferPointer { p in
p[0] = 4
p[1] = 5
p[2] = 6
// FIXME: Seems to have recently regressed
// Buffer should be swapped out of the original array.
// expectEqual(x, [])
throw SillyError.JazzHands
}
expectUnreachable()
} catch {}
// Mutated buffer should be restored to the array.
expectEqual(x, [4, 5, 6])
}
ErrorHandlingTests.test("ErrorHandling/withUnsafeBufferPointer extends lifetime") {
let initialCount = NoisyCount
do {
let x = [Noisy(), Noisy(), Noisy()]
let countBeforeWithUBP = NoisyCount
do {
// Don't use x anywhere in this test after this point.
try x.withUnsafeBufferPointer { p in
expectEqual(NoisyCount, countBeforeWithUBP)
throw SillyError.JazzHands
}
expectUnreachable()
} catch {}
}
expectEqual(NoisyCount, initialCount)
}
ErrorHandlingTests.test("ErrorHandling/Optional.map and .flatMap") {
var x: Int? = 222
do {
let y: String? = try x.map {(n: Int) -> String in
throw SillyError.JazzHands
return "\(n)"
}
expectUnreachable()
} catch {}
do {
let y: String? = try x.flatMap {(n: Int) -> String? in
throw SillyError.JazzHands
return .Some("\(n)")
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/withCString extends lifetime") {
do {
let x = "ad astra per aspera"
do {
// Don't use x anywhere in this test after this point.
try x.withCString { p in
expectEqual(p[0], Int8(("a" as UnicodeScalar).value))
expectEqual(p[1], Int8(("d" as UnicodeScalar).value))
throw SillyError.JazzHands
}
expectUnreachable()
} catch {}
}
// TODO: Some way to check string was deallocated?
}
ErrorHandlingTests.test("ErrorHandling/indexOf") {
do {
let _: Int? = try [1, 2, 3].indexOf {
throw SillyError.JazzHands
return $0 == $0
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/split") {
do {
let _: [String.CharacterView] = try "foo".characters.split { _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
do {
let _: [AnySequence<Character>]
= try AnySequence("foo".characters).split { _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/forEach") {
var loopCount = 0
do {
try [1, 2, 3].forEach {
loopCount += 1
if $0 == 2 {
throw SillyError.JazzHands
}
}
expectUnreachable()
} catch {}
expectEqual(loopCount, 2)
}
ErrorHandlingTests.test("ErrorHandling/Optional flatMap") {
var loopCount = 0
do {
let _: [Int] = try [1, 2, 3].flatMap {
loopCount += 1
if $0 == 2 {
throw SillyError.JazzHands
}
return .Some($0)
}
expectUnreachable()
} catch {}
expectEqual(loopCount, 2)
}
ErrorHandlingTests.test("ErrorHandling/Array flatMap") {
var loopCount = 0
do {
let _: [Int] = try [1, 2, 3].flatMap {(x) -> [Int] in
loopCount += 1
if x == 2 {
throw SillyError.JazzHands
}
return Array(count: x, repeatedValue: x)
}
expectUnreachable()
} catch {}
expectEqual(loopCount, 2)
}
ErrorHandlingTests.test("ErrorHandling/minElement") {
do {
let _: Int? = try [1, 2, 3].minElement { _, _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
do {
let _: Int? = try [1, 2, 3].maxElement { _, _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/startsWith") {
do {
let x: Bool = try [1, 2, 3].startsWith([1, 2]) { _, _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/elementsEqual") {
do {
let x: Bool = try [1, 2, 3].elementsEqual([1, 2, 3]) { _, _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/lexicographicalCompare") {
do {
let x: Bool = try [1, 2, 3].lexicographicalCompare([0, 2, 3]) { _, _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/contains") {
do {
let x: Bool = try [1, 2, 3].contains { _ in
throw SillyError.JazzHands
return false
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/reduce") {
var loopCount = 0
do {
let x: Int = try [1, 2, 3, 4, 5].reduce(0, combine: {
(x: Int, y: Int) -> Int
in
loopCount += 1
var total = x + y
if total > 5 {
throw SillyError.JazzHands
}
return total
})
expectUnreachable()
} catch {}
expectEqual(loopCount, 3)
}
func explosiveBoolean() throws -> Bool {
throw SillyError.JazzHands
}
func explosiveInt() throws -> Int {
throw SillyError.JazzHands
}
ErrorHandlingTests.test("ErrorHandling/operators") {
do {
if try true && explosiveBoolean() {
expectUnreachable()
}
expectUnreachable()
} catch {}
do {
if try false || explosiveBoolean() {
expectUnreachable()
}
expectUnreachable()
} catch {}
do {
if try nil ?? explosiveInt() == 0 {
expectUnreachable()
}
expectUnreachable()
} catch {}
}
ErrorHandlingTests.test("ErrorHandling/Sequence map") {
let initialCount = NoisyCount
let sequence = AnySequence([1, 2, 3])
for throwAtCount in 0...3 {
var loopCount = 0
do {
let result: [Noisy] = try sequence.map { _ in
if loopCount == throwAtCount {
throw SillyError.JazzHands
}
loopCount += 1
return Noisy()
}
expectEqual(NoisyCount, initialCount + 3)
expectEqual(result.count, 3)
} catch {}
expectEqual(NoisyCount, initialCount)
}
}
ErrorHandlingTests.test("ErrorHandling/Sequence filter") {
let initialCount = NoisyCount
for condition in [true, false] {
for throwAtCount in 0...3 {
let sequence = [Noisy(), Noisy(), Noisy()]
var loopCount = 0
do {
let result: [Noisy] = try sequence.filter { _ in
if loopCount == throwAtCount {
throw SillyError.JazzHands
}
loopCount += 1
return condition
}
expectEqual(NoisyCount, initialCount + sequence.count)
expectEqual(result.count, condition ? 3 : 0)
} catch {}
}
expectEqual(NoisyCount, initialCount)
}
}
ErrorHandlingTests.test("ErrorHandling/Collection map") {
let initialCount = NoisyCount
let collection = [1, 2, 3]
for throwAtCount in 0...3 {
var loopCount = 0
do {
let result: [Noisy] = try collection.map { _ in
if loopCount == throwAtCount {
throw SillyError.JazzHands
}
loopCount += 1
return Noisy()
}
expectEqual(NoisyCount, initialCount + 3)
expectEqual(result.count, 3)
} catch {}
expectEqual(NoisyCount, initialCount)
}
}
runAllTests()
| apache-2.0 | 451579f9fefd68f2013a71b257af9a50 | 22.057143 | 97 | 0.618092 | 3.985185 | false | true | false | false |
IntertechInc/uicollectionview-tutorial | CollectionViewCustomLayout/TimeEntryCollectionViewController.swift | 1 | 2440 | //
// ViewController.swift
// CollectionViewCustomLayout
//
// Created by Ryan Harvey on 7/26/15.
// Copyright (c) 2015 Intertech. All rights reserved.
//
import UIKit
class TimeEntryCollectionViewController: UICollectionViewController {
override func viewDidLoad() {
let layout = TimeEntryCollectionLayout()
layout.days = sampleDataByDay
collectionView?.collectionViewLayout = layout
}
override func viewWillAppear(animated: Bool) {
collectionView!.reloadData()
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return sampleDataByDay.count
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sampleDataByDay[section].entries.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("timeEntryCell", forIndexPath: indexPath)
let timeEntry = sampleDataByDay[indexPath.section].entries[indexPath.item]
let label = cell.viewWithTag(1) as! UILabel
label.text = "\(timeEntry.client) (\(timeEntry.hours))"
return cell
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let cell = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "dayHeaderCell", forIndexPath: indexPath) ;
let day = sampleDataByDay[indexPath.section];
let totalHours = day.entries.reduce(0) {(total, entry) in total + entry.hours}
let dateLabel = cell.viewWithTag(1) as! UILabel
let hoursLabel = cell.viewWithTag(2) as! UILabel
dateLabel.text = day.date.stringByReplacingOccurrencesOfString(" ", withString: "\n").uppercaseString
hoursLabel.text = String(totalHours)
let hours = String(totalHours)
let bold = [NSFontAttributeName: UIFont.boldSystemFontOfSize(16)]
let text = NSMutableAttributedString(string: "\(hours)\nHOURS")
text.setAttributes(bold, range: NSMakeRange(0, hours.characters.count))
hoursLabel.attributedText = text
return cell
}
} | mit | c18d4b7aee15e58eb90feb4d70793ac1 | 43.381818 | 180 | 0.710246 | 5.483146 | false | false | false | false |
codesman/toolbox | Sources/VaporToolbox/SelfUpdate.swift | 1 | 852 | import Console
public final class SelfUpdate: Command {
public let id = "update"
public let help: [String] = [
"Downloads and installs the latest toolbox.",
]
public let console: ConsoleProtocol
public let executable: String
public init(console: ConsoleProtocol, executable: String) {
self.console = console
self.executable = executable
}
public func run(arguments: [String]) throws {
let updateBar = console.loadingBar(title: "Updating")
updateBar.start()
do {
_ = try console.backgroundExecute("curl -sL toolbox.qutheory.io | bash 1>&2")
updateBar.finish()
} catch ConsoleError.subexecute(_, let message) {
updateBar.fail()
throw ToolboxError.general("Could not update toolbox: \(message)")
}
}
}
| mit | 55fc965c1471924bdb8baac569b52805 | 28.37931 | 89 | 0.620892 | 4.531915 | false | false | false | false |
peferron/algo | EPI/Graphs/Transform one string into another/swift/main.swift | 1 | 718 | public func shortestProductionSequenceLength(from src: String, to dst: String, in dict: inout Set<String>) -> Int? {
if !dict.contains(src) {
return nil
}
var queue = ArraySlice([(string: src, distance: 1)])
while let (string, distance) = queue.popFirst() {
if string == dst {
return distance
}
for neighbor in dict where adjacent(string, neighbor) {
queue.append((neighbor, distance + 1))
dict.remove(neighbor)
}
}
return nil
}
private func adjacent(_ str1: String, _ str2: String) -> Bool {
return str1.count == str2.count &&
zip(str1, str2).filter { (char1, char2) in char1 != char2 }.count == 1
}
| mit | db3e76bb1a5c0e163d16b8b06fd89318 | 27.72 | 116 | 0.587744 | 3.860215 | false | false | false | false |
SakuragiTen/DYTV | DYTV/DYTV/Classes/Main/View/CollectionBaseCell.swift | 1 | 1165 | //
// CollectionBaseCell.swift
// DYTV
//
// Created by gongsheng on 2017/1/10.
// Copyright © 2017年 gongsheng. All rights reserved.
//
import UIKit
class CollectionBaseCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var onlineButton: UIButton!
@IBOutlet weak var nickNameLabel: UILabel!
//MARK: - 定义模型
var anchor : AnchorModel? {
didSet {
//校验模型是否有值
guard let anchor = anchor else { return }
var onlineStr : String = ""
if anchor.online >= 10000 {
onlineStr = "\(Int(anchor.online / 10000))万在线"
} else {
onlineStr = "\(anchor.online)在线"
}
onlineButton.setTitle(onlineStr, for: UIControlState())
//昵称的显示
nickNameLabel.text = anchor.nickname
//设置封面图片
// guard let iconURL = URL(string : anchor.vertical_src) else {
// return
// }
// iconImageView
}
}
}
| mit | 4b2fccea92785e079a910a4c0bd771ea | 21.571429 | 74 | 0.5217 | 4.850877 | false | false | false | false |
loudnate/Loop | Loop/View Controllers/TestingScenariosTableViewController.swift | 1 | 5745 | //
// TestingScenariosTableViewController.swift
// Loop
//
// Created by Michael Pangburn on 4/20/19.
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import UIKit
import LoopKitUI
final class TestingScenariosTableViewController: RadioSelectionTableViewController {
private let scenariosManager: TestingScenariosManager
private var scenarioURLs: [URL] = [] {
didSet {
options = scenarioURLs.map { $0.deletingPathExtension().lastPathComponent }
if isViewLoaded {
DispatchQueue.main.async {
self.updateLoadButtonEnabled()
self.tableView.reloadData()
}
}
}
}
override var selectedIndex: Int? {
didSet {
updateLoadButtonEnabled()
}
}
private lazy var loadButtonItem = UIBarButtonItem(title: "Load", style: .done, target: self, action: #selector(loadSelectedScenario))
init(scenariosManager: TestingScenariosManager) {
assertDebugOnly()
self.scenariosManager = scenariosManager
super.init(style: .grouped)
scenariosManager.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
title = "🧪 Scenarios"
navigationItem.rightBarButtonItem = loadButtonItem
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel))
contextHelp = "The scenarios directory location is available in the debug output of the Xcode console."
if let activeScenarioURL = scenariosManager.activeScenarioURL {
selectedIndex = scenarioURLs.firstIndex(of: activeScenarioURL)
}
updateLoadButtonEnabled()
}
override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let url = scenarioURLs[indexPath.row]
let rewindScenario = contextualAction(
rowTitle: "⏮ Rewind",
alertTitle: "Rewind Scenario",
message: "Step backward a number of loop iterations.",
loadScenario: { self.scenariosManager.loadScenario(from: url, rewoundByLoopIterations: $0, completion: $1) }
)
rewindScenario.backgroundColor = .lightGray
return UISwipeActionsConfiguration(actions: [rewindScenario])
}
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let url = scenarioURLs[indexPath.row]
let advanceScenario = contextualAction(
rowTitle: "Advance ⏭",
alertTitle: "Advance Scenario",
message: "Step forward a number of loop iterations.",
loadScenario: { self.scenariosManager.loadScenario(from: url, advancedByLoopIterations: $0, completion: $1) }
)
advanceScenario.backgroundColor = .HIGGreenColor()
return UISwipeActionsConfiguration(actions: [advanceScenario])
}
private func contextualAction(
rowTitle: String, alertTitle: String, message: String,
loadScenario: @escaping (_ iterations: Int, _ completion: @escaping (Error?) -> Void) -> Void
) -> UIContextualAction {
return UIContextualAction(style: .normal, title: rowTitle) { action, sourceView, completion in
let alert = UIAlertController(
title: alertTitle,
message: message,
cancelButtonTitle: "Cancel",
okButtonTitle: "OK",
validate: { text in
guard let iterations = Int(text) else {
return false
}
return iterations > 0
},
textFieldConfiguration: { textField in
textField.placeholder = "Iteration count"
textField.keyboardType = .numberPad
}
) { result in
switch result {
case .cancel:
completion(false)
case .ok(let iterationsText):
let iterations = Int(iterationsText)!
loadScenario(iterations) { [weak self] _ in
self?.dismiss(animated: true)
}
completion(true)
}
}
self.present(alert, animated: true)
}
}
private func updateLoadButtonEnabled() {
loadButtonItem.isEnabled = !scenarioURLs.isEmpty && selectedIndex != nil
}
@objc private func loadSelectedScenario() {
guard let selectedIndex = selectedIndex else {
assertionFailure("Loading should be possible only when a scenario is selected")
return
}
let url = scenarioURLs[selectedIndex]
scenariosManager.loadScenario(from: url) { error in
DispatchQueue.main.async {
if let error = error {
self.present(UIAlertController(with: error), animated: true)
} else {
self.dismiss(animated: true)
}
}
}
}
@objc private func cancel() {
self.dismiss(animated: true)
}
}
extension TestingScenariosTableViewController: TestingScenariosManagerDelegate {
func testingScenariosManager(_ manager: TestingScenariosManager, didUpdateScenarioURLs scenarioURLs: [URL]) {
self.scenarioURLs = scenarioURLs
}
}
| apache-2.0 | b1c75556e21809a722697f5449aa0b85 | 34.63354 | 151 | 0.613038 | 5.521655 | false | false | false | false |
PureSwift/BluetoothLinux | Sources/BluetoothLinux/L2CAP/L2CAPSocket.swift | 1 | 7763 | //
// L2CAP.swift
// BluetoothLinux
//
// Created by Alsey Coleman Miller on 2/28/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
import Foundation
import Bluetooth
import BluetoothHCI
@_implementationOnly import CBluetoothLinux
import SystemPackage
import Socket
/// L2CAP Bluetooth socket
public final class L2CAPSocket: Bluetooth.L2CAPSocket {
// MARK: - Properties
/// Internal socket file descriptor
@usableFromInline
internal let socket: Socket
/// L2CAP Socket address
public let address: BluetoothAddress
public var event: L2CAPSocketEventStream {
let stream = self.socket.event
var iterator = stream.makeAsyncIterator()
return L2CAPSocketEventStream(unfolding: {
await iterator
.next()
.map { L2CAPSocketEvent($0) }
})
}
// MARK: - Initialization
deinit {
Task(priority: .high) {
await socket.close()
}
}
internal init(
fileDescriptor: SocketDescriptor,
address: L2CAPSocketAddress
) async {
self.socket = await Socket(fileDescriptor: fileDescriptor)
self.address = address.address
}
/// Create a new L2CAP socket with the specified address.
public init(address: L2CAPSocketAddress) async throws {
self.socket = try await Socket(fileDescriptor: .l2cap(address, [.closeOnExec, .nonBlocking]))
self.address = address.address
}
/// Create a new L2CAP socket on the `HostController` with the specified identifier.
public init(
hostController: HostController,
type: AddressType? = nil,
protocolServiceMultiplexer: ProtocolServiceMultiplexer? = nil,
channel: ChannelIdentifier
) async throws {
let deviceAddress = try await hostController.readDeviceAddress()
let socketAddress = L2CAPSocketAddress(
address: deviceAddress,
addressType: type,
protocolServiceMultiplexer: protocolServiceMultiplexer,
channel: channel
)
self.socket = try await Socket(fileDescriptor: .l2cap(socketAddress, [.closeOnExec, .nonBlocking]))
self.address = socketAddress.address
}
/// Creates a server socket for an L2CAP connection.
public static func lowEnergyServer(
address: BluetoothAddress,
isRandom: Bool = false,
backlog: Int = 10
) async throws -> Self {
let address = L2CAPSocketAddress(
lowEnergy: address,
isRandom: isRandom
)
let fileDescriptor = try SocketDescriptor.l2cap(address, [.closeOnExec, .nonBlocking])
try fileDescriptor.closeIfThrows {
try fileDescriptor.listen(backlog: backlog)
}
return await Self(
fileDescriptor: fileDescriptor,
address: address
)
}
/// Creates a server socket for an L2CAP connection.
public static func lowEnergyServer(
hostController: HostController,
isRandom: Bool = false,
backlog: Int = 10
) async throws -> Self {
let address = try await hostController.readDeviceAddress()
return try await lowEnergyServer(
address: address,
isRandom: isRandom,
backlog: backlog
)
}
/// Creates a new socket connected to the remote address specified.
public static func lowEnergyClient(
address: BluetoothAddress,
destination: BluetoothAddress,
isRandom: Bool
) async throws -> Self {
try await lowEnergyClient(
address: address,
destination: destination,
type: isRandom ? .random : .public
)
}
/// Creates a client socket for an L2CAP connection.
public static func lowEnergyClient(
address localAddress: BluetoothAddress,
destination destinationAddress: BluetoothAddress,
type destinationAddressType: LowEnergyAddressType
) async throws -> Self {
let localSocketAddress = L2CAPSocketAddress(
address: localAddress,
addressType: nil,
protocolServiceMultiplexer: nil,
channel: .att
)
let destinationSocketAddress = L2CAPSocketAddress(
address: destinationAddress,
addressType: AddressType(lowEnergy: destinationAddressType),
protocolServiceMultiplexer: nil,
channel: .att
)
let fileDescriptor = try SocketDescriptor.l2cap(localSocketAddress, [.closeOnExec, .nonBlocking])
try await fileDescriptor.closeIfThrows {
try await fileDescriptor.connect(to: destinationSocketAddress, sleep: 100_000_000)
}
return await Self(
fileDescriptor: fileDescriptor,
address: localSocketAddress
)
}
/// Creates a client socket for an L2CAP connection.
public static func lowEnergyClient(
address localAddress: BluetoothAddress,
destination: HCILEAdvertisingReport.Report
) async throws -> Self {
try await lowEnergyClient(
address: localAddress,
destination: destination.address,
type: destination.addressType
)
}
// MARK: - Methods
/// Attempt to accept an incoming connection.
public func accept() async throws -> Self {
let (clientFileDescriptor, clientAddress) = try await socket.fileDescriptor.accept(L2CAPSocketAddress.self, sleep: 100_000_000)
try clientFileDescriptor.closeIfThrows {
try clientFileDescriptor.setNonblocking()
}
return await Self(
fileDescriptor: clientFileDescriptor,
address: clientAddress
)
}
/// Write to the socket.
public func send(_ data: Data) async throws {
try await socket.write(data)
}
/// Reads from the socket.
public func recieve(_ bufferSize: Int) async throws -> Data {
return try await socket.read(bufferSize)
}
/// Attempts to change the socket's security level.
public func setSecurityLevel(_ securityLevel: SecurityLevel) throws {
let socketOption = BluetoothSocketOption.Security(
level: securityLevel,
keySize: 0
)
try socket.fileDescriptor.setSocketOption(socketOption)
}
public var securityLevel: SecurityLevel {
get throws {
let socketOption = try socket.fileDescriptor.getSocketOption(BluetoothSocketOption.Security.self)
return socketOption.level
}
}
/// Attempt to get L2CAP socket options.
public var options: L2CAPSocketOption.Options {
get throws {
return try socket.fileDescriptor.getSocketOption(L2CAPSocketOption.Options.self)
}
}
}
// MARK: - Supporting Types
internal extension L2CAPSocketEvent {
init(_ event: Socket.Event) {
switch event {
case .pendingRead:
self = .pendingRead
case let .read(bytes):
self = .read(bytes)
case let .write(bytes):
self = .write(bytes)
case let .close(error):
self = .close(error)
}
}
}
internal extension L2CAPSocket {
enum ConnectionResult: UInt16 {
case success = 0x0000
case pending = 0x0001
case badPSM = 0x0002
case secBlock = 0x0003
case noMemory = 0x0004
}
enum ConnectionStatus: UInt16 {
case noInfo = 0x0000
case authenticationPending = 0x0001
case authorizationPending = 0x0002
}
}
| mit | 71d9951709fd0b5726b39765027524be | 30.298387 | 135 | 0.623551 | 4.985228 | false | false | false | false |
Masteryyz/CSYMicroBlockSina | CSYMicroBlockSina/CSYMicroBlockSina/Classes/Module/Message/MessageTableViewController.swift | 1 | 3516 | //
// MessageTableViewController.swift
// CSYMicroBlockSina
//
// Created by 姚彦兆 on 15/11/8.
// Copyright © 2015年 姚彦兆. All rights reserved.
//
import UIKit
class MessageTableViewController: CSYBasicTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
if !GetUserInfoModel().isLogin{
visitorView?.setViewItems("visitordiscover_image_message", tipsInfo: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知")
}
// 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.
}
*/
}
| mit | 92ce64be6b77a247cb1d51d370f8ea58 | 33.43 | 157 | 0.680802 | 5.589286 | false | false | false | false |
tqtifnypmb/armature | Sources/Armature/Connection/RawConnection.swift | 1 | 2332 | //
// RawConnection.swift
// Armature
//
// The MIT License (MIT)
//
// Copyright (c) 2016 tqtifnypmb
//
// 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
final class RawConnection: Connection {
var sock: Int32
private var inputStream: InputStream!
private var outputStream: OutputStream!
required init(sock: Int32, server _: Server) {
self.sock = sock
self.inputStream = RawInputStream.init(sock: self.sock)
self.outputStream = RawOutputStream.init(sock: self.sock)
}
init(sock: Int32) {
self.sock = sock
self.inputStream = RawInputStream.init(sock: self.sock)
self.outputStream = RawOutputStream.init(sock: self.sock)
}
func readInto(inout buffer: [UInt8]) throws -> Int {
return try self.inputStream.readInto(&buffer)
}
func readLength(len: Int) throws -> [UInt8] {
var buffer = [UInt8].init(count: len, repeatedValue: 0)
let nread = try self.readInto(&buffer)
if nread < len {
buffer = [UInt8].init(buffer.dropLast(len - nread))
}
return buffer
}
func write(inout data: [UInt8]) throws {
try self.outputStream.write(&data)
}
func loop(once: Bool) {}
func halt() {}
}
| mit | dea554013ee57a49df8fec8d64e08268 | 33.80597 | 82 | 0.680961 | 4.164286 | false | false | false | false |
thomasvl/swift-protobuf | Sources/protoc-gen-swift/GeneratorOptions.swift | 2 | 3576 | // Sources/protoc-gen-swift/GeneratorOptions.swift - Wrapper for generator options
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
import SwiftProtobufPluginLibrary
class GeneratorOptions {
enum OutputNaming {
case fullPath
case pathToUnderscores
case dropPath
init?(flag: String) {
switch flag.lowercased() {
case "fullpath", "full_path":
self = .fullPath
case "pathtounderscores", "path_to_underscores":
self = .pathToUnderscores
case "droppath", "drop_path":
self = .dropPath
default:
return nil
}
}
}
enum Visibility {
case `internal`
case `public`
init?(flag: String) {
switch flag.lowercased() {
case "internal":
self = .internal
case "public":
self = .public
default:
return nil
}
}
}
let outputNaming: OutputNaming
let protoToModuleMappings: ProtoFileToModuleMappings
let visibility: Visibility
/// A string snippet to insert for the visibility
let visibilitySourceSnippet: String
init(parameter: String?) throws {
var outputNaming: OutputNaming = .fullPath
var moduleMapPath: String?
var visibility: Visibility = .internal
var swiftProtobufModuleName: String? = nil
for pair in parseParameter(string:parameter) {
switch pair.key {
case "FileNaming":
if let naming = OutputNaming(flag: pair.value) {
outputNaming = naming
} else {
throw GenerationError.invalidParameterValue(name: pair.key,
value: pair.value)
}
case "ProtoPathModuleMappings":
if !pair.value.isEmpty {
moduleMapPath = pair.value
}
case "Visibility":
if let value = Visibility(flag: pair.value) {
visibility = value
} else {
throw GenerationError.invalidParameterValue(name: pair.key,
value: pair.value)
}
case "SwiftProtobufModuleName":
// This option is not documented in PLUGIN.md, because it's a feature
// that would ordinarily not be required for a given adopter.
if isValidSwiftIdentifier(pair.value) {
swiftProtobufModuleName = pair.value
} else {
throw GenerationError.invalidParameterValue(name: pair.key,
value: pair.value)
}
default:
throw GenerationError.unknownParameter(name: pair.key)
}
}
if let moduleMapPath = moduleMapPath {
do {
self.protoToModuleMappings = try ProtoFileToModuleMappings(path: moduleMapPath, swiftProtobufModuleName: swiftProtobufModuleName)
} catch let e {
throw GenerationError.wrappedError(
message: "Parameter 'ProtoPathModuleMappings=\(moduleMapPath)'",
error: e)
}
} else {
self.protoToModuleMappings = ProtoFileToModuleMappings(swiftProtobufModuleName: swiftProtobufModuleName)
}
self.outputNaming = outputNaming
self.visibility = visibility
switch visibility {
case .internal:
visibilitySourceSnippet = ""
case .public:
visibilitySourceSnippet = "public "
}
}
}
| apache-2.0 | ff2d1aeac90d377b23f0c02d850bf895 | 29.05042 | 137 | 0.610459 | 4.878581 | false | false | false | false |
jakarmy/swift-summary | The Swift Summary Book.playground/Pages/14 Initialization.xcplaygroundpage/Contents.swift | 1 | 7384 |
// |=------------------------------------------------------=|
// Copyright (c) 2016 Juan Antonio Karmy.
// Licensed under MIT License
//
// See https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ for Swift Language Reference
//
// See Juan Antonio Karmy - http://karmy.co | http://twitter.com/jkarmy
//
// |=------------------------------------------------------=|
import UIKit
struct Celsius {
var temperatureInCelsius: Double
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}
init(_ celsius: Double) {
temperatureInCelsius = celsius
}
}
/*
For the struct, a memberwise initializer is provided. This means that stored properties don't
necessarily need to have an initial value. A default initializer is created for all of them.
*/
struct Other {
var temp: Double
var otherProp: Int = 10
}
struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
/*
In this case, the second initializer performs delegation, which is
calling another initializer within the struct. This is only valid for
value types, and not classes!
*/
struct Rect {
var origin = Point()
var size = Size()
init() {}
init(origin: Point, size: Size) {
self.origin = origin
self.size = size
}
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
/*
==================================
*/
/*
For a class, every stored property must have an initial value, or have a value assigned to it inside the initializer.
This reference image explains the relationship between designated initializers and convenience initializers.
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/initializerDelegation01_2x.png
• Rule 1
A designated initializer must call a designated initializer from its immediate superclass.
• Rule 2
A convenience initializer must call another initializer from the same class.
• Rule 3
A convenience initializer must ultimately call a designated initializer.
A simple way to remember this is:
- Designated initializers must always delegate up.
- Convenience initializers must always delegate across.
• Phase 1
- A designated or convenience initializer is called on a class.
- Memory for a new instance of that class is allocated. The memory is not yet initialized.
- A designated initializer for that class confirms that all stored properties introduced by that class have a value. The memory for these stored properties is now initialized.
- The designated initializer hands off to a superclass initializer to perform the same task for its own stored properties.
- This continues up the class inheritance chain until the top of the chain is reached.
- Once the top of the chain is reached, and the final class in the chain has ensured that all of its store
properties have a value, the instance’s memory is considered to be fully initialized, and phase 1 is complete.
• Phase 2
- Working back down from the top of the chain, each designated initializer in the chain has the option to
customize the instance further. Initializers are now able to access self and can modify its properties, call its instance methods, and so on.
- Finally, any convenience initializers in the chain have the option to customize the instance and to work with self.
Also, keep in mind that:
• Rule 1
If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.
• Rule 2
If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as
per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.
NOTE
A subclass can implement a superclass designated initializer as a subclass convenience initializer as part of satisfying rule 2.
*/
class Human {
var gender: String
init(){
self.gender = "Female"
}
}
class Person: Human {
var name: String
init(fullName name: String){
//Phase 1: Initialize class-defined properties and call the superclass initializer.
self.name = name
super.init()
//-------
//Phase 2: Further customization of local and inherited properties.
self.gender = "Male"
//-------
}
convenience init(partialName name: String){
//Phase 1: Call designated initializer
let newName = "\(name) Karmy"
self.init(fullName: newName)
//-------
//Phase 2: Access to self and properties
self.name = "John Karmy"
//-------
}
}
/*
==================================
*/
/*
Failable initializers allow us to return nil during initialization in case there was a problem.
The object being initalized is treated as an optional.
You can also define a failable initializer that returns an implicitly unwrapped optional instance by writing init!
*/
// For enums, nil can be returned at any point of initalizations
enum TemperatureUnit {
case Kelvin, Celsius, Fahrenheit
init?(symbol: Character) {
switch symbol {
case "K":
self = .Kelvin
case "C":
self = .Celsius
case "F":
self = .Fahrenheit
default:
return nil
}
}
}
// For class instances, nil can only be returned after initalizing all properties.
class Product {
let name: String!
init?(name: String) {
self.name = name
if name.isEmpty { return nil }
}
}
/*
==================================
*/
/*
You can pre-initialize properties by running code inside a closure. Since the execution happens before all other properties are initialized,
you can't access other properties nor call self inside the closure.
*/
struct Checkerboard {
let boardColors: [Bool] = {
var temporaryBoard = [Bool]()
var isBlack = false
for i in 1...10 {
for j in 1...10 {
temporaryBoard.append(isBlack)
isBlack = !isBlack
}
isBlack = !isBlack
}
return temporaryBoard
}() //Note that these parenthesis indicate that you want to run the closure immediately.
func squareIsBlackAtRow(row: Int, column: Int) -> Bool {
return boardColors[(row * 10) + column]
}
}
/*
==================================
*/
class ViewController: UIViewController {
override func viewDidLoad() {
let bodyTemperature = Celsius(37.0)
print((bodyTemperature.temperatureInCelsius))
let person = Person(fullName: "John")
print(person.name)
let other = Other(temp: 20, otherProp: 10)
print(other.otherProp)
if let product = Product(name: "Apple"){
print("Product is not nil. Names \(product.name)")
}
}
}
| mit | d535ee7ae8f4dfb9c754d0625acc652e | 30.063291 | 176 | 0.651182 | 4.615674 | false | false | false | false |
bindlechat/ZenText | Example/Pods/Nimble/Sources/Nimble/Matchers/Contain.swift | 4 | 5139 | import Foundation
/// A Nimble matcher that succeeds when the actual sequence contains the expected values.
public func contain<S: Sequence, T: Equatable>(_ items: T...) -> Predicate<S>
where S.Element == T {
return contain(items)
}
/// A Nimble matcher that succeeds when the actual sequence contains the expected values.
public func contain<S: Sequence, T: Equatable>(_ items: [T]) -> Predicate<S>
where S.Element == T {
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
if let actual = try actualExpression.evaluate() {
let matches = items.allSatisfy {
return actual.contains($0)
}
return PredicateStatus(bool: matches)
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual set contains the expected values.
public func contain<S: SetAlgebra, T: Equatable>(_ items: T...) -> Predicate<S>
where S.Element == T {
return contain(items)
}
/// A Nimble matcher that succeeds when the actual set contains the expected values.
public func contain<S: SetAlgebra, T: Equatable>(_ items: [T]) -> Predicate<S>
where S.Element == T {
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
if let actual = try actualExpression.evaluate() {
let matches = items.allSatisfy {
return actual.contains($0)
}
return PredicateStatus(bool: matches)
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual string contains the expected substring.
public func contain(_ substrings: String...) -> Predicate<String> {
return contain(substrings)
}
public func contain(_ substrings: [String]) -> Predicate<String> {
return Predicate.simple("contain <\(arrayAsString(substrings))>") { actualExpression in
if let actual = try actualExpression.evaluate() {
let matches = substrings.allSatisfy {
let range = actual.range(of: $0)
return range != nil && !range!.isEmpty
}
return PredicateStatus(bool: matches)
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual string contains the expected substring.
public func contain(_ substrings: NSString...) -> Predicate<NSString> {
return contain(substrings)
}
public func contain(_ substrings: [NSString]) -> Predicate<NSString> {
return Predicate.simple("contain <\(arrayAsString(substrings))>") { actualExpression in
if let actual = try actualExpression.evaluate() {
let matches = substrings.allSatisfy { actual.range(of: $0.description).length != 0 }
return PredicateStatus(bool: matches)
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual collection contains the expected object.
public func contain(_ items: Any?...) -> Predicate<NMBContainer> {
return contain(items)
}
public func contain(_ items: [Any?]) -> Predicate<NMBContainer> {
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
guard let actual = try actualExpression.evaluate() else { return .fail }
let matches = items.allSatisfy { item in
return item.map { actual.contains($0) } ?? false
}
return PredicateStatus(bool: matches)
}
}
#if canImport(Darwin)
extension NMBObjCMatcher {
@objc public class func containMatcher(_ expected: [NSObject]) -> NMBMatcher {
return NMBPredicate { actualExpression in
let location = actualExpression.location
let actualValue = try actualExpression.evaluate()
if let value = actualValue as? NMBContainer {
let expr = Expression(expression: ({ value as NMBContainer }), location: location)
// A straightforward cast on the array causes this to crash, so we have to cast the individual items
let expectedOptionals: [Any?] = expected.map({ $0 as Any? })
return try contain(expectedOptionals).satisfies(expr).toObjectiveC()
} else if let value = actualValue as? NSString {
let expr = Expression(expression: ({ value as String }), location: location)
// swiftlint:disable:next force_cast
return try contain(expected as! [String]).satisfies(expr).toObjectiveC()
}
let message: ExpectationMessage
if actualValue != nil {
message = ExpectationMessage.expectedActualValueTo(
// swiftlint:disable:next line_length
"contain <\(arrayAsString(expected))> (only works for NSArrays, NSSets, NSHashTables, and NSStrings)"
)
} else {
message = ExpectationMessage
.expectedActualValueTo("contain <\(arrayAsString(expected))>")
.appendedBeNilHint()
}
return NMBPredicateResult(status: .fail, message: message.toObjectiveC())
}
}
}
#endif
| mit | f6b5c76f5dcd9b845fc6037b72896f46 | 40.443548 | 121 | 0.627943 | 5.04318 | false | false | false | false |
morisk/CalculatorKeyboard | kbCalc/UIView+DesignCorners.swift | 1 | 647 | //
// UIView+Corner.swift
// CalculatorKeyboard
//
// Created by Moris Kramer on 9/6/16.
// Copyright © 2016 CalculatorKeyboard. All rights reserved.
//
import UIKit
extension UIView {
/**
Rounding corners of this UIView by adjusting layer properties and setting
color and stroke radios ** We should move it to design protocol **
- parameter radios: radius
- parameter borderWidth: stroke width
*/
func designCorners(withRadius radius: CGFloat = 4, borderWidth: CGFloat = 1 ) {
layer.borderWidth = borderWidth
layer.borderColor = UIColor.lightGrayColor().CGColor
layer.cornerRadius = radius
clipsToBounds = true
}
}
| apache-2.0 | 7f9bd63a48a18fc2778402040d2095ea | 24.84 | 81 | 0.729102 | 3.868263 | false | false | false | false |
jonbalbarin/LibGroupMe | LibGroupMeTests/StorageTest.swift | 1 | 2642 | import LibGroupMe
import Quick
import Nimble
class StorageSpec: QuickSpec {
override func spec() {
xdescribe("the storage system") {
var storage: Storage? = nil
storage = Storage(name: "StorageSpec")
it("should store a list of groups") {
let dataDict = GroupTestHelper().groupIndex()
var groups: Array = Array<Group>()
if let groupInfos = dataDict["response"] as? NSArray {
expect(groupInfos.count).to(equal(9))
for info in groupInfos {
groups.append(Group(info: info as! NSDictionary))
}
} else {
fail()
}
var fetchedGroups: Array<Group>? = []
storage!.storeGroups(groups) {
storage!.fetchGroups({(fetched: Array<Group>?) in
fetchedGroups = fetched;
})
}
expect(fetchedGroups!.count).toEventually(equal(9))
}
it("should store a list of powerups") {
let powerups = PowerupTestHelper().powerupFixtures()
expect(powerups.count).to(beGreaterThan(1))
var fetchedPowerups: Array<Powerup>? = []
storage!.storePowerups(powerups, completion: { () -> Void in
storage!.fetchPowerups({(fetched: Array<Powerup>?) in
fetchedPowerups = fetched
})
})
expect(fetchedPowerups!.count).toEventually(equal(powerups.count))
}
it("should should store a list of DM users") {
let usersJSON = UserTestHelper().dmIndex()
var users: Array<User> = Array<User>()
if let infos = usersJSON["response"] as? NSArray {
expect(infos.count).to(equal(1))
for info in infos {
users.append(User(info: info as! NSDictionary))
}
} else {
fail()
}
expect(users.count).to(equal(1))
var fetchedUsers: Array<User>? = []
storage!.storeUsers(users, completion: { () -> Void in
storage!.fetchUsers({(fetched: Array<User>?) in
fetchedUsers = fetched
})
})
expect(fetchedUsers!.count).toEventually(equal(1))
}
}
}
}
| mit | bcceca4650127a214373dda02f07ecf8 | 39.646154 | 82 | 0.459879 | 5.380855 | false | false | false | false |
spearal/SpearalIOS | SpearalIOS/SpearalDecoderImpl.swift | 1 | 18840 | /**
* == @Spearal ==>
*
* Copyright (C) 2014 Franck WOLFF & William DRAI (http://www.spearal.io)
*
* 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.
*/
// author: Franck WOLFF
import Foundation
private class SpearalConverterContextRootImpl: SpearalConverterContextRoot {
}
private class SpearalConverterContextObjectImpl: SpearalConverterContextObject {
let type:AnyClass
private var _property:String?
var property:String {
get { return _property! }
}
init(_ type:AnyClass) {
self.type = type
}
}
private class SpearalConverterContextCollectionImpl: SpearalConverterContextCollection {
private var _index:Int?
var index:Int {
get { return _index! }
}
}
private class SpearalConverterContextMapKeyImpl: SpearalConverterContextMapKey {
}
private class SpearalConverterContextMapValueImpl: SpearalConverterContextMapValue {
private var _key:NSObject?
var key:NSObject {
get { return _key! }
}
}
class SpearalDecoderImpl: SpearalDecoder {
let context:SpearalContext
let input:SpearalInput
let printer:SpearalPrinter?
private var sharedStrings:[String]
private var sharedObjects:[Any]
private var depth:Int
private let calendar:NSCalendar
init(context:SpearalContext, input:SpearalInput, printer:SpearalPrinter? = nil) {
self.context = context
self.input = input
self.printer = printer
self.sharedStrings = [String]()
self.sharedObjects = [Any]()
self.depth = 0
self.calendar = NSCalendar(identifier:NSGregorianCalendar)!
}
func readAny() -> Any? {
var value:Any?
let parameterizedType = input.read()
++depth
if let type = SpearalType.valueOf(parameterizedType) {
switch type {
case .NULL:
value = nil
printer?.printNil()
case .TRUE:
value = true
printer?.printBoolean(true)
case .FALSE:
value = false
printer?.printBoolean(false)
case .INTEGRAL:
value = readIntegral(parameterizedType)
case .BIG_INTEGRAL:
value = readBigIntegral(parameterizedType)
case .FLOATING:
value = readFloating(parameterizedType)
case .BIG_FLOATING:
value = readBigFloating(parameterizedType)
case .STRING:
value = readString(parameterizedType)
case .BYTE_ARRAY:
value = readByteArray(parameterizedType)
case .DATE_TIME:
value = readDateTime(parameterizedType)
case .COLLECTION:
value = readCollection(parameterizedType)
case .MAP:
value = readMap(parameterizedType)
case .ENUM:
value = readEnum(parameterizedType)
case .CLASS:
value = readClass(parameterizedType)
case .BEAN:
value = readBean(parameterizedType)
}
}
if --depth == 0 {
value = context.convert(value, context: SpearalConverterContextRootImpl())
//println((printer as SpearalStringPrinter).representation)
}
return value
}
func readIntegral(parameterizedType:UInt8) -> Int {
let length0 = (parameterizedType & 0x07)
var value:Int = 0
switch length0 {
case 7:
value |= (Int(input.read()) << 56)
value |= (Int(input.read()) << 48)
value |= (Int(input.read()) << 40)
value |= (Int(input.read()) << 32)
value |= (Int(input.read()) << 24)
value |= (Int(input.read()) << 16)
value |= (Int(input.read()) << 8)
case 6:
value |= (Int(input.read()) << 48)
value |= (Int(input.read()) << 40)
value |= (Int(input.read()) << 32)
value |= (Int(input.read()) << 24)
value |= (Int(input.read()) << 16)
value |= (Int(input.read()) << 8)
case 5:
value |= (Int(input.read()) << 40)
value |= (Int(input.read()) << 32)
value |= (Int(input.read()) << 24)
value |= (Int(input.read()) << 16)
value |= (Int(input.read()) << 8)
case 4:
value |= (Int(input.read()) << 32)
value |= (Int(input.read()) << 24)
value |= (Int(input.read()) << 16)
value |= (Int(input.read()) << 8)
case 3:
value |= (Int(input.read()) << 24)
value |= (Int(input.read()) << 16)
value |= (Int(input.read()) << 8)
case 2:
value |= (Int(input.read()) << 16)
value |= (Int(input.read()) << 8)
case 1:
value |= (Int(input.read()) << 8)
default:
break
}
value |= Int(input.read())
if (parameterizedType & 0x08) != 0 {
value = -value;
}
printer?.printIntegral(value)
return value
}
func readBigIntegral(parameterizedType:UInt8) -> SpearalBigIntegral {
let indexOrLength = readIndexOrLength(parameterizedType)
var value:SpearalBigIntegral
if SpearalDecoderImpl.isStringReference(parameterizedType) {
value = SpearalBigIntegral(sharedStrings[indexOrLength])
}
else {
value = SpearalBigIntegral(readBigNumberData(indexOrLength))
}
printer?.printBigIntegral(value.representation)
return value
}
func readFloating(parameterizedType:UInt8) -> Double {
var value:Double = Double.NaN
if (parameterizedType & 0x08) != 0 {
let length0 = (parameterizedType & 0x03)
var intValue:Int = readUnsignedIntegerValue(length0)
if (parameterizedType & 0x04) != 0 {
intValue = -intValue
}
value = Double(intValue) / 1000.0
}
else {
let pointer = doubleToUInt8MutablePointer(&value)
pointer[7] = input.read()
pointer[6] = input.read()
pointer[5] = input.read()
pointer[4] = input.read()
pointer[3] = input.read()
pointer[2] = input.read()
pointer[1] = input.read()
pointer[0] = input.read()
}
printer?.printFloating(value)
return value
}
func readBigFloating(parameterizedType:UInt8) -> SpearalBigFloating {
let indexOrLength = readIndexOrLength(parameterizedType)
var value:SpearalBigFloating
if SpearalDecoderImpl.isStringReference(parameterizedType) {
value = SpearalBigFloating(sharedStrings[indexOrLength])
}
else {
value = SpearalBigFloating(readBigNumberData(indexOrLength))
}
printer?.printBigFloating(value.representation)
return value
}
func readString(parameterizedType:UInt8) -> String {
let value = readStringData(parameterizedType)
printer?.printString(value)
return value
}
func readByteArray(parameterizedType:UInt8) -> [UInt8] {
let indexOrLength = readIndexOrLength(parameterizedType)
var value:[UInt8]
if SpearalDecoderImpl.isObjectReference(parameterizedType) {
printer?.printByteArrayReference(indexOrLength)
value = sharedObjects[indexOrLength] as [UInt8]
}
else {
value = input.read(indexOrLength)
printer?.printByteArray(value, referenceIndex: sharedObjects.count)
sharedObjects.append(value)
}
return value
}
func readDateTime(parameterizedType:UInt8) -> NSDate {
var components = NSDateComponents()
if (parameterizedType & 0x08) != 0 {
let month = input.read()
components.month = Int(month & 0x0f)
components.day = Int(input.read())
components.year = readUnsignedIntegerValue((month >> 4) & 0x03)
if (month & 0x80) != 0 {
components.year = -components.year
}
components.year += 2000
}
if (parameterizedType & 0x04) != 0 {
let hours = input.read()
components.hour = Int(hours & 0x1f)
components.minute = Int(input.read())
components.second = Int(input.read())
let subsecondsType = (parameterizedType & 0x03)
if subsecondsType != 0 {
components.nanosecond = readUnsignedIntegerValue(hours >> 5)
if subsecondsType == 2 {
components.nanosecond *= 1000;
}
else if subsecondsType == 3 {
components.nanosecond *= 1000000;
}
}
}
let value = calendar.dateFromComponents(components)!
printer?.printDateTime(value)
return value
}
func readCollection(parameterizedType:UInt8) -> [AnyObject] {
let indexOrLength = readIndexOrLength(parameterizedType)
if SpearalDecoderImpl.isObjectReference(parameterizedType) {
printer?.printCollectionReference(indexOrLength)
return sharedObjects[indexOrLength] as [AnyObject]
}
let null = NSNull()
var collection = [AnyObject](count: indexOrLength, repeatedValue: null)
printer?.printStartCollection(sharedObjects.count)
sharedObjects.append(collection)
let converterContext = SpearalConverterContextCollectionImpl()
let max = (indexOrLength - 1)
for i in 0...max {
converterContext._index = i
let value = context.convert(readAny(), context: converterContext)
collection[i] = value as? NSObject ?? null
}
printer?.printEndCollection()
return collection
}
func readMap(parameterizedType:UInt8) -> [NSObject: AnyObject] {
let indexOrLength = readIndexOrLength(parameterizedType)
if SpearalDecoderImpl.isObjectReference(parameterizedType) {
printer?.printMapReference(indexOrLength)
return sharedObjects[indexOrLength] as [NSObject: AnyObject]
}
let null = NSNull()
var map = [NSObject: AnyObject](minimumCapacity: indexOrLength)
printer?.printStartMap(sharedObjects.count)
sharedObjects.append(map)
let converterKeyContext = SpearalConverterContextMapKeyImpl()
let converterValueContext = SpearalConverterContextMapValueImpl()
let max = (indexOrLength - 1)
for i in 0...max {
let key:NSObject = context.convert(readAny(), context: converterKeyContext) as? NSObject ?? null
converterValueContext._key = key
let val:NSObject = context.convert(readAny(), context: converterValueContext) as? NSObject ?? null
map[key] = val
}
printer?.printEndMap()
return map
}
func readEnum(parameterizedType:UInt8) -> SpearalEnum {
let remoteClassName = readStringData(parameterizedType)
let valueName = readString(input.read())
printer?.printEnum(remoteClassName, valueName: valueName)
let localClassName = context.getAliasStrategy()?.remoteToLocalClassName(remoteClassName) ?? remoteClassName
return SpearalEnum(localClassName, valueName: valueName)
}
func readClass(parameterizedType:UInt8) -> AnyClass? {
let name = readStringData(parameterizedType)
printer?.printClass(name)
return context.getIntrospector()!.classForName(name)
}
func readBean(parameterizedType:UInt8) -> Any {
let indexOrLength = readIndexOrLength(parameterizedType)
if SpearalDecoderImpl.isObjectReference(parameterizedType) {
printer?.printBeanReference(indexOrLength)
return sharedObjects[indexOrLength]
}
let description = readStringData(parameterizedType, indexOrLength: indexOrLength)
let (remoteClassName, localClassName, remotePropertyNames, localPropertyNames) = parseDescription(description)
printer?.printStartBean(remoteClassName, referenceIndex: sharedObjects.count)
if let cls = NSClassFromString(localClassName) as? NSObject.Type {
let instance = cls()
sharedObjects.append(instance as NSObject as Any)
let converterContext = SpearalConverterContextObjectImpl(cls)
let properties = context.getIntrospector()!.introspect(cls).properties
for (i, localPropertyName) in enumerate(localPropertyNames) {
printer?.printBeanProperty(remotePropertyNames[i])
let any = readAny()
if contains(properties, localPropertyName) {
converterContext._property = localPropertyName
let value:AnyObject? = context.convert(any, context: converterContext) as? NSObject as AnyObject?
instance.setValue(value, forKey: localPropertyName)
}
}
printer?.printEndBean()
return instance
}
let instance = SpearalUnsupportedClassInstance(localClassName)
sharedObjects.append(instance)
for remotePropertyName in remotePropertyNames {
printer?.printBeanProperty(remotePropertyName)
instance.properties[remotePropertyName] = readAny() as? NSObject as AnyObject?
}
printer?.printEndBean()
return instance
}
private func parseDescription(description:String) -> (String, String, [String], [String]) {
let aliasStrategy = context.getAliasStrategy()
let classNamePropertyNames = description.componentsSeparatedByString("#")
let remoteClassName = classNamePropertyNames[0]
let localClassName = aliasStrategy?.remoteToLocalClassName(remoteClassName) ?? remoteClassName
if classNamePropertyNames.count == 1 || classNamePropertyNames[1].isEmpty {
return (remoteClassName, localClassName, [], [])
}
let remotePropertyNames = classNamePropertyNames[1].componentsSeparatedByString(",").filter({
(elt:String) -> Bool in return !elt.isEmpty
})
if remotePropertyNames.isEmpty {
return (remoteClassName, localClassName, [], [])
}
let aliases = aliasStrategy?.remoteToLocalProperties(localClassName) ?? [String: String]()
let localPropertyNames:[String] = aliases.isEmpty ? remotePropertyNames : (
remotePropertyNames.map { (remotePropertyName) -> String in
return aliases[remotePropertyName] ?? remotePropertyName
}
)
return (remoteClassName, localClassName, remotePropertyNames, localPropertyNames)
}
private func readStringData(parameterizedType:UInt8) -> String {
let indexOrLength = readIndexOrLength(parameterizedType)
return readStringData(parameterizedType, indexOrLength: indexOrLength)
}
private func readStringData(parameterizedType:UInt8, indexOrLength:Int) -> String {
if SpearalDecoderImpl.isStringReference(parameterizedType) {
return sharedStrings[indexOrLength]
}
if indexOrLength == 0 {
return ""
}
let utf8:[UInt8] = input.read(indexOrLength)
let value = NSString(bytes: utf8, length: utf8.count, encoding: NSUTF8StringEncoding) as String
sharedStrings.append(value)
return value
}
private func doubleToUInt8MutablePointer(pointer:UnsafeMutablePointer<Double>) -> UnsafeMutablePointer<UInt8> {
return UnsafeMutablePointer<UInt8>(pointer)
}
private func readIndexOrLength(parameterizedType:UInt8) -> Int {
let length0 = (parameterizedType & 0x03);
return readUnsignedIntegerValue(length0);
}
private func readUnsignedIntegerValue(length0:UInt8) -> Int {
var value:Int = 0
switch length0 {
case 3:
value |= (Int(input.read()) << 24)
value |= (Int(input.read()) << 16)
value |= (Int(input.read()) << 8)
case 2:
value |= (Int(input.read()) << 16)
value |= (Int(input.read()) << 8)
case 1:
value |= (Int(input.read()) << 8)
default:
break
}
value |= Int(input.read())
return value
}
private class func isObjectReference(parameterizedType:UInt8) -> Bool {
return ((parameterizedType & 0x08) != 0)
}
private class func isStringReference(parameterizedType:UInt8) -> Bool {
return ((parameterizedType & 0x04) != 0)
}
private func readBigNumberData(length:Int) -> String {
let count = (length / 2) + (length % 2)
var chars = [UInt8](count: length, repeatedValue: 0)
var iChar = 0
for i in 0...count {
var b = input.read()
chars[iChar++] = BIG_NUMBER_ALPHA[Int((b & 0xf0) >> 4)]
if iChar == length {
break
}
chars[iChar++] = BIG_NUMBER_ALPHA[Int(b & 0x0f)]
}
let value = NSString(bytes: chars, length: chars.count, encoding: NSUTF8StringEncoding) as String
sharedStrings.append(value)
return value
}
} | apache-2.0 | 3cc7797e522704f3bd20e3d18dad63cd | 32.947748 | 118 | 0.577017 | 4.861935 | false | false | false | false |
tatsuyamoriguchi/PoliPoli | View Controller/TodaysTasksTableViewController.swift | 1 | 16454 | //
// TodaysTasksTableViewController.swift
// Poli
//
// Created by Tatsuya Moriguchi on 8/16/18.
// Copyright © 2018 Becko's Inc. All rights reserved.
//
import UIKit
import CoreData
class TodaysTasksTableViewController: UITableViewController {
var context: NSManagedObjectContext!
var tasks = [Task]()
var selectedGoal: Goal?
var userName: String = ""
@objc func getInfoAction() {
let NSL_shareAlert = NSLocalizedString("NSL_shareAlert", value: "To share with Facebook, LinkedIn or app that doens't show your Today's To-Do", comment: "")
let NSL_shareMessage = NSLocalizedString("NSL_shareMessage", value: "Please use 'Copy' first, then tap share button again and paste copied your Today's To-Do(s) to Facebook or LinkedIn Share screen view.", comment: "")
AlertNotification().alert(title: NSL_shareAlert, message: NSL_shareMessage, sender: self)
}
@objc func addTapped() {
var image: UIImage
var message: String
var url: URL
image = UIImage(named: "PoliRoundIcon")!
let NSL_postMessage = NSLocalizedString("NSL_postMessage", value: "I will complete the following task(s) today :", comment: "")
message = NSL_postMessage
url = URL(string: "http://beckos.com/?p=1044")!
var previousGoalTitle: String = ""
for task in tasks {
let goalTitle = task.goalAssigned?.goalTitle
let toDo = task.toDo
if goalTitle != previousGoalTitle {
message.append("\n\nGoal: \(goalTitle ?? "ERROR NO GOALTITLE")\n- To Do: \(toDo ?? "ERROR NO TODO") ")
previousGoalTitle = goalTitle!
} else {
message.append("\n- To Do: \(toDo ?? "ERROR NO TODO") ")
}
}
//let activityItems = [message, url] as [Any]
// Not using UIActivityItemSource
// If with url, Facebook, Facebook Messenger and LinkedIn recognize url only, not message or image
// Mail, Message, Reminders, NotesTwitter, Messenger, LINE, Snapchat, Facebook(url only), LinkedIn(url only)
// With only message and image, LinkedIn still returns an error, but message was posted successfully.
// let activityItems = [ActivityItemSource(message: message, image: image, url: url)]
let activityItems = [ActivityItemSource(message: message), ActivityItemSourceImage(image: image), ActivityItemSourceURL(url: url)]
let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
activityVC.excludedActivityTypes = [
UIActivity.ActivityType.assignToContact,
UIActivity.ActivityType.print,
UIActivity.ActivityType.addToReadingList,
UIActivity.ActivityType.markupAsPDF,
UIActivity.ActivityType.saveToCameraRoll,
UIActivity.ActivityType.openInIBooks,
//UIActivity.ActivityType(rawValue: "com.snapchat.Share")
//UIActivity.ActivityType(rawValue: "com.apple.reminders.RemindersEditorExtension"),
//UIActivity.ActivityType(rawValue: "com.apple.mobilenotes.SharingExtension"),
]
activityVC.popoverPresentationController?.sourceView = self.view
self.present(activityVC, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
//let NSL_taskList = NSLocalizedString("NSL_taskList", value: "Task List", comment: "")
//self.navigationItem.prompt = NSL_taskList
if UserDefaults.standard.bool(forKey: "isLoggedIn") == true {
userName = UserDefaults.standard.string(forKey: "userName")!
//let NSL_loginUsername = NSLocalizedString("NSL_loginUsername", value: "Login as \(userName)", comment: "")
let NSL_loginUsername = String(format: NSLocalizedString("NSL_loginUsername", value: "Login as %@", comment: ""), userName)
//let LoginNameText = "Login as %@"
//let NSL_loginUsername = String(format: NSLocalizedString("LoginNameText", comment: ""), userName)
self.navigationItem.prompt = NSL_loginUsername
}else {
let NSL_loginError = NSLocalizedString("NSL_loginError", value: "Login Error", comment: "")
self.navigationItem.prompt = NSL_loginError
}
let NSL_naviToday = NSLocalizedString("NSL_naviToday", value: "Today's Tasks To-Do", comment: "")
self.navigationItem.title = NSL_naviToday
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
// Fetch the data from Core Data
fetchData()
// Reload the table view
tableView.reloadData()
// Display a share button, if any tasks item. If no tasks, segue back to root view
if tasks.count > 0 {
let share = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(addTapped))
// Create the info button
let infoButton = UIButton(type: .infoLight)
// You will need to configure the target action for the button itself, not the bar button itemr
infoButton.addTarget(self, action: #selector(getInfoAction), for: .touchUpInside)
// Create a bar button item using the info button as its custom view
let info = UIBarButtonItem(customView: infoButton)
navigationItem.rightBarButtonItems = [share, info]
} else {
let NSL_noTodaysTask = NSLocalizedString("NSL_noTodaysTask", value: "No Today's Task now.", comment: "")
let noTodaysTaskAlert = UIAlertController(title: "Aelrt", message: NSL_noTodaysTask, preferredStyle: .alert)
self.present(noTodaysTaskAlert, animated: true, completion: nil)
// Hide rightBarButtonItem
navigationItem.rightBarButtonItem = nil
// Display congratAlert view for x seconds
let when = DispatchTime.now() + 2
DispatchQueue.main.asyncAfter(deadline: when, execute: {
noTodaysTaskAlert.dismiss(animated: true, completion: nil)
})
//navigationController!.popToRootViewController(animated: true)
}
}
func fetchData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest = NSFetchRequest<Task>(entityName: "Task")
//var taskDate = Task.date
var calendar = Calendar.current
calendar.timeZone = NSTimeZone.local
let dateFrom = calendar.startOfDay(for: Date())
let dateTo = calendar.date(byAdding: .day, value: 1, to: dateFrom)
// let todayPredicate = NSPredicate(format: "date >= %@ AND date < %@", dateFrom as CVarArg, dateTo! as CVarArg)
let todayPredicate = NSPredicate(format: "date < %@", dateTo! as CVarArg)
let donePredicate = NSPredicate(format: "isDone == %@", NSNumber(value: false))
let andPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: [todayPredicate, donePredicate])
fetchRequest.predicate = andPredicate
// Declare sort descriptor
let sortByGoalAssigned = NSSortDescriptor(key: #keyPath(Task.goalAssigned), ascending: true)
let sortByToDo = NSSortDescriptor(key: #keyPath(Task.toDo), ascending: true)
// let sortByDone = NSSortDescriptor(key: #keyPath(Task.isDone), ascending: true)
let sortByDate = NSSortDescriptor(key: #keyPath(Task.date), ascending: true)
// Sort fetchRequest array data
fetchRequest.sortDescriptors = [sortByGoalAssigned, sortByDate, sortByToDo]
do {
tasks = try context.fetch(fetchRequest)
} catch {
print(error.localizedDescription)
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return tasks.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
// Configure the cell...
let task = tasks[indexPath.row]
cell.textLabel?.text = task.toDo
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
let dateString = dateFormatter.string(from: (task.date)! as Date)
if let goalTitle = task.goalAssigned?.goalTitle {
cell.detailTextLabel?.text = "\(dateString) : \(goalTitle)"
}else{
cell.detailTextLabel?.text = dateString
}
let today = Date()
let evaluate = NSCalendar.current.compare(task.date! as Date, to: today, toGranularity: .day)
switch evaluate {
// If task date is today, display it in purple
case ComparisonResult.orderedSame :
cell.detailTextLabel?.textColor = .purple
// If task date passed today, display it in red
case ComparisonResult.orderedAscending :
cell.detailTextLabel?.textColor = .red
default:
cell.detailTextLabel?.textColor = .black
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "toTaskList", sender: self)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toTaskList" {
if let vc = segue.destination as? TaskTableViewController {
let indexPath = self.tableView.indexPathForSelectedRow
selectedGoal = tasks[(indexPath?.row)!].goalAssigned //goals[(indexPath?.row)!]
vc.selectedGoal = selectedGoal
}
}
}
}
class ActivityItemSource: NSObject, UIActivityItemSource {
var message: String!
init(message: String) {
self.message = message
}
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return message
// to display Instagram button, return image
// image: Mail, Message, Notes, Twitter, Instagram, Shared Album, Post to Google Maps, Messenger, LINE, Snapchat, Facebook
// message: Mail, Message, Notes, Twitter, Messenger, LINE, Facebook, LinkedIn
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
switch activityType {
case UIActivity.ActivityType.postToFacebook:
return nil
case UIActivity.ActivityType.postToTwitter:
message = "#Poli #ToDoToday " + message
return message
case UIActivity.ActivityType.mail:
return message
case UIActivity.ActivityType.copyToPasteboard:
return message
case UIActivity.ActivityType.markupAsPDF:
return message
case UIActivity.ActivityType.message:
return message
case UIActivity.ActivityType.postToFlickr:
return message
case UIActivity.ActivityType.postToTencentWeibo:
return message
case UIActivity.ActivityType.postToVimeo:
return message
case UIActivity.ActivityType.print:
return message
case UIActivity.ActivityType(rawValue: "com.apple.reminders.RemindersEditorExtension"):
return message
case UIActivity.ActivityType(rawValue: "com.apple.mobilenotes.SharingExtension"):
return message
case UIActivity.ActivityType(rawValue: "com.burbn.instagram.shareextension"):
return nil
case UIActivity.ActivityType(rawValue: "jp.naver.line.Share"):
return message
default:
return message
}
}
}
class ActivityItemSourceImage: NSObject, UIActivityItemSource {
var image: UIImage!
init(image: UIImage) {
self.image = UIImage(named: "PoliRoundIcon")!
}
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return image
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
switch activityType {
case UIActivity.ActivityType.postToFacebook:
return nil
case UIActivity.ActivityType.postToTwitter:
return nil
case UIActivity.ActivityType.mail:
return image
case UIActivity.ActivityType.copyToPasteboard:
return image
case UIActivity.ActivityType.markupAsPDF:
return image
case UIActivity.ActivityType.message:
return image
case UIActivity.ActivityType.postToFlickr:
return image
case UIActivity.ActivityType.postToTencentWeibo:
return image
case UIActivity.ActivityType.postToVimeo:
return image
case UIActivity.ActivityType.print:
return image
case UIActivity.ActivityType(rawValue: "com.apple.reminders.RemindersEditorExtension"):
return nil
case UIActivity.ActivityType(rawValue: "com.apple.mobilenotes.SharingExtension"):
return nil
case UIActivity.ActivityType(rawValue: "com.burbn.instagram.shareextension"):
return image
case UIActivity.ActivityType(rawValue: "jp.naver.line.Share"):
return image
default:
return image
}
}
}
class ActivityItemSourceURL: NSObject, UIActivityItemSource {
var url: URL!
init(url: URL) {
self.url = url
}
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return url
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
switch activityType {
case UIActivity.ActivityType.postToFacebook:
return url
case UIActivity.ActivityType.postToTwitter:
return url
case UIActivity.ActivityType.mail:
return url
case UIActivity.ActivityType.copyToPasteboard:
return nil
case UIActivity.ActivityType.message:
return url
case UIActivity.ActivityType.postToFlickr:
return url
case UIActivity.ActivityType.postToTencentWeibo:
return url
case UIActivity.ActivityType.postToVimeo:
return url
case UIActivity.ActivityType.print:
return url
case UIActivity.ActivityType(rawValue: "com.apple.reminders.RemindersEditorExtension"):
return url
case UIActivity.ActivityType(rawValue: "com.apple.mobilenotes.SharingExtension"):
return url
case UIActivity.ActivityType(rawValue: "com.burbn.instagram.shareextension"):
return nil
case UIActivity.ActivityType(rawValue: "jp.naver.line.Share"):
return url
//case UIActivity.ActivityType(rawValue: "com.snapchat.Share"):
// return nil
default:
return url
}
}
}
| gpl-3.0 | 8c9e9db4b3913957b95db35776265a38 | 37.531616 | 226 | 0.630341 | 5.40151 | false | false | false | false |
DRybochkin/Spika.swift | Spika/Cells/UserInfoCell/CSUserInfoTableViewCell.swift | 1 | 1823 | //
// UserInfoTableViewCell.h
// Prototype
//
// Created by Dmitry Rybochkin on 25.02.17.
// Copyright (c) 2015 Clover Studio. All rights reserved.
//
import UIKit
class CSUserInfoTableViewCell: CSBaseTableViewCell {
@IBOutlet weak var userInfoMessage: UILabel!
@IBOutlet weak var parentView: UIView!
@IBOutlet weak var userInfoBackground: UIView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var dateConstraint: NSLayoutConstraint!
override var message: CSMessageModel! {
didSet {
userInfoMessage.numberOfLines = 0
userInfoMessage.textColor = kAppInfoUserMessageColor(1)
let dateCreated: String = message.created != nil ? message.created.toString(format: "dd/MM/yyyy HH:mm:ss") : ""
var textMessage: String = ""
if (message.messageType == KAppMessageType.NewUser) {
textMessage = String(format: "%@\n%@ joined to conversation.", dateCreated, message.user.name)
} else if (message.messageType == KAppMessageType.LeaveUser) {
textMessage = String(format: "%@\n%@ left conversation.", dateCreated, message.user.name)
}
userInfoMessage.text = textMessage
if (isShouldShowDate) {
dateLabel.text = message.created != nil ? message.created.toString(format: "d MMMM yyyy") : ""
dateConstraint.constant = 20.0
} else {
dateLabel.text = ""
dateConstraint.constant = 0.0
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 1abc945b0d97d596bea3dc85b73ce02e | 36.204082 | 123 | 0.622052 | 4.686375 | false | false | false | false |
nguyenantinhbk77/practice-swift | CoreData/Relationships in CoreData/Relationships in CoreData/AppDelegate.swift | 2 | 6169 | //
// AppDelegate.swift
// Relationships in CoreData
//
// Created by Domenico Solazzo on 17/05/15.
// License MIT
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.domenicosolazzo.swift.Relationships_in_CoreData" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Relationships_in_CoreData", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Relationships_in_CoreData.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 7ac0bdee14af1a238082b8070fce30d8 | 54.576577 | 290 | 0.71762 | 5.770814 | false | false | false | false |
LoopKit/LoopKit | MockKitUI/View Controllers/MockPumpManagerSettingsViewController.swift | 1 | 29133 | //
// MockPumpManagerSettingsViewController.swift
// LoopKitUI
//
// Created by Michael Pangburn on 11/20/18.
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import UIKit
import HealthKit
import LoopKit
import LoopKitUI
import MockKit
import SwiftUI
final class MockPumpManagerSettingsViewController: UITableViewController {
let pumpManager: MockPumpManager
let supportedInsulinTypes: [InsulinType]
init(pumpManager: MockPumpManager, supportedInsulinTypes: [InsulinType]) {
self.pumpManager = pumpManager
self.supportedInsulinTypes = supportedInsulinTypes
super.init(style: .grouped)
title = NSLocalizedString("Pump Settings", comment: "Title for Pump simulator settings")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private let quantityFormatter = QuantityFormatter()
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44
tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 55
tableView.register(DateAndDurationTableViewCell.nib(), forCellReuseIdentifier: DateAndDurationTableViewCell.className)
tableView.register(SegmentedControlTableViewCell.self, forCellReuseIdentifier: SegmentedControlTableViewCell.className)
tableView.register(SettingsTableViewCell.self, forCellReuseIdentifier: SettingsTableViewCell.className)
tableView.register(BoundSwitchTableViewCell.self, forCellReuseIdentifier: BoundSwitchTableViewCell.className)
tableView.register(TextButtonTableViewCell.self, forCellReuseIdentifier: TextButtonTableViewCell.className)
tableView.register(SuspendResumeTableViewCell.self, forCellReuseIdentifier: SuspendResumeTableViewCell.className)
pumpManager.addStatusObserver(self, queue: .main)
let button = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneTapped(_:)))
self.navigationItem.setRightBarButton(button, animated: false)
}
@objc func doneTapped(_ sender: Any) {
done()
}
private func done() {
if let nav = navigationController as? SettingsNavigationViewController {
nav.notifyComplete()
}
}
// MARK: - Data Source
private enum Section: Int, CaseIterable {
case basalRate = 0
case actions
case settings
case statusProgress
case deletePump
}
private enum ActionRow: Int, CaseIterable {
case suspendResume = 0
case occlusion
case pumpError
}
private enum SettingsRow: Int, CaseIterable {
case deliverableIncrements = 0
case supportedBasalRates
case supportedBolusVolumes
case insulinType
case reservoirRemaining
case batteryRemaining
case tempBasalErrorToggle
case bolusErrorToggle
case bolusCancelErrorToggle
case suspendErrorToggle
case resumeErrorToggle
case uncertainDeliveryErrorToggle
case lastReconciliationDate
}
private enum StatusProgressRow: Int, CaseIterable {
case percentComplete
case warningThreshold
case criticalThreshold
}
// MARK: UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return Section.allCases.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Section(rawValue: section)! {
case .basalRate:
return 1
case .actions:
return ActionRow.allCases.count
case .settings:
return SettingsRow.allCases.count
case .statusProgress:
return StatusProgressRow.allCases.count
case .deletePump:
return 1
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch Section(rawValue: section)! {
case .basalRate:
return nil
case .actions:
return nil
case .settings:
return "Configuration"
case .statusProgress:
return "Status Progress"
case .deletePump:
return " " // Use an empty string for more dramatic spacing
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch Section(rawValue: indexPath.section)! {
case .basalRate:
let cell = tableView.dequeueReusableCell(withIdentifier: SettingsTableViewCell.className, for: indexPath)
cell.textLabel?.text = "Current Basal Rate"
if let currentBasalRate = pumpManager.currentBasalRate {
cell.detailTextLabel?.text = quantityFormatter.string(from: currentBasalRate, for: HKUnit.internationalUnit().unitDivided(by: .hour()))
} else {
cell.detailTextLabel?.text = "—"
}
cell.isUserInteractionEnabled = false
return cell
case .actions:
switch ActionRow(rawValue: indexPath.row)! {
case .suspendResume:
let cell = tableView.dequeueReusableCell(withIdentifier: SuspendResumeTableViewCell.className, for: indexPath) as! SuspendResumeTableViewCell
cell.basalDeliveryState = pumpManager.status.basalDeliveryState
return cell
case .occlusion:
let cell = tableView.dequeueReusableCell(withIdentifier: TextButtonTableViewCell.className, for: indexPath) as! TextButtonTableViewCell
if pumpManager.state.occlusionDetected {
cell.textLabel?.text = "Resolve Occlusion"
} else {
cell.textLabel?.text = "Detect Occlusion"
}
return cell
case .pumpError:
let cell = tableView.dequeueReusableCell(withIdentifier: TextButtonTableViewCell.className, for: indexPath) as! TextButtonTableViewCell
if pumpManager.state.pumpErrorDetected {
cell.textLabel?.text = "Resolve Pump Error"
} else {
cell.textLabel?.text = "Cause Pump Error"
}
return cell
}
case .settings:
switch SettingsRow(rawValue: indexPath.row)! {
case .deliverableIncrements:
let cell = tableView.dequeueReusableCell(withIdentifier: SegmentedControlTableViewCell.className, for: indexPath) as! SegmentedControlTableViewCell
let possibleDeliverableIncrements = MockPumpManagerState.DeliverableIncrements.allCases
cell.textLabel?.text = "Increments"
cell.options = possibleDeliverableIncrements.map { increments in
switch increments {
case .omnipod:
return "Pod"
case .medtronicX22:
return "x22"
case .medtronicX23:
return "x23"
case .custom:
return "Custom"
}
}
cell.segmentedControl.selectedSegmentIndex = possibleDeliverableIncrements.firstIndex(of: pumpManager.state.deliverableIncrements)!
cell.onSelection { [pumpManager] index in
pumpManager.state.deliverableIncrements = possibleDeliverableIncrements[index]
tableView.reloadRows(at: [IndexPath(row: SettingsRow.supportedBasalRates.rawValue, section: Section.settings.rawValue), IndexPath(row: SettingsRow.supportedBolusVolumes.rawValue, section: Section.settings.rawValue)], with: .automatic)
}
return cell
case .supportedBasalRates:
let cell = tableView.dequeueReusableCell(withIdentifier: SettingsTableViewCell.className, for: indexPath)
cell.textLabel?.text = "Basal Rates"
cell.detailTextLabel?.text = pumpManager.state.supportedBasalRatesDescription
if pumpManager.state.deliverableIncrements == .custom {
cell.accessoryType = .disclosureIndicator
}
return cell
case .supportedBolusVolumes:
let cell = tableView.dequeueReusableCell(withIdentifier: SettingsTableViewCell.className, for: indexPath)
cell.textLabel?.text = "Bolus Volumes"
cell.detailTextLabel?.text = pumpManager.state.supportedBolusVolumesDescription
if pumpManager.state.deliverableIncrements == .custom {
cell.accessoryType = .disclosureIndicator
}
return cell
case .insulinType:
let cell = tableView.dequeueReusableCell(withIdentifier: SettingsTableViewCell.className, for: indexPath)
cell.prepareForReuse()
cell.textLabel?.text = "Insulin Type"
cell.detailTextLabel?.text = pumpManager.state.insulinType?.brandName ?? "Unset"
cell.accessoryType = .disclosureIndicator
return cell
case .reservoirRemaining:
let cell = tableView.dequeueReusableCell(withIdentifier: SettingsTableViewCell.className, for: indexPath)
cell.textLabel?.text = "Reservoir Remaining"
cell.detailTextLabel?.text = quantityFormatter.string(from: HKQuantity(unit: .internationalUnit(), doubleValue: pumpManager.state.reservoirUnitsRemaining), for: .internationalUnit())
cell.accessoryType = .disclosureIndicator
return cell
case .batteryRemaining:
let cell = tableView.dequeueReusableCell(withIdentifier: SettingsTableViewCell.className, for: indexPath)
cell.textLabel?.text = "Battery Remaining"
if let remainingCharge = pumpManager.status.pumpBatteryChargeRemaining {
cell.detailTextLabel?.text = "\(Int(round(remainingCharge * 100)))%"
} else {
cell.detailTextLabel?.text = SettingsTableViewCell.NoValueString
}
cell.accessoryType = .disclosureIndicator
return cell
case .tempBasalErrorToggle:
return switchTableViewCell(for: indexPath, titled: "Error on Temp Basal", boundTo: \.tempBasalEnactmentShouldError)
case .bolusErrorToggle:
return switchTableViewCell(for: indexPath, titled: "Error on Bolus", boundTo: \.bolusEnactmentShouldError)
case .bolusCancelErrorToggle:
return switchTableViewCell(for: indexPath, titled: "Error on Cancel Bolus", boundTo: \.bolusCancelShouldError)
case .suspendErrorToggle:
return switchTableViewCell(for: indexPath, titled: "Error on Suspend", boundTo: \.deliverySuspensionShouldError)
case .resumeErrorToggle:
return switchTableViewCell(for: indexPath, titled: "Error on Resume", boundTo: \.deliveryResumptionShouldError)
case .uncertainDeliveryErrorToggle:
return switchTableViewCell(for: indexPath, titled: "Next Delivery Command Uncertain", boundTo: \.deliveryCommandsShouldTriggerUncertainDelivery)
case .lastReconciliationDate:
let cell = tableView.dequeueReusableCell(withIdentifier: DateAndDurationTableViewCell.className, for: indexPath) as! DateAndDurationTableViewCell
cell.titleLabel.text = "Last Reconciliation Date"
cell.date = pumpManager.lastSync ?? Date()
cell.datePicker.maximumDate = Date()
cell.datePicker.minimumDate = Date() - .hours(48)
cell.datePicker.datePickerMode = .dateAndTime
#if swift(>=5.2)
if #available(iOS 14.0, *) {
cell.datePicker.preferredDatePickerStyle = .wheels
}
#endif
cell.datePicker.isEnabled = true
cell.delegate = self
return cell
}
case .statusProgress:
let cell = tableView.dequeueReusableCell(withIdentifier: SettingsTableViewCell.className, for: indexPath)
switch StatusProgressRow(rawValue: indexPath.row)! {
case .percentComplete:
cell.textLabel?.text = "Percent Completed"
if let percentCompleted = pumpManager.state.progressPercentComplete {
cell.detailTextLabel?.text = "\(Int(round(percentCompleted * 100)))%"
} else {
cell.detailTextLabel?.text = SettingsTableViewCell.NoValueString
}
case .warningThreshold:
cell.textLabel?.text = "Warning Threshold"
if let warningThreshold = pumpManager.state.progressWarningThresholdPercentValue {
cell.detailTextLabel?.text = "\(Int(round(warningThreshold * 100)))%"
} else {
cell.detailTextLabel?.text = SettingsTableViewCell.NoValueString
}
case .criticalThreshold:
cell.textLabel?.text = "Critical Threshold"
if let criticalThreshold = pumpManager.state.progressCriticalThresholdPercentValue {
cell.detailTextLabel?.text = "\(Int(round(criticalThreshold * 100)))%"
} else {
cell.detailTextLabel?.text = SettingsTableViewCell.NoValueString
}
}
cell.accessoryType = .disclosureIndicator
return cell
case .deletePump:
let cell = tableView.dequeueReusableCell(withIdentifier: TextButtonTableViewCell.className, for: indexPath) as! TextButtonTableViewCell
cell.textLabel?.text = "Delete Pump"
cell.textLabel?.textAlignment = .center
cell.tintColor = .delete
cell.isEnabled = true
return cell
}
}
private func switchTableViewCell(for indexPath: IndexPath, titled title: String, boundTo keyPath: WritableKeyPath<MockPumpManagerState, Bool>) -> SwitchTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: BoundSwitchTableViewCell.className, for: indexPath) as! BoundSwitchTableViewCell
cell.textLabel?.text = title
cell.switch?.isOn = pumpManager.state[keyPath: keyPath]
cell.onToggle = { [unowned pumpManager] isOn in
pumpManager.state[keyPath: keyPath] = isOn
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let sender = tableView.cellForRow(at: indexPath)
switch Section(rawValue: indexPath.section)! {
case .actions:
switch ActionRow(rawValue: indexPath.row)! {
case .suspendResume:
if let suspendResumeCell = sender as? SuspendResumeTableViewCell {
suspendResumeCellTapped(suspendResumeCell)
}
tableView.deselectRow(at: indexPath, animated: true)
case .occlusion:
pumpManager.injectPumpEvents(pumpManager.state.occlusionDetected ? [NewPumpEvent(alarmClearAt: Date())] : [NewPumpEvent(alarmAt: Date(), alarmType: .occlusion)])
pumpManager.state.occlusionDetected = !pumpManager.state.occlusionDetected
tableView.deselectRow(at: indexPath, animated: true)
tableView.reloadRows(at: [indexPath], with: .automatic)
case .pumpError:
pumpManager.injectPumpEvents(pumpManager.state.pumpErrorDetected ? [NewPumpEvent(alarmClearAt: Date())] : [NewPumpEvent(alarmAt: Date(), alarmType: .other("Mock Pump Error"))])
pumpManager.state.pumpErrorDetected = !pumpManager.state.pumpErrorDetected
tableView.deselectRow(at: indexPath, animated: true)
tableView.reloadRows(at: [indexPath], with: .automatic)
}
case .settings:
tableView.deselectRow(at: indexPath, animated: true)
switch SettingsRow(rawValue: indexPath.row)! {
case .deliverableIncrements:
break
case .supportedBasalRates:
if pumpManager.state.deliverableIncrements == .custom, pumpManager.state.supportedBasalRates.indices.contains(1) {
let basalRates = pumpManager.state.supportedBasalRates
let vc = SupportedRangeTableViewController(minValue: basalRates.first!, maxValue: basalRates.last!, stepSize: basalRates[1] - basalRates.first!)
vc.title = "Supported Basal Rates"
vc.indexPath = indexPath
vc.delegate = self
show(vc, sender: sender)
}
break
case .supportedBolusVolumes:
if pumpManager.state.deliverableIncrements == .custom, pumpManager.state.supportedBolusVolumes.indices.contains(1) {
let bolusVolumes = pumpManager.state.supportedBolusVolumes
let vc = SupportedRangeTableViewController(minValue: bolusVolumes.first!, maxValue: bolusVolumes.last!, stepSize: bolusVolumes[1] - bolusVolumes.first!)
vc.title = "Supported Bolus Volumes"
vc.indexPath = indexPath
vc.delegate = self
show(vc, sender: sender)
}
break
case .insulinType:
let view = InsulinTypeSetting(initialValue: pumpManager.state.insulinType, supportedInsulinTypes: InsulinType.allCases, allowUnsetInsulinType: true) { (newType) in
self.pumpManager.state.insulinType = newType
}
let vc = DismissibleHostingController(rootView: view) {
tableView.reloadRows(at: [indexPath], with: .automatic)
}
vc.title = LocalizedString("Insulin Type", comment: "Controller title for insulin type selection screen")
show(vc, sender: sender)
case .reservoirRemaining:
let vc = TextFieldTableViewController()
vc.value = String(format: "%.1f", pumpManager.state.reservoirUnitsRemaining)
vc.unit = "U"
vc.keyboardType = .decimalPad
vc.indexPath = indexPath
vc.delegate = self
show(vc, sender: sender)
case .batteryRemaining:
let vc = PercentageTextFieldTableViewController()
vc.percentage = pumpManager.status.pumpBatteryChargeRemaining
vc.indexPath = indexPath
vc.percentageDelegate = self
show(vc, sender: sender)
case .tempBasalErrorToggle, .bolusErrorToggle, .bolusCancelErrorToggle, .suspendErrorToggle, .resumeErrorToggle, .uncertainDeliveryErrorToggle:
break
case .lastReconciliationDate:
tableView.deselectRow(at: indexPath, animated: true)
tableView.beginUpdates()
tableView.endUpdates()
}
case .statusProgress:
let vc = PercentageTextFieldTableViewController()
vc.indexPath = indexPath
vc.percentageDelegate = self
switch StatusProgressRow(rawValue: indexPath.row)! {
case .percentComplete:
vc.percentage = pumpManager.state.progressPercentComplete
case .warningThreshold:
vc.percentage = pumpManager.state.progressWarningThresholdPercentValue
case .criticalThreshold:
vc.percentage = pumpManager.state.progressCriticalThresholdPercentValue
}
show(vc, sender: sender)
case .deletePump:
let confirmVC = UIAlertController(pumpDeletionHandler: {
self.pumpManager.notifyDelegateOfDeactivation {
DispatchQueue.main.async {
self.done()
}
}
})
present(confirmVC, animated: true) {
tableView.deselectRow(at: indexPath, animated: true)
}
default:
tableView.deselectRow(at: indexPath, animated: true)
}
}
private func suspendResumeCellTapped(_ cell: SuspendResumeTableViewCell) {
switch cell.shownAction {
case .resume:
pumpManager.resumeDelivery { (error) in
if let error = error {
DispatchQueue.main.async {
let title = LocalizedString("Error Resuming", comment: "The alert title for a resume error")
self.present(UIAlertController(with: error, title: title), animated: true)
}
}
}
case .suspend:
pumpManager.suspendDelivery { (error) in
if let error = error {
DispatchQueue.main.async {
let title = LocalizedString("Error Suspending", comment: "The alert title for a suspend error")
self.present(UIAlertController(with: error, title: title), animated: true)
}
}
}
default:
break
}
}
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
switch Section(rawValue: indexPath.section)! {
case .settings:
switch SettingsRow(rawValue: indexPath.row)! {
case .lastReconciliationDate:
let resetAction = UIContextualAction(style: .normal, title: "Reset") {[weak self] _,_,_ in
self?.pumpManager.testLastReconciliation = nil
tableView.reloadRows(at: [indexPath], with: .automatic)
}
resetAction.backgroundColor = .systemRed
return UISwipeActionsConfiguration(actions: [resetAction])
default:
break
}
default:
break
}
return nil
}
}
extension MockPumpManagerSettingsViewController: DatePickerTableViewCellDelegate {
func datePickerTableViewCellDidUpdateDate(_ cell: DatePickerTableViewCell) {
guard let row = tableView.indexPath(for: cell)?.row else { return }
switch SettingsRow(rawValue: row) {
case .lastReconciliationDate?:
pumpManager.testLastReconciliation = cell.date
default:
break
}
}
}
extension MockPumpManagerSettingsViewController: PumpManagerStatusObserver {
public func pumpManager(_ pumpManager: PumpManager, didUpdate status: PumpManagerStatus, oldStatus: PumpManagerStatus) {
dispatchPrecondition(condition: .onQueue(.main))
if let suspendResumeTableViewCell = self.tableView?.cellForRow(at: IndexPath(row: ActionRow.suspendResume.rawValue, section: Section.actions.rawValue)) as? SuspendResumeTableViewCell
{
suspendResumeTableViewCell.basalDeliveryState = status.basalDeliveryState
}
tableView.reloadSections([Section.basalRate.rawValue], with: .automatic)
}
}
extension MockPumpManagerSettingsViewController: TextFieldTableViewControllerDelegate {
func textFieldTableViewControllerDidReturn(_ controller: TextFieldTableViewController) {
update(from: controller)
}
func textFieldTableViewControllerDidEndEditing(_ controller: TextFieldTableViewController) {
update(from: controller)
}
private func update(from controller: TextFieldTableViewController) {
guard let indexPath = controller.indexPath else { assertionFailure(); return }
assert(indexPath == [Section.settings.rawValue, SettingsRow.reservoirRemaining.rawValue])
if let value = controller.value.flatMap(Double.init) {
pumpManager.state.reservoirUnitsRemaining = max(value, 0)
}
tableView.reloadRows(at: [indexPath], with: .automatic)
}
}
extension MockPumpManagerSettingsViewController: PercentageTextFieldTableViewControllerDelegate {
func percentageTextFieldTableViewControllerDidChangePercentage(_ controller: PercentageTextFieldTableViewController) {
guard let indexPath = controller.indexPath else {
assertionFailure()
return
}
switch indexPath {
case [Section.settings.rawValue, SettingsRow.batteryRemaining.rawValue]:
pumpManager.pumpBatteryChargeRemaining = controller.percentage.map { $0.clamped(to: 0...1) }
tableView.reloadRows(at: [indexPath], with: .automatic)
case [Section.statusProgress.rawValue, StatusProgressRow.percentComplete.rawValue]:
pumpManager.state.progressPercentComplete = controller.percentage.map { $0.clamped(to: 0...1) }
tableView.reloadRows(at: [indexPath], with: .automatic)
case [Section.statusProgress.rawValue, StatusProgressRow.warningThreshold.rawValue]:
pumpManager.state.progressWarningThresholdPercentValue = controller.percentage.map { $0.clamped(to: 0...1) }
tableView.reloadRows(at: [indexPath], with: .automatic)
case [Section.statusProgress.rawValue, StatusProgressRow.criticalThreshold.rawValue]:
pumpManager.state.progressCriticalThresholdPercentValue = controller.percentage.map { $0.clamped(to: 0...1) }
tableView.reloadRows(at: [indexPath], with: .automatic)
default:
assertionFailure()
}
}
}
private extension UIAlertController {
convenience init(pumpDeletionHandler handler: @escaping () -> Void) {
self.init(
title: nil,
message: "Are you sure you want to delete this pump?",
preferredStyle: .actionSheet
)
addAction(UIAlertAction(
title: "Delete Pump",
style: .destructive,
handler: { _ in handler() }
))
addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
}
convenience init(title: String, error: Error) {
let message: String
if let localizedError = error as? LocalizedError {
let sentenceFormat = NSLocalizedString("%@.", comment: "Appends a full-stop to a statement")
message = [localizedError.failureReason, localizedError.recoverySuggestion].compactMap({ $0 }).map({
String(format: sentenceFormat, $0)
}).joined(separator: "\n")
} else {
message = String(describing: error)
}
self.init(
title: title,
message: message,
preferredStyle: .alert
)
addAction(UIAlertAction(
title: NSLocalizedString("OK", comment: "Button title to acknowledge error"),
style: .default,
handler: nil
))
}
}
extension MockPumpManagerSettingsViewController: SupportedRangeTableViewControllerDelegate {
func supportedRangeDidUpdate(_ controller: SupportedRangeTableViewController) {
guard let indexPath = controller.indexPath else {
assertionFailure()
return
}
let rangeMin = Int(controller.minValue/controller.stepSize)
let rangeMax = Int(controller.maxValue/controller.stepSize)
let rangeStep = 1/controller.stepSize
let values: [Double] = (rangeMin...rangeMax).map { Double($0) / rangeStep }
switch indexPath {
case [Section.settings.rawValue, SettingsRow.supportedBasalRates.rawValue]:
pumpManager.state.supportedBasalRates = values
tableView.reloadRows(at: [indexPath], with: .automatic)
case [Section.settings.rawValue, SettingsRow.supportedBolusVolumes.rawValue]:
pumpManager.state.supportedBolusVolumes = values
tableView.reloadRows(at: [indexPath], with: .automatic)
default:
assertionFailure()
}
}
}
fileprivate extension NewPumpEvent {
init(alarmAt date: Date, alarmType: PumpAlarmType? = nil) {
self.init(date: date,
dose: nil,
raw: Data(UUID().uuidString.utf8),
title: "alarm[\(alarmType?.rawValue ?? "")]",
type: .alarm,
alarmType: alarmType)
}
init(alarmClearAt date: Date) {
self.init(date: date,
dose: nil,
raw: Data(UUID().uuidString.utf8),
title: "alarmClear",
type: .alarmClear)
}
}
| mit | 63a90627de5a201861acd88dfc1181dd | 45.533546 | 254 | 0.62863 | 5.615963 | false | false | false | false |
VBVMI/VerseByVerse-iOS | VBVMI/SoundManager.swift | 1 | 35387 | //
// SoundManager.swift
// VBVMI
//
// Created by Thomas Carey on 6/03/16.
// Copyright © 2016 Tom Carey. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
import CoreData
import Crashlytics
enum SoundError : Error, CustomNSError {
case debug(message: String)
var errorCode: Int {
switch self {
case .debug(_):
return 0
}
}
var errorUserInfo: [String : Any] {
switch self {
case .debug(let message):
return ["debug": message]
}
}
static var errorDomain: String = "com.versebyverseministry.SoundError"
}
class SoundManager: NSObject {
static let sharedInstance = SoundManager()
fileprivate(set) var study: Study? //backgroundContext version
fileprivate(set) var lesson: Lesson? //backgroundContext version
fileprivate(set) var lessonQueue = [Lesson]() //backgroundContext version
fileprivate(set) var audioURL: URL?
fileprivate var initialCategory: String?
fileprivate var initialMode: String?
let avPlayer = AVQueuePlayer()
fileprivate var imageView = UIImageView()
var albumCover: UIImage? {
return imageView.image
}
fileprivate var audioCache: AudioPlayer?
fileprivate var backgroundQueueContext: NSManagedObjectContext?
fileprivate var playbackRate: Float = AudioPlayerViewController.AudioRate.load().rawValue
fileprivate var initializeCompletionHandler: ((NSError?) -> Void)?
fileprivate var initiatePlaybackCompletionHandler: ((NSError?) -> Void)?
weak var activeController: UIViewController?
fileprivate var currentMonitoredItem: AVPlayerItem? {
didSet {
if let old = oldValue {
old.removeObserver(self, forKeyPath: "status")
}
if let new = currentMonitoredItem {
new.addObserver(self, forKeyPath: "status", options: .new, context: nil)
}
}
}
fileprivate var timerObserver : AnyObject?
fileprivate override init() {
super.init()
startTimerObserver()
startBackgroundTask()
self.configureCommandCenter()
self.restoreState()
self.configureContentManager()
NotificationCenter.default.addObserver(self, selector: #selector(audioDidFinish(_:)), name: Notification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
self.avPlayer.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
if #available(iOS 10.0, *) {
self.avPlayer.automaticallyWaitsToMinimizeStalling = false
} else {
// Fallback on earlier versions
}
}
deinit {
self.avPlayer.removeObserver(self, forKeyPath: "rate")
self.currentMonitoredItem = nil
stopTimerObserver()
NotificationCenter.default.removeObserver(self)
}
private var backgroundTask: UIBackgroundTaskIdentifier?
private func startBackgroundTask() {
backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "SoundManagerLoading", expirationHandler: {
logger.info("🍕Sound loading background task expired")
})
if backgroundTask == UIBackgroundTaskInvalid {
backgroundTask = nil
} else {
logger.info("🍕Background task started")
}
}
private func endBackgroundTask() {
if let task = backgroundTask {
UIApplication.shared.endBackgroundTask(task)
backgroundTask = nil
logger.info("🍕Background task ended")
}
}
@objc func audioDidFinish(_ notification: Notification) {
//Mark the lesson as complete
backgroundQueueContext?.perform({ () -> Void in
self.lesson?.audioProgress = 0
let _ = try? self.backgroundQueueContext?.save()
})
}
fileprivate var isReady: Bool = false {
didSet {
if isReady {
self.readyBlock?()
self.readyBlock = nil
self.initializeCompletionHandler?(nil)
self.initializeCompletionHandler = nil
self.initiatePlaybackCompletionHandler?(nil)
self.initiatePlaybackCompletionHandler = nil
}
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let _ = object as? AVPlayer , keyPath == "rate" {
self.configureInfo()
}
if let item = object as? AVPlayerItem , keyPath == "status" {
if item.status == AVPlayerItemStatus.readyToPlay {
logger.info("🍕Player became ready to play")
let currentProgress = self.loadProgress
let durationSeconds = CMTimeGetSeconds(item.duration)
let progress = currentProgress * durationSeconds
var time = CMTime(seconds: progress, preferredTimescale: item.duration.timescale)
if time == kCMTimeInvalid {
logger.error("🍕Time is invalid: progess: \(progress), timeScale: \(item.duration.timescale)")
time = kCMTimeZero
}
self.currentMonitoredItem = nil
item.seek(to: time, completionHandler: { (sucess) in
logger.debug("🍕Seek to time: \(sucess ? "Success" : "Failed")")
self.configureInfo()
self.isReady = true
self.endBackgroundTask()
})
}
}
}
fileprivate func stopTimerObserver() {
logger.info("🍕Sound Manager Stopping timer observer")
if let timerObserver = timerObserver {
self.avPlayer.removeTimeObserver(timerObserver)
self.timerObserver = nil
}
}
fileprivate func startTimerObserver() {
logger.info("🍕Sound Manager Starting timer observer")
self.timerObserver = self.avPlayer.addPeriodicTimeObserver(forInterval: CMTime(seconds: 5, preferredTimescale: 600), queue: nil, using: { (currentTime) -> Void in
self.saveState()
// self.configureInfo()
// logger.debug("Observing time: \(CMTimeGetSeconds(currentTime))")
}) as AnyObject?
}
func restoreState(_ completion:(()->())? = nil) {
isReady = false
logger.verbose("Sound Manager Attempting To Restore State")
let context = ContextCoordinator.sharedInstance.backgroundManagedObjectContext!
self.backgroundQueueContext = context
logger.verbose("Sound Manager has found context: \(context)")
context.perform({ () -> Void in
self.audioCache = AudioPlayer.findFirst(context)
if self.audioCache == nil {
self.audioCache = AudioPlayer(managedObjectContext: context)
self.audioCache?.currentTime = 0
do {
try context.save()
} catch let error {
logger.error("Error saving: \(error)")
}
self.endBackgroundTask()
} else if let audioCache = self.audioCache {
self.lesson = audioCache.lesson.first
self.study = audioCache.study.first
if let audioLesson = self.lesson, let audioStudy = self.study , audioLesson.audioProgress != 0 && audioLesson.audioProgress != 1 && audioLesson.audioProgress != 0 {
if let audioURLString = audioLesson.audioSourceURL {
if let url = APIDataManager.fileExists(audioLesson, urlString: audioURLString) {
// The file is downloaded and ready for playing
logger.verbose("Sound Manager State restored...")
let lessonId = audioLesson.objectID
let studyId = audioStudy.objectID
DispatchQueue.main.async { () -> Void in
guard let mainLesson = ContextCoordinator.sharedInstance.managedObjectContext!.object(with: lessonId) as? Lesson,
let mainStudy = ContextCoordinator.sharedInstance.managedObjectContext!.object(with: studyId) as? Study else {
return
}
//We should dispatch a notification to load the audio controller...
if let controller = (UIApplication.shared.delegate as? AppDelegate)?.window?.rootViewController as? HomeTabBarController {
if let audioPlayerController = controller.popupContent as? AudioPlayerViewController {
audioPlayerController.configure(url, name: mainLesson.title, subTitle: mainLesson.descriptionText ?? "", lesson: mainLesson, study: mainStudy)
if controller.popupPresentationState == .closed {
controller.openPopup(animated: true, completion: completion)
}
} else {
let demoVC = AudioPlayerViewController()
demoVC.configure(url, name: mainLesson.title, subTitle: mainLesson.descriptionText ?? "", lesson: mainLesson, study: mainStudy, startPlaying: false)
controller.presentPopupBar(withContentViewController: demoVC, openPopup: true, animated: true, completion: completion)
}
}
}
//self.configure(study, lesson: lesson, audioURL: url, progress: lesson.audioProgress, readyBlock: completion)
} else {
// The file needs to be downloaded
// maybe? lets deal with this later?
self.endBackgroundTask()
}
}
} else {
self.lesson = nil
self.study = nil
self.audioCache?.currentTime = 0
self.endBackgroundTask()
}
}
})
}
fileprivate var readyBlock: (()->())? = nil
fileprivate var loadProgress: Double = 0 {
didSet {
logger.info("🍕Loading progress: \(self.loadProgress)")
}
}
func configure(_ study: Study, lesson: Lesson, audioURL: URL, progress: Double = 0, readyBlock: (()->())? = nil) {
isReady = false
guard let context = backgroundQueueContext else {
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "Sound Manager Background Context Not Configured"))
logger.error("Sound Manager Background Context Not Configured")
return
}
logger.info("🍕Sound Manager configuring with audio \(audioURL.lastPathComponent)")
//convert the lesson and study into appropriate context objects
self.loadProgress = progress == 1 ? 0 : progress
context.performAndWait { () -> Void in
do {
self.study = try Study.withIdentifier(study.objectID, context: context)
self.lesson = try Lesson.withIdentifier(lesson.objectID, context: context)
} catch let error {
logger.error("Error in SoundManager \(error)")
}
}
self.audioURL = audioURL
let asset = AVAsset(url: audioURL)
let item = AVPlayerItem(asset: asset)
self.currentMonitoredItem = item
self.avPlayer.replaceCurrentItem(with: item)
self.readyBlock = readyBlock
getImage()
}
func startPlaying() {
// logger.info("🍕Start playing")
//// if !audioSessionConfigured {
//// logger.error("Audio session not configured")
//// self.setupAudioSession({ (success) in
//// self.startPlaying()
//// })
//// return
//// }
// if avPlayer.status == AVPlayerStatus.ReadyToPlay {
// logger.info("🍕Playing audio")
// avPlayer.setRate(playbackRate, time: kCMTimeInvalid, atHostTime: kCMTimeInvalid)
// configureInfo()
// } else {
// logger.info("🍕AVPlayerStatus is not ready to play")
// }
let _ = start(registerObservers: true)
}
fileprivate func start(registerObservers addObservers: Bool) -> Bool {
logger.info("🍕Starting AudioManager - addObservers:\(addObservers)")
if avPlayer.status != AVPlayerStatus.readyToPlay {
logger.error("avPlayer status is not readyToPlay")
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "avPlayer status is not readyToPlay"))
return false
}
let session = AVAudioSession.sharedInstance()
if !setAudioSessionMode() || !setAudioSessionCategory() {
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "Failed to configure Audio session"))
logger.error("Failed to configure Audio session")
return false
}
do {
try session.setActive(true)
} catch let error {
logger.error("Error activating audio session: \(error)")
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "Error activating audio session: \(error)"))
return false
}
if addObservers {
registerObservers()
}
// if let duration = avPlayer.currentItem?.duration {
// let seconds = CMTimeGetSeconds(duration)
// time = CMTimeMakeWithSeconds(seconds * progress, duration.timescale)
//
// }
//
// logger.info("🍕Starting audio player at rate \(playbackRate)")
// if let duration = avPlayer.currentItem?.duration where time >= duration {
// time = kCMTimeZero
// logger.info("🍕Resetting time to zero")
// }
//
// avPlayer.setRate(playbackRate, time: time, atHostTime: kCMTimeInvalid)
avPlayer.setRate(playbackRate, time: kCMTimeInvalid, atHostTime: kCMTimeInvalid)
return true
}
func pausePlaying() {
self.saveState()
stop(unregisterObservers: true)
}
fileprivate func stop(unregisterObservers removeObservers: Bool) {
avPlayer.pause()
do {
try AVAudioSession.sharedInstance().setActive(false)
} catch let error {
logger.error("Error deactivating audio session: \(error)")
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "Error deactivating audio session: \(error)"))
}
if removeObservers {
unregisterObservers()
}
}
fileprivate func configureInfo() {
let info = MediaCenterInfo.shared
logger.info("🍕Configuring the info")
guard let lesson = lesson, let study = study, let item = avPlayer.currentItem else {
logger.warning("Trying to configure Sound Manager without all details")
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "Trying to configure Sound Manager without all details"), withAdditionalUserInfo: ["lesson": self.lesson != nil ? "valid": "invalid", "study": self.study != nil ? "valid": "invalid", "avPlayer.currentItem": avPlayer.currentItem != nil ? "valid": "invalid"])
return
}
info.configureInfo(studyTitle: study.title, lessonTitle: lesson.title, duration: CMTimeGetSeconds(item.duration), playbackRate: self.avPlayer.rate, defaultPlaybackRate: self.playbackRate, elapsedTime: CMTimeGetSeconds(self.avPlayer.currentTime()), artwork: self.imageView.image)
}
fileprivate func configureContentManager() {
logger.info("🍕Configure Content Manager")
let manager = MPPlayableContentManager.shared()
manager.delegate = self
}
fileprivate func configureCommandCenter() {
logger.info("🍕Configuring command center")
UIApplication.shared.beginReceivingRemoteControlEvents()
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.addTarget (handler: { [weak self] (event) -> MPRemoteCommandHandlerStatus in
guard let this = self else { return MPRemoteCommandHandlerStatus.commandFailed }
// If no item, load the cached one
if let item = this.avPlayer.currentItem {
// If item is at end, and next is unavailable, error
if CMTimeCompare(item.duration, this.avPlayer.currentTime()) <= 0 {
logger.verbose("Sound Manager Item is at end while trying to play")
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "CC: Sound Manager Item is at end while trying to play"))
return .noSuchContent
} else {
this.startPlaying()
this.configureInfo()
logger.verbose("Sound Manager Did Play")
return MPRemoteCommandHandlerStatus.success
}
} else {
logger.verbose("Sound Manager Choosing to restore State then play")
this.restoreState() {
this.startPlaying()
this.configureInfo()
}
return MPRemoteCommandHandlerStatus.success // ???
}
})
commandCenter.togglePlayPauseCommand.addTarget (handler: { [weak self] (event) -> MPRemoteCommandHandlerStatus in
guard let this = self else { return MPRemoteCommandHandlerStatus.commandFailed }
if let item = this.avPlayer.currentItem {
// If item is at end, and next is unavailable, error
if CMTimeCompare(item.duration, this.avPlayer.currentTime()) <= 0 {
logger.verbose("Sound Manager Item is at end while trying to play")
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "CC: Sound Manager Item is at end while trying to play"))
return .noSuchContent
} else {
if this.avPlayer.rate == 0 {
//Player is stopped
this.startPlaying()
this.configureInfo()
logger.verbose("Sound Manager Did Play")
return MPRemoteCommandHandlerStatus.success
} else {
this.pausePlaying()
this.configureInfo()
logger.verbose("Sound Manager Did Pause")
return MPRemoteCommandHandlerStatus.success
}
}
} else {
logger.verbose("Sound Manager Choosing to restore State then play")
this.restoreState() {
this.startPlaying()
this.configureInfo()
}
return MPRemoteCommandHandlerStatus.success // ???
}
})
commandCenter.pauseCommand.addTarget (handler: { [weak self] (event) -> MPRemoteCommandHandlerStatus in
guard let this = self else { return MPRemoteCommandHandlerStatus.commandFailed }
//Pause the player
if let _ = this.avPlayer.currentItem {
this.pausePlaying()
logger.verbose("Sound Manager Did Pause audio")
// this.configureInfo()
return MPRemoteCommandHandlerStatus.success
}
logger.verbose("Sound Manager Failed Pause audio")
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "CC: Sound Manager Failed Pause audio"))
return MPRemoteCommandHandlerStatus.noSuchContent
//save state
})
commandCenter.skipBackwardCommand.addTarget (handler: { (event) -> MPRemoteCommandHandlerStatus in
if let skipEvent = event as? MPSkipIntervalCommandEvent , self.skipBackward(skipEvent.interval) {
return .success
}
return .noSuchContent
})
commandCenter.skipBackwardCommand.preferredIntervals = [30]
commandCenter.skipForwardCommand.addTarget (handler: { (event) -> MPRemoteCommandHandlerStatus in
if let skipEvent = event as? MPSkipIntervalCommandEvent , self.skipForward(skipEvent.interval) {
return .success
}
return .noSuchContent
})
commandCenter.skipForwardCommand.preferredIntervals = [30]
commandCenter.changePlaybackPositionCommand.addTarget (handler: { (event) -> MPRemoteCommandHandlerStatus in
if let changeEvent = event as? MPChangePlaybackPositionCommandEvent {
let timeStamp = changeEvent.positionTime
if self.seekToTime(timeStamp) {
return .success
} else {
return .noSuchContent
}
}
return .commandFailed
})
commandCenter.nextTrackCommand.addTarget (handler: { (event) -> MPRemoteCommandHandlerStatus in
logger.info("🍕Want to skip to next track?")
return MPRemoteCommandHandlerStatus.noSuchContent
})
}
func seekToTime(_ time: TimeInterval, completion:((_ success:Bool)->())? = nil) -> Bool {
guard let currentItem = self.avPlayer.currentItem else {
return false
}
let cmTime = self.avPlayer.currentTime()
let totalTime = CMTimeGetSeconds(currentItem.duration)
let skipToTime = max(0, min(totalTime, time))
self.avPlayer.seek(to: CMTimeMakeWithSeconds(skipToTime, cmTime.timescale), completionHandler: { (success) -> Void in
self.configureInfo()
self.saveState()
completion?(success)
})
return true
}
func skipForward(_ time: TimeInterval) -> Bool {
logger.info("🍕Skip forward")
guard let currentItem = self.avPlayer.currentItem else {
return false
}
let interval = time
let cmTime = self.avPlayer.currentTime()
let currentTime = CMTimeGetSeconds(cmTime)
let totalTime = CMTimeGetSeconds(currentItem.duration)
let skipToTime = min(totalTime, currentTime + interval)
self.avPlayer.seek(to: CMTimeMakeWithSeconds(skipToTime, cmTime.timescale), completionHandler: { (success) -> Void in
self.configureInfo()
self.saveState()
})
return true
}
func skipBackward(_ time: TimeInterval) -> Bool {
logger.info("🍕Skip backward")
let interval = time
let cmTime = self.avPlayer.currentTime()
let currentTime = CMTimeGetSeconds(cmTime)
let skipToTime = max(0, currentTime - interval)
self.avPlayer.seek(to: CMTimeMakeWithSeconds(skipToTime, cmTime.timescale), completionHandler: { (success) -> Void in
self.configureInfo()
self.saveState()
})
return true
}
fileprivate func saveState() {
let duration = self.avPlayer.currentItem?.duration
let currentTime = self.avPlayer.currentTime()
backgroundQueueContext?.perform({ () -> Void in
guard let audioCache = self.audioCache else {
logger.error("There is no audio-cache for some reason")
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "There is no audio-cache for some reason"))
return
}
audioCache.lessonIdentifier = self.lesson?.identifier
audioCache.studyIdentifier = self.study?.identifier
audioCache.currentTime = CMTimeGetSeconds(currentTime)
//calculate progress for the lesson and store that!!
if let duration = duration {
let durationSeconds = CMTimeGetSeconds(duration)
let currentTimeSeconds = CMTimeGetSeconds(currentTime)
if durationSeconds == 0 {
self.lesson?.audioProgress = 0
} else {
self.lesson?.audioProgress = max(0, min(currentTimeSeconds / durationSeconds, 1))
logger.debug("progress: \(self.lesson?.audioProgress ?? -1)")
}
}
do {
try self.backgroundQueueContext?.save()
} catch let error {
logger.error("Error saving SoundManager state: \(error)")
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "Error saving SoundManager state: \(error)"))
}
})
}
fileprivate var wasPlaying = false
func handleInterruption(_ notification: Notification) {
logger.info("🍕Handle interruption wasplaying: \(self.wasPlaying) notification: \(notification.userInfo ?? [:])")
guard let userInfo = (notification as NSNotification).userInfo as? [String: AnyObject] else { return }
guard let type = userInfo[AVAudioSessionInterruptionTypeKey] as? AVAudioSessionInterruptionType else { return }
switch type {
case .began:
logger.info("🍕Got interrupted")
wasPlaying = true
case .ended:
if let flag = userInfo[AVAudioSessionInterruptionOptionKey] as? AVAudioSessionInterruptionOptions {
if flag == .shouldResume && wasPlaying {
self.startPlaying()
}
}
}
}
fileprivate var isObservingAudioSession = false
fileprivate var audioSessionConfigured = false
func handleNotification(_ notification: Notification) {
logger.info("🍕\(notification.name) - \(notification.userInfo ?? [:])")
}
// private func setupAudioSession(completion: ((success: Bool)->())?) {
// logger.info("🍕Sound Manager Setting up Audio Session")
// let audioSession = AVAudioSession.sharedInstance()
// self.initialCategory = audioSession.category
// self.initialMode = audioSession.mode
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
// let success : Bool
// do {
// try audioSession.setCategory(AVAudioSessionCategoryPlayback)
// try audioSession.setMode(AVAudioSessionModeSpokenAudio)
//
// if !self.isObservingAudioSession {
// NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SoundManager.handleInterruption(_:)), name: AVAudioSessionInterruptionNotification, object: audioSession)
// NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SoundManager.handleNotification(_:)), name: AVAudioSessionMediaServicesWereLostNotification, object: audioSession)
// NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SoundManager.handleNotification(_:)), name: AVAudioSessionMediaServicesWereResetNotification, object: audioSession)
// NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SoundManager.handleNotification(_:)), name: AVAudioSessionSilenceSecondaryAudioHintNotification, object: audioSession)
// self.isObservingAudioSession = true
// }
//
//
// try audioSession.setActive(true)
// success = true
// self.audioSessionConfigured = true
// } catch let error {
// logger.info("🍕error :\(error)")
// success = false
// }
// if let completion = completion {
// dispatch_async(dispatch_get_main_queue()) { () -> Void in
// logger.info("🍕Sound Manager Completed Setup of Audio Session: \(success)")
// completion(success: success)
// }
// }
// }
// }
fileprivate var audioInterruptionObserverToken : NSObjectProtocol? {
didSet {
if let oldValue = oldValue {
NotificationCenter.default.removeObserver(oldValue)
}
}
}
fileprivate func registerObservers() {
logger.info("🍕registering observers")
let session = AVAudioSession.sharedInstance()
audioInterruptionObserverToken = NotificationCenter.default.addObserver(forName: NSNotification.Name.AVAudioSessionInterruption, object: session, queue: nil) { [weak self] (notification) in
logger.info("🍕Interruption: \((notification as NSNotification).userInfo ?? [:])")
if let value = (notification as NSNotification).userInfo?[AVAudioSessionInterruptionTypeKey] as? NSNumber {
if let key = AVAudioSessionInterruptionType(rawValue: value.uintValue) , key == .began {
logger.info("🍕Began")
self?.stop(unregisterObservers: false)
} else {
logger.info("🍕Ended")
if let option = (notification as NSNotification).userInfo?[AVAudioSessionInterruptionOptionKey] as? NSNumber , option == NSNumber(value:AVAudioSessionInterruptionOptions.shouldResume.rawValue) {
if let this = self {
if this.start(registerObservers: false) != true {
logger.error("Couldn't restart after interruption")
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "Couldn't restart after interruption"))
}
}
}
}
}
}
}
fileprivate func setAudioSessionCategory() -> Bool {
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayback)
} catch let error {
logger.error("Error setting AVAudioSession category: \(error)")
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "Error setting AVAudioSession category: \(error)"))
return false
}
return true
}
fileprivate func setAudioSessionMode() -> Bool {
let session = AVAudioSession.sharedInstance()
do {
try session.setMode(AVAudioSessionModeSpokenAudio)
} catch let error {
logger.error("Error setting AVAudioSession mode: \(error)")
Crashlytics.sharedInstance().recordError(SoundError.debug(message: "Error setting AVAudioSession mode: \(error)"))
return false
}
return true
}
fileprivate func unregisterObservers() {
logger.info("🍕unregisering observers")
if let token = audioInterruptionObserverToken {
NotificationCenter.default.removeObserver(token)
audioInterruptionObserverToken = nil
}
}
fileprivate func getImage() {
guard let thumbnailSource = study?.thumbnailSource, let url = URL(string: thumbnailSource) else {
return
}
imageView.af_setImage(withURL: url, placeholderImage: nil, filter: nil, imageTransition: UIImageView.ImageTransition.noTransition, runImageTransitionIfCached: false) { (response) -> Void in
DispatchQueue.main.async {
self.updateImage()
}
if let imageSource = self.study?.imageSource, let imageURL = URL(string: imageSource) {
let image = self.imageView.image
self.imageView.af_setImage(withURL: imageURL, placeholderImage: image, filter: nil, imageTransition: .noTransition, runImageTransitionIfCached: false) { (response) in
switch response.result {
case .failure(let error):
logger.error("Error download large image: \(error)")
case .success(let value):
self.imageView.image = value
DispatchQueue.main.async {
self.updateImage()
}
}
}
}
}
}
fileprivate func updateImage() {
configureInfo()
}
func setRate(_ value: Float) {
playbackRate = value
if avPlayer.rate != 0 {
startPlaying()
}
}
}
extension SoundManager : MPPlayableContentDelegate {
func playableContentManager(_ contentManager: MPPlayableContentManager, didUpdate context: MPPlayableContentManagerContext) {
logger.debug("playableContentManager:didUpdateContext")
}
func playableContentManager(_ contentManager: MPPlayableContentManager, initializePlaybackQueueWithCompletionHandler completionHandler: @escaping (Error?) -> Void) {
logger.debug("initializePlaybackQueueWithCompletionHandler")
//Not sure about my understanding here. Seems that if you just call completionHandler(nil) then that means that you are good to go, and iOS will let you push info onto the command center
if isReady {
completionHandler(nil)
} else {
//content is loading so deal
self.initializeCompletionHandler = completionHandler
}
}
func playableContentManager(_ contentManager: MPPlayableContentManager, initiatePlaybackOfContentItemAt indexPath: IndexPath, completionHandler: @escaping (Error?) -> Void) {
logger.debug("initiatePlaybackOfContentItemAtIndexPath - (\(indexPath.section),\(indexPath.row))")
if isReady {
self.startPlaying()
completionHandler(nil)
} else {
self.initiatePlaybackCompletionHandler = { [weak self] error in
if error == nil {
self?.startPlaying()
}
completionHandler(error)
}
}
}
}
| mit | 3fa22b82f5f33d982b8bbfc330aeb59b | 42.834783 | 336 | 0.582566 | 5.681372 | false | false | false | false |
therealbnut/swift | test/Sema/accessibility_compound.swift | 2 | 2034 | // RUN: %target-typecheck-verify-swift -swift-version 4
public struct Pair<A, B> {}
public struct PublicStruct {
public struct Inner {}
internal struct Internal {}
}
private typealias PrivateAlias = PublicStruct // expected-note * {{type declared here}}
public let a: PrivateAlias.Inner? // expected-error {{constant cannot be declared public because its type uses a private type}}
public let b: PrivateAlias.Internal? // expected-error {{constant cannot be declared public because its type uses a private type}}
public let c: Pair<PrivateAlias.Inner, PublicStruct.Internal>? // expected-error {{constant cannot be declared public because its type uses a private type}}
public let c2: Pair<PublicStruct.Internal, PrivateAlias.Inner>? // expected-error {{constant cannot be declared public because its type uses a private type}}
public let d: PrivateAlias? // expected-error {{constant cannot be declared public because its type uses a private type}}
// rdar://problem/21408035
private class PrivateBox<T> { // expected-note 2 {{type declared here}}
typealias ValueType = T
typealias AlwaysFloat = Float
}
let boxUnboxInt: PrivateBox<Int>.ValueType = 0 // expected-error {{constant must be declared private or fileprivate because its type uses a private type}}
let boxFloat: PrivateBox<Int>.AlwaysFloat = 0 // expected-error {{constant must be declared private or fileprivate because its type uses a private type}}
private protocol PrivateProto {
associatedtype Inner
}
extension PublicStruct: PrivateProto {}
private class SpecificBox<T: PrivateProto> { // expected-note 2 {{type declared here}}
typealias InnerType = T.Inner
typealias AlwaysFloat = Float
}
let specificBoxUnboxInt: SpecificBox<PublicStruct>.InnerType = .init() // expected-error {{constant must be declared private or fileprivate because its type uses a private type}}
let specificBoxFloat: SpecificBox<PublicStruct>.AlwaysFloat = 0 // expected-error {{constant must be declared private or fileprivate because its type uses a private type}}
| apache-2.0 | d1f4df11b6da973031913c31ab081144 | 49.85 | 178 | 0.77237 | 4.460526 | false | false | false | false |
rtoal/polyglot | swift/circle.swift | 2 | 486 | import Foundation
struct Circle {
var radius: Double // stored property
var area: Double { // computed property
get {return Double.pi * radius * radius}
set(a) {radius = sqrt(a/Double.pi)}
}
}
var c = Circle(radius: 10)
assert(c.radius == 10 && c.area == 100*Double.pi) // invokes get
c.area = 16*Double.pi // invokes set
assert(c.radius == 4 && c.area == 16*Double.pi)
| mit | b8c8fe0fae6fe7a0ec4ba9044c82f2f9 | 33.714286 | 71 | 0.516461 | 3.857143 | false | false | false | false |
odigeoteam/TableViewKit | Examples/Viper/TableViewKit+VIPER/AboutModule/MoreAboutSection.swift | 1 | 1136 | import Foundation
import TableViewKit
class MoreAboutSection: TableSection {
var items: ObservableArray<TableItem> = []
var header: HeaderFooterView = .title("More about eDreams")
let presenter: AboutPresenterProtocol?
weak var manager: TableViewManager?
required init(presenter: AboutPresenterProtocol?, manager: TableViewManager?) {
self.presenter = presenter
self.manager = manager
let moreAction = UITableViewRowAction(style: .normal, title: "More", handler: { _, _ in
print("MoreAction executed")
})
let deleteAction = UITableViewRowAction(style: .destructive, title: "Delete", handler: { _, indexPath in
self.items.remove(at: indexPath.row)
})
let types: [MoreAboutItemType] = [.faq, .contact, .terms, .feedback, .share, .rate]
let items: [TableItem] = types.map {
let moreAboutItem = MoreAboutItem(type: $0, presenter: presenter, manager: manager)
moreAboutItem.actions = [deleteAction, moreAction]
return moreAboutItem
}
self.items.replace(with: items)
}
}
| mit | 5bd2c9e21b3f0f258d2eed4a0b598435 | 34.5 | 112 | 0.654049 | 4.580645 | false | false | false | false |
wj2061/ios7ptl-swift3.0 | ch21-Text/Columns/Columns/ViewController.swift | 1 | 1020 | //
// ViewController.swift
// Columns
//
// Created by wj on 15/11/28.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var kLipsum:String? = {
let path = Bundle.main.path(forResource: "Lipsum", ofType: "txt")!
let st = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)
return st
}()
override func viewDidLoad() {
super.viewDidLoad()
var alignment = CTTextAlignment.justified
var setting = CTParagraphStyleSetting(spec: .alignment, valueSize: MemoryLayout<CTTextAlignment>.size, value: &alignment)
let style = CTParagraphStyleCreate(&setting, 1)
let attrString = NSAttributedString(string: kLipsum!, attributes: [kCTParagraphStyleAttributeName as String:style])
let columnView = ColumnView(frame: self.view.bounds)
columnView.attributedString = attrString
view.addSubview(columnView)
}
}
| mit | ec676b32b6642070156eeb0ece0b66c1 | 28.911765 | 132 | 0.653884 | 4.441048 | false | false | false | false |
researchpanelasia/sop-ios-sdk | SurveyonPartners/HttpClient.swift | 1 | 4678 | //
// HttpClient.swift
// SurveyonPartners
//
// Copyright © 2017年 d8aspring. All rights reserved.
//
import Foundation
struct HttpClient {
static let HTTPS = "https://"
static let HTTP = "http://"
static let PATH_GET_SURVEY = "/api/v1_1/surveys/json"
static let PATH_GET_SYNC_SURVEY = "/api/v1_1/sync-surveys/json"
static let PATH_POST_IDFA = "/api/v1_1/resource/app/member/identifier/apple_idfa"
static let KEY_APP_ID = "app_id";
static let KEY_APP_MID = "app_mid";
static let KEY_TIME = "time";
static let KEY_SIG = "sig";
static let KEY_IDENTIFIER = "identifier";
static let KEY_IS_AD_TRACKING_ENABLED = "is_ad_tracking_enabled";
static let KEY_SOP_AD_TRACKING = "sop_ad_tracking";
var appId: String
var appMid: String
var secretKey: String
var sopHost: String
var sopConsoleHost: String
var idfaUpdateSpan: Int64
var useHttps: Bool
var verifyHost: Bool
init(appId: String,
appMid: String,
secretKey: String,
sopHost: String,
sopConsoleHost: String,
updateSpan: Int64,
useHttps: Bool,
verifyHost: Bool ) {
self.appId = appId
self.appMid = appMid
self.secretKey = secretKey
self.sopHost = sopHost
self.sopConsoleHost = sopConsoleHost
self.idfaUpdateSpan = updateSpan
self.useHttps = useHttps
self.verifyHost = verifyHost
}
}
extension HttpClient {
func updateIdfa(completion: @escaping (RequestResult) -> Void) {
if !Utility.isOnline() {
completion(RequestResult.failed(error: SOPError(message: "Network not available", type: .NetworkNotAvailable, response: nil, error: nil)))
return
}
let url = URL(string: getProtocol() + self.sopConsoleHost + HttpClient.PATH_POST_IDFA)!
let dictionary: Dictionary<String,Any> = [
HttpClient.KEY_APP_ID: self.appId,
HttpClient.KEY_APP_MID: self.appMid,
HttpClient.KEY_TIME: Utility.getPosixTime(),
HttpClient.KEY_IDENTIFIER: IDFA.shared.identifier,
HttpClient.KEY_IS_AD_TRACKING_ENABLED: IDFA.shared.isAdvertisingTrackingEnabled
]
let JSONData = try! JSONSerialization.data(withJSONObject: dictionary, options: JSONSerialization.WritingOptions.prettyPrinted)
if let JSONString = String(data: JSONData, encoding: String.Encoding.utf8) {
SOPLog.debug(message: "request: POST \(url)")
let request = Request(url: url,
requestBody: JSONString,
httpMethod: .POST,
verifyHost: verifyHost)
request.addHeader(key: Request.CONTENT_TYPE, value: Request.APPLICATION_JSON)
request.addHeader(key: Request.X_SOP_SIG,
value: Authentication().createSignature(message: JSONString, key: secretKey))
request.addHeader(key: Request.USER_AGENT, value: Utility.getUserAgent())
request.post(completion: completion)
}
}
func getSurveyList(completion: @escaping (RequestResult) -> Void) {
getSurvey(with: HttpClient.PATH_GET_SURVEY, completion: completion)
}
func getSyncSurvey(completion: @escaping (RequestResult) -> Void) {
getSurvey(with: HttpClient.PATH_GET_SYNC_SURVEY, completion: completion)
}
private func getSurvey(with path: String, completion: @escaping (RequestResult) -> Void) {
if !Utility.isOnline() {
completion(RequestResult.failed(error: SOPError(message: "Network not available", type: .NetworkNotAvailable, response: nil, error: nil)))
return
}
var apiUrl = getProtocol() + self.sopHost + path
let populationDict: Dictionary<String,String> = [
HttpClient.KEY_APP_ID: self.appId,
HttpClient.KEY_APP_MID: self.appMid,
HttpClient.KEY_TIME: Utility.getPosixTime(),
HttpClient.KEY_SOP_AD_TRACKING: "1"
]
let sig = Authentication().createSignature(parameters: populationDict, key: self.secretKey)
var params = "?app_id=" + self.appId
params += "&app_mid=" + self.appMid
params += "&time=" + Utility.getPosixTime()
params += "&sop_ad_tracking=" + "1"
let paramSig = "&sig=" + sig
apiUrl += params + paramSig
SOPLog.debug(message: "request: GET \(apiUrl)")
let url = URL(string: apiUrl)!
let request = Request(url: url,
httpMethod: .GET,
verifyHost: verifyHost)
request.addHeader(key: Request.USER_AGENT, value: Utility.getUserAgent())
request.get(completion: completion)
}
func getProtocol() -> String {
if self.useHttps {
return HttpClient.HTTPS
}
return HttpClient.HTTP
}
}
| mit | 10b62601f9d4761d6b4a1a5759aadaa6 | 29.756579 | 144 | 0.652834 | 3.847737 | false | false | false | false |
SwiftCamp/SwiftPathToMastery | Generics/Generics Example/Starter/Generics Example/AppDelegate.swift | 1 | 3020 | //
// AppDelegate.swift
// Generics Example
//
// Created by João Mourato on 23/03/16.
// Copyright © 2016 iOSwiftCamp. All rights reserved.
//
import UIKit
enum API {
static let Name = "Name"
static let Id = "Id"
static let Title = "Title"
static let ListId = "ListId"
static let Done = "Done"
}
struct List {
let name: String
let id: Int
}
struct Todo {
let title: String
let listId: Int
let done: Bool
}
extension List {
init?(json: [String:AnyObject]){
guard let name = json[API.Name] as? String,
let id = json[API.Id] as? Int else { return nil }
self.name = name
self.id = id
}
}
extension Todo {
init?(json: [String:AnyObject]){
guard let title = json[API.Title] as? String,
let listId = json[API.ListId] as? Int,
let done = json[API.Done] as? Bool
else { return nil }
self.title = title
self.listId = listId
self.done = done
}
}
let listsURL = NSURL(string: "https://raw.githubusercontent.com/SwiftCamp/SwiftPathToMastery/Generics/master/persons.json")!
let todosURL = NSURL(string: "https://raw.githubusercontent.com/SwiftCamp/SwiftPathToMastery/Generics/master/0.json")!
func loadTodos () -> [Todo]? {
if let data = NSData(contentsOfURL: todosURL),
let json = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()),
let lists = json as? [[String:AnyObject]]{
return lists.flatMap(Todo.init)
}
return nil
}
func loadLists() -> [List]? {
if let data = NSData(contentsOfURL: listsURL),
let json = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()),
let lists = json as? [[String:AnyObject]]{
return lists.flatMap(List.init)
}
return nil
}
class TableVC: UITableViewController {
var items: [List] = [] {
didSet {
tableView.reloadData()
}
}
override func viewDidLoad() {
items = loadLists() ?? []
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: nil)
let item = items[indexPath.row]
cell.textLabel?.text = item.name
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let viewController = TableVC(style: .Plain)
let navigationController = UINavigationController(rootViewController: viewController)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
print(loadTodos())
testConformityToProtocol()
return true
}
}
| mit | 3bee8b5ac952a26c9d3aa04d361ee4f4 | 24.15 | 125 | 0.687541 | 4.089431 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/01376-swift-parser-parsetoken.swift | 1 | 869 | // 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
class a {
protocol b = b(Any) {
class func c<T) -> {
}
}
let t: U) -> {
}
var f : NSObject {
t: d = b() in return self.h = Swift.e = a<T) {
b: b {
class func e> {
}
func g() { c(c : P> {
}
}
var b() {
enum A : Range<T, T : T> U) -> Bool {
}
assert() {
if c {
i<U -> == c(f() -> {
}
class a : String)
}
}
protocol b {
struct S())
}
}
}
}
}
protocol a {
}
class a {
protocol c {
}
protocol a {
}
func c(T.b {
return ".Element>], e(m: A""a!
}
return { c()
}("
func a<S : a)
| apache-2.0 | f74433000838c64a3c478008d412c9c5 | 15.396226 | 79 | 0.605293 | 2.665644 | false | false | false | false |
SequencingDOTcom/oAuth2-demo | swift/demo-auth-swift/FilesViewController.swift | 4 | 9287 | //
// FilesViewController.swift
// Copyright © 2015-2016 Sequencing.com. All rights reserved.
//
import UIKit
// ADD THIS POD IMPORT
import sequencing_oauth_api_swift
class FilesViewController: UITableViewController {
let kMainQueue = dispatch_get_main_queue()
let FILE_DETAILS_CONTROLLER_SEGUE_ID = "SHOW_DETAILS"
var showDetailsButton = UIBarButtonItem()
var segmentView = UIView()
var fileTypePassed: String = ""
// files source
var filesArray = NSArray()
var sampleFilesArray = NSArray()
var ownFilesArray = NSArray()
// file type selection and row selection
var nowSelectedFileType = ""
var nowSelectedFileIndexPath: NSIndexPath?
// activity indicator with label
var messageFrame = UIView()
var activityIndicator = UIActivityIndicatorView()
var strLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "File selector"
self.tableView.setEditing(true, animated: true)
// showDetails button
self.showDetailsButton = UIBarButtonItem(title: "Details", style: UIBarButtonItemStyle.Done, target: self, action: "showDetails")
self.navigationItem.setRightBarButtonItem(self.showDetailsButton, animated: true)
self.showDetailsButton.enabled = false
// segmented control
let fileTypeSelection = UISegmentedControl.init(items: ["My Files", "Sample Files"])
fileTypeSelection.addTarget(self, action: "segmentControlAction:", forControlEvents: UIControlEvents.ValueChanged)
fileTypeSelection.sizeToFit()
self.navigationItem.titleView = fileTypeSelection
// select related segmentedIndex and load related own/sample files
if self.fileTypePassed.containsString("Sample") {
fileTypeSelection.selectedSegmentIndex = 1
self.nowSelectedFileType = "Sample"
self.loadSampleFiles()
} else {
fileTypeSelection.selectedSegmentIndex = 0
self.nowSelectedFileType = "My"
self.loadOwnFiles()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Actions
func segmentControlAction(sender: UISegmentedControl) -> Void {
self.nowSelectedFileIndexPath = nil
self.showDetailsButton.enabled = false
let emptyArray = NSArray()
self.filesArray = emptyArray
self.tableView.reloadData()
if sender.selectedSegmentIndex == 1 {
self.nowSelectedFileType = "Sample"
if self.sampleFilesArray.count > 0 {
self.filesArray = self.sampleFilesArray
self.reloadTableViewWithAnimation()
} else {
self.loadSampleFiles()
}
} else {
self.nowSelectedFileType = "My"
if self.ownFilesArray.count > 0 {
self.filesArray = self.ownFilesArray
self.reloadTableViewWithAnimation()
} else {
self.loadOwnFiles()
}
}
}
// MARK: - TableView getting source data
func loadSampleFiles() {
self.startActivityIndicatorWithTitle("Loading sample files")
SQAPI.instance.loadSampleFiles { (files) -> Void in
if files != nil {
dispatch_async(self.kMainQueue, { () -> Void in
self.sampleFilesArray = files!
self.filesArray = self.sampleFilesArray
self.stopActivityIndicator()
self.reloadTableViewWithAnimation()
})
} else {
self.stopActivityIndicator()
print("Can't load sample files")
}
}
}
func loadOwnFiles() {
self.startActivityIndicatorWithTitle("Loading my files")
SQAPI.instance.loadOwnFiles { (files) -> Void in
if files != nil {
dispatch_async(self.kMainQueue, { () -> Void in
self.ownFilesArray = files!
self.filesArray = self.ownFilesArray
self.stopActivityIndicator()
self.reloadTableViewWithAnimation()
})
} else {
self.stopActivityIndicator()
print("Can't load own files")
}
}
}
// MARK: - TableView delegates
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let demoText = self.filesArray.objectAtIndex(indexPath.row) as? NSDictionary {
let text = DemoDataCell.prepareText(demoText, FromFileType: self.nowSelectedFileType)
let height = DemoDataCell.heightForRow(text)
return height
} else {
return CGFloat()
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filesArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! DemoDataCell
if let demoText = self.filesArray.objectAtIndex(indexPath.row) as? NSDictionary {
let text = DemoDataCell.prepareText(demoText, FromFileType: self.nowSelectedFileType)
cell.demoTextLabel.text = text
cell.demoTextLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.tintColor = UIColor.blueColor()
}
return cell
}
func reloadTableViewWithAnimation() {
var indexPath:[NSIndexPath] = [NSIndexPath]()
for var i = 0; i < self.filesArray.count; i++ {
indexPath.append(NSIndexPath(forRow: i, inSection: 0))
}
self.tableView.beginUpdates()
self.tableView.insertRowsAtIndexPaths(indexPath, withRowAnimation: UITableViewRowAnimation.Top)
self.tableView.endUpdates()
}
// MARK: - Cells selection
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
// return UITableViewCellEditingStyle.None
return unsafeBitCast(3, UITableViewCellEditingStyle.self)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if self.nowSelectedFileIndexPath == nil {
self.nowSelectedFileIndexPath = indexPath
} else {
self.tableView.deselectRowAtIndexPath(self.nowSelectedFileIndexPath!, animated: true)
self.nowSelectedFileIndexPath = indexPath
}
self.showDetailsButton.enabled = true
}
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
self.nowSelectedFileIndexPath = nil
self.showDetailsButton.enabled = false
}
// MARK: - Navigation
func showDetails() {
self.performSegueWithIdentifier(self.FILE_DETAILS_CONTROLLER_SEGUE_ID, sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.destinationViewController.isKindOfClass(DetailsViewController) {
let destinationVC = segue.destinationViewController as! DetailsViewController
if let row = self.nowSelectedFileIndexPath?.row {
if let dict = self.filesArray.objectAtIndex(row) as? NSDictionary {
destinationVC.nowSelectedFile = dict
}
}
}
}
// MARK: - Activity indicator
func startActivityIndicatorWithTitle(title: String) -> Void {
dispatch_async(self.kMainQueue) { () -> Void in
self.strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 150, height: 50))
self.strLabel.font = UIFont.systemFontOfSize(13)
self.strLabel.text = title
self.strLabel.textColor = UIColor.grayColor()
self.messageFrame = UIView(frame: CGRect(x: self.tableView.frame.midX - 100, y: self.tableView.frame.midY - 100 , width: 250, height: 40))
self.messageFrame.layer.cornerRadius = 15
self.messageFrame.backgroundColor = UIColor.clearColor()
self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
self.activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
self.activityIndicator.startAnimating()
self.messageFrame.addSubview(self.activityIndicator)
self.messageFrame.addSubview(self.strLabel)
self.tableView.addSubview(self.messageFrame)
}
}
func stopActivityIndicator() -> Void {
dispatch_async(kMainQueue) { () -> Void in
self.activityIndicator.stopAnimating()
self.messageFrame.removeFromSuperview()
}
}
}
| mit | 39d85025d85af94f921c4ae019459780 | 36.747967 | 150 | 0.626319 | 5.345999 | false | false | false | false |
TrondKjeldas/KnxBasics2 | Source/KnxTelegram.swift | 1 | 8138 | //
// KnxTelegram.swift
// KnxBasics2
//
// The KnxBasics2 framework provides basic interworking with a KNX installation.
// Copyright © 2016 Trond Kjeldås ([email protected]).
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License Version 2.1
// as published by the Free Software Foundation.
//
// This library 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
import Foundation
/// Identifies the different KNX DPTs.
public enum KnxTelegramType {
/// Unknown/unspecified DPT.
case unknown
/// A generic 1-bit value in the range of DPT 1.001 - 1.022.
/// DPT1.001 - On/off
/// DPT1.002 - True/false
/// DPT1.003 - Enable/disable
/// DPT1.005 - Alarm/no alarm
/// DPT1.009 - Close/open
/// DPT1.015 - Reset/no action
case dpt1_xxx
/// Dimming control
case dpt3_007
/// Scaled value, range 0-100%.
case dpt5_001
/// Temperature, in degree celsius
case dpt9_001
/// Brightness
case dpt9_004
/// Wind
case dpt9_005
/// Time of day
case dpt10_001
/// Scene number
case dpt17_001
/// HVAC mode
case dpt20_102
/// Combined info, on/off
case dpt27_001
// Return type from string name
static func fromName(name: String) -> KnxTelegramType {
switch name {
case "DPT1.001": return .dpt1_xxx
case "DPT1.002": return .dpt1_xxx
case "DPT1.003": return .dpt1_xxx
case "DPT1.005": return .dpt1_xxx
case "DPT1.009": return .dpt1_xxx
case "DPT1.015": return .dpt1_xxx
case "DPT1.XXX": return .dpt1_xxx
case "DPT3.007": return .dpt3_007
case "DPT5.001": return .dpt5_001
case "DPT9.001": return .dpt9_001
case "DPT9.004": return .dpt9_004
case "DPT9.005": return .dpt9_005
case "DPT10.001": return .dpt10_001
case "DPT17.001": return .dpt17_001
case "DPT20.102": return .dpt20_102
case "DPT27.001": return .dpt27_001
default:
return .unknown
}
}
}
/// Class representing a KNX telegram.
open class KnxTelegram {
// MARK: Public API
/// Default initializer.
public init() {
_bytes = nil
_type = .unknown
}
/**
Intializes a telegram instance with the given data and type.
- parameter bytes: The payload to initialize the telegram with.
- parameter type: The DPT type to set for the telegram.
*/
public init(bytes: [UInt8], type: KnxTelegramType = .unknown) {
_bytes = bytes
_len = bytes.count
_type = type
if bytes.count >= 5 {
_groupAddress = UInt16(UInt16(bytes[3]) << 8 | UInt16(bytes[4]))
}
}
/**
Returns the group address of the telegram.
*/
open func getGroupAddress() -> KnxGroupAddress {
return KnxGroupAddress(fromUInt16: _groupAddress)
}
/**
Returns the data value in the telegram as a specific DPT.
- parameter type: DPT type to decode the telegram according to.
- returns: The decoded value as an integer.
- throws: IllformedTelegramForType, UnknownTelegramType
*/
open func getValueAsType(type: KnxTelegramType) throws -> Int {
switch type {
case .dpt1_xxx:
if _bytes!.count != 8 {
throw KnxException.illformedTelegramForType
}
return Int(_bytes![7] & 0x1)
case .dpt3_007:
if _bytes!.count != 8 {
throw KnxException.illformedTelegramForType
}
var returnValue: Int = 0
let inc = (_bytes![7] & 0x08) == 0x08
let stepcode = Int(_bytes![7] & 0x07)
if stepcode == 0 {
// Stop!
returnValue = 0
} else {
// Go!
let steps = 1 << (stepcode-1)
if inc {
returnValue = steps
} else {
returnValue = -steps
}
}
return returnValue
case .dpt5_001:
if _bytes!.count != 9 {
throw KnxException.illformedTelegramForType
}
let dimVal = Int(_bytes![8] & 0xff)
return (dimVal * 100) / 255
default:
throw KnxException.unknownTelegramType
}
}
/**
Returns the data value in the telegram as a specific DPT.
- parameter type: DPT type to decode the telegram according to.
- returns: The decoded value as a float.
- throws: IllformedTelegramForType, UnknownTelegramType
*/
open func getValueAsType(type: KnxTelegramType) throws -> Double {
switch type {
case .dpt9_001: fallthrough
case .dpt9_004: fallthrough
case .dpt9_005:
if _bytes!.count != 10 {
throw KnxException.illformedTelegramForType
}
//FloatValue = (0,01*M)*2(E)
//E = [0 ... 15]
//M = [-2 048 ... 2 047], two’s complement notation
//For all Datapoint Types 9.xxx, the encoded value 7FFFh shall always be used to denote invalid data.
let val: UInt16 = (UInt16(_bytes![9] & 0xff) | (UInt16(_bytes![8] & 0xff)<<8))
let sign = ((val & 0x8000) >> 15)
let exp = (val & 0x7800) >> 11
var mantissa: Int32 = Int32(val & 0x7FF)
if sign == 1 {
mantissa = 2048 - mantissa
mantissa = -mantissa
}
let twoExp = Int32(1 << exp)
mantissa *= twoExp
let floatVal = Double(mantissa) * 0.01
return floatVal
default:
throw KnxException.unknownTelegramType
}
}
/**
Returns the data value in the telegram as a specific DPT.
- parameter type: DPT type to decode the telegram according to.
- returns: The decoded value as a string.
- throws: IllformedTelegramForType, UnknownTelegramType
*/
open func getValueAsType(type: KnxTelegramType) throws -> String {
switch type {
case .dpt10_001:
if _bytes!.count != 11 {
throw KnxException.illformedTelegramForType
}
let days = ["??", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
let day = Int((_bytes![8] & 0xE0) >> 5)
let hour = (_bytes![8] & 0x1F)
let minutes = (_bytes![9] & 0x3F)
let seconds = (_bytes![10] & 0x3F)
let time = String(format: "%@ %.2d:%.2d:%.2d",
days[day], hour, minutes, seconds)
return time
default:
throw KnxException.unknownTelegramType
}
}
/// Read-only property indicating whether the telegram contains a
/// write request or value response, i.e. not a read request.
open var isWriteRequestOrValueResponse: Bool {
guard let bytes = _bytes else {
return false
}
if bytes.count >= 7 {
return ((bytes[6] & 0x03 == 0x00)
&& ((bytes[7] & 0xC0 == 0x80)) // write request
|| ((bytes[7] & 0xC0 == 0x40))) // value response
} else {
return false
}
}
// MARK: Internal and private declarations
fileprivate var _bytes: [UInt8]?
fileprivate var _len: Int = 0
fileprivate var _type: KnxTelegramType
fileprivate var _groupAddress: UInt16 = 0
internal var payload: [UInt8] { return _bytes! }
}
| lgpl-2.1 | 5a58666863ecc3fbe434989f32a50778 | 26.113333 | 113 | 0.55729 | 3.884432 | false | false | false | false |
DanijelHuis/HDAugmentedReality | HDAugmentedReality/Classes/Main/Presenter/ARPresenterTransform.swift | 1 | 5999 | //
// ARPresenter+Stacking.swift
// HDAugmentedRealityDemo
//
// Created by Danijel Huis on 13/04/2017.
// Copyright © 2017 Danijel Huis. All rights reserved.
//
import Foundation
import UIKit
/**
Responsible for transform/layout of annotations, usually after they have been layouted by ARPresenter.
e.g. stacking.
ARPresenterTransform can change arPositionOffset of annotations, or set transform.
*/
public protocol ARPresenterTransform: class
{
/// ARresenter, it is set when setting presenterTransform on presenter.
var arPresenter: ARPresenter! { set get }
func preLayout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
func postLayout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
}
open class ARPresenterStackTransform: ARPresenterTransform
{
open weak var arPresenter: ARPresenter!
public init() {}
public func preLayout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
{
}
public func postLayout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
{
if needsRelayout
{
self.stackAnnotationViews()
}
}
/**
Stacks annotationViews vertically if they are overlapping. This works by comparing frames of annotationViews.
This must be called if parameters that affect relative x,y of annotations changed.
- if azimuths on annotations are calculated(This can change relative horizontal positions of annotations)
- when adjustVerticalOffsetParameters is called because that can affect relative vertical positions of annotations
Pitch/heading of the device doesn't affect relative positions of annotationViews.
*/
open func stackAnnotationViews()
{
guard self.arPresenter.annotationViews.count > 0 else { return }
guard let arStatus = self.arPresenter.arViewController?.arStatus else { return }
// Sorting makes stacking faster
let sortedAnnotationViews = self.arPresenter.annotationViews.sorted(by: { $0.frame.origin.y > $1.frame.origin.y })
let centerX = self.arPresenter.bounds.size.width * 0.5
let totalWidth = CGFloat( arStatus.hPixelsPerDegree * 360 )
let rightBorder = centerX + totalWidth / 2
let leftBorder = centerX - totalWidth / 2
// This is simple brute-force comparing of frames, compares annotationView1 to all annotationsViews beneath(before) it, if overlap is found,
// annotationView1 is moved above it. This is done until annotationView1 is not overlapped by any other annotationView beneath it. Then it moves to
// the next annotationView.
for annotationView1 in sortedAnnotationViews
{
//===== Alternate frame
// Annotation views are positioned left(0° - -180°) and right(0° - 180°) from the center of the screen. So if annotationView1
// is on -180°, its x position is ~ -6000px, and if annoationView2 is on 180°, its x position is ~ 6000px. These two annotationViews
// are basically on the same position (180° = -180°) but simply by comparing frames -6000px != 6000px we cannot know that.
// So we are construcing alternate frame so that these near-border annotations can "see" each other.
var hasAlternateFrame = false
let left = annotationView1.frame.origin.x;
let right = left + annotationView1.frame.size.width
// Assuming that annotationViews have same width
if right > (rightBorder - annotationView1.frame.size.width)
{
annotationView1.arAlternateFrame = annotationView1.frame
annotationView1.arAlternateFrame.origin.x = annotationView1.frame.origin.x - totalWidth
hasAlternateFrame = true
}
else if left < (leftBorder + annotationView1.frame.size.width)
{
annotationView1.arAlternateFrame = annotationView1.frame
annotationView1.arAlternateFrame.origin.x = annotationView1.frame.origin.x + totalWidth
hasAlternateFrame = true
}
//====== Detecting collision
var hasCollision = false
let y = annotationView1.frame.origin.y;
var i = 0
while i < sortedAnnotationViews.count
{
let annotationView2 = sortedAnnotationViews[i]
if annotationView1 == annotationView2
{
// If collision, start over because movement could cause additional collisions
if hasCollision
{
hasCollision = false
i = 0
continue
}
break
}
let collision = annotationView1.frame.intersects(annotationView2.frame)
if collision
{
annotationView1.frame.origin.y = annotationView2.frame.origin.y - annotationView1.frame.size.height - 5
annotationView1.arAlternateFrame.origin.y = annotationView1.frame.origin.y
hasCollision = true
}
else if hasAlternateFrame && annotationView1.arAlternateFrame.intersects(annotationView2.frame)
{
annotationView1.frame.origin.y = annotationView2.frame.origin.y - annotationView1.frame.size.height - 5
annotationView1.arAlternateFrame.origin.y = annotationView1.frame.origin.y
hasCollision = true
}
i = i + 1
}
annotationView1.arPositionOffset.y = annotationView1.frame.origin.y - y;
}
}
}
| mit | 0c2cfbcc4a64d45bdb076dc63f62abdb | 42.722628 | 155 | 0.63172 | 5.01675 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.