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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
szpnygo/firefox-ios | Account/FxALoginStateMachine.swift | 20 | 9110 | /* 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 FxA
import Shared
import XCGLogger
// TODO: log to an FxA-only, persistent log file.
private let log = XCGLogger.defaultInstance()
// TODO: fill this in!
private let KeyUnwrappingError = NSError(domain: "org.mozilla", code: 1, userInfo: nil)
protocol FxALoginClient {
func keyPair() -> Deferred<Result<KeyPair>>
func keys(keyFetchToken: NSData) -> Deferred<Result<FxAKeysResponse>>
func sign(sessionToken: NSData, publicKey: PublicKey) -> Deferred<Result<FxASignResponse>>
}
extension FxAClient10: FxALoginClient {
func keyPair() -> Deferred<Result<KeyPair>> {
let result = RSAKeyPair.generateKeyPairWithModulusSize(2048) // TODO: debate key size and extract this constant.
return Deferred(value: Result(success: result))
}
}
class FxALoginStateMachine {
let client: FxALoginClient
// The keys are used as a set, to prevent cycles in the state machine.
var stateLabelsSeen = [FxAStateLabel: Bool]()
init(client: FxALoginClient) {
self.client = client
}
func advanceFromState(state: FxAState, now: Timestamp) -> Deferred<FxAState> {
stateLabelsSeen.updateValue(true, forKey: state.label)
return self.advanceOneState(state, now: now).bind { (newState: FxAState) in
let labelAlreadySeen = self.stateLabelsSeen.updateValue(true, forKey: newState.label) != nil
if labelAlreadySeen {
// Last stop!
return Deferred(value: newState)
}
return self.advanceFromState(newState, now: now)
}
}
private func advanceOneState(state: FxAState, now: Timestamp) -> Deferred<FxAState> {
// For convenience. Without type annotation, Swift complains about types not being exact.
let separated: Deferred<FxAState> = Deferred(value: SeparatedState())
let doghouse: Deferred<FxAState> = Deferred(value: DoghouseState())
let same: Deferred<FxAState> = Deferred(value: state)
log.info("Advancing from state: \(state.label.rawValue)")
switch state.label {
case .Married:
let state = state as! MarriedState
log.debug("Checking key pair freshness.")
if state.isKeyPairExpired(now) {
log.info("Key pair has expired; transitioning to CohabitingBeforeKeyPair.")
return advanceOneState(state.withoutKeyPair(), now: now)
}
log.debug("Checking certificate freshness.")
if state.isCertificateExpired(now) {
log.info("Certificate has expired; transitioning to CohabitingAfterKeyPair.")
return advanceOneState(state.withoutCertificate(), now: now)
}
log.info("Key pair and certificate are fresh; staying Married.")
return same
case .CohabitingBeforeKeyPair:
let state = state as! CohabitingBeforeKeyPairState
log.debug("Generating key pair.")
return self.client.keyPair().bind { result in
if let keyPair = result.successValue {
log.info("Generated key pair! Transitioning to CohabitingAfterKeyPair.")
let newState = CohabitingAfterKeyPairState(sessionToken: state.sessionToken,
kA: state.kA, kB: state.kB,
keyPair: keyPair, keyPairExpiresAt: now + OneMonthInMilliseconds)
return Deferred(value: newState)
} else {
log.error("Failed to generate key pair! Something is horribly wrong; transitioning to Separated in the hope that the error is transient.")
return separated
}
}
case .CohabitingAfterKeyPair:
let state = state as! CohabitingAfterKeyPairState
log.debug("Signing public key.")
return client.sign(state.sessionToken, publicKey: state.keyPair.publicKey).bind { result in
if let response = result.successValue {
log.info("Signed public key! Transitioning to Married.")
let newState = MarriedState(sessionToken: state.sessionToken,
kA: state.kA, kB: state.kB,
keyPair: state.keyPair, keyPairExpiresAt: state.keyPairExpiresAt,
certificate: response.certificate, certificateExpiresAt: now + OneDayInMilliseconds)
return Deferred(value: newState)
} else {
if let error = result.failureValue as? FxAClientError {
switch error {
case let .Remote(remoteError):
if remoteError.isUpgradeRequired {
log.error("Upgrade required: \(error.description)! Transitioning to Doghouse.")
return doghouse
} else if remoteError.isInvalidAuthentication {
log.error("Invalid authentication: \(error.description)! Transitioning to Separated.")
return separated
} else if remoteError.code < 200 || remoteError.code >= 300 {
log.error("Unsuccessful HTTP request: \(error.description)! Assuming error is transient and not transitioning.")
return same
} else {
log.error("Unknown error: \(error.description). Transitioning to Separated.")
return separated
}
default:
break
}
}
log.error("Unknown error: \(result.failureValue!). Transitioning to Separated.")
return separated
}
}
case .EngagedBeforeVerified, .EngagedAfterVerified:
let state = state as! ReadyForKeys
log.debug("Fetching keys.")
return client.keys(state.keyFetchToken).bind { result in
if let response = result.successValue {
if let kB = response.wrapkB.xoredWith(state.unwrapkB) {
log.info("Unwrapped keys response. Transition to CohabitingBeforeKeyPair.")
let newState = CohabitingBeforeKeyPairState(sessionToken: state.sessionToken,
kA: response.kA, kB: kB)
return Deferred(value: newState)
} else {
log.error("Failed to unwrap keys response! Transitioning to Separated in order to fetch new initial datum.")
return separated
}
} else {
if let error = result.failureValue as? FxAClientError {
log.error("Error \(error.description) \(error.description)")
switch error {
case let .Remote(remoteError):
if remoteError.isUpgradeRequired {
log.error("Upgrade required: \(error.description)! Transitioning to Doghouse.")
return doghouse
} else if remoteError.isInvalidAuthentication {
log.error("Invalid authentication: \(error.description)! Transitioning to Separated in order to fetch new initial datum.")
return separated
} else if remoteError.isUnverified {
log.warning("Account is not yet verified; not transitioning.")
return same
} else if remoteError.code < 200 || remoteError.code >= 300 {
log.error("Unsuccessful HTTP request: \(error.description)! Assuming error is transient and not transitioning.")
return same
} else {
log.error("Unknown error: \(error.description). Transitioning to Separated.")
return separated
}
default:
break
}
}
log.error("Unknown error: \(result.failureValue!). Transitioning to Separated.")
return separated
}
}
case .Separated, .Doghouse:
// We can't advance from the separated state (we need user input) or the doghouse (we need a client upgrade).
log.warning("User interaction required; not transitioning.")
return same
}
}
}
| mpl-2.0 | d8df7ed91b72005efe4a1eefef109924 | 50.468927 | 159 | 0.55719 | 5.722362 | false | false | false | false |
rikwatson/host | host/messageHandler.swift | 1 | 5488 | // messageHandler.swift
// host
//
// Created by Rik Watson on 11/09/2017.
// Copyright © 2017 Rik Watson. All rights reserved.
//
import Foundation
import WebKit
import Zip
import os.log
class messageHandler:NSObject, WKScriptMessageHandler {
var appWebView:WKWebView?
/*
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
if let url = Bundle.main.url(forResource: "file", withExtension: "txt")
{
do
{
let contents = try String(contentsOfFile: url.path)
webView.loadHTMLString(contents, baseURL: url.deletingLastPathComponent())
}
catch
{
print("Could not load the HTML string.")
}
}
}
}
*/
var logString = ""
init(theController:ViewController){
super.init()
let theConfiguration = WKWebViewConfiguration()
// let unzipDirectory: URL = getWwwRoot()
theConfiguration.userContentController.add(self, name: "native")
appWebView = WKWebView(frame: theController.view.frame, configuration: theConfiguration)
/*
let zipURL = URL(fileURLWithPath: "wwwroot/index.html", relativeTo: unzipDirectory as URL?)
os_log ("zipURL = %{public}@", zipURL.absoluteString )
my_log ("zipURL = " + zipURL.absoluteString )
let request = URLRequest(url: zipURL) // unzipDirectory)
my_log ("Request is " + request.debugDescription)
my_log("Hello!")
*/
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html")
let htmlUrl = URL(fileURLWithPath: htmlPath!, isDirectory: false)
let request = URLRequest(url: htmlUrl)
// appWebView!.loadFileURL(zipURL, allowingReadAccessTo: zipURL)
// appWebView!.navigationDelegate = self
appWebView!.load(request)
theController.view.addSubview(appWebView!)
}
func my_log(_ str: String) {
os_log ("%{public}@", str)
let viewportString = "<meta name='viewport' content='width=device-width'><meta name='viewport' content='initial-scale=1.0'>"
logString += ("<pre>"+str+"</pre>")
if (appWebView != nil) {
appWebView!.loadHTMLString("<html>"+viewportString+"<body>"+logString+"</body></html>", baseURL: nil)
}
}
func getWwwRoot() -> URL {
var unzipDirectory: URL
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html")
my_log ("htmlPath = \(htmlPath!)" )
let htmlUrl = URL(fileURLWithPath: htmlPath!, isDirectory: false)
my_log ("htmlUrl = \(htmlUrl)" )
my_log ("Start doUnzip")
do {
let filePath = Bundle.main.url(forResource: "wwwroot", withExtension: "zip")!
unzipDirectory = try Zip.quickUnzipFile(filePath) // Unzip
my_log ("unzipDirectory = \(unzipDirectory)")
// let zipFilePath = try Zip.quickZipFiles([filePath], fileName: "archive") // Zip
}
catch {
my_log("Something went wrong")
return htmlUrl
}
my_log ("End doUnzip")
return unzipDirectory
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
let sentData = message.body as! NSDictionary
print("SentData")
print(sentData)
let command = sentData["cmd"] as! String
var response = Dictionary<String,AnyObject>()
if command == "increment" {
guard var count = sentData["count"] as? Int else {
return
}
count += 1
response["count"] = count as AnyObject
}
let callbackString = sentData["callbackFunc"] as? String
sendResponse(aResponse: response, callback: callbackString)
}
func sendResponse(aResponse:Dictionary<String,AnyObject>, callback:String?){
print("Send Response")
print(aResponse)
print("to")
print(callback as Any)
guard let callbackString = callback else {
return
}
guard let generatedJSONData = try? JSONSerialization.data(withJSONObject: aResponse, options: JSONSerialization.WritingOptions(rawValue: 0)) else {
print("failed to generate JSON for \(aResponse)")
return
}
let script = "(\(callbackString)('\(String(data:generatedJSONData, encoding: .utf8)!)'))"
appWebView!.evaluateJavaScript(script){(JSReturnValue:Any?, error:Error?) in
if let errorDescription = error?.localizedDescription {
print("returned value: \(errorDescription)")
} else if JSReturnValue != nil {
print("returned value: \(JSReturnValue!)")
} else {
print("no return from JS")
}
}
}
}
| apache-2.0 | da42c36d697cbaa2fb1d9d1d4144129f | 28.659459 | 155 | 0.564972 | 4.965611 | false | false | false | false |
a770322699/YQKit | Swift/YQKit/YQView.swift | 1 | 2027 | //
// YQView.swift
// BiuBiu
//
// Created by meizu on 2018/4/3.
// Copyright © 2018年 meizu. All rights reserved.
//
import Foundation
import UIKit
// MARK: 坐标
extension YQValue where Value == UIView {
var origin: CGPoint {
get {
return value.frame.origin
}
set {
value.frame.origin = newValue
}
}
var x: CGFloat {
get {
return origin.x
}
set {
origin.x = newValue
}
}
var y: CGFloat {
get {
return origin.y
}
set {
origin.y = newValue
}
}
var maxY: CGFloat{
get {
return value.frame.maxY
}
set {
y = newValue - height
}
}
var maxX: CGFloat {
get {
return value.frame.maxX
}
set {
x = newValue - width
}
}
var size: CGSize {
set {
value.frame.size = newValue
}
get {
return value.frame.size
}
}
var height: CGFloat {
get {
return size.height
}
set {
size.height = newValue
}
}
var width: CGFloat{
get {
return size.width
}
set {
size.width = newValue
}
}
var center: CGPoint{
get {
return CGPoint.init(x: width / 2, y: height / 2)
}
set {
origin = CGPoint.init(x: newValue.x - width / 2, y: newValue.y - height / 2)
}
}
}
extension YQValue where Value == UIView {
func boarderRadiusMask(radius: CGFloat, borderWidth: CGFloat = 0, borderColor: UIColor? = nil, mask: Bool = false) {
value.layer.cornerRadius = radius
value.layer.masksToBounds = mask
value.layer.borderWidth = borderWidth
value.layer.borderColor = borderColor?.cgColor
}
}
| mit | 7d133b0f26d54e92522e872de3a7d09c | 17.878505 | 120 | 0.458416 | 4.372294 | false | false | false | false |
alexcomu/swift3-tutorial | 12-webRequest/12-webRequest/Constants.swift | 1 | 717 | //
// Constants.swift
// 12-webRequest
//
// Created by Alex Comunian on 19/01/17.
// Copyright © 2017 Alex Comunian. All rights reserved.
//
import Foundation
let BASE_URL = "http://api.openweathermap.org/data/2.5/weather?"
let BASE_URL_FORECAST = "http://api.openweathermap.org/data/2.5/forecast/daily?cnt=10&mode=json&"
let LATITUDE = "lat=\(Location.sharedInstance.latitude!)"
let LONGITUDE = "&lon=\(Location.sharedInstance.longitude!)"
let APP_ID = "&appid="
let API_KEY = "YOUR-APP-ID"
typealias DownloadComplete = () -> ()
let CURRENT_WEATHER_URL = "\(BASE_URL)\(LATITUDE)\(LONGITUDE)\(APP_ID)\(API_KEY)"
let FOREACAST_WEATHER_URL = "\(BASE_URL_FORECAST)\(LATITUDE)\(LONGITUDE)\(APP_ID)\(API_KEY)"
| mit | 36f01d1b97be8a83d40077491b062ac3 | 30.130435 | 97 | 0.698324 | 3.046809 | false | false | false | false |
amitburst/Palettes | Palettes/ViewController.swift | 1 | 14631 | //
// ViewController.swift
// Palettes
//
// Created by Amit Burstein on 11/26/14.
// Copyright (c) 2014 Amit Burstein. All rights reserved.
//
import Cocoa
class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate, NSWindowDelegate {
// MARK: Properties
let DefaultNumResults = 20
let RowHeight = 110
let PaletteViewCornerRadius = 5
let CopiedViewAnimationSpringBounciness = 20
let CopiedViewAnimationSpringSpeed = 15
let CopiedViewReverseAnimationSpringBounciness = 10
let CopiedViewReverseAnimationSpringSpeed = 15
let CopiedViewAnimationToValue = -20
let CopiedViewReverseAnimationToValue = -40
let CopiedViewHeight = 40
let CopiedViewBackgroundColor = "#67809FF5"
let CopiedViewText = "Copied!"
let CopiedViewTextSize = 12
let CopiedViewTextColor = "#ECF0F1"
let TableTextHeight = 40
let TableTextSize = 16
let TableTextColor = "#bdc3c7"
let TableTextNoResults = "No Results Found"
let TableTextError = "Error Loading Palettes :("
let PaletteViewBorderColor = NSColor.gridColor().CGColor
let PaletteViewBorderWidth = 0.2
let PaletteCellIdentifier = "PaletteCell"
let CopyTypeKey = "CopyType"
let PalettesEndpoint = "http://www.colourlovers.com/api/palettes"
let TopPalettesEndpoint = "http://www.colourlovers.com/api/palettes/top"
var manager: AFHTTPRequestOperationManager!
var preferences: NSUserDefaults!
var showingTopPalettes: Bool!
var scrolledToBottom: Bool!
var noResults: Bool!
var lastEndpoint: String!
var lastParams: [String:String]!
var resultsPage: Int!
var palettes: [Palette]!
var copyType: Int!
var copiedView: NSView!
var copiedViewAnimation: POPSpringAnimation!
var copiedViewReverseAnimation: POPSpringAnimation!
var fadeAnimation: POPBasicAnimation!
var fadeReverseAnimation: POPBasicAnimation!
var tableText: NSTextField!
@IBOutlet weak var tableView: MainTableView!
@IBOutlet weak var scrollView: NSScrollView!
// MARK: Structs
struct Palette {
var url: String
var colors: [String]
var title: String
}
// MARK: Initialization
required init?(coder: NSCoder) {
super.init(coder: coder)
manager = AFHTTPRequestOperationManager()
preferences = NSUserDefaults.standardUserDefaults()
showingTopPalettes = true
scrolledToBottom = false
noResults = false
lastEndpoint = ""
lastParams = [String:String]()
resultsPage = 0
palettes = []
copyType = 0
copiedView = NSView()
copiedViewAnimation = POPSpringAnimation()
copiedViewReverseAnimation = POPSpringAnimation()
fadeAnimation = POPBasicAnimation()
fadeReverseAnimation = POPBasicAnimation()
tableText = NSTextField()
}
// MARK: NSViewController
override func viewDidLoad() {
super.viewDidLoad()
let window = NSApplication.sharedApplication().windows[0] as NSWindow
window.delegate = self
NSNotificationCenter.defaultCenter().addObserver(self, selector: "scrollViewDidScroll:", name: NSViewBoundsDidChangeNotification, object: scrollView.contentView)
setupCopiedView()
setupTableText()
setupAnimations()
getPalettes(endpoint: TopPalettesEndpoint, params: nil)
}
override func viewDidAppear() {
if let lastCopyType = preferences.valueForKey(CopyTypeKey) as? Int {
copyType = lastCopyType
let window = NSApplication.sharedApplication().windows[0] as NSWindow
window.delegate = self
let popUpButton = window.toolbar?.items[1].view? as NSPopUpButton
popUpButton.selectItemAtIndex(copyType)
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: NSTableViewDataSource
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return palettes.count
}
// MARK: NSTableViewDelegate
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return CGFloat(RowHeight)
}
func tableView(tableView: NSTableView, selectionIndexesForProposedSelection proposedSelectionIndexes: NSIndexSet) -> NSIndexSet {
return NSIndexSet()
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
// Create and get references to other important items
let cell = tableView.makeViewWithIdentifier(PaletteCellIdentifier, owner: self) as PaletteTableCellView
let paletteView = cell.paletteView
let openButton = cell.openButton
let palette = palettes[row]
// Set cell properties
cell.textField?.stringValue = palette.title
cell.colors = palette.colors
cell.url = palette.url
cell.addTrackingArea(NSTrackingArea(rect: NSZeroRect, options: .ActiveInActiveApp | .InVisibleRect | .MouseEnteredAndExited, owner: cell, userInfo: nil))
// Set cell's open button properties
cell.openButton.wantsLayer = true
cell.openButton.layer?.opacity = 0
// Set cell's palette view properties
paletteView.wantsLayer = true
paletteView.layer?.cornerRadius = CGFloat(PaletteViewCornerRadius)
paletteView.layer?.borderColor = PaletteViewBorderColor
paletteView.layer?.borderWidth = CGFloat(PaletteViewBorderWidth)
paletteView.subviews = []
paletteView.addTrackingArea(NSTrackingArea(rect: NSZeroRect, options: .ActiveAlways | .InVisibleRect | .CursorUpdate, owner: cell, userInfo: nil))
// Calculate width and height of each color view
let colorViewWidth = ceil(paletteView.bounds.width / CGFloat(cell.colors.count))
let colorViewHeight = paletteView.bounds.height
// Create and append color views to palette view
for i in 0..<cell.colors.count {
let colorView = NSView(frame: CGRectMake(CGFloat(i) * colorViewWidth, 0, colorViewWidth, colorViewHeight))
colorView.wantsLayer = true
colorView.layer?.backgroundColor = NSColor(rgba: "#\(cell.colors[i])").CGColor
paletteView.addSubview(colorView)
}
return cell
}
// MARK: IBActions
@IBAction func searchFieldChanged(searchField: NSSearchField!) {
resultsPage = 0
if searchField.stringValue == "" {
if !showingTopPalettes {
getPalettes(endpoint: TopPalettesEndpoint, params: nil)
showingTopPalettes = true
}
} else {
if let match = searchField.stringValue.rangeOfString("^#?[0-9a-fA-F]{6}$", options: .RegularExpressionSearch) {
var query = searchField.stringValue
if query.hasPrefix("#") {
query = query[1...6]
}
getPalettes(endpoint: PalettesEndpoint, params: ["hex": query])
} else {
getPalettes(endpoint: PalettesEndpoint, params: ["keywords": searchField.stringValue])
}
showingTopPalettes = false
}
}
@IBAction func copyTypeChanged(button: NSPopUpButton!) {
copyType = button.indexOfSelectedItem
preferences.setInteger(copyType, forKey: CopyTypeKey)
preferences.synchronize()
}
// MARK: Functions
func setupCopiedView() {
// Set up copied view text
let copiedViewTextField = NSTextField(frame: CGRectMake(0, 0, view.bounds.width, CGFloat(CopiedViewHeight)))
copiedViewTextField.bezeled = false
copiedViewTextField.drawsBackground = false
copiedViewTextField.editable = false
copiedViewTextField.selectable = false
copiedViewTextField.alignment = .CenterTextAlignment
copiedViewTextField.textColor = NSColor(rgba: CopiedViewTextColor)
copiedViewTextField.font = NSFont.boldSystemFontOfSize(CGFloat(CopiedViewTextSize))
copiedViewTextField.stringValue = CopiedViewText
// Set up copied view
copiedView = NSView(frame: CGRectMake(0, CGFloat(-CopiedViewHeight), view.bounds.width, CGFloat(CopiedViewHeight)))
copiedView.addSubview(copiedViewTextField)
copiedView.wantsLayer = true
copiedView.layer?.backgroundColor = NSColor(rgba: CopiedViewBackgroundColor).CGColor
view.addSubview(copiedView)
}
func setupTableText() {
// Set up table text
tableText = NSTextField(frame: CGRectMake(0, view.bounds.height / 2 - CGFloat(TableTextHeight) / 4, view.bounds.width, CGFloat(TableTextHeight)))
tableText.bezeled = false
tableText.drawsBackground = false
tableText.editable = false
tableText.selectable = false
tableText.alignment = .CenterTextAlignment
tableText.textColor = NSColor(rgba: TableTextColor)
tableText.font = NSFont.boldSystemFontOfSize(CGFloat(TableTextSize))
}
func setupAnimations() {
// Set up copied view animation
copiedViewAnimation.property = POPAnimatableProperty.propertyWithName(kPOPLayerPositionY) as POPAnimatableProperty
copiedViewAnimation.toValue = CopiedViewAnimationToValue
copiedViewAnimation.springBounciness = CGFloat(CopiedViewAnimationSpringBounciness)
copiedViewAnimation.springSpeed = CGFloat(CopiedViewAnimationSpringSpeed)
// Set up copied view reverse animation
copiedViewReverseAnimation.property = POPAnimatableProperty.propertyWithName(kPOPLayerPositionY) as POPAnimatableProperty
copiedViewReverseAnimation.toValue = CopiedViewReverseAnimationToValue
copiedViewReverseAnimation.springBounciness = CGFloat(CopiedViewReverseAnimationSpringBounciness)
copiedViewReverseAnimation.springSpeed = CGFloat(CopiedViewReverseAnimationSpringSpeed)
// Set up fade animation
fadeAnimation.property = POPAnimatableProperty.propertyWithName(kPOPLayerOpacity) as POPAnimatableProperty
fadeAnimation.fromValue = 0
fadeAnimation.toValue = 1
// Set up fade reverse animation
fadeReverseAnimation.property = POPAnimatableProperty.propertyWithName(kPOPLayerOpacity) as POPAnimatableProperty
fadeReverseAnimation.fromValue = 1
fadeReverseAnimation.toValue = 0
}
func getPalettes(#endpoint: String, params: [String:String]?) {
// Add default keys to params
var params = params
if params == nil {
params = [String:String]()
}
params?.updateValue("json", forKey: "format")
params?.updateValue(String(DefaultNumResults), forKey: "numResults")
// No request if endpoint ans params are unchanged
if endpoint == lastEndpoint && params! == lastParams {
return
}
// Make the request
manager.GET(endpoint, parameters: params, success: { operation, responseObject in
// Save the latest endpoint and params
self.lastEndpoint = "\(operation.request.URL.scheme!)://\(operation.request.URL.host!)\(operation.request.URL.path!)"
self.lastParams = params!
// Parse the response object
if let jsonArray = responseObject as? [NSDictionary] {
// Remove all palettes if this is a new query
if params?.indexForKey("resultOffset") == nil {
self.palettes.removeAll()
}
// Keep track of whether any results were returned
// Show and hide table text accordingly
self.noResults = jsonArray.count == 0
if self.noResults! {
if params?.indexForKey("resultOffset") == nil {
self.showErrorMessage(self.TableTextNoResults)
}
return
} else {
self.tableText.removeFromSuperview()
self.tableText.layer?.pop_addAnimation(self.fadeReverseAnimation, forKey: nil)
}
// Parse JSON for each palette and add to palettes array
for paletteInfo in jsonArray {
let url = paletteInfo.objectForKey("url") as? String
let colors = paletteInfo.objectForKey("colors") as? [String]
let title = paletteInfo.objectForKey("title") as? String
self.palettes.append(Palette(url: url!, colors: colors!, title: title!))
}
// Reload table in main queue and scroll to top if this is a new query
dispatch_async(dispatch_get_main_queue(), {
if params?.indexForKey("resultOffset") == nil {
self.tableView.scrollRowToVisible(0)
self.tableView.layer?.pop_addAnimation(self.fadeAnimation, forKey: nil)
} else {
self.scrolledToBottom = false
}
self.tableView.reloadData()
})
} else {
self.showErrorMessage(self.TableTextError)
}
}) { _, _ in
self.showErrorMessage(self.TableTextError)
}
}
func showErrorMessage(errorMessage: String) {
palettes.removeAll()
tableText.stringValue = errorMessage
view.addSubview(tableText)
tableText.layer?.pop_addAnimation(fadeAnimation, forKey: nil)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
self.tableView.layer?.pop_addAnimation(self.fadeReverseAnimation, forKey: nil)
})
}
func scrollViewDidScroll(notification: NSNotification) {
let currentPosition = CGRectGetMaxY(scrollView.contentView.visibleRect)
let contentHeight = tableView.bounds.size.height - 5;
if !noResults && !scrolledToBottom && currentPosition > contentHeight - 2 {
scrolledToBottom = true
resultsPage = resultsPage + 1
var params = lastParams
params.updateValue(String(DefaultNumResults * resultsPage), forKey: "resultOffset")
getPalettes(endpoint: lastEndpoint, params: params)
}
}
}
| mit | 446b5187f5652fe87b9d1a02c110185a | 40.447592 | 169 | 0.647051 | 5.312636 | false | false | false | false |
ThumbWorks/i-meditated | Pods/RxTests/RxTests/Any+Equatable.swift | 4 | 920 | //
// Any+Equatable.swift
// Rx
//
// Created by Krunoslav Zaher on 12/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
A way to use built in XCTest methods with objects that are partially equatable.
If this can be done simpler, PRs are welcome :)
*/
struct AnyEquatable<Target>
: Equatable
, CustomDebugStringConvertible
, CustomStringConvertible {
typealias Comparer = (Target, Target) -> Bool
let _target: Target
let _comparer: Comparer
init(target: Target, comparer: @escaping Comparer) {
_target = target
_comparer = comparer
}
}
func == <T>(lhs: AnyEquatable<T>, rhs: AnyEquatable<T>) -> Bool {
return lhs._comparer(lhs._target, rhs._target)
}
extension AnyEquatable {
var description: String {
return "\(_target)"
}
var debugDescription: String {
return "\(_target)"
}
}
| mit | e71b46055cb6ec38a17f14d331c6727b | 20.372093 | 80 | 0.647443 | 4.030702 | false | false | false | false |
maxsokolov/TableKit | Sources/TableSection.swift | 3 | 3263 | //
// Copyright (c) 2015 Max Sokolov https://twitter.com/max_sokolov
//
// 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
open class TableSection {
open private(set) var rows = [Row]()
open var headerTitle: String?
open var footerTitle: String?
open var indexTitle: String?
open var headerView: UIView?
open var footerView: UIView?
open var headerHeight: CGFloat? = nil
open var footerHeight: CGFloat? = nil
open var numberOfRows: Int {
return rows.count
}
open var isEmpty: Bool {
return rows.isEmpty
}
public init(rows: [Row]? = nil) {
if let initialRows = rows {
self.rows.append(contentsOf: initialRows)
}
}
public convenience init(headerTitle: String?, footerTitle: String?, rows: [Row]? = nil) {
self.init(rows: rows)
self.headerTitle = headerTitle
self.footerTitle = footerTitle
}
public convenience init(headerView: UIView?, footerView: UIView?, rows: [Row]? = nil) {
self.init(rows: rows)
self.headerView = headerView
self.footerView = footerView
}
// MARK: - Public -
open func clear() {
rows.removeAll()
}
open func append(row: Row) {
append(rows: [row])
}
open func append(rows: [Row]) {
self.rows.append(contentsOf: rows)
}
open func insert(row: Row, at index: Int) {
rows.insert(row, at: index)
}
open func insert(rows: [Row], at index: Int) {
self.rows.insert(contentsOf: rows, at: index)
}
open func replace(rowAt index: Int, with row: Row) {
rows[index] = row
}
open func swap(from: Int, to: Int) {
rows.swapAt(from, to)
}
open func delete(rowAt index: Int) {
rows.remove(at: index)
}
open func remove(rowAt index: Int) {
rows.remove(at: index)
}
// MARK: - deprecated methods -
@available(*, deprecated, message: "Use 'delete(rowAt:)' method instead")
open func delete(index: Int) {
rows.remove(at: index)
}
}
| mit | 6a68c78c2c4f4512cb13dc8c5180dbf6 | 28.663636 | 93 | 0.624579 | 4.237662 | false | false | false | false |
AndreasRicci/firebase-continue | samples/ios/Continote/Continote/Sample-Constants.swift | 2 | 3027 | //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import MaterialComponents.MaterialTypography
import MaterialComponents.MDCColorScheme
/**
These constants are organized as part of a struct for clarity and a cleaner namespace.
The constants predefined below are relevant to more than one screen within the app.
For local constants, use a private extension within the file you need those extra constants.
See the use of "private extension Constants" in MainViewController.swift for an example.
*/
struct Constants {
static let appName: String = "Continote"
// FirebaseContinue usage related.
struct FirebaseContinue {
static let applicationName: String = "continote"
static let urlToEditNoteWithKey: String =
"[TODO: YOUR-FIREBASE-HOSTING-URL-FOR-CONTINOTE-WEB-HERE]/edit-note.html?noteKey=%@"
}
// UI appearance related constants.
struct Theme {
// The color scheme we will apply to Material Components to mimic the look of Firebase.
static let colorScheme: MDCColorScheme & NSObjectProtocol =
MDCBasicColorScheme.init(
primaryColor: UIColor(red: 1.0, green: 0.76, blue: 0.05, alpha: 1.0),
secondaryColor: UIColor(red: 1.0, green: 0.6, blue: 0, alpha: 1.0))
struct Button {
// The elevation for buttons to give a raised look.
static let elevation: CGFloat = 4;
}
// All text-based inputs (i.e. UITextField and UITextView).
struct TextInput {
static let borderColor: CGColor =
UIColor(red: 0.76, green: 0.76, blue: 0.76, alpha: 0.5).cgColor
static let borderWidth: CGFloat = 1
static let borderCornerRadius: CGFloat = 2
}
enum LabelKind {
// Labels with text we wish to appear normal/standard (such as longer text content).
case normalText
// Labels with text we wish to appear as a title.
case titleText
/**
- Returns: The font to use for this kind of label.
*/
func getFont() -> UIFont {
switch self {
case .normalText:
return MDCTypography.subheadFont()
case .titleText:
return MDCTypography.titleFont()
}
}
/**
- Returns: The alpha to use for this kind of label.
*/
func getAlpha() -> CGFloat {
switch self {
case .normalText:
return MDCTypography.subheadFontOpacity()
case .titleText:
return MDCTypography.titleFontOpacity()
}
}
}
}
}
| apache-2.0 | c2195ffecd45bedb44de1523f44b915f | 31.902174 | 93 | 0.673274 | 4.330472 | false | false | false | false |
ming1016/smck | smck/Lib/RxSwift/ElementAt.swift | 47 | 2100 | //
// ElementAt.swift
// RxSwift
//
// Created by Junior B. on 21/10/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
final class ElementAtSink<O: ObserverType> : Sink<O>, ObserverType {
typealias SourceType = O.E
typealias Parent = ElementAt<SourceType>
let _parent: Parent
var _i: Int
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_i = parent._index
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceType>) {
switch event {
case .next(_):
if (_i == 0) {
forwardOn(event)
forwardOn(.completed)
self.dispose()
}
do {
let _ = try decrementChecked(&_i)
} catch(let e) {
forwardOn(.error(e))
dispose()
return
}
case .error(let e):
forwardOn(.error(e))
self.dispose()
case .completed:
if (_parent._throwOnEmpty) {
forwardOn(.error(RxError.argumentOutOfRange))
} else {
forwardOn(.completed)
}
self.dispose()
}
}
}
final class ElementAt<SourceType> : Producer<SourceType> {
let _source: Observable<SourceType>
let _throwOnEmpty: Bool
let _index: Int
init(source: Observable<SourceType>, index: Int, throwOnEmpty: Bool) {
if index < 0 {
rxFatalError("index can't be negative")
}
self._source = source
self._index = index
self._throwOnEmpty = throwOnEmpty
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == SourceType {
let sink = ElementAtSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| apache-2.0 | 94a12f4c0ff18938d6e0744996886827 | 25.910256 | 147 | 0.529776 | 4.60307 | false | false | false | false |
ahoppen/swift | test/Parse/matching_patterns.swift | 9 | 11147 | // RUN: %target-typecheck-verify-swift -swift-version 4 -I %S/Inputs -enable-source-import
import imported_enums
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int,Int,Int), y: (Int,Int,Int)) -> Bool {
return true
}
var x:Int
func square(_ x: Int) -> Int { return x*x }
struct A<B> {
struct C<D> { }
}
switch x {
// Expressions as patterns.
case 0:
()
case 1 + 2:
()
case square(9):
()
// 'var' and 'let' patterns.
case var a:
a = 1
case let a:
a = 1 // expected-error {{cannot assign}}
case var var a: // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}}
a += 1
case var let a: // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}}
print(a, terminator: "")
case var (var b): // expected-error {{'var' cannot appear nested inside another 'var'}}
b += 1
// 'Any' pattern.
case _:
()
// patterns are resolved in expression-only positions are errors.
case 1 + (_): // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}}
()
}
switch (x,x) {
case (var a, var a): // expected-error {{invalid redeclaration of 'a'}} expected-note {{'a' previously declared here}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
fallthrough
case _: // expected-warning {{case is already handled by previous patterns; consider removing it}}
()
}
var e : Any = 0
switch e { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
// 'is' pattern.
case is Int,
is A<Int>,
is A<Int>.C<Int>,
is (Int, Int),
is (a: Int, b: Int):
()
}
// Enum patterns.
enum Foo { case A, B, C }
func == <T>(_: Voluntary<T>, _: Voluntary<T>) -> Bool { return true }
enum Voluntary<T> : Equatable {
case Naught
case Mere(T)
case Twain(T, T)
func enumMethod(_ other: Voluntary<T>, foo: Foo) {
switch self {
case other:
()
case .Naught,
.Naught(), // expected-error {{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{17-19=}}
.Naught(_), // expected-error{{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{17-20=}}
.Naught(_, _): // expected-error{{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{17-23=}}
()
case .Mere,
.Mere(), // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}}
.Mere(_),
.Mere(_, _): // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}}
()
case .Twain(), // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}}
.Twain(_), // expected-warning {{enum case 'Twain' has 2 associated values; matching them as a tuple is deprecated}}
// expected-note@-25 {{'Twain' declared here}}
.Twain(_, _),
.Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}}
()
}
switch foo {
case .Naught: // expected-error{{type 'Foo' has no member 'Naught'}}
()
case .A, .B, .C:
()
}
}
}
var n : Voluntary<Int> = .Naught
if case let .Naught(value) = n {} // expected-error{{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{20-27=}}
if case let .Naught(value1, value2, value3) = n {} // expected-error{{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{20-44=}}
switch n {
case Foo.A: // expected-error{{enum case 'A' is not a member of type 'Voluntary<Int>'}}
()
case Voluntary<Int>.Naught,
Voluntary<Int>.Naught(), // expected-error {{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{27-29=}}
Voluntary<Int>.Naught(_, _), // expected-error{{pattern with associated values does not match enum case 'Naught'}}
// expected-note@-1 {{remove associated values to make the pattern match}} {{27-33=}}
Voluntary.Naught,
.Naught:
()
case Voluntary<Int>.Mere,
Voluntary<Int>.Mere(_),
Voluntary<Int>.Mere(_, _), // expected-error{{tuple pattern cannot match values of the non-tuple type 'Int'}}
Voluntary.Mere,
Voluntary.Mere(_),
.Mere,
.Mere(_):
()
case .Twain,
.Twain(_), // expected-warning {{enum case 'Twain' has 2 associated values; matching them as a tuple is deprecated}}
// expected-note@-69 {{'Twain' declared here}}
.Twain(_, _),
.Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(Int, Int)'}}
()
}
var notAnEnum = 0
switch notAnEnum {
case .Foo: // expected-error{{type 'Int' has no member 'Foo'}}
()
}
struct ContainsEnum {
enum Possible<T> {
case Naught
case Mere(T)
case Twain(T, T)
}
func member(_ n: Possible<Int>) {
switch n { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Mere(_)'}}
// expected-note@-2 {{missing case: '.Twain(_, _)'}}
case ContainsEnum.Possible<Int>.Naught,
ContainsEnum.Possible.Naught, // expected-warning {{case is already handled by previous patterns; consider removing it}}
Possible<Int>.Naught, // expected-warning {{case is already handled by previous patterns; consider removing it}}
Possible.Naught, // expected-warning {{case is already handled by previous patterns; consider removing it}}
.Naught: // expected-warning {{case is already handled by previous patterns; consider removing it}}
()
}
}
}
func nonmemberAccessesMemberType(_ n: ContainsEnum.Possible<Int>) {
switch n { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Mere(_)'}}
// expected-note@-2 {{missing case: '.Twain(_, _)'}}
case ContainsEnum.Possible<Int>.Naught,
.Naught: // expected-warning {{case is already handled by previous patterns; consider removing it}}
()
}
}
var m : ImportedEnum = .Simple
switch m {
case imported_enums.ImportedEnum.Simple,
ImportedEnum.Simple, // expected-warning {{case is already handled by previous patterns; consider removing it}}
.Simple: // expected-warning {{case is already handled by previous patterns; consider removing it}}
()
case imported_enums.ImportedEnum.Compound,
imported_enums.ImportedEnum.Compound(_), // expected-warning {{case is already handled by previous patterns; consider removing it}}
ImportedEnum.Compound, // expected-warning {{case is already handled by previous patterns; consider removing it}}
ImportedEnum.Compound(_), // expected-warning {{case is already handled by previous patterns; consider removing it}}
.Compound, // expected-warning {{case is already handled by previous patterns; consider removing it}}
.Compound(_): // expected-warning {{case is already handled by previous patterns; consider removing it}}
()
}
// Check that single-element tuple payloads work sensibly in patterns.
enum LabeledScalarPayload {
case Payload(name: Int)
}
var lsp: LabeledScalarPayload = .Payload(name: 0)
func acceptInt(_: Int) {}
func acceptString(_: String) {}
switch lsp {
case .Payload(0):
()
case .Payload(name: 0):
()
case let .Payload(x):
acceptInt(x)
acceptString("\(x)")
case let .Payload(name: x): // expected-warning {{case is already handled by previous patterns; consider removing it}}
acceptInt(x)
acceptString("\(x)")
case let .Payload((name: x)): // expected-warning {{case is already handled by previous patterns; consider removing it}}
acceptInt(x)
acceptString("\(x)")
case .Payload(let (name: x)): // expected-warning {{case is already handled by previous patterns; consider removing it}}
acceptInt(x)
acceptString("\(x)")
case .Payload(let (name: x)): // expected-warning {{case is already handled by previous patterns; consider removing it}}
acceptInt(x)
acceptString("\(x)")
case .Payload(let x): // expected-warning {{case is already handled by previous patterns; consider removing it}}
acceptInt(x)
acceptString("\(x)")
case .Payload((let x)): // expected-warning {{case is already handled by previous patterns; consider removing it}}
acceptInt(x)
acceptString("\(x)")
}
// Property patterns.
struct S {
static var stat: Int = 0
var x, y : Int
var comp : Int {
return x + y
}
func nonProperty() {}
}
// Tuple patterns.
var t = (1, 2, 3)
prefix operator +++
infix operator +++
prefix func +++(x: (Int,Int,Int)) -> (Int,Int,Int) { return x }
func +++(x: (Int,Int,Int), y: (Int,Int,Int)) -> (Int,Int,Int) {
return (x.0+y.0, x.1+y.1, x.2+y.2)
}
switch t {
case (_, var a, 3):
a += 1
case var (_, b, 3):
b += 1
case var (_, var c, 3): // expected-error{{'var' cannot appear nested inside another 'var'}}
c += 1
case (1, 2, 3):
()
// patterns in expression-only positions are errors.
case +++(_, var d, 3):
// expected-error@-1{{'_' can only appear in a pattern or on the left side of an assignment}}
()
case (_, var e, 3) +++ (1, 2, 3):
// expected-error@-1{{'_' can only appear in a pattern or on the left side of an assignment}}
()
case (let (_, _, _)) + 1:
// expected-error@-1 {{'_' can only appear in a pattern or on the left side of an assignment}}
()
}
// FIXME: We don't currently allow subpatterns for "isa" patterns that
// require interesting conditional downcasts.
class Base { }
class Derived : Base { }
switch [Derived(), Derived(), Base()] {
case let ds as [Derived]: // expected-error{{collection downcast in cast pattern is not implemented; use an explicit downcast to '[Derived]' instead}}
()
case is [Derived]: // expected-error{{collection downcast in cast pattern is not implemented; use an explicit downcast to '[Derived]' instead}}
()
default:
()
}
// Optional patterns.
let op1 : Int?
let op2 : Int??
switch op1 {
case nil: break
case 1?: break
case _?: break
}
switch op2 {
case nil: break
case _?: break
case (1?)?: break
case (_?)?: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
// <rdar://problem/20365753> Bogus diagnostic "refutable pattern match can fail"
let (responseObject: Int?) = op1
// expected-error @-1 {{expected ',' separator}} {{25-25=,}}
// expected-error @-2 {{expected pattern}}
// expected-error @-3 {{type of expression is ambiguous without more context}}
| apache-2.0 | da6019d353e84f1e71f987733ccf6f16 | 32.575301 | 304 | 0.641697 | 3.846446 | false | false | false | false |
tgebarowski/SwiftySettings | Source/UI/OptionButtonCell.swift | 1 | 4385 | //
// SettingsOptionButtonCell.swift
//
// SwiftySettings
// Created by Tomasz Gebarowski on 07/08/15.
// Copyright © 2015 codica Tomasz Gebarowski <gebarowski at gmail.com>.
// All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
class OptionsButtonCell : SettingsCell {
let selectedOptionLabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
override func updateConstraints() {
if !didSetupConstraints {
selectedOptionLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraints([
// Spacing Between Title and Selected UILabel
NSLayoutConstraint(item: selectedOptionLabel,
attribute: .left,
relatedBy: .greaterThanOrEqual,
toItem: textLabel!,
attribute: .right,
multiplier: 1.0,
constant: 15),
// Selected Option UILabel - Horizontal Constraints
NSLayoutConstraint(item: contentView,
attribute: .trailing,
relatedBy: .equal,
toItem: selectedOptionLabel,
attribute: .trailing,
multiplier: 1.0,
constant: 5),
// Selected Option UILabel - Vertical Constraints
NSLayoutConstraint(item: contentView,
attribute: .centerY,
relatedBy: .equal,
toItem: selectedOptionLabel,
attribute: .centerY,
multiplier: 1.0,
constant: 0)
])
}
super.updateConstraints()
}
override func setupViews() {
super.setupViews()
textLabel?.setContentHuggingPriority(UILayoutPriorityDefaultHigh,
for: .horizontal)
selectedOptionLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultHigh,
for: .horizontal)
contentView.addSubview(selectedOptionLabel)
}
override func configureAppearance() {
super.configureAppearance()
textLabel?.textColor = appearance?.cellTextColor
selectedOptionLabel.textColor = appearance?.cellSecondaryTextColor
contentView.backgroundColor = appearance?.cellBackgroundColor
accessoryView?.backgroundColor = appearance?.cellBackgroundColor
}
func load(_ item: OptionsButton) {
self.textLabel?.text = item.title
self.selectedOptionLabel.text = item.selectedOptionTitle
self.accessoryType = .disclosureIndicator
if let image = item.icon {
self.imageView?.image = image
}
configureAppearance()
setNeedsUpdateConstraints()
}
}
| mit | 67275a298bafd2fc5687b04a1f429a62 | 38.495495 | 96 | 0.604243 | 5.956522 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPress/Classes/Services/PeopleService.swift | 2 | 12738 | import Foundation
import CocoaLumberjack
import WordPressKit
/// Service providing access to the People Management WordPress.com API.
///
struct PeopleService {
/// MARK: - Public Properties
///
let siteID: Int
/// MARK: - Private Properties
///
fileprivate let context: NSManagedObjectContext
fileprivate let remote: PeopleServiceRemote
/// Designated Initializer.
///
/// - Parameters:
/// - blog: Target Blog Instance
/// - context: CoreData context to be used.
///
init?(blog: Blog, context: NSManagedObjectContext) {
guard let api = blog.wordPressComRestApi(), let dotComID = blog.dotComID as? Int else {
return nil
}
self.remote = PeopleServiceRemote(wordPressComRestApi: api)
self.siteID = dotComID
self.context = context
}
/// Loads a page of Users associated to the current blog, starting at the specified offset.
///
/// - Parameters:
/// - offset: Number of records to skip.
/// - count: Number of records to retrieve. By default set to 20.
/// - success: Closure to be executed on success.
/// - failure: Closure to be executed on failure.
///
func loadUsersPage(_ offset: Int = 0, count: Int = 20, success: @escaping ((_ retrieved: Int, _ shouldLoadMore: Bool) -> Void), failure: ((Error) -> Void)? = nil) {
remote.getUsers(siteID, offset: offset, count: count, success: { users, hasMore in
self.mergePeople(users)
success(users.count, hasMore)
}, failure: { error in
DDLogError(String(describing: error))
failure?(error)
})
}
/// Loads a page of Followers associated to the current blog, starting at the specified offset.
///
/// - Parameters:
/// - offset: Number of records to skip.
/// - count: Number of records to retrieve. By default set to 20.
/// - success: Closure to be executed on success.
/// - failure: Closure to be executed on failure.
///
func loadFollowersPage(_ offset: Int = 0, count: Int = 20, success: @escaping ((_ retrieved: Int, _ shouldLoadMore: Bool) -> Void), failure: ((Error) -> Void)? = nil) {
remote.getFollowers(siteID, offset: offset, count: count, success: { followers, hasMore in
self.mergePeople(followers)
success(followers.count, hasMore)
}, failure: { error in
DDLogError(String(describing: error))
failure?(error)
})
}
/// Loads a page of Viewers associated to the current blog, starting at the specified offset.
///
/// - Parameters:
/// - offset: Number of records to skip.
/// - count: Number of records to retrieve. By default set to 20.
/// - success: Closure to be executed on success.
/// - failure: Closure to be executed on failure.
///
func loadViewersPage(_ offset: Int = 0, count: Int = 20, success: @escaping ((_ retrieved: Int, _ shouldLoadMore: Bool) -> Void), failure: ((Error) -> Void)? = nil) {
remote.getViewers(siteID, offset: offset, count: count, success: { viewers, hasMore in
self.mergePeople(viewers)
success(viewers.count, hasMore)
}, failure: { error in
DDLogError(String(describing: error))
failure?(error)
})
}
/// Updates a given User with the specified role.
///
/// - Parameters:
/// - user: Instance of the person to be updated.
/// - role: New role that should be assigned
/// - failure: Optional closure, to be executed in case of error
///
/// - Returns: A new Person instance, with the new Role already assigned.
///
func updateUser(_ user: User, role: String, failure: ((Error, User) -> Void)?) -> User {
guard let managedPerson = managedPersonFromPerson(user) else {
return user
}
// OP Reversal
let pristineRole = managedPerson.role
// Hit the Backend
remote.updateUserRole(siteID, userID: user.ID, newRole: role, success: nil, failure: { error in
DDLogError("### Error while updating person \(user.ID) in blog \(self.siteID): \(error)")
guard let managedPerson = self.managedPersonFromPerson(user) else {
DDLogError("### Person with ID \(user.ID) deleted before update")
return
}
managedPerson.role = pristineRole
let reloadedPerson = User(managedPerson: managedPerson)
failure?(error, reloadedPerson)
})
// Pre-emptively update the role
managedPerson.role = role
return User(managedPerson: managedPerson)
}
/// Deletes a given User.
///
/// - Parameters:
/// - user: The person that should be deleted
/// - success: Closure to be executed in case of success.
/// - failure: Closure to be executed on error
///
func deleteUser(_ user: User, success: (() -> Void)? = nil, failure: ((Error) -> Void)? = nil) {
guard let managedPerson = managedPersonFromPerson(user) else {
return
}
// Hit the Backend
remote.deleteUser(siteID, userID: user.ID, success: {
success?()
}, failure: { error in
DDLogError("### Error while deleting person \(user.ID) from blog \(self.siteID): \(error)")
// Revert the deletion
self.createManagedPerson(user)
failure?(error)
})
// Pre-emptively nuke the entity
context.delete(managedPerson)
}
/// Deletes a given Follower.
///
/// - Parameters:
/// - person: The follower that should be deleted
/// - success: Closure to be executed in case of success.
/// - failure: Closure to be executed on error
///
func deleteFollower(_ person: Follower, success: (() -> Void)? = nil, failure: ((Error) -> Void)? = nil) {
guard let managedPerson = managedPersonFromPerson(person) else {
return
}
// Hit the Backend
remote.deleteFollower(siteID, userID: person.ID, success: {
success?()
}, failure: { error in
DDLogError("### Error while deleting follower \(person.ID) from blog \(self.siteID): \(error)")
// Revert the deletion
self.createManagedPerson(person)
failure?(error)
})
// Pre-emptively nuke the entity
context.delete(managedPerson)
}
/// Deletes a given Viewer.
///
/// - Parameters:
/// - person: The follower that should be deleted
/// - success: Closure to be executed in case of success.
/// - failure: Closure to be executed on error
///
func deleteViewer(_ person: Viewer, success: (() -> Void)? = nil, failure: ((Error) -> Void)? = nil) {
guard let managedPerson = managedPersonFromPerson(person) else {
return
}
// Hit the Backend
remote.deleteViewer(siteID, userID: person.ID, success: {
success?()
}, failure: { error in
DDLogError("### Error while deleting viewer \(person.ID) from blog \(self.siteID): \(error)")
// Revert the deletion
self.createManagedPerson(person)
failure?(error)
})
// Pre-emptively nuke the entity
context.delete(managedPerson)
}
/// Validates Invitation Recipients.
///
/// - Parameters:
/// - usernameOrEmail: Recipient that should be validated.
/// - role: Role that would be granted to the recipient.
/// - success: Closure to be executed on success
/// - failure: Closure to be executed on error.
///
func validateInvitation(_ usernameOrEmail: String,
role: String,
success: @escaping (() -> Void),
failure: @escaping ((Error) -> Void)) {
remote.validateInvitation(siteID,
usernameOrEmail: usernameOrEmail,
role: role,
success: success,
failure: failure)
}
/// Sends an Invitation to a specified recipient, to access a Blog.
///
/// - Parameters:
/// - usernameOrEmail: Recipient that should be validated.
/// - role: Role that would be granted to the recipient.
/// - message: String that should be sent to the users.
/// - success: Closure to be executed on success
/// - failure: Closure to be executed on error.
///
func sendInvitation(_ usernameOrEmail: String,
role: String,
message: String = "",
success: @escaping (() -> Void),
failure: @escaping ((Error) -> Void)) {
remote.sendInvitation(siteID,
usernameOrEmail: usernameOrEmail,
role: role,
message: message,
success: success,
failure: failure)
}
}
/// Encapsulates all of the PeopleService Private Methods.
///
private extension PeopleService {
/// Updates the Core Data collection of users, to match with the array of People received.
///
func mergePeople<T: Person>(_ remotePeople: [T]) {
for remotePerson in remotePeople {
if let existingPerson = managedPersonFromPerson(remotePerson) {
existingPerson.updateWith(remotePerson)
DDLogDebug("Updated person \(existingPerson)")
} else {
createManagedPerson(remotePerson)
}
}
}
/// Retrieves the collection of users, persisted in Core Data, associated with the current blog.
///
func loadPeople<T: Person>(_ siteID: Int, type: T.Type) -> [T] {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
request.predicate = NSPredicate(format: "siteID = %@ AND kind = %@",
NSNumber(value: siteID as Int),
NSNumber(value: type.kind.rawValue as Int))
let results: [ManagedPerson]
do {
results = try context.fetch(request) as! [ManagedPerson]
} catch {
DDLogError("Error fetching all people: \(error)")
results = []
}
return results.map { return T(managedPerson: $0) }
}
/// Retrieves a Person from Core Data, with the specifiedID.
///
func managedPersonFromPerson(_ person: Person) -> ManagedPerson? {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
request.predicate = NSPredicate(format: "siteID = %@ AND userID = %@ AND kind = %@",
NSNumber(value: siteID as Int),
NSNumber(value: person.ID as Int),
NSNumber(value: type(of: person).kind.rawValue as Int))
request.fetchLimit = 1
let results = (try? context.fetch(request) as! [ManagedPerson]) ?? []
return results.first
}
/// Nukes the set of users, from Core Data, with the specified ID's.
///
func removeManagedPeopleWithIDs<T: Person>(_ ids: Set<Int>, type: T.Type) {
if ids.isEmpty {
return
}
let numberIDs = ids.map { return NSNumber(value: $0 as Int) }
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
request.predicate = NSPredicate(format: "siteID = %@ AND kind = %@ AND userID IN %@",
NSNumber(value: siteID as Int),
NSNumber(value: type.kind.rawValue as Int),
numberIDs)
let objects = (try? context.fetch(request) as! [NSManagedObject]) ?? []
for object in objects {
DDLogDebug("Removing person: \(object)")
context.delete(object)
}
}
/// Inserts a new Person instance into Core Data, with the specified payload.
///
func createManagedPerson<T: Person>(_ person: T) {
let managedPerson = NSEntityDescription.insertNewObject(forEntityName: "Person", into: context) as! ManagedPerson
managedPerson.updateWith(person)
managedPerson.creationDate = Date()
DDLogDebug("Created person \(managedPerson)")
}
}
| gpl-2.0 | ae1e9d6ab5c433c4e2418aab70bafcae | 37.023881 | 172 | 0.565395 | 4.859977 | false | false | false | false |
plivesey/SwiftGen | Pods/Commander/Sources/ArgumentDescription.swift | 3 | 11043 | public enum ArgumentType {
case argument
case option
}
public protocol ArgumentDescriptor {
associatedtype ValueType
/// The arguments name
var name: String { get }
/// The arguments description
var description: String? { get }
var type: ArgumentType { get }
/// Parse the argument
func parse(_ parser: ArgumentParser) throws -> ValueType
}
extension ArgumentConvertible {
init(string: String) throws {
try self.init(parser: ArgumentParser(arguments: [string]))
}
}
public class VariadicArgument<T : ArgumentConvertible> : ArgumentDescriptor {
public typealias ValueType = [T]
public typealias Validator = (ValueType) throws -> ValueType
public let name: String
public let description: String?
public let validator: Validator?
public var type: ArgumentType { return .argument }
public init(_ name: String, description: String? = nil, validator: Validator? = nil) {
self.name = name
self.description = description
self.validator = validator
}
public func parse(_ parser: ArgumentParser) throws -> ValueType {
let value = try Array<T>(parser: parser)
if let validator = validator {
return try validator(value)
}
return value
}
}
@available(*, deprecated, message: "use VariadicArgument instead")
typealias VaradicArgument<T : ArgumentConvertible> = VariadicArgument<T>
public class Argument<T : ArgumentConvertible> : ArgumentDescriptor {
public typealias ValueType = T
public typealias Validator = (ValueType) throws -> ValueType
public let name: String
public let description: String?
public let validator: Validator?
public var type: ArgumentType { return .argument }
public init(_ name: String, description: String? = nil, validator: Validator? = nil) {
self.name = name
self.description = description
self.validator = validator
}
public func parse(_ parser: ArgumentParser) throws -> ValueType {
let value: T
do {
value = try T(parser: parser)
} catch ArgumentError.missingValue {
throw ArgumentError.missingValue(argument: name)
} catch {
throw error
}
if let validator = validator {
return try validator(value)
}
return value
}
}
public class Option<T : ArgumentConvertible> : ArgumentDescriptor {
public typealias ValueType = T
public typealias Validator = (ValueType) throws -> ValueType
public let name: String
public let flag: Character?
public let description: String?
public let `default`: ValueType
public var type: ArgumentType { return .option }
public let validator: Validator?
public init(_ name: String, _ default: ValueType, flag: Character? = nil, description: String? = nil, validator: Validator? = nil) {
self.name = name
self.flag = flag
self.description = description
self.`default` = `default`
self.validator = validator
}
public func parse(_ parser: ArgumentParser) throws -> ValueType {
if let value = try parser.shiftValueForOption(name) {
let value = try T(string: value)
if let validator = validator {
return try validator(value)
}
return value
}
if let flag = flag {
if let value = try parser.shiftValueForFlag(flag) {
let value = try T(string: value)
if let validator = validator {
return try validator(value)
}
return value
}
}
return `default`
}
}
public class Options<T : ArgumentConvertible> : ArgumentDescriptor {
public typealias ValueType = [T]
public let name: String
public let description: String?
public let count: Int
public let `default`: ValueType
public var type: ArgumentType { return .option }
public init(_ name: String, _ default: ValueType, count: Int, description: String? = nil) {
self.name = name
self.`default` = `default`
self.count = count
self.description = description
}
public func parse(_ parser: ArgumentParser) throws -> ValueType {
let values = try parser.shiftValuesForOption(name, count: count)
return try values?.map { try T(string: $0) } ?? `default`
}
}
public class VariadicOption<T : ArgumentConvertible> : ArgumentDescriptor {
public typealias ValueType = [T]
public let name: String
public let description: String?
public let `default`: ValueType
public var type: ArgumentType { return .option }
public init(_ name: String, _ default: ValueType = [], description: String? = nil) {
self.name = name
self.`default` = `default`
self.description = description
}
public func parse(_ parser: ArgumentParser) throws -> ValueType {
var values: ValueType? = nil
while let shifted = try parser.shiftValueForOption(name) {
let argument = try T(string: shifted)
if values == nil {
values = ValueType()
}
values?.append(argument)
}
return values ?? `default`
}
}
public class Flag : ArgumentDescriptor {
public typealias ValueType = Bool
public let name: String
public let flag: Character?
public let disabledName: String
public let disabledFlag: Character?
public let description: String?
public let `default`: ValueType
public var type: ArgumentType { return .option }
public init(_ name: String, flag: Character? = nil, disabledName: String? = nil, disabledFlag: Character? = nil, description: String? = nil, default: Bool = false) {
self.name = name
self.disabledName = disabledName ?? "no-\(name)"
self.flag = flag
self.disabledFlag = disabledFlag
self.description = description
self.`default` = `default`
}
public func parse(_ parser: ArgumentParser) throws -> ValueType {
if parser.hasOption(disabledName) {
return false
}
if parser.hasOption(name) {
return true
}
if let flag = flag {
if parser.hasFlag(flag) {
return true
}
}
if let disabledFlag = disabledFlag {
if parser.hasFlag(disabledFlag) {
return false
}
}
return `default`
}
}
class BoxedArgumentDescriptor {
let name: String
let description: String?
let `default`: String?
let type: ArgumentType
init<T : ArgumentDescriptor>(value: T) {
name = value.name
description = value.description
type = value.type
if let value = value as? Flag {
`default` = value.`default`.description
} else if let value = value as? Option<String> {
`default` = value.`default`.description
} else if let value = value as? Option<Int> {
`default` = value.`default`.description
} else {
// TODO, default for Option of generic type
`default` = nil
}
}
}
class UsageError : Error, ANSIConvertible, CustomStringConvertible {
let message: String
let help: Help
init(_ message: String, _ help: Help) {
self.message = message
self.help = help
}
var description: String {
return [message, help.description].filter { !$0.isEmpty }.joined(separator: "\n\n")
}
var ansiDescription: String {
return [message, help.ansiDescription].filter { !$0.isEmpty }.joined(separator: "\n\n")
}
}
class Help : Error, ANSIConvertible, CustomStringConvertible {
let command: String?
let group: Group?
let descriptors: [BoxedArgumentDescriptor]
init(_ descriptors: [BoxedArgumentDescriptor], command: String? = nil, group: Group? = nil) {
self.command = command
self.group = group
self.descriptors = descriptors
}
func reraise(_ command: String? = nil) -> Help {
if let oldCommand = self.command, let newCommand = command {
return Help(descriptors, command: "\(newCommand) \(oldCommand)")
}
return Help(descriptors, command: command ?? self.command)
}
var description: String {
var output = [String]()
let arguments = descriptors.filter { $0.type == ArgumentType.argument }
let options = descriptors.filter { $0.type == ArgumentType.option }
if let command = command {
let args = arguments.map { "<\($0.name)>" }
let usage = ([command] + args).joined(separator: " ")
output.append("Usage:")
output.append("")
output.append(" \(usage)")
output.append("")
}
if let group = group {
output.append("Commands:")
output.append("")
for command in group.commands {
if let description = command.description {
output.append(" + \(command.name) - \(description)")
} else {
output.append(" + \(command.name)")
}
}
output.append("")
} else if !arguments.isEmpty {
output.append("Arguments:")
output.append("")
output += arguments.map { argument in
if let description = argument.description {
return " \(argument.name) - \(description)"
} else {
return " \(argument.name)"
}
}
output.append("")
}
if !options.isEmpty {
output.append("Options:")
for option in options {
var line = " --\(option.name)"
if let `default` = option.default {
line += " [default: \(`default`)]"
}
if let description = option.description {
line += " - \(description)"
}
output.append(line)
}
}
return output.joined(separator: "\n")
}
var ansiDescription: String {
var output = [String]()
let arguments = descriptors.filter { $0.type == ArgumentType.argument }
let options = descriptors.filter { $0.type == ArgumentType.option }
if let command = command {
let args = arguments.map { "<\($0.name)>" }
let usage = ([command] + args).joined(separator: " ")
output.append("Usage:")
output.append("")
output.append(" \(usage)")
output.append("")
}
if let group = group {
output.append("Commands:")
output.append("")
for command in group.commands {
if let description = command.description {
output.append(" + \(ANSI.green)\(command.name)\(ANSI.reset) - \(description)")
} else {
output.append(" + \(ANSI.green)\(command.name)\(ANSI.reset)")
}
}
output.append("")
} else if !arguments.isEmpty {
output.append("Arguments:")
output.append("")
output += arguments.map { argument in
if let description = argument.description {
return " \(ANSI.blue)\(argument.name)\(ANSI.reset) - \(description)"
} else {
return " \(ANSI.blue)\(argument.name)\(ANSI.reset)"
}
}
output.append("")
}
if !options.isEmpty {
output.append("Options:")
for option in options {
var line = " \(ANSI.blue)--\(option.name)\(ANSI.reset)"
if let `default` = option.default {
line += " [default: \(`default`)]"
}
if let description = option.description {
line += " - \(description)"
}
output.append(line)
}
}
return output.joined(separator: "\n")
}
}
| mit | 31dae7f105f60f735e026ff04dad4119 | 24.801402 | 167 | 0.630897 | 4.333987 | false | false | false | false |
huangboju/Moots | Examples/SwiftUI/CreatingAmacOSApp/Complete/Landmarks/WatchLandmarks Extension/NotificationController.swift | 1 | 1417 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
A notificatio for the watchOS app.
*/
import WatchKit
import SwiftUI
import UserNotifications
class NotificationController: WKUserNotificationHostingController<NotificationView> {
var landmark: Landmark?
var title: String?
var message: String?
let landmarkIndexKey = "landmarkIndex"
override var body: NotificationView {
NotificationView(title: title,
message: message,
landmark: landmark)
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
override func didReceive(_ notification: UNNotification) {
let userData = UserData()
let notificationData =
notification.request.content.userInfo as? [String: Any]
let aps = notificationData?["aps"] as? [String: Any]
let alert = aps?["alert"] as? [String: Any]
title = alert?["title"] as? String
message = alert?["body"] as? String
if let index = notificationData?[landmarkIndexKey] as? Int {
landmark = userData.landmarks[index]
}
}
}
| mit | ed58862f8d419465cdb922e02c8b89dc | 26.745098 | 90 | 0.640989 | 5.089928 | false | false | false | false |
Lves/LLRefresh | LLRefresh/Custom/Footer/LLRefreshAutoStateFooter.swift | 1 | 2019 | //
// LLRefreshAutoStateFooter.swift
// LLRefreshDemo
//
// Created by 李兴乐 on 2016/12/15.
// Copyright © 2016年 com.lvesli. All rights reserved.
//
import UIKit
open class LLRefreshAutoStateFooter: LLRefreshAutoFooter {
var labelLeftInset:CGFloat = LLConstant.RefreshLabelLeftInset
lazy var stateLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 14)
label.autoresizingMask = .flexibleWidth
label.backgroundColor = UIColor.clear
self.addSubview(label)
return label
}()
var refreshingTitleHidden:Bool = false
fileprivate var stateTitles:[Int:String] = [:]
override open func prepare() {
super.prepare()
setTitle(LLConstant.kFooterStateTitleNormal, state: .normal)
setTitle(LLConstant.kFooterStateTitleRefreshing, state: .refreshing)
setTitle(LLConstant.kFooterStateTitleNoMoreData, state: .noMoreData)
stateLabel.isUserInteractionEnabled = true
stateLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(stateLabelClick)))
}
override open func setState(_ state: LLRefreshState) {
super.setState(state)
if refreshingTitleHidden && state == .refreshing{
stateLabel.text = nil
}
stateLabel.text = stateTitles[refreshState.rawValue]
}
override open func placeSubViews() {
super.placeSubViews()
guard stateLabel.constraints.count == 0 else{
return
}
stateLabel.frame = self.bounds
}
//MARK:- private
@objc private func stateLabelClick() {
if refreshState == .normal {
beginRefreshing()
}
}
//MARK: - Public
open func setTitle(_ title:String?, state:LLRefreshState) {
if let title = title {
stateTitles[state.rawValue] = title
stateLabel.text = stateTitles[refreshState.rawValue]
}
}
}
| mit | e1f6c36d7f3fb613449718b8cc5bd489 | 32.5 | 113 | 0.653234 | 4.740566 | false | false | false | false |
ReactKit/ReactKitCatalog | ReactKitCatalog-iOS/MasterViewController.swift | 2 | 3042 | //
// MasterViewController.swift
// ReactKitCatalog-iOS
//
// Created by Yasuhiro Inami on 2014/10/06.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import UIKit
import Dollar
class MasterViewController: UITableViewController
{
let catalogs = Catalog.allCatalogs()
override func awakeFromNib()
{
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad()
{
super.viewDidLoad()
// auto-select
if let index = ($.findIndex(self.catalogs) { $0.selected }) {
self.showDetailViewControllerAtIndex(index)
}
}
//--------------------------------------------------
// MARK: - UITableViewDataSource
//--------------------------------------------------
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.catalogs.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let catalog = self.catalogs[indexPath.row]
cell.textLabel?.text = catalog.title
cell.detailTextLabel?.text = catalog.description
return cell
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
self.showDetailViewControllerAtIndex(indexPath.row)
}
func showDetailViewControllerAtIndex(index: Int)
{
let catalog = self.catalogs[index]
//
// change Swift's className to Obj-C nibName
//
// e.g.
// NSStringFromClass(catalog.class_)
// = "ReactKitCatalog_iOS.TextFieldViewController"
//
let className = NSStringFromClass(catalog.class_).componentsSeparatedByString(".").last
if let className = className {
let newVC: UIViewController
if catalog.hasXib {
newVC = catalog.class_.init(nibName: className, bundle: nil)
}
else {
newVC = catalog.class_.init()
}
// let newVC = catalog.class_(nibName: className, bundle: nil)
let newNavC = UINavigationController(rootViewController: newVC)
self.splitViewController?.showDetailViewController(newNavC, sender: self)
newVC.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
newVC.navigationItem.leftItemsSupplementBackButton = true
}
}
}
| mit | cb2c081345f00bef2818bbc9dd534f35 | 29.09901 | 116 | 0.601645 | 5.619224 | false | false | false | false |
corey-lin/PlayMarvelAPI | NameSHero/ResultViewModel.swift | 1 | 912 | //
// ResultViewModel.swift
// NameSHero
//
// Created by coreylin on 3/5/16.
// Copyright © 2016 coreylin. All rights reserved.
//
import Foundation
import ReactiveCocoa
class ResultViewModel {
let finalScore: MutableProperty<Int>
let perfectScore = MutableProperty<Bool>(false)
let newRecordScore = MutableProperty<Bool>(false)
init() {
finalScore = MutableProperty<Int>(0)
}
init(_ score: Int) {
finalScore = MutableProperty<Int>(score)
finalScore.producer.startWithNext {
currentScore in
let recordScore: Int = NSUserDefaults.standardUserDefaults().integerForKey(Constants.RecordScoreKey)
if recordScore < currentScore {
self.newRecordScore.value = true
NSUserDefaults.standardUserDefaults().setInteger(score, forKey: Constants.RecordScoreKey)
}
if currentScore == 100 {
self.perfectScore.value = true
}
}
}
}
| mit | 78d93f2accd0bd7931bfea8b23a3c0e4 | 25.794118 | 106 | 0.700329 | 4.257009 | false | false | false | false |
10686142/eChance | eChance/MoreVC.swift | 1 | 2957 | //
// MoreVC.swift
// Iraffle
//
// Created by Vasco Meerman on 03/05/2017.
// Copyright © 2017 Vasco Meerman. All rights reserved.
//
import UIKit
class MoreVC: UIViewController {
// Outlets
@IBOutlet weak var backHomeButton: UIButton!
@IBOutlet weak var logOutButton: UIButton!
@IBOutlet weak var termsAndConditionsButton: UIButton!
@IBOutlet weak var explanationButton: UIButton!
@IBOutlet weak var fbImageView: UIImageView!
@IBOutlet weak var instaImageView: UIImageView!
// Constants and Variables
let defaults = UserDefaults.standard
var referalCode: String!
var sendURL: URL!
// CHANGE THESE TO CORRESPONDING PAGES
let instaLink = "https://www.instagram.com/echance_nl"
let fbLink = "https://www.facebook.com/EChance-117132965615435/"
let termsAndCondLink = "https://raffler.co/"
override func viewDidLoad() {
super.viewDidLoad()
let tapGestureRecognizerFB = UITapGestureRecognizer(target: self, action: #selector(facebookTapped))
let tapGestureRecognizerINSTA = UITapGestureRecognizer(target: self, action: #selector(instagramTapped))
fbImageView.addGestureRecognizer(tapGestureRecognizerFB)
instaImageView.addGestureRecognizer(tapGestureRecognizerINSTA)
}
func instagramTapped() {
defaults.set("eChance op Instagram", forKey: "sourceURL")
defaults.set(instaLink, forKey: "webPageURL")
let vc = storyboard?.instantiateViewController(withIdentifier: "webPageVC") as! WebPageVC
present(vc, animated: true, completion: nil)
}
func facebookTapped() {
defaults.set("eChance op Facebook", forKey: "sourceURL")
defaults.set(fbLink, forKey: "webPageURL")
let vc = storyboard?.instantiateViewController(withIdentifier: "webPageVC") as! WebPageVC
present(vc, animated: true, completion: nil)
}
@IBAction func termsAndConditionsTapped(_ sender: Any) {
defaults.set("Terms & Conditions", forKey: "sourceURL")
defaults.set(termsAndCondLink, forKey: "webPageURL")
let vc = storyboard?.instantiateViewController(withIdentifier: "webPageVC") as! WebPageVC
present(vc, animated: true, completion: nil)
}
@IBAction func explanationTapped(_ sender: Any) {
self.defaults.set("0", forKey: "fromRegister")
self.performSegue(withIdentifier: "toExplanation", sender: nil)
}
@IBAction func backHomeTapped(_ sender: Any) {
let vc = storyboard?.instantiateViewController(withIdentifier: "homeVC") as! HomeVC
present(vc, animated: true, completion: nil)
}
@IBAction func logOutTapped(_ sender: Any) {
let vc = storyboard?.instantiateViewController(withIdentifier: "loginVC") as! LoginVC
present(vc, animated: true, completion: nil)
defaults.removeObject(forKey: "user")
}
}
| mit | 1f578584b34480a720f7ece70c7840b2 | 35.493827 | 112 | 0.680311 | 4.465257 | false | false | false | false |
huonw/swift | stdlib/public/SDK/Foundation/Codable.swift | 13 | 2780 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Errors
//===----------------------------------------------------------------------===//
// Both of these error types bridge to NSError, and through the entry points they use, no further work is needed to make them localized.
extension EncodingError : LocalizedError {}
extension DecodingError : LocalizedError {}
//===----------------------------------------------------------------------===//
// Error Utilities
//===----------------------------------------------------------------------===//
internal extension DecodingError {
/// Returns a `.typeMismatch` error describing the expected type.
///
/// - parameter path: The path of `CodingKey`s taken to decode a value of this type.
/// - parameter expectation: The type expected to be encountered.
/// - parameter reality: The value that was encountered instead of the expected type.
/// - returns: A `DecodingError` with the appropriate path and debug description.
internal static func _typeMismatch(at path: [CodingKey], expectation: Any.Type, reality: Any) -> DecodingError {
let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead."
return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description))
}
/// Returns a description of the type of `value` appropriate for an error message.
///
/// - parameter value: The value whose type to describe.
/// - returns: A string describing `value`.
/// - precondition: `value` is one of the types below.
fileprivate static func _typeDescription(of value: Any) -> String {
if value is NSNull {
return "a null value"
} else if value is NSNumber /* FIXME: If swift-corelibs-foundation isn't updated to use NSNumber, this check will be necessary: || value is Int || value is Double */ {
return "a number"
} else if value is String {
return "a string/data"
} else if value is [Any] {
return "an array"
} else if value is [String : Any] {
return "a dictionary"
} else {
return "\(type(of: value))"
}
}
}
| apache-2.0 | 99664570505146e05e74ab00c0bb5266 | 47.77193 | 175 | 0.553957 | 5.46169 | false | false | false | false |
allenngn/firefox-ios | Utils/KeychainCache.swift | 17 | 2238 | /* 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 XCGLogger
private let log = XCGLogger.defaultInstance()
public protocol JSONLiteralConvertible {
func asJSON() -> JSON
}
public class KeychainCache<T: JSONLiteralConvertible> {
public let branch: String
public let label: String
public var value: T? {
didSet {
checkpoint()
}
}
public init(branch: String, label: String, value: T?) {
self.branch = branch
self.label = label
self.value = value
}
public class func fromBranch(branch: String, withLabel label: String?, withDefault defaultValue: T? = nil, factory: JSON -> T?) -> KeychainCache<T> {
if let l = label {
if let s = KeychainWrapper.stringForKey("\(branch).\(l)") {
if let t = factory(JSON.parse(s)) {
log.info("Read \(branch) from Keychain with label \(branch).\(l).")
return KeychainCache(branch: branch, label: l, value: t)
} else {
log.warning("Found \(branch) in Keychain with label \(branch).\(l), but could not parse it.")
}
} else {
log.warning("Did not find \(branch) in Keychain with label \(branch).\(l).")
}
} else {
log.warning("Did not find \(branch) label in Keychain.")
}
// Fall through to missing.
log.warning("Failed to read \(branch) from Keychain.")
let label = label ?? Bytes.generateGUID()
return KeychainCache(branch: branch, label: label, value: defaultValue)
}
public func checkpoint() {
log.info("Storing \(self.branch) in Keychain with label \(self.branch).\(self.label).")
// TODO: PII logging.
if let value = value {
let jsonString = value.asJSON().toString(pretty: false)
KeychainWrapper.setString(jsonString, forKey: "\(branch).\(label)")
} else {
KeychainWrapper.removeObjectForKey("\(branch).\(label)")
}
}
}
| mpl-2.0 | 4e320ee4c53f6d94e043c974871c2a10 | 35.688525 | 153 | 0.58445 | 4.54878 | false | false | false | false |
nikkis/OrchestratorJSiOS | orchestrator.js/orchestrator.js/TestCapability.swift | 1 | 2348 | //
// TestCapability.swift
// orchestrator.js
//
// Created by Niko Mäkitalo on 27.8.2014.
// Copyright (c) 2014 Niko Mäkitalo. All rights reserved.
//
import Foundation
import AVFoundation
@objc
class TestCapability : NSObject, AVSpeechSynthesizerDelegate
{
@objc let speechSynthesizer = AVSpeechSynthesizer()
override init() {
super.init()
print("iitu")
//speechSynthesizer.delegate = self
}
@objc func initMeasurement() {
print("init measurement")
}
@objc func calculateAverage() {
print("calculate average")
}
@objc func dummyMethod() {
print("Dummy")
}
@objc func test() -> String {
print("test method")
//let line = "moikka"
//let utterance = AVSpeechUtterance(string: line)
//speechSynthesizer.stopSpeakingAtBoundary(AVSpeechBoundary.Immediate)
//speechSynthesizer.speakUtterance(utterance)
return "foobar"
}
@objc func say(_ line: String, filter: String, pitch: String) {
print("say method")
let utterance = AVSpeechUtterance(string: line)
/*
speechSynthesizer.stopSpeaking(at: AVSpeechBoundary.immediate)
speechSynthesizer.speak(utterance)
// wait so that the speaking starts
Thread.sleep(forTimeInterval: 0.1)
// wait until speaking is over (TODO: timeout based on line length)
while(speechSynthesizer.isSpeaking) {
Thread.sleep(forTimeInterval: 0.2)
}
*/
print("speaking is over")
}
@objc func shout(_ line: String, filter2: String, pitch: Double) {
let utterance = AVSpeechUtterance(string: line)
/*
speechSynthesizer.stopSpeaking(at: AVSpeechBoundary.immediate)
speechSynthesizer.speak(utterance)
// wait so that the speaking starts
Thread.sleep(forTimeInterval: 0.1)
// wait until speaking is over (TODO: timeout based on line length)
while(speechSynthesizer.isSpeaking) {
Thread.sleep(forTimeInterval: 0.2)
}
*/
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer,
didFinish utterance: AVSpeechUtterance)
{
print("LOPPU")
}
}
| mit | 632906bbe4092a855b22495ce3e0b6c9 | 23.4375 | 78 | 0.606138 | 4.720322 | false | false | false | false |
austinzheng/swift | test/IDE/complete_trailing_closure.swift | 11 | 4498 | // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=GLOBAL_1 > %t
// RUN: %FileCheck %s -check-prefix=GLOBAL_1 < %t
// RUN: %FileCheck %s -check-prefix=NONTRIVIAL < %t
// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=METHOD_1 > %t
// RUN: %FileCheck %s -check-prefix=METHOD_1 < %t
// RUN: %FileCheck %s -check-prefix=NONTRIVIAL < %t
// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=METHOD_2 > %t
// RUN: %FileCheck %s -check-prefix=GLOBAL_1 < %t
// RUN: %FileCheck %s -check-prefix=METHOD_1 < %t
// RUN: %FileCheck %s -check-prefix=NONTRIVIAL < %t
// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=METHOD_3 > %t
// RUN: %FileCheck %s -check-prefix=METHOD_1 < %t
// RUN: %FileCheck %s -check-prefix=NONTRIVIAL < %t
// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=STATIC_METHOD_1 > %t
// RUN: %FileCheck %s -check-prefix=STATIC_METHOD_1 < %t
// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=METHOD_4 > %t
// RUN: %FileCheck %s -check-prefix=METHOD_4 < %t
// RUN: %FileCheck %s -check-prefix=NONTRIVIAL < %t
// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=CLASS_METHOD_1 > %t
// RUN: %FileCheck %s -check-prefix=CLASS_METHOD_1 < %t
// NONTRIVIAL-NOT: nonTrivial{{.*}} {|}
func global1(_: ()->()) {}
func global2(label: ()->()) {}
func global3(_: () throws -> ()) rethrows {}
func global4(x: Int = 0, y: Int = 2, _: ()->()) {}
func nonTrivial1(_: (Int) -> ()) {}
func nonTrivial2(_: () -> Int) {}
func nonTrivial3(x: Int, _: () -> Int) {}
func test1() {
#^GLOBAL_1^#
}
// GLOBAL_1: Begin completions
// GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global1 {|}[#Void#]
// GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global2 {|}[#Void#]
// GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global3 {|}[#Void#]
// GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global4 {|}[#Void#]
// GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global1({#() -> ()##() -> ()#})[#Void#]
// GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global2({#label: () -> ()##() -> ()#})[#Void#]
// GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global3({#() throws -> ()##() throws -> ()#})[' rethrows'][#Void#]
// GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global4({#() -> ()##() -> ()#})[#Void#]
// GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global4({#x: Int#}, {#y: Int#}, {#() -> ()##() -> ()#})[#Void#]
// GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: nonTrivial1({#(Int) -> ()##(Int) -> ()#})[#Void#]
// GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: nonTrivial2({#() -> Int##() -> Int#})[#Void#]
// GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: nonTrivial3({#x: Int#}, {#() -> Int##() -> Int#})[#Void#]
// GLOBAL_1: End completions
struct S {
func method1(_: ()->()) {}
static func method2(_: ()->()) {}
func nonTrivial1(_: (Int)->()) {}
func nonTrivial2(_: @autoclosure ()->()) {}
func test2() {
self.#^METHOD_1^#
}
// METHOD_1: Begin completions
// METHOD_1: Decl[InstanceMethod]/CurrNominal: method1 {|}[#Void#]
// METHOD_1: Decl[InstanceMethod]/CurrNominal: method1({#() -> ()##() -> ()#})[#Void#]
// METHOD_1: Decl[InstanceMethod]/CurrNominal: nonTrivial1({#(Int) -> ()##(Int) -> ()#})[#Void#]
// METHOD_1: Decl[InstanceMethod]/CurrNominal: nonTrivial2({#()#})[#Void#]
// METHOD_1: End completions
func test3() {
#^METHOD_2^#
}
}
func test4() {
S().#^METHOD_3^#
}
func test5() {
S.#^STATIC_METHOD_1^#
}
// STATIC_METHOD_1-NOT: {|}
// STATIC_METHOD_1: Decl[StaticMethod]/CurrNominal: method2 {|}[#Void#]
// STATIC_METHOD_1-NOT: {|}
class C {
func method1(_: ()->()) {}
class func method2(_: ()->()) {}
func nonTrivial1(_: (Int)->()) {}
func nonTrivial2(_: @autoclosure ()->()) {}
func test6() {
self.#^METHOD_4^#
}
// METHOD_4: Begin completions
// METHOD_4: Decl[InstanceMethod]/CurrNominal: method1 {|}[#Void#]
// METHOD_4: Decl[InstanceMethod]/CurrNominal: method1({#() -> ()##() -> ()#})[#Void#]
// METHOD_4: Decl[InstanceMethod]/CurrNominal: nonTrivial1({#(Int) -> ()##(Int) -> ()#})[#Void#]
// METHOD_4: End completions
func test7() {
C.#^CLASS_METHOD_1^#
}
// CLASS_METHOD_1-NOT: {|}
// CLASS_METHOD_1: Decl[StaticMethod]/CurrNominal: method2 {|}[#Void#]
// CLASS_METHOD_1-NOT: {|}
}
| apache-2.0 | 7360c5b710168018e2a827bf8532f27f | 41.433962 | 119 | 0.603602 | 3.156491 | false | true | false | false |
iSapozhnik/FamilyPocket | FamilyPocket/ViewControllers/NewCategoryViewController.swift | 1 | 4088 | //
// NewCategoryViewController.swift
// FamilyPocket
//
// Created by Ivan Sapozhnik on 5/17/17.
// Copyright © 2017 Ivan Sapozhnik. All rights reserved.
//
import UIKit
class NewCategoryViewController: BaseViewController, UIScrollViewDelegate {
typealias CategoryHandler = (_ sender: UIViewController, _ category: Category?, _ canceled: Bool) -> ()
@IBOutlet weak var bottomContainerConstraint: NSLayoutConstraint!
@IBOutlet weak var colorButton: UIButton!
@IBOutlet weak var titleLabel: ALabel!
@IBOutlet weak var categoryNameTextfield: PaddingTextfield!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var deleteButton: UIButton!
@IBOutlet weak var iconView: UIImageView!
var categoryColorName: String?
var categoryColor: UIColor?
var completion: CategoryHandler?
var kbUtility: KeyboardUtility!
init(withCompletion completion: CategoryHandler?) {
super.init(nibName: "NewCategoryViewController", bundle: nil)
self.completion = completion
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
colorButton.layer.cornerRadius = 3.0
colorButton.layer.borderColor = UIColor.white.cgColor
colorButton.layer.borderWidth = 1.0
scrollView.contentOffset = CGPoint(x: 0, y: 20)
categoryNameTextfield.paddingLeft = 16.0
kbUtility = KeyboardUtility { (height: CGFloat, duration :TimeInterval) in
UIView.animate(withDuration: duration, animations: {
self.bottomContainerConstraint.constant = height
self.view.layoutIfNeeded()
})
}
}
override func animate() {
titleLabel.animate()
}
@IBAction func pickeColor(_ sender: Any) {
let palette = ColorPaletteTableViewController { (color) in
self.animateOnAppearence = false
print("selected \(color.hexString())")
self.categoryColorName = color.hexString()
self.categoryColor = color
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
UIView.animate(withDuration: 0.3, animations: {
self.view.layer.backgroundColor = color.cgColor
self.colorButton.layer.backgroundColor = color.cgColor
})
}
}
navigationController?.pushViewController(palette, animated: true)
}
@IBAction func saveCategory(_ sender: Any) {
categoryNameTextfield.resignFirstResponder()
guard
let categoryColorName = self.categoryColorName,
let categoryName = self.categoryNameTextfield.text, categoryName.characters.count > 0 else { return }
let newCategory = Category()
newCategory.color = categoryColorName
newCategory.name = categoryName
newCategory.dateOfCreation = Date()
newCategory.iconName = "Edit User Male-80.png" //default icon
let categoryManager = CategoryManager()
if categoryManager.canAdd(object: newCategory) {
CategoryManager().add(object: newCategory)
completion?(self, newCategory, false)
} else {
print("Object already exists")
}
}
@IBAction func cancel(_ sender: Any) {
completion?(self, nil, true)
}
@IBAction func deleteCategory(_ sender: Any) {
// Overrides in EditCategoryViewController
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y <= -50 {
completion?(self, nil, true)
}
}
}
| mit | b7cdf72855cf2623aca14cb9535cfabf | 31.696 | 113 | 0.62393 | 5.370565 | false | false | false | false |
natecook1000/swift | test/IRGen/protocol_metadata.swift | 1 | 5559 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s -DINT=i%target-ptrsize
// REQUIRES: CPU=x86_64
protocol A { func a() }
protocol B { func b() }
protocol C : class { func c() }
@objc protocol O { func o() }
@objc protocol OPT {
@objc optional func opt()
@objc optional static func static_opt()
@objc optional var prop: O { get }
@objc optional subscript (x: O) -> O { get }
}
protocol AB : A, B { func ab() }
protocol ABO : A, B, O { func abo() }
// -- @objc protocol O uses ObjC symbol mangling and layout
// CHECK-LABEL: @_PROTOCOL__TtP17protocol_metadata1O_ = private constant
// CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS__TtP17protocol_metadata1O_,
// -- size, flags: 1 = Swift
// CHECK-SAME: i32 96, i32 1
// CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata1O_
// CHECK-SAME: }
// CHECK: [[A_NAME:@.*]] = private constant [2 x i8] c"A\00"
// CHECK-LABEL: @"$S17protocol_metadata1AMp" = hidden constant
// CHECK-SAME: i32 65603,
// CHECK-SAME: @"$S17protocol_metadataMXM"
// CHECK-SAME: [[A_NAME]]
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1,
// CHECK-SAME: i32 0,
// CHECK-SAME: }
// CHECK: [[B_NAME:@.*]] = private constant [2 x i8] c"B\00"
// CHECK-LABEL: @"$S17protocol_metadata1BMp" = hidden constant
// CHECK-SAME: i32 65603,
// CHECK-SAME: @"$S17protocol_metadataMXM"
// CHECK-SAME: i32 0,
// CHECK-SAME: [[B_NAME]]
// CHECK-SAME: i32 1,
// CHECK: }
// CHECK: [[C_NAME:@.*]] = private constant [2 x i8] c"C\00"
// CHECK-LABEL: @"$S17protocol_metadata1CMp" = hidden constant
// CHECK-SAME: i32 67,
// CHECK-SAME: @"$S17protocol_metadataMXM"
// CHECK-SAME: [[C_NAME]]
// CHECK-SAME: i32 1,
// CHECK-SAME: i32 1,
// CHECK-SAME: i32 0,
// AnyObject layout constraint
// CHECK-SAME: i32 31, i32 0, i32 0
// CHECK-SAME: }
// -- @objc protocol OPT uses ObjC symbol mangling and layout
// CHECK: @_PROTOCOL__TtP17protocol_metadata3OPT_ = private constant { {{.*}} i32, [4 x i8*]*, i8*, i8* } {
// CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS_OPT__TtP17protocol_metadata3OPT_,
// CHECK-SAME: @_PROTOCOL_CLASS_METHODS_OPT__TtP17protocol_metadata3OPT_,
// -- size, flags: 1 = Swift
// CHECK-SAME: i32 96, i32 1
// CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata3OPT_
// CHECK-SAME: }
// -- inheritance lists for refined protocols
// CHECK: [[AB_NAME:@.*]] = private constant [3 x i8] c"AB\00"
// CHECK: @"$S17protocol_metadata2ABMp" = hidden constant
// CHECK-SAME: i32 65603,
// CHECK-SAME: @"$S17protocol_metadataMXM"
// CHECK-SAME: [[AB_NAME]]
// CHECK-SAME: i32 2, i32 3, i32 0
// Inheritance from A
// CHECK-SAME: i32 128, i32 0
// CHECK-SAME: @"$S17protocol_metadata1AMp"
// Inheritance from B
// CHECK-SAME: i32 128, i32 0
// CHECK-SAME: @"$S17protocol_metadata1BMp"
// CHECK: }
protocol Comprehensive {
associatedtype Assoc : A
init()
func instanceMethod()
static func staticMethod()
var instance: Assoc { get set }
static var global: Assoc { get set }
}
// CHECK: [[COMPREHENSIVE_ASSOC_NAME:@.*]] = private constant [6 x i8] c"Assoc\00"
// CHECK: @"$S17protocol_metadata13ComprehensiveMp" = hidden constant
// CHECK-SAME: i32 65603
// CHECK-SAME: i32 1
// CHECK-SAME: i32 11,
// CHECK-SAME: i32 trunc
// CHECK-SAME: [6 x i8]* [[COMPREHENSIVE_ASSOC_NAME]]
// CHECK-SAME: %swift.protocol_requirement { i32 7, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 8, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 2, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 17, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 1, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 19, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 20, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 22, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 3, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 4, i32 0 },
// CHECK-SAME: %swift.protocol_requirement { i32 6, i32 0 }
func reify_metadata<T>(_ x: T) {}
// CHECK: define hidden swiftcc void @"$S17protocol_metadata0A6_types{{[_0-9a-zA-Z]*}}F"
func protocol_types(_ a: A,
abc: A & B & C,
abco: A & B & C & O) {
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$S17protocol_metadata1AMp" to [[INT]])
// CHECK: call %swift.type* @swift_getExistentialTypeMetadata(i1 true, %swift.type* null, i64 1, [[INT]]* {{%.*}})
reify_metadata(a)
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$S17protocol_metadata1AMp"
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$S17protocol_metadata1BMp"
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$S17protocol_metadata1CMp"
// CHECK: call %swift.type* @swift_getExistentialTypeMetadata(i1 false, %swift.type* null, i64 3, [[INT]]* {{%.*}})
reify_metadata(abc)
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$S17protocol_metadata1AMp"
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$S17protocol_metadata1BMp"
// CHECK: store [[INT]] ptrtoint ({{.*}} @"$S17protocol_metadata1CMp"
// CHECK: [[O_REF:%.*]] = load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP17protocol_metadata1O_"
// CHECK: [[O_REF_INT:%.*]] = ptrtoint i8* [[O_REF]] to [[INT]]
// CHECK: [[O_REF_DESCRIPTOR:%.*]] = or [[INT]] [[O_REF_INT]], 1
// CHECK: store [[INT]] [[O_REF_DESCRIPTOR]]
// CHECK: call %swift.type* @swift_getExistentialTypeMetadata(i1 false, %swift.type* null, i64 4, [[INT]]* {{%.*}})
reify_metadata(abco)
}
| apache-2.0 | 3961a2731cc637eba51048620eaa4d04 | 38.425532 | 204 | 0.638064 | 3.016278 | false | false | false | false |
wilfreddekok/Antidote | Antidote/NotificationObject.swift | 1 | 2757 | // 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
enum NotificationAction {
case OpenChat(chatUniqueIdentifier: String)
case OpenRequest(requestUniqueIdentifier: String)
case AnswerIncomingCall(userInfo: String)
}
extension NotificationAction {
private struct Constants {
static let ValueKey = "ValueKey"
static let ArgumentKey = "ArgumentKey"
static let OpenChatValue = "OpenChatValue"
static let OpenRequestValue = "OpenRequestValue"
static let AnswerIncomingCallValue = "AnswerIncomingCallValue"
}
init?(dictionary: [String: String]) {
guard let value = dictionary[Constants.ValueKey] else {
return nil
}
switch value {
case Constants.OpenChatValue:
guard let argument = dictionary[Constants.ArgumentKey] else {
return nil
}
self = OpenChat(chatUniqueIdentifier: argument)
case Constants.OpenRequestValue:
guard let argument = dictionary[Constants.ArgumentKey] else {
return nil
}
self = OpenRequest(requestUniqueIdentifier: argument)
case Constants.AnswerIncomingCallValue:
guard let argument = dictionary[Constants.ArgumentKey] else {
return nil
}
self = AnswerIncomingCall(userInfo: argument)
default:
return nil
}
}
func archive() -> [String: String] {
switch self {
case .OpenChat(let identifier):
return [
Constants.ValueKey: Constants.OpenChatValue,
Constants.ArgumentKey: identifier,
]
case .OpenRequest(let identifier):
return [
Constants.ValueKey: Constants.OpenRequestValue,
Constants.ArgumentKey: identifier,
]
case .AnswerIncomingCall(let userInfo):
return [
Constants.ValueKey: Constants.AnswerIncomingCallValue,
Constants.ArgumentKey: userInfo,
]
}
}
}
struct NotificationObject {
/// Title of notification
let title: String
/// Body text of notification
let body: String
/// Action to be fired when user interacts with notification
let action: NotificationAction
/// Sound to play when notification is fired. Valid only for local notifications.
let soundName: String
}
| mpl-2.0 | b1f09c35269dc0e359c119af56b99304 | 32.621951 | 85 | 0.594487 | 5.64959 | false | false | false | false |
Poligun/NihonngoSwift | Nihonngo/MeaningPreviewViewController.swift | 1 | 4159 | //
// MeaningPreviewViewController.swift
// Nihonngo
//
// Created by ZhaoYuhan on 15/1/9.
// Copyright (c) 2015年 ZhaoYuhan. All rights reserved.
//
import UIKit
class MeaningPreviewViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
private let labelCellIdentifier = "LabelCell"
private let examplePreviewCellIdentifier = "ExamplePreviewCell"
private var meaning: Meaning!
private var tableView: UITableView!
convenience init(meaning: Meaning) {
self.init()
self.meaning = meaning
}
override func viewDidLoad() {
tableView = UITableView(frame: self.view.bounds, style: .Grouped)
tableView.setTranslatesAutoresizingMaskIntoConstraints(false)
tableView.estimatedRowHeight = 120.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)
tableView.registerClass(LabelCell.self, forCellReuseIdentifier: labelCellIdentifier)
tableView.registerClass(ExamplePreviewCell.self, forCellReuseIdentifier: examplePreviewCellIdentifier)
navigationItem.title = "释义预览"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "添加", style: .Plain, target: self, action: "onAddExampleButtonClick:")
}
override func viewWillAppear(animated: Bool) {
tableView.reloadData()
}
func onAddExampleButtonClick(sender: AnyObject) {
let viewController = EditExampleViewController(example: "", translation: "", onSave: {
(newExample: String, newTranslation: String) -> Void in
DataStore.sharedInstance.addExample(newExample, withTranslation: newTranslation, forMeaning: self.meaning)
DataStore.sharedInstance.saveContext()
})
navigationController?.pushViewController(viewController, animated: true)
}
// TableView DataSource & Delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return section == 0 ? "释义" : "例子"
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 2 {
return 1
}
return section == 0 ? 1 : meaning.examples.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier(labelCellIdentifier, forIndexPath: indexPath) as LabelCell
cell.setLabelText(meaning.meaning)
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier(examplePreviewCellIdentifier, forIndexPath: indexPath) as ExamplePreviewCell
cell.setExample(meaning.examples[indexPath.row] as Example)
return cell
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 {
let viewController = EditMeaningViewController(meaning: meaning.meaning, onSave: {(newMeaning: String) -> Void in
self.meaning.meaning = newMeaning
DataStore.sharedInstance.saveContext()
})
navigationController?.pushViewController(viewController, animated: true)
} else if indexPath.section == 1 {
let example = meaning.examples[indexPath.row] as Example
let viewController = EditExampleViewController(example: example.example, translation: example.translation, onSave: {
(newExample: String, newTranslation: String) -> Void in
example.example = newExample
example.translation = newTranslation
DataStore.sharedInstance.saveContext()
})
navigationController?.pushViewController(viewController, animated: true)
}
}
} | mit | 54351031e6ab2ef4e840c5843a792053 | 39.970297 | 143 | 0.673435 | 5.55302 | false | false | false | false |
yarshure/Surf | Surf/AddEditProxyController.swift | 1 | 23937 | //
// AddEditController.swift
// Surf
//
// Created by kiwi on 15/11/20.
// Copyright © 2015年 yarshure. All rights reserved.
//
import Foundation
import UIKit
import SFSocket
import Photos
#if !targetEnvironment(UIKitForMac)
import AssetsLibrary
#endif
import XRuler
enum UIUserInterfaceIdiom : Int {
case Unspecified
case Phone // iPhone and iPod touch style UI
case Pad // iPad style UI
}
class MiscCell: UITableViewCell {
@IBOutlet weak var button:UIButton?
}
/// The tunnel delegate protocol.
protocol AddEditProxyDelegate:class {
func addProxyConfig(_ controller: AddEditProxyController, proxy:SFProxy)//
func editProxyConfig(_ controller: AddEditProxyController, proxy:SFProxy)//
}
let label:[String] = ["Server","Port","Username","Password","TLS","KCPTUN","KCPTUN parameter"]
let tlsAlert = "Note:if enable TLS,Server value must domain name".localized
let supported_ciphers = [
"rc4",
"rc4-md5",
"aes-128-cfb",
"aes-192-cfb",
"aes-256-cfb",
"bf-cfb",
"cast5-cfb",
"des-cfb",
"rc2-cfb",
"salsa20",
"chacha20",
"chacha20-ietf"
]
let supported_ciphers_press = "aes"
class SegmentCell:UITableViewCell {
@IBOutlet weak var segement:UISegmentedControl!
}
import Xcon
public class AddEditProxyController: SFTableViewController ,BarcodeScanDelegate,SFMethodDelegate
//UIImagePickerControllerDelegate,UINavigationControllerDelegate
{
var numberOfSetting: Int = 0
var useCamera:Bool = true
var proxy:SFProxy!
var qrImage:UIImage?
var chain:Bool = false
//var config:String = "" //fn
weak var delegate:AddEditProxyDelegate?
var add:Bool = false
var textFields = NSMutableArray()
var firstLoad:Bool = true
var addressField:UITextField?
var portField:UITextField?
var usernameField:UITextField?
var passwordField:UITextField?
var kcpparamterField:UITextField?
var proxyNameField:UITextField?
//@IBOutlet weak var contro:UISegmentedControl!
override public func viewDidLoad() {
super.viewDidLoad()
self.title = "Proxy Config".localized
//NSTimer.scheduledTimerWithTimeInterval(1.0, target: self.tableView, selector: "reloadData", userInfo: nil, repeats: false)
//config.proxyName = "Surf"
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action:#selector(AddEditProxyController.saveConfig(_:)))
if proxy == nil {
proxy = SFProxy.create(name: "PROXY", type: .SS, address: "", port: "", passwd: "", method: "aes-256-cfb",tls: false)
add = true
}
}
@IBAction func valueChanged(sender:UISegmentedControl){
let index = sender.selectedSegmentIndex
//AxLogger.log("\(sender.titleForSegmentAtIndex(index))")
print(index)
if firstLoad {
var indext = 0
if proxy.type == .HTTPS || proxy.type == .HTTP{
indext = 0
}else {
indext = 1
}
sender.selectedSegmentIndex = indext
firstLoad = false
return
}
if proxy.method == supported_ciphers_press {
proxy.type = .HTTPAES
}
if index == 0 {
proxy.type = .HTTP
}else if index == 1{
proxy.type = .SOCKS5
for method in supported_ciphers {
if method == proxy.method {
proxy.type = .SS
return
}
}
}
}
func saveConfigTemp(){
proxy.serverAddress = self.addressField!.text!.trimmingCharacters(in: .whitespacesAndNewlines)
proxy.proxyName = self.proxyNameField!.text!.trimmingCharacters(in: .whitespacesAndNewlines)
proxy.serverPort = self.portField!.text!.trimmingCharacters(in: .whitespacesAndNewlines)
proxy.method = self.usernameField!.text!.trimmingCharacters(in: .whitespacesAndNewlines)
proxy.password = self.passwordField!.text!.trimmingCharacters(in: .whitespacesAndNewlines)
}
@IBAction func saveConfig(_ sender: AnyObject){
//guard let d = self.delegate else{ return }
if proxy.kcptun {
if !verifyReceipt(.KCP) {
changeToBuyPage()
return
}
}
proxy.serverAddress = self.addressField!.text!.trimmingCharacters(in: .whitespacesAndNewlines)
proxy.proxyName = self.proxyNameField!.text!.trimmingCharacters(in: .whitespacesAndNewlines)
proxy.serverPort = self.portField!.text!.trimmingCharacters(in: .whitespacesAndNewlines)
proxy.method = self.usernameField!.text!.trimmingCharacters(in: .whitespacesAndNewlines)
proxy.password = self.passwordField!.text!.trimmingCharacters(in: .whitespacesAndNewlines)
//proxy.mode = self.kcpparamterField!.text!.trimmingCharacters(in: .whitespacesAndNewlines)
if proxy.proxyName.isEmpty || proxy.serverAddress.isEmpty || proxy.serverPort.isEmpty {
alertMessageAction("Config Invalid!".localized,complete: nil)
}
if proxy.type == .SS {
var found = false
for method in supported_ciphers {
if method == proxy.method {
found = true
break
}
}
if found == false {
alertMessageAction("Method Invalid".localized, complete: nil)
return
}
if proxy.password.isEmpty {
alertMessageAction("Empty Password".localized, complete: nil)
return
}
}
if proxy.tlsEnable {
}
if let port = Int(proxy.serverPort) {
if port == 0 || port > 65535 {
alertMessageAction("\(proxy.serverPort) invalid ",complete: nil)
return
}
}else {
//crash here
alertMessageAction("\(proxy.serverPort) invalid ",complete: nil)
return
}
if let d = delegate {
if add {
d.addProxyConfig(self, proxy: proxy)
}else {
d.editProxyConfig(self, proxy: proxy)
}
}else {
_ = ProxyGroupSettings.share.addProxy(proxy)
}
_ = self.navigationController?.popViewController(animated: true)
}
@IBAction func useBarcode(_ sender: AnyObject) {
self.performSegue(withIdentifier: "showBarCode", sender: sender)
}
func convertConfigString(configString: String){
let r = SFProxy.createProxyWithURL(configString)
if let proxy = r.proxy {
self.proxy = proxy
tableView.reloadData()
}else {
alertMessageAction(r.message, complete: nil)
}
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//self.tableView.reloadData()
}
public func barcodeScanDidScan(controller: BarcodeScanViewController, configString:String){
if self.presentedViewController == controller {
self.dismiss(animated: true, completion: { () -> Void in
})
}
self.convertConfigString(configString: configString)
}
public func barcodeScanCancelScan(controller: BarcodeScanViewController){
if self.presentedViewController == controller {
self.dismiss(animated: true, completion: { () -> Void in
})
}
}
override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showBarCode"{
guard let barCodeController = segue.destination as? BarcodeScanViewController else{return}
//barCodeController.useCamera = self.useCamera
barCodeController.delegate = self
//barCodeController.navigationItem.title = "Add Proxy"
}else if segue.identifier == "showImage"{
guard let vc = segue.destination as? ImageViewController else{return}
vc.image = qrImage!
}else if segue.identifier == "showKcp"{
guard let vc = segue.destination as? KcpTableViewController else{return}
vc.kcpinfo = self.proxy.config
}
}
@IBAction func saveConfigToImage(_ sender: AnyObject) {
generateQRCodeScale(scale: 10.0)
}
func generateQRCodeScale(scale:CGFloat){
//
// ss://aes-256-cfb:[email protected]:14860"
let base64Encoded = proxy.base64String()
let stringData = base64Encoded.data(using: .utf8, allowLossyConversion: false)
let filter = CIFilter(name: "CIQRCodeGenerator")
guard let f = filter else {
return
}
f.setValue(stringData, forKey: "inputMessage")
f.setValue("M", forKey: "inputCorrectionLevel")
guard let image = f.outputImage else {
return
}
let cgImage = CIContext(options:nil).createCGImage(image, from: image.extent)
UIGraphicsBeginImageContext(CGSize(width:image.extent.size.width*scale, height:image.extent.size.height*scale))
let context = UIGraphicsGetCurrentContext()
context!.interpolationQuality = .none
//CGContextDrawImage(context!,context!.boundingBoxOfClipPath,cgImage!)
context!.draw(cgImage!, in: context!.boundingBoxOfClipPath, byTiling: false)
// if let appIcon = UIImage.init(named: "logo.png") {
// context!.translateBy(x: 0, y: image.extent.size.height*scale)
// context!.scaleBy(x: 1, y: -1)
// let r = CGRect(x:image.extent.size.width*scale/2-120/2, y:image.extent.size.width*scale/2-120/2,width: 120, height:120)
// appIcon.draw(in: r)
// }
let output = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//CGImageRelease(cgImage);
let qrImage = UIImage(cgImage: output!.cgImage!, scale: output!.scale, orientation: .downMirrored)
self.qrImage = qrImage
performSegue(withIdentifier: "showImage", sender: nil)
}
public override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
if proxy.kcptun {
return 8
}
return 7
case 2:
return 2
default:
return 0
}
}
public override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "NAME".localized
case 1:
return "PROXY".localized
case 2:
return "MISC".localized
default:
return ""
}
}
public override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch section {
case 1:
return tlsAlert
default:
return ""
}
}
// override public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath){
// if indexPath.section == 1 && indexPath.row == 0 {
// let c = cell as! SegmentCell
// var index = 0
// if proxy.type.rawValue < 2 {
// index = proxy.type.rawValue
// }else {
// index = 2
// }
// c.segement.selectedSegmentIndex == index
// }
// }
@objc func tlsChanged(_ sender:UISwitch) {
let on = sender.isOn
proxy.tlsEnable = on
}
func proxyChainAction(_ sender:UISwitch){
chain = sender.isOn
}
@objc func kcpEnableAction(_ sender:UISwitch){
let x = IndexPath.init(row: 7, section: 1)
proxy.kcptun = sender.isOn
if proxy.kcptun {
tableView.insertRows(at: [x], with: UITableView.RowAnimation.none)
}else {
tableView.deleteRows(at: [x], with: UITableView.RowAnimation.none)
}
}
public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "textfield-cell") as! TextFieldCell
cell.cellLabel?.text = "Name".localized
cell.textField.text = proxy.proxyName
cell.wwdcStyle()
self.proxyNameField = cell.textField
return cell
case 1:
if indexPath.row == 0{
let cell = tableView.dequeueReusableCell(withIdentifier: "textfield-cell") as! TextFieldCell
cell.cellLabel?.text = "Type".localized
cell.textField.text = proxy.type.description
cell.textField.isEnabled = false
cell.wwdcStyle()
return cell
}else {
if indexPath.row == 5 || indexPath.row == 6 {
let cell = tableView.dequeueReusableCell(withIdentifier: "Advance", for: indexPath as IndexPath) as! AdvancedCell
cell.wwdcStyle()
switch indexPath.row {
case 5:
if proxy.type == .SS {
cell.label.text = "One Time Auth".localized
}else {
cell.label.text = label[indexPath.row-1].localized
}
cell.s.isOn = proxy.tlsEnable
cell.s.addTarget(self, action: #selector(AddEditProxyController.tlsChanged(_:)), for: .valueChanged)
return cell
case 6:
cell.label.text = label[indexPath.row-1].localized
cell.s.isOn = proxy.kcptun
cell.s.addTarget(self, action: #selector(AddEditProxyController.kcpEnableAction(_:)), for: .valueChanged)
return cell
default:
return cell
}
}else {
let cell = tableView.dequeueReusableCell(withIdentifier: "textfield-cell") as! TextFieldCell
cell.cellLabel?.text = label[indexPath.row-1].localized
var placeHold:String = ""
cell.wwdcStyle()
switch indexPath.row{
case 1:
cell.textField.text = proxy.serverAddress
self.addressField = cell.textField
// cell.valueChanged = { [weak self] (textfield:UITextField) -> Void in
// self!.proxy.serverAddress = textfield.text!..trimmingCharacters(in: .whitespacesAndNewlines)
// }
placeHold = "server address or ip".localized
case 2:
cell.textField.text = proxy.serverPort
self.portField = cell.textField
cell.textField.keyboardType = .decimalPad
// cell.valueChanged = { [weak self] (textfield:UITextField) -> Void in
// self!.proxy.serverPort = textfield.text!..trimmingCharacters(in: .whitespacesAndNewlines)
// }
placeHold = "server port"
case 3:
cell.textField.text = proxy.method
self.usernameField = cell.textField
if proxy.type == .SS {
placeHold = "value"
cell.cellLabel?.text = "Method".localized
cell.textField.isEnabled = false
}else {
cell.textField.isEnabled = true
placeHold = "option"
// cell.valueChanged = { [weak self] (textfield:UITextField) -> Void in
// self!.proxy.method = textfield.text!..trimmingCharacters(in: .whitespacesAndNewlines)
// }
}
case 4:
cell.textField.text = proxy.password
cell.textField.isSecureTextEntry = true
if proxy.type == .SS{
placeHold = "value"
}else {
placeHold = "option"
}
self.passwordField = cell.textField
// cell.valueChanged = { [weak self] (textfield:UITextField) -> Void in
// self!.proxy.password = textfield.text!..trimmingCharacters(in: .whitespacesAndNewlines)
// }
case 7:
//cell.textField.text = proxy.mode//kcptun
self.kcpparamterField = cell.textField
placeHold = "paramter"
self.kcpparamterField?.isHidden = true
cell.cellLabel?.text = label[indexPath.row-1]
cell.textField.isEnabled = true
default:
break
}
let s = NSMutableAttributedString(string:placeHold)
//let r = (title as NSString)
s.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.cyan], range: NSMakeRange(0, placeHold.count))
cell.textField?.attributedPlaceholder = s
return cell
}
}
case 2:
var iden:String
if indexPath.row == 0 {
iden = "barcodescan"
}else {
iden = "barcodesave"
}
let cell = tableView.dequeueReusableCell(withIdentifier: iden) as! MiscCell
if ProxyGroupSettings.share.wwdcStyle {
cell.button?.setTitleColor(UIColor.white, for: .normal)
}else {
cell.button?.setTitleColor(UIColor.black, for: .normal)
}
return cell
default:
break
}
return UITableViewCell()
}
public override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if let cell = tableView.cellForRow(at: indexPath) {
if let x = cell as? TextFieldCell{
if indexPath.section == 1 {
if indexPath.row == 0 {
return indexPath
}else if indexPath.row == 3{
if proxy.type == .SS {
return indexPath
}else {
x.textField.becomeFirstResponder()
}
}else {
if x.textField.isHidden {
return indexPath
}else {
x.textField.becomeFirstResponder()
}
}
}else {
x.textField.becomeFirstResponder()
}
}
}
return nil
}
public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 1 && indexPath.row == 0 {
if verifyReceipt(.HTTP) {
showSelectType()
}else {
changeToBuyPage()
}
}else if indexPath.section == 1 && indexPath.row == 3{
showMethodSelect()
}else if indexPath.section == 1 && indexPath.row == 7 {
self.performSegue(withIdentifier: "showKcp", sender: nil)
}else {
tableView.deselectRow(at: indexPath as IndexPath, animated: false)
}
}
func showMethodSelect(){
// 临时保存数据
saveConfigTemp()
let st = UIStoryboard.init(name: "SSMethod", bundle: nil)
guard let vc = st.instantiateInitialViewController() as? SFMethodViewController else {return }
vc.delegate = self
self.navigationController?.pushViewController(vc, animated: true)
}
func didSelectMethod(controller: SFMethodViewController, method:String){
if proxy.type == .SS {
proxy.method = method
tableView.reloadData()
}
}
func showSelectType() {
var style:UIAlertController.Style = .alert
let deviceIdiom = UIScreen.main.traitCollection.userInterfaceIdiom
switch deviceIdiom {
case .pad:
style = .alert
default:
style = .actionSheet
break
}
guard let indexPath = tableView.indexPathForSelectedRow else {return}
//let result = results[indexPath.row]
let alert = UIAlertController.init(title: "Alert".localized, message: "Please Select Proxy Type".localized, preferredStyle: style)
let action = UIAlertAction.init(title: "HTTP", style: .default) {[unowned self ] (action:UIAlertAction) -> Void in
self.proxy.type = .HTTP
self.tableView.deselectRow(at: indexPath, animated: true)
self.tableView.reloadData()
}
let action1 = UIAlertAction.init(title: "SOCKS5", style: .default) { [unowned self ] (action:UIAlertAction) -> Void in
self.proxy.type = .SOCKS5
self.tableView.deselectRow(at: indexPath, animated: true)
self.tableView.reloadData()
}
let action2 = UIAlertAction.init(title: "SS", style: .default) { [unowned self ] (action:UIAlertAction) -> Void in
self.proxy.type = .SS
self.tableView.deselectRow(at: indexPath, animated: true)
self.tableView.reloadData()
}
let cancle = UIAlertAction.init(title: "Cancel".localized, style: .cancel) { [unowned self ] (action:UIAlertAction) -> Void in
self.tableView.deselectRow(at: indexPath, animated: true)
}
alert.addAction(action)
alert.addAction(action1)
alert.addAction(action2)
alert.addAction(cancle)
self.present(alert, animated: true) { () -> Void in
}
}
}
| bsd-3-clause | 40e069abe7b3321ad9c715f9fdb2e31a | 35.973725 | 163 | 0.531394 | 5.226568 | false | false | false | false |
xiawuacha/DouYuzhibo | DouYuzhibo/DouYuzhibo/Classses/Home/ViewModel/RecommendViewModel.swift | 1 | 4143 | //
// RecommendViewModel.swift
// DouYuzhibo
//
// Created by 汪凯 on 2016/11/2.
// Copyright © 2016年 汪凯. All rights reserved.
//
import UIKit
class RecommendViewModel : BaseViewModel {
// MARK:- 懒加载属性
fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup()
fileprivate lazy var prettyGroup : AnchorGroup = AnchorGroup()
lazy var cycleModels : [CycleModel] = [CycleModel]()
}
extension RecommendViewModel {
//请求数据
func requestData(_ finishCallback : @escaping () -> ()) {
// 1.定义参数
let parameters = ["limit" : "4", "offset" : "0", "time" : Date.getCurrentTime()]
//2:创建一个异步请求组
let dGroup = DispatchGroup()
//3 请求热门数据
dGroup.enter()
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : Date.getCurrentTime()]) { (result) in
// 1.将result转成字典类型
guard let resultDict = result as? [String : NSObject] else { return }
//2.根据data该key,获取数组
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
// 3.遍历字典,并且转成模型对象
// 3.1.设置组的属性
self.bigDataGroup.tag_name = "热门"
self.bigDataGroup.icon_name = "home_header_hot"
// 3.2.获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.bigDataGroup.anchors.append(anchor)
}
// 3.3.离开组
dGroup.leave()
}
// 4.请求第二部分颜值数据
dGroup.enter()
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in
// 1.将result转成字典类型
guard let resultDict = result as? [String : NSObject] else { return }
// 2.根据data该key,获取数组
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
// 3.遍历字典,并且转成模型对象
// 3.1.设置组的属性
self.prettyGroup.tag_name = "颜值"
self.prettyGroup.icon_name = "home_header_phone"
// 3.2.获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.prettyGroup.anchors.append(anchor)
}
// 3.3.离开组
dGroup.leave()
}
// 5.请求2-12部分游戏数据
dGroup.enter()
// http://capi.douyucdn.cn/api/v1/getHotCate?limit=4&offset=0&time=1474252024
loadAnchorData(isGroupData: true, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) {
dGroup.leave()
}
// 6.所有的数据都请求到,之后进行排序
dGroup.notify(queue: DispatchQueue.main) {
self.anchorGroups.insert(self.prettyGroup, at: 0)
self.anchorGroups.insert(self.bigDataGroup, at: 0)
finishCallback()
}
}
// 请求无线轮播的数据
func requestCycleData(_ finishCallback : @escaping () -> ()) {
NetworkTools.requestData(.get, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"]) { (result) in
// 1.获取整体字典数据
guard let resultDict = result as? [String : NSObject] else { return }
// 2.根据data的key获取数据
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
// 3.字典转模型对象
for dict in dataArray {
self.cycleModels.append(CycleModel(dict: dict))
}
finishCallback()
}
}
}
| mit | 5e16f27dbb7c132a98177a803476a00c | 31.551724 | 158 | 0.534693 | 4.468639 | false | false | false | false |
calkinssean/TIY-Assignments | Day 1/Counter/Counter/ViewController.swift | 1 | 1440 | //
// ViewController.swift
// Counter
//
// Created by Phil Wright on 1/30/16.
// Copyright © 2016 The Iron Yard. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
var currentCount: Int = Int(arc4random() % 100)
@IBOutlet weak var countTextField: UITextField!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var stepper: UIStepper!
override func viewDidLoad()
{
super.viewDidLoad()
updateViewsWithCurrentCount()
}
override func didReceiveMemoryWarning()
{
}
func updateViewsWithCurrentCount()
{
countTextField.text = "\(currentCount)"
slider.value = Float(currentCount)
stepper.value = Double(currentCount)
}
@IBAction func viewTapped(sender: UITapGestureRecognizer)
{
if countTextField.isFirstResponder()
{
countTextField.resignFirstResponder()
updateViewsWithCurrentCount()
}
}
@IBAction func slider(sender: UISlider) {
currentCount = Int(sender.value)
updateViewsWithCurrentCount()
}
@IBAction func stepper(sender: UIStepper)
{
currentCount = Int(sender.value)
updateViewsWithCurrentCount()
}
@IBAction func textFieldDidEnd(sender: AnyObject) {
print("did end on exit")
}
} | cc0-1.0 | ba97ba8239ff48636605908515edf865 | 19 | 61 | 0.602502 | 5.139286 | false | false | false | false |
tjw/swift | test/IRGen/class_resilience.swift | 1 | 26897 | // RUN: %empty-directory(%t)
// RUN: %utils/chex.py < %s > %t/class_resilience.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -enable-class-resilience %t/class_resilience.swift | %FileCheck %t/class_resilience.swift --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize -DINT=i%target-ptrsize
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -enable-class-resilience -O %t/class_resilience.swift
// CHECK: @"$S16class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvpWvd" = hidden global [[INT]] 0
// CHECK: @"$S16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd" = hidden global [[INT]] 0
// CHECK: @"$S16class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvpWvd" = hidden global [[INT]] 0
// CHECK: @"$S16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd" = hidden global [[INT]] 0
// CHECK: @"$S16class_resilience14ResilientChildC5fields5Int32VvpWvd" = hidden global [[INT]] {{8|16}}
// CHECK: @"$S16class_resilience21ResilientGenericChildCMo" = {{(protected )?}}global [[BOUNDS:{ (i32|i64), i32, i32 }]] zeroinitializer
// CHECK: @"$S16class_resilience26ClassWithResilientPropertyCMo" = {{(protected )?}}constant [[BOUNDS]]
// CHECK-SAME-32: { [[INT]] 52, i32 2, i32 13 }
// CHECK-SAME-64: { [[INT]] 80, i32 2, i32 10 }
// CHECK: @"$S16class_resilience28ClassWithMyResilientPropertyC1rAA0eF6StructVvpWvd" = hidden constant [[INT]] {{8|16}}
// CHECK: @"$S16class_resilience28ClassWithMyResilientPropertyC5colors5Int32VvpWvd" = hidden constant [[INT]] {{12|20}}
// CHECK: @"$S16class_resilience30ClassWithIndirectResilientEnumC1s14resilient_enum10FunnyShapeOvpWvd" = hidden constant [[INT]] {{8|16}}
// CHECK: @"$S16class_resilience30ClassWithIndirectResilientEnumC5colors5Int32VvpWvd" = hidden constant [[INT]] {{12|24}}
// CHECK: [[RESILIENTCHILD_NAME:@.*]] = private constant [15 x i8] c"ResilientChild\00"
// CHECK: @"$S16class_resilience14ResilientChildCMo" = {{(protected )?}}global [[BOUNDS]] zeroinitializer
// CHECK: @"$S16class_resilience14ResilientChildCMn" = {{(protected )?}}constant <{{.*}}> <{
// -- flags: class, unique, reflectable, has vtable, has resilient superclass
// CHECK-SAME: <i32 0xD004_0050>
// -- name:
// CHECK-SAME: [15 x i8]* [[RESILIENTCHILD_NAME]]
// -- num fields
// CHECK-SAME: i32 1,
// -- field offset vector offset
// CHECK-SAME: i32 3,
// CHECK-SAME: }>
// CHECK: @"$S16class_resilience16FixedLayoutChildCMo" = {{(protected )?}}global [[BOUNDS]] zeroinitializer
// CHECK: @"$S16class_resilience17MyResilientParentCMo" = {{(protected )?}}constant [[BOUNDS]]
// CHECK-SAME-32: { [[INT]] 52, i32 2, i32 13 }
// CHECK-SAME-64: { [[INT]] 80, i32 2, i32 10 }
// CHECK: @"$S16class_resilience16MyResilientChildCMo" = {{(protected )?}}constant [[BOUNDS]]
// CHECK-SAME-32: { [[INT]] 60, i32 2, i32 15 }
// CHECK-SAME-64: { [[INT]] 96, i32 2, i32 12 }
// CHECK: @"$S16class_resilience24MyResilientGenericParentCMo" = {{(protected )?}}constant [[BOUNDS]]
// CHECK-SAME-32: { [[INT]] 52, i32 2, i32 13 }
// CHECK-SAME-64: { [[INT]] 80, i32 2, i32 10 }
// CHECK: @"$S16class_resilience24MyResilientConcreteChildCMo" = {{(protected )?}}constant [[BOUNDS]]
// CHECK-SAME-32: { [[INT]] 64, i32 2, i32 16 }
// CHECK-SAME-64: { [[INT]] 104, i32 2, i32 13 }
import resilient_class
import resilient_struct
import resilient_enum
// Concrete class with resilient stored property
public class ClassWithResilientProperty {
public let p: Point
public let s: Size
public let color: Int32
public init(p: Point, s: Size, color: Int32) {
self.p = p
self.s = s
self.color = color
}
}
// Concrete class with non-fixed size stored property
public class ClassWithResilientlySizedProperty {
public let r: Rectangle
public let color: Int32
public init(r: Rectangle, color: Int32) {
self.r = r
self.color = color
}
}
// Concrete class with resilient stored property that
// is fixed-layout inside this resilience domain
public struct MyResilientStruct {
public let x: Int32
}
public class ClassWithMyResilientProperty {
public let r: MyResilientStruct
public let color: Int32
public init(r: MyResilientStruct, color: Int32) {
self.r = r
self.color = color
}
}
// Enums with indirect payloads are fixed-size
public class ClassWithIndirectResilientEnum {
public let s: FunnyShape
public let color: Int32
public init(s: FunnyShape, color: Int32) {
self.s = s
self.color = color
}
}
// Superclass is resilient, so the number of fields and their
// offsets is not known at compile time
public class ResilientChild : ResilientOutsideParent {
public var field: Int32 = 0
public override func getValue() -> Int {
return 1
}
}
// Superclass is resilient, but the class is fixed-layout.
// This simulates a user app subclassing a class in a resilient
// framework. In this case, we still want to emit a base offset
// global.
@_fixed_layout public class FixedLayoutChild : ResilientOutsideParent {
public var field: Int32 = 0
}
// Superclass is resilient, so the number of fields and their
// offsets is not known at compile time
public class ResilientGenericChild<T> : ResilientGenericOutsideParent<T> {
public var field: Int32 = 0
}
// Superclass is resilient and has a resilient value type payload,
// but everything is in one module
public class MyResilientParent {
public let s: MyResilientStruct = MyResilientStruct(x: 0)
}
public class MyResilientChild : MyResilientParent {
public let field: Int32 = 0
}
public class MyResilientGenericParent<T> {
public let t: T
public init(t: T) {
self.t = t
}
}
public class MyResilientConcreteChild : MyResilientGenericParent<Int> {
public let x: Int
public init(x: Int) {
self.x = x
super.init(t: x)
}
}
extension ResilientGenericOutsideParent {
public func genericExtensionMethod() -> A.Type {
return A.self
}
}
// ClassWithResilientProperty.color getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @"$S16class_resilience26ClassWithResilientPropertyC5colors5Int32Vvg"(%T16class_resilience26ClassWithResilientPropertyC* swiftself)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$S16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd"
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience26ClassWithResilientPropertyC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK: ret i32 [[FIELD_VALUE]]
// ClassWithResilientProperty metadata accessor
// CHECK-LABEL: define{{( protected)?}} swiftcc %swift.metadata_response @"$S16class_resilience26ClassWithResilientPropertyCMa"(
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** @"$S16class_resilience26ClassWithResilientPropertyCML"
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: call void @swift_once([[INT]]* @"$S16class_resilience26ClassWithResilientPropertyCMa.once_token", i8* bitcast (void (i8*)* @initialize_metadata_ClassWithResilientProperty to i8*), i8* undef)
// CHECK-NEXT: [[METADATA:%.*]] = load %swift.type*, %swift.type** @"$S16class_resilience26ClassWithResilientPropertyCML"
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[RESULT]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] 0, 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
// ClassWithResilientlySizedProperty.color getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @"$S16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32Vvg"(%T16class_resilience33ClassWithResilientlySizedPropertyC* swiftself)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$S16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd"
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience33ClassWithResilientlySizedPropertyC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK: ret i32 [[FIELD_VALUE]]
// ClassWithResilientlySizedProperty metadata accessor
// CHECK-LABEL: define{{( protected)?}} swiftcc %swift.metadata_response @"$S16class_resilience33ClassWithResilientlySizedPropertyCMa"(
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** @"$S16class_resilience33ClassWithResilientlySizedPropertyCML"
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: call void @swift_once([[INT]]* @"$S16class_resilience33ClassWithResilientlySizedPropertyCMa.once_token", i8* bitcast (void (i8*)* @initialize_metadata_ClassWithResilientlySizedProperty to i8*), i8* undef)
// CHECK-NEXT: [[METADATA:%.*]] = load %swift.type*, %swift.type** @"$S16class_resilience33ClassWithResilientlySizedPropertyCML"
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[RESULT]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] 0, 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
// ClassWithIndirectResilientEnum.color getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @"$S16class_resilience30ClassWithIndirectResilientEnumC5colors5Int32Vvg"(%T16class_resilience30ClassWithIndirectResilientEnumC* swiftself)
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T16class_resilience30ClassWithIndirectResilientEnumC, %T16class_resilience30ClassWithIndirectResilientEnumC* %0, i32 0, i32 2
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK: ret i32 [[FIELD_VALUE]]
// ResilientChild.field getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @"$S16class_resilience14ResilientChildC5fields5Int32Vvg"(%T16class_resilience14ResilientChildC* swiftself)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$S16class_resilience14ResilientChildC5fields5Int32VvpWvd"
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience14ResilientChildC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK: call void @swift_beginAccess
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: call void @swift_endAccess
// CHECK: ret i32 [[FIELD_VALUE]]
// ResilientGenericChild.field getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @"$S16class_resilience21ResilientGenericChildC5fields5Int32Vvg"(%T16class_resilience21ResilientGenericChildC* swiftself)
// FIXME: we could eliminate the unnecessary isa load by lazily emitting
// metadata sources in EmitPolymorphicParameters
// CHECK: load %swift.type*
// CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds %T16class_resilience21ResilientGenericChildC, %T16class_resilience21ResilientGenericChildC* %0, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ADDR]]
// CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S16class_resilience21ResilientGenericChildCMo", i32 0, i32 0)
// CHECK-NEXT: [[METADATA_OFFSET:%.*]] = add [[INT]] [[BASE]], {{16|32}}
// CHECK-NEXT: [[ISA_ADDR:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[FIELD_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_ADDR]], [[INT]] [[METADATA_OFFSET]]
// CHECK-NEXT: [[FIELD_OFFSET_ADDR:%.*]] = bitcast i8* [[FIELD_OFFSET_TMP]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_ADDR:%.*]]
// CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T16class_resilience21ResilientGenericChildC* %0 to i8*
// CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = bitcast i8* [[ADDR]] to %Ts5Int32V*
// CHECK: call void @swift_beginAccess
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0
// CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]]
// CHECK-NEXT: call void @swift_endAccess
// CHECK: ret i32 [[RESULT]]
// MyResilientChild.field getter
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @"$S16class_resilience16MyResilientChildC5fields5Int32Vvg"(%T16class_resilience16MyResilientChildC* swiftself)
// CHECK: [[FIELD_ADDR:%.*]] = getelementptr inbounds %T16class_resilience16MyResilientChildC, %T16class_resilience16MyResilientChildC* %0, i32 0, i32 2
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0
// CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]]
// CHECK: ret i32 [[RESULT]]
// ResilientGenericOutsideParent.genericExtensionMethod()
// CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @"$S15resilient_class29ResilientGenericOutsideParentC0B11_resilienceE22genericExtensionMethodxmyF"(%T15resilient_class29ResilientGenericOutsideParentC* swiftself) #0 {
// CHECK: [[ISA_ADDR:%.*]] = bitcast %T15resilient_class29ResilientGenericOutsideParentC* %0 to %swift.type**
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
// CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S15resilient_class29ResilientGenericOutsideParentCMo", i32 0, i32 0)
// CHECK-NEXT: [[GENERIC_PARAM_OFFSET:%.*]] = add [[INT]] [[BASE]], 0
// CHECK-NEXT: [[ISA_TMP:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[GENERIC_PARAM_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_TMP]], [[INT]] [[GENERIC_PARAM_OFFSET]]
// CHECK-NEXT: [[GENERIC_PARAM_ADDR:%.*]] = bitcast i8* [[GENERIC_PARAM_TMP]] to %swift.type**
// CHECK-NEXT: [[GENERIC_PARAM:%.*]] = load %swift.type*, %swift.type** [[GENERIC_PARAM_ADDR]]
// CHECK-NEXT: ret %swift.type* [[GENERIC_PARAM]]
// ClassWithResilientProperty metadata initialization function
// CHECK-LABEL: define private void @initialize_metadata_ClassWithResilientProperty
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata({{.*}}, [[INT]] {{60|96}}, [[INT]] 4)
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S16resilient_struct4SizeVMa"([[INT]] 63)
// CHECK-NEXT: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: call void @swift_initClassMetadata(%swift.type* [[METADATA]], [[INT]] 0, [[INT]] 3, {{.*}})
// CHECK-native: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{12|15}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$S16class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvWvd"
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{13|16}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$S16class_resilience26ClassWithResilientPropertyC5colors5Int32VvWvd"
// CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @"$S16class_resilience26ClassWithResilientPropertyCML" release,
// CHECK: ret void
// ClassWithResilientlySizedProperty metadata initialization function
// CHECK-LABEL: define private void @initialize_metadata_ClassWithResilientlySizedProperty
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata({{.*}}, [[INT]] {{60|96}}, [[INT]] 3)
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S16resilient_struct9RectangleVMa"([[INT]] 63)
// CHECK-NEXT: [[RECTANGLE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: call void @swift_initClassMetadata(%swift.type* [[METADATA]], [[INT]] 0, [[INT]] 2, {{.*}})
// CHECK-native: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{11|14}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$S16class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvWvd"
// CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{12|15}}
// CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$S16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvWvd"
// CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @"$S16class_resilience33ClassWithResilientlySizedPropertyCML" release,
// CHECK: ret void
// ResilientChild metadata initialization function
// CHECK-LABEL: define private void @initialize_metadata_ResilientChild(i8*)
// Initialize the superclass field...
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S15resilient_class22ResilientOutsideParentCMa"([[INT]] 1)
// CHECK: [[SUPER:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: store %swift.type* [[SUPER]], %swift.type** getelementptr inbounds ({{.*}})
// Relocate metadata if necessary...
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata(%swift.type* {{.*}}, [[INT]] {{60|96}}, [[INT]] 4)
// Initialize field offset vector...
// CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S16class_resilience14ResilientChildCMo", i32 0, i32 0)
// CHECK: [[OFFSET:%.*]] = add [[INT]] [[BASE]], {{12|24}}
// CHECK: call void @swift_initClassMetadata(%swift.type* [[METADATA]], [[INT]] 0, [[INT]] 1, i8*** {{.*}}, [[INT]]* {{.*}})
// Initialize constructor vtable override...
// CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S15resilient_class22ResilientOutsideParentCMo", i32 0, i32 0)
// CHECK: [[OFFSET:%.*]] = add [[INT]] [[BASE]], {{16|32}}
// CHECK: [[METADATA_BYTES:%.*]] = bitcast %swift.type* [[METADATA]] to i8*
// CHECK: [[VTABLE_ENTRY_ADDR:%.*]] = getelementptr inbounds i8, i8* [[METADATA_BYTES]], [[INT]] [[OFFSET]]
// CHECK: [[VTABLE_ENTRY_TMP:%.*]] = bitcast i8* [[VTABLE_ENTRY_ADDR]] to i8**
// CHECK: store i8* bitcast (%T16class_resilience14ResilientChildC* (%T16class_resilience14ResilientChildC*)* @"$S16class_resilience14ResilientChildCACycfc" to i8*), i8** [[VTABLE_ENTRY_TMP]]
// Initialize getValue() vtable override...
// CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S15resilient_class22ResilientOutsideParentCMo", i32 0, i32 0)
// CHECK: [[OFFSET:%.*]] = add [[INT]] [[BASE]], {{28|56}}
// CHECK: [[METADATA_BYTES:%.*]] = bitcast %swift.type* [[METADATA]] to i8*
// CHECK: [[VTABLE_ENTRY_ADDR:%.*]] = getelementptr inbounds i8, i8* [[METADATA_BYTES]], [[INT]] [[OFFSET]]
// CHECK: [[VTABLE_ENTRY_TMP:%.*]] = bitcast i8* [[VTABLE_ENTRY_ADDR]] to i8**
// CHECK: store i8* bitcast ([[INT]] (%T16class_resilience14ResilientChildC*)* @"$S16class_resilience14ResilientChildC8getValueSiyF" to i8*), i8** [[VTABLE_ENTRY_TMP]]
// Store the completed metadata in the cache variable...
// CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @"$S16class_resilience14ResilientChildCML" release
// CHECK: ret void
// ResilientChild.field getter dispatch thunk
// CHECK-LABEL: define{{( protected)?}} swiftcc i32 @"$S16class_resilience14ResilientChildC5fields5Int32VvgTj"(%T16class_resilience14ResilientChildC* swiftself)
// CHECK: [[ISA_ADDR:%.*]] = getelementptr inbounds %T16class_resilience14ResilientChildC, %T16class_resilience14ResilientChildC* %0, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
// CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S16class_resilience14ResilientChildCMo", i32 0, i32 0)
// CHECK-NEXT: [[METADATA_BYTES:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[VTABLE_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[METADATA_BYTES]], [[INT]] [[BASE]]
// CHECK-NEXT: [[VTABLE_OFFSET_ADDR:%.*]] = bitcast i8* [[VTABLE_OFFSET_TMP]] to i32 (%T16class_resilience14ResilientChildC*)**
// CHECK-NEXT: [[METHOD:%.*]] = load i32 (%T16class_resilience14ResilientChildC*)*, i32 (%T16class_resilience14ResilientChildC*)** [[VTABLE_OFFSET_ADDR]]
// CHECK-NEXT: [[RESULT:%.*]] = call swiftcc i32 [[METHOD]](%T16class_resilience14ResilientChildC* swiftself %0)
// CHECK-NEXT: ret i32 [[RESULT]]
// ResilientChild.field setter dispatch thunk
// CHECK-LABEL: define{{( protected)?}} swiftcc void @"$S16class_resilience14ResilientChildC5fields5Int32VvsTj"(i32, %T16class_resilience14ResilientChildC* swiftself)
// CHECK: [[ISA_ADDR:%.*]] = getelementptr inbounds %T16class_resilience14ResilientChildC, %T16class_resilience14ResilientChildC* %1, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
// CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S16class_resilience14ResilientChildCMo", i32 0, i32 0)
// CHECK-NEXT: [[METADATA_OFFSET:%.*]] = add [[INT]] [[BASE]], {{4|8}}
// CHECK-NEXT: [[METADATA_BYTES:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[VTABLE_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[METADATA_BYTES]], [[INT]] [[METADATA_OFFSET]]
// CHECK-NEXT: [[VTABLE_OFFSET_ADDR:%.*]] = bitcast i8* [[VTABLE_OFFSET_TMP]] to void (i32, %T16class_resilience14ResilientChildC*)**
// CHECK-NEXT: [[METHOD:%.*]] = load void (i32, %T16class_resilience14ResilientChildC*)*, void (i32, %T16class_resilience14ResilientChildC*)** [[VTABLE_OFFSET_ADDR]]
// CHECK-NEXT: call swiftcc void [[METHOD]](i32 %0, %T16class_resilience14ResilientChildC* swiftself %1)
// CHECK-NEXT: ret void
// FixedLayoutChild metadata initialization function
// CHECK-LABEL: define private void @initialize_metadata_FixedLayoutChild(i8*)
// Initialize the superclass field...
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S15resilient_class22ResilientOutsideParentCMa"([[INT]] 1)
// CHECK: [[SUPER:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: store %swift.type* [[SUPER]], %swift.type** getelementptr inbounds ({{.*}})
// Relocate metadata if necessary...
// CHECK: call %swift.type* @swift_relocateClassMetadata(%swift.type* {{.*}}, [[INT]] {{60|96}}, [[INT]] 4)
// CHECK: ret void
// ResilientGenericChild metadata initialization function
// CHECK-LABEL: define internal %swift.type* @"$S16class_resilience21ResilientGenericChildCMi"(%swift.type_descriptor*, i8**, i8**)
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_descriptor* %0, i8** %1, i8** %2)
// CHECK: ret %swift.type* [[METADATA]]
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$S16class_resilience21ResilientGenericChildCMr"
// CHECK-SAME: (%swift.type* [[METADATA:%.*]], i8*, i8**)
// Initialize the superclass pointer...
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S15resilient_class29ResilientGenericOutsideParentCMa"([[INT]] 257, %swift.type* %T)
// CHECK: [[SUPER:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: [[SUPER_STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1
// CHECK: [[SUPER_OK:%.*]] = icmp ule [[INT]] [[SUPER_STATUS]], 1
// CHECK: br i1 [[SUPER_OK]],
// CHECK: [[T0:%.*]] = bitcast %swift.type* [[METADATA]] to %swift.type**
// CHECK: [[SUPER_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[T0]], i32 1
// CHECK: store %swift.type* [[SUPER]], %swift.type** [[SUPER_ADDR]],
// CHECK: call void @swift_initClassMetadata(%swift.type* [[METADATA]], [[INT]] 0,
// CHECK: [[DEP:%.*]] = phi %swift.type* [ [[SUPER]], {{.*}} ], [ null, {{.*}} ]
// CHECK: [[DEP_REQ:%.*]] = phi [[INT]] [ 1, {{.*}} ], [ 0, {{.*}} ]
// CHECK: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[DEP]], 0
// CHECK: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[DEP_REQ]], 1
// CHECK: ret %swift.metadata_response [[T1]]
| apache-2.0 | 303a047418f910f6127480a16de812c1 | 57.092873 | 235 | 0.669071 | 3.703291 | false | false | false | false |
wistia/WistiaKit | Pod/Classes/Core/public/model/WistiaAsset.swift | 1 | 3760 | //
// WistiaAsset.swift
// WistiaKit
//
// Created by Daniel Spinosa on 1/25/16.
// Copyright © 2016 Wistia, Inc. All rights reserved.
//
import Foundation
/**
Represents one of the many actual files backing a `WistiaMedia`.
- Note: Some of the attributes in this struct are obtained through an internal API different from the
public Data API. These attributes are undocumented and marked internal.
See [Wistia Data API: Asset](http://wistia.com/doc/data-api#asset_object_response)
*/
public struct WistiaAsset {
/// The `WistiaMedia` this is a derivative of.
public var media: WistiaMedia
/// A direct-access URL to the content of the asset (as a String).
public var urlString: String
/// A direct-access URL to the content of the asset.
public var url: URL {
get {
return URL(string: self.urlString)!
}
}
/// The width of this specific asset, if applicable (otherwise 0).
public var width: Int64
/// The height of this specific asset, if applicable (otherwise 0).
public var height: Int64
/// The size of the asset file that's referenced by url, measured in bytes.
public var size: Int64?
/// The internal type of the asset, describing how the asset should be used. Values can include OriginalFile, FlashVideoFile, MdFlashVideoFile, HdFlashVideoFile, Mp4VideoFile, MdMp4VideoFile, HdMp4VideoFile, IPhoneVideoFile, StillImageFile, SwfFile, Mp3AudioFile, and LargeImageFile.
public var type: String
/// The status of this asset
public var status: WistiaObjectStatus?
// MARK: - ------------Internal------------
public var slug: String?
internal var displayName: String?
internal var container: String?
internal var codec: String?
internal var ext: String?
internal var bitrate: Int64?
}
extension WistiaAsset: WistiaJSONParsable {
/// Initialize a WistiaAsset from the provided JSON hash. It is unlikely you would use this
/// method directly as assets are generally returned inside of their parent WistiaMedia. Instead,
/// see WistiaMedia.create(from:).
///
/// - seealso: WistiaMedia.create(from:)
///
/// - Note: Prints error message to console on parsing issue.
///
/// - parameter dictionary: JSON hash representing the WistiaAsset.
/// - parameter media: The owning WistiaMedia to which this asset belongs.
///
/// - returns: Initialized WistiaAsset if parsing is successful.
init?(from dictionary: [String: Any], forMedia media:WistiaMedia) {
let parser = Parser(dictionary: dictionary)
do {
self.media = media
urlString = try parser.fetch("url")
type = try parser.fetch("type")
width = parser.fetchOptional("width", default: 0, transformation: { (w:Int) in Int64(w) })
height = parser.fetchOptional("height", default: 0, transformation: { (h:Int) in Int64(h) })
size = parser.fetchOptional("size", transformation: { (s:Int) in Int64(s) })
if size == nil {
size = parser.fetchOptional("filesize", transformation: { (s:Int) in Int64(s) })
}
displayName = try parser.fetchOptional("display_name")
container = try parser.fetchOptional("container")
codec = try parser.fetchOptional("codec")
ext = try parser.fetchOptional("ext")
bitrate = parser.fetchOptional("bitrate", transformation: { (b:Int) in Int64(b) })
status = parser.fetchOptional("status") { WistiaObjectStatus(failsafeFromRaw: $0) }
slug = try parser.fetchOptional("slug")
} catch let error {
print(error)
return nil
}
}
}
| mit | bf838689271da25190d960f2beba0f8a | 36.217822 | 287 | 0.650705 | 4.214126 | false | false | false | false |
sora0077/iTunesMusicKit | src/Entity/Album.swift | 1 | 2274 | //
// Album.swift
// iTunesMusicKit
//
// Created by 林達也 on 2015/10/14.
// Copyright © 2015年 jp.sora0077. All rights reserved.
//
import Foundation
public struct Album {
public var id: String
public var name: String
public var censoredName: String?
public var artistId: String
public var artist: Artist?
public var url: String
public var artwork: (
thumbnail: Artwork,
large: Artwork
)
public var discCount: Int
public var discNumber: Int
public var trackCount: Int
public var price: String
public var priceDisplay: String
public var releaseDate: String
public var copyright: String
public struct Artwork {
private static let regex = try! NSRegularExpression(pattern: "\\d{2,3}x\\d{2,3}", options: [])
public enum Size {
case Large
case Thumbnail
case Custom(width: Int, height: Int)
var width: Int {
switch self {
case .Large:
return 600
case .Thumbnail:
return 300
case let .Custom(width: width, height: _):
return width
}
}
var height: Int {
switch self {
case .Large:
return 600
case .Thumbnail:
return 300
case let .Custom(width: _, height: height):
return height
}
}
}
public var width: Int
public var height: Int
public var url: String
init(url: String, size: Size) {
let width = size.width
let height = size.height
let result = NSMutableString(string: url)
Artwork.regex.replaceMatchesInString(result, options: [], range: NSMakeRange(0, url.characters.count), withTemplate: "\(width)x\(height)")
self.url = result as String
self.width = width
self.height = height
}
}
} | mit | 11b2315363bca299afb3b015c2ceb68a | 22.852632 | 150 | 0.486534 | 5.341981 | false | false | false | false |
mutualmobile/HolidayCard | CardBuilder/CardBuilder/CardBuilder.swift | 1 | 2090 | //
// CardBuilder.swift
// CardBuilder
//
// Created by Conrad Stoll on 12/7/14.
// Copyright (c) 2014 Mutual Mobile. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
public func printCard(card : Card) -> UIImage {
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, CGRectMake(0, 0, 640, 960), nil);
UIGraphicsBeginPDFPage();
let pdfContext = UIGraphicsGetCurrentContext()
let pageView = UIView(frame: CGRectMake(0, 0, 640, 960))
card.view.frame.origin.y = 480
pageView.addSubview(card.view)
pageView.layer.renderInContext(pdfContext!)
UIGraphicsEndPDFContext();
let documentDirectories = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true)
let documentDirectory: AnyObject? = documentDirectories.first
let documentDirectoryFilename = documentDirectory?.stringByAppendingPathComponent("HolidayCard.pdf")
pdfData.writeToFile(documentDirectoryFilename!, atomically: true)
UIGraphicsBeginImageContext(card.view.bounds.size)
card.view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public func printDocumentsDirectory() -> NSString {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
return documentsPath
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
} | mit | 0d46965397ce40f8514a50cfc574a738 | 31.169231 | 151 | 0.698086 | 4.675615 | false | false | false | false |
pksprojects/ElasticSwift | Sources/ElasticSwift/Requests/MultiGetRequest.swift | 1 | 11487 | //
// MultiGetRequest.swift
// ElasticSwift
//
// Created by Prafull Kumar Soni on 8/23/19.
//
import ElasticSwiftCore
import Foundation
import NIOHTTP1
// MARK: - Multi-Get Request Builder
public class MultiGetRequestBuilder: RequestBuilder {
public typealias RequestType = MultiGetRequest
private var _index: String?
private var _type: String?
private var _items: [MultiGetRequest.Item] = []
private var _source: String?
private var _sourceExcludes: [String]?
private var _sourceIncludes: [String]?
private var _realTime: Bool?
private var _refresh: Bool?
private var _routing: String?
private var _preference: String?
private var _storedFields: [String]?
public init() {}
@discardableResult
@available(*, deprecated, message: "Elasticsearch has deprecated use of custom types and will be remove in 7.0")
public func set(type: String) -> MultiGetRequestBuilder {
_type = type
return self
}
@discardableResult
public func set(index: String) -> MultiGetRequestBuilder {
_index = index
return self
}
@discardableResult
public func set(items: [MultiGetRequest.Item]) -> MultiGetRequestBuilder {
_items = items
return self
}
@discardableResult
public func add(item: MultiGetRequest.Item) -> MultiGetRequestBuilder {
_items.append(item)
return self
}
@discardableResult
public func set(source: String) -> MultiGetRequestBuilder {
_source = source
return self
}
@discardableResult
public func set(sourceExcludes: [String]) -> MultiGetRequestBuilder {
_sourceExcludes = sourceExcludes
return self
}
@discardableResult
public func set(sourceIncludes: [String]) -> MultiGetRequestBuilder {
_sourceIncludes = sourceIncludes
return self
}
@discardableResult
public func set(realTime: Bool) -> MultiGetRequestBuilder {
_realTime = realTime
return self
}
@discardableResult
public func set(refresh: Bool) -> MultiGetRequestBuilder {
_refresh = refresh
return self
}
@discardableResult
public func set(routing: String) -> MultiGetRequestBuilder {
_routing = routing
return self
}
@discardableResult
public func set(preference: String) -> MultiGetRequestBuilder {
_preference = preference
return self
}
@discardableResult
public func set(storedFields: [String]) -> MultiGetRequestBuilder {
_storedFields = storedFields
return self
}
public var index: String? {
return _index
}
public var type: String? {
return _type
}
public var source: String? {
return _source
}
public var items: [MultiGetRequest.Item] {
return _items
}
public var sourceExcludes: [String]? {
return _sourceExcludes
}
public var sourceIncludes: [String]? {
return _sourceIncludes
}
public var realTime: Bool? {
return _realTime
}
public var refresh: Bool? {
return _refresh
}
public var routing: String? {
return _routing
}
public var preference: String? {
return _preference
}
public var storedFields: [String]? {
return _storedFields
}
public func build() throws -> MultiGetRequest {
return try MultiGetRequest(withBuilder: self)
}
}
// MARK: - Multi-Get Request
public struct MultiGetRequest: Request {
public var headers = HTTPHeaders()
public let index: String?
public let type: String?
public let items: [Item]
public var source: String?
public var sourceExcludes: [String]?
public var sourceIncludes: [String]?
public var realTime: Bool?
public var refresh: Bool?
public var routing: String?
public var preference: String?
public var storedFields: [String]?
public init(index: String? = nil, type: String? = nil, items: [MultiGetRequest.Item], source: String? = nil, sourceExcludes: [String]? = nil, sourceIncludes: [String]? = nil, realTime: Bool? = nil, refresh: Bool? = nil, routing: String? = nil, preference: String? = nil, storedFields: [String]? = nil) {
self.index = index
self.type = type
self.items = items
self.source = source
self.sourceExcludes = sourceExcludes
self.sourceIncludes = sourceIncludes
self.realTime = realTime
self.refresh = refresh
self.routing = routing
self.preference = preference
self.storedFields = storedFields
}
internal init(withBuilder builder: MultiGetRequestBuilder) throws {
guard !builder.items.isEmpty else {
throw RequestBuilderError.atlestOneElementRequired("item")
}
self.init(index: builder.index, type: builder.type, items: builder.items, source: builder.source, sourceExcludes: builder.sourceIncludes, sourceIncludes: builder.sourceExcludes, realTime: builder.realTime, refresh: builder.refresh, routing: builder.routing, preference: builder.preference, storedFields: builder.storedFields)
}
public var queryParams: [URLQueryItem] {
var params = [URLQueryItem]()
if let source = self.source {
params.append(URLQueryItem(name: QueryParams.source.rawValue, value: source))
}
if let excludes = sourceExcludes {
params.append(URLQueryItem(name: QueryParams.sourceExcludes.rawValue, value: excludes.joined(separator: ",")))
}
if let includes = sourceIncludes {
params.append(URLQueryItem(name: QueryParams.sourceIncludes.rawValue, value: includes.joined(separator: ",")))
}
if let realTime = self.realTime {
params.append(URLQueryItem(name: QueryParams.realTime.rawValue, value: String(realTime)))
}
if let refresh = self.refresh {
params.append(URLQueryItem(name: QueryParams.refresh.rawValue, value: String(refresh)))
}
if let routing = self.routing {
params.append(URLQueryItem(name: QueryParams.routing.rawValue, value: routing))
}
if let preference = self.preference {
params.append(URLQueryItem(name: QueryParams.preference.rawValue, value: preference))
}
if let storedFields = self.storedFields {
params.append(URLQueryItem(name: QueryParams.storedFields.rawValue, value: storedFields.joined(separator: ",")))
}
return params
}
public var method: HTTPMethod {
return .POST
}
public var endPoint: String {
var _endPoint = "/_mget"
if let type = self.type {
_endPoint = "/" + type + _endPoint
}
if let index = self.index {
_endPoint = "/" + index + _endPoint
}
return _endPoint
}
public func makeBody(_ serializer: Serializer) -> Result<Data, MakeBodyError> {
let body = Body(docs: items)
return serializer.encode(body).mapError { error -> MakeBodyError in
.wrapped(error)
}
}
struct Body: Encodable {
public let docs: [Item]
}
public struct Item: Codable, Equatable {
public let index: String
public let type: String?
public let id: String
public let routing: String?
public let parent: String?
public let fetchSource: Bool?
public let sourceIncludes: [String]?
public let sourceExcludes: [String]?
public let storedFields: [String]?
public init(index: String, type: String? = nil, id: String, routing: String? = nil, parent: String? = nil, fetchSource: Bool? = nil, sourceIncludes: [String]? = nil, sourceExcludes: [String]? = nil, storedFields: [String]? = nil) {
self.index = index
self.type = type
self.id = id
self.routing = routing
self.parent = parent
self.fetchSource = fetchSource
self.sourceIncludes = sourceIncludes
self.sourceExcludes = sourceExcludes
self.storedFields = storedFields
}
enum CodingKeys: String, CodingKey {
case index = "_index"
case type = "_type"
case id = "_id"
case routing
case parent
case source = "_source"
case storedFields = "stored_fields"
}
enum SourceCodingKeys: String, CodingKey {
case include
case exclude
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(index, forKey: .index)
try container.encode(id, forKey: .id)
try container.encodeIfPresent(type, forKey: .type)
try container.encodeIfPresent(routing, forKey: .routing)
try container.encodeIfPresent(parent, forKey: .parent)
try container.encodeIfPresent(storedFields, forKey: .storedFields)
if let fetchSource = self.fetchSource, self.sourceIncludes == nil && sourceExcludes == nil {
try container.encodeIfPresent(fetchSource, forKey: .source)
} else if sourceIncludes != nil || sourceExcludes != nil {
var nested = container.nestedContainer(keyedBy: SourceCodingKeys.self, forKey: .source)
try nested.encodeIfPresent(sourceIncludes, forKey: .include)
try nested.encodeIfPresent(sourceExcludes, forKey: .exclude)
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
index = try container.decode(String.self, forKey: .index)
id = try container.decode(String.self, forKey: .id)
type = try container.decodeIfPresent(String.self, forKey: .type)
routing = try container.decodeIfPresent(String.self, forKey: .routing)
parent = try container.decodeIfPresent(String.self, forKey: .parent)
storedFields = try container.decodeIfPresent([String].self, forKey: .storedFields)
do {
fetchSource = try container.decodeIfPresent(Bool.self, forKey: .source)
sourceIncludes = nil
sourceExcludes = nil
} catch {
do {
sourceIncludes = try container.decode([String].self, forKey: .source)
fetchSource = nil
sourceExcludes = nil
} catch {
let sourceContainer = try container.nestedContainer(keyedBy: SourceCodingKeys.self, forKey: .source)
fetchSource = nil
sourceIncludes = try sourceContainer.decodeIfPresent([String].self, forKey: .include)
sourceExcludes = try sourceContainer.decodeIfPresent([String].self, forKey: .exclude)
}
}
}
}
}
extension MultiGetRequest: Equatable {
public static func == (lhs: MultiGetRequest, rhs: MultiGetRequest) -> Bool {
return lhs.index == rhs.index
&& lhs.items == rhs.items
&& lhs.type == rhs.type
&& lhs.headers == rhs.headers
&& lhs.method == rhs.method
&& lhs.queryParams == rhs.queryParams
}
}
| mit | 846f1d57e22013fd03298ad3d6cd9644 | 32.686217 | 333 | 0.619918 | 4.796242 | false | false | false | false |
SomeSimpleSolutions/MemorizeItForever | MemorizeItForeverCore/MemorizeItForeverCoreTests/Helper/FakeWordDataAccess.swift | 1 | 2945 | //
// FakeWordDataAccess.swift
// MemorizeItForeverCore
//
// Created by Hadi Zamani on 10/22/16.
// Copyright © 2016 SomeSimpleSolutions. All rights reserved.
//
import Foundation
import BaseLocalDataAccess
@testable import MemorizeItForeverCore
class FakeWordDataAccess: WordDataAccessProtocol{
public func fetchWords(phrase: String, status: WordStatus, fetchLimit: Int, fetchOffset: Int) throws -> [WordModel] {
var word = WordModel()
word.wordId = UUID()
word.phrase = phrase
word.meaning = "Book"
word.order = 1
word.setId = UUID()
word.status = status.rawValue
return [word]
}
public func fetchWords(status: WordStatus, fetchLimit: Int, fetchOffset: Int) throws -> [WordModel] {
var word = WordModel()
word.wordId = UUID()
word.phrase = "Livre"
word.meaning = "Book"
word.order = 1
word.setId = UUID()
word.status = status.rawValue
return [word]
}
func save(_ wordModel: WordModel) throws {
guard let phrase = wordModel.phrase,
let meaning = wordModel.meaning,
let _ = wordModel.setId,
!phrase.trim().isEmpty,
!meaning.trim().isEmpty else {
return
}
objc_setAssociatedObject(self, &resultKey, FakeSetDataAccessEnum.save, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
func edit(_ wordModel: WordModel) throws {
objc_setAssociatedObject(self, &phraseKey, wordModel.phrase, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_setAssociatedObject(self, &meaningKey, wordModel.meaning, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_setAssociatedObject(self, &statusKey, wordModel.status, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_setAssociatedObject(self, &orderKey, wordModel.order, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_setAssociatedObject(self, &wordIdKey, wordModel.wordId, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_setAssociatedObject(self, &setIdKey, wordModel.setId, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
func delete(_ wordModel: WordModel) throws {
objc_setAssociatedObject(self, &resultKey, FakeSetDataAccessEnum.delete, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
func fetchAll(fetchLimit: Int?) throws -> [WordModel] {
return []
}
func fetchLast(set: SetModel, wordStatus: WordStatus) throws -> WordModel? {
if let result = objc_getAssociatedObject(self, &wordKey) as? WordModel{
return result
}
return nil
}
func fetchWithNotStartedStatus(set: SetModel, fetchLimit: Int) throws -> [WordModel] {
var word = WordModel()
word.wordId = UUID()
word.phrase = "Livre"
word.meaning = "Book"
word.order = 1
word.setId = UUID()
word.status = WordStatus.notStarted.rawValue
return [word]
}
}
| mit | f8251adf1c0b456f6d3a3250e27a55dc | 35.8 | 121 | 0.648098 | 4.329412 | false | false | false | false |
iosprogrammingwithswift/iosprogrammingwithswift | 15_SwiftNetworking/SwiftNetworking/ViewController.swift | 1 | 1697 | //
// ViewController.swift
// SwiftNetworking
//
// Created by Andreas Wittmann on 11/01/15.
// Copyright (c) 2015 🐨 + 🙉. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
let wuerzburgWeatherURL:NSURL = NSURL(string:"http://api.openweathermap.org/data/2.5/weather?q=wuerzburg")!
//NSURLSession
let request: NSURLRequest = NSURLRequest(URL:wuerzburgWeatherURL)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
session.dataTaskWithRequest(request, completionHandler:
{(data, response, error) in
guard data != nil else {
print("no data found: \(error)")
return
}
guard error != nil else {
print("no error found: \(error)")
return
}
var jsonResult:NSDictionary!
do {
jsonResult = try (NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary)!
} catch {
print(error)
}
guard jsonResult != nil else{
return
}
print(jsonResult)
}).resume()
}
} | mit | 6ba4a9c5a6f66fc18e2642dfee7d43e4 | 32.176471 | 150 | 0.553519 | 5.437299 | false | true | false | false |
edragoev1/pdfjet | Sources/PDFjet/Field.swift | 1 | 2085 | /**
* Field.swift
*
Copyright 2020 Innovatics Inc.
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
/**
* Please see Example_45
*/
public class Field {
var x: Float
var values: [String]
var actualText: [String]
var altDescription: [String]
var format: Bool = false
public init(_ x: Float, _ values: [String], _ format: Bool) {
self.x = x
self.values = values
self.actualText = [String]()
self.altDescription = [String]()
self.format = format
for value in self.values {
self.actualText.append(value)
self.altDescription.append(value)
}
}
public convenience init(_ x: Float, _ values: [String]) {
self.init(x, values, false)
}
@discardableResult
public func setAltDescription(_ altDescription: String) -> Field {
self.altDescription[0] = altDescription
return self
}
@discardableResult
public func setActualText(_ actualText: String) -> Field {
self.actualText[0] = actualText
return self
}
}
| mit | 743f82bf967ff7f51e52ef2bd9bba696 | 28.785714 | 78 | 0.698801 | 4.398734 | false | false | false | false |
Sherlouk/monzo-vapor | Sources/FeedItem.swift | 1 | 1893 | import Foundation
protocol FeedItem {
var type: String { get }
var params: [String: String] { get }
var url: URL? { get }
func validate() throws
}
public struct BasicFeedItem: FeedItem {
var type: String {
return "basic"
}
public var title: String
public var imageUrl: URL
public var url: URL?
public var body: String?
public var options: [BasicFeedItemStyleOptions]
public init(title: String, imageUrl: URL, openUrl: URL? = nil, body: String? = nil, options: [BasicFeedItemStyleOptions] = []) {
self.title = title
self.imageUrl = imageUrl
self.url = openUrl
self.body = body
self.options = options
}
var params: [String: String] {
var builder = [String: String]()
builder["title"] = title
builder["image_url"] = imageUrl.absoluteString
if let body = body {
builder["body"] = body
}
options.forEach {
switch $0 {
case .backgroundColor(let color): builder["background_color"] = color
case .titleColor(let color): builder["title_color"] = color
case .bodyColor(let color): builder["body_color"] = color
}
}
return builder
}
func validate() throws {
if title.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
throw MonzoUsageError.invalidFeedItem
}
}
}
public enum BasicFeedItemStyleOptions {
/// Sets the background color of the feed item. Value should be a HEX code
case backgroundColor(String)
/// Sets the text color of the feed item's title label. Value should be a HEX code
case titleColor(String)
/// Sets the text color of the feed item's body label, if one exists. Value should be a HEX code
case bodyColor(String)
}
| mit | c8f0efa6568499971f380e874d8b9bee | 28.123077 | 132 | 0.596936 | 4.528708 | false | false | false | false |
SwiftKit/Reactant | Source/Core/View/ButtonBase.swift | 2 | 3323 | //
// ButtonBase.swift
// Reactant
//
// Created by Filip Dolnik on 09.11.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import RxSwift
@available(*, deprecated, message: "This class has been deprecated by ControlBase")
open class ButtonBase<STATE, ACTION>: UIButton, ComponentWithDelegate, Configurable {
public typealias StateType = STATE
public typealias ActionType = ACTION
public let lifetimeDisposeBag = DisposeBag()
public let componentDelegate = ComponentDelegate<STATE, ACTION, ButtonBase<STATE, ACTION>>()
open var actions: [Observable<ACTION>] {
return []
}
open var action: Observable<ACTION> {
return componentDelegate.action
}
open var configuration: Configuration = .global {
didSet {
layoutMargins = configuration.get(valueFor: Properties.layoutMargins)
configuration.get(valueFor: Properties.Style.button)(self)
}
}
open override class var requiresConstraintBasedLayout: Bool {
return true
}
#if ENABLE_SAFEAREAINSETS_FALLBACK
open override var frame: CGRect {
didSet {
fallback_computeSafeAreaInsets()
}
}
open override var bounds: CGRect {
didSet {
fallback_computeSafeAreaInsets()
}
}
open override var center: CGPoint {
didSet {
fallback_computeSafeAreaInsets()
}
}
#endif
public init() {
super.init(frame: CGRect.zero)
componentDelegate.ownerComponent = self
translatesAutoresizingMaskIntoConstraints = false
if let reactantUi = self as? ReactantUI {
reactantUi.__rui.setupReactantUI()
// On these platforms Apple changed the behavior of traitCollectionDidChange that it's not guaranteed
// to be called at least once. We need it to setup trait-dependent values in RUI.
if #available(iOS 13.0, tvOS 13.0, macOS 10.15, *) {
reactantUi.__rui.updateReactantUI()
}
}
loadView()
setupConstraints()
resetActions()
reloadConfiguration()
afterInit()
componentDelegate.canUpdate = true
}
@available(*, unavailable)
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
if let reactantUi = self as? ReactantUI {
type(of: reactantUi.__rui).destroyReactantUI(target: self)
}
}
open func afterInit() {
}
open func update() {
}
public func observeState(_ when: ObservableStateEvent) -> Observable<STATE> {
return componentDelegate.observeState(when)
}
open func loadView() {
}
open func setupConstraints() {
}
open func needsUpdate() -> Bool {
return true
}
open override func addSubview(_ view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
super.addSubview(view)
}
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if let reactantUi = self as? ReactantUI {
reactantUi.__rui.updateReactantUI()
}
}
}
| mit | 3acce2b4d92382d51e0d98d76f575cef | 24.166667 | 113 | 0.63245 | 4.958209 | false | false | false | false |
alisidd/iOS-WeJ | WeJ/Play Tracks/BackgroundTask.swift | 1 | 2038 | //
// BackgroundTask.swift
//
// Created by Yaro on 8/27/16.
// Copyright © 2016 Yaro. All rights reserved.
//
import AVFoundation
class BackgroundTask {
static var player = AVAudioPlayer()
static var isPlaying = false
static func startBackgroundTask() {
DispatchQueue.global(qos: .userInitiated).async {
if !isPlaying {
NotificationCenter.default.addObserver(self, selector: #selector(interuptedAudio), name: NSNotification.Name.AVAudioSessionInterruption, object: AVAudioSession.sharedInstance())
playAudio()
isPlaying = true
}
}
}
static func stopBackgroundTask() {
DispatchQueue.global(qos: .userInitiated).async {
if isPlaying {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVAudioSessionInterruption, object: nil)
player.stop()
isPlaying = false
}
}
}
@objc static func interuptedAudio(_ notification: Notification) {
if notification.name == NSNotification.Name.AVAudioSessionInterruption && notification.userInfo != nil {
var info = notification.userInfo!
var intValue = 0
(info[AVAudioSessionInterruptionTypeKey]! as AnyObject).getValue(&intValue)
if intValue == 1 { playAudio() }
}
}
private static func playAudio() {
do {
let bundle = Bundle.main.path(forResource: "BlankAudio", ofType: "wav")
let alertSound = URL(fileURLWithPath: bundle!)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
try player = AVAudioPlayer(contentsOf: alertSound)
player.numberOfLoops = -1
player.volume = 0.01
player.prepareToPlay()
player.play()
} catch { print(error) }
}
}
| gpl-3.0 | bf00965efaadf8803e4c3cb9369e4147 | 34.12069 | 193 | 0.614629 | 5.346457 | false | false | false | false |
ps2/rileylink_ios | RileyLinkBLEKit/RileyLinkDevice.swift | 1 | 2437 | //
// RileyLinkDevice.swift
// RileyLinkBLEKit
//
// Copyright © 2017 Pete Schwamb. All rights reserved.
//
import CoreBluetooth
public enum RileyLinkHardwareType {
case riley
case orange
case ema
var monitorsBattery: Bool {
if self == .riley {
return false
}
return true
}
}
public struct RileyLinkDeviceStatus {
public let lastIdle: Date?
public let name: String?
public let version: String
public let ledOn: Bool
public let vibrationOn: Bool
public let voltage: Float?
public let battery: Int?
public let hasPiezo: Bool
public init(lastIdle: Date?, name: String?, version: String, ledOn: Bool, vibrationOn: Bool, voltage: Float?, battery: Int?, hasPiezo: Bool) {
self.lastIdle = lastIdle
self.name = name
self.version = version
self.ledOn = ledOn
self.vibrationOn = vibrationOn
self.voltage = voltage
self.battery = battery
self.hasPiezo = hasPiezo
}
}
public protocol RileyLinkDevice {
var isConnected: Bool { get }
var rlFirmwareDescription: String { get }
var hasOrangeLinkService: Bool { get }
var hardwareType: RileyLinkHardwareType? { get }
var rssi: Int? { get }
var name: String? { get }
var deviceURI: String { get }
var peripheralIdentifier: UUID { get }
var peripheralState: CBPeripheralState { get }
func readRSSI()
func setCustomName(_ name: String)
func updateBatteryLevel()
func orangeAction(_ command: OrangeLinkCommand)
func setOrangeConfig(_ config: OrangeLinkConfigurationSetting, isOn: Bool)
func orangeWritePwd()
func orangeClose()
func orangeReadSet()
func orangeReadVDC()
func findDevice()
func setDiagnosticeLEDModeForBLEChip(_ mode: RileyLinkLEDMode)
func readDiagnosticLEDModeForBLEChip(completion: @escaping (RileyLinkLEDMode?) -> Void)
func assertOnSessionQueue()
func sessionQueueAsyncAfter(deadline: DispatchTime, execute: @escaping () -> Void)
func runSession(withName name: String, _ block: @escaping (_ session: CommandSession) -> Void)
func getStatus(_ completion: @escaping (_ status: RileyLinkDeviceStatus) -> Void)
}
extension Array where Element == RileyLinkDevice {
public var firstConnected: Element? {
return self.first { (device) -> Bool in
return device.isConnected
}
}
}
| mit | 5a7a8a56362721c6ca5b3201213a6f6c | 27 | 146 | 0.672414 | 4.229167 | false | false | false | false |
peterentwistle/SwiftCSVReader | CSVReader/CSV+Write.swift | 1 | 1678 | //
// CSV+Write.swift
// CSVReader
//
// Copyright © 2017 Peter Entwistle. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
extension CSV: Writable {
public func write(url: URL, delimiter: String = ",", atomically: Bool = true, encoding: String.Encoding = .utf8) {
let data: String = ""
try! data.write(to: url, atomically: atomically, encoding: encoding)
}
func createCSV(delimiter: String) -> String {
var data = ""
// Start with headers
for header in headers {
data += header + delimiter + newLine
}
return data
}
}
| mit | 97b401f03106a0a4a57795ace11e52a5 | 37.113636 | 118 | 0.697078 | 4.311054 | false | false | false | false |
leemorgan/Swift8 | Swift8/AppDelegate.swift | 1 | 1730 | //
// AppDelegate.swift
// Swift8
//
// Created by Lee Morgan on 2/24/15.
// Copyright (c) 2015 Lee Morgan. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
@IBOutlet weak var pauseResumeMenuItem: NSMenuItem!
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var swift8view: Swift8View!
var swift8 = Swift8()
var paused = false
var displayTimer: Timer?
func applicationDidFinishLaunching(_ aNotification: Notification) {
openROM(nil)
displayTimer = Timer.scheduledTimer(timeInterval: 1.0/60.0, target: self, selector: #selector(AppDelegate.updateDisplay), userInfo: nil, repeats: true)
_ = swift8view.becomeFirstResponder()
}
@IBAction func openROM(_ sender: AnyObject?) {
pause()
let openPanel = NSOpenPanel()
openPanel.begin {
result in
if result == NSFileHandlingPanelOKButton {
if let path = openPanel.url?.path {
self.swift8.loadROM(path: path)
self.resume()
}
}
}
}
@IBAction func togglePauseResume(_ sender: AnyObject?) {
if paused {
resume()
}
else {
pause()
}
}
func pause() {
paused = true
swift8.paused = paused
pauseResumeMenuItem.title = "Resume"
}
func resume() {
paused = false
swift8.paused = paused
pauseResumeMenuItem.title = "Pause"
}
func updateDisplay() {
if swift8.needsDisplay {
swift8view.needsDisplay = true
swift8.needsDisplay = false
}
}
func windowWillResize(_ sender: NSWindow, to frameSize: NSSize) -> NSSize {
let windowWidth = floor(frameSize.width / 64) * 64
return NSSize(width: windowWidth, height: frameSize.height)
}
}
| mit | ced6326e985a1449f79562144b77ce91 | 16.474747 | 153 | 0.671098 | 3.649789 | false | false | false | false |
AgaKhanFoundation/WCF-iOS | Steps4Impact/Challenge/CreateTeamSuccessViewController.swift | 1 | 4506 | /**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import UIKit
import SnapKit
class CreateTeamSuccessViewController: ViewController {
private let checkmarkImageView = UIImageView(image: Assets.checkmark.image)
private let titleLabel = UILabel(typography: .bodyRegular)
private let lblNextSteps: UILabel = UILabel(typography: .bodyRegular)
private let inviteButton = Button(style: .primary)
private let btnContinue: Button = Button(style: .secondary)
private let event: Event?
private var teamName = ""
public init(for event: Event?, teamName: String) {
self.event = event
self.teamName = teamName
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func configureView() {
super.configureView()
title = Strings.Challenge.CreateTeam.title
checkmarkImageView.contentMode = .scaleAspectFit
titleLabel.text = Strings.Challenge.CreateTeam.successTitle
titleLabel.textAlignment = .center
lblNextSteps.text = "Next, invite friends to join. You have \((event?.teamLimit ?? 1) - 1) spots remaining on your team." // swiftlint:disable:this line_length
lblNextSteps.textAlignment = .center
inviteButton.title = "Invite Friends to Join"
inviteButton.addTarget(self, action: #selector(inviteButtonTapped), for: .touchUpInside)
btnContinue.title = Strings.Challenge.CreateTeam.continue
btnContinue.addTarget(self, action: #selector(continueTapped), for: .touchUpInside)
navigationItem.leftBarButtonItem = UIBarButtonItem(
image: Assets.close.image,
style: .plain,
target: self,
action: #selector(closeButtonTapped))
view.addSubview(checkmarkImageView) {
$0.height.width.equalTo(100)
$0.centerX.equalToSuperview()
$0.top.equalTo(view.safeAreaLayoutGuide).inset(Style.Padding.p32)
}
view.addSubview(titleLabel) {
$0.leading.trailing.equalToSuperview().inset(Style.Padding.p32)
$0.top.equalTo(checkmarkImageView.snp.bottom).offset(Style.Padding.p32)
}
view.addSubview(lblNextSteps) { (make) in
make.leading.trailing.equalToSuperview().inset(Style.Padding.p32)
make.top.equalTo(titleLabel.snp.bottom).offset(Style.Padding.p32)
}
// TODO(samisuteria) add image upload and visibility toggle
let stack: UIStackView = UIStackView()
stack.axis = .vertical
stack.spacing = Style.Padding.p8
stack.distribution = .fillEqually
stack.addArrangedSubviews(inviteButton, btnContinue)
view.addSubview(stack) {
$0.leading.trailing.equalToSuperview().inset(Style.Padding.p32)
$0.top.equalTo(lblNextSteps.snp.bottom).offset(Style.Padding.p24)
}
}
@objc
func closeButtonTapped() {
dismiss(animated: true, completion: nil)
}
@objc
func inviteButtonTapped() {
AppController.shared.shareTapped(
viewController: self,
shareButton: inviteButton,
string: Strings.Share.item(teamName: teamName))
}
@objc
private func continueTapped() {
self.dismiss(animated: true)
}
}
| bsd-3-clause | 6d84c0795a8d00196b70de72e04057d0 | 35.04 | 163 | 0.738291 | 4.306883 | false | false | false | false |
jayesh15111988/JKWayfairPriceGame | JKWayfairPriceGame/Random.swift | 1 | 1774 | //
// Random.swift
// JKWayfairPriceGame
//
// Created by Jayesh Kawli Backup on 8/19/16.
// Copyright © 2016 Jayesh Kawli Backup. All rights reserved.
//
import Foundation
func negativeRandomNumberInRange(lowerValue: Int, upperValue: Int) -> Int {
return Int(arc4random_uniform(UInt32(upperValue - lowerValue + 1))) + lowerValue
}
func positiveRandomNumberInRange(lowerValue: UInt32, upperValue: UInt32) -> Int {
return Int(arc4random_uniform(upperValue - lowerValue + 1) + lowerValue)
}
func randomChoicesWith(correctValue: Int, numberOfRandomOptions: Int, randomOffset: Int) -> [QuizOption] {
var randomChoices: [Int] = [correctValue]
let lowerOffset = ((correctValue - randomOffset) <= 0) ? 1 : (correctValue - randomOffset)
var upperOffset = correctValue + randomOffset
// This check is to avoid an infinite loop in case difference between upper and lower offet is less than total number of options. That will cause an infinite loop during random options generation.
if upperOffset - lowerOffset < numberOfRandomOptions {
while upperOffset - lowerOffset < numberOfRandomOptions {
upperOffset = upperOffset + 1
}
}
while randomChoices.count < numberOfRandomOptions {
let randomChoice = Int(positiveRandomNumberInRange(UInt32(lowerOffset), upperValue: UInt32(upperOffset)))
if (randomChoices.contains(randomChoice) == false) {
randomChoices.append(randomChoice)
}
}
randomChoices = randomChoices.shuffle()
let randomQuizOptions = randomChoices.map({
(value: Int) -> QuizOption in
return QuizOption(name: String(value), isCorrectOption: value == correctValue)
})
return randomQuizOptions
} | mit | 71830f51b422d091aa11d6081defa6dc | 36.744681 | 200 | 0.701072 | 4.366995 | false | false | false | false |
MukeshKumarS/Swift | stdlib/public/core/Index.swift | 1 | 13453 | //===--- Index.swift - A position in a CollectionType ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// ForwardIndexType, BidirectionalIndexType, and RandomAccessIndexType
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//===--- Dispatching advance and distance functions -----------------------===//
// These generic functions are for user consumption; they dispatch to the
// appropriate implementation for T.
@available(*, unavailable, message="call the 'distanceTo(end)' method on the index")
public func distance<T : ForwardIndexType>(start: T, _ end: T) -> T.Distance {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message="call the 'advancedBy(n)' method on the index")
public func advance<T : ForwardIndexType>(start: T, _ n: T.Distance) -> T {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message="call the 'advancedBy(n, limit:)' method on the index")
public func advance<T : ForwardIndexType>(start: T, _ n: T.Distance, _ end: T) -> T {
fatalError("unavailable function can't be called")
}
//===----------------------------------------------------------------------===//
//===--- ForwardIndexType -------------------------------------------------===//
/// This protocol is an implementation detail of `ForwardIndexType`; do
/// not use it directly.
///
/// Its requirements are inherited by `ForwardIndexType` and thus must
/// be satisfied by types conforming to that protocol.
public protocol _Incrementable : Equatable {
/// Return the next consecutive value in a discrete sequence of
/// `Self` values.
///
/// - Requires: `self` has a well-defined successor.
@warn_unused_result
func successor() -> Self
mutating func _successorInPlace()
}
extension _Incrementable {
@inline(__always)
public mutating func _successorInPlace() { self = self.successor() }
}
//===----------------------------------------------------------------------===//
// A dummy type that we can use when we /don't/ want to create an
// ambiguity indexing Range<T> outside a generic context. See the
// implementation of Range for details.
public struct _DisabledRangeIndex_ {
init() {
_sanityCheckFailure("Nobody should ever create one.")
}
}
//===----------------------------------------------------------------------===//
/// Replace `i` with its `successor()` and return the updated value of
/// `i`.
@_transparent
public prefix func ++ <T : _Incrementable> (inout i: T) -> T {
i._successorInPlace()
return i
}
/// Replace `i` with its `successor()` and return the original
/// value of `i`.
@_transparent
public postfix func ++ <T : _Incrementable> (inout i: T) -> T {
let ret = i
i._successorInPlace()
return ret
}
/// Represents a discrete value in a series, where a value's
/// successor, if any, is reachable by applying the value's
/// `successor()` method.
public protocol ForwardIndexType : _Incrementable {
/// A type that can represent the number of steps between pairs of
/// `Self` values where one value is reachable from the other.
///
/// Reachability is defined by the ability to produce one value from
/// the other via zero or more applications of `successor`.
typealias Distance : _SignedIntegerType = Int
// See the implementation of Range for an explanation of this
// associated type
typealias _DisabledRangeIndex = _DisabledRangeIndex_
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(bounds.contains(index))
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
static func _failEarlyRangeCheck(index: Self, bounds: Range<Self>)
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(
/// bounds.contains(range.startIndex) ||
/// range.startIndex == bounds.endIndex)
/// precondition(
/// bounds.contains(range.endIndex) ||
/// range.endIndex == bounds.endIndex)
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
static func _failEarlyRangeCheck2(
rangeStart: Self, rangeEnd: Self, boundsStart: Self, boundsEnd: Self)
// FIXME: the suffix `2` in the name, and passing `startIndex` and `endIndex`
// separately (rather than as a range) are workarounds for a compiler defect.
// <rdar://problem/21855350> Rejects-valid: rejects code that has two Self
// types in non-direct-argument-type position
/// Return the result of advancing `self` by `n` positions.
///
/// - Returns:
/// - If `n > 0`, the result of applying `successor` to `self` `n` times.
/// - If `n < 0`, the result of applying `predecessor` to `self` `-n` times.
/// - Otherwise, `self`.
///
/// - Requires: `n >= 0` if only conforming to `ForwardIndexType`
/// - Complexity:
/// - O(1) if conforming to `RandomAccessIndexType`
/// - O(`abs(n)`) otherwise
@warn_unused_result
func advancedBy(n: Distance) -> Self
/// Return the result of advancing `self` by `n` positions, or until it
/// equals `limit`.
///
/// - Returns:
/// - If `n > 0`, the result of applying `successor` to `self` `n` times
/// but not past `limit`.
/// - If `n < 0`, the result of applying `predecessor` to `self` `-n` times
/// but not past `limit`.
/// - Otherwise, `self`.
///
/// - Requires: `n >= 0` if only conforming to `ForwardIndexType`.
///
/// - Complexity:
/// - O(1) if conforming to `RandomAccessIndexType`
/// - O(`abs(n)`) otherwise
@warn_unused_result
func advancedBy(n: Distance, limit: Self) -> Self
/// Measure the distance between `self` and `end`.
///
/// - Requires:
/// - `start` and `end` are part of the same sequence when conforming to
/// `RandomAccessSequenceType`.
/// - `end` is reachable from `self` by incrementation otherwise.
///
/// - Complexity:
/// - O(1) if conforming to `RandomAccessIndexType`
/// - O(`n`) otherwise, where `n` is the function's result.
@warn_unused_result
func distanceTo(end: Self) -> Distance
}
// advance and distance implementations
extension ForwardIndexType {
public static func _failEarlyRangeCheck(index: Self, bounds: Range<Self>) {
// Can't perform range checks in O(1) on forward indices.
}
public static func _failEarlyRangeCheck2(
rangeStart: Self, rangeEnd: Self, boundsStart: Self, boundsEnd: Self
) {
// Can't perform range checks in O(1) on forward indices.
}
/// Do not use this method directly; call advancedBy(n) instead.
@_transparent
@warn_unused_result
internal func _advanceForward(n: Distance) -> Self {
_precondition(n >= 0,
"Only BidirectionalIndexType can be advanced by a negative amount")
var p = self
var i : Distance = 0
while i != n {
p._successorInPlace()
i = i + 1
}
return p
}
/// Do not use this method directly; call advancedBy(n, limit) instead.
@_transparent
@warn_unused_result
internal func _advanceForward(n: Distance, _ limit: Self) -> Self {
_precondition(n >= 0,
"Only BidirectionalIndexType can be advanced by a negative amount")
var p = self
var i : Distance = 0
while i != n {
if p == limit { break }
p._successorInPlace()
i = i + 1
}
return p
}
@warn_unused_result
public func advancedBy(n: Distance) -> Self {
return self._advanceForward(n)
}
@warn_unused_result
public func advancedBy(n: Distance, limit: Self) -> Self {
return self._advanceForward(n, limit)
}
@warn_unused_result
public func distanceTo(end: Self) -> Distance {
var p = self
var count: Distance = 0
while p != end {
count += 1
p._successorInPlace()
}
return count
}
}
//===----------------------------------------------------------------------===//
//===--- BidirectionalIndexType -------------------------------------------===//
/// An *index* that can step backwards via application of its
/// `predecessor()` method.
public protocol BidirectionalIndexType : ForwardIndexType {
/// Return the previous consecutive value in a discrete sequence.
///
/// If `self` has a well-defined successor,
/// `self.successor().predecessor() == self`. If `self` has a
/// well-defined predecessor, `self.predecessor().successor() ==
/// self`.
///
/// - Requires: `self` has a well-defined predecessor.
@warn_unused_result
func predecessor() -> Self
mutating func _predecessorInPlace()
}
extension BidirectionalIndexType {
@inline(__always)
public mutating func _predecessorInPlace() {
self = self.predecessor()
}
@warn_unused_result
public func advancedBy(n: Distance) -> Self {
if n >= 0 {
return _advanceForward(n)
}
var p = self
var i: Distance = n
while i != 0 {
p._predecessorInPlace()
i._successorInPlace()
}
return p
}
@warn_unused_result
public func advancedBy(n: Distance, limit: Self) -> Self {
if n >= 0 {
return _advanceForward(n, limit)
}
var p = self
var i: Distance = n
while i != 0 && p != limit {
p._predecessorInPlace()
i._successorInPlace()
}
return p
}
}
/// Replace `i` with its `predecessor()` and return the updated value
/// of `i`.
@_transparent
public prefix func -- <T : BidirectionalIndexType> (inout i: T) -> T {
i._predecessorInPlace()
return i
}
/// Replace `i` with its `predecessor()` and return the original
/// value of `i`.
@_transparent
public postfix func -- <T : BidirectionalIndexType> (inout i: T) -> T {
let ret = i
i._predecessorInPlace()
return ret
}
//===----------------------------------------------------------------------===//
//===--- RandomAccessIndexType --------------------------------------------===//
/// Used to force conformers of RandomAccessIndexType to implement
/// `advancedBy` methods and `distanceTo`.
public protocol _RandomAccessAmbiguity {
typealias Distance : _SignedIntegerType = Int
}
extension _RandomAccessAmbiguity {
@warn_unused_result
public func advancedBy(n: Distance) -> Self {
fatalError("advancedBy(n) not implememented")
}
}
/// An *index* that can be offset by an arbitrary number of positions,
/// and can measure the distance to any reachable value, in O(1).
public protocol RandomAccessIndexType : BidirectionalIndexType, Strideable,
_RandomAccessAmbiguity {
@warn_unused_result
func distanceTo(other: Self) -> Distance
@warn_unused_result
func advancedBy(n: Distance) -> Self
@warn_unused_result
func advancedBy(n: Distance, limit: Self) -> Self
}
extension RandomAccessIndexType {
public static func _failEarlyRangeCheck(index: Self, bounds: Range<Self>) {
_precondition(
bounds.startIndex <= index,
"index is out of bounds: index designates a position before bounds.startIndex")
_precondition(
index < bounds.endIndex,
"index is out of bounds: index designates the bounds.endIndex position or a position after it")
}
public static func _failEarlyRangeCheck2(
rangeStart: Self, rangeEnd: Self, boundsStart: Self, boundsEnd: Self
) {
let range = rangeStart..<rangeEnd
let bounds = boundsStart..<boundsEnd
_precondition(
bounds.startIndex <= range.startIndex,
"range.startIndex is out of bounds: index designates a position before bounds.startIndex")
_precondition(
bounds.startIndex <= range.endIndex,
"range.endIndex is out of bounds: index designates a position before bounds.startIndex")
_precondition(
range.startIndex <= bounds.endIndex,
"range.startIndex is out of bounds: index designates a position after bounds.endIndex")
_precondition(
range.endIndex <= bounds.endIndex,
"range.startIndex is out of bounds: index designates a position after bounds.endIndex")
}
@_transparent
@warn_unused_result
public func advancedBy(n: Distance, limit: Self) -> Self {
let d = self.distanceTo(limit)
if d == 0 || (d > 0 ? d <= n : d >= n) {
return limit
}
return self.advancedBy(n)
}
}
| apache-2.0 | e4ffeb9b3a8234dc0f354c7e32c5f830 | 32.054054 | 101 | 0.624768 | 4.287126 | false | false | false | false |
iossocket/VIPER-Douban | VIPER-Douban/HorizontalSectionController.swift | 1 | 2672 | //
// HorizontalSectionController.swift
// VIPER-Douban
//
// Created by XueliangZhu on 3/2/17.
// Copyright © 2017 ThoughtWorks. All rights reserved.
//
import IGListKit
class HorizontalSectionController: IGListSectionController {
var data: Top250Movies?
override init() {
super.init()
inset = UIEdgeInsets(top: 0, left: 0, bottom: 15, right: 0)
supplementaryViewSource = self
}
lazy var adapter: IGListAdapter = {
let adapter = IGListAdapter(updater: IGListAdapterUpdater(),
viewController: self.viewController,
workingRangeSize: 0)
adapter.dataSource = self
return adapter
}()
}
extension HorizontalSectionController: IGListSectionType {
func numberOfItems() -> Int {
return 1
}
func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 180)
}
func cellForItem(at index: Int) -> UICollectionViewCell {
let cell = collectionContext!.dequeueReusableCell(of: EmbeddedCollectionViewCell.self, for: self, at: index) as! EmbeddedCollectionViewCell
adapter.collectionView = cell.collectionView
adapter.collectionView?.showsHorizontalScrollIndicator = false
return cell
}
func didUpdate(to object: Any) {
data = object as? Top250Movies
}
func didSelectItem(at index: Int) {}
}
extension HorizontalSectionController: IGListAdapterDataSource {
func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] {
guard let movies = data?.movies else { return [] }
return movies
}
func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController {
return EmbeddedSectionController()
}
func emptyView(for listAdapter: IGListAdapter) -> UIView? {
return nil
}
}
extension HorizontalSectionController: IGListSupplementaryViewSource {
func supportedElementKinds() -> [String] {
return [UICollectionElementKindSectionHeader]
}
func viewForSupplementaryElement(ofKind elementKind: String, at index: Int) -> UICollectionReusableView {
let view = collectionContext?.dequeueReusableSupplementaryView(ofKind: elementKind, for: self, nibName: "CommonHeaderView", bundle: nil, at: index) as! CommonHeaderView
return view
}
func sizeForSupplementaryView(ofKind elementKind: String, at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 40)
}
}
| mit | 566618662f02714a6365385e9a463b45 | 31.180723 | 176 | 0.672407 | 5.352705 | false | false | false | false |
andresilvagomez/Localize | Source/LocalizeUI.swift | 2 | 1682 | //
// LocalizeUI.swift
// Localize
//
// Copyright © 2019 @andresilvagomez.
//
import Foundation
class LocalizeUI: NSObject {
/// Localize UI component using key and value or result
/// It decide wich is the way to localize, user IB Properties
/// or values in the ui component.
///
/// - returns: localized string and also edit it inside.
@discardableResult
static func localize(
key: inout String?,
value: inout String?,
updateKey: Bool = true) -> String {
if let localized = key?.localize() {
value = localized
return localized
}
if let localized = value?.localize() {
if updateKey { key = value }
value = localized
return localized
}
return value ?? ""
}
/// Get key for segment controls based on string like to
/// navigation.segment: one, two or one, two
/// it returns the right access key to localize segment at index
///
/// - returns: key to localize
static func keyFor(index: Int, localizeKey: String?) -> String? {
var localizeKey = localizeKey?.replacingOccurrences(of: " ", with: "")
let root = localizeKey?.components(separatedBy: ":")
var rootKey: String?
if root?.count == 2 {
rootKey = root?.first
localizeKey = root?.last
}
let keys = localizeKey?.components(separatedBy: ",")
let key = keys?.count ?? 0 > index ? keys?[index] : nil
if key == nil || key?.isEmpty ?? true { return nil }
if rootKey == nil { return key }
return "\(rootKey ?? "").\(key ?? "")"
}
}
| mit | 7428e2b057f68728e43377be30c1b471 | 27.982759 | 78 | 0.568709 | 4.580381 | false | false | false | false |
darren90/Gankoo_Swift | Gankoo/Gankoo/Classes/Main/Base/BaseTableViewController.swift | 1 | 1552 | //
// BaseTableViewController.swift
// iTVshows
//
// Created by Fengtf on 2016/11/21.
// Copyright © 2016年 tengfei. All rights reserved.
//
import UIKit
class BaseTableViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {
public var tableView:UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addTableView()
// addLoadingView()
}
func addTableView() {
let rect = CGRect(x: 0, y: 64, width: self.view.bounds.width, height: self.view.bounds.height-64)
tableView = UITableView.init(frame: rect, style: .plain)
self.view .addSubview(tableView)
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .none
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView .dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell.init(style: .default, reuseIdentifier: "cell")
}
return cell!;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
/// 移除选中的状态
tableView.deselectRow(at: indexPath, animated: true)
}
}
| apache-2.0 | 47168fb92d5977f1926a860cf7329734 | 23.758065 | 105 | 0.652117 | 4.69419 | false | false | false | false |
zhaoguohui/AMTagListView | SwiftDemo/SwiftDemo/ViewController.swift | 1 | 1218 | //
// ViewController.swift
// SwiftDemo
//
// Created by Andrea Mazzini on 31/10/14.
// Copyright (c) 2014 Fancy Pixel. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var tagListView: AMTagListView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Demo"
textField.layer.borderColor = UIColor(red:0.12, green:0.55, blue:0.84, alpha:1).CGColor
textField.layer.borderWidth = 2.0
textField.delegate = self
AMTagView.appearance().tagLength = 10
AMTagView.appearance().textPadding = 14
AMTagView.appearance().textFont = UIFont(name: "Futura", size: 14)
AMTagView.appearance().tagColor = UIColor(red:0.12, green:0.55, blue:0.84, alpha:1)
tagListView.addTag("my tag")
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
tagListView.addTag(textField.text)
textField.text = ""
return false;
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
textField.resignFirstResponder()
}
}
| mit | 31ef6a8571e5c4ff1ecf73ef1773a7cc | 27.325581 | 95 | 0.651067 | 4.171233 | false | false | false | false |
TIEmerald/UNDanielBasicTool_Swift | UNDanielBasicTool_Swift/Classes/Base UI Elements/UNDBaseTableViewCell.swift | 1 | 1579 | //
// TableViewCellExtension.swift
// Pods
//
// Created by 尓健 倪 on 15/6/17.
//
//
import UIKit
public class UNDBaseTableViewCell : UITableViewCell {
/// Mark - Constant
public static let UITableViewCell_BaseModle_Key = "UITableViewCellBaseModleKey"
/// Mark: - Override Methods
/// Override this method with table view cell's nib name
open class var nibName : String {
return ""
}
open class var cellIdentifierName : String {
return ""
}
open class var cellHeight : CGFloat{
return 44.0
}
// Set Up Related
open func setupCell(basedOnModelDictionary modelDictionary : Dictionary<String, Any>){
}
open func updateCellUI(){
}
/// Mark: - General Methods
//// Call this method to register the cell into target table view
public static func registerSelf(intoTableView tableview: UITableView?) -> Void{
tableview?.register(UINib.init(nibName: self.nibName, bundle: nil),
forCellReuseIdentifier: self.cellIdentifierName)
}
/// Border Related
public func setupBorder(withWidth width: CGFloat, andColor borderColor: UIColor, isOutSide: Bool){
if isOutSide {
self.frame = self.frame.insetBy(dx: -width, dy: -width)
}
self.contentView.layer.borderWidth = width
self.contentView.layer.borderColor = borderColor.cgColor
}
public func removeBorder(){
self.contentView.layer.borderWidth = 0
}
}
| mit | b430f022e8515ff80b8c558217c33d2b | 24.786885 | 102 | 0.622378 | 4.781155 | false | false | false | false |
Hydropal/Hydropal-iOS | HydroPal/HydroPal/SexTableViewController.swift | 1 | 3009 | //
// SexTableViewController.swift
// HydroPal
//
// Created by Shao Qian MAH on 17/11/2016.
// Copyright © 2016 Hydropal. All rights reserved.
//
import UIKit
class SexTableViewController: UITableViewController {
var sexes:[String] = [
"Male",
"Female"
]
var selectedSex:String? {
didSet {
if let sex = selectedSex {
selectedSexIndex = sexes.index(of: sex)!
}
}
}
var selectedSexIndex:Int?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sexes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "sexSelectCell", for: indexPath)
cell.textLabel?.text = sexes[(indexPath as NSIndexPath).row]
if (indexPath as NSIndexPath).row == selectedSexIndex {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
//Other row is selected - need to deselect it
if let index = selectedSexIndex {
let cell = tableView.cellForRow(at: IndexPath(row: index, section: 0))
cell?.accessoryType = .none
}
selectedSex = sexes[(indexPath as NSIndexPath).row]
//update the checkmark for the current row
let cell = tableView.cellForRow(at: indexPath)
cell?.accessoryType = .checkmark
//FIXME: Sex tick
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SaveSelectedSex" {
if let cell = sender as? UITableViewCell {
let indexPath = tableView.indexPath(for: cell)
if let index = (indexPath as NSIndexPath?)?.row {
selectedSex = sexes[index]
}
}
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
| mit | ff9cc7e77dda061916c7f755396003e3 | 30.333333 | 113 | 0.60871 | 5.204152 | false | false | false | false |
groovelab/SwiftBBS | SwiftBBS/SwiftBBS Server/ImageRepository.swift | 1 | 3432 | //
// ImageRepository.swift
// SwiftBBS
//
// Created by Takeo Namba on 2016/01/21.
// Copyright GrooveLab
//
import PerfectLib
// MARK: entity
struct ImageEntity {
enum Parent {
case Bbs
case BbsComment
case User
func toString() -> String {
switch self {
case .Bbs:
return "bbs"
case .BbsComment:
return "bbs_comment"
case .User:
return "user"
}
}
init(value: String) {
switch value {
case "bbs":
self = .Bbs
case "bbs_comment":
self = .BbsComment
case "user":
self = .User
default:
self = .User
}
}
}
var id: UInt?
var parent: Parent
var parentId: UInt
var path: String
var ext: String
var originalName: String
var width: UInt
var height: UInt
var userId: UInt
var createdAt: String?
var updatedAt: String?
func toDictionary() -> [String: Any] {
return [
"id": id,
"parent": parent.toString(),
"parentId": parentId,
"path": path,
"ext": ext,
"originalName": originalName,
"width": userId,
"height": userId,
"userId": userId,
"createdAt": createdAt,
"updatedAt": updatedAt,
]
}
}
// MARK: - repository
class ImageRepository : Repository {
func insert(entity: ImageEntity) throws -> UInt {
let sql = "INSERT INTO image (parent, parent_id, path, ext, original_name, width, height, user_id, created_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, \(nowSql), \(nowSql))"
let params: Params = [
entity.parent.toString(),
entity.parentId,
entity.path,
entity.ext,
entity.originalName,
entity.width,
entity.height,
entity.userId
]
return try executeInsertSql(sql, params: params)
}
func selectBelongTo(parent parent: ImageEntity.Parent, parentId: UInt) throws -> [ImageEntity] {
let sql = "SELECT id, parent, parent_id, path, ext, original_name, width, height, user_id, created_at, updated_at FROM image "
+ "WHERE parent = ? AND parent_id = ? ORDER BY id";
let rows = try executeSelectSql(sql, params: [ parent.toString(), parentId ])
return rows.map { row in
return createEntityFromRow(row)
}
}
// row contains id, parent, parent_id, path, ext, original_name, width, height, user_id, created_at, updated_at
private func createEntityFromRow(row: Row) -> ImageEntity {
return ImageEntity(
id: UInt(row[0] as! UInt32),
parent: ImageEntity.Parent(value: row[1] as! String),
parentId: UInt(row[2] as! UInt32),
path: stringFromMySQLText(row[3] as? [UInt8]) ?? "",
ext: row[4] as! String,
originalName: stringFromMySQLText(row[5] as? [UInt8]) ?? "",
width: UInt(row[6] as! UInt32),
height: UInt(row[7] as! UInt32),
userId: UInt(row[8] as! UInt32),
createdAt: row[9] as? String,
updatedAt: row[10] as? String
)
}
}
| mit | 7dc6cae4e9b0798aad0edeee520cb672 | 28.843478 | 134 | 0.513695 | 4.125 | false | false | false | false |
toggl/superday | teferi/TimelineGenerator/Helpers/Persister.swift | 1 | 3163 | import Foundation
class Persister
{
private let timeSlotService : TimeSlotService
private let timeService : TimeService
private let metricsService: MetricsService
init(timeSlotService: TimeSlotService,
timeService: TimeService,
metricsService: MetricsService)
{
self.timeSlotService = timeSlotService
self.timeService = timeService
self.metricsService = metricsService
}
func persist(slots: [TemporaryTimeSlot])
{
guard let firstSlot = slots.first else { return }
var lastLocation : Location? = nil
var firstSlotCreated : TimeSlot? = nil
var auxSlots = slots
if let lastSlot = timeSlotService.getLast(), shouldContinue(lastSlot: lastSlot, withSlot: firstSlot) {
auxSlots = Array(auxSlots.dropFirst())
}
for temporaryTimeSlot in auxSlots
{
let addedTimeSlot = timeSlotService.addTimeSlot(fromTemporaryTimeslot: temporaryTimeSlot)
if firstSlotCreated == nil { firstSlotCreated = addedTimeSlot }
lastLocation = addedTimeSlot?.location ?? lastLocation
}
logTimeSlotsSince(date: firstSlotCreated?.startTime)
}
private func shouldContinue(lastSlot: TimeSlot, withSlot nextSlot: TemporaryTimeSlot) -> Bool
{
guard lastSlot.startTime.ignoreTimeComponents() == nextSlot.start.ignoreTimeComponents() else { return false }
let activityMatches = activitiesMatch(slot: lastSlot, temporaryTimeSlot: nextSlot)
if lastSlot.categoryWasSetByUser {
// If the last stored slot category was set by user and the activity matches the first TTS, we just continue the last stored one
return activityMatches
}
// If the last stored slot category was NOT set by user we also check the category matches with the smartguessed one
return activityMatches && (lastSlot.category == nextSlot.category || nextSlot.category == .unknown)
}
private func activitiesMatch(slot: TimeSlot, temporaryTimeSlot: TemporaryTimeSlot) -> Bool
{
switch (slot.activity, temporaryTimeSlot.activity) {
case (nil, .still):
return true
case (nil, _):
return false
case (let a, let b):
return a == b
}
}
private func logTimeSlotsSince(date: Date?)
{
guard let startDate = date else { return }
timeSlotService.getTimeSlots(betweenDate: startDate, andDate: timeService.now).forEach({ slot in
metricsService.log(event: .timeSlotCreated(date: timeService.now, category: slot.category, duration: slot.duration))
if slot.categoryWasSmartGuessed
{
metricsService.log(event: .timeSlotSmartGuessed(date: timeService.now, category: slot.category, duration: slot.duration))
}
else
{
metricsService.log(event: .timeSlotNotSmartGuessed(date: timeService.now, category: slot.category, duration: slot.duration))
}
})
}
}
| bsd-3-clause | 8afebdd7783486bb57909d67490b024c | 37.108434 | 140 | 0.644325 | 4.95768 | false | false | false | false |
lappp9/AsyncDisplayKit | examples_extra/Shop/Shop/Scenes/Products/ProductTableNode.swift | 11 | 4399 | //
// ProductTableNode.swift
// Shop
//
// Created by Dimitri on 15/11/2016.
// Copyright © 2016 Dimitri. All rights reserved.
//
import UIKit
class ProductTableNode: ASCellNode {
// MARK: - Variables
private lazy var imageSize: CGSize = {
return CGSize(width: 80, height: 80)
}()
private let product: Product
private let imageNode: ASNetworkImageNode
private let titleNode: ASTextNode
private let subtitleNode: ASTextNode
private let starRatingNode: StarRatingNode
private let priceNode: ASTextNode
private let separatorNode: ASDisplayNode
// MARK: - Object life cycle
init(product: Product) {
self.product = product
imageNode = ASNetworkImageNode()
titleNode = ASTextNode()
subtitleNode = ASTextNode()
starRatingNode = StarRatingNode(rating: product.starRating)
priceNode = ASTextNode()
separatorNode = ASDisplayNode()
super.init()
self.setupNodes()
self.buildNodeHierarchy()
}
// MARK: - Setup nodes
private func setupNodes() {
self.setupImageNode()
self.setupTitleNode()
self.setupSubtitleNode()
self.setupPriceNode()
self.setupSeparatorNode()
}
private func setupImageNode() {
self.imageNode.url = URL(string: self.product.imageURL)
self.imageNode.preferredFrameSize = self.imageSize
}
private func setupTitleNode() {
self.titleNode.attributedText = NSAttributedString(string: self.product.title, attributes: self.titleTextAttributes())
self.titleNode.maximumNumberOfLines = 1
self.titleNode.truncationMode = .byTruncatingTail
}
private var titleTextAttributes = {
return [NSForegroundColorAttributeName: UIColor.black, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 16)]
}
private func setupSubtitleNode() {
self.subtitleNode.attributedText = NSAttributedString(string: self.product.descriptionText, attributes: self.subtitleTextAttributes())
self.subtitleNode.maximumNumberOfLines = 2
self.subtitleNode.truncationMode = .byTruncatingTail
}
private var subtitleTextAttributes = {
return [NSForegroundColorAttributeName: UIColor.darkGray, NSFontAttributeName: UIFont.systemFont(ofSize: 14)]
}
private func setupPriceNode() {
self.priceNode.attributedText = NSAttributedString(string: self.product.currency + " \(self.product.price)", attributes: self.priceTextAttributes())
}
private var priceTextAttributes = {
return [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 15)]
}
private func setupSeparatorNode() {
self.separatorNode.backgroundColor = UIColor.lightGray
}
// MARK: - Build node hierarchy
private func buildNodeHierarchy() {
self.addSubnode(imageNode)
self.addSubnode(titleNode)
self.addSubnode(subtitleNode)
self.addSubnode(starRatingNode)
self.addSubnode(priceNode)
self.addSubnode(separatorNode)
}
// MARK: - Layout
override func layout() {
super.layout()
let separatorHeight = 1 / UIScreen.main.scale
self.separatorNode.frame = CGRect(x: 0.0, y: 0.0, width: self.calculatedSize.width, height: separatorHeight)
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
let spacer = ASLayoutSpec()
spacer.flexGrow = true
self.titleNode.flexShrink = true
let titlePriceSpec = ASStackLayoutSpec(direction: .horizontal, spacing: 2.0, justifyContent: .start, alignItems: .center, children: [self.titleNode, spacer, self.priceNode])
titlePriceSpec.alignSelf = .stretch
let contentSpec = ASStackLayoutSpec(direction: .vertical, spacing: 4.0, justifyContent: .start, alignItems: .stretch, children: [titlePriceSpec, self.subtitleNode, self.starRatingNode])
contentSpec.flexShrink = true
let finalSpec = ASStackLayoutSpec(direction: .horizontal, spacing: 10.0, justifyContent: .start, alignItems: .start, children: [self.imageNode, contentSpec])
return ASInsetLayoutSpec(insets: UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0), child: finalSpec)
}
}
| bsd-3-clause | 7ad78bf143866e5d3a39bef639c69bba | 34.756098 | 193 | 0.67849 | 4.859669 | false | false | false | false |
marketplacer/Dodo | Dodo/DodoToolbar.swift | 2 | 5887 | import UIKit
class DodoToolbar: UIView {
var anchor: NSLayoutYAxisAnchor?
var style: DodoStyle
weak var buttonViewDelegate: DodoButtonViewDelegate?
private var didCallHide = false
convenience init(witStyle style: DodoStyle) {
self.init(frame: CGRect())
self.style = style
}
override init(frame: CGRect) {
style = DodoStyle()
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func show(inSuperview parentView: UIView, withMessage message: String) {
if superview != nil { return } // already being shown
parentView.addSubview(self)
applyStyle()
layoutBarInSuperview()
let buttons = createButtons()
createLabel(message, withButtons: buttons)
style.bar.animationShow(self, style.bar.animationShowDuration, style.bar.locationTop, {})
}
func hide(_ onAnimationCompleted: @escaping ()->()) {
// Respond only to the first hide() call
if didCallHide { return }
didCallHide = true
style.bar.animationHide(self, style.bar.animationHideDuration,
style.bar.locationTop, { [weak self] in
self?.removeFromSuperview()
onAnimationCompleted()
})
}
// MARK: - Label
private func createLabel(_ message: String, withButtons buttons: [UIView]) {
let label = UILabel()
label.font = style.label.font
label.text = message
label.textColor = style.label.color
label.textAlignment = NSTextAlignment.center
label.numberOfLines = style.label.numberOfLines
if style.bar.debugMode {
label.backgroundColor = UIColor.red
}
if let shadowColor = style.label.shadowColor {
label.shadowColor = shadowColor
label.shadowOffset = style.label.shadowOffset
}
addSubview(label)
layoutLabel(label, withButtons: buttons)
}
private func layoutLabel(_ label: UILabel, withButtons buttons: [UIView]) {
label.translatesAutoresizingMaskIntoConstraints = false
// Stretch the label vertically
TegAutolayoutConstraints.fillParent(label, parentView: self,
margin: style.label.horizontalMargin, vertically: true)
if buttons.count == 0 {
if let superview = superview {
// If there are no buttons - stretch the label to the entire width of the view
TegAutolayoutConstraints.fillParent(label, parentView: superview,
margin: style.label.horizontalMargin, vertically: false)
}
} else {
layoutLabelWithButtons(label, withButtons: buttons)
}
}
private func layoutLabelWithButtons(_ label: UILabel, withButtons buttons: [UIView]) {
if buttons.count != 2 { return }
let views = [buttons[0], label, buttons[1]]
if let superview = superview {
TegAutolayoutConstraints.viewsNextToEachOther(views,
constraintContainer: superview, margin: style.label.horizontalMargin, vertically: false)
}
}
// MARK: - Buttons
private func createButtons() -> [DodoButtonView] {
precondition(buttonViewDelegate != nil, "Button view delegate can not be nil")
let buttonStyles = [style.leftButton, style.rightButton]
let buttonViews = DodoButtonView.createMany(buttonStyles)
for (index, button) in buttonViews.enumerated() {
addSubview(button)
button.delegate = buttonViewDelegate
button.doLayout(onLeftSide: index == 0)
if style.bar.debugMode {
button.backgroundColor = UIColor.yellow
}
}
return buttonViews
}
// MARK: - Style the bar
private func applyStyle() {
backgroundColor = style.bar.backgroundColor
layer.cornerRadius = style.bar.cornerRadius
layer.masksToBounds = true
if let borderColor = style.bar.borderColor , style.bar.borderWidth > 0 {
layer.borderColor = borderColor.cgColor
layer.borderWidth = style.bar.borderWidth
}
}
private func layoutBarInSuperview() {
translatesAutoresizingMaskIntoConstraints = false
if let superview = superview {
// Stretch the toobar horizontally to the width if its superview
TegAutolayoutConstraints.fillParent(self, parentView: superview,
margin: style.bar.marginToSuperview.width, vertically: false)
var verticalMargin = style.bar.marginToSuperview.height
verticalMargin = style.bar.locationTop ? -verticalMargin : verticalMargin
var verticalConstraints = [NSLayoutConstraint]()
if let anchor = anchor {
// Align the top/bottom edge of the toolbar with the top/bottom anchor
// (a tab bar, for example)
verticalConstraints = TegAutolayoutConstraints.alignVerticallyToAnchor(self,
onTop: style.bar.locationTop,
anchor: anchor,
margin: verticalMargin)
} else {
// Align the top/bottom of the toolbar with the top/bottom of its superview
verticalConstraints = TegAutolayoutConstraints.alignSameAttributes(superview, toItem: self,
constraintContainer: superview,
attribute: style.bar.locationTop ? NSLayoutConstraint.Attribute.top : NSLayoutConstraint.Attribute.bottom,
margin: verticalMargin)
}
setupKeyboardEvader(verticalConstraints)
}
}
// Moves the message bar from under the keyboard
private func setupKeyboardEvader(_ verticalConstraints: [NSLayoutConstraint]) {
if let bottomConstraint = verticalConstraints.first,
let superview = superview
, !style.bar.locationTop {
DodoKeyboardListener.underKeyboardLayoutConstraint.setup(bottomConstraint, view: superview)
}
}
}
| mit | a0c1551a5d08b5dc8d63a2164429915b | 31.346154 | 116 | 0.663326 | 5.308386 | false | false | false | false |
codeflows/SceneLauncher | src/SceneViewController.swift | 1 | 5599 | import UIKit
import ReactiveCocoa
let CellId = "SceneCell"
class SceneViewController: UICollectionViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
let osc: OSCService
let dataSource: SceneDataSource
let refreshControl: UIRefreshControl
let helpMessageView: UITextView
override func viewDidLoad() {
super.viewDidLoad()
collectionView!.backgroundColor = UIColor.whiteColor()
// TODO autolayout
helpMessageView.frame = CGRect(x: UIConstants.margin, y: UIConstants.margin, width: collectionView!.bounds.width - 2 * UIConstants.margin, height: collectionView!.bounds.height)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// TODO if server address changes (note: ACTUALLY changes from previous) -> should discard any ongoing refresh
if(!refreshControl.refreshing) {
refreshScenesAutomatically()
}
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let scene = dataSource.scenes[indexPath.indexAtPosition(1)]
osc.sendMessage(OSCMessage(address: "/live/play/scene", arguments: [scene.order]))
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: 58)
}
private let sectionInsets = UIEdgeInsets(top: 0, left: 0, bottom: UIConstants.controlsHeight, right: 0)
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return sectionInsets
}
init(applicationContext: ApplicationContext) {
self.osc = applicationContext.oscService
dataSource = SceneDataSource(osc: osc)
refreshControl = UIRefreshControl()
helpMessageView = UITextView()
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
super.init(collectionViewLayout: layout)
collectionView!.registerClass(SceneCell.self, forCellWithReuseIdentifier: CellId)
collectionView!.dataSource = dataSource
refreshControl.addTarget(self, action: "refreshScenesManually", forControlEvents: .ValueChanged)
collectionView!.addSubview(refreshControl)
collectionView!.alwaysBounceVertical = true
collectionView!.addSubview(helpMessageView)
helpMessageView.font = UIFont(name: UIConstants.fontName, size: 20)
helpMessageView.scrollEnabled = false
helpMessageView.editable = false
// TODO jari: move somewhere else
let sceneNumberChanges: Signal<Int, NoError> =
osc.incomingMessagesSignal
|> filter { $0.address == "/live/scene" }
// This seems to be off-by-one??!
|> map { ($0.arguments[0] as! Int) - 1 }
|> observeOn(UIScheduler())
sceneNumberChanges.observe(next: { sceneNumber in
for (index, scene) in enumerate(self.dataSource.scenes) {
if(scene.order == sceneNumber) {
let p = NSIndexPath(forRow: index, inSection: 0)
self.collectionView?.selectItemAtIndexPath(p, animated: true, scrollPosition: UICollectionViewScrollPosition.CenteredVertically)
}
}
})
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func refreshScenesManually() {
osc.ensureConnected()
refreshScenes()
}
private func refreshScenesAutomatically() {
refreshControl.beginRefreshing()
// Hack to make indicator visible: http://stackoverflow.com/questions/17930730/uirefreshcontrol-on-viewdidload
collectionView?.contentOffset = CGPointMake(0, -refreshControl.frame.size.height)
refreshScenes()
}
private func refreshScenes() {
dataSource.reloadData() { maybeError in
if let error = maybeError {
self.handleError(error)
} else {
self.helpMessageView.hidden = true
}
self.collectionView!.reloadData()
self.refreshControl.endRefreshing()
}
}
private func handleError(error: SceneLoadingError) {
let scenesHaveBeenPreviouslyLoaded = dataSource.scenes.count > 0
switch error {
case let .NoAddressConfigured:
if scenesHaveBeenPreviouslyLoaded {
showAlert("No address configured", message: "Please go to settings and configure your Ableton Live server address")
}
case let .Unknown: showAlert("Unknown error", message: "Could not load scenes")
case let .LiveOsc(message): showAlert("LiveOSC error", message: message)
case let .Timeout: showAlert("Could not load scenes", message: "Please make sure Ableton Live is running and the server address is correct in settings")
}
if !scenesHaveBeenPreviouslyLoaded {
helpMessageView.hidden = false
switch error {
case let .NoAddressConfigured:
helpMessageView.text = "Welcome to SceneLauncher!\n\nTo start, please click the settings icon below and configure your Ableton Live server address."
default:
helpMessageView.text = "Scenes could not be loaded. Please make sure Ableton Live is running and the server address is correct in settings.\n\nTo try loading the scenes again, simply pull down to refresh."
}
}
}
private func showAlert(title: String, message: String) {
let alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
| mit | 8b4631f571ee2bc9f40bdb230605ba97 | 38.70922 | 215 | 0.72638 | 4.985752 | false | false | false | false |
TurfDb/Turf | Turf/Extensions/SecondaryIndex/Internals/WhereClauses.swift | 1 | 3881 | internal struct WhereClauses {
static func equals<Value: SQLiteType>(name: String, value: Value) -> WhereClause {
return WhereClause(sql: "\(name)=?",
bindStatements: { (stmt, firstColumnIndex) -> Int32 in
value.sqliteBind(stmt, index: firstColumnIndex)
return 1
})
}
static func notEquals<Value: SQLiteType>(name: String, value: Value) -> WhereClause {
return WhereClause(sql: "\(name)!=?",
bindStatements: { (stmt, firstColumnIndex) -> Int32 in
value.sqliteBind(stmt, index: firstColumnIndex)
return 1
})
}
static func like(name: String, value: String, negate: Bool = false) -> WhereClause {
return WhereClause(sql: "\(name) \(negate ? "NOT" : "") LIKE ?",
bindStatements: { (stmt, firstColumnIndex) -> Int32 in
value.sqliteBind(stmt, index: firstColumnIndex)
return 1
})
}
static func regexp(name: String, regex: String, negate: Bool = false) -> WhereClause {
return WhereClause(sql: "\(name) \(negate ? "NOT" : "") REGEXP ?",
bindStatements: { (stmt, firstColumnIndex) -> Int32 in
regex.sqliteBind(stmt, index: firstColumnIndex)
return 1
})
}
static func IN<Value: SQLiteType>(name: String, values: [Value], negate: Bool = false) -> WhereClause {
precondition(values.count < Int(Int32.max))
let placeholders = [String](repeating: "?", count: values.count).joined(separator: ",")
return WhereClause(sql: "\(name) \(negate ? "NOT" : "") IN [\(placeholders)]",
bindStatements: { (stmt, firstColumnIndex) -> Int32 in
for (index, value) in values.enumerated() {
value.sqliteBind(stmt, index: firstColumnIndex + Int32(index))
}
return Int32(values.count)
})
}
static func between<Value: SQLiteType>(name: String, left: Value, right: Value) -> WhereClause {
return WhereClause(sql: "\(name) BETWEEN ? AND ?",
bindStatements: { (stmt, firstColumnIndex) -> Int32 in
left.sqliteBind(stmt, index: firstColumnIndex)
right.sqliteBind(stmt, index: firstColumnIndex + 1)
return 2
})
}
static func lessThan<Value: SQLiteType>(name: String, value: Value) -> WhereClause {
return WhereClause(sql: "\(name) < ?",
bindStatements: { (stmt, firstColumnIndex) -> Int32 in
value.sqliteBind(stmt, index: firstColumnIndex)
return 1
})
}
static func lessThanOrEqual<Value: SQLiteType>(name: String, value: Value) -> WhereClause {
return WhereClause(sql: "\(name) <= ?",
bindStatements: { (stmt, firstColumnIndex) -> Int32 in
value.sqliteBind(stmt, index: firstColumnIndex)
return 1
})
}
static func greaterThan<Value: SQLiteType>(name: String, value: Value) -> WhereClause {
return WhereClause(sql: "\(name) > ?",
bindStatements: { (stmt, firstColumnIndex) -> Int32 in
value.sqliteBind(stmt, index: firstColumnIndex)
return 1
})
}
static func greaterThanOrEqual<Value: SQLiteType>(name: String, value: Value) -> WhereClause {
return WhereClause(sql: "\(name) >= ?",
bindStatements: { (stmt, firstColumnIndex) -> Int32 in
value.sqliteBind(stmt, index: firstColumnIndex)
return 1
})
}
static func isNull(name: String, negate: Bool = false) -> WhereClause {
return WhereClause(sql: "\(name) \(negate ? "NOT" : "") IS NULL",
bindStatements: { (stmt, firstColumnIndex) -> Int32 in
return 0
})
}
}
| mit | 223caa5bddac300cc3708437ccdc9d51 | 39.852632 | 107 | 0.569441 | 4.307436 | false | false | false | false |
ntwf/TheTaleClient | TheTale/Stores/PlayerInformation/AccountInformation/Hero/Companion/Companion.swift | 1 | 1909 | //
// Companion.swift
// the-tale
//
// Created by Mikhail Vospennikov on 25/06/2017.
// Copyright © 2017 Mikhail Vospennikov. All rights reserved.
//
import Foundation
class Companion: NSObject {
var coherence: Int
var experience: Double
var experienceToLevel: Double
var health: Double
var maxHealth: Double
var name: String
var realCoherence: Int
var type: Int
required init?(jsonObject: JSON) {
guard let coherence = jsonObject["coherence"] as? Int,
let experience = jsonObject["experience"] as? Double,
let experienceToLevel = jsonObject["experience_to_level"] as? Double,
let health = jsonObject["health"] as? Double,
let maxHealth = jsonObject["max_health"] as? Double,
let name = jsonObject["name"] as? String,
let realCoherence = jsonObject["real_coherence"] as? Int,
let type = jsonObject["type"] as? Int else {
return nil
}
self.coherence = coherence
self.experience = experience
self.experienceToLevel = experienceToLevel
self.health = health
self.maxHealth = maxHealth
self.name = name
self.realCoherence = realCoherence
self.type = type
}
}
extension Companion {
var levelRepresentation: String {
return "\(coherence)"
}
var nameRepresentation: String {
return "\(coherence) \(name)"
}
var healthRepresentation: String {
return "\(Int(health))/\(Int(maxHealth))"
}
var experienceRepresentation: String {
return "\(Int(experience))/\(Int(experienceToLevel))"
}
var healthProgressRepresentation: Float {
return (Float(health) / Float(maxHealth))
}
var experienceProgressRepresentation: Float {
return (Float(experience) / Float(experienceToLevel))
}
}
| mit | ff6e3cea89256b3b18f954ef77db3c41 | 26.257143 | 79 | 0.622117 | 4.326531 | false | false | false | false |
ackratos/firefox-ios | Client/Frontend/Browser/TabManager.swift | 2 | 17208 | /* 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 TabManagerDelegate: class {
func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?)
func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool)
func tabManager(tabManager: TabManager, didAddTab tab: Browser, atIndex: Int, restoring: Bool)
func tabManager(tabManager: TabManager, didRemoveTab tab: Browser, atIndex index: Int)
func tabManagerDidRestoreTabs(tabManager: TabManager)
func tabManagerDidAddTabs(tabManager: TabManager)
}
// We can't use a WeakList here because this is a protocol.
class WeakTabManagerDelegate {
weak var value : TabManagerDelegate?
init (value: TabManagerDelegate) {
self.value = value
}
func get() -> TabManagerDelegate? {
return value
}
}
// TabManager must extend NSObjectProtocol in order to implement WKNavigationDelegate
class TabManager : NSObject {
private var delegates = [WeakTabManagerDelegate]()
func addDelegate(delegate: TabManagerDelegate) {
assert(NSThread.isMainThread())
delegates.append(WeakTabManagerDelegate(value: delegate))
}
func removeDelegate(delegate: TabManagerDelegate) {
assert(NSThread.isMainThread())
for var i = 0; i < delegates.count; i++ {
var del = delegates[i]
if delegate === del.get() {
delegates.removeAtIndex(i)
return
}
}
}
private var tabs: [Browser] = []
private var _selectedIndex = -1
var selectedIndex: Int { return _selectedIndex }
private let defaultNewTabRequest: NSURLRequest
private let navDelegate: TabManagerNavDelegate
private var configuration: WKWebViewConfiguration
let storage: RemoteClientsAndTabs?
private let prefs: Prefs
init(defaultNewTabRequest: NSURLRequest, storage: RemoteClientsAndTabs? = nil, prefs: Prefs) {
// Create a common webview configuration with a shared process pool.
configuration = WKWebViewConfiguration()
configuration.processPool = WKProcessPool()
configuration.preferences.javaScriptCanOpenWindowsAutomatically = !(prefs.boolForKey("blockPopups") ?? true)
self.defaultNewTabRequest = defaultNewTabRequest
self.storage = storage
self.navDelegate = TabManagerNavDelegate()
self.prefs = prefs
super.init()
addNavigationDelegate(self)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "prefsDidChange", name: NSUserDefaultsDidChangeNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func addNavigationDelegate(delegate: WKNavigationDelegate) {
self.navDelegate.insert(delegate)
}
var count: Int {
return tabs.count
}
var selectedTab: Browser? {
if !(0..<count ~= _selectedIndex) {
return nil
}
return tabs[_selectedIndex]
}
subscript(index: Int) -> Browser? {
if index >= tabs.count {
return nil
}
return tabs[index]
}
subscript(webView: WKWebView) -> Browser? {
for tab in tabs {
if tab.webView === webView {
return tab
}
}
return nil
}
func selectTab(tab: Browser?) {
assert(NSThread.isMainThread())
if selectedTab === tab {
return
}
let previous = selectedTab
_selectedIndex = -1
for i in 0..<count {
if tabs[i] === tab {
_selectedIndex = i
break
}
}
assert(tab === selectedTab, "Expected tab is selected")
selectedTab?.createWebview()
for delegate in delegates {
delegate.get()?.tabManager(self, didSelectedTabChange: tab, previous: previous)
}
}
// This method is duplicated to hide the flushToDisk option from consumers.
func addTab(var request: NSURLRequest! = nil, configuration: WKWebViewConfiguration! = nil) -> Browser {
return self.addTab(request: request, configuration: configuration, flushToDisk: true, zombie: false)
}
func addTabsForURLs(urls: [NSURL], zombie: Bool) {
if urls.isEmpty {
return
}
var tab: Browser!
for (let url) in urls {
tab = self.addTab(request: NSURLRequest(URL: url), flushToDisk: false, zombie: zombie, restoring: true)
}
// Flush.
storeChanges()
// Select the most recent.
self.selectTab(tab)
// Notify that we bulk-loaded so we can adjust counts.
for delegate in delegates {
delegate.get()?.tabManagerDidAddTabs(self)
}
}
func addTab(var request: NSURLRequest! = nil, configuration: WKWebViewConfiguration! = nil, flushToDisk: Bool, zombie: Bool, restoring: Bool = false) -> Browser {
assert(NSThread.isMainThread())
configuration?.preferences.javaScriptCanOpenWindowsAutomatically = !(prefs.boolForKey("blockPopups") ?? true)
let tab = Browser(configuration: configuration ?? self.configuration)
for delegate in delegates {
delegate.get()?.tabManager(self, didCreateTab: tab, restoring: restoring)
}
tabs.append(tab)
for delegate in delegates {
delegate.get()?.tabManager(self, didAddTab: tab, atIndex: tabs.count - 1, restoring: restoring)
}
if !zombie {
tab.createWebview()
}
tab.navigationDelegate = self.navDelegate
tab.loadRequest(request ?? defaultNewTabRequest)
if flushToDisk {
storeChanges()
}
return tab
}
// This method is duplicated to hide the flushToDisk option from consumers.
func removeTab(tab: Browser) {
self.removeTab(tab, flushToDisk: true)
}
private func removeTab(tab: Browser, flushToDisk: Bool) {
assert(NSThread.isMainThread())
// If the removed tab was selected, find the new tab to select.
if tab === selectedTab {
let index = getIndex(tab)
if index + 1 < count {
selectTab(tabs[index + 1])
} else if index - 1 >= 0 {
selectTab(tabs[index - 1])
} else {
assert(count == 1, "Removing last tab")
selectTab(nil)
}
}
let prevCount = count
var index = -1
for i in 0..<count {
if tabs[i] === tab {
tabs.removeAtIndex(i)
index = i
break
}
}
assert(count == prevCount - 1, "Tab removed")
// There's still some time between this and the webView being destroyed.
// We don't want to pick up any stray events.
tab.webView?.navigationDelegate = nil
for delegate in delegates {
delegate.get()?.tabManager(self, didRemoveTab: tab, atIndex: index)
}
if flushToDisk {
storeChanges()
}
}
func removeAll() {
let tabs = self.tabs
for tab in tabs {
self.removeTab(tab, flushToDisk: false)
}
storeChanges()
}
func getIndex(tab: Browser) -> Int {
for i in 0..<count {
if tabs[i] === tab {
return i
}
}
assertionFailure("Tab not in tabs list")
return -1
}
private func storeChanges() {
// It is possible that not all tabs have loaded yet, so we filter out tabs with a nil URL.
let storedTabs: [RemoteTab] = optFilter(tabs.map(Browser.toTab))
storage?.insertOrUpdateTabs(storedTabs)
// Also save (full) tab state to disk
preserveTabs()
}
func prefsDidChange() {
let allowPopups = !(prefs.boolForKey("blockPopups") ?? true)
for tab in tabs {
tab.webView?.configuration.preferences.javaScriptCanOpenWindowsAutomatically = allowPopups
}
}
}
extension TabManager {
class SavedTab: NSObject, NSCoding {
let isSelected: Bool
let screenshot: UIImage?
var sessionData: SessionData?
init?(browser: Browser, isSelected: Bool) {
let currentItem = browser.webView?.backForwardList.currentItem
if browser.sessionData == nil {
let backList = browser.webView?.backForwardList.backList as? [WKBackForwardListItem] ?? []
let forwardList = browser.webView?.backForwardList.forwardList as? [WKBackForwardListItem] ?? []
let currentList = (currentItem != nil) ? [currentItem!] : []
var urlList = backList + currentList + forwardList
var updatedUrlList = [NSURL]()
for url in urlList {
updatedUrlList.append(url.URL)
}
var currentPage = -forwardList.count
self.sessionData = SessionData(currentPage: currentPage, urls: updatedUrlList)
} else {
self.sessionData = browser.sessionData
}
self.screenshot = browser.screenshot
self.isSelected = isSelected
super.init()
}
required init(coder: NSCoder) {
self.sessionData = coder.decodeObjectForKey("sessionData") as? SessionData
self.screenshot = coder.decodeObjectForKey("screenshot") as? UIImage
self.isSelected = coder.decodeBoolForKey("isSelected")
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(sessionData, forKey: "sessionData")
coder.encodeObject(screenshot, forKey: "screenshot")
coder.encodeBool(isSelected, forKey: "isSelected")
}
}
private func tabsStateArchivePath() -> String? {
if let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as? String {
return documentsPath.stringByAppendingPathComponent("tabsState.archive")
}
return nil
}
private func preserveTabsInternal() {
if let path = tabsStateArchivePath() {
var savedTabs = [SavedTab]()
for (tabIndex, tab) in enumerate(tabs) {
if let savedTab = SavedTab(browser: tab, isSelected: tabIndex == selectedIndex) {
savedTabs.append(savedTab)
}
}
let tabStateData = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: tabStateData)
archiver.encodeObject(savedTabs, forKey: "tabs")
archiver.finishEncoding()
tabStateData.writeToFile(path, atomically: true)
}
}
func preserveTabs() {
// This is wrapped in an Objective-C @try/@catch handler because NSKeyedArchiver may throw exceptions which Swift cannot handle
Try(
try: { () -> Void in
self.preserveTabsInternal()
},
catch: { exception in
println("Failed to preserve tabs: \(exception)")
}
)
}
private func restoreTabsInternal() {
if let tabStateArchivePath = tabsStateArchivePath() {
if NSFileManager.defaultManager().fileExistsAtPath(tabStateArchivePath) {
if let data = NSData(contentsOfFile: tabStateArchivePath) {
let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
if let savedTabs = unarchiver.decodeObjectForKey("tabs") as? [SavedTab] {
var tabToSelect: Browser?
for (tabIndex, savedTab) in enumerate(savedTabs) {
let tab = self.addTab(flushToDisk: false, zombie: true, restoring: true)
tab.screenshot = savedTab.screenshot
if savedTab.isSelected {
tabToSelect = tab
}
tab.sessionData = savedTab.sessionData
}
if tabToSelect == nil {
tabToSelect = tabs.first
}
for delegate in delegates {
delegate.get()?.tabManagerDidRestoreTabs(self)
}
if let tab = tabToSelect {
selectTab(tab)
tab.createWebview()
}
}
}
}
}
}
func restoreTabs() {
// This is wrapped in an Objective-C @try/@catch handler because NSKeyedUnarchiver may throw exceptions which Swift cannot handle
Try(
try: { () -> Void in
self.restoreTabsInternal()
},
catch: { exception in
println("Failed to restore tabs: \(exception)")
}
)
}
}
extension TabManager : WKNavigationDelegate {
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
storeChanges()
}
}
// WKNavigationDelegates must implement NSObjectProtocol
class TabManagerNavDelegate : NSObject, WKNavigationDelegate {
private var delegates = WeakList<WKNavigationDelegate>()
func insert(delegate: WKNavigationDelegate) {
delegates.insert(delegate)
}
func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
for delegate in delegates {
delegate.webView?(webView, didCommitNavigation: navigation)
}
}
func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
for delegate in delegates {
delegate.webView?(webView, didFailNavigation: navigation, withError: error)
}
}
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!,
withError error: NSError) {
for delegate in delegates {
delegate.webView?(webView, didFailProvisionalNavigation: navigation, withError: error)
}
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
for delegate in delegates {
delegate.webView?(webView, didFinishNavigation: navigation)
}
}
func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition,
NSURLCredential!) -> Void) {
var disp: NSURLSessionAuthChallengeDisposition? = nil
for delegate in delegates {
delegate.webView?(webView, didReceiveAuthenticationChallenge: challenge) { (disposition, credential) in
// Whoever calls this method first wins. All other calls are ignored.
if disp != nil {
return
}
disp = disposition
completionHandler(disposition, credential)
}
}
}
func webView(webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
for delegate in delegates {
delegate.webView?(webView, didReceiveServerRedirectForProvisionalNavigation: navigation)
}
}
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
for delegate in delegates {
delegate.webView?(webView, didStartProvisionalNavigation: navigation)
}
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction,
decisionHandler: (WKNavigationActionPolicy) -> Void) {
var res = WKNavigationActionPolicy.Allow
for delegate in delegates {
delegate.webView?(webView, decidePolicyForNavigationAction: navigationAction, decisionHandler: { policy in
if policy == .Cancel {
res = policy
}
})
}
decisionHandler(res)
}
func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse,
decisionHandler: (WKNavigationResponsePolicy) -> Void) {
var res = WKNavigationResponsePolicy.Allow
for delegate in delegates {
delegate.webView?(webView, decidePolicyForNavigationResponse: navigationResponse, decisionHandler: { policy in
if policy == .Cancel {
res = policy
}
})
}
decisionHandler(res)
}
}
| mpl-2.0 | eefdac5f5ad489fa221ebd2e71673668 | 33.48497 | 166 | 0.597222 | 5.645669 | false | false | false | false |
NghiaTranUIT/Unofficial-Uber-macOS | UberGo/UberGo/ProductDetailController.swift | 1 | 2967 | //
// ProductDetailController.swift
// UberGo
//
// Created by Nghia Tran on 7/2/17.
// Copyright © 2017 Nghia Tran. All rights reserved.
//
import UberGoCore
protocol ProductDetailControllerDelegate: class {
func productDetailControllerShouldDimiss()
}
class ProductDetailController: NSViewController {
// MARK: - OUTLET
@IBOutlet fileprivate weak var productImageView: NSImageView!
@IBOutlet fileprivate weak var productNameLbl: NSTextField!
@IBOutlet fileprivate weak var descriptionLbl: NSTextField!
@IBOutlet fileprivate weak var descriptionLblTop: NSLayoutConstraint!
@IBOutlet fileprivate weak var fareLbl: NSTextField!
@IBOutlet fileprivate weak var capacityLbl: NSTextField!
@IBOutlet fileprivate weak var timeArrvivalLbl: NSTextField!
@IBOutlet fileprivate weak var timeLbl: NSTextField!
@IBOutlet fileprivate weak var dividerLineTime: NSBox!
// MARK: - Variable
public weak var delegate: ProductDetailControllerDelegate?
fileprivate var productObj: ProductObj!
// MARK: - View Cycle
override func viewDidLoad() {
super.viewDidLoad()
initCommon()
setupLayout()
setupData()
}
public func configureController(with productObj: ProductObj) {
self.productObj = productObj
}
@IBAction func doneBtnOnTap(_ sender: Any) {
delegate?.productDetailControllerShouldDimiss()
}
@IBAction func breakdownBtnOnTap(_ sender: Any) {
let controller = BreakdownPriceController(nibName: "BreakdownPriceController", bundle: nil)!
controller.configureController(productObj)
presentViewControllerAsSheet(controller)
}
}
// MARK: - Private
extension ProductDetailController {
fileprivate func initCommon() {
}
fileprivate func setupLayout() {
var isHidden = false
var topConstant: CGFloat = 36.0
// Hide Time estimate
if productObj.estimateTime == nil {
isHidden = true
topConstant = 16.0
}
timeLbl.isHidden = isHidden
timeArrvivalLbl.isHidden = isHidden
dividerLineTime.isHidden = isHidden
// Update layout
descriptionLblTop.constant = topConstant
view.layoutSubtreeIfNeeded()
}
fileprivate func setupData() {
// Image
productImageView.image = NSImage(imageLiteralResourceName: "uber_car_selected")
// Name
productNameLbl.stringValue = productObj.displayName
// Desc
descriptionLbl.stringValue = productObj.descr
// Capcity
capacityLbl.stringValue = productObj.prettyCapacity
// Arrive
if let estimateTime = productObj.estimateTime {
timeArrvivalLbl.stringValue = "\(estimateTime.prettyEstimateTime) mins"
}
// Fare
if let estimatePrice = productObj.estimatePrice {
fareLbl.stringValue = estimatePrice.estimate
}
}
}
| mit | 88009884e8d0f925b0c1096548c6b30f | 26.981132 | 100 | 0.680378 | 5.087479 | false | false | false | false |
briancroom/BackgroundFetchLogger | BackgroundFetchLogger/AppDelegate.swift | 1 | 2221 | import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
struct LogEvents {
static let DidFinishLaunching = "Finished Launching"
static let DidEnterBackground = "Entered Background"
static let WillEnterForeground = "Entering Foreground"
static let WillTerminate = "Terminating"
static let BackgroundFetch = "Background Fetch"
}
var window: UIWindow?
// Apple QuickTime sample file. ~75kb
let sampleURL = NSURL(string: "http://a1408.g.akamai.net/5/1408/1388/2005110406/1a1a1ad948be278cff2d96046ad90768d848b41947aa1986/sample_sorenson.mov.zip")!
lazy var logger: Logger = {
let baseURL = NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: false, error: nil)!
return Logger(logURL: baseURL.URLByAppendingPathComponent("events.log"))
}()
lazy var fetcher: Fetcher = { return DownloadFetcher(URL: self.sampleURL, logger: self.logger) }()
lazy var batteryStateObserver: BatteryStateObserver = { return BatteryStateObserver(logger: self.logger) }()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum);
(window?.rootViewController as? ViewController)?.logger = logger
logger.logEvent(LogEvents.DidFinishLaunching)
batteryStateObserver.beginObserving()
return true
}
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
logger.logEvent(LogEvents.BackgroundFetch)
fetcher.fetch(completionHandler)
}
func applicationDidEnterBackground(application: UIApplication) {
logger.logEvent(LogEvents.DidEnterBackground)
}
func applicationWillEnterForeground(application: UIApplication) {
logger.logEvent(LogEvents.WillEnterForeground)
}
func applicationWillTerminate(application: UIApplication) {
logger.logEvent(LogEvents.WillTerminate)
}
}
| mit | 9e7dc0270f3c745d522eaff13d05c5e8 | 40.12963 | 189 | 0.747861 | 5.201405 | false | false | false | false |
emilstahl/swift | validation-test/compiler_crashers_fixed/0172-swift-archetypebuilder-inferrequirementswalker-walktotypepost.swift | 12 | 7754 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A {
typealias B
func b(B)
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
<c b:
func b<c {
enum b {
func b
var _ = b
func b((Any, e))(e: (Any) -> <d>(()-> d) -> f
func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c
k)
func c<i>() -> (i, i -> i) -> i {
k b k.i = {
}
{
i) {
k }
}
protocol c {
class func i()
}
class k: c{ class func i {
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
typealias g
}
func b(c) -> <d>(() -> d) {
}
import Foundation
class d<c>: NSObject {
var b: c
init(b: c) {
self.b = b
}
}
struct c<e> {
let d: i h
}
func f(h: b) -> <e>(()-> e
c
j)
func c<k>() -> (k, > k) -> k {
d h d.f 1, k(j, i)))
class k {
typealias h = h
func C<D, E: A where D.C == E> {
}
func prefix(with: String) -> <T>(() -> T) -> String {
{ g in "\(withing
}
clasnintln(some(xs))
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(m: (Any, Any) -> Any) -> Any in
return m(x, y)
}
}
func b(z: (((Any, Any) -> Any) -> Any)) -> Any {
return z({
(p: Any, q:Any) -> Any in
return p
})
}
b(a(1, a(2, 3)))
protocol f {
k g d {
k d
k k
}
j j<l : d> : d {
k , d>
}
class f: f {
}
class B : l {
}
k l = B
class f<i : f
() {
g g h g
}
}
func e(i: d) -> <f>(() -> f)>
func h<j>() -> (j, j -> j) -> j {
var f: ({ (c: e, f: e -> e) -> return f(c)
}(k, i)
let o: e = { c, g
return f(c)
}(l) -> m) -> p>, e>
}
class n<j : n>
protocol A {
func c() -> String
}
class B {
func d() -> String {
return ""
}
}
class C: B, A {
override func d() -> String {
return ""
}
func c() -> String {
return ""
}
}
func e<T where T: A, T: B>(t: T) {
t.c()
}
struct c<d: SequenceType, b where Optional<b> == d.Generator.Element>
func f<e>() -> (e, e -> e) -> e {
e b e.c = {}
{
e)
{
f
}
}
protocol f {
class func c()
}
class e: f {
class func c
}
}
struct c<d : SequenceType> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
protocol b {
class func e()
}
struct c {
var d: b.Type
func e() {
d.e()
}
}
func a<T>() {
enum b {
case c
}
}
func r<t>() {
f f {
i i
}
}
struct i<o : u> {
o f: o
}
func r<o>() -> [i<o>] {
p []
}
class g<t : g> {
}
class g: g {
}
class n : h {
}
typealias h = n
protocol g {
func i() -> l func o() -> m {
q""
}
}
func j<t k t: g, t: n>(s: t) {
s.i()
}
protocol r {
}
protocol f : r {
}
protocol i : r {
}
j
)
func n<w>() -> (w, w -> w) -> w {
o m o.q = {
}
{
w) {
k }
}
protocol n {
class func q()
}
class o: n{ class func q {}
func p(e: Int = x) {
}
let c = p
c()
func r<o: y, s q n<s> ==(r(t))
protocol p : p {
}
protocol p {
class func c()
}
class e: p {
class func c() { }
}
(e() u p).v.c()
k e.w == l> {
}
func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) {
}
class i {
func d((h: (Any, AnyObject)) {
d(h)
}
}
d
h)
func d<i>() -> (i, i -> i) -> i {
i j i.f = {
}
protocol d {
class func f()
}
class i: d{ class func f {}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
typealias h
}
func a(b: Int = 0) {
}
let c = a
c()
protocol a : a {
}
}
}
class b<i : b> i: g{ func c {}
e g {
: g {
h func i() -> }
struct c<e> {
let d: [( h
}
func b(g: f) -> <e>(()-> e) -> i
func ^(a: BooleanType, Bool) -> Bool {
return !(a)
}
func d() -> String {
return 1
k f {
typealias c
}
class g<i{
}
d(j i)
class h {
typealias i = i
}
func o() as o).m.k()
func p(k: b) -> <i>(() -> i) -> b {
n { o f "\(k): \(o())" }
}
struct d<d : n, o:j n {
l p
}
protocol o : o {
}
func o<
import Foundation
class k<f>: NSObject {
d e: f
g(e: f) {
j h.g()
}
}
d
protocol i : d { func d
i
struct l<e : SequenceType> {
l g: e
}
func h<e>() -> [l<e>] {
f []
}
func i(e: g) -> <j>(() -> j) -> k
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
)
var d = b
=b as c=b
o
}
class f<p : k, p : k where p.n == p> : n {
}
class f<p, p> {
}
protocol k {
typealias n
}
o: i where k.j == f> {l func k() { }
}
(f() as n).m.k()
func k<o {
enum k {
func o
var _ = protocol g {
typealias f
typealias e
}
struct c<h : g> : g {
typealias f = h
typealias e = a<c<h>, f>
import Foundation
class m<j>k i<g : g, e : f k(f: l) {
}
i(())
class h {
typealias g = g
}
class p {
u _ = q() {
}
}
u l = r
u s: k -> k = {
n $h: m.j) {
}
}
o l() {
({})
}
struct m<t> {
let p: [(t, () -> ())] = []
}
protocol p : p {
}
protocol m {
o u() -> String
}
class j {
o m() -> String {
n ""
}
}
class h: j, m {
q o m() -> String {
n ""
}
o u() -> S, q> {
}
protocol u {
typealias u
}
class p {
typealias u = u
}
func ^(r: l, k) -> k {
? {
h (s : t?) q u {
g let d = s {
p d
}
}
e}
let u : [Int?] = [n{
c v: j t.v == m>(n: o<t>) {
}
}
class r {
typealias n = n
func c<e>() -> (e -> e) -> e {
e, e -> e) ->)func d(f: b) -> <e>(() -> e) -> b {
return { g in}
protocol p {
class func g()
}
class h: p {
class func g() { }
}
(h() as p).dynamicType.g()
protocol p {
}
protocol h : p {
}
protocol g : p {
}
protocol n {
o t = p
}
struct h : n {
t : n q m.t == m> (h: m) {
}
func q<t : n q t.t == g> (h: t) {
}
q(h())
func r(g: m) -> <s>(() -> s) -> n
b
protocol d : b { func b
func d(e: = { (g: h, f: h -> h) -> h in
return f(g)
}
func f<T : BooleanType>(b: T) {
}
f(true as BooleanType)
class k {
func l((Any, k))(m }
}
func j<f: l: e -> e = {
{
l) {
m }
}
protocol k {
class func j()
}
class e: k{ class func j
func f(c: i, l: i) -> (((i, i) -> i) -> i) {
b {
(h -> i) d $k
}
let e: Int = 1, 1)
class g<j :g
func a<T>() -> (T, T -> T) -> T {
var b: ((T, T -> T) -> T)!
return b
}
func ^(d: e, Bool) -> Bool {g !(d)
}
protocol d {
f func g()
f e: d {
f func g() { }
}
(e() h d).i()
e
protocol g : e { func e
>)
}
struct n : C {
class p {
typealias n = n
}
l
l)
func l<u>() -> (u, u -> u) -> u {
n j n.q = {
}
{
u) {
h }
}
protocol l {
class {
func n() -> q {
return ""
}
}
class C: s, l {
t) {
return {
(s: (t, t) -> t) -> t o
return s(c, u)
-> Any) -> Any l
k s(j, t)
}
}
func b(s: (((Any, Any) -> Any) -> Any)
func m<u>() -> (u, u -> u) -> u {
p o p.s = {
}
{
u) {
o }
}
s m {
class func s()
}
class p: m{ class func s {}
s p {
func m() -> String
}
class n {
func p() -> String {
q ""
}
}
class e: n, p {
v func> String {
q ""
}
{
r m = m
}
func s<o : m, o : p o o.m == o> (m: o) {
}
func s<v : p o v.m == m> (u: String) -> <t>(() -> t) -
protocol A {
func c()l k {
func l() -> g {
m ""
}
}
class C: k, A {
j func l()q c() -> g {
m ""
}
}
func e<r where r: A, r: k>(n: r) {
n.c()
}
protocol A {
typealias h
}
c k<r : A> {
p f: r
p p: r.h
}
protocol C l.e()
}
}
class o {
typealias l = l
f g
}
struct d<i : b> : b {
typealias b = i
typealias g = a<d<i>i) {
}
let d = a
d()
a=d g a=d
protocol a : a {
}
class a {
typealias b = b
func m(c: b) -> <h>(() -> h) -> b {
f) -> j) -> > j {
l i !(k)
}
d
l)
func d<m>-> (m, m -
| apache-2.0 | b8e3976c2e77330c21eed5b5820cdf2e | 12.723894 | 87 | 0.409724 | 2.342598 | false | false | false | false |
dbahat/conventions-ios | Conventions/Conventions/notifications/NotificationsSchedualer.swift | 1 | 7741 | //
// NotificationsSchedualer.swift
// Conventions
//
// Created by David Bahat on 8/6/16.
// Copyright © 2016 Amai. All rights reserved.
//
import Foundation
class NotificationsSchedualer {
static let CONVENTION_FEEDBACK_INFO = "ConventionFeedback"
static let CONVENTION_FEEDBACK_LAST_CHANCE_INFO = "ConventionFeedbackLastChance"
static let EVENT_ABOUT_TO_START_INFO = "EventAboutToStart"
static let EVENT_FEEDBACK_REMINDER_INFO = "EventFeedbackReminder"
static func scheduleConventionFeedbackIfNeeded() {
if (UIApplication.shared.currentUserNotificationSettings?.types == UIUserNotificationType()) {return}
if NotificationSettings.instance.conventionFeedbackReminderWasSet
|| Convention.instance.feedback.conventionInputs.isSent
|| Convention.instance.isFeedbackSendingTimeOver() {
return;
}
let notification = UILocalNotification()
notification.fireDate = Convention.endDate.addHours(22)
notification.timeZone = Date.timeZone
if #available(iOS 8.2, *) {
notification.alertTitle = "עזור לנו להשתפר"
}
notification.alertBody = String(format: "%@ הסתיים, ואנחנו רוצים לשמוע את דעתך", arguments: [Convention.displayName]);
notification.alertAction = "מלא פידבק על הכנס"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = [CONVENTION_FEEDBACK_INFO: true];
UIApplication.shared.scheduleLocalNotification(notification)
NotificationSettings.instance.conventionFeedbackReminderWasSet = true
}
static func scheduleConventionFeedbackLastChanceIfNeeded() {
if (UIApplication.shared.currentUserNotificationSettings?.types == UIUserNotificationType()) {return}
if NotificationSettings.instance.conventionFeedbackLastChanceReminderWasSet
|| Convention.instance.feedback.conventionInputs.isSent
|| Convention.instance.isFeedbackSendingTimeOver() {
return;
}
let notification = UILocalNotification()
notification.fireDate = Convention.endDate.addDays(4)
notification.timeZone = Date.timeZone
if #available(iOS 8.2, *) {
notification.alertTitle = "הזדמנות אחרונה להשפיע"
}
notification.alertBody = String(format: "נהנתם ב%@? נשארו רק עוד 3 ימים לשליחת פידבק!", arguments: [Convention.displayName]);
notification.alertAction = "מלא פידבק על הכנס"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = [CONVENTION_FEEDBACK_LAST_CHANCE_INFO: true];
UIApplication.shared.scheduleLocalNotification(notification)
NotificationSettings.instance.conventionFeedbackLastChanceReminderWasSet = true
}
static func removeConventionFeedback() {
guard let notifications = UIApplication.shared.scheduledLocalNotifications else {return;};
for notification in notifications {
guard
let userInfo = notification.userInfo,
let conventionFeedback = userInfo[CONVENTION_FEEDBACK_INFO] as? Bool
else {
continue;
}
if conventionFeedback {
UIApplication.shared.cancelLocalNotification(notification);
}
}
}
static func removeConventionFeedbackLastChance() {
guard let notifications = UIApplication.shared.scheduledLocalNotifications else {return;};
for notification in notifications {
guard
let userInfo = notification.userInfo,
let conventionFeedback = userInfo[CONVENTION_FEEDBACK_LAST_CHANCE_INFO] as? Bool
else {
continue;
}
if conventionFeedback {
UIApplication.shared.cancelLocalNotification(notification);
}
}
}
static func scheduleEventAboutToStartNotification(_ event: ConventionEvent) {
if (UIApplication.shared.currentUserNotificationSettings?.types == UIUserNotificationType()) {return}
// In case the user manually disabled event reminder notifications don't schedule anything
if !NotificationSettings.instance.eventStartingReminder {
return
}
// Don't schdule a notification in the past
if (event.startTime.addMinutes(-5).timeIntervalSince1970 < Date.now().timeIntervalSince1970) {return;}
let notification = UILocalNotification()
notification.fireDate = event.startTime.addMinutes(-5)
notification.timeZone = Date.timeZone
if #available(iOS 8.2, *) {
notification.alertTitle = "אירוע עומד להתחיל"
}
notification.alertBody = String(format: "האירוע %@ עומד להתחיל ב%@", arguments: [event.title, event.hall.name])
notification.alertAction = "לפתיחת האירוע"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = [EVENT_ABOUT_TO_START_INFO: event.id]
UIApplication.shared.scheduleLocalNotification(notification)
}
static func removeEventAboutToStartNotification(_ event: ConventionEvent) {
NotificationsSchedualer.removeEventNotification(event, identifier: EVENT_ABOUT_TO_START_INFO)
}
static func scheduleEventFeedbackReminderNotification(_ event: ConventionEvent) {
if (UIApplication.shared.currentUserNotificationSettings?.types == UIUserNotificationType()) {return}
// In case the user manually disabled event reminder notifications don't schedule anything
if !NotificationSettings.instance.eventFeedbackReminder {
return
}
// Don't schdule a notification in the past
if (event.endTime.timeIntervalSince1970 < Date.now().timeIntervalSince1970) {return;}
// event about to start notification
let notification = UILocalNotification()
notification.fireDate = event.endTime.addMinutes(5)
notification.timeZone = Date.timeZone
if #available(iOS 8.2, *) {
notification.alertTitle = "עזור לנו להשתפר"
}
notification.alertBody = String(format: "נהנית באירוע %@? שלח פידבק למארגני האירוע", arguments: [event.title, event.hall.name])
notification.alertAction = "מלא פידבק"
notification.userInfo = [EVENT_FEEDBACK_REMINDER_INFO: event.id]
UIApplication.shared.scheduleLocalNotification(notification)
}
static func removeEventFeedbackReminderNotification(_ event: ConventionEvent) {
NotificationsSchedualer.removeEventNotification(event, identifier: EVENT_FEEDBACK_REMINDER_INFO)
}
fileprivate static func removeEventNotification(_ event: ConventionEvent, identifier: String) {
guard let notifications = UIApplication.shared.scheduledLocalNotifications else {return;};
for notification in notifications {
guard
let userInfo = notification.userInfo,
let eventId = userInfo[identifier] as? String
else {
continue;
}
if eventId == event.id {
UIApplication.shared.cancelLocalNotification(notification);
}
}
}
}
| apache-2.0 | 33e6bc795ac582e77efc9600c8e14a75 | 41.75 | 135 | 0.660819 | 4.927308 | false | false | false | false |
quangvu1994/Exchange | Exchange/View Controllers/ItemDetailViewController.swift | 1 | 13732 | //
// ItemDetailViewController.swift
// Exchange
//
// Created by Quang Vu on 7/27/17.
// Copyright © 2017 Quang Vu. All rights reserved.
//
import UIKit
import FirebaseDatabase
import Kingfisher
class ItemDetailViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var actionButton: UIButton!
var scenario: EXScenarios = .exchange
var post: Post?
// Convert date to a formatted string
let timestampFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM d, YYYY"
return dateFormatter
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.statusBarStyle = .lightContent
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.statusBarStyle = .default
self.navigationController?.navigationBar.setBackgroundImage(nil, for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = nil
self.navigationController?.navigationBar.isTranslucent = false
}
override func viewDidLoad() {
super.viewDidLoad()
actionButton.layer.masksToBounds = true
actionButton.layer.cornerRadius = 3
guard let post = post else {
return
}
switch post.poster.uid {
case User.currentUser.uid:
if !post.requestedBy.isEmpty {
actionButton.alpha = 0.5
actionButton.setTitle("In Exchange", for: .normal)
} else {
actionButton.setTitle("Edit Item", for: .normal)
}
default:
if let _ = post.requestedBy["\(User.currentUser.uid)"] {
actionButton.alpha = 0.5
actionButton.setTitle("In Exchange", for: .normal)
} else {
actionButton.setTitle("Exchange Item", for: .normal)
}
}
let itemRef = Database.database().reference().child("allItems/\(post.key!)/availability")
itemRef.observe(.value, with: { [weak self] (snapshot) in
guard let availability = snapshot.value as? Bool else {
return
}
if !availability {
self?.actionButton.alpha = 0.5
self?.actionButton.setTitle("Sold", for: .normal)
self?.actionButton.isUserInteractionEnabled = false
}
})
}
@IBAction func actionHandler(_ sender: UIButton) {
guard let post = post else {
return
}
UIApplication.shared.beginIgnoringInteractionEvents()
switch post.poster.uid {
case User.currentUser.uid:
if actionButton.titleLabel?.text == "In Exchange" {
let alertController = UIAlertController(title: nil, message: "Please finalize all exchange requests that contain this item before editing this item. You can review your requests in your Profile", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
} else {
self.performSegue(withIdentifier: "Edit Item", sender: nil)
}
default:
if actionButton.titleLabel?.text == "In Exchange" {
let alertController = UIAlertController(title: nil, message: "You have already sent a request for this item. You can review your request under 'Outgoing Request' tab in your profile", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
} else {
self.performSegue(withIdentifier: "Exchange Sequence", sender: nil)
}
}
UIApplication.shared.endIgnoringInteractionEvents()
}
/**
Flagging post with inappropriate content
*/
@IBAction func flaggingPost(_ sender: UIBarButtonItem) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
guard let post = post else {
return
}
// If this item is belong to current user -> display delete item
if post.poster.uid == User.currentUser.uid {
let deleteAction = UIAlertAction(title: "Delete Item" , style: .default, handler: { [unowned self] _ in
let confirmationMessage = UIAlertController(title: nil, message: "Are you sure that you want to delete this item?", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "No", style: .cancel, handler: nil)
let confirmedAction = UIAlertAction(title: "Yes", style: .default, handler: { _ in
// Don't allow user to delete item if the item is still in exchange progress
if !post.requestedBy.isEmpty {
self.displayWarningMessage(message: "Please finalize all exchange requests that contain this item before deleting this item. You can review your requests in your Profile")
} else {
PostService.deleteSpecificPost(for: post.key!, completionHandler: { (success) in
if success {
switch self.scenario {
case .edit:
self.performSegue(withIdentifier: "Personal Item Detail", sender: nil)
default:
self.performSegue(withIdentifier: "Item Detail", sender: nil)
}
} else {
self.displayWarningMessage(message: "Unable to delete this item. Please check your network and try again")
}
})
}
})
confirmationMessage.addAction(cancelAction)
confirmationMessage.addAction(confirmedAction)
self.present(confirmationMessage, animated: true, completion: nil)
})
alertController.addAction(deleteAction)
} else {
// Report inappropriate post option
let flagAction = UIAlertAction(title: "Report as Inappropriate", style: .default) { [weak self] _ in
PostService.flag(post)
let okAlert = UIAlertController(title: nil, message: "The post has been flagged.", preferredStyle: .alert)
okAlert.addAction(UIAlertAction(title: "Ok", style: .default))
self?.present(okAlert, animated: true)
}
alertController.addAction(flagAction)
}
// Add cancel button
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
// Prenset action sheet
present(alertController, animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
if identifier == "Exchange Sequence" {
let navControllerDestination = segue.destination as! UINavigationController
let viewControllerDestination = navControllerDestination.viewControllers.first as! ExchangeSequenceViewController
viewControllerDestination.originalItem = post
} else if identifier == "Edit Item" {
let editView = segue.destination as! CreatePostViewController
editView.scenario = .edit
if let post = post {
let dispGroup = DispatchGroup()
for i in 0..<post.imagesURL.count {
dispGroup.enter()
let url = URL(string: post.imagesURL[i])
ImageDownloader.default.downloadImage(with: url!, options: [], progressBlock: nil) {
(image, error, url, data) in
if let error = error {
assertionFailure(error.localizedDescription)
return
}
editView.imageList[i] = image
dispGroup.leave()
}
}
dispGroup.notify(queue: .main, execute: {
editView.postTitle = post.postTitle
editView.postDescription = post.postDescription
editView.tradeLocation = post.tradeLocation
editView.wishList = post.wishList
editView.category = post.postCategory
editView.postKey = post.key
editView.activityIndicator.stopAnimating()
})
}
} else if identifier == "Open User Store" {
guard let user = sender as? User else {
return
}
let viewControllerDestination = segue.destination as! MyItemViewController
// Safe to force unwrap here
viewControllerDestination.user = user
}
}
}
@IBAction func backAction(_ sender: Any) {
switch scenario {
case .edit:
self.performSegue(withIdentifier: "Personal Item Detail", sender: nil)
default:
self.performSegue(withIdentifier: "Item Detail", sender: nil)
}
}
@IBAction func unwindFromExchangeSequence(_ sender: UIStoryboardSegue) {
if let identifier = sender.identifier {
if identifier == "Finish Exchange Sequence" {
actionButton.alpha = 0.5
actionButton.setTitle("In Exchange", for: .normal)
}
}
}
func segueToUserStore() {
// Fetch user info
UserService.retrieveUser((post?.poster.uid)!, completion: { [weak self] (userFromFIR) in
guard let user = userFromFIR else {
self?.displayWarningMessage(message: "Unable to retrieve this user information, please check your network")
return
}
self?.performSegue(withIdentifier: "Open User Store", sender: user)
})
}
}
extension ItemDetailViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let post = post else {
fatalError("No post found, can't display information")
}
switch indexPath.row {
case 0:
let cell: ItemImageCell = tableView.dequeueReusableCell()
let slide = cell.createImageSlides(post: post)
cell.setupSlide(slide: slide, view: view)
cell.pageControl.numberOfPages = post.imagesURL.count
cell.pageControl.currentPage = 0
return cell
case 1:
let cell: PosterInformationCell = tableView.dequeueReusableCell()
cell.topLabel.text = post.poster.username
cell.topLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ItemDetailViewController.segueToUserStore)))
cell.bottomLabel.text = timestampFormatter.string(from: post.creationDate)
return cell
case 2:
let cell: ItemInfomationCell = tableView.dequeueReusableCell()
cell.titleLabel.text = post.postTitle
cell.detailText.text = post.postDescription
return cell
case 3:
let cell: ItemInfomationCell = tableView.dequeueReusableCell()
cell.titleLabel.text = "Wish List"
cell.detailText.text = post.wishList
return cell
case 4:
let cell: ItemCategoryCell = tableView.dequeueReusableCell()
cell.categoryLabel.text = post.postCategory
return cell
case 5:
let cell: ItemInfomationCell = tableView.dequeueReusableCell()
cell.titleLabel.text = "Trade Location"
cell.detailText.text = post.tradeLocation
return cell
default:
fatalError("Unrecognized index path row")
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
case 0:
return view.frame.height*4/7
case 1:
return 80
case 2:
return 140
case 3:
return 140
case 4:
return 80
case 5:
return 140
default:
fatalError("Unrecognized index path row")
}
}
}
| mit | 05b1bd30cba69bab1655005d6c2e1241 | 41.909375 | 235 | 0.572573 | 5.673967 | false | false | false | false |
Staance/Swell | Swell/Logger.swift | 2 | 6097 | //
// Logger.swift
// Swell
//
// Created by Hubert Rabago on 6/20/14.
// Copyright (c) 2014 Minute Apps LLC. All rights reserved.
//
public class Logger {
let name: String
public var level: LogLevel
public var formatter: LogFormatter
var locations: [LogLocation]
var enabled: Bool;
public init(name: String,
level: LogLevel = .INFO,
formatter: LogFormatter = QuickFormatter(),
logLocation: LogLocation = ConsoleLocation.getInstance()) {
self.name = name
self.level = level
self.formatter = formatter
self.locations = [LogLocation]()
self.locations.append(logLocation)
self.enabled = true;
Swell.registerLogger(self);
}
public func log<T>(logLevel: LogLevel,
@autoclosure message: () -> T,
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__) {
if (self.enabled) && (logLevel.level >= level.level) {
let logMessage = formatter.formatLog(self, level: logLevel, message: message,
filename: filename, line: line, function: function);
for location in locations {
location.log(logMessage)
}
}
}
//**********************************************************************
// Main log methods
public func trace<T>(@autoclosure message: () -> T,
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__) {
self.log(.TRACE, message: message, filename: filename, line: line, function: function)
}
public func debug<T>(@autoclosure message: () -> T,
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__) {
self.log(.DEBUG, message: message, filename: filename, line: line, function: function)
}
public func info<T>(@autoclosure message: () -> T,
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__) {
self.log(.INFO, message: message, filename: filename, line: line, function: function)
}
public func warn<T>(@autoclosure message: () -> T,
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__) {
self.log(.WARN, message: message, filename: filename, line: line, function: function)
}
public func error<T>(@autoclosure message: () -> T,
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__) {
self.log(.ERROR, message: message, filename: filename, line: line, function: function)
}
public func severe<T>(@autoclosure message: () -> T,
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__) {
self.log(.SEVERE, message: message, filename: filename, line: line, function: function)
}
//*****************************************************************************************
// Log methods that accepts closures - closures must accept no param and return a String
public func log(logLevel: LogLevel,
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__,
fn: () -> String) {
if (self.enabled) && (logLevel.level >= level.level) {
let message = fn()
self.log(logLevel, message: message)
}
}
public func trace(
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__,
fn: () -> String
) {
log(.TRACE, filename: filename, line: line, function: function, fn: fn)
}
public func debug(
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__,
fn: () -> String) {
log(.DEBUG, filename: filename, line: line, function: function, fn: fn)
}
public func info(
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__,
fn: () -> String) {
log(.INFO, filename: filename, line: line, function: function, fn: fn)
}
public func warn(
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__,
fn: () -> String) {
log(.WARN, filename: filename, line: line, function: function, fn: fn)
}
public func error(
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__,
fn: () -> String) {
log(.ERROR, filename: filename, line: line, function: function, fn: fn)
}
public func severe(
filename: String? = __FILE__, line: Int? = __LINE__, function: String? = __FUNCTION__,
fn: () -> String) {
log(.SEVERE, filename: filename, line: line, function: function, fn: fn)
}
//**********************************************************************
// Methods to expose this functionality to Objective C code
class func getLogger(name: String) -> Logger {
return Logger(name: name);
}
public func traceMessage(message: String) {
self.trace(message, filename: nil, line: nil, function: nil);
}
public func debugMessage(message: String) {
self.debug(message, filename: nil, line: nil, function: nil);
}
public func infoMessage(message: String) {
self.info(message, filename: nil, line: nil, function: nil);
}
public func warnMessage(message: String) {
self.warn(message, filename: nil, line: nil, function: nil);
}
public func errorMessage(message: String) {
self.error(message, filename: nil, line: nil, function: nil);
}
public func severeMessage(message: String) {
self.severe(message, filename: nil, line: nil, function: nil);
}
}
| apache-2.0 | b123c6ffd667c3a289865ab3ac2df307 | 35.291667 | 99 | 0.531573 | 4.348787 | false | false | false | false |
tomasharkema/HoelangTotTrein2.iOS | Packages/Core/Sources/Core/Services/TravelService.swift | 1 | 16824 | //
// TravelService.swift
// HoelangTotTrein2
//
// Created by Tomas Harkema on 27-09-15.
// Copyright © 2015 Tomas Harkema. All rights reserved.
//
import API
import Bindable
import BindableNSObject
import CancellationToken
import CoreLocation
import Foundation
import Promissum
import WatchConnectivity
enum TravelServiceError: Error {
case notChanged
}
public struct MultipleAdvices {
let responses: [AdvicesResponse]
public var trips: Advices {
Array(responses.map(\.trips).joined())
}
}
public class TravelService: NSObject {
private let queue = DispatchQueue(label: "nl.tomasharkema.TravelService")
private let apiService: ApiService
private let locationService: LocationService
private let dataStore: DataStore
private let preferenceStore: PreferenceStore
private let heartBeat: HeartBeat
private var heartBeatToken: HeartBeat.Token?
private var advicesCancellationToken: CancellationTokenSource?
#if os(iOS)
private let session = WCSession.default
#endif
private let currentAdvicesSource = VariableSource<LoadingState<AdvicesAndRequest>>(value: .loading)
public let currentAdvices: Variable<LoadingState<AdvicesAndRequest>>
private let currentAdviceOnScreenSource = VariableSource<Advice?>(value: nil)
public let currentAdviceOnScreen: Variable<Advice?>
// private let pickedAdviceRequestSource = VariableSource(value: AdviceRequest(from: nil, to: nil))
public let adviceRequest: Variable<AdviceRequest>
public let originalAdviceRequest: Variable<AdviceRequest>
private let adviceStationsSource = VariableSource<AdviceStations>(value: AdviceStations(from: nil, to: nil))
public var adviceStations: Variable<AdviceStations> { adviceStationsSource.variable }
private let mostUsedStationsSource = VariableSource(value: Stations())
public let mostUsedStations: Variable<Stations>
private let stationsSource = VariableSource(value: Stations())
public let stations: Variable<Stations>
public let currentAdvice: Variable<LoadingState<Advice?>>
private let errorSource = ChannelSource<Error>()
public var error: Channel<Error> { errorSource.channel }
// public static func create() -> Self {
// return Self()
// }
//
// required override init() {
// super.init()
// }
public init(apiService: ApiService, locationService: LocationService, dataStore: DataStore, preferenceStore: PreferenceStore, heartBeat: HeartBeat) {
self.apiService = apiService
self.locationService = locationService
self.dataStore = dataStore
self.preferenceStore = preferenceStore
self.heartBeat = heartBeat
currentAdvices = currentAdvicesSource.variable
currentAdviceOnScreen = currentAdviceOnScreenSource.variable
mostUsedStations = mostUsedStationsSource.variable
stations = stationsSource.variable
currentAdvice = (currentAdvices && preferenceStore.currentAdviceIdentifier)
.map { loadedAdvices, adviceIdentifier in
switch loadedAdvices {
case .result(let advices):
let firstAdvice = advices.advices.first { $0.checksum == adviceIdentifier?.rawValue }
return .result(firstAdvice ?? advices.advices.first)
case .error(let error):
return .error(error)
case .loading:
return .loading
}
}
adviceRequest = preferenceStore.adviceRequest
originalAdviceRequest = preferenceStore.originalAdviceRequest
super.init()
start()
}
// var fromAndToCodePicked: (String?, String?) = (nil, nil) {
// didSet {
// let from: Promise<Station?, Error> = fromAndToCodePicked.0.map {
// self.dataStore.find(stationCode: $0)
// .map { .some($0) }
// } ?? Promise(value: nil)
//
// let to: Promise<Station?, Error> = fromAndToCodePicked.1.map {
// self.dataStore.find(stationCode: $0)
// .map { .some($0) }
// } ?? Promise(value: nil)
//
// whenBoth(from, to)
// .map {
// AdviceRequest(from: $0.0, to: $0.1)
// }
// .then { [pickedAdviceRequestSource] request in
// pickedAdviceRequestSource.value = request
// }
// .trap { [weak self] error in
// self?.errorSource.post(error)
// print("fromAndToCodePicked error \(error)")
// }
// }
// }
private func start() {
heartBeatToken = heartBeat.register(type: .repeating(interval: 60)) { [weak self] _ in
self?.tick(userInteraction: false)
}
tick(userInteraction: true)
if let persisted = preferenceStore.persistedAdvicesAndRequest(for: adviceRequest.value) {
notifyOfNewAdvices(persisted)
}
bind(\.fromAndToCodePicked, to: adviceRequest)
}
private var fromAndToCodePicked: AdviceRequest! {
didSet {
let from: Promise<Station?, Error> = fromAndToCodePicked.from.map {
self.dataStore.find(uicCode: $0)
.map { .some($0) }
} ?? Promise(value: nil)
let to: Promise<Station?, Error> = fromAndToCodePicked.to.map {
self.dataStore.find(uicCode: $0)
.map { .some($0) }
} ?? Promise(value: nil)
whenBoth(from, to)
.then { [weak self] from, to in
if let persisted = self?.preferenceStore.persistedAdvicesAndRequest(for: AdviceRequest(from: from?.UICCode, to: to?.UICCode)) {
self?.notifyOfNewAdvices(persisted)
}
}
.map {
AdviceStations(from: $0.0?.name, to: $0.1?.name)
}
.then { [weak self] request in
self?.adviceStationsSource.value = request
}
.trap { [weak self] error in
self?.errorSource.post(error)
print("fromAndToCodePicked error \(error)")
}
}
}
public func attach() {
#if os(iOS)
// session.delegate = self
// session.activate()
#endif
// _ = firstAdviceRequestObservable.observeOn(scheduler).subscribe(onNext: { adviceRequest in
// guard let adviceRequest = adviceRequest else {
// return
// }
//
// if let from = adviceRequest.from {
// self.preferenceStore.setFromStationCode(code: from.code)
// }
//
// if let to = adviceRequest.to {
// self.preferenceStore.setToStationCode(code: to.code)
// }
//
// _ = self.fetchCurrentAdvices(for: adviceRequest, shouldEmitLoading: true)
// })
// _ = stationsObservable.asObservable()
// .single()
// .subscribe(onNext: { [pickedAdviceRequest, preferenceStore] _ in
//
// let adviceRequest = pickedAdviceRequest.value
// if self.firstAdviceRequestVariable.value != adviceRequest {
// self.firstAdviceRequestVariable.value = adviceRequest
// }
// if let advicesAndRequest = preferenceStore.persistedAdvicesAndRequest, advicesAndRequest.adviceRequest == adviceRequest {
// self.notifyOfNewAdvices(advicesAndRequest.advices)
// }
// })
// _ = currentAdviceOnScreenVariable.asObservable()
// .observeOn(scheduler)
// .filterOptional()
// .throttle(3, scheduler: scheduler)
// .subscribe(onNext: { advice in
//
//// self.startDepartureTimer(for: advice.vertrek.actual.timeIntervalSince(Date()))
//
// #if os(iOS)
// self.session.sendEvent(.currentAdviceChange(change: CurrentAdviceChangeData(identifier: advice.identifier(), fromCode: advice.request.from, toCode: advice.request.to)))
// self.session.transferCurrentComplicationUserInfo(["delay": advice.vertrekVertraging ?? "+ 1 min"])
// #endif
// })
//
// _ = currentAdvicesObservable.asObservable().observeOn(scheduler).subscribe(onNext: { advices in
//
// guard case .loaded(let advices) = advices else {
// return
// }
//
// let element = advices.enumerated()
// .first { $0.element.identifier() == self.preferenceStore.currentAdviceIdentifier }?
// .element ?? advices.first
//
// self.currentAdviceOnScreenVariable.value = element
// })
// self.getCurrentAdviceRequest()
// .dispatch(on: self.queue)
// .then { adviceRequest in
// if self.firstAdviceRequestVariable.value != adviceRequest {
// self.firstAdviceRequestVariable.value = adviceRequest
// }
//
// if let advicesAndRequest = self.preferenceStore.persistedAdvicesAndRequest, advicesAndRequest.adviceRequest == adviceRequest {
// self.notifyOfNewAdvices(advicesAndRequest.advices)
// }
// }
}
public func tick(userInteraction: Bool) -> Promise<Void, Error> {
fetchCurrentAdvices(shouldEmitLoading: userInteraction)
.finallyResult {
print("\(Date()) DID FINISH TICK has value \($0.value != nil)")
}
}
public func fetchStations() -> Promise<Stations, Error> {
apiService.stations(cancellationToken: nil)
.mapError { $0 as Error }
.map { $0.payload.filter { $0.land == "NL" } }
.then { [stationsSource] stations in
print("TravelService did fetch stations: \(stations.count)")
stationsSource.value = stations
}
}
private func setCurrentAdviceRequest(_ adviceRequest: AdviceRequest, byPicker: Bool) -> Promise<Void, Error> {
let previousAdviceRequest = self.adviceRequest.value
let originalAdviceRequest = self.originalAdviceRequest.value
let correctedAdviceRequest: AdviceRequest
if adviceRequest.from == adviceRequest.to, previousAdviceRequest.from == adviceRequest.from {
correctedAdviceRequest = AdviceRequest(from: previousAdviceRequest.to, to: previousAdviceRequest.from) // TODO: figure out this case
} else if adviceRequest.from == adviceRequest.to, previousAdviceRequest.to == originalAdviceRequest.from {
correctedAdviceRequest = AdviceRequest(from: originalAdviceRequest.from, to: originalAdviceRequest.to)
} else if adviceRequest.from == adviceRequest.to, previousAdviceRequest.to == adviceRequest.to {
correctedAdviceRequest = AdviceRequest(from: previousAdviceRequest.to, to: originalAdviceRequest.from ?? previousAdviceRequest.from)
} else {
correctedAdviceRequest = adviceRequest
}
if byPicker {
preferenceStore.set(originalAdviceRequest: correctedAdviceRequest)
}
preferenceStore.set(adviceRequest: correctedAdviceRequest)
return tick(userInteraction: previousAdviceRequest != adviceRequest)
}
public func setStation(_ state: PickerState, byPicker: Bool, uicCode: UicCode) -> Promise<Void, Error> {
var advice = adviceRequest.value
switch state {
case .from:
advice.from = uicCode
case .to:
advice.to = uicCode
}
return setCurrentAdviceRequest(advice, byPicker: byPicker)
}
public func fetchAdvices(for adviceRequest: AdviceRequest, cancellationToken: CancellationToken?) -> Promise<MultipleAdvices, Error> {
let first = apiService.advices(for: adviceRequest, scrollRequestForwardContext: nil, cancellationToken: cancellationToken)
.mapError { $0 as Error }
let second = first.flatMap {
self.apiService.advices(for: adviceRequest, scrollRequestForwardContext: $0.scrollRequestForwardContext, cancellationToken: cancellationToken)
.mapError { $0 as Error }
}
return whenBoth(first, second)
.map {
MultipleAdvices(responses: [$0, $1])
}
}
public func refresh() {
_ = fetchCurrentAdvices(shouldEmitLoading: false)
}
private func fetchCurrentAdvices(shouldEmitLoading: Bool) -> Promise<Void, Error> {
if shouldEmitLoading {
currentAdvicesSource.value = .loading
}
let request = adviceRequest.value
advicesCancellationToken?.cancel()
let token = CancellationTokenSource()
advicesCancellationToken = token
return fetchAdvices(for: request, cancellationToken: token.token)
.then { advicesResult in
print("TravelService fetchCurrentAdvices \(advicesResult.trips.count)")
let advicesAndRequest = AdvicesAndRequest(advices: advicesResult.trips, adviceRequest: request)
self.preferenceStore.setPersistedAdvicesAndRequest(for: request, persisted: advicesAndRequest)
self.notifyOfNewAdvices(advicesAndRequest)
}
.mapVoid()
.trap { [weak self] error in
self?.errorSource.post(error)
print(error)
}
}
fileprivate func notifyOfNewAdvices(_ advices: AdvicesAndRequest) {
let keepDepartedAdvice = preferenceStore.keepDepartedAdvice
let currentAdviceIdentifier = preferenceStore.currentAdviceIdentifier.value
let filteredAdvices = advices.advices.filter {
$0.isOngoing || (keepDepartedAdvice && $0.identifier == currentAdviceIdentifier)
}
currentAdvicesSource.value = .result(AdvicesAndRequest(advices: filteredAdvices, adviceRequest: advices.adviceRequest, lastUpdated: advices.lastUpdated))
// if let secondAdvice = advices.dropFirst().first {
// nextAdviceVariable.value = secondAdvice
// }
}
private func sortCloseLocations(_ center: CLLocation, stations: [Station]) -> [Station] {
assert(!Thread.isMainThread, "prolly no good idea to call this from main thread")
return stations.sorted { lhs, rhs in
lhs.coords.location.distance(from: center) < rhs.coords.location.distance(from: center)
}
}
public func getCloseStations() -> Promise<[Station], Error> {
locationService.currentLocation()
.flatMap { currentLocation in
let circularRegionBounds = CLCircularRegion(center: currentLocation.coordinate, radius: 0.1, identifier: "").bounds
return self.dataStore.find(inBounds: circularRegionBounds)
.dispatch(on: self.queue)
.map { stations in
self.sortCloseLocations(currentLocation, stations: stations)
}
}
}
public func travelFromCurrentLocation() -> Promise<Void, Error> {
getCloseStations()
.then { stations in
guard let station = stations.first else {
return // Promise(error: TravelServiceError.notChanged)
}
var adviceRequest = self.adviceRequest.value
adviceRequest.from = station.UICCode
self.setCurrentAdviceRequest(adviceRequest, byPicker: true)
}
.mapVoid()
}
public func switchFromTo() {
let currentAdvice = adviceRequest.value
setCurrentAdviceRequest(AdviceRequest(from: currentAdvice.to, to: currentAdvice.from), byPicker: true)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
public func setCurrentAdviceOnScreen(advice: Advice?) {
setCurrentAdviceOnScreen(adviceIdentifier: advice?.identifier)
}
public func setCurrentAdviceOnScreen(adviceIdentifier: AdviceIdentifier?) {
preferenceStore.setCurrentAdviceIdentifier(identifier: adviceIdentifier)
// preferenceStore.currentAdviceIdentifier = adviceIdentifier
//
// queue.async {
// let advice = self.preferenceStore.persistedAdvices?.first { $0.identifier() == adviceIdentifier }
// self.currentAdviceOnScreenVariable.value = advice
// }
}
func setMostUsedStations(stations: [Station]) {
mostUsedStationsSource.value = stations
}
public func find(stationNameContains: String) -> Promise<[Station], Error> {
dataStore.find(stationNameContains: stationNameContains)
}
public func find(stationCode: StationCode) -> Promise<Station, Error> {
dataStore.find(stationCode: stationCode)
}
}
// #if os(iOS)
//
// extension TravelService: WCSessionDelegate {
// public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
// /* stub */
// }
//
// public func sessionDidBecomeInactive(_ session: WCSession) {
// /* stub */
// }
//
// public func sessionDidDeactivate(_ session: WCSession) {
// /* stub */
// }
//
// public func session(_ session: WCSession, didReceiveMessageData messageData: Data) {
// print(String(data: messageData, encoding: .utf8))
// }
//
// public func session(_ session: WCSession, didReceiveMessageData messageData: Data, replyHandler: @escaping (Data) -> Void) {
// guard let advice = currentAdviceOnScreenVariable.value else {
// return
// }
//
// let event = TravelEvent.currentAdviceChange(change: CurrentAdviceChangeData(identifier: advice.identifier(), fromCode: advice.request.from, toCode: advice.request.to))
//
// guard let data = try? JSONEncoder().encode(event) else {
// return
// }
//
// replyHandler(data)
// }
//
//
// public func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
// print("didReceiveApplicationContext: \(applicationContext)")
// }
// }
// #endif
@propertyWrapper
public struct Injected<Service: Injectable> {
public var wrappedValue: Service {
Service.create()
}
public init() {}
}
public protocol Injectable {
static func create() -> Self
}
| mit | 10f7b593e23c8c2c59bfb69ed6fdf60c | 33.830228 | 180 | 0.691256 | 3.911416 | false | false | false | false |
divljiboy/IOSChatApp | Quick-Chat/MagicChat/Repository/ConversationRemoteRepository.swift | 1 | 2016 | //
// ConversationRemoteRepository.swift
// MagicChat
//
// Created by Ivan Divljak on 6/22/18.
// Copyright © 2018 Mexonis. All rights reserved.
//
import Foundation
import Firebase
class ConversationRemoteRepository: ConversationRepositoryProtocol {
var messageRepository: MessageRepositoryProtocol!
var userRepository: UserRepositoryProtocol!
init(messageRepository: MessageRepositoryProtocol, userRepository: UserRepositoryProtocol) {
self.messageRepository = messageRepository
self.userRepository = userRepository
}
func showConversations(completion: @escaping ([Conversation]) -> Void) {
if let currentUserID = Auth.auth().currentUser?.uid {
var conversations = [Conversation]()
Database.database().reference().child("users")
.child(currentUserID).child("conversations").observe(.childAdded, with: { snapshot in
if snapshot.exists() {
let fromID = snapshot.key
guard let values = snapshot.value as? [String: String],
let location = values["location"] else {
return
}
self.userRepository.info(forUserID: fromID, completion: { user in
let emptyMessage = Message.init(type: .text, content: "loading", owner: .sender, timestamp: 0, isRead: true)
let conversation = Conversation.init(user: user, lastMessage: emptyMessage)
conversations.append(conversation)
self.messageRepository.downloadLastMessage(forLocation: location, completion: { message in
conversation.lastMessage = message
completion(conversations)
})
})
}
})
}
}
}
| mit | 6ea9060b85792d2c620f5bc195788d58 | 40.979167 | 136 | 0.559801 | 5.857558 | false | false | false | false |
rhx/SwiftGtk | Sources/Gtk/ListStore.swift | 1 | 3943 | //
// ListStore.swift
// Gtk
//
// Created by Rene Hexel on 22/4/17.
// Copyright © 2017, 2018, 2019, 2020 Rene Hexel. All rights reserved.
//
import GLibObject
import CGtk
public extension ListStore {
/// Return a tree model reference for the list store
@inlinable var treeModel: TreeModelRef { return TreeModelRef(cPointer: list_store_ptr) }
/// Convenience constructor specifying the column types
///
/// - Parameter types: array of column types for this list model
@inlinable convenience init(types: [GType]) {
var ts = types
self.init(nColumns: types.count, types: &ts)
}
/// Convenience constructor specifying the list column types
///
/// - Parameter types: column types for this list model
@inlinable convenience init(_ types: GType...) {
var ts = types
self.init(nColumns: types.count, types: &ts)
}
/// Set the given values for the current row
///
/// - Parameters:
/// - i: iterator representing the current row
/// - values: array of values to add
/// - startColumn: column to start from (defaults to `0`)
@inlinable func set<I: TreeIterProtocol, V: ValueProtocol>(iter i: I, values: [V], startColumn: Int = 0) {
list_store_ptr.withMemoryRebound(to: GtkListStore.self, capacity: 1) {
var c = gint(startColumn)
for v in values {
gtk_list_store_set_value($0, i.tree_iter_ptr, c, v.value_ptr)
c += 1
}
}
}
/// Append the given values to the next row
///
/// - Parameters:
/// - i: iterator representing the current row (updated to next row)
/// - v: array of values to add
/// - startColumn: column to start from (defaults to `0`)
@inlinable func append<I: TreeIterProtocol, V: ValueProtocol>(asNextRow i: I, values v: [V], startColumn s: Int = 0) {
list_store_ptr.withMemoryRebound(to: GtkListStore.self, capacity: 1) {
gtk_list_store_append($0, i.tree_iter_ptr)
}
set(iter: i, values: v, startColumn: s)
}
/// Append the given values to the next row
///
/// - Parameters:
/// - i: tree iterator representing the current row (updated to next row)
/// - values: array of values to add
/// - startColumn: column to start from (defaults to `0`)
@inlinable func append<I: TreeIterProtocol>(asNextRow i: I, startColumn s: Int = 0, _ values: Value...) {
list_store_ptr.withMemoryRebound(to: GtkListStore.self, capacity: 1) {
gtk_list_store_append($0, i.tree_iter_ptr)
}
set(iter: i, values: values, startColumn: s)
}
}
/// TreeView subclass for displaying lists that retain their model
open class ListView: TreeView {
/// The underlying list store
public var listStore: ListStore
/// Convenience List View constructor
///
/// - Parameter store: list view store description
@inlinable public init(model store: ListStore) {
listStore = store
super.init(model: store.treeModel)
}
/// Unsafe untyped initialiser.
/// **Do not use unless you know the underlying data type the pointer points to conforms to `StringProtocol`.**
/// - Parameter p: raw pointer to the underlying object
@inlinable required public init(raw p: UnsafeMutableRawPointer) {
var gtype = GType.string
listStore = ListStore(nColumns: 0, types: >ype)
super.init(raw: p)
}
/// Unsafe untyped initialiser.
/// **Do not use unless you know the underlying data type the pointer points to conforms to `StringProtocol`.**
/// - Parameter p: raw pointer to the underlying object to be retained
@inlinable required public init(retainingRaw raw: UnsafeMutableRawPointer) {
var gtype = GType.string
listStore = ListStore(nColumns: 0, types: >ype)
super.init(retainingRaw: raw)
}
}
| bsd-2-clause | 9c8e85f34fc3406fd66cfef170f24246 | 36.542857 | 122 | 0.632927 | 3.997972 | false | false | false | false |
davetrux/1DevDayDetroit-2014 | ios/Hello1DevDay/Hello1DevDay/ViewController.swift | 1 | 873 | //
// ViewController.swift
// Hello1DevDay
//
// Created by David Truxall on 10/24/14.
// Copyright (c) 2014 Hewlett-Packard Company. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var yoLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didTouchButton(sender: UIButton) {
var speakerText = "Hello speaker"
var audienceText = "Hello audience"
if(yoLabel.text != speakerText){
yoLabel.text = speakerText
} else {
yoLabel.text = audienceText
}
}
}
| mit | d33dca44470101016d48bc6aca75ec21 | 22.594595 | 80 | 0.631157 | 4.454082 | false | false | false | false |
tkremenek/swift | benchmark/single-source/Diffing.swift | 18 | 3142 | //===--- Diffing.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
//
//===----------------------------------------------------------------------===//
import TestsUtils
let t: [BenchmarkCategory] = [.api]
public let Diffing = [
BenchmarkInfo(
name: "Diffing.Same",
runFunction: { diff($0, from: longPangram, to: longPangram) },
tags: t,
setUpFunction: { blackHole(longPangram) }),
BenchmarkInfo(
name: "Diffing.PangramToAlphabet",
runFunction: { diff($0, from: longPangram, to: alphabets) },
tags: t,
setUpFunction: { blackHole((longPangram, alphabets)) }),
BenchmarkInfo(
name: "Diffing.Pangrams",
runFunction: { diff($0, from:typingPangram, to: longPangram) },
tags: t,
setUpFunction: { blackHole((longPangram, typingPangram)) }),
BenchmarkInfo(
name: "Diffing.ReversedAlphabets",
runFunction: { diff($0, from:alphabets, to: alphabetsReversed) },
tags: t,
setUpFunction: { blackHole((alphabets, alphabetsReversed)) }),
BenchmarkInfo(
name: "Diffing.ReversedLorem",
runFunction: { diff($0, from: loremIpsum, to: loremReversed) },
tags: t,
setUpFunction: { blackHole((loremIpsum, loremReversed)) }),
BenchmarkInfo(
name: "Diffing.Disparate",
runFunction: { diff($0, from: numbersAndSymbols, to: alphabets) },
tags: t,
setUpFunction: { blackHole((numbersAndSymbols, alphabets)) }),
BenchmarkInfo(
name: "Diffing.Similar",
runFunction: { diff($0, from: unabridgedLorem, to: loremIpsum) },
tags: t,
setUpFunction: { blackHole((unabridgedLorem, loremIpsum)) }),
]
let numbersAndSymbols = Array("0123456789`~!@#$%^&*()+=_-\"'?/<,>.\\{}'")
let alphabets = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
let alphabetsReversed = Array(alphabets.reversed())
let longPangram = Array("This pangram contains four As, one B, two Cs, one D, thirty Es, six Fs, five Gs, seven Hs, eleven Is, one J, one K, two Ls, two Ms, eighteen Ns, fifteen Os, two Ps, one Q, five Rs, twenty-seven Ss, eighteen Ts, two Us, seven Vs, eight Ws, two Xs, three Ys, & one Z")
let typingPangram = Array("The quick brown fox jumps over the lazy dog")
let loremIpsum = Array("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")
let unabridgedLorem = Array("Lorem ipsum, quia dolor sit amet consectetur adipisci[ng] velit, sed quia non-numquam [do] eius modi tempora inci[di]dunt, ut labore et dolore magnam aliqua.")
let loremReversed = Array(loremIpsum.reversed())
@inline(never) func diff(_ N: Int, from older: [Character], to newer: [Character]) {
if #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) {
for _ in 1...N {
blackHole(newer.difference(from: older))
}
}
}
| apache-2.0 | ed192e6b6a3da38c9a7e22a915d41110 | 44.536232 | 291 | 0.663908 | 3.808485 | false | false | false | false |
phanthanhhai/DayseeNetwork | DayseeNetwork/Network/DayseeUploadLocation.swift | 1 | 4615 | //
// DayseeUploadLocation.swift
// Shopping
//
// Created by haipt on 9/15/15.
// Copyright (c) 2015 NextFetch. All rights reserved.
//
import Foundation
import AFNetworking
let BFLocationEnter = "enter_area"
let BFLocationExit = "exit_area"
public class DayseeUploadLocation {
private var requestManager : AFHTTPRequestOperationManager!
private var url : String!
private var ideaId : Int!
private var failHandle : RequestFailHandler!
private var params = [String : AnyObject]()
private var allowInvalidCert: Bool = true
public init(ideaId: Int, triggerId: Int, url: String, allowInvalidCert: Bool) {
self.requestManager = AFHTTPRequestOperationManager()
self.allowInvalidCert = allowInvalidCert
self.requestManager.requestSerializer.timeoutInterval = BFApi_Timeout * 3
self.url = url
var typeStr: String = ""
if triggerId == TriggerIdIOS.LocationEnter.rawValue {
typeStr = BFLocationEnter
} else if triggerId == TriggerIdIOS.LocationExit.rawValue {
typeStr = BFLocationExit
}
self.params["type"] = typeStr
self.params["ids[0]"] = ideaId
self.params["detected_at"] = NSDate()
self.params["_method"] = "PUT"
}
func addHeader(){
self.requestManager.requestSerializer.setValue("form-data", forHTTPHeaderField: "Content-Type")
if let accessToken = DayseeHelper.sharedInstance.getAccessToken() {
self.requestManager.requestSerializer.setValue(accessToken, forHTTPHeaderField: BFTokenHeaderKey)
}
self.requestManager.requestSerializer.setValue("v" + BFAppVersion, forHTTPHeaderField: BFVersionHeaderKey)
self.requestManager.requestSerializer.setValue(BFDeviceName, forHTTPHeaderField: BFDeviceHeaderKey)
}
/*Call to start network request */
public func startService (
success: (AnyObject?) -> Void,
failure: RequestFailHandler) -> Void
{
if self.allowInvalidCert {
DayseeHelper.sharedInstance.allowInvalidCertificates(self.requestManager)
}
if self.failHandle == nil {
self.failHandle = failure
}
if !ReachabilityHelper.sharedInstance.isNetworkConntected() {
let alertController = UIAlertController(title: "", message: BFApiMsgNetworkErrorWithRetry, preferredStyle: .Alert)
let retryHandler = { (action:UIAlertAction!) -> Void in
self.startService({ (response1) -> Void in
success(response1)
}, failure: { (error1) -> Void in
failure(error1)
})
}
let cancelHandler = { (action:UIAlertAction!) -> Void in
failure(nil)
}
let cancelAction = UIAlertAction(title: BFApiBtn_Cancel, style: .Default, handler: cancelHandler)
let retryAction = UIAlertAction(title: BFApiBtnRetry, style: .Default, handler: retryHandler)
alertController.addAction(cancelAction)
alertController.addAction(retryAction)
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
return
}
//log here
print("start put with url \(url)")
print("parameter \(self.params))")
//add header
self.addHeader()
let request : NSMutableURLRequest = self.requestManager.requestSerializer.multipartFormRequestWithMethod("POST", URLString: url, parameters: self.params , constructingBodyWithBlock: { (formData :AFMultipartFormData!) -> Void in
formData.appendPartWithFileData(NSData(), name: "", fileName: "" , mimeType: "image/jpeg")
}, error: nil)
let requestOperation : AFHTTPRequestOperation = self.requestManager.HTTPRequestOperationWithRequest(request,
success: { (operation :AFHTTPRequestOperation!, response :AnyObject!) -> Void in
print("response \(response))")
success(response)
}) { (operation, error) -> Void in
self.failHandle(error)
}
requestOperation.start()
}
}
| mit | 9999b38e56a7dde51ff65c9361e7f2b2 | 42.952381 | 235 | 0.598267 | 5.435807 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | source/RSTBSupport/Classes/RSFullScreenImageStepGenerator.swift | 1 | 1223 | //
// RSFullScreenImageStepGenerator.swift
// ResearchSuiteExtensions
//
// Created by James Kizer on 2/6/19.
//
import UIKit
import ResearchKit
import ResearchSuiteTaskBuilder
import Gloss
import SwiftyMarkdown
import Mustache
import SwiftyGif
open class RSFullScreenImageStepGenerator: RSTBBaseStepGenerator {
public init(){}
open var supportedTypes: [String]! {
return ["fullScreenImage"]
}
open func generateStep(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> ORKStep? {
guard let stepDescriptor = RSFullScreenImageStepDescriptor(json:jsonObject),
let image = UIImage(named: stepDescriptor.imageTitle) else {
return nil
}
let step = RSFullScreenImageStep(identifier: stepDescriptor.identifier)
step.image = image
step.buttonText = stepDescriptor.buttonText
return step
}
open func processStepResult(type: String,
jsonObject: JsonObject,
result: ORKStepResult,
helper: RSTBTaskBuilderHelper) -> JSON? {
return nil
}
}
| apache-2.0 | 364f469c5ab1552ba1463fd50f0e72db | 25.021277 | 103 | 0.620605 | 5.364035 | false | false | false | false |
zom/Zom-iOS | Zom/Zom/Classes/View Controllers/ZomVerificationDetailViewController.swift | 1 | 4662 | //
// ZomVerificationDetailViewController.swift
// Zom
//
// Created by Benjamin Erhart on 06.03.18.
//
/**
Scene for verification of all fingerprints of a buddy.
Use the `convenience init(buddy: OTRBuddy)` or set `self.buddy` immediately after init!
Better, yet, if you already loaded keys/fingerprints, use the
`convenience init(buddy: OTRBuddy?, omemoDevices: [OMEMODevice]?, otrFingerprints: [OTRFingerprint]?)`.
*/
class ZomVerificationDetailViewController: ZomFingerprintBaseViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var subtitleLb: UILabel!
@IBOutlet weak var descriptionLb: UILabel!
@IBOutlet weak var fingerprintTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
if let titleView = navigationItem.titleView as? OTRTitleSubtitleView {
titleView.titleLabel.text = NSLocalizedString("Zom Codes", comment:
"Title for code verification detail scene")
}
descriptionLb.text = NSLocalizedString("Make sure the codes match your friend's latest Zom codes on his or her phone.",
comment: "Description for code verification detail scene")
fingerprintTable.register(UINib(nibName: "ZomFingerprintVerificationCell", bundle: nil),
forCellReuseIdentifier: "FingerprintCell")
fingerprintTable.register(UINib(nibName: "ZomFingerprintVerificationHeader", bundle: nil),
forCellReuseIdentifier: "FingerprintHeader")
fingerprintTable.tableFooterView = UIView(frame: .zero)
}
/**
Callback, when all OMEMO devices and all OTR fingerprints of our buddy are loaded.
Update the number of untrusted new fingerprints text and reload the table to show all
fingerprints.
*/
override func fingerprintsLoaded() {
updateUntrustedNewFingerprintsInfo()
fingerprintTable.reloadData()
}
// MARK: ZomFingerprintVerificationCell
/**
Callback for `ZomFingerprintVerificationCell`, when a user changed the trust of a fingerprint.
*/
func trustChanged() {
updateUntrustedNewFingerprintsInfo()
}
// MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
var count = 0
if omemoDevices.count > 0 {
count += 1
}
if otrFingerprints.count > 0 {
count += 1
}
return count
}
/**
Show two sections, one for OMEMO and one for OTR.
*/
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 && omemoDevices.count > 0 ? omemoDevices.count : otrFingerprints.count
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableCell(withIdentifier: "FingerprintHeader") as! ZomFingerprintVerificationHeader
header.label.text = section == 0 && omemoDevices.count > 0 ? "OMEMO" : "OTR"
return header
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FingerprintCell", for: indexPath)
as! ZomFingerprintVerificationCell
cell.delegate = self
if indexPath.section == 0 && omemoDevices.count > 0 {
cell.set(omemoDevices[indexPath.row])
}
else {
cell.set(otrFingerprints[indexPath.row])
}
return cell
}
// MARK: Private methods
/**
Calculcate the number of `.untrustedNew` `OMEMODevice`s and `OTRFingerprint`s and show that
information in the `subtitleLb` label.
*/
private func updateUntrustedNewFingerprintsInfo() {
let keys = countKeys()
ZomFingerprintBaseViewController.setBadge(badgeLb, ok: keys.trusted > 0 && keys.untrustedNew < 1)
if keys.trusted > 0 || keys.untrustedNew > 0 {
subtitleLb.text = NSLocalizedString("\(keys.untrustedNew) Untrusted New Codes for \(buddyName())",
comment: "Subtitle for code verification detail scene")
descriptionLb.isHidden = false
}
else {
subtitleLb.text = NSLocalizedString("No Zom Codes for \(buddyName())",
comment: "Subtitle for code verification detail scene")
descriptionLb.isHidden = true
}
}
}
| mpl-2.0 | e989e1ac59a37f1f7af6205753f82d22 | 33.029197 | 127 | 0.657443 | 4.991435 | false | false | false | false |
openHPI/xikolo-ios | iOS/Helpers/PersistenceManager/DocumentsPersistenceManager.swift | 1 | 1818 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import Common
import CoreData
final class DocumentsPersistenceManager: FilePersistenceManager<DocumentsPersistenceManager.Configuration> {
enum Configuration: PersistenceManagerConfiguration {
// swiftlint:disable nesting
typealias Resource = DocumentLocalization
typealias Session = URLSession
// swiftlint:enable nesting
static let keyPath = \DocumentLocalization.localFileBookmark
static let downloadType = "documents"
static let titleForFailedDownloadAlert = NSLocalizedString("alert.download-error.documents.title",
comment: "title of alert for stream download errors")
static func newFetchRequest() -> NSFetchRequest<DocumentLocalization> {
return DocumentLocalization.fetchRequest()
}
}
static let shared = DocumentsPersistenceManager()
override func newDownloadSession() -> URLSession {
return self.createURLSession(withIdentifier: "documents-download")
}
func startDownload(for documentLocalization: DocumentLocalization) {
guard let url = documentLocalization.fileURL else { return }
self.startDownload(with: url, for: documentLocalization)
}
}
extension DocumentsPersistenceManager {
func deleteDownloads(for document: Document) {
self.persistentContainerQueue.addOperation {
document.localizations.filter { documentLocalization -> Bool in
return self.downloadState(for: documentLocalization) == .downloaded
}.forEach { documentLocalization in
self.deleteDownload(for: documentLocalization)
}
}
}
}
| gpl-3.0 | 22db75d25aabf0ae5836d54cbb30a67f | 32.648148 | 120 | 0.682444 | 5.75 | false | true | false | false |
Yeatse/KingfisherWebP | Sources/WebPSerializer.swift | 1 | 1185 | //
// WebPSerializer.swift
// Pods
//
// Created by yeatse on 2016/10/20.
//
//
import CoreGraphics
import Foundation
import Kingfisher
public struct WebPSerializer: CacheSerializer {
public static let `default` = WebPSerializer()
/// Whether the image should be serialized in a lossy format. Default is false.
public var isLossy: Bool = false
/// The compression quality when converting image to a lossy format data. Default is 1.0.
public var compressionQuality: CGFloat = 1.0
private init() {}
public func data(with image: KFCrossPlatformImage, original: Data?) -> Data? {
if let original = original, !original.isWebPFormat {
return DefaultCacheSerializer.default.data(with: image, original: original)
} else {
let qualityInWebp = min(max(0, compressionQuality), 1) * 100
return image.kf.normalized.kf.webpRepresentation(isLossy: isLossy, quality: Float(qualityInWebp))
}
}
public func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
return WebPProcessor.default.process(item: .data(data), options: options)
}
}
| mit | 691ce07389e51107b1f21e7f9f6e7b5c | 31.916667 | 109 | 0.685232 | 4.309091 | false | false | false | false |
schrockblock/subway-stations | SubwayStations/Classes/Prediction.swift | 1 | 744 | //
// Prediction.swift
// Pods
//
// Created by Elliot Schrock on 6/28/16.
//
//
import UIKit
public enum Direction: Int {
case uptown = 0
case downtown = 1
}
open class Prediction {
open var secondsToArrival: Int? {
if let arrival = timeOfArrival {
return Int(arrival.timeIntervalSinceNow)
}else{
return nil
}
}
open var timeOfArrival: Date?
open var direction: Direction?
open var route: Route?
public init(time: Date?) {
timeOfArrival = time
}
}
public func ==(lhs: Prediction, rhs: Prediction) -> Bool {
return lhs.route?.objectId == rhs.route?.objectId && lhs.timeOfArrival == rhs.timeOfArrival && lhs.direction == rhs.direction
}
| mit | b8092992319c6d65dadbf5ca766e9e55 | 20.257143 | 129 | 0.616935 | 3.815385 | false | false | false | false |
lokinfey/MyPerfectframework | PerfectLib/NetTCP.swift | 1 | 19536 | //
// NetTCP.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/5/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
#if os(Linux)
import SwiftGlibc
let AF_UNSPEC: Int32 = 0
let AF_INET: Int32 = 2
let INADDR_NONE = UInt32(0xffffffff)
let EINPROGRESS = Int32(115)
#else
import Darwin
#endif
/// Provides an asynchronous IO wrapper around a file descriptor.
/// Fully realized for TCP socket types but can also serve as a base for sockets from other families, such as with `NetNamedPipe`/AF_UNIX.
public class NetTCP : Closeable {
private var networkFailure: Bool = false
private var semaphore: Threading.Event?
private var waitAcceptEvent: LibEvent?
class ReferenceBuffer {
var b: UnsafeMutablePointer<UInt8>
let size: Int
init(size: Int) {
self.size = size
self.b = UnsafeMutablePointer<UInt8>.alloc(size)
}
deinit {
self.b.destroy()
self.b.dealloc(self.size)
}
}
var fd: SocketFileDescriptor = SocketFileDescriptor(fd: invalidSocket, family: AF_UNSPEC)
/// Create a new object with an initially invalid socket file descriptor.
public init() {
}
/// Creates an instance which will use the given file descriptor
/// - parameter fd: The pre-existing file descriptor
public convenience init(fd: Int32) {
self.init()
self.fd.fd = fd
self.fd.family = AF_INET
self.fd.switchToNBIO()
}
/// Allocates a new socket if it has not already been done.
/// The functions `bind` and `connect` will call this method to ensure the socket has been allocated.
/// Sub-classes should override this function in order to create their specialized socket.
/// All sub-class sockets should be switched to utilize non-blocking IO by calling `SocketFileDescriptor.switchToNBIO()`.
public func initSocket() {
if fd.fd == invalidSocket {
#if os(Linux)
fd.fd = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0)
#else
fd.fd = socket(AF_INET, SOCK_STREAM, 0)
#endif
fd.family = AF_INET
fd.switchToNBIO()
}
}
public func sockName() -> (String, UInt16) {
let staticBufferSize = 1024
var addr = UnsafeMutablePointer<sockaddr_in>.alloc(1)
let len = UnsafeMutablePointer<socklen_t>.alloc(1)
let buffer = UnsafeMutablePointer<Int8>.alloc(staticBufferSize)
defer {
addr.dealloc(1)
len.dealloc(1)
buffer.dealloc(staticBufferSize)
}
len.memory = socklen_t(sizeof(sockaddr_in))
getsockname(fd.fd, UnsafeMutablePointer<sockaddr>(addr), len)
inet_ntop(fd.family, &addr.memory.sin_addr, buffer, len.memory)
let s = String.fromCString(buffer) ?? ""
let p = ntohs(addr.memory.sin_port)
return (s, p)
}
public func peerName() -> (String, UInt16) {
let staticBufferSize = 1024
var addr = UnsafeMutablePointer<sockaddr_in>.alloc(1)
let len = UnsafeMutablePointer<socklen_t>.alloc(1)
let buffer = UnsafeMutablePointer<Int8>.alloc(staticBufferSize)
defer {
addr.dealloc(1)
len.dealloc(1)
buffer.dealloc(staticBufferSize)
}
len.memory = socklen_t(sizeof(sockaddr_in))
getpeername(fd.fd, UnsafeMutablePointer<sockaddr>(addr), len)
inet_ntop(fd.family, &addr.memory.sin_addr, buffer, len.memory)
let s = String.fromCString(buffer) ?? ""
let p = ntohs(addr.memory.sin_port)
return (s, p)
}
func isEAgain(err: Int) -> Bool {
return err == -1 && errno == EAGAIN
}
func evWhatFor(operation: Int32) -> Int32 {
return operation
}
/// Bind the socket on the given port and optional local address
/// - parameter port: The port on which to bind
/// - parameter address: The the local address, given as a string, on which to bind. Defaults to "0.0.0.0".
/// - throws: PerfectError.NetworkError
public func bind(port: UInt16, address: String = "0.0.0.0") throws {
initSocket()
var addr: sockaddr_in = sockaddr_in()
let res = makeAddress(&addr, host: address, port: port)
guard res != -1 else {
try ThrowNetworkError()
}
let i0 = Int8(0)
#if os(Linux)
var sock_addr = sockaddr(sa_family: 0, sa_data: (i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0))
#else
var sock_addr = sockaddr(sa_len: 0, sa_family: 0, sa_data: (i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0))
#endif
memcpy(&sock_addr, &addr, Int(sizeof(sockaddr_in)))
#if os(Linux)
let bRes = SwiftGlibc.bind(fd.fd, &sock_addr, socklen_t(sizeof(sockaddr_in)))
#else
let bRes = Darwin.bind(fd.fd, &sock_addr, socklen_t(sizeof(sockaddr_in)))
#endif
if bRes == -1 {
try ThrowNetworkError()
}
}
/// Switches the socket to server mode. Socket should have been previously bound using the `bind` function.
public func listen(backlog: Int32 = 128) {
#if os(Linux)
SwiftGlibc.listen(fd.fd, backlog)
#else
Darwin.listen(fd.fd, backlog)
#endif
}
/// Shuts down and closes the socket.
/// The object may be reused.
public func close() {
if fd.fd != invalidSocket {
#if os(Linux)
shutdown(fd.fd, 2) // !FIX!
SwiftGlibc.close(fd.fd)
#else
shutdown(fd.fd, SHUT_RDWR)
Darwin.close(fd.fd)
#endif
fd.fd = invalidSocket
if let event = self.waitAcceptEvent {
event.del()
self.waitAcceptEvent = nil
}
if self.semaphore != nil {
self.semaphore!.lock()
self.semaphore!.signal()
self.semaphore!.unlock()
}
}
}
func recv(buf: UnsafeMutablePointer<Void>, count: Int) -> Int {
#if os(Linux)
return SwiftGlibc.recv(self.fd.fd, buf, count, 0)
#else
return Darwin.recv(self.fd.fd, buf, count, 0)
#endif
}
func send(buf: UnsafePointer<Void>, count: Int) -> Int {
#if os(Linux)
return SwiftGlibc.send(self.fd.fd, buf, count, 0)
#else
return Darwin.send(self.fd.fd, buf, count, 0)
#endif
}
private func makeAddress(inout sin: sockaddr_in, host: String, port: UInt16) -> Int {
let theHost: UnsafeMutablePointer<hostent> = gethostbyname(host)
if theHost == nil {
if inet_addr(host) == INADDR_NONE {
endhostent()
return -1
}
}
let bPort = port.bigEndian
sin.sin_port = in_port_t(bPort)
sin.sin_family = sa_family_t(AF_INET)
if theHost != nil {
sin.sin_addr.s_addr = UnsafeMutablePointer<UInt32>(theHost.memory.h_addr_list.memory).memory
} else {
sin.sin_addr.s_addr = inet_addr(host)
}
endhostent()
return 0
}
private func completeArray(from: ReferenceBuffer, count: Int) -> [UInt8] {
var ary = [UInt8](count: count, repeatedValue: 0)
for index in 0..<count {
ary[index] = from.b[index]
}
return ary
}
func readBytesFully(into: ReferenceBuffer, read: Int, remaining: Int, timeoutSeconds: Double, completion: ([UInt8]?) -> ()) {
let readCount = recv(into.b + read, count: remaining)
if readCount == 0 {
completion(nil) // disconnect
} else if self.isEAgain(readCount) {
// no data available. wait
self.readBytesFullyIncomplete(into, read: read, remaining: remaining, timeoutSeconds: timeoutSeconds, completion: completion)
} else if readCount < 0 {
completion(nil) // networking or other error
} else {
// got some data
if remaining - readCount == 0 { // done
completion(completeArray(into, count: read + readCount))
} else { // try again for more
readBytesFully(into, read: read + readCount, remaining: remaining - readCount, timeoutSeconds: timeoutSeconds, completion: completion)
}
}
}
func readBytesFullyIncomplete(into: ReferenceBuffer, read: Int, remaining: Int, timeoutSeconds: Double, completion: ([UInt8]?) -> ()) {
let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: fd.fd, what: EV_READ, userData: nil) {
(fd:Int32, w:Int16, ud:AnyObject?) -> () in
if (Int32(w) & EV_TIMEOUT) == 0 {
self.readBytesFully(into, read: read, remaining: remaining, timeoutSeconds: timeoutSeconds, completion: completion)
} else {
completion(nil) // timeout or error
}
}
event.add(timeoutSeconds)
}
/// Read the indicated number of bytes and deliver them on the provided callback.
/// - parameter count: The number of bytes to read
/// - parameter timeoutSeconds: The number of seconds to wait for the requested number of bytes. A timeout value of negative one indicates that the request should have no timeout.
/// - parameter completion: The callback on which the results will be delivered. If the timeout occurs before the requested number of bytes have been read, a nil object will be delivered to the callback.
public func readBytesFully(count: Int, timeoutSeconds: Double, completion: ([UInt8]?) -> ()) {
let ptr = ReferenceBuffer(size: count)
readBytesFully(ptr, read: 0, remaining: count, timeoutSeconds: timeoutSeconds, completion: completion)
}
/// Read up to the indicated number of bytes and deliver them on the provided callback.
/// - parameter count: The maximum number of bytes to read.
/// - parameter completion: The callback on which to deliver the results. If an error occurs during the read then a nil object will be passed to the callback, otherwise, the immediately available number of bytes, which may be zero, will be passed.
public func readSomeBytes(count: Int, completion: ([UInt8]?) -> ()) {
let ptr = ReferenceBuffer(size: count)
let readCount = recv(ptr.b, count: count)
if readCount == 0 {
completion(nil)
} else if self.isEAgain(readCount) {
completion([UInt8]())
} else if readCount == -1 {
completion(nil)
} else {
completion(completeArray(ptr, count: readCount))
}
}
/// Write the string and call the callback with the number of bytes which were written.
/// - parameter s: The string to write. The string will be written based on its UTF-8 encoding.
/// - parameter completion: The callback which will be called once the write has completed. The callback will be passed the number of bytes which were successfuly written, which may be zero.
public func write(s: String, completion: (Int) -> ()) {
writeBytes([UInt8](s.utf8), completion: completion)
}
/// Write the indicated bytes and call the callback with the number of bytes which were written.
/// - parameter bytes: The array of UInt8 to write.
/// - parameter completion: The callback which will be called once the write has completed. The callback will be passed the number of bytes which were successfuly written, which may be zero.
public func write(bytes: [UInt8], completion: (Int) -> ()) {
writeBytes(bytes, dataPosition: 0, length: bytes.count, completion: completion)
}
/// Write the string and call the callback with the number of bytes which were written.
/// - parameter s: The string to write. The string will be written based on its UTF-8 encoding.
/// - parameter completion: The callback which will be called once the write has completed. The callback will be passed the number of bytes which were successfuly written, which may be zero.
public func writeString(s: String, completion: (Int) -> ()) {
writeBytes([UInt8](s.utf8), completion: completion)
}
/// Write the indicated bytes and call the callback with the number of bytes which were written.
/// - parameter bytes: The array of UInt8 to write.
/// - parameter completion: The callback which will be called once the write has completed. The callback will be passed the number of bytes which were successfuly written, which may be zero.
public func writeBytes(bytes: [UInt8], completion: (Int) -> ()) {
writeBytes(bytes, dataPosition: 0, length: bytes.count, completion: completion)
}
/// Write the indicated bytes and return true if all data was sent.
/// - parameter bytes: The array of UInt8 to write.
public func writeBytesFully(bytes: [UInt8]) -> Bool {
let length = bytes.count
var totalSent = 0
let ptr = UnsafeMutablePointer<UInt8>(bytes)
var s: Threading.Event?
var what: Int32 = 0
let waitFunc = {
let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: self.fd.fd, what: EV_WRITE, userData: nil) {
(fd:Int32, w:Int16, ud:AnyObject?) -> () in
what = Int32(w)
s!.lock()
s!.signal()
s!.unlock()
}
event.add()
}
while length > 0 {
let sent = send(ptr.advancedBy(totalSent), count: length - totalSent)
if sent == length {
return true
}
if s == nil {
s = Threading.Event()
}
if sent == -1 {
if isEAgain(sent) { // flow
s!.lock()
waitFunc()
} else { // error
break
}
} else {
totalSent += sent
if totalSent == length {
return true
}
s!.lock()
waitFunc()
}
s!.wait()
s!.unlock()
if what != EV_WRITE {
break
}
}
return totalSent == length
}
/// Write the indicated bytes and call the callback with the number of bytes which were written.
/// - parameter bytes: The array of UInt8 to write.
/// - parameter dataPosition: The offset within `bytes` at which to begin writing.
/// - parameter length: The number of bytes to write.
/// - parameter completion: The callback which will be called once the write has completed. The callback will be passed the number of bytes which were successfuly written, which may be zero.
public func writeBytes(bytes: [UInt8], dataPosition: Int, length: Int, completion: (Int) -> ()) {
let ptr = UnsafeMutablePointer<UInt8>(bytes).advancedBy(dataPosition)
writeBytes(ptr, wrote: 0, length: length, completion: completion)
}
func writeBytes(ptr: UnsafeMutablePointer<UInt8>, wrote: Int, length: Int, completion: (Int) -> ()) {
let sent = send(ptr, count: length)
if isEAgain(sent) {
writeBytesIncomplete(ptr, wrote: wrote, length: length, completion: completion)
} else if sent == -1 {
completion(sent)
} else if sent < length {
// flow control
writeBytesIncomplete(ptr.advancedBy(sent), wrote: wrote + sent, length: length - sent, completion: completion)
} else {
completion(wrote + sent)
}
}
func writeBytesIncomplete(nptr: UnsafeMutablePointer<UInt8>, wrote: Int, length: Int, completion: (Int) -> ()) {
let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: fd.fd, what: EV_WRITE, userData: nil) {
(fd:Int32, w:Int16, ud:AnyObject?) -> () in
self.writeBytes(nptr, wrote: wrote, length: length, completion: completion)
}
event.add()
}
/// Connect to the indicated server
/// - parameter address: The server's address, expressed as a string.
/// - parameter port: The port on which to connect.
/// - parameter timeoutSeconds: The number of seconds to wait for the connection to complete. A timeout of negative one indicates that there is no timeout.
/// - parameter callBack: The closure which will be called when the connection completes. If the connection completes successfully then the current NetTCP instance will be passed to the callback, otherwise, a nil object will be passed.
/// - returns: `PerfectError.NetworkError`
public func connect(address: String, port: UInt16, timeoutSeconds: Double, callBack: (NetTCP?) -> ()) throws {
initSocket()
var addr: sockaddr_in = sockaddr_in()
let res = makeAddress(&addr, host: address, port: port)
guard res != -1 else {
try ThrowNetworkError()
}
let i0 = Int8(0)
#if os(Linux)
var sock_addr = sockaddr(sa_family: 0, sa_data: (i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0))
#else
var sock_addr = sockaddr(sa_len: 0, sa_family: 0, sa_data: (i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0, i0))
#endif
memcpy(&sock_addr, &addr, Int(sizeof(sockaddr_in)))
#if os(Linux)
let cRes = SwiftGlibc.connect(fd.fd, &sock_addr, socklen_t(sizeof(sockaddr_in)))
#else
let cRes = Darwin.connect(fd.fd, &sock_addr, socklen_t(sizeof(sockaddr_in)))
#endif
if cRes != -1 {
callBack(self)
} else {
guard errno == EINPROGRESS else {
try ThrowNetworkError()
}
let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: fd.fd, what: EV_WRITE, userData: nil) {
(fd:Int32, w:Int16, ud:AnyObject?) -> () in
if (Int32(w) & EV_TIMEOUT) != 0 {
callBack(nil)
} else {
callBack(self)
}
}
event.add(timeoutSeconds)
}
}
/// Accept a new client connection and pass the result to the callback.
/// - parameter timeoutSeconds: The number of seconds to wait for a new connection to arrive. A timeout value of negative one indicates that there is no timeout.
/// - parameter callBack: The closure which will be called when the accept completes. the parameter will be a newly allocated instance of NetTCP which represents the client.
/// - returns: `PerfectError.NetworkError`
public func accept(timeoutSeconds: Double, callBack: (NetTCP?) -> ()) throws {
#if os(Linux)
let accRes = SwiftGlibc.accept(fd.fd, UnsafeMutablePointer<sockaddr>(), UnsafeMutablePointer<socklen_t>())
#else
let accRes = Darwin.accept(fd.fd, UnsafeMutablePointer<sockaddr>(), UnsafeMutablePointer<socklen_t>())
#endif
if accRes != -1 {
let newTcp = self.makeFromFd(accRes)
callBack(newTcp)
} else {
guard self.isEAgain(Int(accRes)) else {
try ThrowNetworkError()
}
let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: fd.fd, what: self.evWhatFor(EV_READ), userData: nil) {
(fd:Int32, w:Int16, ud:AnyObject?) -> () in
if (Int32(w) & EV_TIMEOUT) != 0 {
callBack(nil)
} else {
do {
try self.accept(timeoutSeconds, callBack: callBack)
} catch {
callBack(nil)
}
}
}
event.add(timeoutSeconds)
}
}
private func tryAccept() -> Int32 {
#if os(Linux)
let accRes = SwiftGlibc.accept(fd.fd, UnsafeMutablePointer<sockaddr>(), UnsafeMutablePointer<socklen_t>())
#else
let accRes = Darwin.accept(fd.fd, UnsafeMutablePointer<sockaddr>(), UnsafeMutablePointer<socklen_t>())
#endif
return accRes
}
private func waitAccept() {
let event: LibEvent = LibEvent(base: LibEvent.eventBase, fd: fd.fd, what: self.evWhatFor(EV_READ), userData: nil) {
[weak self] (fd:Int32, w:Int16, ud:AnyObject?) -> () in
self?.waitAcceptEvent = nil
if (Int32(w) & EV_TIMEOUT) != 0 {
print("huh?")
} else {
self?.semaphore!.lock()
self?.semaphore!.signal()
self?.semaphore!.unlock()
}
}
self.waitAcceptEvent = event
event.add()
}
/// Accept a series of new client connections and pass them to the callback. This function does not return outside of a catastrophic error.
/// - parameter callBack: The closure which will be called when the accept completes. the parameter will be a newly allocated instance of NetTCP which represents the client.
public func forEachAccept(callBack: (NetTCP?) -> ()) {
guard self.semaphore == nil else {
return
}
self.semaphore = Threading.Event()
defer { self.semaphore = nil }
repeat {
let accRes = tryAccept()
if accRes != -1 {
Threading.dispatchBlock {
callBack(self.makeFromFd(accRes))
}
} else if self.isEAgain(Int(accRes)) {
self.semaphore!.lock()
waitAccept()
self.semaphore!.wait()
self.semaphore!.unlock()
} else {
let errStr = String.fromCString(strerror(Int32(errno))) ?? "NO MESSAGE"
print("Unexpected networking error: \(errno) '\(errStr)'")
networkFailure = true
}
} while !networkFailure && self.fd.fd != invalidSocket
return
}
func makeFromFd(fd: Int32) -> NetTCP {
return NetTCP(fd: fd)
}
}
| apache-2.0 | db1b031c11799bb2f85da7eaff41cb5a | 33.034843 | 248 | 0.677518 | 3.357278 | false | false | false | false |
MUECKE446/ActionLoggerPackage | Examples/ActionLoggerExample_1/ActionLoggerExample_1/ViewController.swift | 1 | 2016 | //
// ViewController.swift
// ActionLoggerExample_1
//
// Created by Christian Muth on 13.12.15.
// Copyright © 2015 Christian Muth. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
// this can used for output log messages
@IBOutlet var outputTextView: NSTextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let appDelegate = NSApplication.shared.delegate as! AppDelegate
appDelegate.textViewController = self
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func generateOutputToTextViewInWindow() {
// let textViewDestination = ActionLogTextViewDestination(identifier:"textView",textView: outputTextView)
let textViewDestination = ActionLogXcodeConsoleSimulationDestination(identifier:"textView",textView: outputTextView)
let log = ActionLogger(identifier: "newLogger",logDestinations: [textViewDestination])
log!.info("let us start with a NSTextView")
log!.verbose("it looks good")
log!.error("this is only a message in category: error")
outputLogLines(linesNumber: 1000, log: log!)
}
func outputLogLines(linesNumber: Int, log: ActionLogger) {
for i in 1 ... linesNumber {
log.debug("\(i): this is a line for output \(i)")
}
}
func fixAttributesInTextView() {
let s = outputTextView.textStorage!.string
let string: MyMutableAttributedString = MyMutableAttributedString(string: s)
// var s1 = MyMutableAttributedString()
// s1.appendAttributedString(NSMutableAttributedString(string: s))
string.fixAttributes(in: NSRange.init(location: 0, length: string.length))
outputTextView.textStorage!.replaceCharacters(in: NSRange.init(location: 0, length: string.length), with: string)
}
}
| mit | 2d5ea1137e2cbd00bf1a1f7a6bc69537 | 32.032787 | 124 | 0.666998 | 4.832134 | false | false | false | false |
Romdeau4/16POOPS | iOS_app/Help's Kitchen/WaitingViewController.swift | 1 | 2802 | //
// WaitingViewController.swift
// Help's Kitchen
//
// Created by Stephen Ulmer on 2/13/17.
// Copyright © 2017 Stephen Ulmer. All rights reserved.
//
import UIKit
import Firebase
class WaitingViewController: UIViewController {
let ref = FIRDatabase.database().reference(fromURL: "https://helps-kitchen.firebaseio.com/")
let timeLeftLabel: UILabel = {
let tll = UILabel()
tll.translatesAutoresizingMaskIntoConstraints = false
tll.backgroundColor = UIColor.black
tll.textColor = UIColor.white
tll.text = "X Minutes Remaining"
return tll
}()
let tempButton: UIButton = {
let tb = UIButton()
tb.translatesAutoresizingMaskIntoConstraints = false
tb.setTitle("Temp", for: .normal)
tb.addTarget(self, action: #selector(handleSeated), for: .touchUpInside)
tb.backgroundColor = UIColor.black
return tb
}()
func handleSeated() {
guard let uid = FIRAuth.auth()?.currentUser?.uid else{
return
}
ref.child("users").child(uid).child("customerIsSeated").setValue(true)
dismiss(animated: true, completion: nil)
}
func handleCancel(){
guard let uid = FIRAuth.auth()?.currentUser?.uid else{
return
}
//TODO add reservation functionality
ref.child("users").child(uid).child("customerHasReservation").setValue(false)
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
// Do any additional setup after loading the view.
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(handleCancel))
view.addSubview(timeLeftLabel)
view.addSubview(tempButton)
setupTimeLeftLabel()
setupTempButton()
}
func setupTimeLeftLabel() {
timeLeftLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true
timeLeftLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
timeLeftLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
timeLeftLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
}
func setupTempButton() {
tempButton.topAnchor.constraint(equalTo: timeLeftLabel.bottomAnchor, constant: 50).isActive = true
tempButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
tempButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
tempButton.widthAnchor.constraint(equalToConstant: 150).isActive = true
}
}
| mit | 08822ebfd3a8199a05ce21e9bb7d816e | 32.746988 | 137 | 0.65548 | 4.914035 | false | false | false | false |
24/ios-o2o-c | gxc/User/AddUserAddressViewController.swift | 1 | 11550 | //
// AddUserAddress.swift
// gxc
//
// Created by gx on 14/11/18.
// Copyright (c) 2014年 zheng. All rights reserved.
//
import Foundation
import UIKit
class AddUserAddressViewController: UIViewController {
var firstTxt :UITextField!
var secondTxt :UITextField!
var threeTxt :UITextField!
var address :UserAddressModel!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "bar_back.png"), style: UIBarButtonItemStyle.Done, target: self, action: Selector("NavigationControllerBack"))
/*navigation 不遮住View*/
self.automaticallyAdjustsScrollViewInsets = false
self.edgesForExtendedLayout = UIRectEdge()
self.view.backgroundColor = UIColor.whiteColor()
let superview: UIView = self.view
var navigationBar = self.navigationController?.navigationBar
navigationBar?.tintColor = UIColor.whiteColor()
var firstView = UIView()
var secondView = UIView()
var threeView = UIView()
self.view.addSubview(firstView)
self.view.addSubview(secondView)
self.view.addSubview(threeView)
firstView.snp_makeConstraints { make in
make.top.equalTo(superview.snp_top).offset(10)
make.left.equalTo(CGPointZero)
make.width.equalTo(superview)
make.height.equalTo(50)
}
secondView.snp_makeConstraints { make in
make.top.equalTo(firstView.snp_bottom)
make.left.equalTo(CGPointZero)
make.width.equalTo(superview)
make.height.equalTo(50)
}
threeView.snp_makeConstraints { make in
make.top.equalTo(secondView.snp_bottom)
make.left.equalTo(CGPointZero)
make.width.equalTo(superview)
make.height.equalTo(50)
}
var firstImageView = UIImageView(image: UIImage(named: "address_name.png"))
var secondImageView = UIImageView(image: UIImage(named: "address_phone.png"))
var threeImageView = UIImageView(image: UIImage(named: "address.png"))
firstView.addSubview(firstImageView)
secondView.addSubview(secondImageView)
threeView.addSubview(threeImageView)
firstImageView.snp_makeConstraints { make in
make.centerY.equalTo(firstView.snp_centerY)
make.left.equalTo(CGPointZero).offset(3)
make.width.equalTo(30)
make.height.equalTo(30)
}
secondImageView.snp_makeConstraints { make in
make.centerY.equalTo(secondView.snp_centerY)
make.left.equalTo(CGPointZero).offset(3)
make.width.equalTo(30)
make.height.equalTo(30)
}
threeImageView.snp_makeConstraints { make in
make.centerY.equalTo(threeView.snp_centerY)
make.left.equalTo(CGPointZero).offset(3)
make.width.equalTo(30)
make.height.equalTo(30)
}
firstTxt = UITextField()
firstTxt.placeholder = "姓名"
firstTxt.adjustsFontSizeToFitWidth = true
firstTxt.clearButtonMode = UITextFieldViewMode.WhileEditing
firstTxt.borderStyle = UITextBorderStyle.RoundedRect
firstTxt.keyboardAppearance = UIKeyboardAppearance.Dark
secondTxt = UITextField()
secondTxt.placeholder = "手机号"
secondTxt.adjustsFontSizeToFitWidth = true
secondTxt.clearButtonMode = UITextFieldViewMode.WhileEditing
secondTxt.borderStyle = UITextBorderStyle.RoundedRect
secondTxt.keyboardAppearance = UIKeyboardAppearance.Dark
secondTxt.keyboardType = UIKeyboardType.NumberPad
threeTxt = UITextField()
threeTxt.placeholder = "地址"
threeTxt.adjustsFontSizeToFitWidth = true
threeTxt.clearButtonMode = UITextFieldViewMode.WhileEditing
threeTxt.borderStyle = UITextBorderStyle.RoundedRect
threeTxt.keyboardAppearance = UIKeyboardAppearance.Dark
firstView.addSubview(firstTxt)
secondView.addSubview(secondTxt)
threeView.addSubview(threeTxt)
firstTxt.snp_makeConstraints { make in
make.centerY.equalTo(firstImageView.snp_centerY)
make.left.equalTo(firstImageView.snp_right).offset(5)
make.right.equalTo(firstView).offset(-5)
make.height.equalTo(40)
}
secondTxt.snp_makeConstraints { make in
make.centerY.equalTo(secondView.snp_centerY)
make.left.equalTo(secondImageView.snp_right).offset(5)
make.right.equalTo(secondView).offset(-5)
make.height.equalTo(40)
}
threeTxt.snp_makeConstraints { make in
make.centerY.equalTo(threeView.snp_centerY)
make.left.equalTo(threeImageView.snp_right).offset(5)
make.right.equalTo(threeView).offset(-5)
make.height.equalTo(40)
}
var loginBtn = UIButton()
self.view.addSubview(loginBtn)
loginBtn.backgroundColor = UIColor(fromHexString: "#E61D4C")
loginBtn.snp_makeConstraints { make in
make.top.equalTo(threeView.snp_bottom).offset(50)
make.left.equalTo(CGPointZero).offset(5)
make.right.equalTo(superview).offset(-5)
make.height.equalTo(40)
}
loginBtn.layer.cornerRadius = 4
if(address == nil)
{
firstTxt.text = ""
secondTxt.text = ""
threeTxt.text = ""
loginBtn.setTitle("添加", forState: UIControlState.Normal)
loginBtn.addTarget(self, action: Selector("addAddress"), forControlEvents: .TouchUpInside)
self.navigationItem.title = "添加地址"
}else
{
firstTxt.text = address.UserName
firstTxt.font = UIFont (name: "Heiti SC", size: 15)
secondTxt.text = address.UserPhone
secondTxt.font = UIFont (name: "Heiti SC", size: 15)
threeTxt.text = address.UserCommunity! + address.UserRoomNo!
threeTxt.font = UIFont (name: "Heiti SC", size: 15)
loginBtn.setTitle("修改", forState: UIControlState.Normal)
loginBtn.addTarget(self, action: Selector("updateAddress"), forControlEvents: .TouchUpInside)
var rightBtn = UIButton()
var image = UIImage(named: "user_delete.png")
rightBtn.setImage(image, forState: UIControlState.Normal)
rightBtn.addTarget(self, action: Selector("DeleteUserAddress"), forControlEvents: UIControlEvents.TouchUpInside)
rightBtn.frame = CGRectMake(0, 0, 24, 25)
var rightBarButton = UIBarButtonItem(customView: rightBtn)
self.navigationItem.rightBarButtonItem = rightBarButton
self.navigationItem.title = "修改地址"
}
}
func DeleteUserAddress()
{
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("delSuccess:"), name: GXNotifaction_User_DelAddress, object: nil)
GxApiCall().DeleteAddress(GXViewState.userInfo.Token!, userAddressId: address.UserAddressId!)
}
func addAddress()
{
//set tongzhi
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("addSuccess:"), name: GXNotifaction_User_AddAddress, object: nil)
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
var txt_name = firstTxt.text
var txt_phone = secondTxt.text
var txt_address = threeTxt.text
GxApiCall().AddAddress(GXViewState.userInfo.Token!, userName: txt_name, userCommunity: "", userRoomNo: txt_address, userPhone: txt_phone,updateType:"addressupdate")
}
func delSuccess(notif :NSNotification)
{
MBProgressHUD.hideHUDForView(self.view, animated: true)
var newUserAddress = notif.userInfo?["GXNotifaction_User_DelAddress"] as GX_UpdateUserAddress
deleteAddress(address)
SweetAlert().showAlert("", subTitle: "地址已删除!", style: AlertStyle.Success)
self.navigationController?.popViewControllerAnimated(true)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func addSuccess(notif :NSNotification)
{
MBProgressHUD.hideHUDForView(self.view, animated: true)
var newUserAddress = notif.userInfo?["GXNotifaction_User_AddAddress"] as GX_UpdateUserAddress
SweetAlert().showAlert("", subTitle: "地址已添加成功!", style: AlertStyle.Success)
NSNotificationCenter.defaultCenter().removeObserver(self)
addAddressM(newUserAddress.addressId!)
self.navigationController?.popViewControllerAnimated(true)
}
func updateSuccess(notif :NSNotification)
{
MBProgressHUD.hideHUDForView(self.view, animated: true)
var newUserAddress = notif.userInfo?["GXNotifaction_User_updateAddress"] as GX_UpdateUserAddress
SweetAlert().showAlert("", subTitle: "地地址已修改成功", style: AlertStyle.Success)
if(address != nil)
{
deleteAddress(address)
}
NSNotificationCenter.defaultCenter().removeObserver(self)
addAddressM(newUserAddress.addressId!)
self.navigationController?.popViewControllerAnimated(true)
}
func addAddressM(newAddressId:String)
{
var userAddressModel:UserAddressModel! = UserAddressModel(data: [String : AnyObject]())
userAddressModel.UserName = firstTxt.text
userAddressModel.UserAddressId = newAddressId
userAddressModel.UserCommunity = ""
userAddressModel.UserRoomNo = threeTxt.text
userAddressModel.UserPhone = secondTxt.text
GXViewState.userAddressList.insert(userAddressModel, atIndex: 0)
}
func deleteAddress(address:UserAddressModel) -> [UserAddressModel]
{
var list = [UserAddressModel]()
for item in GXViewState.userAddressList
{
if (item.UserAddressId! != address.UserAddressId)
{
list.append(item)
}
}
GXViewState.userAddressList = list
return list
}
func updateAddress()
{
//set tongzhi
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("updateSuccess:"), name: GXNotifaction_User_updateAddress, object: nil)
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
var txt_name = firstTxt.text
var txt_phone = secondTxt.text
var txt_address = threeTxt.text
var addressId = address.UserAddressId!
GxApiCall().UpateAddress(GXViewState.userInfo.Token!, userAddressId: addressId, userName: txt_name, userCommunity: "", userRoomNo: txt_address, userPhone: txt_phone,updateType:"addressupdate")
}
func NavigationControllerBack()
{
self.navigationController?.popViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
} | mit | 7aa860f6cf7fd5f8808ab359b298373d | 35.733974 | 200 | 0.63726 | 4.891165 | false | false | false | false |
Thomvis/GoodProgress | GoodProgress/Progress.swift | 1 | 7597 | // The MIT License (MIT)
//
// Copyright (c) 2015 Thomas Visser
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public func progress(@autoclosure fn: () -> ()) -> Progress {
return progress(100, fn)
}
public func progress(totalUnitCount: Int64, @autoclosure fn: () -> ()) -> Progress {
return progress { source in
source.becomeCurrentWithPendingUnitCount(source.totalUnitCount)
fn()
source.resignCurrent()
}
}
public func progress(@noescape fn: ProgressSource -> ()) -> Progress {
return progress(100, fn)
}
public func progress(totalUnitCount: Int64, @noescape fn: ProgressSource -> ()) -> Progress {
let source = ProgressSource(totalUnitCount: totalUnitCount)
fn(source)
return source.progress
}
public func progress<T>(totalUnitCount: Int64, @noescape fn: ProgressSource -> (T)) -> (Progress, T) {
let source = ProgressSource(totalUnitCount: totalUnitCount)
let res = fn(source)
return (source.progress, res)
}
typealias KVOContext = UnsafeMutablePointer<UInt8>
public class Progress : NSObject {
let fractionCompletedKVOContext = KVOContext()
internal let progress: NSProgress
public typealias ProgressCallback = (Double) -> ()
private var progressCallbacks = [ProgressCallback]()
private let callbackSemaphore = dispatch_semaphore_create(1)
public init(progress: NSProgress) {
assert(progress.goodProgressObject == nil)
self.progress = progress
super.init()
self.progress.goodProgressObject = self
// hook to NSProgress
self.progress.addObserver(self, forKeyPath: "fractionCompleted", options: nil, context: self.fractionCompletedKVOContext)
}
deinit {
self.progress.removeObserver(self, forKeyPath: "fractionCompleted")
}
public convenience init(totalUnitCount: Int64) {
self.init(progress: NSProgress(totalUnitCount: totalUnitCount))
}
internal convenience init(parent: NSProgress, userInfo: [NSObject:AnyObject]?) {
self.init(progress: NSProgress(parent: parent, userInfo: userInfo))
}
override public func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if context == self.fractionCompletedKVOContext {
self.reportProgress()
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
public func onProgress(fn: ProgressCallback) -> Self {
dispatch_semaphore_wait(self.callbackSemaphore, DISPATCH_TIME_FOREVER)
if self.fractionCompleted < 1.0 {
self.progressCallbacks.append { fraction in
let keepAliveSelf = self
fn(fraction)
}
}
dispatch_semaphore_signal(self.callbackSemaphore)
return self
}
internal func reportProgress() {
dispatch_semaphore_wait(self.callbackSemaphore, DISPATCH_TIME_FOREVER)
for progressCallback in self.progressCallbacks {
progressCallback(self.fractionCompleted)
}
if self.fractionCompleted == 1.0 {
progressCallbacks.removeAll()
}
dispatch_semaphore_signal(self.callbackSemaphore)
}
}
// NSProgress proxy
extension Progress {
public internal(set) var totalUnitCount: Int64 {
get {
return self.progress.totalUnitCount
}
set(newTotal) {
self.progress.totalUnitCount = newTotal
}
}
public internal(set) var completedUnitCount: Int64 {
get {
return self.progress.completedUnitCount
}
set(newUnitCount) {
self.progress.completedUnitCount = newUnitCount
}
}
public var fractionCompleted: Double {
get {
return self.progress.fractionCompleted
}
}
public var localizedDescription: String {
get {
return self.progress.localizedDescription
}
set(newDescription) {
self.progress.localizedDescription = newDescription
}
}
public var localizedAdditionalDescription: String {
get {
return self.progress.localizedAdditionalDescription
}
set(newDescription) {
self.progress.localizedAdditionalDescription = newDescription
}
}
public internal(set) var cancellable: Bool {
get {
return self.progress.cancellable
}
set(newCancellable) {
self.progress.cancellable = newCancellable
}
}
public var cancelled: Bool {
get {
return self.progress.cancelled
}
}
public func cancel() {
assert(self.fractionCompleted < 1.0)
self.progress.cancel()
}
public internal(set) var pausable: Bool {
get {
return self.progress.pausable
}
set(newPausable) {
self.progress.pausable = newPausable
}
}
public var paused: Bool {
get {
return self.progress.paused
}
}
public func pause() {
assert(self.fractionCompleted < 1.0)
self.progress.pause()
}
public var indeterminate: Bool {
get {
return self.progress.indeterminate
}
}
public var kind: String? {
get {
return self.progress.kind
}
}
internal func becomeCurrentWithPendingUnitCount(pendingUnitCount: Int64) {
self.progress.becomeCurrentWithPendingUnitCount(pendingUnitCount)
}
internal func resignCurrent() {
self.progress.resignCurrent()
}
public class func currentProgress() -> Progress? {
return NSProgress.currentProgress()?.goodProgressObject
}
public func setUserInfoObject(object: AnyObject?, forKey key: String) {
self.progress.setUserInfoObject(object, forKey: key)
}
}
private let GoodProgressObjectKey = UnsafePointer<Void>()
extension NSProgress {
internal var goodProgressObject: Progress? {
get {
return objc_getAssociatedObject(self, GoodProgressObjectKey) as? Progress
}
set(newObject) {
objc_setAssociatedObject(self, GoodProgressObjectKey, newObject, UInt(OBJC_ASSOCIATION_ASSIGN))
}
}
}
| mit | 93363f3237e5d6e939835fd749c2a47c | 29.266932 | 163 | 0.644465 | 5.017834 | false | false | false | false |
younatics/MediaBrowser | MediaBrowser/MediaGridViewController.swift | 1 | 6154 | //
// MediaGridViewController.swift
// MediaBrowser
//
// Created by Seungyoun Yi on 2017. 9. 6..
// Copyright © 2017년 Seungyoun Yi. All rights reserved.
//
import UIKit
class MediaGridViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
weak var browser: MediaBrowser?
var selectionMode = false
var initialContentOffset = CGPoint(x: 0.0, y: CGFloat.greatestFiniteMagnitude)
init() {
super.init(collectionViewLayout: UICollectionViewFlowLayout())
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
//MARK: - View
override func viewDidLoad() {
super.viewDidLoad()
if let cv = collectionView {
cv.register(MediaGridCell.self, forCellWithReuseIdentifier: "MediaGridCell")
cv.alwaysBounceVertical = true
cv.backgroundColor = UIColor.black
}
}
override func viewWillDisappear(_ animated: Bool) {
// Cancel outstanding loading
if let cv = collectionView {
for cell in cv.visibleCells {
let c = cell as! MediaGridCell
if let p = c.photo {
p.cancelAnyLoading()
}
}
}
super.viewWillDisappear(animated)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
func adjustOffsetsAsRequired() {
// Move to previous content offset
if initialContentOffset.y != CGFloat.greatestFiniteMagnitude {
collectionView!.contentOffset = initialContentOffset
collectionView!.layoutIfNeeded() // Layout after content offset change
}
// Check if current item is visible and if not, make it so!
if let b = browser, b.numberOfMedias > 0 {
let currentPhotoIndexPath = IndexPath(item: b.currentIndex, section: 0)
let visibleIndexPaths = collectionView!.indexPathsForVisibleItems
var currentVisible = false
for indexPath in visibleIndexPaths {
if indexPath == currentPhotoIndexPath {
currentVisible = true
break
}
}
if !currentVisible {
collectionView!.scrollToItem(at: currentPhotoIndexPath, at: UICollectionView.ScrollPosition.left, animated: false)
}
}
}
//MARK: - Layout
var columns: CGFloat {
return floorcgf(x: view.bounds.width / 93.0)
}
var margin = CGFloat(1.0)
var gutter = CGFloat(1.0)
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: nil) { _ in
if let cv = self.collectionView {
cv.reloadData()
}
}
super.viewWillTransition(to: size, with: coordinator)
}
//MARK: - Collection View
override func collectionView(_ view: UICollectionView, numberOfItemsInSection section: Int) -> NSInteger {
if let b = browser {
return b.numberOfMedias
}
return 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MediaGridCell", for: indexPath as IndexPath) as! MediaGridCell
if let b = browser, let photo = b.thumbPhotoAtIndex(index: indexPath.row) {
cell.photo = photo
cell.gridController = self
cell.selectionMode = selectionMode
cell.index = indexPath.row
cell.isSelected = b.photoIsSelectedAtIndex(index: indexPath.row)
if let placeholder = self.browser?.placeholderImage {
cell.placeholderImage = placeholder.image
cell.imageView.image = placeholder.image
}
if let _ = b.image(for: photo) {
cell.displayImage()
} else {
photo.loadUnderlyingImageAndNotify()
}
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let b = browser {
b.currentPhotoIndex = indexPath.row
b.hideGrid()
}
}
override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let gridCell = cell as? MediaGridCell, let gcp = gridCell.photo {
gcp.cancelAnyLoading()
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if let delegateSize = self.browser?.delegate?.gridCellSize() {
return delegateSize
}
let value = CGFloat(floorf(Float((view.bounds.size.width - (columns - 1.0) * gutter - 2.0 * margin) / columns)))
return CGSize(width: value, height: value)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return gutter
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return gutter
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let margin = self.margin
return UIEdgeInsets.init(top: margin, left: margin, bottom: margin, right: margin)
}
}
| mit | 1eae74e42f35f95144f2e4f02940fffb | 34.350575 | 175 | 0.617461 | 5.727188 | false | false | false | false |
deisterhold/MKPolygonEditViewController | MKPolygonEditViewController/MKPolygonEditViewController.swift | 1 | 3536 | //
// ViewController.swift
// MKPolygonEditViewController
//
// Created by Daniel Eisterhold on 4/2/16.
// Copyright © 2016 Daniel Eisterhold. All rights reserved.
//
import UIKit
import MapKit
class MKPolygonEditViewController: UIViewController, MKMapViewDelegate {
// Map View
@IBOutlet var mapView:MKMapView!
// Array for holding coordinates
var coordinates = [CLLocationCoordinate2D]()
// Polygon to draw on map
var polygon = MKPolygon()
override func viewDidLoad() {
super.viewDidLoad()
// Add an edit button to the navigation bar
navigationItem.rightBarButtonItem = self.editButtonItem()
}
// MARK: Customize the drawing of the map overlay
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
// Create polygon renderer
let renderer = MKPolygonRenderer(overlay: overlay)
// Set the line color
renderer.strokeColor = UIColor.orangeColor()
// Set the line width
renderer.lineWidth = 5.0
// Return the customized renderer
return renderer
}
// MARK: - Get notified when the view begins/ends editing
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
if editing {
// Disable the map from moving
mapView.userInteractionEnabled = false
}
else {
// Enable the map to move
mapView.userInteractionEnabled = true
}
}
// MARK: - Handle Touches
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// If editing
if editing {
// Empty array
coordinates.removeAll()
// Convert touches to map coordinates
for touch in touches {
let coordinate = mapView.convertPoint(touch.locationInView(mapView), toCoordinateFromView: mapView)
coordinates.append(coordinate)
}
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
// If editing
if editing {
// Convert touches to map coordinates
for touch in touches {
// Use this method to convert a CGPoint to CLLocationCoordinate2D
let coordinate = mapView.convertPoint(touch.locationInView(mapView), toCoordinateFromView: mapView)
// Add the coordinate to the array
coordinates.append(coordinate)
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
// If editing
if editing {
// Convert touches to map coordinates
for touch in touches {
let coordinate = mapView.convertPoint(touch.locationInView(mapView), toCoordinateFromView: mapView)
coordinates.append(coordinate)
}
// Remove existing polygon
mapView.removeOverlay(polygon)
// Create new polygon
polygon = MKPolygon(coordinates: &coordinates, count: coordinates.count)
// Add polygon to map
mapView.addOverlay(polygon)
}
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
// If editing
if editing {
// Do nothing
}
}
}
| gpl-3.0 | b45f65121a2d062925e0c633519484c9 | 30.5625 | 115 | 0.599151 | 5.593354 | false | false | false | false |
ylankgz/safebook | Safebook/Defaults.swift | 1 | 740 | //
// Defaults.swift
// Keinex
//
// Created by Андрей on 07.08.16.
// Copyright © 2016 Keinex. All rights reserved.
//
import Foundation
import UIKit
let userDefaults = UserDefaults.standard
let isiPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
let latestPostValue = "postValue"
//Sources
let sourceUrl:NSString = "SourceUrlDefault"
let sourceUrlKeinexRu:NSString = "https://gist.githubusercontent.com/ylankgz/f22089e4824a0845da64a7978736eab8/raw/8d2234f5bfb0f264f9776010c0a99b5e8d117b59/data.json"
let sourceUrlKeinexCom:NSString = "https://gist.githubusercontent.com/ylankgz/f22089e4824a0845da64a7978736eab8/raw/8d2234f5bfb0f264f9776010c0a99b5e8d117b59/data.json"
let autoDelCache:NSString = "none"
| mit | ca79e81a94d90f0ab28ada2596ff650b | 33.904762 | 166 | 0.814461 | 2.79771 | false | false | false | false |
ddki/my_study_project | language/swift/SimpleTunnelCustomizedNetworkingUsingtheNetworkExtensionFramework/tunnel_server/ServerConfiguration.swift | 1 | 3518 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file contains the ServerConfiguration class. The ServerConfiguration class is used to parse the SimpleTunnel server configuration.
*/
import Foundation
import SystemConfiguration
/// An object containing configuration settings for the SimpleTunnel server.
class ServerConfiguration {
// MARK: Properties
/// A dictionary containing configuration parameters.
var configuration: [String: AnyObject]
/// A pool of IP addresses to allocate to clients.
var addressPool: AddressPool?
// MARK: Initializers
init() {
configuration = [String: AnyObject]()
addressPool = nil
}
// MARK: Interface
/// Read the configuration settings from a plist on disk.
func loadFromFileAtPath(path: String) -> Bool {
guard let fileStream = NSInputStream(fileAtPath: path) else {
simpleTunnelLog("Failed to open \(path) for reading")
return false
}
fileStream.open()
var newConfiguration: [String: AnyObject]
do {
newConfiguration = try NSPropertyListSerialization.propertyListWithStream(fileStream, options: .MutableContainers, format: nil) as! [String: AnyObject]
}
catch {
simpleTunnelLog("Failed to read the configuration from \(path): \(error)")
return false
}
guard let startAddress = getValueFromPlist(newConfiguration, keyArray: [.IPv4, .Pool, .StartAddress]) as? String else {
simpleTunnelLog("Missing v4 start address")
return false
}
guard let endAddress = getValueFromPlist(newConfiguration, keyArray: [.IPv4, .Pool, .EndAddress]) as? String else {
simpleTunnelLog("Missing v4 end address")
return false
}
addressPool = AddressPool(startAddress: startAddress, endAddress: endAddress)
// The configuration dictionary gets sent to clients as the tunnel settings dictionary. Remove the IP pool parameters.
if let value = newConfiguration[SettingsKey.IPv4.rawValue] as? [NSObject: AnyObject] {
var IPv4Dictionary = value
IPv4Dictionary.removeValueForKey(SettingsKey.Pool.rawValue)
newConfiguration[SettingsKey.IPv4.rawValue] = IPv4Dictionary
}
if !newConfiguration.keys.contains({ $0 == SettingsKey.DNS.rawValue }) {
// The configuration does not specify any DNS configuration, so get the current system default resolver.
let (DNSServers, DNSSearchDomains) = ServerConfiguration.copyDNSConfigurationFromSystem()
newConfiguration[SettingsKey.DNS.rawValue] = [
SettingsKey.Servers.rawValue: DNSServers,
SettingsKey.SearchDomains.rawValue: DNSSearchDomains
]
}
configuration = newConfiguration
return true
}
/// Copy the default resolver configuration from the system on which the server is running.
class func copyDNSConfigurationFromSystem() -> ([String], [String]) {
let globalDNSKey = SCDynamicStoreKeyCreateNetworkGlobalEntity(kCFAllocatorDefault, kSCDynamicStoreDomainState, kSCEntNetDNS)
var DNSServers = [String]()
var DNSSearchDomains = [String]()
// The default resolver configuration can be obtained from State:/Network/Global/DNS in the dynamic store.
if let globalDNS = SCDynamicStoreCopyValue(nil, globalDNSKey) as? [NSObject: AnyObject],
servers = globalDNS[kSCPropNetDNSServerAddresses as String] as? [String]
{
if let searchDomains = globalDNS[kSCPropNetDNSSearchDomains as String] as? [String] {
DNSSearchDomains = searchDomains
}
DNSServers = servers
}
return (DNSServers, DNSSearchDomains)
}
} | mit | 830029ecec279804a0aa9e558f07ac92 | 32.817308 | 155 | 0.754551 | 4.117096 | false | true | false | false |
chenkaige/EasyIOS-Swift | Pod/Classes/Easy/Lib/PullRefresh/EZPullToRefresh.swift | 3 | 6249 | //
// EZPullToRefresh.swift
// Demo
//
// Created by zhuchao on 15/5/15.
// Copyright (c) 2015年 zhuchao. All rights reserved.
//
import UIKit
import Bond
let EZPullToRefreshViewHeight:CGFloat = 60.0
public enum EZPullToRefreshState {
case Stopped
case Triggered
case Loading
case Pulling
}
public class Header : UIView {
init(scrollView:UIScrollView,frame: CGRect = CGRectZero) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func resetScrollViewContentInset(scrollView:UIScrollView){
var currentInsets = scrollView.contentInset
currentInsets.top = scrollView.pullToRefreshView!.originalTopInset
self.setScrollViewContentInset(currentInsets, scrollView: scrollView)
}
public func setScrollViewContentInsetForLoading(scrollView:UIScrollView){
let offset = max(EZPullToRefreshViewHeight, 0)
var currentInsets = scrollView.contentInset
currentInsets.top = max(offset, scrollView.pullToRefreshView!.originalTopInset + scrollView.pullToRefreshView!.bounds.size.height)
self.setScrollViewContentInset(currentInsets, scrollView: scrollView)
}
public func setScrollViewContentInset(contentInset:UIEdgeInsets,scrollView:UIScrollView){
UIView.animateWithDuration(0.3, delay: 0,
options: UIViewAnimationOptions.BeginFromCurrentState,
animations: {
scrollView.contentInset = contentInset
},completion:nil)
}
}
public class EZPullToRefreshView : UIView {
public var state = Observable<EZPullToRefreshState>(.Stopped)
public var originalTopInset:CGFloat = 0.0
public var originalBottomInset:CGFloat = 0.0
public var originalOffset:CGFloat = 0.0
private var pullToRefreshActionHandler:(Void -> ())?
private var oldState = EZPullToRefreshState.Stopped
private func commonInit(){
self.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.state.observe{ [unowned self] state in
if state == .Loading && self.oldState == .Triggered {
self.pullToRefreshActionHandler?()
}
self.oldState = state
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
func setCustomView(customView:UIView){
if customView.isKindOfClass(UIView) {
for view in self.subviews {
view.removeFromSuperview()
}
self.addSubview(customView)
let viewBounds = customView.bounds;
let origin = CGPointMake(
CGFloat(roundf(Float(self.bounds.size.width-viewBounds.size.width)/2)),
CGFloat(roundf(Float(self.bounds.size.height-viewBounds.size.height)/2)))
customView.frame = CGRectMake(origin.x, origin.y, viewBounds.size.width, viewBounds.size.height)
}
}
public func startAnimating(){
self.state.value = .Loading
}
public func stopAnimating(){
self.state.value = .Stopped
}
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
let scrollView = object as! UIScrollView
if keyPath == "contentOffset" && scrollView.showsPullToRefresh {
if self.state.value != .Loading{
let pullNum = scrollView.contentOffset.y + self.originalTopInset
if !scrollView.dragging && self.state.value == .Triggered {
self.state.value = .Loading
}else if scrollView.dragging && self.state.value == .Pulling && pullNum < -EZPullToRefreshViewHeight {
self.state.value = .Triggered
}else if pullNum <= -1 && pullNum > -EZPullToRefreshViewHeight {
self.state.value = .Pulling
}else if pullNum > -1 {
self.state.value = .Stopped
}
}
}
}
}
private var PullToRefreshViewHandle :UInt8 = 0
extension UIScrollView {
public var pullToRefreshView : EZPullToRefreshView? {
get{
if let d: AnyObject = objc_getAssociatedObject(self, &PullToRefreshViewHandle) {
return d as? EZPullToRefreshView
}else{
return nil
}
}set (value){
objc_setAssociatedObject(self, &PullToRefreshViewHandle, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var showsPullToRefresh :Bool {
get{
return !self.pullToRefreshView!.hidden
}set(value){
if value {
self.addObserver(self.pullToRefreshView!, forKeyPath: "contentOffset", options:NSKeyValueObservingOptions.New, context: nil)
self.pullToRefreshView?.hidden = false
}else{
self.removeObserver(self.pullToRefreshView!, forKeyPath: "contentOffset")
self.pullToRefreshView?.hidden = true
}
}
}
public func addPullToRefreshWithActionHandler(customer:UIView? = nil,actionHandler:Void -> ()){
if self.pullToRefreshView == nil {
let view = EZPullToRefreshView(frame: CGRectZero)
view.pullToRefreshActionHandler = actionHandler
view.originalTopInset = self.contentInset.top;
view.originalBottomInset = self.contentInset.bottom;
self.pullToRefreshView = view;
self.showsPullToRefresh = true;
self.addSubview(self.pullToRefreshView!)
}
if customer == nil {
self.pullToRefreshView?.setCustomView(PullHeader(scrollView: self))
}else{
self.pullToRefreshView?.setCustomView(customer!)
}
}
public func triggerPullToRefresh(){
self.pullToRefreshView?.oldState = .Triggered
self.pullToRefreshView?.startAnimating()
}
} | mit | 6e1abb634972307b947231abc7c03eb6 | 34.299435 | 164 | 0.635345 | 5.192851 | false | false | false | false |
fangspeen/swift-linear-algebra | LinearAlgebra/main.swift | 1 | 1942 | //
// main.swift
// LinearAlgebra
//
// Created by Jean Blignaut on 2015/03/21.
// Copyright (c) 2015 Jean Blignaut. All rights reserved.
//
import Foundation
import Accelerate
let a: Array<Double> = [1,2,3,4]
let b: Array<Double> = [1,2,3]
var A = la_object_t()
var B = la_object_t()
a.withUnsafeBufferPointer{ (buffer: UnsafeBufferPointer<Double>) -> Void in
//should have been short hand for below but some how doesn't work in swift
//A = la_vector_from_double_buffer(buffer.baseAddress, la_count_t(4), la_count_t(1), la_attribute_t(LA_DEFAULT_ATTRIBUTES))
A = la_matrix_from_double_buffer(buffer.baseAddress, la_count_t(a.count), la_count_t(1), la_count_t(1), la_hint_t(LA_NO_HINT), la_attribute_t(LA_DEFAULT_ATTRIBUTES))
}
b.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<Double>) -> Void in
//should have been short hand for below but some how doesn't work in swift
//B = la_vector_from_double_buffer(buffer.baseAddress, la_count_t(4), la_count_t(1), la_attribute_t(LA_DEFAULT_ATTRIBUTES))
//I would have expected that the transpose would be required but seems oiptional
B = //la_transpose(
la_matrix_from_double_buffer(buffer.baseAddress, la_count_t(b.count), la_count_t(1), la_count_t(1), la_hint_t(LA_NO_HINT), la_attribute_t(LA_DEFAULT_ATTRIBUTES))//)
}
let res = la_solve(A,B)
let mult = la_outer_product(A, B)
var buf: Array<Double> = [0,0,0
,0,0,0
,0,0,0
,0,0,0]
buf.withUnsafeMutableBufferPointer {
(inout buffer: UnsafeMutableBufferPointer<Double>) -> Void in
la_matrix_to_double_buffer(buffer.baseAddress, la_count_t(3), mult)
}
//contents of a
println(a)
//contents of b
println(b)
//seems to be the dimensions of the vector in A
print(A)
//seems to be the dimensions of the vector in B
print(B)
//seems to be the dimensions of the resultant matrix
print(mult)
//result
println(buf)
| bsd-2-clause | b363bdfd1c7bf21129b07f2ea69ef607 | 32.482759 | 172 | 0.678682 | 3.112179 | false | false | false | false |
longsirhero/DinDinShop | DinDinShopDemo/Pods/FSPagerView/Sources/FSPagerView.swift | 1 | 22720 | //
// FSPagerView.swift
// FSPagerView
//
// Created by Wenchao Ding on 17/12/2016.
// Copyright © 2016 Wenchao Ding. All rights reserved.
//
// https://github.com/WenchaoD
//
// FSPagerView is an elegant Screen Slide Library implemented primarily with UICollectionView. It is extremely helpful for making Banner、Product Show、Welcome/Guide Pages、Screen/ViewController Sliders.
//
import UIKit
@objc
public protocol FSPagerViewDataSource: NSObjectProtocol {
/// Asks your data source object for the number of items in the pager view.
@objc(numberOfItemsInPagerView:)
func numberOfItems(in pagerView: FSPagerView) -> Int
/// Asks your data source object for the cell that corresponds to the specified item in the pager view.
@objc(pagerView:cellForItemAtIndex:)
func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell
}
@objc
public protocol FSPagerViewDelegate: NSObjectProtocol {
/// Asks the delegate if the item should be highlighted during tracking.
@objc(pagerView:shouldHighlightItemAtIndex:)
optional func pagerView(_ pagerView: FSPagerView, shouldHighlightItemAt index: Int) -> Bool
/// Tells the delegate that the item at the specified index was highlighted.
@objc(pagerView:didHighlightItemAtIndex:)
optional func pagerView(_ pagerView: FSPagerView, didHighlightItemAt index: Int)
/// Asks the delegate if the specified item should be selected.
@objc(pagerView:shouldSelectItemAtIndex:)
optional func pagerView(_ pagerView: FSPagerView, shouldSelectItemAt index: Int) -> Bool
/// Tells the delegate that the item at the specified index was selected.
@objc(pagerView:didSelectItemAtIndex:)
optional func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int)
/// Tells the delegate that the specified cell is about to be displayed in the pager view.
@objc(pagerView:willDisplayCell:forItemAtIndex:)
optional func pagerView(_ pagerView: FSPagerView, willDisplay cell: FSPagerViewCell, forItemAt index: Int)
/// Tells the delegate that the specified cell was removed from the pager view.
@objc(pagerView:didEndDisplayingCell:forItemAtIndex:)
optional func pagerView(_ pagerView: FSPagerView, didEndDisplaying cell: FSPagerViewCell, forItemAt index: Int)
/// Tells the delegate when the pager view is about to start scrolling the content.
@objc(pagerViewWillBeginDragging:)
optional func pagerViewWillBeginDragging(_ pagerView: FSPagerView)
/// Tells the delegate when the user finishes scrolling the content.
@objc(pagerViewWillEndDragging:targetIndex:)
optional func pagerViewWillEndDragging(_ pagerView: FSPagerView, targetIndex: Int)
/// Tells the delegate when the user scrolls the content view within the receiver.
@objc(pagerViewDidScroll:)
optional func pagerViewDidScroll(_ pagerView: FSPagerView)
/// Tells the delegate when a scrolling animation in the pager view concludes.
@objc(pagerViewDidEndScrollAnimation:)
optional func pagerViewDidEndScrollAnimation(_ pagerView: FSPagerView)
/// Tells the delegate that the pager view has ended decelerating the scrolling movement.
@objc(pagerViewDidEndDecelerating:)
optional func pagerViewDidEndDecelerating(_ pagerView: FSPagerView)
}
@objc
public enum FSPagerViewScrollDirection: Int {
case horizontal
case vertical
}
@IBDesignable
open class FSPagerView: UIView,UICollectionViewDataSource,UICollectionViewDelegate {
// MARK: - Public properties
#if TARGET_INTERFACE_BUILDER
// Yes you need to lie to the Interface Builder, otherwise "@IBOutlet" cannot be connected.
@IBOutlet open weak var dataSource: AnyObject?
@IBOutlet open weak var delegate: AnyObject?
#else
open weak var dataSource: FSPagerViewDataSource?
open weak var delegate: FSPagerViewDelegate?
#endif
/// The scroll direction of the pager view. Default is horizontal.
open var scrollDirection: FSPagerViewScrollDirection = .horizontal {
didSet {
self.collectionViewLayout.forceInvalidate()
}
}
/// The time interval of automatic sliding. 0 means disabling automatic sliding. Default is 0.
@IBInspectable
open var automaticSlidingInterval: CGFloat = 0.0 {
didSet {
self.cancelTimer()
if self.automaticSlidingInterval > 0 {
self.startTimer()
}
}
}
/// The spacing to use between items in the pager view. Default is 0.
@IBInspectable
open var interitemSpacing: CGFloat = 0 {
didSet {
self.collectionViewLayout.forceInvalidate()
}
}
/// The item size of the pager view. .zero means always fill the bounds of the pager view. Default is .zero.
@IBInspectable
open var itemSize: CGSize = .zero {
didSet {
self.collectionViewLayout.forceInvalidate()
}
}
/// A Boolean value indicates that whether the pager view has infinite items. Default is false.
@IBInspectable
open var isInfinite: Bool = false {
didSet {
self.collectionViewLayout.needsReprepare = true
self.collectionView.reloadData()
}
}
/// The background view of the pager view.
@IBInspectable
open var backgroundView: UIView? {
didSet {
if let backgroundView = self.backgroundView {
if backgroundView.superview != nil {
backgroundView.removeFromSuperview()
}
self.insertSubview(backgroundView, at: 0)
self.setNeedsLayout()
}
}
}
/// The transformer of the pager view.
open var transformer: FSPagerViewTransformer? {
didSet {
self.transformer?.pagerView = self
self.collectionViewLayout.forceInvalidate()
}
}
// MARK: - Public readonly-properties
/// Returns whether the user has touched the content to initiate scrolling.
open var isTracking: Bool {
return self.collectionView.isTracking
}
/// The percentage of x position at which the origin of the content view is offset from the origin of the pagerView view.
open var scrollOffset: CGFloat {
let contentOffset = max(self.collectionView.contentOffset.x, self.collectionView.contentOffset.y)
let scrollOffset = Double(contentOffset.divided(by: self.collectionViewLayout.itemSpacing))
return fmod(CGFloat(scrollOffset), CGFloat(Double(self.numberOfItems)))
}
/// The underlying gesture recognizer for pan gestures.
open var panGestureRecognizer: UIPanGestureRecognizer {
return self.collectionView.panGestureRecognizer
}
open fileprivate(set) dynamic var currentIndex: Int = 0
// MARK: - Private properties
internal weak var collectionViewLayout: FSPagerViewLayout!
internal weak var collectionView: FSPagerViewCollectionView!
internal weak var contentView: UIView!
internal var timer: Timer?
internal var numberOfItems: Int = 0
internal var numberOfSections: Int = 0
fileprivate var dequeingSection = 0
fileprivate var centermostIndexPath: IndexPath {
guard self.numberOfItems > 0, self.collectionView.contentSize != .zero else {
return IndexPath(item: 0, section: 0)
}
let sortedIndexPaths = self.collectionView.indexPathsForVisibleItems.sorted { (l, r) -> Bool in
let leftFrame = self.collectionViewLayout.frame(for: l)
let rightFrame = self.collectionViewLayout.frame(for: r)
var leftCenter: CGFloat,rightCenter: CGFloat,ruler: CGFloat
switch self.scrollDirection {
case .horizontal:
leftCenter = leftFrame.midX
rightCenter = rightFrame.midX
ruler = self.collectionView.bounds.midX
case .vertical:
leftCenter = leftFrame.midY
rightCenter = rightFrame.midY
ruler = self.collectionView.bounds.midY
}
return abs(ruler-leftCenter) < abs(ruler-rightCenter)
}
let indexPath = sortedIndexPaths.first
if let indexPath = indexPath {
return indexPath
}
return IndexPath(item: 0, section: 0)
}
fileprivate var possibleTargetingIndexPath: IndexPath?
// MARK: - Overriden functions
public override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
open override func layoutSubviews() {
super.layoutSubviews()
self.backgroundView?.frame = self.bounds
self.contentView.frame = self.bounds
self.collectionView.frame = self.contentView.bounds
}
open override func willMove(toWindow newWindow: UIWindow?) {
super.willMove(toWindow: newWindow)
if newWindow != nil {
self.startTimer()
} else {
self.cancelTimer()
}
}
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
self.contentView.layer.borderWidth = 1
self.contentView.layer.cornerRadius = 5
self.contentView.layer.masksToBounds = true
let label = UILabel(frame: self.contentView.bounds)
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 25)
label.text = "FSPagerView"
self.contentView.addSubview(label)
}
deinit {
self.collectionView.dataSource = nil
self.collectionView.delegate = nil
}
// MARK: - UICollectionViewDataSource
public func numberOfSections(in collectionView: UICollectionView) -> Int {
guard let dataSource = self.dataSource else {
return 1
}
self.numberOfItems = dataSource.numberOfItems(in: self)
guard self.numberOfItems > 0 else {
return 0;
}
self.numberOfSections = self.isInfinite ? Int(Int16.max)/self.numberOfItems : 1
return self.numberOfSections
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.numberOfItems
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let index = indexPath.item
self.dequeingSection = indexPath.section
let cell = self.dataSource!.pagerView(self, cellForItemAt: index)
return cell
}
// MARK: - UICollectionViewDelegate
public func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
guard let function = self.delegate?.pagerView(_:shouldHighlightItemAt:) else {
return true
}
let index = indexPath.item % self.numberOfItems
return function(self,index)
}
public func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
guard let function = self.delegate?.pagerView(_:didHighlightItemAt:) else {
return
}
let index = indexPath.item % self.numberOfItems
function(self,index)
}
public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard let function = self.delegate?.pagerView(_:shouldSelectItemAt:) else {
return true
}
let index = indexPath.item % self.numberOfItems
return function(self,index)
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let function = self.delegate?.pagerView(_:didSelectItemAt:) else {
return
}
self.possibleTargetingIndexPath = indexPath
defer {
self.possibleTargetingIndexPath = nil
}
let index = indexPath.item % self.numberOfItems
function(self,index)
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let function = self.delegate?.pagerView(_:willDisplay:forItemAt:) else {
return
}
let index = indexPath.item % self.numberOfItems
function(self,cell as! FSPagerViewCell,index)
}
public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let function = self.delegate?.pagerView(_:didEndDisplaying:forItemAt:) else {
return
}
let index = indexPath.item % self.numberOfItems
function(self,cell as! FSPagerViewCell,index)
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if self.numberOfItems > 0 {
// In case someone is using KVO
let currentIndex = lround(Double(self.scrollOffset)) % self.numberOfItems
if (currentIndex != self.currentIndex) {
self.currentIndex = currentIndex
}
}
guard let function = self.delegate?.pagerViewDidScroll else {
return
}
function(self)
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if let function = self.delegate?.pagerViewWillBeginDragging(_:) {
function(self)
}
if self.automaticSlidingInterval > 0 {
self.cancelTimer()
}
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if let function = self.delegate?.pagerViewWillEndDragging(_:targetIndex:) {
let contentOffset = self.scrollDirection == .horizontal ? targetContentOffset.pointee.x : targetContentOffset.pointee.y
let targetItem = lround(Double(contentOffset/self.collectionViewLayout.itemSpacing))
function(self, targetItem % self.numberOfItems)
}
if self.automaticSlidingInterval > 0 {
self.startTimer()
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if let function = self.delegate?.pagerViewDidEndDecelerating {
function(self)
}
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
if let function = self.delegate?.pagerViewDidEndScrollAnimation {
function(self)
}
}
// MARK: - Public functions
/// Register a class for use in creating new pager view cells.
///
/// - Parameters:
/// - cellClass: The class of a cell that you want to use in the pager view.
/// - identifier: The reuse identifier to associate with the specified class. This parameter must not be nil and must not be an empty string.
@objc(registerClass:forCellWithReuseIdentifier:)
open func register(_ cellClass: Swift.AnyClass?, forCellWithReuseIdentifier identifier: String) {
self.collectionView.register(cellClass, forCellWithReuseIdentifier: identifier)
}
/// Register a nib file for use in creating new pager view cells.
///
/// - Parameters:
/// - nib: The nib object containing the cell object. The nib file must contain only one top-level object and that object must be of the type FSPagerViewCell.
/// - identifier: The reuse identifier to associate with the specified nib file. This parameter must not be nil and must not be an empty string.
@objc(registerNib:forCellWithReuseIdentifier:)
open func register(_ nib: UINib?, forCellWithReuseIdentifier identifier: String) {
self.collectionView.register(nib, forCellWithReuseIdentifier: identifier)
}
/// Returns a reusable cell object located by its identifier
///
/// - Parameters:
/// - identifier: The reuse identifier for the specified cell. This parameter must not be nil.
/// - index: The index specifying the location of the cell.
/// - Returns: A valid FSPagerViewCell object.
@objc(dequeueReusableCellWithReuseIdentifier:atIndex:)
open func dequeueReusableCell(withReuseIdentifier identifier: String, at index: Int) -> FSPagerViewCell {
let indexPath = IndexPath(item: index, section: self.dequeingSection)
let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
guard cell.isKind(of: FSPagerViewCell.self) else {
fatalError("Cell class must be subclass of FSPagerViewCell")
}
return cell as! FSPagerViewCell
}
/// Reloads all of the data for the collection view.
@objc(reloadData)
open func reloadData() {
self.collectionViewLayout.needsReprepare = true;
self.collectionView.reloadData()
}
/// Selects the item at the specified index and optionally scrolls it into view.
///
/// - Parameters:
/// - index: The index path of the item to select.
/// - animated: Specify true to animate the change in the selection or false to make the change without animating it.
@objc(selectItemAtIndex:animated:)
open func selectItem(at index: Int, animated: Bool) {
let indexPath = self.nearbyIndexPath(for: index)
let scrollPosition: UICollectionViewScrollPosition = self.scrollDirection == .horizontal ? .centeredVertically : .centeredVertically
self.collectionView.selectItem(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}
/// Deselects the item at the specified index.
///
/// - Parameters:
/// - index: The index of the item to deselect.
/// - animated: Specify true to animate the change in the selection or false to make the change without animating it.
@objc(deselectItemAtIndex:animated:)
open func deselectItem(at index: Int, animated: Bool) {
let indexPath = self.nearbyIndexPath(for: index)
self.collectionView.deselectItem(at: indexPath, animated: animated)
}
/// Scrolls the pager view contents until the specified item is visible.
///
/// - Parameters:
/// - index: The index of the item to scroll into view.
/// - animated: Specify true to animate the scrolling behavior or false to adjust the pager view’s visible content immediately.
@objc(scrollToItemAtIndex:animated:)
open func scrollToItem(at index: Int, animated: Bool) {
guard index < self.numberOfItems else {
fatalError("index \(index) is out of range [0...\(self.numberOfItems-1)]")
}
let indexPath = { () -> IndexPath in
if let indexPath = self.possibleTargetingIndexPath, indexPath.item == index {
defer {
self.possibleTargetingIndexPath = nil
}
return indexPath
}
return self.isInfinite ? self.nearbyIndexPath(for: index) : IndexPath(item: index, section: 0)
}()
let contentOffset = self.collectionViewLayout.contentOffset(for: indexPath)
self.collectionView.setContentOffset(contentOffset, animated: animated)
}
/// Returns the index of the specified cell.
///
/// - Parameter cell: The cell object whose index you want.
/// - Returns: The index of the cell or NSNotFound if the specified cell is not in the pager view.
@objc(indexForCell:)
open func index(for cell: FSPagerViewCell) -> Int {
guard let indexPath = self.collectionView.indexPath(for: cell) else {
return NSNotFound
}
return indexPath.item
}
// MARK: - Private functions
fileprivate func commonInit() {
// Content View
let contentView = UIView(frame:CGRect.zero)
contentView.backgroundColor = UIColor.clear
self.addSubview(contentView)
self.contentView = contentView
// UICollectionView
let collectionViewLayout = FSPagerViewLayout()
let collectionView = FSPagerViewCollectionView(frame: CGRect.zero, collectionViewLayout: collectionViewLayout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.clear
self.contentView.addSubview(collectionView)
self.collectionView = collectionView
self.collectionViewLayout = collectionViewLayout
}
fileprivate func startTimer() {
guard self.automaticSlidingInterval > 0 && self.timer == nil else {
return
}
self.timer = Timer.scheduledTimer(timeInterval: TimeInterval(self.automaticSlidingInterval), target: self, selector: #selector(self.flipNext(sender:)), userInfo: nil, repeats: true)
RunLoop.current.add(self.timer!, forMode: .commonModes)
}
@objc
fileprivate func flipNext(sender: Timer?) {
guard let _ = self.superview, let _ = self.window, self.numberOfItems > 0, !self.isTracking else {
return
}
let contentOffset: CGPoint = {
let indexPath = self.centermostIndexPath
let section = self.isInfinite ? (indexPath.section+(indexPath.item+1)/self.numberOfItems) : 0
let item = (indexPath.item+1) % self.numberOfItems
return self.collectionViewLayout.contentOffset(for: IndexPath(item: item, section: section))
}()
self.collectionView.setContentOffset(contentOffset, animated: true)
}
fileprivate func cancelTimer() {
guard self.timer != nil else {
return
}
self.timer!.invalidate()
self.timer = nil
}
fileprivate func nearbyIndexPath(for index: Int) -> IndexPath {
// Is there a better algorithm?
let currentIndex = self.currentIndex
let currentSection = self.centermostIndexPath.section
if abs(currentIndex-index) <= self.numberOfItems/2 {
return IndexPath(item: index, section: currentSection)
} else if (index-currentIndex >= 0) {
return IndexPath(item: index, section: currentSection-1)
} else {
return IndexPath(item: index, section: currentSection+1)
}
}
}
| mit | 90a1522b9fcff0f6590c1bfb67839169 | 39.19646 | 201 | 0.666197 | 5.331221 | false | false | false | false |
citysite102/kapi-kaffeine | kapi-kaffeine/kapi-kaffeine/KPMainListCellFeatureContainer.swift | 1 | 3244 | //
// KPMainListCellFeatureView.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/4/11.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import UIKit
class KPMainListCellFeatureContainer: UIView {
let maximumTagCount: Int = UIDevice().isSuperCompact ? 2 : 3
var container: UIView!
var tagViews: [UIView] = []
var featureContents:Array<String>! {
didSet {
for subView in self.tagViews {
subView.removeAllRelatedConstraintsInSuperView()
subView.removeFromSuperview()
}
self.tagViews.removeAll()
for (index, content) in featureContents.enumerated() {
let addedTagView = UIView()
let addedTagLabel = UILabel()
self.container.addSubview(addedTagView)
addedTagView.layer.cornerRadius = 10.0
addedTagView.layer.borderWidth = 1.0
addedTagView.layer.borderColor = KPColorPalette.KPMainColor.mainColor_light?.cgColor
if index < maximumTagCount {
if index == 0 {
if index == featureContents.count-1 {
addedTagView.addConstraints(fromStringArray:
["V:|[$self(20)]|", "H:|[$self]|"])
} else {
addedTagView.addConstraints(fromStringArray:
["V:|[$self(20)]|", "H:|[$self]"])
}
} else if index == maximumTagCount-1 {
addedTagView.addConstraints(fromStringArray:
["V:|[$self(20)]|", "H:[$view0]-4-[$self]|"],
views: [self.tagViews[index-1]])
} else {
addedTagView.addConstraints(fromStringArray:
["V:|[$self(20)]|", "H:[$view0]-4-[$self]"],
views: [self.tagViews[index-1]])
}
addedTagLabel.font = UIFont.systemFont(ofSize: 10.0)
addedTagLabel.textColor = KPColorPalette.KPTextColor.mainColor_light
addedTagLabel.text = content
addedTagView.addSubview(addedTagLabel)
addedTagLabel.addConstraintForCenterAligningToSuperview(in: .vertical)
addedTagLabel.addConstraints(fromStringArray:
["H:|-4-[$self]-4-|"])
self.tagViews.append(addedTagView)
}
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.container = UIView()
self.addSubview(self.container)
self.container.addConstraints(fromStringArray: ["V:|[$self]|",
"H:|[$self]|"])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | ed53088eb277a2dfb84d340864dc9c36 | 37.129412 | 100 | 0.472694 | 5.656195 | false | false | false | false |
jopamer/swift | benchmark/utils/DriverUtils.swift | 1 | 15426 | //===--- DriverUtils.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
//
//===----------------------------------------------------------------------===//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import TestsUtils
struct BenchResults {
let sampleCount, min, max, mean, sd, median, maxRSS: UInt64
}
public var registeredBenchmarks: [BenchmarkInfo] = []
enum TestAction {
case run
case listTests
}
struct TestConfig {
/// The delimiter to use when printing output.
let delim: String
/// Duration of the test measurement in seconds.
///
/// Used to compute the number of iterations, if no fixed amount is specified.
/// This is useful when one wishes for a test to run for a
/// longer amount of time to perform performance analysis on the test in
/// instruments.
let sampleTime: Double
/// If we are asked to have a fixed number of iterations, the number of fixed
/// iterations. The default value of 0 means: automatically compute the
/// number of iterations to measure the test for a specified sample time.
let fixedNumIters: UInt
/// The number of samples we should take of each test.
let numSamples: Int
/// Is verbose output enabled?
let verbose: Bool
// Should we log the test's memory usage?
let logMemory: Bool
/// After we run the tests, should the harness sleep to allow for utilities
/// like leaks that require a PID to run on the test harness.
let afterRunSleep: Int?
/// The list of tests to run.
let tests: [(index: String, info: BenchmarkInfo)]
let action: TestAction
init(_ registeredBenchmarks: [BenchmarkInfo]) {
struct PartialTestConfig {
var delim: String?
var tags, skipTags: Set<BenchmarkCategory>?
var numSamples, afterRunSleep: Int?
var fixedNumIters: UInt?
var sampleTime: Double?
var verbose: Bool?
var logMemory: Bool?
var action: TestAction?
var tests: [String]?
}
// Custom value type parsers
func tags(tags: String) throws -> Set<BenchmarkCategory> {
// We support specifying multiple tags by splitting on comma, i.e.:
// --tags=Array,Dictionary
// --skip-tags=Array,Set,unstable,skip
return Set(
try tags.split(separator: ",").map(String.init).map {
try checked({ BenchmarkCategory(rawValue: $0) }, $0) })
}
func finiteDouble(value: String) -> Double? {
return Double(value).flatMap { $0.isFinite ? $0 : nil }
}
// Configure the command line argument parser
let p = ArgumentParser(into: PartialTestConfig())
p.addArgument("--num-samples", \.numSamples,
help: "number of samples to take per benchmark; default: 1",
parser: { Int($0) })
p.addArgument("--num-iters", \.fixedNumIters,
help: "number of iterations averaged in the sample;\n" +
"default: auto-scaled to measure for `sample-time`",
parser: { UInt($0) })
p.addArgument("--sample-time", \.sampleTime,
help: "duration of test measurement in seconds\ndefault: 1",
parser: finiteDouble)
p.addArgument("--verbose", \.verbose, defaultValue: true,
help: "increase output verbosity")
p.addArgument("--memory", \.logMemory, defaultValue: true,
help: "log the change in maximum resident set size (MAX_RSS)")
p.addArgument("--delim", \.delim,
help:"value delimiter used for log output; default: ,",
parser: { $0 })
p.addArgument("--tags", \PartialTestConfig.tags,
help: "run tests matching all the specified categories",
parser: tags)
p.addArgument("--skip-tags", \PartialTestConfig.skipTags, defaultValue: [],
help: "don't run tests matching any of the specified\n" +
"categories; default: unstable,skip",
parser: tags)
p.addArgument("--sleep", \.afterRunSleep,
help: "number of seconds to sleep after benchmarking",
parser: { Int($0) })
p.addArgument("--list", \.action, defaultValue: .listTests,
help: "don't run the tests, just log the list of test \n" +
"numbers, names and tags (respects specified filters)")
p.addArgument(nil, \.tests) // positional arguments
let c = p.parse()
// Configure from the command line arguments, filling in the defaults.
delim = c.delim ?? ","
sampleTime = c.sampleTime ?? 1.0
fixedNumIters = c.fixedNumIters ?? 0
numSamples = c.numSamples ?? 1
verbose = c.verbose ?? false
logMemory = c.logMemory ?? false
afterRunSleep = c.afterRunSleep
action = c.action ?? .run
tests = TestConfig.filterTests(registeredBenchmarks,
specifiedTests: Set(c.tests ?? []),
tags: c.tags ?? [],
skipTags: c.skipTags ?? [.unstable, .skip])
if logMemory && tests.count > 1 {
print(
"""
warning: The memory usage of a test, reported as the change in MAX_RSS,
is based on measuring the peak memory used by the whole process.
These results are meaningful only when running a single test,
not in the batch mode!
""")
}
if verbose {
let testList = tests.map({ $0.1.name }).joined(separator: ", ")
print("""
--- CONFIG ---
NumSamples: \(numSamples)
Verbose: \(verbose)
LogMemory: \(logMemory)
SampleTime: \(sampleTime)
FixedIters: \(fixedNumIters)
Tests Filter: \(c.tests ?? [])
Tests to run: \(testList)
--- DATA ---\n
""")
}
}
/// Returns the list of tests to run.
///
/// - Parameters:
/// - registeredBenchmarks: List of all performance tests to be filtered.
/// - specifiedTests: List of explicitly specified tests to run. These can be
/// specified either by a test name or a test number.
/// - tags: Run tests tagged with all of these categories.
/// - skipTags: Don't run tests tagged with any of these categories.
/// - Returns: An array of test number and benchmark info tuples satisfying
/// specified filtering conditions.
static func filterTests(
_ registeredBenchmarks: [BenchmarkInfo],
specifiedTests: Set<String>,
tags: Set<BenchmarkCategory>,
skipTags: Set<BenchmarkCategory>
) -> [(index: String, info: BenchmarkInfo)] {
let allTests = registeredBenchmarks.sorted()
let indices = Dictionary(uniqueKeysWithValues:
zip(allTests.map { $0.name },
(1...).lazy.map { String($0) } ))
func byTags(b: BenchmarkInfo) -> Bool {
return b.tags.isSuperset(of: tags) &&
b.tags.isDisjoint(with: skipTags)
}
func byNamesOrIndices(b: BenchmarkInfo) -> Bool {
return specifiedTests.contains(b.name) ||
specifiedTests.contains(indices[b.name]!)
} // !! "`allTests` have been assigned an index"
return allTests
.filter(specifiedTests.isEmpty ? byTags : byNamesOrIndices)
.map { (index: indices[$0.name]!, info: $0) }
}
}
func internalMeanSD(_ inputs: [UInt64]) -> (UInt64, UInt64) {
// If we are empty, return 0, 0.
if inputs.isEmpty {
return (0, 0)
}
// If we have one element, return elt, 0.
if inputs.count == 1 {
return (inputs[0], 0)
}
// Ok, we have 2 elements.
var sum1: UInt64 = 0
var sum2: UInt64 = 0
for i in inputs {
sum1 += i
}
let mean: UInt64 = sum1 / UInt64(inputs.count)
for i in inputs {
sum2 = sum2 &+ UInt64((Int64(i) &- Int64(mean))&*(Int64(i) &- Int64(mean)))
}
return (mean, UInt64(sqrt(Double(sum2)/(Double(inputs.count) - 1))))
}
func internalMedian(_ inputs: [UInt64]) -> UInt64 {
return inputs.sorted()[inputs.count / 2]
}
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
@_silgen_name("_swift_leaks_startTrackingObjects")
func startTrackingObjects(_: UnsafePointer<CChar>) -> ()
@_silgen_name("_swift_leaks_stopTrackingObjects")
func stopTrackingObjects(_: UnsafePointer<CChar>) -> Int
#endif
#if os(Linux)
class Timer {
typealias TimeT = timespec
func getTime() -> TimeT {
var ticks = timespec(tv_sec: 0, tv_nsec: 0)
clock_gettime(CLOCK_REALTIME, &ticks)
return ticks
}
func diffTimeInNanoSeconds(from start_ticks: TimeT, to end_ticks: TimeT) -> UInt64 {
var elapsed_ticks = timespec(tv_sec: 0, tv_nsec: 0)
if end_ticks.tv_nsec - start_ticks.tv_nsec < 0 {
elapsed_ticks.tv_sec = end_ticks.tv_sec - start_ticks.tv_sec - 1
elapsed_ticks.tv_nsec = end_ticks.tv_nsec - start_ticks.tv_nsec + 1000000000
} else {
elapsed_ticks.tv_sec = end_ticks.tv_sec - start_ticks.tv_sec
elapsed_ticks.tv_nsec = end_ticks.tv_nsec - start_ticks.tv_nsec
}
return UInt64(elapsed_ticks.tv_sec) * UInt64(1000000000) + UInt64(elapsed_ticks.tv_nsec)
}
}
#else
class Timer {
typealias TimeT = UInt64
var info = mach_timebase_info_data_t(numer: 0, denom: 0)
init() {
mach_timebase_info(&info)
}
func getTime() -> TimeT {
return mach_absolute_time()
}
func diffTimeInNanoSeconds(from start_ticks: TimeT, to end_ticks: TimeT) -> UInt64 {
let elapsed_ticks = end_ticks - start_ticks
return elapsed_ticks * UInt64(info.numer) / UInt64(info.denom)
}
}
#endif
class SampleRunner {
let timer = Timer()
let baseline = SampleRunner.getResourceUtilization()
let c: TestConfig
init(_ config: TestConfig) {
self.c = config
}
private static func getResourceUtilization() -> rusage {
var u = rusage(); getrusage(RUSAGE_SELF, &u); return u
}
/// Returns maximum resident set size (MAX_RSS) delta in bytes
func measureMemoryUsage() -> Int {
var current = SampleRunner.getResourceUtilization()
let maxRSS = current.ru_maxrss - baseline.ru_maxrss
if c.verbose {
let pages = maxRSS / sysconf(_SC_PAGESIZE)
func deltaEquation(_ stat: KeyPath<rusage, Int>) -> String {
let b = baseline[keyPath: stat], c = current[keyPath: stat]
return "\(c) - \(b) = \(c - b)"
}
print("""
MAX_RSS \(deltaEquation(\rusage.ru_maxrss)) (\(pages) pages)
ICS \(deltaEquation(\rusage.ru_nivcsw))
VCS \(deltaEquation(\rusage.ru_nvcsw))
""")
}
return maxRSS
}
func run(_ name: String, fn: (Int) -> Void, num_iters: UInt) -> UInt64 {
// Start the timer.
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
name.withCString { p in startTrackingObjects(p) }
#endif
let start_ticks = timer.getTime()
fn(Int(num_iters))
// Stop the timer.
let end_ticks = timer.getTime()
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
name.withCString { p in stopTrackingObjects(p) }
#endif
// Compute the spent time and the scaling factor.
return timer.diffTimeInNanoSeconds(from: start_ticks, to: end_ticks)
}
}
/// Invoke the benchmark entry point and return the run time in milliseconds.
func runBench(_ test: BenchmarkInfo, _ c: TestConfig) -> BenchResults? {
var samples = [UInt64](repeating: 0, count: c.numSamples)
// Before we do anything, check that we actually have a function to
// run. If we don't it is because the benchmark is not supported on
// the platform and we should skip it.
guard let testFn = test.runFunction else {
if c.verbose {
print("Skipping unsupported benchmark \(test.name)!")
}
return nil
}
if c.verbose {
print("Running \(test.name) for \(c.numSamples) samples.")
}
let sampler = SampleRunner(c)
test.setUpFunction?()
for s in 0..<c.numSamples {
let nsPerSecond = 1_000_000_000.0 // nanoseconds
let time_per_sample = UInt64(c.sampleTime * nsPerSecond)
var scale : UInt
var elapsed_time : UInt64 = 0
if c.fixedNumIters == 0 {
elapsed_time = sampler.run(test.name, fn: testFn, num_iters: 1)
if elapsed_time > 0 {
scale = UInt(time_per_sample / elapsed_time)
} else {
if c.verbose {
print(" Warning: elapsed time is 0. This can be safely ignored if the body is empty.")
}
scale = 1
}
} else {
// Compute the scaling factor if a fixed c.fixedNumIters is not specified.
scale = c.fixedNumIters
if scale == 1 {
elapsed_time = sampler.run(test.name, fn: testFn, num_iters: 1)
}
}
// Make integer overflow less likely on platforms where Int is 32 bits wide.
// FIXME: Switch BenchmarkInfo to use Int64 for the iteration scale, or fix
// benchmarks to not let scaling get off the charts.
scale = min(scale, UInt(Int.max) / 10_000)
// Rerun the test with the computed scale factor.
if scale > 1 {
if c.verbose {
print(" Measuring with scale \(scale).")
}
elapsed_time = sampler.run(test.name, fn: testFn, num_iters: scale)
} else {
scale = 1
}
// save result in microseconds or k-ticks
samples[s] = elapsed_time / UInt64(scale) / 1000
if c.verbose {
print(" Sample \(s),\(samples[s])")
}
}
test.tearDownFunction?()
let (mean, sd) = internalMeanSD(samples)
// Return our benchmark results.
return BenchResults(sampleCount: UInt64(samples.count),
min: samples.min()!, max: samples.max()!,
mean: mean, sd: sd, median: internalMedian(samples),
maxRSS: UInt64(sampler.measureMemoryUsage()))
}
/// Execute benchmarks and continuously report the measurement results.
func runBenchmarks(_ c: TestConfig) {
let withUnit = {$0 + "(us)"}
let header = (
["#", "TEST", "SAMPLES"] +
["MIN", "MAX", "MEAN", "SD", "MEDIAN"].map(withUnit)
+ (c.logMemory ? ["MAX_RSS(B)"] : [])
).joined(separator: c.delim)
print(header)
var testCount = 0
func report(_ index: String, _ t: BenchmarkInfo, results: BenchResults?) {
func values(r: BenchResults) -> [String] {
return ([r.sampleCount, r.min, r.max, r.mean, r.sd, r.median] +
(c.logMemory ? [r.maxRSS] : [])).map { String($0) }
}
let benchmarkStats = (
[index, t.name] + (results.map(values) ?? ["Unsupported"])
).joined(separator: c.delim)
print(benchmarkStats)
fflush(stdout)
if (results != nil) {
testCount += 1
}
}
for (index, test) in c.tests {
report(index, test, results:runBench(test, c))
}
print("")
print("Totals\(c.delim)\(testCount)")
}
public func main() {
let config = TestConfig(registeredBenchmarks)
switch (config.action) {
case .listTests:
print("#\(config.delim)Test\(config.delim)[Tags]")
for (index, t) in config.tests {
let testDescription = [String(index), t.name, t.tags.sorted().description]
.joined(separator: config.delim)
print(testDescription)
}
case .run:
runBenchmarks(config)
if let x = config.afterRunSleep {
sleep(UInt32(x))
}
}
}
| apache-2.0 | a40d4a218cadcd0d8b03cd96d97807e8 | 32.174194 | 99 | 0.615908 | 3.974749 | false | true | false | false |
admkopec/BetaOS | Kernel/Swift Extensions/Frameworks/Networking/Networking/UDP.swift | 1 | 1049 | //
// UDP.swift
// Networking
//
// Created by Adam Kopeć on 3/3/18.
// Copyright © 2018 Adam Kopeć. All rights reserved.
//
public struct UDP {
let networkDevice: NetworkModule
public init(device: NetworkModule) {
networkDevice = device
}
public func send(data: UnsafeRawPointer, length: Int, sourcePort: Int, destinationPort: Int, destinationIP: IPv4) {
let packet = UnsafeMutablePointer<UDPPacket>(OpaquePointer(malloc(MemoryLayout<UDPPacket>.size + length)))!
memcpy(packet.advanced(by: 1), data, length)
packet.pointee.sourcePort = UInt16(htons_(Int16(sourcePort)))
packet.pointee.destinationPort = UInt16(htons_(Int16(destinationPort)))
packet.pointee.length = UInt16(htons_(Int16(MemoryLayout<UDPPacket>.size + length)))
packet.pointee.checksum = 0
networkDevice.ip.send(data: packet, length: length + MemoryLayout<UDPPacket>.size, IP: destinationIP, proto: 17, offloading: 0)
UnsafeRawPointer(packet).deallocate()
}
}
| apache-2.0 | 3c38764cb191707ff5614c28515050cb | 37.740741 | 135 | 0.680688 | 3.94717 | false | false | false | false |
huonw/swift | validation-test/compiler_crashers_fixed/01161-getselftypeforcontainer.swift | 65 | 1213 | // 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
// RUN: not %target-swift-frontend %s -typecheck
protocol b {
func a<d>() -> [c<d>] {
}
var _ = i() {
}
func c<d {
enum c {
}
}
protocol A {
}
struct B<T : A> {
}
protocol C {
}
struct D : C {
func g<T where T.E == F>(f: B<T>) {
}
}
func some<S: Sequence, T where Optional<T> == S.Iterator.Element>(xs : S) -> T? {
for (mx : T?) in xs {
if let x = mx {
}
}
}
protocol a {
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
}
var f1: Int -> Int = {
}
let succeeds: Int = { (x: Int, f: Int -> Int) -> Int in
}(x1, f1)
let crashes: Int = { x, f in
}(x1, f1)
func f() {
}
protocol a {
}
class b: a {
}
protocol A {
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
class A<T : A> {
}
class c {
func b((Any, c))(a: (Any, AnyObject)) {
}
}
func a<T>() {
enum b {
}
}
protocol c : b { func b
| apache-2.0 | d8951471d91eca81a882b5850d9c5d83 | 15.391892 | 81 | 0.582852 | 2.485656 | false | false | false | false |
tedvb/Looking-Glass | Looking Glass/Looking Glass/LGModifiedHaarFilter.swift | 1 | 4024 | //
// LGFilter.swift
// Looking Glass
//
// Created by Ted von Bevern on 6/28/14.
// Copyright (c) 2014 Ted von Bevern. All rights reserved.
//
import Foundation
class LGModifiedHaarFilter {
let inputData: LGSeries
var outputData: LGSeries
let conservesEnergy: Bool
var trendArrays: [LGSeries]
var deviationArrays: [LGSeries]
var deviationCoefficients: [Double]
init(inputSeries inSeries: LGSeries) {
inputData = inSeries
conservesEnergy = false
trendArrays = [LGSeries]()
deviationArrays = [LGSeries]()
deviationCoefficients = [Double]()
outputData = LGSeries()
}
//returns true if computation successful, false otherwise
func compute() -> (success: Bool, message: String) {
if inputData.count < 2 {
return (false, "Too few points")
}
else if log2(Double(inputData.count)) % 1 != 0 {
return (false, "Number of points not a power of 2")
}
var newDecomposition = decompose(inputData)
trendArrays.append(newDecomposition.trend)
deviationArrays.append(newDecomposition.deviations)
deviationCoefficients.append(1.0)
while trendArrays[trendArrays.count - 1].count > 2 {
newDecomposition = decompose(trendArrays[trendArrays.count - 1])
trendArrays.append(newDecomposition.trend)
deviationArrays.append(newDecomposition.deviations)
deviationCoefficients.append(1.0)
}
//outputData = trendArrays[3]
return (true, "Computation successful")
}
func decompose(input:LGSeries) -> (trend: LGSeries, deviations:LGSeries) {
var s = LGSeries()
var d = LGSeries()
for var i = 0; i < input.count; i=i+2 {
var newX = (input[i].x + input[i+1].x) / 2
var newSY = (input[i].y + input[i+1].y) / 2
var newDY = (input[i+1].y - input[i].y) / 2
s.append((newX, newSY))
d.append((newX, newDY))
}
return (s, d)
}
func synthesize() -> (success: Bool, message: String) {
outputData = trendArrays[trendArrays.count - 1]
//println("outputData.count = \(outputData.count)")
for var i = deviationArrays.count - 1; i >= 0; --i {
//for var i = deviationArrays.count - 1; i >= deviationArrays.count - 3; --i {
var deviations = deviationArrays[i]
var deviationCoefficient = deviationCoefficients[i]
//println("\n\(deviations.count):")
for var j = 0; j < deviations.count; ++j {
let x = 0.0
let seriesY = outputData[j*2].y
let adjustedDeviation = deviations[j].y * deviationCoefficient
var y = seriesY - adjustedDeviation
outputData.insert((x, y), atIndex: j*2)
y = seriesY + adjustedDeviation
//outputData.insert((x, y), atIndex: j*2+1)
outputData[j*2+1] = (x, y)
//println("outputData.count = \(outputData.count)")
}
/*
//println("OutputData.count = \(outputData.count)")
//for p in 0..(outputData.count-1) {
var correctSeries = trendArrays[i-1]
println("correctSeries.count = \(correctSeries.count), outputData.count = \(outputData.count)")
for var p = 0; p < outputData.count; ++p {
println("\(correctSeries[p].y), \(outputData[p].y)")
}*/
}
if inputData.count != outputData.count {
return (false, "Synthesized series incorrect length")
}
for var i = 0; i < outputData.count; ++i {
outputData[i].x = inputData[i].x
}
return (true, "Synthesis successful")
}
}
| mit | 0c10440ceab77420c867a900be861af2 | 33.101695 | 107 | 0.541501 | 4.161324 | false | false | false | false |
luzefeng/iOS8-day-by-day | 19-core-image-kernels/FilterBuilder/FilterBuilder/SobelFilter.swift | 21 | 2155 | //
// 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 CoreImage
class SobelFilter: CIFilter {
// MARK: - Properties
var kernel: CIKernel?
var inputImage: CIImage?
// MARK: - Initialization
override init() {
super.init()
kernel = createKernel()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
kernel = createKernel()
}
// MARK: - API
override var outputImage : CIImage! {
if let inputImage = inputImage,
let kernel = kernel {
let args = [inputImage as AnyObject]
let dod = inputImage.extent().rectByInsetting(dx: -1, dy: -1)
return kernel.applyWithExtent(dod, roiCallback: {
(index, rect) in
return rect.rectByInsetting(dx: -1, dy: -1)
}, arguments: args)
}
return nil
}
// MARK: - Utility methods
private func createKernel() -> CIKernel {
let kernelString =
"kernel vec4 sobel (sampler image) {\n" +
" mat3 sobel_x = mat3( -1, -2, -1, 0, 0, 0, 1, 2, 1 );\n" +
" mat3 sobel_y = mat3( 1, 0, -1, 2, 0, -2, 1, 0, -1 );\n" +
" float s_x = 0.0;\n" +
" float s_y = 0.0;\n" +
" vec2 dc = destCoord();\n" +
" for (int i=-1; i <= 1; i++) {\n" +
" for (int j=-1; j <= 1; j++) {\n" +
" vec4 currentSample = sample(image, samplerTransform(image, dc + vec2(i,j)));" +
" s_x += sobel_x[j+1][i+1] * currentSample.g;\n" +
" s_y += sobel_y[j+1][i+1] * currentSample.g;\n" +
" }\n" +
" }\n" +
" return vec4(s_x, s_y, 0.0, 1.0);\n" +
"}"
return CIKernel(string: kernelString)
}
}
| apache-2.0 | e1c3b52b07452f61ecb4f8ebc864b0c4 | 29.785714 | 90 | 0.591183 | 3.216418 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Model/LinearEquations/Solution/Items/MLinearEquationsSolutionEquationItemPolynomialDivision.swift | 1 | 7738 | import UIKit
class MLinearEquationsSolutionEquationItemPolynomialDivision:MLinearEquationsSolutionEquationItemPolynomial
{
let stringDividend:NSAttributedString
let stringDivisor:NSAttributedString
let stringSign:String
let signWidth:CGFloat
let imageSign:UIImage?
let kBorderHeight:CGFloat = 1
let kLabelHeight:CGFloat = 15
private let drawingOptions:NSStringDrawingOptions
private let kMaxSignWidth:CGFloat = 20
private let kFontSize:CGFloat = 12
private let kMaxStringWidth:CGFloat = 5000
private let kMaxStringHeight:CGFloat = 20
private let kShowAsDivision:Bool = true
private let kAdd:String = "+"
private let kSubstract:String = "-"
private let kDivision:String = "/"
private let kEmpty:String = ""
init(
indeterminate:MLinearEquationsSolutionIndeterminatesItem,
coefficientDividend:Double,
coefficientDivisor:Double,
showSign:Bool)
{
drawingOptions = NSStringDrawingOptions([
NSStringDrawingOptions.usesLineFragmentOrigin,
NSStringDrawingOptions.usesFontLeading])
let absoluteDividend:Double = abs(coefficientDividend)
let attributes:[String:AnyObject] = [
NSFontAttributeName:UIFont.numericBold(size:kFontSize)]
let maxSize:CGSize = CGSize(
width:kMaxStringWidth,
height:kMaxStringHeight)
let rawStringDivisor:String = MSession.sharedInstance.stringFrom(
number:coefficientDivisor)
let attributedIndeterminate:NSAttributedString = NSAttributedString(
string:indeterminate.symbol,
attributes:attributes)
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
if absoluteDividend != 1
{
let rawStringDividend:String = MSession.sharedInstance.stringFrom(
number:absoluteDividend)
let attributedDividend:NSAttributedString = NSAttributedString(
string:rawStringDividend,
attributes:attributes)
mutableString.append(attributedDividend)
}
mutableString.append(attributedIndeterminate)
stringDividend = mutableString
stringDivisor = NSAttributedString(
string:rawStringDivisor,
attributes:attributes)
let stringDividendRect:CGRect = stringDividend.boundingRect(
with:maxSize,
options:drawingOptions,
context:nil)
let stringDivisorRect:CGRect = stringDivisor.boundingRect(
with:maxSize,
options:drawingOptions,
context:nil)
let textDividendWidth:CGFloat = ceil(stringDividendRect.size.width)
let textDivisorWidth:CGFloat = ceil(stringDivisorRect.size.width)
let textMaxWidth:CGFloat = max(textDividendWidth, textDivisorWidth)
let reusableIdentifier:String = VLinearEquationsSolutionCellPolynomialDivision.reusableIdentifier
if showSign
{
signWidth = kMaxSignWidth
if coefficientDividend >= 0
{
imageSign = #imageLiteral(resourceName: "assetGenericColAddSmall")
stringSign = kAdd
}
else
{
imageSign = #imageLiteral(resourceName: "assetGenericColSubstractSmall")
stringSign = kSubstract
}
}
else
{
signWidth = 0
imageSign = nil
stringSign = kEmpty
}
let cellWidth:CGFloat = textMaxWidth + signWidth
super.init(
indeterminate:indeterminate,
coefficientDividend:coefficientDividend,
coefficientDivisor:coefficientDivisor,
showSign:showSign,
showAsDivision:kShowAsDivision,
reusableIdentifier:reusableIdentifier,
cellWidth:cellWidth)
}
override func shareText() -> String?
{
let mutableString:NSMutableString = NSMutableString()
mutableString.append(stringSign)
mutableString.append(stringDividend.string)
mutableString.append(kDivision)
mutableString.append(stringDivisor.string)
let string:String = mutableString as String
return string
}
override func drawInRect(rect:CGRect)
{
let rectX:CGFloat = rect.origin.x
let rectY:CGFloat = rect.origin.y
let rectWidth:CGFloat = rect.size.width
let rectHeight:CGFloat = rect.size.height
let rectHeight_2:CGFloat = rectHeight / 2.0
let rectCenterY:CGFloat = rectY + rectHeight_2
if let imageSign:UIImage = self.imageSign
{
let imageWidth:CGFloat = imageSign.size.width
let imageHeight:CGFloat = imageSign.size.height
let imageRemainX:CGFloat = signWidth - imageWidth
let imageRemainY:CGFloat = rectHeight - imageHeight
let imageMarginX:CGFloat = imageRemainX / 2.0
let imageMarginY:CGFloat = imageRemainY / 2.0
let imageRect:CGRect = CGRect(
x:rectX + imageMarginX,
y:rectY + imageMarginY,
width:imageWidth,
height:imageHeight)
imageSign.draw(in:imageRect)
}
let stringPossibleWidth:CGFloat = rectWidth - signWidth
let dividendRect:CGRect = stringDividend.boundingRect(
with:rect.size,
options:drawingOptions,
context:nil)
let maxDividendWidth:CGFloat = ceil(dividendRect.width)
let dividendRemainWidth:CGFloat = stringPossibleWidth - maxDividendWidth
let dividendMarginLeft:CGFloat = dividendRemainWidth / 2.0
let stringDividendTop:CGFloat = (rectCenterY + kBorderHeight) - kLabelHeight
let stringDividendLeft:CGFloat = rectX + dividendMarginLeft + signWidth
let stringDividendRect:CGRect = CGRect(
x:stringDividendLeft,
y:stringDividendTop,
width:maxDividendWidth,
height:kLabelHeight)
stringDividend.draw(in:stringDividendRect)
let divisorRect:CGRect = stringDivisor.boundingRect(
with:rect.size,
options:drawingOptions,
context:nil)
let maxDivisorWidth:CGFloat = ceil(divisorRect.width)
let divisorRemainWidth:CGFloat = stringPossibleWidth - maxDivisorWidth
let divisorMarginLeft:CGFloat = divisorRemainWidth / 2.0
let stringDivisorTop:CGFloat = rectCenterY - kBorderHeight
let stringDivisorLeft:CGFloat = rectX + divisorMarginLeft + signWidth
let stringDivisorRect:CGRect = CGRect(
x:stringDivisorLeft,
y:stringDivisorTop,
width:maxDivisorWidth,
height:kLabelHeight)
stringDivisor.draw(in:stringDivisorRect)
guard
let context:CGContext = UIGraphicsGetCurrentContext()
else
{
return
}
let borderLeft:CGFloat = rectX + signWidth
let borderWidth:CGFloat = rectWidth - signWidth
let borderRemain:CGFloat = rectHeight - kBorderHeight
let borderTop:CGFloat = borderRemain / 2.0
let borderRect:CGRect = CGRect(
x:borderLeft,
y:borderTop + rectY,
width:borderWidth,
height:kBorderHeight)
context.setFillColor(UIColor(white:0, alpha:0.3).cgColor)
context.fill(borderRect)
}
}
| mit | 1c5e2e70bad787a58386847f4d2f327d | 36.201923 | 107 | 0.631042 | 5.30727 | false | false | false | false |
playbasis/native-sdk-ios | PlaybasisSDK/Classes/PBModel/PBApiResponse.swift | 1 | 4351 | //
// ApiResponse.swift
// Idea
//
// Created by Médéric Petit on 4/20/2559 BE.
// Copyright © 2559 playbasis. All rights reserved.
//
import Alamofire
import ObjectMapper
public typealias PBFailureErrorBlock = (error:PBError) -> Void
public typealias PBEmptyCompletionBlock = () -> Void
typealias PBAuthenticationCompletionBlock = (authenticationToken:PBAuthenticationToken) -> Void
public typealias PBPlayerCompletionBlock = (player:PBPlayer) -> Void
public typealias PBPlayerCustomFieldsCompletionBlock = (customFields:[String:String]) -> Void
public typealias PBPlayerAuthCompletionBlock = (playerId:String) -> Void
public typealias PBPlayerBadgesCompletionBlock = ([PBBadge]) -> Void
public typealias PBQuestCompletionBlock = (PBQuest) -> Void
public typealias PBQuestsCompletionBlock = ([PBQuest]) -> Void
public typealias PBGoodsCompletionBlock = ([PBRewardData]) -> Void
public typealias PBRewardsCompletionBlock = ([PBReward]) -> Void
public typealias PBPointsCompletionBlock = ([PBPoint]) -> Void
public typealias PBLeaderBoardCompletionBlock = (leadearBoard:[PBLeaderBoard], playerData:PBLeaderBoard?) -> Void
public typealias PBContentCompletionBlock = ([PBContent]) -> Void
public typealias PBRanksCompletionBlock = ([PBRank]) -> Void
public typealias PBActionReportsCompletionBlock = ([PBActionReport]) -> Void
public typealias PBRuleCompletionBlock = (PBRule) -> Void
public typealias PBRulesCompletionBlock = ([PBRule]) -> Void
public typealias PBAvailableRedeemPlacesCompletionBlock = (redeemPlaces:[PBRedeemPlace]) -> Void
public typealias PBReferralCodeCompletionBlock = (code:String) -> Void
public typealias PBLinkCompletionBlock = (link:String) -> Void
public typealias PBRecentActivitiesCompletionBlock = (activities:[PBRecentActivity]) -> Void
public typealias PBActionCountCompletionBlock = (actionId:String?, count:Int) -> Void
public typealias PBAppStatusCompletionBlock = (appStatus:Bool, appPeriod:PBAppPeriod?) -> Void
public typealias PBRemainingPointsCompletionBlock = (remainingPoints:[PBRemainingPoint]) -> Void
public typealias PBGameSettingCompletionBlock = (gameSettings:[PBGameSetting]) -> Void
public typealias PBGameRulesCompletionBlock = (gameRules:[PBGameRule]) -> Void
public typealias PBCampaignCompletionBlock = (campaign:PBCampaign) -> Void
public typealias PBCampaignsCompletionBlock = (campaigns:[PBCampaign]) -> Void
/**
Represents a response from the server.
*/
public class PBApiResponse:Mappable {
/// Response JSON parsed into a dictionary, or nil if no JSON in response
private(set) public var parsedJson:AnyObject?
/// Whether the request was successful or not
public var success: Bool = false
/// The raised error, if any
public var apiError:PBError?
/// The message returned
public var message:String = ""
/// The error code
public var errorCode:String = "0000"
// MARK: - Initialisation
init() {
}
required public init?(_ map: Map){}
public func mapping(map: Map) {
success <- map["success"]
message <- map["message"]
parsedJson <- map["response"]
errorCode <- map["error_code"]
self.processError()
}
public convenience init(response:Response<AnyObject, NSError>) {
let jsonResponse = response.result.value as? [String:AnyObject]
if response.result.isFailure {
self.init(nsError: response.result.error!, json: jsonResponse)
}
else if let jsonResponse = jsonResponse {
self.init()
Mapper<PBApiResponse>().map(jsonResponse, toObject: self)
}
else {
print("Failed to get a valid JSON from server")
let nsError = NSError(domain: API_ERROR_DOMAIN, code: -1, userInfo: nil)
self.init(nsError: nsError, json: nil)
}
}
// Private
private init(nsError: NSError, json: [String:AnyObject]?) {
self.success = false
self.message = nsError.localizedDescription
self.errorCode = String(nsError.code)
self.processError()
}
private func processError() {
guard success == false else { return }
self.apiError = PBError(code: errorCode, message: message)
}
}
| mit | c7ca47506ddae150b261c2d6d1606e2c | 30.507246 | 113 | 0.700092 | 4.572029 | false | false | false | false |
spacedrabbit/CatAerisWeatherDemo | CatAerisWeatherDemo/AerisRequestManager.swift | 1 | 2771 | //
// AerisRequestManager.swift
// CatAerisWeatherDemo
//
// Created by Louis Tur on 9/5/16.
// Copyright © 2016 catthoughts. All rights reserved.
//
import Foundation
import UIKit
import Aeris
internal enum AerisRequestState {
case ready, started, inProgress, completed
}
protocol AerisRequestManagerDelegate: class {
func placesRequestDidFinish(_ place: AWFPlace)
func placesRequestDidFailWithError(_ error: NSError)
func forecastRequestDidFinish(_ forecast: AWFForecast, forPlace place: AWFPlace)
func forecastRequestDidFailWithError(_ error: NSError)
}
internal class AerisRequestManager {
internal var currentRequestState: AerisRequestState = .ready
fileprivate var lastRequestedPlace: AWFPlace?
fileprivate var lastRequestedForecastDictionary: [AWFPlace : AWFForecast] = [:]
internal weak var delegate: AerisRequestManagerDelegate?
// TODO: eventually, if the current location is not found, set it to this default
internal var defaultPlace: AWFPlace = AWFPlace(city: "new york", state: "ny", country: "us")
internal var observationLoader: AWFObservationsLoader = AWFObservationsLoader()
internal var forecastLoader: AWFForecastsLoader = AWFForecastsLoader()
internal var placeLoader: AWFPlacesLoader = AWFPlacesLoader()
// singleton
internal static let shared: AerisRequestManager = AerisRequestManager()
fileprivate init () {
}
internal func beginPlaceRequestForCoordinates(_ coordinates: CLLocationCoordinate2D) {
let tempPlaceHolder: AWFPlace = AWFPlace(coordinate: coordinates)
self.placeLoader.getPlace(tempPlaceHolder, options: AWFRequestOptions()) { (places, error) in
if (places?.count)! > 0 {
if let validPlace: AWFPlace = places?.first as? AWFPlace {
self.lastRequestedPlace = validPlace
self.delegate?.placesRequestDidFinish(self.lastRequestedPlace!)
}
}
else {
if error != nil {
self.delegate?.placesRequestDidFailWithError(error as! NSError)
}
}
}
}
internal func beginForecastRequestForPlace(_ place: AWFPlace) {
let requestOptions: AWFRequestOptions = AWFRequestOptions()
requestOptions.periodLimit = 10
requestOptions.fromDate = Date()
self.forecastLoader.getForecastFor(place, options: requestOptions) { (forecast, error) in
if (forecast?.count)! > 0 {
if let forecast: AWFForecast = forecast?.first as? AWFForecast {
self.delegate?.forecastRequestDidFinish(forecast, forPlace: place)
self.lastRequestedForecastDictionary[place] = forecast
}
}
else {
if error != nil {
self.delegate?.forecastRequestDidFailWithError(error as! NSError)
}
}
}
}
}
| mit | bb1fc2b1d1e11c350bc3de57b9b0f98e | 31.97619 | 97 | 0.712996 | 4.307932 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/PaymentSheet/Views/ShadowedRoundedRectangleView.swift | 1 | 2775 | //
// ShadowedRoundedRectangleView.swift
// StripePaymentSheet
//
// Created by Yuki Tokuhiro on 1/28/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import UIKit
@_spi(STP) import StripeUICore
/// The shadowed rounded rectangle that our cells use to display content
/// For internal SDK use only
@objc(STP_Internal_ShadowedRoundedRectangle)
class ShadowedRoundedRectangle: UIView {
let roundedRectangle: UIView
var appearance: PaymentSheet.Appearance {
didSet {
layer.applyShadow(shadow: appearance.asElementsTheme.shadow)
layer.cornerRadius = appearance.cornerRadius
roundedRectangle.layer.cornerRadius = appearance.cornerRadius
roundedRectangle.backgroundColor = appearance.colors.componentBackground
}
}
lazy var shouldDisplayShadow: Bool = true {
didSet {
if shouldDisplayShadow {
layer.applyShadow(shadow: appearance.asElementsTheme.shadow)
} else {
layer.shadowOpacity = 0
}
}
}
var isEnabled: Bool = true {
didSet {
updateBackgroundColor()
}
}
private func updateBackgroundColor() {
if isEnabled {
roundedRectangle.backgroundColor = appearance.colors.componentBackground
} else {
roundedRectangle.backgroundColor = appearance.colors.componentBackground.disabledColor
}
}
required init(appearance: PaymentSheet.Appearance) {
self.appearance = appearance
roundedRectangle = UIView()
roundedRectangle.layer.cornerRadius = appearance.cornerRadius
roundedRectangle.layer.masksToBounds = true
super.init(frame: .zero)
layer.cornerRadius = appearance.cornerRadius
layer.applyShadow(shadow: appearance.asElementsTheme.shadow)
addSubview(roundedRectangle)
updateBackgroundColor()
}
override func layoutSubviews() {
super.layoutSubviews()
// Update shadow paths based on current frame
roundedRectangle.frame = bounds
// Turn off shadows in dark mode
if traitCollection.userInterfaceStyle == .dark || !shouldDisplayShadow {
layer.shadowOpacity = 0
} else {
layer.applyShadow(shadow: appearance.asElementsTheme.shadow)
}
// Update shadow (cg)color
layer.applyShadow(shadow: appearance.asElementsTheme.shadow)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
setNeedsLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | d73f6c79908c713b38ef6ca843e8ae96 | 30.168539 | 98 | 0.665105 | 5.46063 | false | false | false | false |
normand1/DNFlyingBadge | Example/Tests/Tests.swift | 1 | 1093 | // https://github.com/Quick/Quick
import Quick
import Nimble
import DNFlyingBadges
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
| mit | afa83e6a3a076dbe5cdca96285a314fc | 20.74 | 60 | 0.395584 | 5.055814 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.