repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hoomazoid/CTSlidingUpPanel | refs/heads/master | Example/CTSlidingUpPanel/TableViewController.swift | mit | 1 | //
// TableViewController.swift
// CTSlidingUpPanel_Example
//
// Created by Giorgi Andriadze on 1/26/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import UIKit
import CTSlidingUpPanel
class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var bottomController:CTBottomSlideController?;
@IBOutlet weak var parrent: UIView!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
@IBOutlet weak var heightConstr: NSLayoutConstraint!
let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat", "Eagle", "Smeagle", "Dreagle", "Feagle", "Foogo"]
// cell reuse id (cells that scroll out of view can be reused)
let cellReuseIdentifier = "cell"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
bottomController = CTBottomSlideController(topConstraint: topConstraint, heightConstraint: heightConstr, parent: view, bottomView: parrent, tabController: self.tabBarController!, navController: self.navigationController, visibleHeight: 64)
bottomController?.set(table: tableView)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
tableView.delegate = self
tableView.dataSource = self
tableView.setEditing(true, animated: true)
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true;
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:UITableViewCell = (self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier))!
// set the text from the data model
cell.textLabel?.text = self.animals[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 8c232a588956429555bc9bdd68235741 | 34.909091 | 247 | 0.689873 | false | false | false | false |
michaelhayman/OHHTTPStubsExtensions | refs/heads/master | OHHTTPStubsExtensions/Classes/OHHTTPStubs+Extension.swift | mit | 1 | //
// OHHTTPStubs+Extension.swift
//
// Created by Michael Hayman on 2016-05-16.
import UIKit
import OHHTTPStubs
extension OHHTTPStubs {
class func stubURLThatMatchesPattern(regexPattern: String, jsonFileName: String, statusCode: Int, HTTPMethod: String, bundle: NSBundle) -> AnyObject? {
guard let path = bundle.pathForResource(jsonFileName, ofType: "json") else { return nil }
do {
let responseString = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
return self._stubURLThatMatchesPattern(regexPattern, responseString: responseString, statusCode: statusCode, HTTPMethod: HTTPMethod)
} catch {
print("Parse error \(error)")
return nil
}
}
class func _stubURLThatMatchesPattern(regexPattern: String, responseString: String, statusCode: Int, HTTPMethod: String) -> AnyObject? {
var regex: NSRegularExpression
do {
regex = try NSRegularExpression(pattern: regexPattern, options: [])
} catch {
print("Regular expression error \(error)")
return nil
}
return OHHTTPStubs.stubRequestsPassingTest({ request in
if request.HTTPMethod != HTTPMethod {
return false
}
let requestURLString = request.URL?.absoluteString
if regex.firstMatchInString(requestURLString!, options: [], range: NSMakeRange(0, requestURLString!.characters.count)) != nil {
return true
}
return false
}) { (request) -> OHHTTPStubsResponse in
guard let response = responseString.dataUsingEncoding(NSUTF8StringEncoding) else { return OHHTTPStubsResponse() }
let headers = [ "Content-Type": "application/json; charset=utf-8" ]
let statusCode = Int32(statusCode)
if statusCode == 422 || statusCode == 500 {
let error = NSError(domain: NSURLErrorDomain, code: Int(CFNetworkErrors.CFURLErrorCannotLoadFromNetwork.rawValue), userInfo: nil)
return OHHTTPStubsResponse(error: error)
}
return OHHTTPStubsResponse(data: response, statusCode: statusCode, headers: headers)
}
}
}
| 0104abdee12dbaf3265da837a54be811 | 37.508475 | 155 | 0.638204 | false | false | false | false |
Fenrikur/ef-app_ios | refs/heads/master | Domain Model/EurofurenceModelTests/Announcements/AnnouncementAssertion.swift | mit | 1 | import EurofurenceModel
import TestUtilities
class AnnouncementAssertion: Assertion {
func assertOrderedAnnouncements(_ announcements: [Announcement],
characterisedBy characteristics: [AnnouncementCharacteristics]) {
guard announcements.count == characteristics.count else {
fail(message: "Differing amount of expected/actual announcements")
return
}
var orderedCharacteristics = orderAnnouncementsCharacteristicsByDate(characteristics)
for (idx, announcement) in announcements.enumerated() {
let characteristic = orderedCharacteristics[idx]
assertAnnouncement(announcement, characterisedBy: characteristic)
}
}
func assertAnnouncement(_ announcement: Announcement?,
characterisedBy characteristic: AnnouncementCharacteristics) {
assert(announcement?.identifier, isEqualTo: AnnouncementIdentifier(characteristic.identifier))
assert(announcement?.title, isEqualTo: characteristic.title)
assert(announcement?.content, isEqualTo: characteristic.content)
assert(announcement?.date, isEqualTo: characteristic.lastChangedDateTime)
}
private func orderAnnouncementsCharacteristicsByDate(_ characteristics: [AnnouncementCharacteristics]) -> [AnnouncementCharacteristics] {
return characteristics.sorted { (first, second) -> Bool in
return first.lastChangedDateTime.compare(second.lastChangedDateTime) == .orderedDescending
}
}
}
| b015f80b7368a51881c7c48a418d6354 | 43.685714 | 141 | 0.713555 | false | false | false | false |
Kawoou/KWDrawerController | refs/heads/master | DrawerController/Transition/DrawerZoomTransition.swift | mit | 1 | /*
The MIT License (MIT)
Copyright (c) 2017 Kawoou (Jungwon An)
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 DrawerZoomTransition: DrawerTransition {
// MARK: - Public
open override func initTransition(content: DrawerContent) {
super.initTransition(content: content)
content.isBringToFront = false
}
open override func startTransition(content: DrawerContent, side: DrawerSide) {
super.startTransition(content: content, side: side)
content.contentView.transform = .identity
content.contentView.frame = CGRect(
x: content.drawerOffset,
y: 0,
width: CGFloat(content.drawerWidth),
height: content.contentView.frame.height
)
}
open override func endTransition(content: DrawerContent, side: DrawerSide) {
super.endTransition(content: content, side: side)
}
open override func transition(content: DrawerContent, side: DrawerSide, percentage: CGFloat, viewRect: CGRect) {
switch content.drawerSide {
case .left:
let sidePercent = CGFloat(1.3 - (1.0 + percentage) * 0.3)
content.contentView.transform = CGAffineTransform(scaleX: sidePercent, y: sidePercent)
case .right:
let sidePercent = CGFloat(1.3 - (1.0 - percentage) * 0.3)
content.contentView.transform = CGAffineTransform(scaleX: sidePercent, y: sidePercent)
default:
content.contentView.transform = .identity
content.contentView.frame = CGRect(
x: viewRect.width * percentage + content.drawerOffset,
y: viewRect.minY,
width: CGFloat(content.drawerWidth),
height: content.contentView.frame.height
)
}
}
public override init() {
super.init()
}
}
| 2a79dc5e39a60b9e57fffac158858c90 | 35.7375 | 116 | 0.672678 | false | false | false | false |
pecuniabanking/pecunia-client | refs/heads/master | Plugins/Source/PluginWorker.swift | gpl-2.0 | 1 | /**
* Copyright (c) 2015, 2019, Pecunia Project. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; version 2 of the
* License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
// Contains the implementation needed to run JS code.
import Foundation
import WebKit
import AppKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
@objc protocol JSLogger : JSExport {
func logError(_ message: String) -> Void;
func logWarning(_ message: String) -> Void;
func logInfo(_ message: String) -> Void;
func logDebug(_ message: String) -> Void;
func logVerbose(_ message: String) -> Void;
}
internal class UserQueryEntry {
var bankCode: String;
var passwords: String;
var accountNumbers: [String];
var authRequest: AuthRequest;
init(bankCode bank: String, password pw: String, accountNumbers numbers: [String], auth: AuthRequest) {
bankCode = bank;
passwords = pw;
accountNumbers = numbers;
authRequest = auth;
}
};
class WebClient: WebView, WebViewJSExport {
fileprivate var redirecting: Bool = false;
fileprivate var pluginDescription: String = ""; // The plugin description for error messages.
var URL: String {
get {
return mainFrameURL;
}
set {
redirecting = false;
if let url = Foundation.URL(string: newValue) {
mainFrame.load(URLRequest(url: url));
}
}
}
var postURL: String {
get {
return mainFrameURL;
}
set {
redirecting = false;
if let url = Foundation.URL(string: newValue) {
var request = URLRequest(url: url);
request.httpMethod = "POST";
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type");
mainFrame.load(request);
}
}
}
var query: UserQueryEntry?;
var callback: JSValue = JSValue();
var completion: ([BankQueryResult]) -> Void = { (_: [BankQueryResult]) -> Void in }; // Block to call on results arrival.
func doTest() {
redirecting = false;
}
func reportError(_ account: String, _ message: String) {
query!.authRequest.errorOccured = true; // Flag the error in the auth request, so it doesn't store the PIN.
let alert = NSAlert();
alert.messageText = NSString.localizedStringWithFormat(NSLocalizedString("AP1800", comment: "") as NSString,
account, pluginDescription) as String;
alert.informativeText = message;
alert.alertStyle = .warning;
alert.runModal();
}
func resultsArrived(_ results: JSValue) -> Void {
query!.authRequest.finishPasswordEntry();
if let entries = results.toArray() as? [[String: AnyObject]] {
var queryResults: [BankQueryResult] = [];
// Unfortunately, the number format can change within a single set of values, which makes it
// impossible to just have the plugin specify it for us.
for entry in entries {
let queryResult = BankQueryResult();
if let type = entry["isCreditCard"] as? Bool {
queryResult.type = type ? .creditCard : .bankStatement;
}
if let lastSettleDate = entry["lastSettleDate"] as? Date {
queryResult.lastSettleDate = lastSettleDate;
}
if let account = entry["account"] as? String {
queryResult.account = BankAccount.findAccountWithNumber(account, bankCode: query!.bankCode);
if queryResult.type == .creditCard {
queryResult.ccNumber = account;
}
}
// Balance string might contain a currency code (3 letters).
if let value = entry["balance"] as? String, value.count > 0 {
if let number = NSDecimalNumber.fromString(value) { // Returns the value up to the currency code (if any).
queryResult.balance = number;
}
}
let statements = entry["statements"] as! [[String: AnyObject]];
for jsonStatement in statements {
let statement: BankStatement = BankStatement.createTemporary(); // Created in memory context.
if let final = jsonStatement["final"] as? Bool {
statement.isPreliminary = NSNumber(value: !final);
}
if let date = jsonStatement["valutaDate"] as? Date {
statement.valutaDate = date.addingTimeInterval(12 * 3600); // Add 12hrs so we start at noon.
} else {
statement.valutaDate = Date();
}
if let date = jsonStatement["date"] as? Date {
statement.date = date.addingTimeInterval(12 * 3600);
} else {
statement.date = statement.valutaDate;
}
if let purpose = jsonStatement["transactionText"] as? String {
statement.purpose = purpose;
}
if let value = jsonStatement["value"] as? String, value.count > 0 {
// Because there is a setValue function in NSObject we cannot write to the .value
// member in BankStatement. Using a custom setter would make this into a function
// call instead, but that crashes atm.
// Using dictionary access instead for the time being until this is resolved.
if let number = NSDecimalNumber.fromString(value) {
statement.setValue(number, forKey: "value");
} else {
statement.setValue(NSDecimalNumber(value: 0 as Int32), forKey: "value");
}
}
if let value = jsonStatement["originalValue"] as? String, value.count > 0 {
if let number = NSDecimalNumber.fromString(value) {
statement.origValue = number;
}
}
queryResult.statements.append(statement);
}
// Explicitly sort by date, as it might happen that statements have a different
// sorting (e.g. by valuta date).
queryResult.statements.sort(by: { $0.date < $1.date });
queryResults.append(queryResult);
}
completion(queryResults);
}
}
}
class PluginContext : NSObject, WebFrameLoadDelegate, WebUIDelegate {
fileprivate let webClient: WebClient;
fileprivate let workContext: JSContext; // The context on which we run the script.
// WebView's context is recreated on loading a new page,
// stopping so any running JS code.
fileprivate var jsLogger: JSLogger;
fileprivate var debugScript: String = "";
init?(pluginFile: String, logger: JSLogger, hostWindow: NSWindow?) {
jsLogger = logger;
webClient = WebClient();
workContext = JSContext();
super.init();
prepareContext();
do {
let script = try String(contentsOfFile: pluginFile, encoding: String.Encoding.utf8);
let parseResult = workContext.evaluateScript(script);
if parseResult?.toString() != "true" {
logger.logError("Script konnte geladen werden, wurde aber nicht erfolgreich ausgeführt");
return nil;
}
} catch {
logger.logError("Fehler beim Parsen des Scripts");
return nil;
}
setupWebClient(hostWindow);
}
init?(script: String, logger: JSLogger, hostWindow: NSWindow?) {
jsLogger = logger;
webClient = WebClient();
workContext = JSContext();
super.init();
prepareContext();
let parseResult = workContext.evaluateScript(script);
if parseResult?.toString() != "true" {
return nil;
}
setupWebClient(hostWindow);
}
// MARK: - Setup
fileprivate func prepareContext() {
workContext.setObject(false, forKeyedSubscript: "JSError" as (NSCopying & NSObjectProtocol)?);
workContext.exceptionHandler = { workContext, exception in
self.jsLogger.logError((exception?.toString())!);
workContext?.setObject(true, forKeyedSubscript: "JSError" as (NSCopying & NSObjectProtocol)?);
}
workContext.setObject(jsLogger.self, forKeyedSubscript: "logger" as NSCopying & NSObjectProtocol);
webClient.mainFrame.javaScriptContext.setObject(jsLogger.self, forKeyedSubscript: "logger" as NSCopying & NSObjectProtocol);
//webClient.mainFrame.javaScriptContext.setObject(webClient.self, forKeyedSubscript: "webClient" as NSCopying & NSObjectProtocol);
// Export Webkit to the work context, so that plugins can use it to work with data/the DOM
// from the web client.
workContext.setObject(DOMNodeList.self, forKeyedSubscript: "DOMNodeList" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMCSSStyleDeclaration.self, forKeyedSubscript: "DOMCSSStyleDeclaration" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMCSSRuleList.self, forKeyedSubscript: "DOMCSSRuleList" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMNamedNodeMap.self, forKeyedSubscript: "DOMNamedNodeMap" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMNode.self, forKeyedSubscript: "DOMNode" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMAttr.self, forKeyedSubscript: "DOMAttr" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMElement.self, forKeyedSubscript: "DOMElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLCollection.self, forKeyedSubscript: "DOMHTMLCollection" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLElement.self, forKeyedSubscript: "DOMHTMLElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMDocumentType.self, forKeyedSubscript: "DOMDocumentType" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLFormElement.self, forKeyedSubscript: "DOMHTMLFormElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLInputElement.self, forKeyedSubscript: "DOMHTMLInputElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLButtonElement.self, forKeyedSubscript: "DOMHTMLButtonElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLAnchorElement.self, forKeyedSubscript: "DOMHTMLAnchorElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLOptionElement.self, forKeyedSubscript: "DOMHTMLOptionElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLOptionsCollection.self, forKeyedSubscript: "DOMHTMLOptionsCollection" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMHTMLSelectElement.self, forKeyedSubscript: "DOMHTMLSelectElement" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMImplementation.self, forKeyedSubscript: "DOMImplementation" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMStyleSheetList.self, forKeyedSubscript: "DOMStyleSheetList" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMDocumentFragment.self, forKeyedSubscript: "DOMDocumentFragment" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMCharacterData.self, forKeyedSubscript: "DOMCharacterData" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMText.self, forKeyedSubscript: "DOMText" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMComment.self, forKeyedSubscript: "DOMComment" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMCDATASection.self, forKeyedSubscript: "DOMCDATASection" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMProcessingInstruction.self, forKeyedSubscript: "DOMProcessingInstruction" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMEntityReference.self, forKeyedSubscript: "DOMEntityReference" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(DOMDocument.self, forKeyedSubscript: "DOMDocument" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(WebFrame.self, forKeyedSubscript: "WebFrame" as (NSCopying & NSObjectProtocol)?);
workContext.setObject(webClient.self, forKeyedSubscript: "webClient" as NSCopying & NSObjectProtocol);
}
fileprivate func setupWebClient(_ hostWindow: NSWindow?) {
webClient.frameLoadDelegate = self;
webClient.uiDelegate = self;
webClient.preferences.javaScriptCanOpenWindowsAutomatically = true;
webClient.hostWindow = hostWindow;
if hostWindow != nil {
hostWindow!.contentView = webClient;
}
webClient.pluginDescription = workContext.objectForKeyedSubscript("description").toString();
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString");
webClient.applicationNameForUserAgent = "Pecunia/\(version ?? "1.3.3") (Safari)";
}
// MARK: - Plugin Logic
// Allows to add any additional script to the plugin context.
func addScript(_ script: String) {
workContext.evaluateScript(script);
}
// Like addScript but for both contexts. Applied on the webclient context each time
// it is recreated.
func addDebugScript(_ script: String) {
debugScript = script;
workContext.evaluateScript(script);
}
func pluginInfo() -> (name: String, author: String, description: String, homePage: String, license: String, version: String) {
return (
name: workContext.objectForKeyedSubscript("name").toString(),
author: workContext.objectForKeyedSubscript("author").toString(),
description: workContext.objectForKeyedSubscript("description").toString(),
homePage: workContext.objectForKeyedSubscript("homePage").toString(),
license: workContext.objectForKeyedSubscript("license").toString(),
version: workContext.objectForKeyedSubscript("version").toString()
);
}
// Calls the getStatements() plugin function and translates results from JSON to a BankQueryResult list.
func getStatements(_ userId: String, query: UserQueryEntry, fromDate: Date, toDate: Date,
completion: @escaping ([BankQueryResult]) -> Void) -> Void {
let scriptFunction: JSValue = workContext.objectForKeyedSubscript("getStatements");
let pluginId = workContext.objectForKeyedSubscript("name").toString();
if scriptFunction.isUndefined {
jsLogger.logError("Feler: getStatements() wurde in Plugin " + pluginId! + " nicht gefunden");
return;
}
webClient.completion = completion;
webClient.query = query;
if !(scriptFunction.call(withArguments: [userId, query.bankCode, query.passwords, fromDate,
toDate, query.accountNumbers]) != nil) {
jsLogger.logError("Fehler: getStatements() konnte für Plugin " + pluginId! + " nicht gestartet werden");
}
}
func getFunction(_ name: String) -> JSValue {
return workContext.objectForKeyedSubscript(name);
}
// Returns the outer body HTML text.
func getCurrentHTML() -> String {
return webClient.mainFrame.document.body.outerHTML;
}
func canHandle(_ account: String, bankCode: String) -> Bool {
let function = workContext.objectForKeyedSubscript("canHandle");
if (function?.isUndefined)! {
return false;
}
let result = function?.call(withArguments: [account, bankCode]);
if (result?.isBoolean)! {
return result!.toBool();
}
return false;
}
// MARK: - webView delegate methods.
internal func webView(_ sender: WebView!, didStartProvisionalLoadFor frame: WebFrame!) {
jsLogger.logVerbose("(*) Start loading");
webClient.redirecting = false; // Gets set when we get redirected while processing the provisional frame.
}
internal func webView(_ sender: WebView!, didReceiveServerRedirectForProvisionalLoadFor frame: WebFrame!) {
jsLogger.logVerbose("(*) Received server redirect for frame");
}
internal func webView(_ sender: WebView!, didCommitLoadFor frame: WebFrame!) {
jsLogger.logVerbose("(*) Committed load for frame");
}
internal func webView(_ sender: WebView!, willPerformClientRedirectTo URL: URL!,
delay seconds: TimeInterval, fire date: Date!, for frame: WebFrame!) {
jsLogger.logVerbose("(*) Performing client redirection...");
webClient.redirecting = true;
}
internal func webView(_ sender: WebView!, didCreateJavaScriptContext context: JSContext, for forFrame: WebFrame!) {
jsLogger.logVerbose("(*) JS create");
}
internal func webView(_ sender: WebView!, didFinishLoadFor frame: WebFrame!) {
jsLogger.logVerbose("(*) Finished loading frame from URL: " + frame.dataSource!.response.url!.absoluteString);
if webClient.redirecting {
webClient.redirecting = false;
return;
}
if !webClient.callback.isUndefined && !webClient.callback.isNull {
jsLogger.logVerbose("(*) Calling callback...");
webClient.callback.call(withArguments: [false]);
}
}
internal func webView(_ sender: WebView!, willClose frame: WebFrame!) {
jsLogger.logVerbose("(*) Closing frame...");
}
internal func webView(_ sender: WebView!, didFailLoadWithError error: Error!, for frame: WebFrame!) {
jsLogger.logError("(*) Navigation zur Seite schlug fehl. Ursache: \(error.localizedDescription)")
}
internal func webView(_ sender: WebView!, runJavaScriptAlertPanelWithMessage message: String, initiatedBy initiatedByFrame: WebFrame!) {
let alert = NSAlert();
alert.messageText = message;
alert.runModal();
}
}
| d24a89d1c8c2a7a4316758e72cdfe7f9 | 44.852113 | 143 | 0.639175 | false | false | false | false |
z-abouzamzam/DaisyChain | refs/heads/master | DaisyChain/SecondViewController.swift | apache-2.0 | 1 | //
// SecondViewController.swift
// DaisyChain
//
// Created by Kevin Wu on 2/13/16.
// Copyright © 2016 Zafir Abou-Zamzam. All rights reserved.
//
import UIKit
// import mediaplayer
let secondColor = UIColor.blackColor().CGColor
class SecondViewController: UIViewController {
@IBOutlet var Join: UIButton!
@IBOutlet var Host: UIButton!
override func viewDidAppear(animated: Bool) {
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
Host.layer.cornerRadius = 10
Join.layer.cornerRadius = 10
Host.layer.borderWidth = 1
Join.layer.borderWidth = 1
Join.layer.borderColor = secondColor
Host.layer.borderColor = secondColor
}
}
| a7f42a493f58aebc42499e849e9d84f9 | 22.4375 | 60 | 0.662667 | false | false | false | false |
cyrilwei/TCCalendar | refs/heads/master | Sources/TCCalendarMonthTitleView.swift | mit | 1 | //
// TCCalendarMonthTitleView.swift
// TCCalendar
//
// Copyright (c) 2015 Cyril Wei
//
// 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
class TCCalendarMonthTitleView: UICollectionReusableView {
var titleLabel: UILabel!
var separatorLineColor: UIColor = UIColor.blackColor()
var drawSeparatorLine: Bool = true {
didSet {
self.setNeedsDisplay()
}
}
override func prepareForReuse() {
super.prepareForReuse()
self.drawSeparatorLine = true
}
func initialize() {
self.backgroundColor = UIColor.clearColor()
initTitleLabel()
}
private func initTitleLabel() {
titleLabel = UILabel(frame: self.bounds)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(titleLabel)
let views = ["titleLabel": titleLabel]
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[titleLabel]-15-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-18-[titleLabel]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override func drawRect(rect: CGRect) {
guard drawSeparatorLine else { return }
let context = UIGraphicsGetCurrentContext()
CGContextSetAllowsAntialiasing(context, false)
CGContextSetStrokeColorWithColor(context, separatorLineColor.CGColor)
CGContextSetLineWidth(context, 1.0)
CGContextMoveToPoint(context, 0.0, 0.0)
CGContextAddLineToPoint(context, self.bounds.width, 0.0)
CGContextStrokePath(context)
CGContextSetAllowsAntialiasing(context, true)
}
}
extension TCCalendarMonthTitleView {
dynamic func setFont(font: UIFont) {
self.titleLabel?.font = font
}
dynamic func setTextColor(color: UIColor) {
self.titleLabel?.textColor = color
}
dynamic func setSeparatorColor(color: UIColor) {
separatorLineColor = color
}
} | 70ef2f44b0f8076f4c607c63df554ea5 | 32.5 | 176 | 0.69991 | false | false | false | false |
ndagrawal/MovieFeed | refs/heads/master | MovieFeed/CurrentMovieViewController.swift | mit | 1 | //
// CurrentMovieViewController.swift
// MovieFeed
//
// Created by Nilesh Agrawal on 9/17/15.
// Copyright © 2015 Nilesh Agrawal. All rights reserved.
//
import UIKit
class CurrentMovieViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
@IBOutlet weak var currentMoviesCollectionView:UICollectionView!
var currentMoviesArray:[CurrentMovie]=[CurrentMovie]()
var refreshControl:UIRefreshControl!
var tumblrHud:AMTumblrHud = AMTumblrHud()
var errorLabel:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.setUpView()
self.setUpInitialValues()
self.setUpDelegate()
}
func setUpCollectionViewFlowLayout(){
let width:CGFloat = (CGRectGetWidth(view.frame))
let flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
flowLayout.itemSize = CGSizeMake(width,CGRectGetHeight(view.frame)/5)
flowLayout.scrollDirection = UICollectionViewScrollDirection.Vertical
flowLayout.minimumInteritemSpacing = 0.0
flowLayout.minimumLineSpacing = 0.0
currentMoviesCollectionView.setCollectionViewLayout(flowLayout,animated:false)
currentMoviesCollectionView.backgroundColor = UIColor.whiteColor()
}
func setUpNavigationBar(){
self.navigationController?.navigationBar.barTintColor =
UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0)
self.tabBarController?.tabBar.barTintColor = UIColor(red:0.00, green:0.48, blue:1.00, alpha:0.8)
self.tabBarController?.view.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationItem.title = "Movies"
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
}
func setUpLoadingView(){
tumblrHud = AMTumblrHud.init(frame: CGRectMake(100, 100, 55, 20))
tumblrHud.hudColor = UIColor .grayColor()//UIColorFromRGB(0xF1F2F3)
self.view.addSubview(tumblrHud)
tumblrHud.showAnimated(true)
}
func setUpView(){
// self.view.backgroundColor = UIColor.greenColor()
setUpCollectionViewFlowLayout()
setUpNavigationBar()
addRefreshControl()
}
func addErrorView(){
errorLabel = UILabel.init(frame:CGRectMake(0, 0, self.view.frame.size.width, 30))
errorLabel.backgroundColor = UIColor.redColor()
errorLabel.textColor = UIColor.grayColor()
errorLabel.text = "Unable to load"
currentMoviesCollectionView.insertSubview(errorLabel,atIndex:0)
}
func addRefreshControl(){
refreshControl = UIRefreshControl.init()
refreshControl.addTarget(self, action:"setUpInitialValues", forControlEvents:UIControlEvents.ValueChanged)
currentMoviesCollectionView.insertSubview(refreshControl, atIndex: 0)
}
func setUpInitialValues(){
//let clientId = "e2478f1f8c53474cb6a50ef0387f9756"
let requestedURL = NSURL(string:"https://gist.githubusercontent.com/timothy1ee/d1778ca5b944ed974db0/raw/489d812c7ceeec0ac15ab77bf7c47849f2d1eb2b/gistfile1.json")!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(requestedURL, completionHandler: {data, response, error in
// First, make sure we have real data, and handle the error if not.
// (That's a better use of the API contract than checking the error parameter, because the error parameter is not guaranteed to be non-nil in all cases where correct data is received.)
// Use a guard clause to keep the "good path" less indented.
guard let actualData = data else {
// self.responseText.text = "Response status: \(error!.description)"
return
}
do {
// Use do/try/catch to call the new throwing API.
// Use the new OptionSetType syntax, too.
let dataDictionary = try NSJSONSerialization.JSONObjectWithData(actualData, options: [])
print(dataDictionary);
dispatch_async(dispatch_get_main_queue(), {
let movies = dataDictionary["movies"] as! NSArray
for(var i=0;i<movies.count;i++){
let responseDictionary = movies[i] as! NSDictionary
let posters = responseDictionary["posters"] as! NSDictionary
let movieName = responseDictionary["title"] as! String
let movieRating = responseDictionary["mpaa_rating"] as! String
let movieTime = responseDictionary["runtime"] as! Int
let ratings = responseDictionary["ratings"] as!NSDictionary
let moviePercentage=ratings["audience_score"] as! Int
let movieImageURL = posters["original"] as! String
let casts = responseDictionary["abridged_cast"] as! NSArray
let summary = responseDictionary["synopsis"] as! String
var movieCasts:String = String()
for(var k=0;k<casts.count;k++){
let individualCast = casts[k] as! NSDictionary
let actor = individualCast["name"] as! String
movieCasts = movieCasts + actor + " "
}
print("movieImageURL \(movieImageURL) , movieName \(movieName), movieRatings \(movieRating) movieTime \(movieTime) moviePercentage \(moviePercentage) movieCasts \(movieCasts) summary\(summary)")
let currentMovie:CurrentMovie = CurrentMovie.init(movieImageUrl: movieImageURL, movieName: movieName, movieRating: movieRating, movieTime: movieTime, moviePercentage: moviePercentage,movieCasts:movieCasts,movieSummary:summary)
self.currentMoviesArray.append(currentMovie)
}
self.tumblrHud.showAnimated(false)
self.currentMoviesCollectionView.reloadData()
self.refreshControl.endRefreshing()
})
} catch let parseError {
// No need to treat as NSError and call description here, because ErrorTypes are guaranteed to be describable.
NSLog("Response status: \(parseError)")
}
})
task.resume()
}
func setUpDelegate(){
currentMoviesCollectionView.delegate = self;
currentMoviesCollectionView.dataSource = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return currentMoviesArray.count
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
let cell = currentMoviesCollectionView.dequeueReusableCellWithReuseIdentifier("CurrentMovieCollectionViewCell", forIndexPath: indexPath) as!CurrentMoviesCollecitonViewCell
cell.setCurrentMovieCell(currentMoviesArray[indexPath.row])
return cell;
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if(segue.identifier == "currentMovieSegue"){
let currentMovieDetailViewController:CurrentMoviesDetailViewController = segue.destinationViewController as! CurrentMoviesDetailViewController
let cell = sender as! UICollectionViewCell
let indexPath:NSIndexPath = currentMoviesCollectionView.indexPathForCell(cell) as NSIndexPath!
let selectedCurrentMovie:CurrentMovie = currentMoviesArray[indexPath.row]
currentMovieDetailViewController.selectedCurrentMovie = selectedCurrentMovie
}
}
}
| 4dfeb19ec9a7ca9c71308f5393fc31d5 | 48.854651 | 250 | 0.664606 | false | false | false | false |
codeOfRobin/Components-Personal | refs/heads/master | Sources/HeadingContainNode.swift | mit | 1 | //
// HeadingContainNode.swift
// Example
//
// Created by Robin Malhotra on 06/09/17.
// Copyright © 2017 BuildingBlocks. All rights reserved.
//
import AsyncDisplayKit
public class HeadingContainNode: ASCellNode {
let containerNode: ASDisplayNode
let headingNode: HeadingNode
public init(headingText: String, containerNode: ASDisplayNode) {
self.headingNode = HeadingNode(text: headingText)
self.containerNode = containerNode
super.init()
self.automaticallyManagesSubnodes = true
}
public override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
return ASStackLayoutSpec(direction: .vertical, spacing: 6.0, justifyContent: .center, alignItems: .start, children: [headingNode, containerNode])
}
}
class HeadingNode: ASTextCellNode {
static let textAttrs: [NSAttributedStringKey: Any] = [
NSAttributedStringKey.foregroundColor: UIColor(red:0.63, green:0.67, blue:0.69, alpha:1.00),
NSAttributedStringKey.font: UIFont.systemFont(ofSize: 13)
]
init(text: String) {
super.init(attributes: HeadingNode.textAttrs, insets: .zero)
self.text = text
}
}
| a97aa81dcf5a306557fe0c6fc0855bf1 | 28.315789 | 147 | 0.758528 | false | false | false | false |
TabletopAssistant/DiceKit | refs/heads/master | DiceKit/MultiplicationExpressionResult.swift | apache-2.0 | 1 | //
// MultiplicationExpressionResult.swift
// DiceKit
//
// Created by Brentley Jones on 7/18/15.
// Copyright © 2015 Brentley Jones. All rights reserved.
//
import Foundation
public struct MultiplicationExpressionResult<MultiplierResult: protocol<ExpressionResultType, Equatable>, MultiplicandResult: protocol<ExpressionResultType, Equatable>>: Equatable {
public let multiplierResult: MultiplierResult
public let multiplicandResults: [MultiplicandResult]
public let negateMultiplicandResults: Bool
public init(multiplierResult: MultiplierResult, multiplicandResults: [MultiplicandResult]) {
assert(abs(multiplierResult.resultValue.multiplierEquivalent) == multiplicandResults.count)
self.multiplierResult = multiplierResult
self.multiplicandResults = multiplicandResults
self.negateMultiplicandResults = multiplierResult.resultValue < 0
}
}
// MARK: - CustomStringConvertible
extension MultiplicationExpressionResult: CustomStringConvertible {
public var description: String {
let multiplicandResultsSign = negateMultiplicandResults ? "-" : ""
let multiplicandStrings = multiplicandResults.map { String($0) }
let multiplicandResultsDescription = multiplicandStrings.joinWithSeparator(" + ")
return "((\(multiplierResult)) *> \(multiplicandResultsSign)(\(multiplicandResultsDescription)))"
}
}
// MARK: - CustomDebugStringConvertible
extension MultiplicationExpressionResult: CustomDebugStringConvertible {
public var debugDescription: String {
let multiplicandResultsSign = negateMultiplicandResults ? "-" : ""
let multiplierResultDebugString = String(reflecting: multiplierResult)
let multiplicandDebugStrings = multiplicandResults.map { String(reflecting: $0) }
let multiplicandResultsDebugDescription = multiplicandDebugStrings.joinWithSeparator(" + ")
return "((\(multiplierResultDebugString)) *> \(multiplicandResultsSign)(\(multiplicandResultsDebugDescription)))"
}
}
// MARK: - Equatable
public func == <M, R>(lhs: MultiplicationExpressionResult<M,R>, rhs: MultiplicationExpressionResult<M,R>) -> Bool {
return lhs.multiplierResult == rhs.multiplierResult && lhs.multiplicandResults == rhs.multiplicandResults
}
// MARK: - ExpressionResultType
extension MultiplicationExpressionResult: ExpressionResultType {
public var resultValue: ExpressionResultValue {
let values = multiplicandResults.map { $0.resultValue }
if negateMultiplicandResults {
return values.reduce(0, combine: -)
} else {
return values.reduce(0, combine: +)
}
}
}
| 1478d8520584a2ee16035ae1baea5236 | 35.824324 | 181 | 0.72844 | false | false | false | false |
OHeroJ/twicebook | refs/heads/master | Sources/App/Controllers/BookController.swift | mit | 1 | //
// BookController.swift
// seesometop
//
// Created by laijihua on 29/08/2017.
//
//
import Foundation
import Vapor
final class BookController: ControllerRoutable {
init(builder: RouteBuilder) {
builder.post("create", handler: create)
builder.put("update", handler: update)
builder.get("/",handler: show)
builder.post("report", handler: report)
builder.get("list", handler: getNewerList)
}
/// 获取最新的书本
func getNewerList(req: Request) throws -> ResponseRepresentable {
let isNewer = req.data["isNew"]?.int ?? 0
var query = try Book.makeQuery().filter(Book.Key.state, .notEquals, 1) // 过滤掉在审核的书籍
if isNewer == 1 {
query = try query.sort(Book.Key.createTime, .descending)
}
return try Book.page(request: req, query: query)
}
func report(request: Request) throws -> ResponseRepresentable {
guard let bookId = request.data[Book.Key.id]?.int else {
return try ApiRes.error(code:1, msg:"miss id")
}
guard let _ = request.data["userId"]?.int else {
return try ApiRes.error(code:2, msg:"miss userId")
}
guard let book = try Book.find(bookId) else {
return try ApiRes.error(code: 3, msg: "not found this book")
}
book.reportCount += 1
try book.save()
return try ApiRes.success(data:["success": true])
}
func show(request: Request)throws -> ResponseRepresentable {
let query = try Book.makeQuery().filter(Book.Key.state, .equals, 2).sort(Book.Key.collectCount, .descending)
return try Book.page(request: request, query: query)
}
func update(request: Request)throws -> ResponseRepresentable {
guard let state = request.data[Book.Key.state]?.int else {
return try ApiRes.error(code: 1, msg: "miss state")
}
/// 暂时不对权限限定
guard let _ = request.data["user_id"]?.int else {
return try ApiRes.error(code: 2, msg: "miss userId")
}
guard let bookId = request.data[Book.Key.id]?.int else {
return try ApiRes.error(code: 3, msg: "miss book id")
}
guard let book = try Book.find(bookId) else {
return try ApiRes.error(code: 4, msg: "not fond book")
}
book.state = state
try book.save()
return try ApiRes.success(data:["book": book])
}
func create(request: Request)throws -> ResponseRepresentable {
guard let userId = request.data["userId"]?.int else {
return try ApiRes.error(code: 7, msg: "userId nil")
}
guard let covers = request.data[Book.Key.covers]?.string else {
return try ApiRes.error(code: 1, msg: "covers error")
}
guard let name = request.data[Book.Key.name]?.string else {
return try ApiRes.error(code: 2, msg: "name error")
}
guard let isbn = request.data[Book.Key.isbn]?.string else {
return try ApiRes.error(code: 3, msg: "isbn error")
}
guard let author = request.data[Book.Key.author]?.string else {
return try ApiRes.error(code: 4, msg: "author error")
}
guard let price = request.data["price"]?.double else {
return try ApiRes.error(code: 5, msg: "price error")
}
guard let categoryId = request.data[Book.Key.classifyId]?.int else {
return try ApiRes.error(code: 6, msg: "categoryI 的 err")
}
guard let detail = request.data[Book.Key.detail]?.string else {
return try ApiRes.error(code: 7, msg: "info error")
}
let doubanPrice = request.data[Book.Key.doubanPrice]?.double ?? price
let doubanGrade = request.data[Book.Key.doubanGrade]?.double ?? 0
let time = Date().toString
let priceUnitId = Identifier(1) // 人民币
let book = Book(covers: covers,
name: name,
isbn: isbn,
author: author,
price: price,
detail: detail,
createTime: time,
priceUnitId: priceUnitId,
classifyId: Identifier(categoryId),
createId: Identifier(userId),
doubanPrice: doubanPrice,
doubanGrade: doubanGrade
)
try book.save()
return try ApiRes.success(data:["res": "ok"])
}
}
| ad0f50fa4163e37ca75e71c01d6bbb49 | 35.637097 | 116 | 0.566806 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/SILGen/concrete_subclass.swift | apache-2.0 | 39 | // RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle %s
class BaseClass<T> {
func inAndOut(_ t: T) -> T { return t }
var property: T
init(_ t: T) {
self.property = t
}
}
class DerivedClass : BaseClass<(Int, Int)> {
override func inAndOut(_ t: (Int, Int)) -> (Int, Int) {
let fn = super.inAndOut
return fn(t)
}
override var property: (Int, Int) {
get {
return super.property
}
set {
super.property = newValue
}
}
override init(_ t: (Int, Int)) {
super.init(t)
}
}
let d = DerivedClass((1, 2))
_ = d.inAndOut((1, 2))
let value = d.property
d.property = value
d.property.0 += 1
| 5b271ae0dd31e493f75328a142feef39 | 16.210526 | 62 | 0.574924 | false | false | false | false |
raymondshadow/SwiftDemo | refs/heads/master | SwiftApp/StudyNote/StudyNote/ScrollView/SNWateFlowViewController.swift | apache-2.0 | 1 | //
// SNWateFlowViewController.swift
// StudyNote
//
// Created by wuyp on 2020/5/29.
// Copyright © 2020 Raymond. All rights reserved.
//
import UIKit
class SNWateFlowViewController: UIViewController {
@objc private lazy dynamic var collection: UICollectionView = {
let layout = YAOColumnWaterFlowLayout()
layout.delegate = self
let col = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
col.delegate = self
col.dataSource = self
col.backgroundColor = .white
col.alwaysBounceVertical = true
col.showsVerticalScrollIndicator = false
col.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
col.register(SNCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
return col
}()
@objc private dynamic var dataSource: [CGFloat] = []
@objc override dynamic func viewDidLoad() {
super.viewDidLoad()
self.title = "瀑布流"
self.view.addSubview(collection)
let btn = UIButton(frame: CGRect(x: 0, y: 100, width: 100, height: 30))
btn.setTitle("添加Cell", for: .normal)
btn.backgroundColor = .red
btn.addTarget(self, action: #selector(btnClickAction), for: .touchUpInside)
self.view.addSubview(btn)
for _ in 0..<20 {
let ratio = CGFloat(arc4random() % 3) / 2 + 1
dataSource.append(ratio)
}
}
}
extension SNWateFlowViewController {
@objc private dynamic func btnClickAction() {
for _ in 0..<20 {
let ratio = CGFloat(arc4random() % 3) / 2 + 1
dataSource.append(ratio)
}
collection.reloadData()
}
}
extension SNWateFlowViewController: YAOColumnWaterFlowLayoutProtocol {
func itemHeight(wateflowLayout: YAOColumnWaterFlowLayout, indexPath: IndexPath, itemW: CGFloat) -> CGFloat {
guard indexPath.section == 2 else {
return 100
}
return itemW * dataSource[indexPath.section]
}
/// section header高度
@objc dynamic func headerHeight(wateflowLayout: YAOColumnWaterFlowLayout, section: Int) -> CGFloat {
return 60
}
/// 列数
@objc dynamic func columnCount(wateflowLayout: YAOColumnWaterFlowLayout, section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return 4
case 2:
return 2
default:
return 1
}
}
/// 列间距
@objc dynamic func columnMargin(wateflowLayout: YAOColumnWaterFlowLayout, section: Int) -> CGFloat {
return 10
}
/// 行间距
@objc dynamic func rowMargin(wateflowLayout: YAOColumnWaterFlowLayout, section: Int) -> CGFloat {
return 10
}
/// 内容内边距
@objc dynamic func contetntInset(wateflowLayout: YAOColumnWaterFlowLayout, section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15)
}
}
extension SNWateFlowViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@objc dynamic func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
@objc dynamic func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch section {
case 0:
return 0
case 1:
return 1
case 2:
return dataSource.count
default:
return 0
}
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header", for: indexPath)
header.backgroundColor = UIColor.yellow
return header
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = .purple
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("点击了:\(indexPath.section) -- \(indexPath.item)")
}
}
| 42f9f07356d275c42ca867b0f85d6f74 | 31.062069 | 166 | 0.634545 | false | false | false | false |
FraDeliro/ISaMaterialLogIn | refs/heads/master | ISaMaterialLogIn/Classes/ISaLogInController.swift | mit | 1 | //
// ISaLogInController.swift
// Pods
//
// Created by Francesco on 28/11/16.
//
//
import UIKit
open class ISaLogInController: ISaModelViewController {
private let NibName: String = "ISaLogInController"
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
An initializer that initializes the object with an Optional nib and bundle.
- Parameter nibNameOrNil: An Optional String for the nib.
- Parameter bundle: An Optional NSBundle where the nib is located.
*/
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/// An initializer that accepts no parameters.
public init() {
super.init(nibName: nil, bundle: nil)
}
//MARK: - Page lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
self.loadViewFromNib(NibName, controllerClass: ISaLogInController.self)
// Do any additional setup after loading the view.
self.isaLoginButton.setTitle(loginButtonTitle, for: .normal)
//check if it's needed to dismiss the keyboard
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.setLoginButtonAnimatedView()
}
private func setLoginButtonAnimatedView() {
let animatedView = UIButton(frame: CGRect(x: (UIScreen.main.bounds.width/2) - (self.isaLoginButton.frame.size.height/2) , y: self.isaLoginButton.frame.origin.y, width: self.isaLoginButton.frame.size.height, height: self.isaLoginButton.frame.size.height))
animatedView.backgroundColor = UIColor.white
animatedView.alpha = 0.0
animatedView.layer.cornerRadius = 22.0
self.addAnimatedButton(animatedView)
}
// MARK: - Actions
public func startLoginAnimation() {
self.isaCircleView = ISaCircleLoader(frame: CGRect(x: (UIScreen.main.bounds.width/2) - (self.isaLoginButton.frame.size.height/2) , y: self.isaLoginButton.frame.origin.y, width: self.isaLoginButton.frame.size.height, height: self.isaLoginButton.frame.size.height))
self.isaStartLoginSignUpAnimation(self.isaLoginButton)
}
}
| 130d1719b27428c4678558d9656601bd | 36.809524 | 272 | 0.696054 | false | false | false | false |
mzaks/FlatBuffersSwiftPerformanceTest | refs/heads/master | FBTest/FBReaderClasses.swift | mit | 1 | //
// FBReaderClass.swift
// FBTest
//
// Created by Maxim Zaks on 27.09.16.
// Copyright © 2016 maxim.zaks. All rights reserved.
//
import Foundation
public final class FBMemoryReaderClass : FBReader {
public var count : Int
public let cache : FBReaderCache?
public var buffer : UnsafePointer<UInt8>
init(buffer : UnsafePointer<UInt8>, count : Int, cache : FBReaderCache? = FBReaderCache()) {
self.buffer = buffer
self.count = count
self.cache = cache
}
public func fromByteArray<T : Scalar>(position : Int) throws -> T {
if position + strideof(T) >= count || position < 0 {
throw FBReaderError.OutOfBufferBounds
}
return UnsafePointer<T>(buffer.advancedBy(position)).memory
}
public func buffer(position : Int, length : Int) throws -> UnsafeBufferPointer<UInt8> {
if Int(position + length) > count {
throw FBReaderError.OutOfBufferBounds
}
let pointer = UnsafePointer<UInt8>(buffer).advancedBy(position)
return UnsafeBufferPointer<UInt8>.init(start: pointer, count: Int(length))
}
public func isEqual(other: FBReader) -> Bool{
guard let other = other as? FBMemoryReaderClass else {
return false
}
return self.buffer == other.buffer
}
}
public final class FBFileReaderClass : FBReader {
private let fileSize : UInt64
private let fileHandle : NSFileHandle
public let cache : FBReaderCache?
init(fileHandle : NSFileHandle, cache : FBReaderCache? = FBReaderCache()){
self.fileHandle = fileHandle
fileSize = fileHandle.seekToEndOfFile()
self.cache = cache
}
public func fromByteArray<T : Scalar>(position : Int) throws -> T {
let seekPosition = UInt64(position)
if seekPosition + UInt64(strideof(T)) >= fileSize {
throw FBReaderError.OutOfBufferBounds
}
fileHandle.seekToFileOffset(seekPosition)
return UnsafePointer<T>(fileHandle.readDataOfLength(strideof(T)).bytes).memory
}
public func buffer(position : Int, length : Int) throws -> UnsafeBufferPointer<UInt8> {
if UInt64(position + length) >= fileSize {
throw FBReaderError.OutOfBufferBounds
}
fileHandle.seekToFileOffset(UInt64(position))
let pointer = UnsafeMutablePointer<UInt8>(fileHandle.readDataOfLength(Int(length)).bytes)
return UnsafeBufferPointer<UInt8>.init(start: pointer, count: Int(length))
}
public func isEqual(other: FBReader) -> Bool{
guard let other = other as? FBFileReaderClass else {
return false
}
return self.fileHandle === other.fileHandle
}
}
| d23331b2b441b8f2bc0e11aa2dc2b21d | 32.46988 | 97 | 0.642909 | false | false | false | false |
Draveness/RbSwift | refs/heads/master | Sources/Hash+Transform.swift | mit | 1 | //
// Hash+Transform.swift
// RbSwift
//
// Created by Draveness on 06/04/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Foundation
// MARK: - Transform
public extension Hash {
/// Returns a new hash containing the contents of `otherHash` and the contents of hsh.
/// If no block is specified, the value for entries with duplicate keys will be that
/// of `otherHash`.
///
/// let h1 = ["a": 100, "b": 200]
/// let h2 = ["b": 254, "c": 300]
///
/// h1.merge(h2) #=> ["a": 100, "b": 254, "c": 300]))
///
/// Otherwise the value for each duplicate key is determined by calling
/// the block with the key, its value in hsh and its value in `otherHash`.
///
/// h1.merge(h2) { (key, oldval, newval) in
/// newval - oldval
/// } #=> ["a": 100, "b": 54, "c": 300]
///
/// h1 #=> ["a": 100, "b": 200]
///
/// - Parameters:
/// - otherHash: Another hash instance.
/// - closure: A closure returns a new value if duplicate happens.
/// - Returns: A new hash containing the contents of both hash.
func merge(_ otherHash: Hash<Key, Value>, closure: ((Key, Value, Value) -> Value)? = nil) -> Hash<Key, Value> {
var map = Hash<Key, Value>()
for (k, v) in self {
map[k] = v
}
for (key, value) in otherHash {
if let oldValue = map[key],
let closure = closure {
map[key] = closure(key, oldValue, value)
} else {
map[key] = value
}
}
return map
}
/// An alias to `Hash#merge(otherHash:)` methods.
///
/// - Parameters:
/// - otherHash: Another hash instance.
/// - closure: A closure returns a new value if duplicate happens.
/// - Returns: A new hash containing the contents of both hash.
func update(_ otherHash: Hash<Key, Value>, closure: ((Key, Value, Value) -> Value)? = nil) -> Hash<Key, Value> {
return merge(otherHash, closure: closure)
}
/// A mutating version of `Hash#merge(otherHash:closure:)`
///
/// let h1 = ["a": 100, "b": 200]
/// let h2 = ["b": 254, "c": 300]
///
/// h1.merge(h2) #=> ["a": 100, "b": 254, "c": 300]))
/// h1 #=> ["a": 100, "b": 254, "c": 300]))
///
/// - Parameters:
/// - otherHash: Another hash instance.
/// - closure: A closure returns a new value if duplicate happens.
/// - Returns: Self
@discardableResult
mutating func merged(_ otherHash: Hash<Key, Value>, closure: ((Key, Value, Value) -> Value)? = nil) -> Hash<Key, Value> {
self = self.merge(otherHash, closure: closure)
return self
}
/// An alias to `Hash#merged(otherHash:)` methods.
///
/// - Parameters:
/// - otherHash: Another hash instance.
/// - closure: A closure returns a new value if duplicate happens.
/// - Returns: Self
@discardableResult
mutating func updated(_ otherHash: Hash<Key, Value>, closure: ((Key, Value, Value) -> Value)? = nil) -> Hash<Key, Value> {
return merged(otherHash, closure: closure)
}
/// Removes all key-value pairs from hsh.
///
/// var hash = ["a": 100]
/// hash.clear() #=> [:]
/// hash #=> [:]
///
/// - Returns: Self with empty hash.
@discardableResult
mutating func clear() -> Hash<Key, Value> {
self = [:]
return self
}
/// An alias to `Hash#removeValue(forKey:)`.
///
/// var hash = ["a": 100, "b": 200]
/// hash.delete("a") #=> 100
/// hash #=> ["b": 200]
///
/// - Parameter key: A key of hash.
/// - Returns: Corresponding value or nil.
@discardableResult
mutating func delete(_ key: Key) -> Value? {
return self.removeValue(forKey: key)
}
/// Replaces the contents of hsh with the contents of otherHash.
///
/// var hash = ["a": 100, "b": 200]
/// hash.replace(["c": 300]) #=> ["c": 300]
/// hash #=> ["c": 300]
///
/// - Parameter otherHash: Another hash instance.
/// - Returns: Self
@discardableResult
mutating func replace(_ otherHash: Hash<Key, Value>) -> Hash<Key, Value> {
self = otherHash
return self
}
/// Associates the value given by value with the key given by key.
///
/// var hash = ["a": 4]
/// hash.store("b", 5) #=> 5
/// hash #=> ["a": 4, "b": 5]
///
/// - Parameters:
/// - key: A key
/// - value: A value
/// - Returns: The passing value
@discardableResult
mutating func store(_ key: Key, _ value: Value) -> Value {
self[key] = value
return value
}
/// Removes a key-value pair from hsh and returns it as the two-item
/// array ( key, value ), or nil if the hash is empty.
///
/// var hash = ["a": 4]
/// hash.shift() #=> ("b", 5)
/// hash.shift() #=> nil
///
/// - Returns: A key-value pair
@discardableResult
mutating func shift() -> (Key, Value)? {
if let key = self.keys.first {
return (key, delete(key)!)
}
return nil
}
/// Return a new with the results of running block once for every value.
/// This method does not change the keys.
///
/// let hash = ["a": 1, "b": 2, "c": 3]
/// hash.transformValues { $0 * $0 + 1 } #=> ["a": 2, "b": 5, "c": 10]
/// hash.transformValues { $0.to_s } #=> ["a": "1", "b": "2", "c": "3"]
///
/// - Parameter closure: An closure accepts a value return an new value.
/// - Returns: An new hash with key-value pair
func transformValues<T>(_ closure: @escaping (Value) -> T) -> [Key: T] {
var results: [Key: T] = [:]
for (key, value) in self {
results[key] = closure(value)
}
return results
}
/// Return a new with the results of running block once for every value.
/// This method does not change the keys. The mutates version of
/// `Hash#transformedValues(closure:)` can only accepts a closure with
/// `(Value) -> Value` type.
///
/// var hash = ["a": 1, "b": 2, "c": 3]
/// hash.transformedValues {
/// $0 * $0 + 1
/// } #=> ["a": 2, "b": 5, "c": 10]
/// hash #=> ["a": 2, "b": 5, "c": 10]
///
/// - Parameter closure: An closure accepts a value return an new value.
/// - Returns: Self
@discardableResult
mutating func transformedValues(_ closure: @escaping (Value) -> Value) -> [Key: Value] {
var results: [Key: Value] = [:]
for (key, value) in self {
results[key] = closure(value)
}
self = results
return self
}
}
public extension Hash where Value: Hashable {
/// Returns a new hash created by using hsh’s values as keys, and the keys as values.
///
/// let hash1 = ["a": 100, "b": 200]
/// hash1.invert #=> [100: "a", 200: "b"]
///
/// let hash2 = ["cat": "feline", "dog": "canine", "cow": "bovine"]
/// hash2.invert.invert #=> ["cat": "feline", "dog": "canine", "cow": "bovine"]
///
/// If a key with the same value already exists in the hsh, then the last one defined
/// will be used, the earlier value(s) will be discarded.
///
/// let hash3 = ["cat": 1, "dog": 1]
/// hash3.invert #=> [1: "dog"]
///
var invert: [Value: Key] {
var results: [Value: Key] = [:]
for (key, value) in self {
results[value] = key
}
return results
}
}
| 7341c70e9fd36b1bc9b3b43633dfd96b | 33.608889 | 126 | 0.508283 | false | false | false | false |
LuckyChen73/CW_WEIBO_SWIFT | refs/heads/master | WeiBo/WeiBo/Classes/Tools(工具类)/NetworkTool.swift | mit | 1 | //
// NetworkTool.swift
// WeiBo
//
// Created by chenWei on 2017/4/4.
// Copyright © 2017年 陈伟. All rights reserved.
//
import UIKit
import AFNetworking
class NetworkTool: AFHTTPSessionManager {
//swift 中单例写法
// static let shared: NetworkTool = NetworkTool()
//创建单例
static let shared: NetworkTool = {
let tool = NetworkTool(baseURL: nil)
//设置其可接受的格式
tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
return tool
}()
/// 网络中间层
///
/// - Parameters:
/// - url: url 字符串
/// - method: 请求方式
/// - parameters: 请求参数
/// - callBack: 完成回调
func requeset(url: String, method: String, parameters: Any?, callBack: @escaping (Any?)->()){
//发起 get 请求
if method == "GET" {
self.get(url, parameters: parameters, progress: nil, success: { (_, responseData) in
callBack(responseData)
}, failure: { (_, error) in
print(error)
callBack(nil)
})
}
//发起 post 请求
if method == "POST" {
self.post(url, parameters: parameters, progress: nil, success: { (_, responseData) in
callBack(responseData)
}, failure: { (_, error) in
print(error)
callBack(nil)
})
}
}
/// 网络中间层: 发起二进制的文件数据请求
///
/// - Parameters:
/// - url: url字符串
/// - parameters: 文本参数
/// - data: 文件的二进制数据
/// - name: 服务器接收文件数据所需要的key
/// - fileName: 建议服务器保存的文件的名字
/// - callBack: 完成回调
func upload(url: String, parameters: Any?, data: Data, name: String, fileName: String, callBack: @escaping (Any?)->()) {
self.post(url, parameters: parameters, constructingBodyWith: { (formData) in
formData.appendPart(withFileData: data, name: name, fileName: fileName, mimeType: "application/octet-stream")
}, progress: nil, success: { (_, response) in
callBack(response)
}) { (_, error) in
print(error)
callBack(nil)
}
}
}
| bd5be451ff08abc819e8dc0ed84e1672 | 28.39726 | 124 | 0.532619 | false | false | false | false |
atrick/swift | refs/heads/main | test/Generics/loop_normalization_1.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s
protocol P {
associatedtype T
}
struct C {}
// CHECK-LABEL: .f1@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f1<T: P, U: P>(_: T, _: U) where T.T == C, T.T == U.T { }
// CHECK-LABEL: .f2@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f2<T: P, U: P>(_: T, _: U) where U.T == C, T.T == U.T { }
// CHECK-LABEL: .f3@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f3<T: P, U: P>(_: T, _: U) where T.T == C, U.T == C, T.T == U.T { }
// CHECK-LABEL: .f4@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f4<T: P, U: P>(_: T, _: U) where T.T == C, T.T == U.T, U.T == C { }
// CHECK-LABEL: .f5@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f5<T: P, U: P>(_: T, _: U) where T.T == U.T, T.T == C, U.T == C { }
// CHECK-LABEL: .f6@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f6<T: P, U: P>(_: T, _: U) where U.T == C, T.T == C, T.T == U.T { }
// CHECK-LABEL: .f7@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f7<T: P, U: P>(_: T, _: U) where T.T == C, U.T == C, T.T == U.T { }
// CHECK-LABEL: .f8@
// CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C>
func f8<T: P, U: P>(_: T, _: U) where T.T == U.T, U.T == C, T.T == C { }
| 3a083a60be97314dc70cc7f9a5828797 | 40.333333 | 135 | 0.491935 | false | false | false | false |
insidegui/WWDC | refs/heads/master | PlayerUI/Util/AVAsset+AsyncHelpers.swift | bsd-2-clause | 1 | //
// AVAsset+AsyncHelpers.swift
// PlayerUI
//
// Created by Allen Humphreys on 25/6/18.
// Copyright © 2018 Guilherme Rambo. All rights reserved.
//
import AVFoundation
extension AVAsset {
public var durationIfLoaded: CMTime? {
let error: NSErrorPointer = nil
let durationStatus = statusOfValue(forKey: "duration", error: error)
guard durationStatus == .loaded, error?.pointee == nil else { return nil }
return duration
}
}
| ab9460493b5f611fbd60c4646bb9e486 | 20.636364 | 82 | 0.665966 | false | false | false | false |
ekgorter/MyWikiTravel | refs/heads/master | MyWikiTravel/MyWikiTravel/GuideViewController.swift | unlicense | 1 | //
// GuideViewController.swift
// MyWikiTravel
//
// Created by Elias Gorter on 04-06-15.
// Copyright (c) 2015 EliasGorter6052274. All rights reserved.
//
// Displays table of articles saved in selected guide.
import UIKit
class GuideViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let coreData = CoreData()
var guide = [Guide]()
var articles = [Article]()
let cellIdentifier = "guideArticleCell"
@IBOutlet weak var guideTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Retrieves the currently selected guide entity.
self.guide = coreData.fetchGuide(self.title!)
}
// Reloads the table every time this view is presented, to show any updates.
override func viewWillAppear(animated: Bool) {
self.articles = coreData.fetchArticles(self.guide)
self.guideTableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles.count
}
// Show article titles of selected guide in tableview cells.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! UITableViewCell!
let article = articles[indexPath.row]
cell.textLabel?.text = article.title
cell.imageView?.image = UIImage(named: "Article")
return cell
}
// Allows table cells to be deleted by swiping.
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
// Deletes table cell and the article it contains.
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if(editingStyle == .Delete ) {
let articleToDelete = articles[indexPath.row]
coreData.delete(articleToDelete)
coreData.fetchGuide(self.title!)
self.articles = coreData.fetchArticles(self.guide)
guideTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
coreData.save()
}
}
// Passes required data to next viewcontroller.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let searchViewController: SearchViewController = segue.destinationViewController as? SearchViewController {
searchViewController.guide = guide[0]
}
if let articleViewController: ArticleViewController = segue.destinationViewController as? ArticleViewController {
var articleIndex = guideTableView!.indexPathForSelectedRow()!.row
articleViewController.title = articles[articleIndex].title
articleViewController.articleText = articles[articleIndex].text
articleViewController.imageData = articles[articleIndex].image
articleViewController.onlineSource = false
}
}
} | 2f9b6c8b01082909ce5691b6673783a6 | 38.301205 | 148 | 0.690586 | false | false | false | false |
reswifq/reswifq | refs/heads/master | Sources/Reswifq/MemQueue.swift | lgpl-3.0 | 1 | //
// MemQueue.swift
// Reswifq
//
// Created by Valerio Mazzeo on 28/02/2017.
// Copyright © 2017 VMLabs Limited. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
import Dispatch
enum MemQueueError: Error {
case dataIntegrityFailure
}
/**
Simple, thread safe, in memory queue.
It doesn't implement the Reliable Queue Pattern.
*/
public class MemQueue: Queue {
// MARK: Setting and Getting Attributes
var isEmpty: Bool {
return self.pendingHigh.isEmpty && self.pendingMedium.isEmpty && self.pendingLow.isEmpty
}
// MARK: Concurrency Management
private let queue = DispatchQueue(label: "com.reswifq.MemQueue")
// MARK: Queue Storage
private var jobs = [JobID: (job: Job, priority: QueuePriority, scheduleAt: Date?)]()
private var delayed = [JobID]()
private var pendingHigh = [JobID]()
private var pendingMedium = [JobID]()
private var pendingLow = [JobID]()
// MARK: Queue
private func queueStorage(for priority: QueuePriority, isDelayed: Bool, queue: (inout [JobID]) -> Void) {
switch (priority, isDelayed) {
// Delayed
case (_, true):
queue(&self.delayed)
// Pending
case (.high, false):
queue(&self.pendingHigh)
case (.medium, false):
queue(&self.pendingMedium)
case (.low, false):
queue(&self.pendingLow)
}
}
public func enqueue(_ job: Job, priority: QueuePriority = .medium, scheduleAt: Date? = nil) throws {
self.queue.async {
let identifier = UUID().uuidString
self.jobs[identifier] = (job: job, priority: priority, scheduleAt: scheduleAt)
self.queueStorage(for: priority, isDelayed: scheduleAt != nil) { $0.append(identifier) }
}
}
private func _dequeue() -> JobID? {
let now = Date()
let delayed = self.delayed.filter { identifier in
guard let scheduledAt = self.jobs[identifier]?.scheduleAt else { return false }
return scheduledAt <= now
}.sorted {
guard let lhs = self.jobs[$0] else { return false }
guard let rhs = self.jobs[$1] else { return false }
switch (lhs.priority, rhs.priority) {
case (.high, .medium), (.high, .low):
return true
case (.low, .medium), (.low, .high):
return false
default:
return false
}
}
if let delayedJobID = delayed.first {
if let index = self.delayed.index(of: delayedJobID) {
self.delayed.remove(at: index)
}
return delayedJobID
} else if !self.pendingHigh.isEmpty {
return self.pendingHigh.removeFirst()
} else if !self.pendingMedium.isEmpty {
return self.pendingMedium.removeFirst()
} else if !self.pendingLow.isEmpty {
return self.pendingLow.removeFirst()
} else {
return nil
}
}
public func dequeue() throws -> PersistedJob? {
return try self.queue.sync {
guard let jobID = self._dequeue() else {
return nil
}
guard let jobBox = self.jobs[jobID] else {
throw MemQueueError.dataIntegrityFailure
}
return (identifier: jobID, job: jobBox.job)
}
}
public func bdequeue() throws -> PersistedJob {
while true {
guard let job = try self.dequeue() else {
continue
}
return job
}
}
public func complete(_ job: JobID) throws {
self.queue.async {
self.jobs[job] = nil
}
}
}
| 9a237c29c79456cbef0a8581eb8b8269 | 25.783133 | 109 | 0.589294 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Legacy/Neocom/Neocom/SkillCell.swift | lgpl-2.1 | 2 | //
// SkillCell.swift
// Neocom
//
// Created by Artem Shimanski on 10/23/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import EVEAPI
import TreeController
class SkillCell: RowCell {
@IBOutlet weak var iconView: UIImageView?
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var levelLabel: UILabel?
@IBOutlet weak var spLabel: UILabel?
@IBOutlet weak var trainingTimeLabel: UILabel?
@IBOutlet weak var progressView: UIProgressView?
@IBOutlet weak var skillLevelView: SkillLevelView?
}
extension Prototype {
enum SkillCell {
static let `default` = Prototype(nib: UINib(nibName: "SkillCell", bundle: nil), reuseIdentifier: "SkillCell")
}
}
class SkillLevelView: UIView {
var layers: [CALayer] = []
var level: Int = 0 {
didSet {
layers.enumerated().forEach {
$0.element.backgroundColor = $0.offset < level ? UIColor.gray.cgColor : UIColor.clear.cgColor
}
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(updateAnimation), object: nil)
perform(#selector(updateAnimation), with: nil, afterDelay: 0)
}
}
private var animation: (CALayer, CABasicAnimation)? {
didSet {
if let old = oldValue {
old.0.removeAnimation(forKey: "backgroundColor")
}
}
}
var isActive: Bool = false {
didSet {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(updateAnimation), object: nil)
perform(#selector(updateAnimation), with: nil, afterDelay: 0)
}
}
override func awakeFromNib() {
super.awakeFromNib()
layers = (0..<5).map { i in
let layer = CALayer()
layer.backgroundColor = tintColor.cgColor
self.layer.addSublayer(layer)
return layer
}
layer.borderColor = tintColor.cgColor
layer.borderWidth = ThinnestLineWidth
}
override init(frame: CGRect) {
super.init(frame: frame)
layers = (0..<5).map { i in
let layer = CALayer()
layer.backgroundColor = tintColor.cgColor
self.layer.addSublayer(layer)
return layer
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func layoutSubviews() {
super.layoutSubviews()
var rect = CGRect.zero
rect.size.width = (bounds.width - CGFloat(layers.count) - 1) / CGFloat(layers.count)
rect.size.height = min(bounds.height, 5)
rect.origin.y = (bounds.height - rect.height) / 2
rect.origin.x = 1
rect = rect.integral
for layer in layers {
layer.frame = rect
rect.origin.x += rect.size.width + 1
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: 8 * 5 + 6, height: 7)
}
override func didMoveToWindow() {
super.didMoveToWindow()
if window == nil {
animation = nil
}
else if animation == nil {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(updateAnimation), object: nil)
perform(#selector(updateAnimation), with: nil, afterDelay: 0)
}
}
@objc private func updateAnimation() {
self.animation = nil
if self.isActive && (1...5).contains(self.level) {
let layer = self.layers[self.level - 1]
let animation = CABasicAnimation(keyPath: "backgroundColor")
animation.fromValue = self.tintColor.cgColor
animation.toValue = UIColor.white.cgColor
animation.duration = 0.5
animation.repeatCount = .greatestFiniteMagnitude
animation.autoreverses = true
layer.add(animation, forKey: "backgroundColor")
self.animation = (layer, animation)
}
}
}
extension Tree.Item {
class SkillRow: RoutableRow<Tree.Content.Skill> {
override var prototype: Prototype? {
return Prototype.SkillCell.default
}
lazy var type: SDEInvType? = {
return Services.sde.viewContext.invType(content.skill.typeID)
}()
let character: Character
init(_ content: Tree.Content.Skill, character: Character) {
self.character = character
super.init(content, route: Router.SDE.invTypeInfo(.typeID(content.skill.typeID)))
}
override func configure(cell: UITableViewCell, treeController: TreeController?) {
super.configure(cell: cell, treeController: treeController)
guard let cell = cell as? SkillCell else {return}
let skill: Character.Skill
let trainingTime: TimeInterval
let level: Int?
let skillPoints: String
let isActive: Bool
let trainingProgress: Float
switch content {
case let .skill(item):
skill = item
trainingTime = TrainingQueue.Item(skill: skill, targetLevel: 1, startSP: nil).trainingTime(with: character.attributes)
level = nil
skillPoints = UnitFormatter.localizedString(from: 0, unit: .skillPoints, style: .long)
isActive = false
trainingProgress = 0
case let .skillQueueItem(item):
skill = item.skill
isActive = item.isActive
trainingProgress = item.trainingProgress
trainingTime = item.trainingTimeToLevelUp(with: character.attributes)
level = item.queuedSkill.finishedLevel
let a = UnitFormatter.localizedString(from: item.skillPoints, unit: .none, style: .long)
let b = UnitFormatter.localizedString(from: item.skill.skillPoints(at: level!), unit: .skillPoints, style: .long)
skillPoints = "\(a) / \(b)"
case let .trainedSkill(item, trainedSkill):
skill = item
trainingTime = trainedSkill.trainedSkillLevel < 5 ? TrainingQueue.Item(skill: skill, targetLevel: trainedSkill.trainedSkillLevel + 1, startSP: nil).trainingTime(with: character.attributes) : 0
level = trainedSkill.trainedSkillLevel
skillPoints = UnitFormatter.localizedString(from: trainedSkill.skillpointsInSkill, unit: .skillPoints, style: .long)
isActive = false
trainingProgress = 0
}
cell.titleLabel?.text = "\(type?.typeName ?? "") (x\(Int(skill.rank)))"
cell.skillLevelView?.level = level ?? 0
cell.skillLevelView?.isActive = isActive
cell.progressView?.progress = trainingProgress
if let level = level {
cell.levelLabel?.text = NSLocalizedString("LEVEL", comment: "") + " " + String(romanNumber:level)
}
else {
cell.levelLabel?.text = NSLocalizedString("N/A", comment: "")
}
let sph = Int((skill.skillPointsPerSecond(with: character.attributes) * 3600).rounded())
cell.spLabel?.text = "\(skillPoints) (\(UnitFormatter.localizedString(from: sph, unit: .skillPointsPerSecond, style: .long)))"
if trainingTime > 0 {
cell.trainingTimeLabel?.text = TimeIntervalFormatter.localizedString(from: trainingTime, precision: .minutes)
}
else {
cell.trainingTimeLabel?.text = NSLocalizedString("Completed", comment: "").uppercased()
}
let typeID = skill.typeID
let item = Services.storage.viewContext.currentAccount?.activeSkillPlan?.skills?.first { (skill) -> Bool in
let skill = skill as! SkillPlanSkill
return Int(skill.typeID) == typeID && Int(skill.level) >= level ?? 0
}
if item != nil {
cell.iconView?.image = #imageLiteral(resourceName: "skillRequirementQueued")
cell.iconView?.isHidden = false
}
else {
cell.iconView?.image = nil
cell.iconView?.isHidden = true
}
}
}
}
extension Tree.Content {
enum Skill: Hashable {
case skill(Character.Skill)
case skillQueueItem(Character.SkillQueueItem)
case trainedSkill(Character.Skill, ESI.Skills.CharacterSkills.Skill)
var skill: Character.Skill {
switch self {
case let .skill(skill):
return skill
case let .skillQueueItem(item):
return item.skill
case let .trainedSkill(skill, _):
return skill
}
}
var skillPoints: Int {
switch self {
case .skill:
return 0
case let .skillQueueItem(item):
return item.skillPoints
case let .trainedSkill(_, skill):
return Int(skill.skillpointsInSkill)
}
}
}
}
| afa466ae7d21811628b260f49ffac50e | 28.988235 | 196 | 0.703936 | false | false | false | false |
JGiola/swift-package-manager | refs/heads/master | Tests/BasicPerformanceTests/PathPerfTests.swift | apache-2.0 | 3 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import Basic
import TestSupport
class PathPerfTests: XCTestCasePerf {
/// Tests creating very long AbsolutePaths by joining path components.
func testJoinPerf_X100000() {
let absPath = AbsolutePath("/hello/little")
let relPath = RelativePath("world")
let N = 100000
self.measure {
var lengths = 0
for _ in 0 ..< N {
let result = absPath.appending(relPath)
lengths = lengths &+ result.asString.utf8.count
}
XCTAssertEqual(lengths, (absPath.asString.utf8.count + 1 + relPath.asString.utf8.count) &* N)
}
}
// FIXME: We will obviously want a lot more tests here.
}
| 2fe53f5918bd2cbc8fe3fcda6d447a64 | 30 | 105 | 0.651803 | false | true | false | false |
muukii/Realm-EasyBackground | refs/heads/master | Pod/Classes/EasyBackground.swift | mit | 1 | //
// EasyBackground.swift
// Pods
//
// Created by Hiroshi Kimura on 2/12/16.
//
//
import Foundation
import RealmSwift
extension Realm {
public var queue: NSOperationQueue {
get {
if let queue = objc_getAssociatedObject(self, &StoredProperties.queue) as? NSOperationQueue {
return queue
}
let queue = self.createDefaultQueue()
self.queue = queue
return queue
}
set {
objc_setAssociatedObject(self, &StoredProperties.queue, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
public func writeBackground(block: (Realm throws -> Void)) {
self.writeBackground(block, completion: { _ in })
}
public func writeBackground(block: (Realm throws -> Void), completion: (ErrorType? -> Void)) {
self.queue.addOperationWithBlock {
autoreleasepool {
do {
let realm = try Realm(configuration: self.configuration)
realm.beginWrite()
do {
try block(realm)
try realm.commitWrite()
NSOperationQueue.mainQueue().addOperationWithBlock {
completion(nil)
}
} catch {
realm.cancelWrite()
NSOperationQueue.mainQueue().addOperationWithBlock {
completion(error)
}
}
} catch {
NSOperationQueue.mainQueue().addOperationWithBlock {
completion(error)
}
}
}
}
}
private enum StoredProperties {
static var queue: Void?
}
private func createDefaultQueue() -> NSOperationQueue {
let queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 1
queue.qualityOfService = NSQualityOfService.Default
return queue
}
} | f3cd1e7d1f8213052c453da92b30259a | 29.136986 | 125 | 0.489313 | false | false | false | false |
hrscy/TodayNews | refs/heads/master | News/News/Classes/Mine/Controller/SettingViewController.swift | mit | 1 | //
// TableViewController.swift
// News
//
// Created by 杨蒙 on 2017/9/29.
// Copyright © 2017年 hrscy. All rights reserved.
//
import UIKit
import Kingfisher
class SettingViewController: UITableViewController {
/// 存储 plist 文件中的数据
var sections = [[SettingModel]]()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 设置状态栏属性
navigationController?.navigationBar.barStyle = .default
navigationController?.setNavigationBarHidden(false, animated: false)
}
override func viewDidLoad() {
super.viewDidLoad()
// 设置 UI
setupUI()
}
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 sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.ym_dequeueReusableCell(indexPath: indexPath) as SettingCell
cell.setting = sections[indexPath.section][indexPath.row]
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: cell.calculateDiskCashSize() // 清理缓存,从沙盒中获取缓存数据的大小
case 2: cell.selectionStyle = .none // 摘要
default: break
}
default: break
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath) as! SettingCell
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: cell.clearCacheAlertController() // 清理缓存
case 1: cell.setupFontAlertController() // 设置字体大小
case 3: cell.setupNetworkAlertController() // 非 WiFi 网络流量
case 4: cell.setupPlayNoticeAlertController() // 非 WiFi 网络播放提醒
default: break
}
case 1:
if indexPath.row == 0 { // 离线下载
navigationController?.pushViewController(OfflineDownloadController(), animated: true)
}
default: break
}
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 10))
view.theme_backgroundColor = "colors.tableViewBackgroundColor"
return view
}
}
extension SettingViewController {
/// 设置 UI
private func setupUI() {
// pilst 文件的路径
let path = Bundle.main.path(forResource: "settingPlist", ofType: "plist")
// plist 文件中的数据
let cellPlist = NSArray(contentsOfFile: path!) as! [Any]
sections = cellPlist.compactMap({ section in
(section as! [Any]).compactMap({ SettingModel.deserialize(from: $0 as? [String: Any]) })
})
tableView.sectionHeaderHeight = 10
tableView.ym_registerCell(cell: SettingCell.self)
tableView.rowHeight = 44
tableView.tableFooterView = UIView()
tableView.separatorStyle = .none
tableView.theme_backgroundColor = "colors.tableViewBackgroundColor"
}
}
| b38323f614587638ae7041600521e574 | 33.815534 | 109 | 0.628555 | false | false | false | false |
UKFast-Mobile/Weather-Alert-Test | refs/heads/develop | Weather Alert/CoreData/City+CoreDataClass.swift | mit | 1 | //
// City+CoreDataClass.swift
// Weather Alert
//
// Created by Aleksandr Kelbas on 11/11/2016.
// Copyright © 2016 UKFast. All rights reserved.
//
import Foundation
import CoreData
protocol DataModel {
func mapping(json: [String : Any])
}
public class City: NSManagedObject, DataModel {
internal func mapping(json: [String : Any]) {
id = json["id"] as? NSNumber
name = json["name"] as? String
if let sys = json["sys"] as? [String : Any] {
country = sys["country"] as? String
}
if let coord = json["coord"] as? [String : Any] {
lon = coord["lon"] as? NSNumber
lat = coord["lat"] as? NSNumber
}
if let wind = json["wind"] as? [String : Any] {
deg = wind["deg"] as? NSNumber
speed = wind["speed"] as? NSNumber
}
}
}
| dce3ac5c19f3ff3113b450a595af797d | 22.684211 | 57 | 0.532222 | false | false | false | false |
DoubleSha/BitcoinSwift | refs/heads/master | BitcoinSwift/Models/RejectMessage.swift | apache-2.0 | 1 | //
// RejectMessage.swift
// BitcoinSwift
//
// Created by Kevin Greene on 11/4/14.
// Copyright (c) 2014 DoubleSha. All rights reserved.
//
import Foundation
public func ==(left: RejectMessage, right: RejectMessage) -> Bool {
return left.rejectedCommand == right.rejectedCommand &&
left.code == right.code &&
left.reason == right.reason &&
left.hash == right.hash
}
/// The reject message is sent when messages are rejected.
/// https://en.bitcoin.it/wiki/Protocol_specification#reject
public struct RejectMessage: Equatable {
public enum Code: UInt8 {
case Malformed = 0x01
case Invalid = 0x10
case Obsolete = 0x11
case Duplicate = 0x12
case NonStandard = 0x40
case Dust = 0x41
case InsufficientFee = 0x42
case Checkpoint = 0x43
}
public let rejectedCommand: Message.Command
public let code: Code
public let reason: String
public let hash: SHA256Hash?
public init(rejectedCommand: Message.Command,
code: Code,
reason: String,
hash: SHA256Hash? = nil) {
self.rejectedCommand = rejectedCommand
self.code = code
self.reason = reason
self.hash = hash
}
}
extension RejectMessage: MessagePayload {
public var command: Message.Command {
return Message.Command.Reject
}
public var bitcoinData: NSData {
let data = NSMutableData()
data.appendVarString(rejectedCommand.rawValue)
data.appendUInt8(code.rawValue)
data.appendVarString(reason)
if let hash = self.hash {
data.appendData(hash.bitcoinData)
}
return data
}
public static func fromBitcoinStream(stream: NSInputStream) -> RejectMessage? {
let rawCommand = stream.readVarString()
if rawCommand == nil {
print("WARN: Failed to parse rawCommand from RejectMessage")
return nil
}
let command = Message.Command(rawValue: rawCommand!)
if command == nil {
print("WARN: Invalid command \(rawCommand!) from RejectMessage")
return nil
}
let rawCode = stream.readUInt8()
if rawCode == nil {
print("WARN: Failed to parse rawCode from RejectMessage")
return nil
}
let code = Code(rawValue: rawCode!)
if code == nil {
print("WARN: Invalid code \(rawCode!) from RejectMessage")
return nil
}
let reason = stream.readVarString()
if reason == nil {
print("WARN: Failed to parse reason from RejectMessage")
return nil
}
var hash: SHA256Hash? = nil
if stream.hasBytesAvailable {
hash = SHA256Hash.fromBitcoinStream(stream)
if hash == nil {
print("WARN: Failed to parse hash from RejectMessage")
return nil
}
}
return RejectMessage(rejectedCommand: command!, code: code!, reason: reason!, hash: hash)
}
}
| f5ca4e3cf0db8393d165f6c809625afe | 26.392157 | 93 | 0.661775 | false | false | false | false |
leosimas/ios_KerbalCampaigns | refs/heads/master | Kerbal Campaigns/Models/Constants.swift | apache-2.0 | 1 | //
// Constants.swift
// Kerbal Campaigns
//
// Created by SoSucesso on 01/10/17.
// Copyright © 2017 Simas Team. All rights reserved.
//
struct Constants {
struct ResponseKeys {
static let ID = "id"
static let NAME = "name"
static let INTRO = "introduction"
static let LENGTH = "length"
static let MISSIONS = "missions"
static let DIFFICULTY = "difficulty"
static let TASKS = "tasks"
static let SUBTASKS = "subtasks"
}
}
| 85e8a0554adfea4395f66567d7af8871 | 22.136364 | 53 | 0.59332 | false | false | false | false |
zl00/CocoaMQTT | refs/heads/master | Source/CocoaMQTTMessage.swift | mit | 1 | //
// CocoaMQTTMessage.swift
// CocoaMQTT
//
// Created by Feng Lee<[email protected]> on 14/8/3.
// Copyright (c) 2015 emqtt.io. All rights reserved.
//
import Foundation
/**
* MQTT Message
*/
public class CocoaMQTTMessage: NSObject {
public var qos = CocoaMQTTQOS.qos1
var dup = false
public var topic: String
public var payload: [UInt8]
public var retained = false
// utf8 bytes array to string
public var string: String? {
get {
return NSString(bytes: payload, length: payload.count, encoding: String.Encoding.utf8.rawValue) as String?
}
}
public init(topic: String, string: String, qos: CocoaMQTTQOS = .qos1, retained: Bool = false, dup: Bool = false) {
self.topic = topic
self.payload = [UInt8](string.utf8)
self.qos = qos
self.retained = retained
self.dup = dup
}
public init(topic: String, payload: [UInt8], qos: CocoaMQTTQOS = .qos1, retained: Bool = false, dup: Bool = false) {
self.topic = topic
self.payload = payload
self.qos = qos
self.retained = retained
self.dup = dup
}
}
/**
* MQTT Will Message
*/
public class CocoaMQTTWill: CocoaMQTTMessage {
public init(topic: String, message: String) {
super.init(topic: topic, payload: message.bytesWithLength)
}
}
| 43b5bed9dd00b639330092e45bbdd9f2 | 24.259259 | 120 | 0.621701 | false | false | false | false |
Urinx/SublimeCode | refs/heads/master | DGElasticPullToRefresh/DGElasticPullToRefreshLoadingViewCircle.swift | gpl-3.0 | 10 | /*
The MIT License (MIT)
Copyright (c) 2015 Danil Gontovnik
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
// MARK: -
// MARK: (CGFloat) Extension
public extension CGFloat {
public func toRadians() -> CGFloat {
return (self * CGFloat(M_PI)) / 180.0
}
public func toDegrees() -> CGFloat {
return self * 180.0 / CGFloat(M_PI)
}
}
// MARK: -
// MARK: DGElasticPullToRefreshLoadingViewCircle
public class DGElasticPullToRefreshLoadingViewCircle: DGElasticPullToRefreshLoadingView {
// MARK: -
// MARK: Vars
private let kRotationAnimation = "kRotationAnimation"
private let shapeLayer = CAShapeLayer()
private lazy var identityTransform: CATransform3D = {
var transform = CATransform3DIdentity
transform.m34 = CGFloat(1.0 / -500.0)
transform = CATransform3DRotate(transform, CGFloat(-90.0).toRadians(), 0.0, 0.0, 1.0)
return transform
}()
// MARK: -
// MARK: Constructors
public override init() {
super.init(frame: .zero)
shapeLayer.lineWidth = 1.0
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = tintColor.CGColor
shapeLayer.actions = ["strokeEnd" : NSNull(), "transform" : NSNull()]
shapeLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
layer.addSublayer(shapeLayer)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
// MARK: Methods
override public func setPullProgress(progress: CGFloat) {
super.setPullProgress(progress)
shapeLayer.strokeEnd = min(0.9 * progress, 0.9)
if progress > 1.0 {
let degrees = ((progress - 1.0) * 200.0)
shapeLayer.transform = CATransform3DRotate(identityTransform, degrees.toRadians(), 0.0, 0.0, 1.0)
} else {
shapeLayer.transform = identityTransform
}
}
override public func startAnimating() {
super.startAnimating()
if shapeLayer.animationForKey(kRotationAnimation) != nil { return }
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = CGFloat(2 * M_PI) + currentDegree()
rotationAnimation.duration = 1.0
rotationAnimation.repeatCount = Float.infinity
rotationAnimation.removedOnCompletion = false
rotationAnimation.fillMode = kCAFillModeForwards
shapeLayer.addAnimation(rotationAnimation, forKey: kRotationAnimation)
}
override public func stopLoading() {
super.stopLoading()
shapeLayer.removeAnimationForKey(kRotationAnimation)
}
private func currentDegree() -> CGFloat {
return shapeLayer.valueForKeyPath("transform.rotation.z") as! CGFloat
}
override public func tintColorDidChange() {
super.tintColorDidChange()
shapeLayer.strokeColor = tintColor.CGColor
}
// MARK: -
// MARK: Layout
override public func layoutSubviews() {
super.layoutSubviews()
shapeLayer.frame = bounds
let inset = shapeLayer.lineWidth / 2.0
shapeLayer.path = UIBezierPath(ovalInRect: CGRectInset(shapeLayer.bounds, inset, inset)).CGPath
}
}
| a7134d44314cefa17fbc32bb2dfcb1f7 | 30.956522 | 109 | 0.668707 | false | false | false | false |
UIKit0/AudioKit | refs/heads/master | AudioKit/Tests/Tests/AKVCOscillator.swift | mit | 14 | //
// main.swift
// AudioKit
//
// Created by Nick Arner and Aurelius Prochazka on 12/24/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: NSTimeInterval = 10.0
class Instrument : AKInstrument {
override init() {
super.init()
let pulseWidthLine = AKLine(firstPoint: 0.ak, secondPoint: 1.ak, durationBetweenPoints: 10.ak)
let frequencyLine = AKLine(firstPoint: 110.ak, secondPoint: 880.ak, durationBetweenPoints: 10.ak)
let note = VCONote()
let vcOscillator = AKVCOscillator()
vcOscillator.waveformType = note.waveformType
vcOscillator.pulseWidth = pulseWidthLine
vcOscillator.frequency = frequencyLine
setAudioOutput(vcOscillator)
enableParameterLog(
"\n\n\nWaveform Type = ",
parameter: note.waveformType,
timeInterval:10
)
enableParameterLog(
"Frequency = ",
parameter: frequencyLine,
timeInterval:0.2
)
enableParameterLog(
"Pulse Width = ",
parameter: pulseWidthLine,
timeInterval:0.2
)
}
}
class VCONote: AKNote {
var waveformType = AKNoteProperty()
override init() {
super.init()
addProperty(waveformType)
}
convenience init(waveformType: AKConstant) {
self.init()
self.waveformType.floatValue = waveformType.floatValue
}
}
AKOrchestra.testForDuration(testDuration)
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
let note1 = VCONote(waveformType: AKVCOscillator.waveformTypeForSquare())
let note2 = VCONote(waveformType: AKVCOscillator.waveformTypeForSawtooth())
let note3 = VCONote(waveformType: AKVCOscillator.waveformTypeForSquareWithPWM())
let note4 = VCONote(waveformType: AKVCOscillator.waveformTypeForTriangleWithRamp())
note1.duration.floatValue = 2.0
note2.duration.floatValue = 2.0
note3.duration.floatValue = 2.0
note4.duration.floatValue = 2.0
instrument.playNote(note1)
instrument.playNote(note2, afterDelay: 2.0)
instrument.playNote(note3, afterDelay: 4.0)
instrument.playNote(note4, afterDelay: 6.0)
NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
| 783d0ec16845fb56075f686606a076c0 | 26.325301 | 105 | 0.690917 | false | false | false | false |
A752575700/HOMEWORK | refs/heads/master | Day9_1/Day10_1/PinPoint/PinPoint/ViewController.swift | mit | 1 | //
// ViewController.swift
// PinPoint
//
// Created by Super Admin on 15/8/20.
// Copyright (c) 2015年 Super Admin. All rights reserved.
//
import UIKit
class ViewController: UIViewController, MAMapViewDelegate {
var mapview: MAMapView!
var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
initmapview()
// Do any additional setup after loading the view, typically from a nib.
initControl()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initmapview(){
MAMapServices.sharedServices().apiKey = apikey
mapview = MAMapView(frame: CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height))
self.view.addSubview(mapview!)
}
func initControl(){
button = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
button!.frame = CGRectMake(10, 500, 40, 40)
button.setImage(UIImage(named: "search"), forState: UIControlState.Normal)
self.mapview?.addSubview(button!)
button.addTarget(self, action: "locateAction", forControlEvents: UIControlEvents.TouchUpInside)
}
func locateAction(){
if mapview?.userTrackingMode != MAUserTrackingMode.Follow{
mapview?.setUserTrackingMode(MAUserTrackingMode.Follow, animated: true)
}
}
func mapView(mapView: MAMapView!, didChangeUserTrackingMode mode: MAUserTrackingMode, animated: Bool) {
if mode == MAUserTrackingMode.None{
button?.setImage(UIImage(named: "location_no"), forState: UIControlState.Normal)
}else{
button!.setImage(UIImage(named: "location_yes"), forState: UIControlState.Normal)
}
}
}
| 327a742d3403ebf63cde142d069a79b4 | 29.688525 | 111 | 0.649038 | false | false | false | false |
Tomikes/eidolon | refs/heads/master | KioskTests/Bid Fulfillment/LoadingViewModelTests.swift | mit | 2 | import Quick
import Nimble
@testable
import Kiosk
import ReactiveCocoa
class LoadingViewModelTests: QuickSpec {
override func spec() {
var subject: LoadingViewModel!
it("loads placeBidNetworkModel") {
subject = LoadingViewModel(bidNetworkModel: StubBidderNetworkModel(), placingBid: false)
expect(subject.placeBidNetworkModel.fulfillmentController as? AnyObject) === subject.bidderNetworkModel.fulfillmentController as? AnyObject
}
it("loads bidCheckingModel") {
subject = LoadingViewModel(bidNetworkModel: StubBidderNetworkModel(), placingBid: false)
expect(subject.bidCheckingModel.fulfillmentController as? AnyObject) === subject.bidderNetworkModel.fulfillmentController as? AnyObject
}
it("initializes with bidNetworkModel") {
let networkModel = StubBidderNetworkModel()
subject = LoadingViewModel(bidNetworkModel: networkModel, placingBid: false)
expect(subject.bidderNetworkModel) == networkModel
}
it("initializes with placingBid = false") {
subject = LoadingViewModel(bidNetworkModel: StubBidderNetworkModel(), placingBid: false)
expect(subject.placingBid) == false
}
it("initializes with placingBid = true") {
subject = LoadingViewModel(bidNetworkModel: StubBidderNetworkModel(), placingBid: true)
expect(subject.placingBid) == true
}
it("binds createdNewBidder") {
subject = LoadingViewModel(bidNetworkModel: StubBidderNetworkModel(), placingBid: true)
subject.bidderNetworkModel.createdNewBidder = true
expect(subject.createdNewBidder) == true
}
it("binds bidIsResolved") {
subject = LoadingViewModel(bidNetworkModel: StubBidderNetworkModel(), placingBid: true)
subject.bidCheckingModel.bidIsResolved = true
expect(subject.bidIsResolved) == true
}
it("binds isHighestBidder") {
subject = LoadingViewModel(bidNetworkModel: StubBidderNetworkModel(), placingBid: true)
subject.bidCheckingModel.isHighestBidder = true
expect(subject.isHighestBidder) == true
}
it("binds reserveNotMet") {
subject = LoadingViewModel(bidNetworkModel: StubBidderNetworkModel(), placingBid: true)
subject.bidCheckingModel.reserveNotMet = true
expect(subject.reserveNotMet) == true
}
it("infers bidDetals") {
subject = LoadingViewModel(bidNetworkModel: StubBidderNetworkModel(), placingBid: true)
expect(subject.bidDetails) === subject.bidderNetworkModel.fulfillmentController.bidDetails
}
it("creates a new bidder if necessary") {
subject = LoadingViewModel(bidNetworkModel: StubBidderNetworkModel(), placingBid: false)
kioskWaitUntil { (done) in
subject.performActions().subscribeCompleted { done() }
}
expect(subject.createdNewBidder = true)
}
describe("stubbed auxillary network models") {
var stubPlaceBidNetworkModel: StubPlaceBidNetworkModel!
var stubBidCheckingNetworkModel: StubBidCheckingNetworkModel!
beforeEach {
stubPlaceBidNetworkModel = StubPlaceBidNetworkModel()
stubBidCheckingNetworkModel = StubBidCheckingNetworkModel()
subject = LoadingViewModel(bidNetworkModel: StubBidderNetworkModel(), placingBid: true)
subject.placeBidNetworkModel = stubPlaceBidNetworkModel
subject.bidCheckingModel = stubBidCheckingNetworkModel
}
it("places a bid if necessary") {
kioskWaitUntil { (done) -> Void in
subject.performActions().subscribeCompleted { done() }
return
}
expect(stubPlaceBidNetworkModel.bid) == true
}
it("waits for bid resolution if bid was placed") {
kioskWaitUntil { (done) -> Void in
subject.performActions().subscribeCompleted { done() }
return
}
expect(stubBidCheckingNetworkModel.checked) == true
}
}
}
}
class StubBidderNetworkModel: BidderNetworkModel {
init() {
super.init(fulfillmentController: StubFulfillmentController())
}
override func createOrGetBidder() -> RACSignal {
createdNewBidder = true
return RACSignal.empty()
}
}
class StubPlaceBidNetworkModel: PlaceBidNetworkModel {
var bid = false
init() {
super.init(fulfillmentController: StubFulfillmentController())
}
override func bidSignal(bidDetails: BidDetails) -> RACSignal {
bid = true
return RACSignal.empty()
}
}
class StubBidCheckingNetworkModel: BidCheckingNetworkModel {
var checked = false
init() {
super.init(fulfillmentController: StubFulfillmentController())
}
override func waitForBidResolution() -> RACSignal {
checked = true
return RACSignal.empty()
}
}
| e03aeee354cc3fb13ba3d3c84edc24cc | 32.967532 | 151 | 0.643089 | false | false | false | false |
qiscus/qiscus-sdk-ios | refs/heads/master | Qiscus/Qiscus/View/QiscusChatVC.swift | mit | 1 | //
// QiscusChatVC.swift
// QiscusSDK
//
// Created by Ahmad Athaullah on 8/18/16.
// Copyright © 2016 Ahmad Athaullah. All rights reserved.
//
import UIKit
import MobileCoreServices
import Photos
import ImageViewer
import SwiftyJSON
import UserNotifications
import ContactsUI
import CoreLocation
import RealmSwift
@objc public protocol QiscusChatVCCellDelegate{
@objc optional func chatVC(viewController:QiscusChatVC, didTapLinkButtonWithURL url:URL )
@objc optional func chatVC(viewController:QiscusChatVC, cellForComment comment:QComment, indexPath:IndexPath)->QChatCell?
@objc optional func chatVC(viewController:QiscusChatVC, heightForComment comment:QComment)->QChatCellHeight?
@objc optional func chatVC(viewController:QiscusChatVC, hideCellWith comment:QComment)->Bool
}
@objc public protocol QiscusChatVCConfigDelegate{
@objc optional func chatVCConfigDelegate(userNameLabelColor viewController:QiscusChatVC, forUser user:QUser)->UIColor?
@objc optional func chatVCConfigDelegate(hideLeftAvatarOn viewController:QiscusChatVC)->Bool
@objc optional func chatVCConfigDelegate(hideUserNameLabel viewController:QiscusChatVC, forUser user:QUser)->Bool
@objc optional func chatVCConfigDelegate(usingSoftDeleteOn viewController:QiscusChatVC)->Bool
@objc optional func chatVCConfigDelegate(deletedMessageTextFor viewController:QiscusChatVC, selfMessage isSelf:Bool)->String
@objc optional func chatVCConfigDelegate(enableReplyMenuItem viewController:QiscusChatVC, forComment comment: QComment)->Bool
@objc optional func chatVCConfigDelegate(enableForwardMenuItem viewController:QiscusChatVC, forComment comment: QComment)->Bool
@objc optional func chatVCConfigDelegate(enableResendMenuItem viewController:QiscusChatVC, forComment comment: QComment)->Bool
@objc optional func chatVCConfigDelegate(enableDeleteMenuItem viewController:QiscusChatVC, forComment comment: QComment)->Bool
@objc optional func chatVCConfigDelegate(enableDeleteForMeMenuItem viewController:QiscusChatVC, forComment comment: QComment)->Bool
@objc optional func chatVCConfigDelegate(enableShareMenuItem viewController:QiscusChatVC, forComment comment: QComment)->Bool
@objc optional func chatVCConfigDelegate(enableInfoMenuItem viewController:QiscusChatVC, forComment comment: QComment)->Bool
@objc optional func chatVCConfigDelegate(usingNavigationSubtitleTyping viewController:QiscusChatVC)->Bool
@objc optional func chatVCConfigDelegate(usingTypingCell viewController:QiscusChatVC)->Bool
}
@objc public protocol QiscusChatVCDelegate{
// MARK : Review this
func chatVC(enableForwardAction viewController:QiscusChatVC)->Bool
func chatVC(enableInfoAction viewController:QiscusChatVC)->Bool
func chatVC(overrideBackAction viewController:QiscusChatVC)->Bool
//
@objc optional func chatVC(backAction viewController:QiscusChatVC, room:QRoom?, data:Any?)
@objc optional func chatVC(titleAction viewController:QiscusChatVC, room:QRoom?, data:Any?)
@objc optional func chatVC(viewController:QiscusChatVC, onForwardComment comment:QComment, data:Any?)
@objc optional func chatVC(viewController:QiscusChatVC, infoActionComment comment:QComment,data:Any?)
@objc optional func chatVC(onViewDidLoad viewController:QiscusChatVC)
@objc optional func chatVC(viewController:QiscusChatVC, willAppear animated:Bool)
@objc optional func chatVC(viewController:QiscusChatVC, willDisappear animated:Bool)
@objc optional func chatVC(didTapAttachment actionSheet: UIAlertController, viewController: QiscusChatVC, onRoom: QRoom?)
@objc optional func chatVC(viewController:QiscusChatVC, willPostComment comment:QComment, room:QRoom?, data:Any?)->QComment?
@objc optional func chatVC(viewController:QiscusChatVC, didFailLoadRoom error:String)
}
public class QiscusChatVC: UIViewController{
@IBOutlet weak var inputBarHeight: NSLayoutConstraint!
// MARK: - IBOutlet Properties
@IBOutlet weak var inputBar: UIView!
@IBOutlet public weak var backgroundView: UIImageView!
@IBOutlet public weak var inputText: ChatInputText!
@IBOutlet weak var welcomeView: UIView!
@IBOutlet weak var welcomeText: UILabel!
@IBOutlet weak var welcomeSubtitle: UILabel!
@IBOutlet public weak var sendButton: UIButton!
@IBOutlet weak var attachButton: UIButton!
@IBOutlet weak var archievedNotifView: UIView!
@IBOutlet weak var archievedNotifLabel: UILabel!
@IBOutlet weak var unlockButton: UIButton!
@IBOutlet weak var emptyChatImage: UIImageView!
@IBOutlet public weak var collectionView: QConversationCollectionView!
@IBOutlet weak var bottomButton: UIButton!
@IBOutlet weak var unreadIndicator: UILabel!
@IBOutlet weak var linkPreviewContainer: UIView!
@IBOutlet weak var linkDescription: UITextView!
@IBOutlet weak var linkImage: UIImageView!
@IBOutlet weak var linkTitle: UILabel!
@IBOutlet weak var linkCancelButton: UIButton!
@IBOutlet weak var recordBackground: UIView!
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var cancelRecordButton: UIButton!
// MARK: - Constrain
@IBOutlet public weak var minInputHeight: NSLayoutConstraint!
@IBOutlet weak var archievedNotifTop: NSLayoutConstraint!
@IBOutlet weak var inputBarBottomMargin: NSLayoutConstraint!
@IBOutlet weak var collectionViewBottomConstrain: NSLayoutConstraint!
@IBOutlet weak var linkPreviewTopMargin: NSLayoutConstraint!
@IBOutlet weak var recordViewLeading: NSLayoutConstraint!
@IBOutlet weak var linkImageWidth: NSLayoutConstraint!
@IBOutlet public weak var collectionViewTopMargin: NSLayoutConstraint!
@objc public var delegate:QiscusChatVCDelegate?
@objc public var configDelegate:QiscusChatVCConfigDelegate?
@objc public var cellDelegate:QiscusChatVCCellDelegate?
public var data:Any?
var isPresence:Bool = false
public var titleLabel = UILabel()
public var subtitleLabel = UILabel()
internal var subtitleText:String = ""
var roomAvatarImage:UIImage?
public var roomAvatar = UIImageView()
public var titleView = UIView()
var isBeforeTranslucent = false
// MARK: - shared Properties
var commentClient = QiscusCommentClient.sharedInstance
var archived:Bool = QiscusUIConfiguration.sharedInstance.readOnly
var selectedCellIndex:IndexPath? = nil
let locationManager = CLLocationManager()
var didFindLocation = true
var prefetch:Bool = false
var presentingLoading = false
var flagPresence = true
internal let currentNavbarTint = UINavigationBar.appearance().tintColor
static let currentNavbarTint = UINavigationBar.appearance().tintColor
var replyData:QComment? = nil {
didSet{
self.reply(toComment: replyData)
}
}
public var defaultBack:Bool = true
// MARK: - Data Properties
var loadMoreControl = UIRefreshControl()
var processingFile = false
var processingAudio = false
var loadingMore = false
// MARK: - Data load configuration
@objc public var chatRoom:QRoom?{
didSet{
if let room = self.chatRoom {
if !prefetch && isPresence {
room.subscribeRealtimeStatus()
}
self.collectionView.room = self.chatRoom
}
if oldValue == nil && self.chatRoom != nil {
let _ = self.view
self.view.layoutSubviews()
self.view.layoutIfNeeded()
let delay = 0.5 * Double(NSEC_PER_SEC)
let time = DispatchTime.now() + delay / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time, execute: {
self.dismissLoading()
self.dataLoaded = true
})
}
if let roomId = self.chatRoom?.id {
let center: NotificationCenter = NotificationCenter.default
center.addObserver(self, selector: #selector(QiscusChatVC.userTyping(_:)), name: QiscusNotification.USER_TYPING(onRoom: roomId), object: nil)
}
}
}
public var chatMessage:String?
public var chatRoomId:String?
public var isPublicChannel:Bool = false
public var chatUser:String?
public var chatTitle:String?{
didSet{
self.loadTitle()
}
}
public var chatSubtitle:String?
public var chatNewRoomUsers:[String] = [String]()
var chatDistinctId:String?
var chatData:String?
public var chatRoomUniqueId:String?
public var chatTarget:QComment?
var chatAvatarURL = ""
var chatService = QChatService()
var collectionWidth:CGFloat = 0
var topColor = Qiscus.shared.styleConfiguration.color.topColor
var bottomColor = Qiscus.shared.styleConfiguration.color.bottomColor
var tintColor = Qiscus.shared.styleConfiguration.color.tintColor
// MARK: Galery variable
var galleryItems:[QiscusGalleryItem] = [QiscusGalleryItem]()
var imagePreview:GalleryViewController?
var loadWithUser:Bool = false // will be removed
//MARK: - external action
@objc public var unlockAction:(()->Void) = {}
var audioPlayer: AVAudioPlayer?
var audioTimer: Timer?
var activeAudioCell: QCellAudio?
var loadingView = QLoadingViewController.sharedInstance
var firstLoad = true
// MARK: - Audio recording variable
var isRecording = false
var recordingURL:URL?
var recorder:AVAudioRecorder?
var recordingSession = AVAudioSession.sharedInstance()
var recordTimer:Timer?
var recordDuration:Int = 0
//data flag
var checkingData:Bool = false
var roomSynced = false
var remoteTypingTimer:Timer?
var typingTimer:Timer?
var publishStatusTimer:Timer? = nil
var defaultBackButtonVisibility = true
var defaultNavBarVisibility = true
var defaultLeftButton:[UIBarButtonItem]? = nil
// navigation
public var navTitle:String = ""
public var navSubtitle:String = ""
var dataLoaded = false
var bundle:Bundle {
get{
return Qiscus.bundle
}
}
var lastVisibleRow:IndexPath?{
get{
let indexPaths = collectionView.indexPathsForVisibleItems
if indexPaths.count > 0 {
var lastIndexpath = indexPaths.first!
var i = 0
for indexPath in indexPaths {
if indexPath.section > lastIndexpath.section {
lastIndexpath.section = indexPath.section
lastIndexpath.row = indexPath.row
}else if indexPath.section == lastIndexpath.section {
if indexPath.row > lastIndexpath.row {
lastIndexpath.row = indexPath.row
}
}
i += 1
}
return lastIndexpath
}else{
return nil
}
}
}
var UTIs:[String]{
get{
return ["public.jpeg", "public.png","com.compuserve.gif","public.text", "public.archive", "com.microsoft.word.doc", "com.microsoft.excel.xls", "com.microsoft.powerpoint.ppt", "com.adobe.pdf","public.mpeg-4"]
}
}
var contactVC = CNContactPickerViewController()
var typingUsers = [String:QUser]()
var typingUserTimer = [String:Timer]()
var processingTyping = false
var previewedTypingUsers = [String]()
public init() {
super.init(nibName: "QiscusChatVC", bundle: Qiscus.bundle)
let _ = self.view
let lightColor = self.topColor.withAlphaComponent(0.4)
recordBackground.backgroundColor = lightColor
recordBackground.layer.cornerRadius = 16
bottomButton.setImage(Qiscus.image(named: "bottom")?.withRenderingMode(.alwaysTemplate), for: .normal)
bottomButton.layer.cornerRadius = 17.5
bottomButton.clipsToBounds = true
unreadIndicator.isHidden = true
unreadIndicator.layer.cornerRadius = 11.5
unreadIndicator.clipsToBounds = true
backgroundView.image = Qiscus.image(named: "chat_bg")
linkPreviewContainer.layer.shadowColor = UIColor.black.cgColor
linkPreviewContainer.layer.shadowOpacity = 0.6
linkPreviewContainer.layer.shadowOffset = CGSize(width: -5, height: 0)
linkCancelButton.tintColor = QiscusColorConfiguration.sharedInstance.rightBaloonColor
linkCancelButton.setImage(Qiscus.image(named: "ar_cancel")?.withRenderingMode(.alwaysTemplate), for: .normal)
roomAvatar.contentMode = .scaleAspectFill
inputText.font = Qiscus.style.chatFont
self.emptyChatImage.tintColor = self.topColor
self.emptyChatImage.image = QiscusAssetsConfiguration.shared.emptyChat
self.emptyChatImage.tintColor = self.bottomColor
let sendImage = Qiscus.image(named: "send")?.withRenderingMode(.alwaysTemplate)
let attachmentImage = Qiscus.image(named: "share_attachment")?.withRenderingMode(.alwaysTemplate)
let recordImage = Qiscus.image(named: "ar_record")?.withRenderingMode(.alwaysTemplate)
let cancelRecordImage = Qiscus.image(named: "ar_cancel")?.withRenderingMode(.alwaysTemplate)
self.sendButton.setImage(sendImage, for: .normal)
self.attachButton.setImage(attachmentImage, for: .normal)
self.recordButton.setImage(recordImage, for: .normal)
self.cancelRecordButton.setImage(cancelRecordImage, for: .normal)
self.cancelRecordButton.isHidden = true
self.sendButton.tintColor = Qiscus.shared.styleConfiguration.color.topColor
self.attachButton.tintColor = Qiscus.shared.styleConfiguration.color.topColor
self.recordButton.tintColor = Qiscus.shared.styleConfiguration.color.topColor
self.cancelRecordButton.tintColor = Qiscus.shared.styleConfiguration.color.topColor
self.bottomButton.tintColor = Qiscus.shared.styleConfiguration.color.topColor
self.bottomButton.isHidden = true
sendButton.addTarget(self, action: #selector(QiscusChatVC.sendMessage), for: .touchUpInside)
recordButton.addTarget(self, action: #selector(QiscusChatVC.recordVoice), for: .touchUpInside)
cancelRecordButton.addTarget(self, action: #selector(QiscusChatVC.cancelRecordVoice), for: .touchUpInside)
self.unlockButton.addTarget(self, action: #selector(QiscusChatVC.confirmUnlockChat), for: .touchUpInside)
self.welcomeText.text = QiscusTextConfiguration.sharedInstance.emptyTitle
self.welcomeSubtitle.text = QiscusTextConfiguration.sharedInstance.emptyMessage
self.emptyChatImage.image = Qiscus.style.assets.emptyChat
self.inputText.placeholder = QiscusTextConfiguration.sharedInstance.textPlaceholder
self.inputText.chatInputDelegate = self
// Keyboard stuff.
self.qiscusAutoHideKeyboard()
bottomButton.isHidden = true
self.inputBarBottomMargin.constant = 0
self.archievedNotifView.backgroundColor = QiscusColorConfiguration.sharedInstance.lockViewBgColor
self.archievedNotifLabel.textColor = QiscusColorConfiguration.sharedInstance.lockViewTintColor
let unlockImage = Qiscus.image(named: "ic_open_archived")?.withRenderingMode(.alwaysTemplate)
self.unlockButton.setBackgroundImage(unlockImage, for: UIControlState())
self.unlockButton.tintColor = QiscusColorConfiguration.sharedInstance.lockViewTintColor
self.view.layoutIfNeeded()
let titleWidth = QiscusHelper.screenWidth()
titleLabel = UILabel(frame:CGRect(x: 40, y: 7, width: titleWidth, height: 17))
titleLabel.backgroundColor = UIColor.clear
titleLabel.textColor = QiscusChatVC.currentNavbarTint
titleLabel.font = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)
titleLabel.text = self.chatTitle
titleLabel.textAlignment = .left
subtitleLabel = UILabel(frame:CGRect(x: 40, y: 25, width: titleWidth, height: 13))
subtitleLabel.backgroundColor = UIColor.clear
subtitleLabel.textColor = QiscusChatVC.currentNavbarTint
subtitleLabel.font = UIFont.systemFont(ofSize: 11)
subtitleLabel.text = self.chatSubtitle
subtitleLabel.textAlignment = .left
self.roomAvatar = UIImageView()
self.roomAvatar.contentMode = .scaleAspectFill
self.roomAvatar.backgroundColor = UIColor.white
let bgColor = QiscusColorConfiguration.sharedInstance.avatarBackgroundColor
self.roomAvatar.frame = CGRect(x: 0,y: 6,width: 32,height: 32)
self.roomAvatar.layer.cornerRadius = 16
self.roomAvatar.clipsToBounds = true
self.roomAvatar.backgroundColor = bgColor[0]
self.titleView = UIView(frame: CGRect(x: 0, y: 0, width: titleWidth + 40, height: 44))
self.titleView.addSubview(self.titleLabel)
self.titleView.addSubview(self.subtitleLabel)
self.titleView.addSubview(self.roomAvatar)
let center: NotificationCenter = NotificationCenter.default
center.addObserver(self, selector: #selector(QiscusChatVC.appDidEnterBackground), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
self.welcomeView.isHidden = true
self.collectionView.isHidden = true
}
@objc func appPresence(){
self.loadSubtitle()
}
func checkSingleRoom()->Bool{
if let room = self.chatRoom {
if room.type == .single && flagPresence{
flagPresence = false
return true
}else{
return false
}
}else {
return false
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - UI Lifecycle
override public func viewDidLoad() {
super.viewDidLoad()
self.chatService.delegate = self
if #available(iOS 9, *) {
self.collectionView.dataSource = self.collectionView
}
if let delegate = self.delegate{
delegate.chatVC?(onViewDidLoad: self)
}
}
override public func viewWillDisappear(_ animated: Bool) {
if let room = self.chatRoom {
room.readAll()
room.unsubscribeRoomChannel()
room.clearRemain30()
let predicate = NSPredicate(format: "statusRaw != %d AND statusRaw != %d", QCommentStatus.deleted.rawValue, QCommentStatus.deleting.rawValue)
var messages = room.grouppedCommentsUID(filter: predicate)
messages = self.collectionView.checkHiddenMessage(messages: messages)
self.collectionView.messagesId = messages
}
self.isPresence = false
self.dataLoaded = false
super.viewWillDisappear(animated)
view.endEditing(true)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillChangeFrame, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIApplicationDidBecomeActive, object: nil)
if checkSingleRoom(){
NotificationCenter.default.removeObserver(self, name: QiscusNotification.USER_PRESENCE, object:nil)
}
if let roomId = self.chatRoom?.id {
NotificationCenter.default.removeObserver(self, name: QiscusNotification.USER_TYPING(onRoom: roomId), object: nil)
}
view.endEditing(true)
self.dismissLoading()
if let delegate = self.delegate {
delegate.chatVC?(viewController: self, willDisappear: animated)
}
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if #available(iOS 11.0, *) {
self.navigationController?.navigationBar.prefersLargeTitles = false
self.navigationController?.navigationItem.largeTitleDisplayMode = .never
}
if !self.prefetch {
self.isPresence = true
if let room = self.chatRoom {
let rid = room.id
QiscusBackgroundThread.async {
if let rts = QRoom.threadSaveRoom(withId: rid){
rts.readAll()
rts.subscribeRoomChannel()
}
}
}
}
titleLabel.textColor = QiscusChatVC.currentNavbarTint
subtitleLabel.textColor = QiscusChatVC.currentNavbarTint
self.collectionView.viewDelegate = self
self.collectionView.roomDelegate = self
self.collectionView.cellDelegate = self
self.collectionView.configDelegate = self
self.collectionView.reloadData()
UINavigationBar.appearance().tintColor = self.currentNavbarTint
if let _ = self.navigationController {
self.navigationController?.navigationBar.isTranslucent = false
self.defaultNavBarVisibility = self.navigationController!.isNavigationBarHidden
}
setupNavigationTitle()
setupPage()
if !self.prefetch {
let center: NotificationCenter = NotificationCenter.default
center.addObserver(self, selector: #selector(QiscusChatVC.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
center.addObserver(self, selector: #selector(QiscusChatVC.keyboardChange(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
center.addObserver(self, selector: #selector(QiscusChatVC.applicationDidBecomeActive), name: .UIApplicationDidBecomeActive, object: nil)
if let roomId = self.chatRoom?.id {
center.addObserver(self, selector: #selector(QiscusChatVC.userTyping(_:)), name: QiscusNotification.USER_TYPING(onRoom: roomId), object: nil)
}
}
if self.loadMoreControl.isRefreshing {
self.loadMoreControl.endRefreshing()
}
if self.defaultBack {
self.defaultBackButtonVisibility = self.navigationItem.hidesBackButton
}
if self.navigationItem.leftBarButtonItems != nil {
self.defaultLeftButton = self.navigationItem.leftBarButtonItems
}else{
self.defaultLeftButton = nil
}
if let navController = self.navigationController {
self.isBeforeTranslucent = navController.navigationBar.isTranslucent
self.navigationController?.navigationBar.isTranslucent = false
self.defaultNavBarVisibility = self.navigationController!.isNavigationBarHidden
}
self.navigationController?.setNavigationBarHidden(false , animated: false)
if self.defaultBack {
let backButton = QiscusChatVC.backButton(self, action: #selector(QiscusChatVC.goBack))
self.navigationItem.setHidesBackButton(true, animated: false)
self.navigationItem.leftBarButtonItems = [backButton]
}
self.clearAllNotification()
view.endEditing(true)
if inputText.value == "" {
sendButton.isEnabled = false
sendButton.isHidden = true
recordButton.isHidden = false
}else{
sendButton.isEnabled = true
}
if let room = self.chatRoom {
if self.collectionView.room == nil {
self.collectionView.room = room
}
self.loadTitle()
self.loadSubtitle()
self.unreadIndicator.isHidden = true
if let r = self.collectionView.room {
if r.comments.count == 0 {
if self.isPresence && !self.prefetch && self.chatRoom == nil {
self.showLoading("Load data ...")
}
self.collectionView.loadData()
}
}
if self.chatMessage != nil && self.chatMessage != "" {
let newMessage = self.chatRoom!.newComment(text: self.chatMessage!)
self.postComment(comment: newMessage)
self.chatMessage = nil
}
room.resendPendingMessage()
room.redeletePendingDeletedMessage()
setupNavigationTitle()
setupPage()
}
self.loadData()
if let delegate = self.delegate {
delegate.chatVC?(viewController: self, willAppear: animated)
}
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if firstLoad {
if self.isPresence && !self.prefetch && self.chatRoom == nil {
self.showLoading("Load data ...")
}
self.collectionView.room = self.chatRoom
}
if let room = self.chatRoom {
Qiscus.shared.chatViews[room.id] = self
}else{
if self.isPresence && !self.prefetch && self.chatRoom == nil {
self.showLoading("Load data ...")
}
}
if let target = self.chatTarget {
if let commentTarget = QComment.comment(withUniqueId: target.uniqueId){
self.collectionView.scrollToComment(comment: commentTarget)
}else{
QToasterSwift.toast(target: self, text: "Can't find message", backgroundColor: UIColor(red: 0.9, green: 0,blue: 0,alpha: 0.8), textColor: UIColor.white)
}
self.chatTarget = nil
}
self.prefetch = false
}
// MARK: - Memory Warning
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Clear Notification Method
public func clearAllNotification(){
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications() // To remove all delivered notifications
center.removeAllPendingNotificationRequests()
}else{
UIApplication.shared.cancelAllLocalNotifications()
}
}
// MARK: - Setup UI
func setupNavigationTitle(){
var totalButton = 1
if let leftButtons = self.navigationItem.leftBarButtonItems {
totalButton += leftButtons.count
}
if let rightButtons = self.navigationItem.rightBarButtonItems {
totalButton += rightButtons.count
}
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(QiscusChatVC.goToTitleAction))
self.titleView.addGestureRecognizer(tapRecognizer)
let containerWidth = QiscusHelper.screenWidth() - 49
let titleWidth = QiscusHelper.screenWidth() - CGFloat(49 * totalButton) - 40
self.titleLabel.frame = CGRect(x: 40, y: 7, width: titleWidth, height: 17)
self.subtitleLabel.frame = CGRect(x: 40, y: 25, width: titleWidth, height: 13)
self.roomAvatar.frame = CGRect(x: 0,y: 6,width: 32,height: 32)
self.titleView.frame = CGRect(x: 0, y: 0, width: containerWidth, height: 44)
if self.chatTitle != nil {
self.titleLabel.text = self.chatTitle
}
self.navigationItem.titleView = titleView
}
func setupPage(){
archievedNotifView.isHidden = !archived
self.archievedNotifTop.constant = 0
if archived {
self.archievedNotifLabel.text = QiscusTextConfiguration.sharedInstance.readOnlyText
}else{
self.archievedNotifTop.constant = 65
}
}
// MARK: - Keyboard Methode
@objc func keyboardWillHide(_ notification: Notification){
let info: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
let animateDuration = info[UIKeyboardAnimationDurationUserInfoKey] as! Double
let goToRow = self.lastVisibleRow
self.inputBarBottomMargin.constant = 0
UIView.animate(withDuration: animateDuration, delay: 0, options: UIViewAnimationOptions(), animations: {
self.view.layoutIfNeeded()
if goToRow != nil {
self.collectionView.scrollToItem(at: goToRow!, at: .bottom, animated: false)
}
}, completion: nil)
}
@objc func keyboardChange(_ notification: Notification){
let info:NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
let keyboardSize = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardHeight: CGFloat = keyboardSize.height
let animateDuration = info[UIKeyboardAnimationDurationUserInfoKey] as! Double
self.inputBarBottomMargin.constant = 0 - keyboardHeight
let goToRow = self.lastVisibleRow
UIView.animate(withDuration: animateDuration, delay: 0, options: UIViewAnimationOptions(), animations: {
self.view.layoutIfNeeded()
if goToRow != nil {
self.collectionView.scrollToItem(at: goToRow!, at: .bottom, animated: true)
}
}, completion: nil)
}
// MARK: - Navigation Action
func rightLeftButtonAction(_ sender: AnyObject) {
}
func righRightButtonAction(_ sender: AnyObject) {
}
@objc func goBack() {
self.isPresence = false
view.endEditing(true)
if let delegate = self.delegate{
if delegate.chatVC(overrideBackAction: self){
delegate.chatVC?(backAction: self, room: self.chatRoom, data:data)
}else{
let _ = self.navigationController?.popViewController(animated: true)
}
}else{
let _ = self.navigationController?.popViewController(animated: true)
}
}
func unsubscribeNotificationCenter(){
let center: NotificationCenter = NotificationCenter.default
center.removeObserver(self)
}
// MARK: - Button Action
@objc func appDidEnterBackground(){
self.isPresence = false
view.endEditing(true)
self.dismissLoading()
}
public func resendMessage(){
}
@IBAction func goToBottomTapped(_ sender: UIButton) {
self.collectionView.scrollToBottom()
}
@IBAction func hideLinkPreview(_ sender: UIButton) {
if replyData != nil {
replyData = nil
}
}
@IBAction func showAttcahMenu(_ sender: UIButton) {
self.showAttachmentMenu()
}
@IBAction func doNothing(_ sender: Any) {}
public func postComment(comment : QComment) {
var postedComment = comment
if let delegate = self.delegate {
if let temp = delegate.chatVC?(viewController: self, willPostComment: postedComment, room: self.chatRoom, data: self.data){
postedComment = temp
}
}
chatRoom?.post(comment: postedComment, onSuccess: {
}, onError: { (error) in
Qiscus.printLog(text: "error \(error)")
})
}
public func register(_ nib: UINib?, forChatCellWithReuseIdentifier identifier: String) {
self.collectionView.register(nib, forCellWithReuseIdentifier: identifier)
}
public func register(_ chatCellClass: AnyClass?, forCellWithReuseIdentifier identifier: String) {
self.collectionView.register(chatCellClass, forCellWithReuseIdentifier: identifier)
}
@objc internal func applicationDidBecomeActive(){
if let room = self.collectionView.room{
room.syncRoom()
}
}
public func postReceivedFile(fileUrl: URL) {
self.showLoading("Processing File")
let coordinator = NSFileCoordinator()
coordinator.coordinate(readingItemAt: fileUrl, options: NSFileCoordinator.ReadingOptions.forUploading, error: nil) { (dataURL) in
do{
var data:Data = try Data(contentsOf: dataURL, options: NSData.ReadingOptions.mappedIfSafe)
let mediaSize = Double(data.count) / 1024.0
if mediaSize > Qiscus.maxUploadSizeInKB {
self.processingFile = false
self.dismissLoading()
self.showFileTooBigAlert()
return
}
var fileName = dataURL.lastPathComponent.replacingOccurrences(of: "%20", with: "_")
fileName = fileName.replacingOccurrences(of: " ", with: "_")
var popupText = QiscusTextConfiguration.sharedInstance.confirmationImageUploadText
var fileType = QiscusFileType.image
var thumb:UIImage? = nil
let fileNameArr = (fileName as String).split(separator: ".")
let ext = String(fileNameArr.last!).lowercased()
let gif = (ext == "gif" || ext == "gif_")
let video = (ext == "mp4" || ext == "mp4_" || ext == "mov" || ext == "mov_")
let isImage = (ext == "jpg" || ext == "jpg_" || ext == "tif" || ext == "heic" || ext == "png" || ext == "png_")
let isPDF = (ext == "pdf" || ext == "pdf_")
var usePopup = false
if isImage{
var i = 0
for n in fileNameArr{
if i == 0 {
fileName = String(n)
}else if i == fileNameArr.count - 1 {
fileName = "\(fileName).jpg"
}else{
fileName = "\(fileName).\(String(n))"
}
i += 1
}
let image = UIImage(data: data)!
let imageSize = image.size
var bigPart = CGFloat(0)
if(imageSize.width > imageSize.height){
bigPart = imageSize.width
}else{
bigPart = imageSize.height
}
var compressVal = CGFloat(1)
if(bigPart > 2000){
compressVal = 2000 / bigPart
}
data = UIImageJPEGRepresentation(image, compressVal)!
thumb = UIImage(data: data)
}else if isPDF{
usePopup = true
popupText = "Are you sure to send this document?"
fileType = QiscusFileType.document
if let provider = CGDataProvider(data: data as NSData) {
if let pdfDoc = CGPDFDocument(provider) {
if let pdfPage:CGPDFPage = pdfDoc.page(at: 1) {
var pageRect:CGRect = pdfPage.getBoxRect(.mediaBox)
pageRect.size = CGSize(width:pageRect.size.width, height:pageRect.size.height)
UIGraphicsBeginImageContext(pageRect.size)
if let context:CGContext = UIGraphicsGetCurrentContext(){
context.saveGState()
context.translateBy(x: 0.0, y: pageRect.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.concatenate(pdfPage.getDrawingTransform(.mediaBox, rect: pageRect, rotate: 0, preserveAspectRatio: true))
context.drawPDFPage(pdfPage)
context.restoreGState()
if let pdfImage:UIImage = UIGraphicsGetImageFromCurrentImageContext() {
thumb = pdfImage
}
}
UIGraphicsEndImageContext()
}
}
}
}
else if gif{
let image = UIImage(data: data)!
thumb = image
let asset = PHAsset.fetchAssets(withALAssetURLs: [dataURL], options: nil)
if let phAsset = asset.firstObject {
let option = PHImageRequestOptions()
option.isSynchronous = true
option.isNetworkAccessAllowed = true
PHImageManager.default().requestImageData(for: phAsset, options: option) {
(gifData, dataURI, orientation, info) -> Void in
data = gifData!
}
}
popupText = "Are you sure to send this image?"
usePopup = true
}else if video {
fileType = .video
let assetMedia = AVURLAsset(url: dataURL)
let thumbGenerator = AVAssetImageGenerator(asset: assetMedia)
thumbGenerator.appliesPreferredTrackTransform = true
let thumbTime = CMTimeMakeWithSeconds(0, 30)
let maxSize = CGSize(width: QiscusHelper.screenWidth(), height: QiscusHelper.screenWidth())
thumbGenerator.maximumSize = maxSize
do{
let thumbRef = try thumbGenerator.copyCGImage(at: thumbTime, actualTime: nil)
thumb = UIImage(cgImage: thumbRef)
popupText = "Are you sure to send this video?"
}catch{
Qiscus.printLog(text: "error creating thumb image")
}
usePopup = true
}else{
usePopup = true
let textFirst = QiscusTextConfiguration.sharedInstance.confirmationFileUploadText
let textMiddle = "\(fileName as String)"
let textLast = QiscusTextConfiguration.sharedInstance.questionMark
popupText = "\(textFirst) \(textMiddle) \(textLast)"
fileType = QiscusFileType.file
}
self.dismissLoading()
// UINavigationBar.appearance().tintColor = self.currentNavbarTint
if usePopup {
QPopUpView.showAlert(withTarget: self, image: thumb, message:popupText, isVideoImage: video,
doneAction: {
self.postFile(filename: fileName, data: data, type: fileType, thumbImage: thumb)
},
cancelAction: {
Qiscus.printLog(text: "cancel upload")
QFileManager.clearTempDirectory()
}
)
}else{
let uploader = QiscusUploaderVC(nibName: "QiscusUploaderVC", bundle: Qiscus.bundle)
uploader.chatView = self
uploader.data = data
uploader.fileName = fileName
uploader.room = self.chatRoom
self.navigationController?.pushViewController(uploader, animated: true)
}
}catch _{
self.dismissLoading()
}
}
}
}
extension QiscusChatVC:QChatServiceDelegate{
public func chatService(didFinishLoadRoom inRoom: QRoom, withMessage message: String?) {
self.chatRoomId = inRoom.id
self.chatRoom = inRoom
self.chatRoomUniqueId = inRoom.uniqueId
self.isPublicChannel = inRoom.isPublicChannel
self.loadTitle()
self.loadSubtitle()
self.unreadIndicator.isHidden = true
if inRoom.isPublicChannel {
Qiscus.shared.mqtt?.subscribe("\(Qiscus.client.appId)/\(inRoom.uniqueId)/c")
}
if self.chatMessage != nil && self.chatMessage != "" {
let newMessage = self.chatRoom!.newComment(text: self.chatMessage!)
self.postComment(comment: newMessage)
self.chatMessage = nil
}
Qiscus.shared.chatViews[inRoom.id] = self
if inRoom.comments.count > 0 {
self.collectionView.refreshData()
if let target = self.chatTarget {
self.collectionView.scrollToComment(comment: target)
self.chatTarget = nil
}else{
self.collectionView.scrollToBottom()
}
}
if checkSingleRoom(){
let presence: NotificationCenter = NotificationCenter.default
presence.addObserver(self, selector: #selector(QiscusChatVC.appPresence), name: QiscusNotification.USER_PRESENCE, object: nil)
}
self.dismissLoading()
}
public func chatService(didFailLoadRoom error: String) {
let delay = 1.5 * Double(NSEC_PER_SEC)
let time = DispatchTime.now() + delay / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time, execute: {
self.dismissLoading()
})
if chatRoom?.storedName == nil {
if !Qiscus.sharedInstance.connected {
QToasterSwift.toast(target: self, text: "No Internet Connection", backgroundColor: UIColor(red: 0.9, green: 0,blue: 0,alpha: 0.8), textColor: UIColor.white)
}else {
QToasterSwift.toast(target: self, text: "Can't load chat room\n\(error)", backgroundColor: UIColor(red: 0.9, green: 0,blue: 0,alpha: 0.8), textColor: UIColor.white)
self.hideInputBar()
}
}
self.dataLoaded = false
self.delegate?.chatVC?(viewController: self, didFailLoadRoom: error)
}
}
extension QiscusChatVC:QConversationViewRoomDelegate{
public func roomDelegate(didChangeName room: QRoom, name:String){
if name != self.titleLabel.text{
self.titleLabel.text = name
}
}
public func roomDelegate(didFinishSync room: QRoom){
self.dismissLoading()
if self.chatRoom!.comments.count > 0 {
self.collectionView.refreshData()
if let target = self.chatTarget {
self.collectionView.layoutIfNeeded()
self.collectionView.scrollToComment(comment: target)
}else{
self.collectionView.scrollToBottom()
}
}
}
public func roomDelegate(didChangeAvatar room: QRoom, avatar:UIImage){
self.roomAvatar.image = avatar
}
public func roomDelegate(didFailUpdate error: String){}
public func roomDelegate(didChangeUser room: QRoom, user: QUser){
if self.chatRoom!.type == .single {
if user.email != Qiscus.client.email && self.chatRoom!.typingUser == ""{
self.loadSubtitle()
}
}
}
public func roomDelegate(didChangeParticipant room: QRoom){
if self.chatRoom?.type == .group && (self.chatSubtitle == "" || self.chatSubtitle == nil){
self.loadSubtitle()
}
}
public func roomDelegate(didChangeUnread room:QRoom, unreadCount:Int){
if unreadCount == 0 {
self.unreadIndicator.text = ""
self.unreadIndicator.isHidden = true
}else{
if unreadCount > 99 {
self.unreadIndicator.text = "99+"
}else{
self.unreadIndicator.text = "\(unreadCount)"
}
self.unreadIndicator.isHidden = self.bottomButton.isHidden
}
}
public func roomDelegate(gotFirstComment room: QRoom) {
self.welcomeView.isHidden = true
self.collectionView.isHidden = false
}
}
extension QiscusChatVC: CLLocationManagerDelegate {
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
QiscusBackgroundThread.async {autoreleasepool{
manager.stopUpdatingLocation()
if !self.didFindLocation {
if let currentLocation = manager.location {
let geoCoder = CLGeocoder()
let latitude = currentLocation.coordinate.latitude
let longitude = currentLocation.coordinate.longitude
var address:String?
var title:String?
geoCoder.reverseGeocodeLocation(currentLocation, completionHandler: { (placemarks, error) in
if error == nil {
let placeArray = placemarks
var placeMark: CLPlacemark!
placeMark = placeArray?[0]
if let addressDictionary = placeMark.addressDictionary{
if let addressArray = addressDictionary["FormattedAddressLines"] as? [String] {
address = addressArray.joined(separator: ", ")
}
title = addressDictionary["Name"] as? String
DispatchQueue.main.async { autoreleasepool{
let comment = self.chatRoom!.newLocationComment(latitude: latitude, longitude: longitude, title: title, address: address)
self.postComment(comment: comment)
self.addCommentToCollectionView(comment: comment)
}}
}
}
})
}
self.didFindLocation = true
self.dismissLoading()
}
}}
}
}
| c487bf3863d4e7d74426e217bae6aa16 | 43.085066 | 220 | 0.613117 | false | false | false | false |
legendecas/Rocket.Chat.iOS | refs/heads/sdk | Rocket.Chat.Shared/Controllers/Chat/ChatControllerHeaderStatus.swift | mit | 1 | //
// ChatControllerHeaderStatus.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 10/08/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
extension ChatViewController {
func showHeaderStatusView() {
chatHeaderViewStatus?.removeFromSuperview()
if let headerView = ChatHeaderViewStatus.instantiateFromNib() {
headerView.translatesAutoresizingMaskIntoConstraints = false
headerView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 44)
view.addSubview(headerView)
chatHeaderViewStatus = headerView
// Shadow of the view
headerView.layer.masksToBounds = false
headerView.layer.shadowColor = UIColor.black.cgColor
headerView.layer.shadowOpacity = 0.5
headerView.layer.shadowOffset = CGSize(width: 0, height: 0)
headerView.layer.shadowRadius = 5
view.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "|-0-[headerView]-0-|",
options: .alignAllLeft,
metrics: nil,
views: ["headerView": headerView])
)
view.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[headerView(44)]",
options: .alignAllLeft,
metrics: nil,
views: ["headerView": headerView])
)
}
}
func hideHeaderStatusView() {
chatHeaderViewStatus?.removeFromSuperview()
}
}
| 7d089110053af8ea3a3f5fe9358618da | 31.040816 | 86 | 0.608917 | false | false | false | false |
GaoZhenWei/PhotoBrowser | refs/heads/master | PhotoBrowser/PhotoBroswer/View/ItemCell.swift | mit | 12 | //
// ItemCell.swift
// PhotoBrowser
//
// Created by 成林 on 15/7/29.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
class ItemCell: UICollectionViewCell {
var photoModel: PhotoBrowser.PhotoModel!{didSet{dataFill()}}
var photoType: PhotoBrowser.PhotoType!
var isHiddenBar: Bool = true{didSet{toggleDisplayBottomBar(isHiddenBar)}}
weak var vc: UIViewController!
/** 缓存 */
var cache: Cache<UIImage>!
/** format */
var format: Format<UIImage>!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imageV: ShowImageView!
@IBOutlet weak var bottomContentView: UIView!
@IBOutlet weak var msgTitleLabel: UILabel!
@IBOutlet weak var msgContentTextView: UITextView!
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var imgVHC: NSLayoutConstraint!
@IBOutlet weak var imgVWC: NSLayoutConstraint!
@IBOutlet weak var layoutView: UIView!
@IBOutlet weak var asHUD: NVActivityIndicatorView!
var hasHDImage: Bool = false
var isFix: Bool = false
var isDeinit: Bool = false
var isAlive: Bool = true
lazy private var doubleTapGesture: UITapGestureRecognizer = {
let doubleTapGesture = UITapGestureRecognizer(target: self, action: "doubleTap:")
doubleTapGesture.numberOfTapsRequired = 2
return doubleTapGesture
}()
lazy private var singleTapGesture: UITapGestureRecognizer = {
let singleTapGesture = UITapGestureRecognizer(target: self, action: "singleTap:")
singleTapGesture.numberOfTapsRequired = 1
return singleTapGesture
}()
deinit{
cache = nil
self.asHUD?.removeFromSuperview()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
extension ItemCell: UIScrollViewDelegate{
override func awakeFromNib() {
super.awakeFromNib()
singleTapGesture.requireGestureRecognizerToFail(doubleTapGesture)
self.addGestureRecognizer(doubleTapGesture)
self.addGestureRecognizer(singleTapGesture)
scrollView.delegate = self
msgContentTextView.textContainerInset = UIEdgeInsetsZero
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didRotate", name: UIDeviceOrientationDidChangeNotification, object: nil)
//HUD初始化
asHUD.layer.cornerRadius = 40
asHUD.type = NVActivityIndicatorType.BallTrianglePath
}
func didRotate(){
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(0.1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {[unowned self] () -> Void in
if self.imageV.image != nil {self.imageIsLoaded(self.imageV.image!, needAnim: false)}
})
}
func doubleTap(tapG: UITapGestureRecognizer){
if !hasHDImage {return}
let location = tapG.locationInView(tapG.view)
if scrollView.zoomScale <= 1 {
if !(imageV.convertRect(imageV.bounds, toView: imageV.superview).contains(location)) {return}
let location = tapG.locationInView(tapG.view)
let rect = CGRectMake(location.x, location.y, 10, 10)
scrollView.zoomToRect(rect, animated: true)
}else{
scrollView.setZoomScale(1, animated: true)
}
}
func singleTap(tapG: UITapGestureRecognizer){
NSNotificationCenter.defaultCenter().postNotificationName(CFPBSingleTapNofi, object: nil)
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {return layoutView}
/** 复位 */
func reset(){
scrollView.setZoomScale(1, animated: false)
msgContentTextView.setContentOffset(CGPointZero, animated: false)
}
/** 数据填充 */
func dataFill(){
if photoType == PhotoBrowser.PhotoType.Local {
/** 本地图片模式 */
hasHDImage = true
/** 图片 */
imageV.image = photoModel.localImg
/** 图片数据已经装载 */
imageIsLoaded(photoModel.localImg, needAnim: false)
}else{
self.hasHDImage = false
self.imgVHC.constant = CFPBThumbNailWH
self.imgVWC.constant = CFPBThumbNailWH
self.imageV.image = nil
/** 服务器图片模式 */
let url = NSURL(string: photoModel.hostHDImgURL)!
if cache == nil {cache = Cache<UIImage>(name: CFPBCacheKey)}
if format == nil{format = Format(name: photoModel.hostHDImgURL, diskCapacity: 10 * 1024 * 1024, transform: { img in
return img
})}
cache.fetch(key: photoModel.hostHDImgURL, failure: {[unowned self] fail in
if !self.isAlive {return}
self.showAsHUD()
self.imageV.image = self.photoModel.hostThumbnailImg
self.cache.fetch(URL: NSURL(string: self.photoModel.hostHDImgURL)!, failure: {fail in
println("失败\(fail)")
}, success: {[unowned self] img in
if !NSUserDefaults.standardUserDefaults().boolForKey(CFPBShowKey) {return}
if !self.isAlive {return}
if self.photoModel?.excetionFlag == false {return}
if self.photoModel.modelCell !== self {return}
self.hasHDImage = true
self.dismissAsHUD(true)
self.imageIsLoaded(img, needAnim: true)
self.imageV.image = img
})
}, success: {[unowned self] img in
if !self.isAlive {return}
self.dismissAsHUD(false)
self.imageV.image = img
self.hasHDImage = true
/** 图片数据已经装载 */
if !self.isFix && self.vc.view.bounds.size.width > self.vc.view.bounds.size.height{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(0.06 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {[unowned self] () -> Void in
self.imageIsLoaded(img, needAnim: false)
self.isFix = true
})
}else{
self.imageIsLoaded(img, needAnim: false)
}
})
}
/** 标题 */
if photoModel.titleStr != nil {msgTitleLabel.text = photoModel.titleStr}
/** 内容 */
if photoModel.descStr != nil {msgContentTextView.text = photoModel.descStr}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
Int64(0.1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {[unowned self] () -> Void in
self.reset()
}
}
func toggleDisplayBottomBar(isHidden: Bool){
bottomContentView.hidden = isHidden
}
/** 图片数据已经装载 */
func imageIsLoaded(img: UIImage,needAnim: Bool){
if !hasHDImage {return}
if vc == nil{return}
//图片尺寸
let imgSize = img.size
var boundsSize = self.bounds.size
//这里有一个奇怪的bug,横屏时,bounds居然是竖屏的bounds
if vc.view.bounds.size.width > vc.view.bounds.size.height {
if boundsSize.width < boundsSize.height {
boundsSize = CGSizeMake(boundsSize.height, boundsSize.width)
}
}
let contentSize = boundsSize.sizeMinusExtraWidth
let showSize = CGSize.decisionShowSize(imgSize, contentSize: contentSize)
dispatch_async(dispatch_get_main_queue(), {[unowned self] () -> Void in
self.imgVHC.constant = showSize.height
self.imgVWC.constant = showSize.width
if self.photoModel.isLocal! {return}
if !needAnim{return}
UIView.animateWithDuration(0.25, animations: {[unowned self] () -> Void in
UIView.setAnimationCurve(UIViewAnimationCurve.EaseOut)
self.imageV.setNeedsLayout()
self.imageV.layoutIfNeeded()
})
})
}
/** 展示进度HUD */
func showAsHUD(){
if asHUD == nil {return}
self.asHUD?.hidden = false
asHUD?.startAnimation()
UIView.animateWithDuration(0.25, animations: {[unowned self] () -> Void in
self.asHUD?.alpha = 1
})
}
/** 移除 */
func dismissAsHUD(needAnim: Bool){
if asHUD == nil {return}
if needAnim{
UIView.animateWithDuration(0.25, animations: {[unowned self] () -> Void in
self.asHUD?.alpha = 0
}) { (complete) -> Void in
self.asHUD?.hidden = true
self.asHUD?.stopAnimation()
}
}else{
self.asHUD?.alpha = 0
self.asHUD?.hidden = true
self.asHUD?.stopAnimation()
}
}
} | 898f8745e06cf880d164c8af123b4050 | 28.429003 | 160 | 0.535216 | false | false | false | false |
srosskopf/Geschmacksbildung | refs/heads/master | Geschmacksbildung/Geschmacksbildung/AboutController.swift | mit | 1 | //
// AboutController.swift
// Geschmacksbildung
//
// Created by Sebastian Roßkopf on 07.07.16.
// Copyright © 2016 sebastian rosskopf. All rights reserved.
//
import UIKit
class AboutController: UIViewController {
@IBOutlet var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("About", ofType: "rtf")
let textURL = NSURL.fileURLWithPath(path!)
let options = [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType]
let attribText = try! NSAttributedString(URL: textURL, options: options, documentAttributes: nil)
textView.attributedText = attribText
self.textView.scrollRangeToVisible(NSMakeRange(0, 0))
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 12aca31db942b4563c0d919568b90fba | 29.6 | 106 | 0.68337 | false | false | false | false |
WhatsTaste/WTImagePickerController | refs/heads/master | Vendor/Controllers/WTEditingViewController.swift | mit | 1 | //
// WTEditingViewController.swift
// WTImagePickerController
//
// Created by Jayce on 2017/2/8.
// Copyright © 2017年 WhatsTaste. All rights reserved.
//
import UIKit
import Photos
@objc protocol WTEditingViewControllerDelegate: class {
func editingViewController(_ controller: WTEditingViewController, didFinishWithResult result: WTEditingResult, forAsset asset: PHAsset?)
@objc optional func editingViewControllerDidCancel(_ controller: WTEditingViewController)
}
class WTEditingViewController: UIViewController, WTEditingViewDelegate {
convenience init(image: UIImage, asset: PHAsset? = nil, originalResult: WTEditingResult? = nil) {
self.init(nibName: nil, bundle: nil)
self.image = image
self.asset = asset
self.originalResult = originalResult
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
edgesForExtendedLayout = .all
view.backgroundColor = UIColor.black
view.addSubview(editingView)
view.addConstraint(NSLayoutConstraint.init(item: editingView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint.init(item: view, attribute: .right, relatedBy: .equal, toItem: editingView, attribute: .right, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint.init(item: editingView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint.init(item: view, attribute: .bottom, relatedBy: .equal, toItem: editingView, attribute: .bottom, multiplier: 1, constant: 0))
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
editingView.cropView.layout()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: false)
}
override var prefersStatusBarHidden: Bool {
return true
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: - WTEditingViewDelegate
func editingViewDidCancel(_ view: WTEditingView) {
delegate?.editingViewControllerDidCancel?(self)
_ = navigationController?.popViewController(animated: true)
}
func editingView(_ view: WTEditingView, didFinishWithResult result: WTEditingResult) {
delegate?.editingViewController(self, didFinishWithResult: result, forAsset: asset)
_ = navigationController?.popViewController(animated: true)
}
// MARK: - Private
// MARK: - Properties
weak public var delegate: WTEditingViewControllerDelegate?
lazy public private(set) var editingView: WTEditingView = {
let view = WTEditingView(frame: self.view.bounds, image: self.image, originalResult: self.originalResult)
view.translatesAutoresizingMaskIntoConstraints = false
view.delegate = self
return view
}()
private var image: UIImage!
private var originalResult: WTEditingResult?
private var asset: PHAsset?
}
| b89f16e5c419eecdfbf5506546e53d92 | 35.112245 | 171 | 0.692569 | false | false | false | false |
soxjke/Redux-ReactiveSwift | refs/heads/master | Example/Simple-Weather-App/Simple-Weather-App/Models/Weather.swift | mit | 1 | //
// Weather.swift
// Simple-Weather-App
//
// Created by Petro Korienev on 10/26/17.
// Copyright © 2017 Sigma Software. All rights reserved.
//
import Foundation
import ObjectMapper
enum WeatherValue<Value> {
case single(value: Value)
case minmax(min: Value, max: Value)
}
struct WeatherFeature<T> {
let unit: String
let value: WeatherValue<T>
}
struct DayNightWeather {
let windSpeed: WeatherFeature<Double>
let windDirection: String
let precipitationProbability: Int
let phrase: String
let icon: Int
}
// Since Swift 3.1 there's a neat feature called "Type nesting with generics" is
// around, however implementation is buggy and leads to runtime error
// https://bugs.swift.org/browse/SR-4383
// As a workaround, WeatherValue, WeatherFeature, DayNightWeather are standalone types
struct Weather {
let effectiveDate: Date
let temperature: WeatherFeature<Double>
let realFeel: WeatherFeature<Double>
let day: DayNightWeather
let night: DayNightWeather
}
extension Weather: ImmutableMappable {
init(map: Map) throws {
effectiveDate = try map.value("EpochDate", using: DateTransform())
temperature = try map.value("Temperature")
realFeel = try map.value("RealFeelTemperature")
day = try map.value("Day")
night = try map.value("Night")
}
func mapping(map: Map) {
}
}
extension WeatherFeature: ImmutableMappable {
init(map: Map) throws {
if let minimum: T = try? map.value("Minimum.Value"),
let maximum: T = try? map.value("Maximum.Value") { // Min/max
unit = try map.value("Minimum.Unit")
value = .minmax(min: minimum, max: maximum)
}
else { // Single value
unit = try map.value("Unit")
value = .single(value: try map.value("Value"))
}
}
func mapping(map: Map) {
}
}
extension DayNightWeather: ImmutableMappable {
init(map: Map) throws {
windSpeed = try map.value("Wind.Speed")
windDirection = (try? map.value("Wind.Direction.Localized")) ?? ((try? map.value("Wind.Direction.English")) ?? "")
precipitationProbability = try map.value("PrecipitationProbability")
phrase = try map.value("LongPhrase")
icon = try map.value("Icon")
}
func mapping(map: Map) {
}
}
struct CurrentWeather {
let effectiveDate: Date
let phrase: String
let icon: Int
let temperature: WeatherFeature<Double>
let realFeel: WeatherFeature<Double>
let windSpeed: WeatherFeature<Double>
let windDirection: String
}
extension CurrentWeather: ImmutableMappable {
private static let UnitSystem = Locale.current.usesMetricSystem ? "Metric" : "Imperial"
init(map: Map) throws {
effectiveDate = try map.value("EpochTime", using: DateTransform())
temperature = try map.value("Temperature.\(CurrentWeather.UnitSystem)")
realFeel = try map.value("RealFeelTemperature.\(CurrentWeather.UnitSystem)")
windSpeed = try map.value("Wind.Speed.\(CurrentWeather.UnitSystem)")
windDirection = (try? map.value("Wind.Direction.Localized")) ?? ((try? map.value("Wind.Direction.English")) ?? "")
phrase = try map.value("WeatherText")
icon = try map.value("WeatherIcon")
}
func mapping(map: Map) {
}
}
| e90c81e060ec427e16760451030330c0 | 30.641509 | 122 | 0.658915 | false | false | false | false |
jangxyz/springy | refs/heads/master | springy-swift/springy/Renderer.swift | mit | 1 | //
// Renderer.swift
// springy
//
// Created by 김장환 on 1/16/15.
// Copyright (c) 2015 김장환. All rights reserved.
//
import Foundation
class Renderer:GraphListener {
var layout:ForceDirectedLayout
let clear: () -> ()
let drawEdge: (Edge, Point, Point) -> ()
let drawNode: (Node, Point) -> ()
let onRenderStop: () -> ()
let onRenderStart: () -> ()
init(layout:ForceDirectedLayout,
clear: () -> () = {},
drawEdge: (Edge, Point, Point) -> () = { (_,_,_) in return },
drawNode: (Node, Point) -> () = { (_,_) in return },
onRenderStart: () -> () = {},
onRenderStop: () -> () = {}
) {
self.layout = layout
self.clear = clear
self.drawEdge = drawEdge
self.drawNode = drawNode
self.onRenderStop = onRenderStop
self.onRenderStart = onRenderStart
}
func graphChanged() {
// self.start()
}
} | dc4c85167a116bcd389102dfefa38615 | 24.052632 | 73 | 0.519453 | false | false | false | false |
txstate-etc/mobile-tracs-ios | refs/heads/master | mobile-tracs-ios/MenuViewController.swift | mit | 1 | //
// MenuViewController.swift
// mobile-tracs-ios
//
// Created by Nick Wing on 5/29/17.
// Copyright © 2017 Texas State University. All rights reserved.
//
import UIKit
import StoreKit
class MenuViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SKStoreProductViewControllerDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
NotificationCenter.default.addObserver(self, selector: #selector(deselectRow), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(deselectRow), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewWillAppear(_ animated: Bool) {
deselectRow()
}
// MARK: - Helper functions
func deselectRow() {
if let ip = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: ip, animated: true)
}
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 4
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows: Int
switch section {
case 1:
rows = 3
default:
rows = 1
}
return rows
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "menuitem", for: indexPath)
cell.accessoryType = .disclosureIndicator
switch indexPath.section {
case 0:
if indexPath.row == 0 {
cell.textLabel?.text = "Notification Settings"
}
case 1:
switch indexPath.row {
case 0:
cell.textLabel?.text = "About the App"
case 1:
cell.textLabel?.text = "Give us Feedback"
case 2:
cell.textLabel?.text = "TRACS Support"
default:
break
}
case 2:
if indexPath.row == 0 {
cell.textLabel?.text = "Go to TXST Mobile"
}
case 3:
if indexPath.row == 0 {
cell.textLabel?.text = "Logout"
}
default:
break
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 && indexPath.row == 0 {
let settingsStoryBoard = UIStoryboard(name: "MainStory", bundle: nil)
let settingsVC = settingsStoryBoard.instantiateViewController(withIdentifier: "NotificationSettings")
navigationController?.pushViewController(settingsVC, animated: true)
} else if indexPath.section == 1 {
if indexPath.row == 0 {
let vc = IntroViewController()
self.present(vc, animated: true, completion: nil)
} else if indexPath.row == 1 { // Give us Feedback
let vc = FeedbackViewController()
vc.urltoload = Secrets.shared.surveyurl
navigationController?.pushViewController(vc, animated: true)
} else if indexPath.row == 2 { // TRACS Support
let vc = FeedbackViewController()
vc.urltoload = Secrets.shared.contacturl
navigationController?.pushViewController(vc, animated: true)
}
} else if indexPath.section == 2 && indexPath.row == 0 {
if let url = URL(string: "edu.txstate.mobile://") {
Analytics.event(category: "External", action: "click", label: url.absoluteString, value: nil)
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
} else {
let appstore = SKStoreProductViewController()
appstore.delegate = self
let parameters = [SKStoreProductParameterITunesItemIdentifier:NSNumber(value: 373345139)]
appstore.loadProduct(withParameters: parameters, completionBlock: { (result, err) in
if result {
self.present(appstore, animated: true, completion: nil)
}
})
}
}
} else if indexPath.section == 3 && indexPath.row == 0 {
TRACSClient.userid = ""
Utils.removeCredentials()
IntegrationClient.unregister()
TRACSClient.sitecache.reset()
let navCon = self.tabBarController!
navCon.selectedIndex = 1
UIApplication.shared.applicationIconBadgeNumber = 0
let cookies = HTTPCookieStorage.shared.cookies
for cookie in cookies! {
if cookie.name == "JSESSIONID" {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}
for cookie in HTTPCookieStorage.shared.cookies! {
print("\(cookie.name): \(cookie.value)")
}
}
}
// MARK: - SKStoreProductViewControllerDelegate
func productViewControllerDidFinish(_ viewController: SKStoreProductViewController) {
viewController.dismiss(animated:true, completion:nil)
}
}
| 068772b2410c3c11ccc7a7faca81d482 | 36.236842 | 159 | 0.578622 | false | false | false | false |
rb-de0/Fluxer | refs/heads/master | FluxerTests/Observable/ConnectableObservableTests.swift | mit | 1 | //
// ConnectableObservableTests.swift
// Fluxer
//
// Created by rb_de0 on 2017/04/11.
// Copyright © 2017年 rb_de0. All rights reserved.
//
import XCTest
@testable import Fluxer
class ConnectableObservableTests: XCTestCase {
func testNotConnect() {
let value = ObservableValue(0)
let connectableValue = ConnectableObservable(value)
var bindableValue = -1
_ = connectableValue.subscribe {
bindableValue = $0
}
value.value = 10
XCTAssertEqual(bindableValue, -1)
}
func testConnect() {
let value = ObservableValue(0)
let connectableValue = ConnectableObservable(value)
var bindableValue = -1
let disposeBag = DisposeBag()
connectableValue.connect().addTo(disposeBag)
_ = connectableValue.subscribe {
bindableValue = $0
}
value.value = 10
XCTAssertEqual(bindableValue, 10)
}
func testDispose() {
let value = ObservableValue(0)
let connectableValue = ConnectableObservable(value)
var bindableValue = -1
let disposeBag = DisposeBag()
connectableValue.connect().addTo(disposeBag)
let disposable = connectableValue.subscribe {
bindableValue = $0
}
value.value = 10
XCTAssertEqual(bindableValue, 10)
disposable.dispose()
value.value = 5
XCTAssertEqual(bindableValue, 10)
}
func testDisconnect() {
let value = ObservableValue(0)
let connectableValue = ConnectableObservable(value)
var bindableValue = -1
let disposable = connectableValue.connect()
_ = connectableValue.subscribe {
bindableValue = $0
}
value.value = 10
XCTAssertEqual(bindableValue, 10)
disposable.dispose()
value.value = 5
XCTAssertEqual(bindableValue, 10)
}
}
| 5c42c9c10a03fc4a0b2bfcc2344c18fb | 22.204301 | 59 | 0.548656 | false | true | false | false |
xeo-it/poggy | refs/heads/master | Poggy/TableCells/ActionCell.swift | apache-2.0 | 1 | //
// ActionCell.swift
// Poggy
//
// Created by Francesco Pretelli on 26/04/16.
// Copyright © 2016 Francesco Pretelli. All rights reserved.
//
import Foundation
import UIKit
import SDWebImage
class ActionCell:UITableViewCell {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var recipientLabel: UILabel!
@IBOutlet weak var currentActionImage: UIImageView!
func updateData(action:PoggyAction) {
if let description = action.actionDescription {
descriptionLabel.text = description
}
if let channel = action.slackChannel {
recipientLabel.text = channel.name
if let teamIcon = channel.teamIcon {
currentActionImage.sd_setImageWithURL(NSURL(string: (teamIcon)),placeholderImage: UIImage(named:"Slack-Icon"), options: [SDWebImageOptions.RetryFailed ])
}
} else if let user = action.slackUser {
recipientLabel.text = user.username
if let userIcon = user.profileImage {
currentActionImage.sd_setImageWithURL(NSURL(string: (userIcon)),placeholderImage: UIImage(named:"Alien-Icon"), options: [SDWebImageOptions.RetryFailed ])
}
}
if let team = action.slackTeam {
recipientLabel.text = recipientLabel.text! + " - " + team
}
}
override func prepareForReuse() {
descriptionLabel.text = ""
recipientLabel.text = ""
}
}
| 4109daeee21ca98640c0a7d8d99ba6e6 | 31.673913 | 171 | 0.630739 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Tool/Sources/ToolKit/Utilities/Cache/CacheNew.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
/// A value returned by a cache.
///
/// The cache consumers can request stale cache values (in order to speed up apparent loading times), which should be handled accordingly.
public enum CacheValue<Value>: CustomStringConvertible {
/// Absent cache value.
case absent
/// Stale cache value.
case stale(Value)
/// Present and non-stale cache value.
case present(Value)
// MARK: - Public Properties
public var description: String {
switch self {
case .absent:
return "absent"
case .stale(let value):
return "stale(\(value))"
case .present(let value):
return "present(\(value))"
}
}
}
extension CacheValue: Equatable where Value: Equatable {}
/// A cache, representing a key-value data store.
public protocol CacheAPI {
/// A key used as a cache index.
associatedtype Key: Hashable
/// A value stored in the cache.
associatedtype Value: Equatable
/// Gets the cache value associated with the given key.
///
/// - Parameter key: The key to look up in the cache.
///
/// - Returns: A publisher that emits the cache value.
func get(key: Key) -> AnyPublisher<CacheValue<Value>, Never>
/// Streams the cache value associated with the given key, including any subsequent updates.
///
/// - Parameter key: The key to look up in the cache.
///
/// - Returns: A publisher that streams the cache value, including any subsequent updates.
func stream(key: Key) -> AnyPublisher<CacheValue<Value>, Never>
/// Stores the given value, associating it with the given key.
///
/// - Parameters:
/// - value: A value to store inside the cache.
/// - key: The key to associate with `value`.
///
/// - Returns: A publisher that emits the replaced value, or `nil` if a new value was stored.
func set(_ value: Value, for key: Key) -> AnyPublisher<Value?, Never>
/// Removes the value associated with the given key.
///
/// - Parameter key: The key to look up in the cache.
///
/// - Returns: A publisher that emits the removed value, or `nil` if the key was not present in the cache.
func remove(key: Key) -> AnyPublisher<Value?, Never>
/// Removes all the stored values.
///
/// - Returns: A publisher that emits a void value.
func removeAll() -> AnyPublisher<Void, Never>
}
/// A type-erased cache.
public final class AnyCache<Key: Hashable, Value: Equatable>: CacheAPI {
// MARK: - Private Properties
private let getKey: (Key) -> AnyPublisher<CacheValue<Value>, Never>
private let streamKey: (Key) -> AnyPublisher<CacheValue<Value>, Never>
private let setKey: (Value, Key) -> AnyPublisher<Value?, Never>
private let removeKey: (Key) -> AnyPublisher<Value?, Never>
private let removeAllKeys: () -> AnyPublisher<Void, Never>
// MARK: - Setup
/// Creates a type-erased cache that wraps the given instance.
///
/// - Parameter cache: A cache to wrap.
public init<Cache: CacheAPI>(
_ cache: Cache
) where Cache.Key == Key, Cache.Value == Value {
getKey = cache.get
streamKey = cache.stream
setKey = cache.set
removeKey = cache.remove
removeAllKeys = cache.removeAll
}
// MARK: - Public Methods
public func get(key: Key) -> AnyPublisher<CacheValue<Value>, Never> {
getKey(key)
}
public func stream(key: Key) -> AnyPublisher<CacheValue<Value>, Never> {
streamKey(key)
}
public func set(_ value: Value, for key: Key) -> AnyPublisher<Value?, Never> {
setKey(value, key)
}
public func remove(key: Key) -> AnyPublisher<Value?, Never> {
removeKey(key)
}
public func removeAll() -> AnyPublisher<Void, Never> {
removeAllKeys()
}
}
extension CacheAPI {
/// Wraps this cache with a type eraser.
public func eraseToAnyCache() -> AnyCache<Key, Value> {
AnyCache(self)
}
}
| 4f505e522d421cea925a178437f38681 | 28.496403 | 138 | 0.632195 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/SwiftUI/SwiftUI-master/Example/Example/Page/Picker/DatePickerPage.swift | mit | 1 | //
// PickerPage.swift
// Example
//
// Created by 晋先森 on 2019/6/8.
// Copyright © 2019 晋先森. All rights reserved.
//
import SwiftUI
import Combine
struct DatePickerPage : View {
@ObservedObject var server = DateServer()
var speaceDate: Range<Date>?
init() {
let soon = Calendar.current.date(byAdding: .year,
value: -1,
to: server.date) ?? Date()
let later = Calendar.current.date(byAdding: .year,
value: 1,
to: server.date) ?? Date()
speaceDate = soon..<later
}
var body: some View {
VStack {
VStack(spacing: 10) {
Text("日期选择").bold()
DatePicker(selection: $server.date, in: server.spaceDate, displayedComponents: .date, label: {
Text("")
})
}
.padding(.top)
.navigationBarTitle(Text("DatePicker"))
}
}
}
class DateServer: ObservableObject {
var didChange = PassthroughSubject<DateServer,Never>()
var date: Date = Date() {
didSet {
didChange.send(self)
print("Date Changed: \(date)")
}
}
var spaceDate: ClosedRange<Date> {
let soon = Calendar.current.date(byAdding: .year,
value: -1,
to: date) ?? Date()
let later = Calendar.current.date(byAdding: .year,
value: 1,
to: date) ?? Date()
let speaceDate = soon...later
return speaceDate
}
}
#if DEBUG
struct DatePickerPage_Previews : PreviewProvider {
static var previews: some View {
DatePickerPage()
}
}
#endif
| 1093d544fabf29b42806048633da4c13 | 24.467532 | 110 | 0.45589 | false | false | false | false |
apple/swift-format | refs/heads/main | Sources/SwiftFormatRules/NoEmptyTrailingClosureParentheses.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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 SwiftFormatCore
import SwiftSyntax
/// Function calls with no arguments and a trailing closure should not have empty parentheses.
///
/// Lint: If a function call with a trailing closure has an empty argument list with parentheses,
/// a lint error is raised.
///
/// Format: Empty parentheses in function calls with trailing closures will be removed.
public final class NoEmptyTrailingClosureParentheses: SyntaxFormatRule {
public override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
guard node.argumentList.count == 0 else { return super.visit(node) }
guard let trailingClosure = node.trailingClosure,
node.argumentList.isEmpty && node.leftParen != nil else
{
return super.visit(node)
}
guard let name = node.calledExpression.lastToken?.withoutTrivia() else {
return super.visit(node)
}
diagnose(.removeEmptyTrailingParentheses(name: "\(name)"), on: node)
// Need to visit `calledExpression` before creating a new node so that the location data (column
// and line numbers) is available.
guard let rewrittenCalledExpr = ExprSyntax(visit(Syntax(node.calledExpression))) else {
return super.visit(node)
}
let formattedExp = replaceTrivia(
on: rewrittenCalledExpr,
token: rewrittenCalledExpr.lastToken,
trailingTrivia: .spaces(1))
let formattedClosure = visit(trailingClosure).as(ClosureExprSyntax.self)
let result = node.withLeftParen(nil).withRightParen(nil).withCalledExpression(formattedExp)
.withTrailingClosure(formattedClosure)
return ExprSyntax(result)
}
}
extension Finding.Message {
public static func removeEmptyTrailingParentheses(name: String) -> Finding.Message {
"remove '()' after \(name)"
}
}
| 97ae6d3c817b7e9902c1b57348284fea | 38.362069 | 100 | 0.681121 | false | false | false | false |
SwiftKitz/Sandbox | refs/heads/master | Kitz/Kitz/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Kitz
//
// Created by Mazyad Alabduljaleel on 12/19/15.
// Copyright © 2015 kitz. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| 16b11dc15b33ca3c444c7bfd0714b7a0 | 53.540984 | 285 | 0.764953 | false | false | false | false |
senojsitruc/libSwerve | refs/heads/master | libSwerve/libSwerve/CJHttpServerRequestImpl.swift | mit | 1 | //
// CJHttpServerRequestImpl.swift
// libSwerve
//
// Created by Curtis Jones on 2016.03.19.
// Copyright © 2016 Symphonic Systems, Inc. All rights reserved.
//
import Foundation
internal class CJHttpServerRequestImpl: CJHttpServerRequest {
var method: CJHttpMethod
var path: String
var query: String
var version: String
var headers = [String: CJHttpHeader]()
var values: [String: AnyObject]?
var contentHandler: ((AnyObject?, Bool) -> Void)?
private var connection: CJHttpConnection?
private var completionHandler: (() -> Void)?
required init(methodName: String, path: String, version: String, connection: CJHttpConnection?, completionHandler: (() -> Void)?) {
self.connection = connection
self.completionHandler = completionHandler
method = CJHttpMethod(rawValue: methodName ?? "") ?? .None
// separate the path from the query (if any)
do {
if let qrange = path.rangeOfString("?") {
self.path = path.substringToIndex(qrange.startIndex)
self.query = path.substringFromIndex(qrange.startIndex)
}
else {
self.path = path
self.query = ""
}
}
self.version = version
}
func addHeader(header: CJHttpHeader) {
guard var existingHeader = headers[header.name] else {
headers[header.name] = header
return
}
existingHeader.mergeHeader(header)
headers[header.name] = existingHeader
}
///
/// A connection is paused when the header is received and we need to the "user" to configure the
/// request for receiving whatever data may follow. Thus, after configuring the request, the user
/// will call resume(), and we'll telling the http connection to resume() which'll tell the under-
/// lying tcp connection to resume.
///
func resume() {
connection?.resume()
}
///
/// called by the response when the response is complete
///
func cleanup() {
completionHandler?()
completionHandler = nil
connection = nil
}
}
| 0421b8d7bb1b0ebef73e4e369479784c | 24.653333 | 132 | 0.699064 | false | false | false | false |
mittenimraum/CVGenericDataSource | refs/heads/master | Sources/CVGenericDataSourceBridge.swift | mit | 1 | //
// CVDataSourceBridge.swift
// CVGenericDataSource
//
// Created by Stephan Schulz on 12.04.17.
// Copyright © 2017 Stephan Schulz. All rights reserved.
//
import Foundation
import UIKit
// MARK: - Typealiases
internal typealias NumberOfSections = () -> Int
internal typealias NumberOfItemsInSection = (Int) -> Int
internal typealias CollectionCellForItemAtIndexPath = (UICollectionView, IndexPath) -> UICollectionViewCell
internal typealias CollectionSupplementaryViewAtIndexPath = (UICollectionView, String, IndexPath) -> UICollectionReusableView
internal typealias SizeForItemAtIndexPath = (UICollectionView, UICollectionViewLayout, IndexPath) -> CGSize
internal typealias InsetsForSectionAtIndex = (UICollectionView, UICollectionViewLayout, Int) -> UIEdgeInsets
internal typealias DidSelectItemAtIndexPath = (UICollectionView, IndexPath) -> Void
internal typealias SizeForHeaderInSection = (UICollectionView, UICollectionViewLayout, Int) -> CGSize
internal typealias SizeForFooterInSection = (UICollectionView, UICollectionViewLayout, Int) -> CGSize
internal typealias WillDisplayCell = (UICollectionView, UICollectionViewCell, IndexPath) -> Void
internal typealias WillDisplaySupplementaryView = (UICollectionView, UICollectionReusableView, String, IndexPath) -> Void
internal typealias DidEndDisplayingCell = (UICollectionView, UICollectionViewCell, IndexPath) -> Void
internal typealias DidEndDisplayingSupplementaryView = (UICollectionView, UICollectionReusableView, String, IndexPath) -> Void
internal typealias ScrollViewDidScroll = (UIScrollView) -> Void
internal typealias LineSpacingForSection = (Int) -> CGFloat
internal typealias CellSpacingForSection = (Int) -> CGFloat
internal typealias PrefetchItems = (UICollectionView, [IndexPath]) -> Void
internal typealias CancelPrefetchItems = (UICollectionView, [IndexPath]) -> Void
// MARK: - CVDataSourceBridge
@objc internal final class CVDataSourceBridge: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDataSourcePrefetching {
// MARK: - Constants
let numberOfSections: NumberOfSections
let numberOfItemsInSection: NumberOfItemsInSection
// MARK: - Variables
var collectionCellForItemAtIndexPath: CollectionCellForItemAtIndexPath?
var collectionSupplementaryViewAtIndexPath: CollectionSupplementaryViewAtIndexPath?
var sizeForItemAtIndexPath: SizeForItemAtIndexPath?
var insetsForSectionAtIndex: InsetsForSectionAtIndex?
var selectionAtIndexPath: DidSelectItemAtIndexPath?
var sizeForHeaderInSection: SizeForHeaderInSection?
var sizeForFooterInSection: SizeForFooterInSection?
var willDisplayCell: WillDisplayCell?
var willDisplaySupplementaryView: WillDisplaySupplementaryView?
var didEndDisplayingCell: DidEndDisplayingCell?
var didEndDisplayingSupplementaryView: DidEndDisplayingSupplementaryView?
var scrollViewDidScroll: ScrollViewDidScroll?
var lineSpacingForSection: LineSpacingForSection?
var cellSpacingForSection: CellSpacingForSection?
var prefetchItems: PrefetchItems?
var cancelPrefetchItems: PrefetchItems?
// MARK: - Init
init(numberOfSections: @escaping NumberOfSections, numberOfItemsInSection: @escaping NumberOfItemsInSection) {
self.numberOfSections = numberOfSections
self.numberOfItemsInSection = numberOfItemsInSection
}
// MARK: - UICollectionViewDataSource / UICollectionViewDelegate
@objc func numberOfSections(in _: UICollectionView) -> Int {
return numberOfSections()
}
@objc func collectionView(_: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfItemsInSection(section)
}
@objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let collectionCellForItemAtIndexPath = collectionCellForItemAtIndexPath else {
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: UICollectionViewCell.ReuseIdentifier)
return collectionView.dequeueReusableCell(withReuseIdentifier: UICollectionViewCell.ReuseIdentifier, for: indexPath)
}
return collectionCellForItemAtIndexPath(collectionView, indexPath)
}
@objc func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard let collectionSupplementaryViewAtIndexPath = collectionSupplementaryViewAtIndexPath else {
collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: kind, withReuseIdentifier: UICollectionReusableView.ReuseIdentifier)
return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: UICollectionReusableView.ReuseIdentifier, for: indexPath)
}
return collectionSupplementaryViewAtIndexPath(collectionView, kind, indexPath)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
return sizeForItemAtIndexPath!(collectionView, collectionViewLayout, indexPath)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
guard let sizeForHeaderInSection = sizeForHeaderInSection else {
return CGSize.epsilon
}
return sizeForHeaderInSection(collectionView, collectionViewLayout, section)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
guard let sizeForFooterInSection = sizeForFooterInSection else {
return CGSize.epsilon
}
return sizeForFooterInSection(collectionView, collectionViewLayout, section)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
guard let insetsForSectionAtIndex = insetsForSectionAtIndex else {
return UIEdgeInsets.zero
}
return insetsForSectionAtIndex(collectionView, collectionViewLayout, section)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
guard let lineSpacingForSection = lineSpacingForSection else {
return 0
}
return lineSpacingForSection(section)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
guard let cellSpacingForSection = cellSpacingForSection else {
return 0
}
return cellSpacingForSection(section)
}
@objc func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let selectionAtIndexPath = selectionAtIndexPath else {
return
}
selectionAtIndexPath(collectionView, indexPath)
}
@objc func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let willDisplayCell = willDisplayCell else {
return
}
willDisplayCell(collectionView, cell, indexPath)
}
@objc func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
guard let willDisplaySupplementaryView = willDisplaySupplementaryView else {
return
}
willDisplaySupplementaryView(collectionView, view, elementKind, indexPath)
}
@objc func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let didEndDisplayingCell = didEndDisplayingCell else {
return
}
didEndDisplayingCell(collectionView, cell, indexPath)
}
@objc func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath) {
guard let didEndDisplayingSupplementaryView = didEndDisplayingSupplementaryView else {
return
}
didEndDisplayingSupplementaryView(collectionView, view, elementKind, indexPath)
}
@objc func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
guard let prefetchItems = prefetchItems else {
return
}
prefetchItems(collectionView, indexPaths)
}
@objc func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) {
guard let cancelPrefetchItems = cancelPrefetchItems else {
return
}
cancelPrefetchItems(collectionView, indexPaths)
}
@objc func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollViewDidScroll?(scrollView)
}
}
// MARK: - CVDataSource Bridge Extensions
public extension CVDataSource where CellFactory.View: UICollectionViewCell, SupplementaryFactory.View: UICollectionReusableView, CellFactory.Item == S.Item {
public func bind(collectionView: UICollectionView?) {
if bridgedDataSource == nil {
bridgedDataSource = bridge()
}
bindDataSourceTo(collectionView: collectionView)
guard self.collectionView != collectionView else {
return
}
self.collectionView = collectionView
}
internal func bridge() -> CVDataSourceBridge {
let dataSource = CVDataSourceBridge(
numberOfSections: { [unowned self]() -> Int in
self.numberOfSections()
},
numberOfItemsInSection: { [unowned self](section) -> Int in
self.numberOfItems(inSection: section)
})
dataSource.collectionCellForItemAtIndexPath = { [unowned self](collectionView, indexPath) -> UICollectionViewCell in
self.cellFactory.cell(item: self.item(atIndexPath: indexPath), collectionView: collectionView, indexPath: indexPath)
}
dataSource.collectionSupplementaryViewAtIndexPath = { [unowned self](collectionView, kind, indexPath) -> UICollectionReusableView in
guard self.supplementaryViewFactory != nil else {
collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: UICollectionReusableView.ReuseIdentifier)
return collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: UICollectionReusableView.ReuseIdentifier, for: indexPath)
}
return self.supplementaryViewFactory.view(kind: kind, collectionView: collectionView, indexPath: indexPath)
}
dataSource.sizeForItemAtIndexPath = { [unowned self](_, _, indexPath) -> CGSize in
self.cellFactory.sizeFor(item: self.item(atIndexPath: indexPath), atIndexPath: indexPath)
}
dataSource.insetsForSectionAtIndex = { [unowned self](_, _, section) -> UIEdgeInsets in
if section < self.numberOfSections(), let insets = self.sections[section].insets {
return insets
}
if let insets = self.optionSectionInsets {
return insets(section)
}
return self.optionInsets
}
dataSource.selectionAtIndexPath = { [unowned self](collectionView, indexPath) -> Void in
guard let cell = collectionView.cellForItem(at: indexPath) as? CellFactory.View else {
return
}
let item = self.item(atIndexPath: indexPath)
self.sections[indexPath.section].selection(item, indexPath.row)
self.optionSelect?(indexPath.section, item, cell, indexPath)
}
dataSource.sizeForHeaderInSection = { [unowned self](collectionView, collectionViewLayout, section) -> CGSize in
if let shouldShowSection = self.optionShouldShowSection, !shouldShowSection(section) {
return CGSize.epsilon
}
guard section < self.numberOfSections(), self.sections[section].headerShouldAppear, self.supplementaryViewFactory != nil else {
return CGSize.epsilon
}
return self.supplementaryViewFactory.size(kind: UICollectionElementKindSectionHeader, collectionView: collectionView, collectionViewLayout: collectionViewLayout, section: section)
}
dataSource.sizeForFooterInSection = { [unowned self](collectionView, collectionViewLayout, section) -> CGSize in
guard section < self.numberOfSections(), self.sections[section].footerShouldAppear, self.supplementaryViewFactory != nil else {
return CGSize.epsilon
}
return self.supplementaryViewFactory.size(kind: UICollectionElementKindSectionFooter, collectionView: collectionView, collectionViewLayout: collectionViewLayout, section: section)
}
dataSource.willDisplayCell = { (collectionView, cell, indexPath) -> Void in
cell.prepare()
}
dataSource.didEndDisplayingCell = { (collectionView, cell, indexPath) -> Void in
cell.cleanup()
}
dataSource.willDisplaySupplementaryView = { (collectionView, view, kind, indexPath) -> Void in
view.prepare()
}
dataSource.didEndDisplayingSupplementaryView = { (collectionView, view, kind, indexPath) -> Void in
view.cleanup()
}
dataSource.scrollViewDidScroll = { scrollView in
self.loadAutomatically()
}
dataSource.lineSpacingForSection = { section in
if let sectionLineSpacing = self.sections[section].lineSpacing {
return sectionLineSpacing
}
return self.optionLineSpacing
}
dataSource.cellSpacingForSection = { section in
if let sectionCellSpacing = self.sections[section].cellSpacing {
return sectionCellSpacing
}
return self.optionCellSpacing
}
dataSource.prefetchItems = { (collectionView, indexPaths) in
self.transform(indexPaths).forEach({ (section, items) in
self.optionPrefetch?(section, items)
})
}
dataSource.cancelPrefetchItems = { (collectionView, indexPaths) in
self.transform(indexPaths).forEach({ (section, items) in
self.optionCancelPrefetch?(section, items)
})
}
return dataSource
}
fileprivate func transform(_ indexPaths: [IndexPath]) -> [Int: [S.Item]] {
return indexPaths.reduce([:], { (result, indexPath) -> [Int: [S.Item]] in
var result = result
result[indexPath.section] = result[indexPath.section] ?? []
if let item = self.item(atIndexPath: indexPath) {
result[indexPath.section]?.append(item)
}
return result
})
}
}
public extension CVDataSource {
internal func bindDataSourceTo(collectionView: UICollectionView?) {
guard collectionView?.dataSource !== bridgedDataSource else {
return
}
if #available(iOS 10.0, *) {
collectionView?.prefetchDataSource = bridgedDataSource
}
collectionView?.dataSource = bridgedDataSource
collectionView?.delegate = bridgedDataSource
collectionView?.layoutIfNeeded()
}
}
public extension CVStateDataSource {
public func bind(collectionView: UICollectionView?) {
if bridgedDataSource == nil {
bridgedDataSource = bridge()
}
if #available(iOS 10.0, *) {
collectionView?.prefetchDataSource = bridgedDataSource
}
collectionView?.dataSource = bridgedDataSource
collectionView?.delegate = bridgedDataSource
collectionView?.layoutIfNeeded()
}
internal func bridge() -> CVDataSourceBridge {
let dataSource = CVDataSourceBridge(
numberOfSections: { () -> Int in
return 1
},
numberOfItemsInSection: { (section) -> Int in
return 1
})
dataSource.collectionCellForItemAtIndexPath = { [unowned self](collectionView, indexPath) -> UICollectionViewCell in
return self.stateFactory.cellFor(type: self.type, collectionView: collectionView, indexPath: indexPath) as! UICollectionViewCell
}
dataSource.sizeForItemAtIndexPath = { [unowned self](collectionView, collectionViewLayout, indexPath) -> CGSize in
return self.stateFactory.size(type: self.type, collectionView: collectionView, collectionViewLayout: collectionViewLayout, indexPath: indexPath)
}
dataSource.willDisplayCell = { (collectionView, cell, indexPath) -> Void in
cell.prepare()
}
dataSource.didEndDisplayingCell = { (collectionView, cell, indexPath) -> Void in
cell.cleanup()
}
return dataSource
}
}
// MARK: - CVDataSourceCache
final class CVDataSourceCache {
// MARK: - Constants
static let shared: CVDataSourceCache = CVDataSourceCache()
//MARK: - Variables
lazy var dictionary: [Int: [String]] = [:]
// MARK: - Init
private init() {
}
// MARK: - Convenience
func add(_ collectionView: UICollectionView, _ reuseIdentifier: String) -> Bool {
if has(collectionView, reuseIdentifier) {
return false
}
let collectionViewId = unsafeBitCast(collectionView, to: Int.self)
if dictionary[collectionViewId] == nil {
dictionary[collectionViewId] = []
}
dictionary[collectionViewId]?.append(reuseIdentifier)
return true
}
func has(_ collectionView: UICollectionView, _ reuseIdentifier: String) -> Bool {
let collectionViewId = unsafeBitCast(collectionView, to: Int.self)
guard let array = dictionary[collectionViewId], array.contains(reuseIdentifier) else {
return false
}
return true
}
func clear() {
dictionary.removeAll()
}
}
// MARK: - Extensions
extension CGSize {
static var epsilon: CGSize {
return CGSize(width: 0.0001, height: 0.0001)
}
}
| 63631d772ae208e0b48d4cccde1eaf6d | 44.607656 | 199 | 0.702214 | false | false | false | false |
ludagoo/Perfect | refs/heads/master | PerfectLib/SysProcess.swift | agpl-3.0 | 2 | //
// SysProcess.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/20/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
#if os(Linux)
import SwiftGlibc
let WUNTRACED = Int32(2)
let WNOHANG = Int32(1)
let SIGTERM = Int32(15)
#else
import Darwin
#endif
/// This class permits an external process to be launched given a set of command line arguments and environment variables.
/// The standard in, out and err file streams are made available. The process can be terminated or permitted to be run to completion.
public class SysProcess : Closeable {
/// The standard in file stream.
public var stdin: File?
/// The standard out file stream.
public var stdout: File?
/// The standard err file stream.
public var stderr: File?
/// The process identifier.
public var pid = pid_t(-1)
/// Initialize the object and launch the process.
/// - parameter cmd: The path to the process which will be launched.
/// - parameter args: An optional array of String arguments which will be given to the process.
/// - parameter env: An optional array of environment variable name and value pairs.
/// - throws: `LassoError.SystemError`
public init(_ cmd: String, args: [String]?, env: [(String,String)]?) throws {
let cArgsCount = args != nil ? args!.count : 0
let cArgs = UnsafeMutablePointer<UnsafeMutablePointer<CChar>>.alloc(cArgsCount + 2)
defer { cArgs.destroy() ; cArgs.dealloc(cArgsCount + 2) }
cArgs[0] = strdup(cmd)
cArgs[cArgsCount + 1] = UnsafeMutablePointer<CChar>(())
var idx = 0
while idx < cArgsCount {
cArgs[idx+1] = strdup(args![idx])
idx += 1
}
let cEnvCount = env != nil ? env!.count : 0
let cEnv = UnsafeMutablePointer<UnsafeMutablePointer<CChar>>.alloc(cEnvCount + 1)
defer { cEnv.destroy() ; cEnv.dealloc(cEnvCount + 1) }
cEnv[cEnvCount] = UnsafeMutablePointer<CChar>(())
idx = 0
while idx < cEnvCount {
cEnv[idx] = strdup(env![idx].0 + "=" + env![idx].1)
idx += 1
}
let fSTDIN = UnsafeMutablePointer<Int32>.alloc(2)
let fSTDOUT = UnsafeMutablePointer<Int32>.alloc(2)
let fSTDERR = UnsafeMutablePointer<Int32>.alloc(2)
defer {
fSTDIN.destroy() ; fSTDIN.dealloc(2)
fSTDOUT.destroy() ; fSTDOUT.dealloc(2)
fSTDERR.destroy() ; fSTDERR.dealloc(2)
}
pipe(fSTDIN)
pipe(fSTDOUT)
pipe(fSTDERR)
var action = posix_spawn_file_actions_t()
posix_spawn_file_actions_init(&action);
posix_spawn_file_actions_adddup2(&action, fSTDOUT[1], STDOUT_FILENO);
posix_spawn_file_actions_adddup2(&action, fSTDIN[0], STDIN_FILENO);
posix_spawn_file_actions_adddup2(&action, fSTDERR[1], STDERR_FILENO);
posix_spawn_file_actions_addclose(&action, fSTDOUT[0]);
posix_spawn_file_actions_addclose(&action, fSTDIN[0]);
posix_spawn_file_actions_addclose(&action, fSTDERR[0]);
posix_spawn_file_actions_addclose(&action, fSTDOUT[1]);
posix_spawn_file_actions_addclose(&action, fSTDIN[1]);
posix_spawn_file_actions_addclose(&action, fSTDERR[1]);
var procPid = pid_t()
let spawnRes = posix_spawnp(&procPid, cmd, &action, UnsafeMutablePointer<posix_spawnattr_t>(()), cArgs, cEnv)
posix_spawn_file_actions_destroy(&action)
idx = 0
while idx < cArgsCount {
free(cArgs[idx])
idx += 1
}
idx = 0
while idx < cEnvCount {
free(cEnv[idx])
idx += 1
}
#if os(Linux)
SwiftGlibc.close(fSTDIN[0])
SwiftGlibc.close(fSTDOUT[1])
SwiftGlibc.close(fSTDERR[1])
if spawnRes != 0 {
SwiftGlibc.close(fSTDIN[1])
SwiftGlibc.close(fSTDOUT[0])
SwiftGlibc.close(fSTDERR[0])
try ThrowSystemError()
}
#else
Darwin.close(fSTDIN[0])
Darwin.close(fSTDOUT[1])
Darwin.close(fSTDERR[1])
if spawnRes != 0 {
Darwin.close(fSTDIN[1])
Darwin.close(fSTDOUT[0])
Darwin.close(fSTDERR[0])
try ThrowSystemError()
}
#endif
self.pid = procPid
self.stdin = File(fd: fSTDIN[1], path: "")
self.stdout = File(fd: fSTDOUT[0], path: "")
self.stderr = File(fd: fSTDERR[0], path: "")
}
deinit {
self.close()
}
/// Returns true if the process was opened and was running at some point.
/// Note that the process may not be currently running. Use `wait(false)` to check if the process is currently running.
public func isOpen() -> Bool {
return self.pid != -1
}
/// Terminate the process and clean up.
public func close() {
if self.stdin != nil {
self.stdin!.close()
}
if self.stdout != nil {
self.stdout!.close()
}
if self.stderr != nil {
self.stderr!.close()
}
if self.pid != -1 {
do {
try self.kill()
} catch {
}
}
self.stdin = nil
self.stdout = nil
self.stderr = nil
self.pid = -1
}
/// Detach from the process such that it will not be manually terminated when this object is deinitialized.
public func detach() {
self.pid = -1
}
/// Determine if the process has completed running and retrieve its result code.
public func wait(hang: Bool = true) throws -> Int32 {
var code = Int32(0)
let status = waitpid(self.pid, &code, WUNTRACED | (hang ? 0 : WNOHANG))
if status == -1 {
try ThrowSystemError()
}
self.pid = -1
close()
return code
}
/// Terminate the process and return its result code.
public func kill(signal: Int32 = SIGTERM) throws -> Int32 {
#if os(Linux)
let status = SwiftGlibc.kill(self.pid, signal)
#else
let status = Darwin.kill(self.pid, signal)
#endif
guard status != -1 else {
try ThrowSystemError()
}
return try self.wait()
}
}
| 96b63e9ebcbd8b3b82df63a33a9064ad | 28.336406 | 133 | 0.685046 | false | false | false | false |
SwiftGen/StencilSwiftKit | refs/heads/stable | Sources/StencilSwiftKit/MapNode.swift | mit | 1 | //
// StencilSwiftKit
// Copyright © 2022 SwiftGen
// MIT Licence
//
import Stencil
internal final class MapNode: NodeType {
let resolvable: Resolvable
let resultName: String
let mapVariable: String?
let nodes: [NodeType]
let token: Token?
class func parse(parser: TokenParser, token: Token) throws -> NodeType {
let components = token.components
func hasToken(_ token: String, at index: Int) -> Bool {
components.indices ~= index + 1 && components[index] == token
}
func endsOrHasToken(_ token: String, at index: Int) -> Bool {
components.count == index || hasToken(token, at: index)
}
guard hasToken("into", at: 2) && endsOrHasToken("using", at: 4) else {
throw TemplateSyntaxError(
"""
'map' statements should use the following 'map {array} into \
{varname} [using {element}]'.
"""
)
}
let resolvable = try parser.compileResolvable(components[1], containedIn: token)
let resultName = components[3]
let mapVariable = hasToken("using", at: 4) ? components[5] : nil
let mapNodes = try parser.parse(until(["endmap", "empty"]))
guard let token = parser.nextToken() else {
throw TemplateSyntaxError("`endmap` was not found.")
}
if token.contents == "empty" {
_ = parser.nextToken()
}
return MapNode(
resolvable: resolvable,
resultName: resultName,
mapVariable: mapVariable,
nodes: mapNodes,
token: token
)
}
init(resolvable: Resolvable, resultName: String, mapVariable: String?, nodes: [NodeType], token: Token? = nil) {
self.resolvable = resolvable
self.resultName = resultName
self.mapVariable = mapVariable
self.nodes = nodes
self.token = token
}
func render(_ context: Context) throws -> String {
let values = try resolvable.resolve(context)
if let values = values as? [Any], !values.isEmpty {
let mappedValues: [String] = try values.enumerated().map { index, item in
let mapContext = self.context(values: values, index: index, item: item)
return try context.push(dictionary: mapContext) {
try renderNodes(nodes, context)
}
}
context[resultName] = mappedValues
}
// Map should never render anything
return ""
}
func context(values: [Any], index: Int, item: Any) -> [String: Any] {
var result: [String: Any] = [
"maploop": [
"counter": index,
"first": index == 0,
"last": index == (values.count - 1),
"item": item
]
]
if let mapVariable = mapVariable {
result[mapVariable] = item
}
return result
}
}
| ad8936d7acaf44420bb29e446dd37a04 | 25.465347 | 114 | 0.619155 | false | false | false | false |
wikimedia/wikipedia-ios | refs/heads/main | Wikipedia/Code/Article as a Living Document/ArticleAsLivingDocSmallEventCollectionViewCell.swift | mit | 1 | import UIKit
class ArticleAsLivingDocSmallEventCollectionViewCell: CollectionViewCell {
private let descriptionLabel = UILabel()
let timelineView = TimelineView()
private var theme: Theme?
private var smallEvent: ArticleAsLivingDocViewModel.Event.Small?
weak var delegate: ArticleDetailsShowing?
override func reset() {
super.reset()
descriptionLabel.text = nil
}
override func setup() {
super.setup()
contentView.addSubview(descriptionLabel)
timelineView.decoration = .squiggle
contentView.addSubview(timelineView)
descriptionLabel.numberOfLines = 1
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tappedSmallChanges))
descriptionLabel.addGestureRecognizer(tapGestureRecognizer)
descriptionLabel.isUserInteractionEnabled = true
}
override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
if traitCollection.horizontalSizeClass == .compact {
layoutMarginsAdditions = UIEdgeInsets(top: 0, left: -5, bottom: 20, right: 0)
} else {
layoutMarginsAdditions = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
}
let layoutMargins = calculatedLayoutMargins
let timelineTextSpacing: CGFloat = 5
let timelineWidth: CGFloat = 15
let x = layoutMargins.left + timelineWidth + timelineTextSpacing
let widthToFit = size.width - layoutMargins.right - x
if apply {
timelineView.frame = CGRect(x: layoutMargins.left, y: 0, width: timelineWidth, height: size.height)
}
let descriptionOrigin = CGPoint(x: x + 3, y: layoutMargins.top)
let descriptionFrame = descriptionLabel.wmf_preferredFrame(at: descriptionOrigin, maximumSize: CGSize(width: widthToFit, height: UIView.noIntrinsicMetric), minimumSize: NoIntrinsicSize, alignedBy: .forceLeftToRight, apply: apply)
let finalHeight = descriptionFrame.maxY + layoutMargins.bottom
return CGSize(width: size.width, height: finalHeight)
}
func configure(viewModel: ArticleAsLivingDocViewModel.Event.Small, theme: Theme) {
self.smallEvent = viewModel
descriptionLabel.text = viewModel.eventDescription
apply(theme: theme)
setNeedsLayout()
}
override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
timelineView.dotsY = descriptionLabel.convert(descriptionLabel.bounds, to: timelineView).midY
}
override func updateFonts(with traitCollection: UITraitCollection) {
super.updateFonts(with: traitCollection)
descriptionLabel.font = UIFont.wmf_font(.italicSubheadline, compatibleWithTraitCollection: traitCollection)
}
@objc private func tappedSmallChanges() {
guard let revisionID = smallEvent?.smallChanges.first?.revId,
let parentId = smallEvent?.smallChanges.last?.parentId else {
return
}
if let loggingPosition = smallEvent?.loggingPosition {
ArticleAsLivingDocFunnel.shared.logModalSmallEventsLinkTapped(position: loggingPosition)
}
let diffType: DiffContainerViewModel.DiffType = (smallEvent?.smallChanges.count ?? 0) > 1 ? .compare : .single
delegate?.goToDiff(revisionId: revisionID, parentId: parentId, diffType: diffType)
}
}
extension ArticleAsLivingDocSmallEventCollectionViewCell: Themeable {
func apply(theme: Theme) {
if let oldTheme = self.theme,
theme.webName == oldTheme.webName {
return
}
self.theme = theme
descriptionLabel.textColor = theme.colors.link
timelineView.backgroundColor = theme.colors.paperBackground
timelineView.tintColor = theme.colors.accent
}
}
| 6f21a2e7193b9f3705b89056f66fd1a6 | 36.373832 | 237 | 0.666667 | false | false | false | false |
hyperoslo/Sync | refs/heads/master | Source/Sync/Sync+NSPersistentContainer.swift | mit | 1 | import CoreData
public extension NSPersistentContainer {
/**
Syncs the entity using the received array of dictionaries, maps one-to-many, many-to-many and one-to-one relationships.
It also syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter changes: The array of dictionaries used in the sync process.
- parameter entityName: The name of the entity to be synced.
- parameter completion: The completion block, it returns an error if something in the Sync process goes wrong.
*/
func sync(_ changes: [[String: Any]], inEntityNamed entityName: String, completion: ((_ error: NSError?) -> Void)?) {
self.sync(changes, inEntityNamed: entityName, predicate: nil, parent: nil, parentRelationship: nil, operations: .all, completion: completion)
}
/**
Syncs the entity using the received array of dictionaries, maps one-to-many, many-to-many and one-to-one relationships.
It also syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter changes: The array of dictionaries used in the sync process.
- parameter entityName: The name of the entity to be synced.
- parameter predicate: The predicate used to filter out changes, if you want to exclude some local items to be taken in
account in the Sync process, you just need to provide this predicate.
- parameter completion: The completion block, it returns an error if something in the Sync process goes wrong.
*/
func sync(_ changes: [[String: Any]], inEntityNamed entityName: String, predicate: NSPredicate?, completion: ((_ error: NSError?) -> Void)?) {
Sync.changes(changes, inEntityNamed: entityName, predicate: predicate, persistentContainer: self, operations: .all, completion: completion)
}
/**
Syncs the entity using the received array of dictionaries, maps one-to-many, many-to-many and one-to-one relationships.
It also syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter changes: The array of dictionaries used in the sync process.
- parameter entityName: The name of the entity to be synced.
- parameter predicate: The predicate used to filter out changes, if you want to exclude some local items to be taken in
account in the Sync process, you just need to provide this predicate.
- parameter operations: The type of operations to be applied to the data, Insert, Update, Delete or any possible combination.
- parameter completion: The completion block, it returns an error if something in the Sync process goes wrong.
*/
func sync(_ changes: [[String: Any]], inEntityNamed entityName: String, predicate: NSPredicate?, parent: NSManagedObject?, parentRelationship: NSRelationshipDescription?, operations: Sync.OperationOptions, completion: ((_ error: NSError?) -> Void)?) {
self.performBackgroundTask { backgroundContext in
Sync.changes(changes, inEntityNamed: entityName, predicate: predicate, parent: parent, parentRelationship: parentRelationship, inContext: backgroundContext, operations: operations, completion: completion)
}
}
/// Inserts or updates an object using the given changes dictionary in an specific entity.
///
/// - Parameters:
/// - changes: The dictionary to be used to update or create the object.
/// - entityName: The name of the entity.
/// - id: The primary key.
/// - completion: The completion block.
func insertOrUpdate(_ changes: [String: Any], inEntityNamed entityName: String, completion: @escaping (_ result: SyncResult<Any>) -> Void) {
self.performBackgroundTask { backgroundContext in
do {
let result = try Sync.insertOrUpdate(changes, inEntityNamed: entityName, using: backgroundContext)
let localPrimaryKey = result.entity.sync_localPrimaryKey()
let id = result.value(forKey: localPrimaryKey)
DispatchQueue.main.async {
completion(SyncResult.success(id!))
}
} catch let error as NSError {
DispatchQueue.main.async {
completion(SyncResult.failure(error))
}
}
}
}
/// Updates an object using the given changes dictionary for the provided primary key in an specific entity.
///
/// - Parameters:
/// - id: The primary key.
/// - changes: The dictionary to be used to update the object.
/// - entityName: The name of the entity.
/// - completion: The completion block.
func update(_ id: Any, with changes: [String: Any], inEntityNamed entityName: String, completion: @escaping (_ result: SyncResult<Any>) -> Void) {
self.performBackgroundTask { backgroundContext in
do {
var updatedID: Any?
if let result = try Sync.update(id, with: changes, inEntityNamed: entityName, using: backgroundContext) {
let localPrimaryKey = result.entity.sync_localPrimaryKey()
updatedID = result.value(forKey: localPrimaryKey)
}
DispatchQueue.main.async {
completion(SyncResult.success(updatedID!))
}
} catch let error as NSError {
DispatchQueue.main.async {
completion(SyncResult.failure(error))
}
}
}
}
/// Deletes a managed object for the provided primary key in an specific entity.
///
/// - Parameters:
/// - id: The primary key.
/// - entityName: The name of the entity.
/// - completion: The completion block.
func delete(_ id: Any, inEntityNamed entityName: String, completion: @escaping (_ error: NSError?) -> Void) {
self.performBackgroundTask { backgroundContext in
do {
try Sync.delete(id, inEntityNamed: entityName, using: backgroundContext)
DispatchQueue.main.async {
completion(nil)
}
} catch let error as NSError {
DispatchQueue.main.async {
completion(error)
}
}
}
}
/// Fetches a managed object for the provided primary key in an specific entity.
///
/// - Parameters:
/// - id: The primary key.
/// - entityName: The name of the entity.
/// - Returns: A managed object for a provided primary key in an specific entity.
/// - Throws: Core Data related issues.
@discardableResult
func fetch<ResultType: NSManagedObject>(_ id: Any, inEntityNamed entityName: String) throws -> ResultType? {
Sync.verifyContextSafety(context: self.viewContext)
return try Sync.fetch(id, inEntityNamed: entityName, using: self.viewContext)
}
/// Inserts or updates an object using the given changes dictionary in an specific entity.
///
/// - Parameters:
/// - changes: The dictionary to be used to update or create the object.
/// - entityName: The name of the entity.
/// - Returns: The inserted or updated object. If you call this method from a background context, make sure to not use this on the main thread.
/// - Throws: Core Data related issues.
@discardableResult
func insertOrUpdate<ResultType: NSManagedObject>(_ changes: [String: Any], inEntityNamed entityName: String) throws -> ResultType {
Sync.verifyContextSafety(context: self.viewContext)
return try Sync.insertOrUpdate(changes, inEntityNamed: entityName, using: self.viewContext)
}
/// Updates an object using the given changes dictionary for the provided primary key in an specific entity.
///
/// - Parameters:
/// - id: The primary key.
/// - changes: The dictionary to be used to update the object.
/// - entityName: The name of the entity.
/// - Returns: The updated object, if not found it returns nil. If you call this method from a background context, make sure to not use this on the main thread.
/// - Throws: Core Data related issues.
@discardableResult
func update<ResultType: NSManagedObject>(_ id: Any, with changes: [String: Any], inEntityNamed entityName: String) throws -> ResultType? {
Sync.verifyContextSafety(context: self.viewContext)
return try Sync.update(id, with: changes, inEntityNamed: entityName, using: self.viewContext)
}
/// Deletes a managed object for the provided primary key in an specific entity.
///
/// - Parameters:
/// - id: The primary key.
/// - entityName: The name of the entity.
/// - Throws: Core Data related issues.
func delete(_ id: Any, inEntityNamed entityName: String, using context: NSManagedObjectContext) throws {
Sync.verifyContextSafety(context: self.viewContext)
return try Sync.delete(id, inEntityNamed: entityName, using: self.viewContext)
}
}
public extension Sync {
/**
Syncs the entity using the received array of dictionaries, maps one-to-many, many-to-many and one-to-one relationships.
It also syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter changes: The array of dictionaries used in the sync process.
- parameter entityName: The name of the entity to be synced.
- parameter predicate: The predicate used to filter out changes, if you want to exclude some local items to be taken in
account in the Sync process, you just need to provide this predicate.
- parameter persistentContainer: The NSPersistentContainer instance.
- parameter completion: The completion block, it returns an error if something in the Sync process goes wrong.
*/
class func changes(_ changes: [[String: Any]], inEntityNamed entityName: String, predicate: NSPredicate?, persistentContainer: NSPersistentContainer, completion: ((_ error: NSError?) -> Void)?) {
self.changes(changes, inEntityNamed: entityName, predicate: predicate, persistentContainer: persistentContainer, operations: .all, completion: completion)
}
/**
Syncs the entity using the received array of dictionaries, maps one-to-many, many-to-many and one-to-one relationships.
It also syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter changes: The array of dictionaries used in the sync process.
- parameter entityName: The name of the entity to be synced.
- parameter predicate: The predicate used to filter out changes, if you want to exclude some local items to be taken in
account in the Sync process, you just need to provide this predicate.
- parameter persistentContainer: The NSPersistentContainer instance.
- parameter operations: The type of operations to be applied to the data, Insert, Update, Delete or any possible combination.
- parameter completion: The completion block, it returns an error if something in the Sync process goes wrong.
*/
class func changes(_ changes: [[String: Any]], inEntityNamed entityName: String, predicate: NSPredicate?, persistentContainer: NSPersistentContainer, operations: Sync.OperationOptions, completion: ((_ error: NSError?) -> Void)?) {
persistentContainer.performBackgroundTask { backgroundContext in
self.changes(changes, inEntityNamed: entityName, predicate: predicate, parent: nil, parentRelationship: nil, inContext: backgroundContext, operations: operations, completion: completion)
}
}
}
| 96886327791c5d5f6f4a7a4af9fd486a | 58.471698 | 255 | 0.685755 | false | false | false | false |
CaiMiao/CGSSGuide | refs/heads/master | DereGuide/Toolbox/Gacha/Controller/GachaFilterSortController.swift | mit | 1 | //
// GachaFilterSortController.swift
// DereGuide
//
// Created by zzk on 2017/1/17.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
protocol GachaFilterSortControllerDelegate: class {
func doneAndReturn(filter: CGSSGachaFilter, sorter: CGSSSorter)
}
class GachaFilterSortController: BaseFilterSortController {
var filter: CGSSGachaFilter!
var sorter: CGSSSorter!
weak var delegate: GachaFilterSortControllerDelegate?
var gachaTypeTitles = [CGSSGachaTypes.normal.description,
CGSSGachaTypes.limit.description,
CGSSGachaTypes.fes.description,
CGSSGachaTypes.singleType.description]
var sorterTitles = [NSLocalizedString("更新时间", comment: "")]
var sorterMethods = ["id"]
var sorterOrderTitles = [NSLocalizedString("降序", comment: ""), NSLocalizedString("升序", comment: "")]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func reloadData() {
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func doneAction() {
delegate?.doneAndReturn(filter: filter, sorter: sorter)
drawerController?.hide(animated: true)
}
override func resetAction() {
filter = CGSSSorterFilterManager.DefaultFilter.gachaPool
sorter = CGSSSorterFilterManager.DefaultSorter.gachaPool
tableView.reloadData()
}
// MARK: - TableViewDelegate & DataSource
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return NSLocalizedString("筛选", comment: "")
} else {
return NSLocalizedString("排序", comment: "")
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
return 1
} else {
return 2
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "FilterCell", for: indexPath) as! FilterTableViewCell
switch indexPath.row {
case 0:
cell.setup(titles: gachaTypeTitles, index: filter.gachaTypes.rawValue, all: CGSSGachaTypes.all.rawValue)
default:
break
}
cell.delegate = self
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "SortCell", for: indexPath) as! SortTableViewCell
switch indexPath.row {
case 0:
cell.setup(titles: sorterOrderTitles)
cell.presetIndex(index: sorter.ascending ? 1 : 0)
case 1:
cell.setup(titles: sorterTitles)
if let index = sorterMethods.index(of: sorter.property) {
cell.presetIndex(index: UInt(index))
}
default:
break
}
cell.delegate = self
return cell
}
}
}
extension GachaFilterSortController: FilterTableViewCellDelegate {
func filterTableViewCell(_ cell: FilterTableViewCell, didSelect index: Int) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 0 {
switch indexPath.row {
case 0:
filter.gachaTypes.insert(CGSSGachaTypes.init(rawValue: 1 << UInt(index)))
default:
break
}
}
}
}
func filterTableViewCell(_ cell: FilterTableViewCell, didDeselect index: Int) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 0 {
switch indexPath.row {
case 0:
filter.gachaTypes.remove(CGSSGachaTypes.init(rawValue: 1 << UInt(index)))
default:
break
}
}
}
}
func didSelectAll(filterTableViewCell cell: FilterTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 0 {
switch indexPath.row {
case 0:
filter.gachaTypes = .all
default:
break
}
}
}
}
func didDeselectAll(filterTableViewCell cell: FilterTableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 0 {
switch indexPath.row {
case 0:
filter.gachaTypes = CGSSGachaTypes.init(rawValue: 0)
default:
break
}
}
}
}
}
extension GachaFilterSortController: SortTableViewCellDelegate {
func sortTableViewCell(_ cell: SortTableViewCell, didSelect index: Int) {
if let indexPath = tableView.indexPath(for: cell) {
if indexPath.section == 1 {
switch indexPath.row {
case 0:
sorter.ascending = (index == 1)
case 1:
sorter.property = sorterMethods[index]
default:
break
}
}
}
}
}
| 47057cb3fbbf65754b763c7c5cdd9a63 | 30.657609 | 122 | 0.553991 | false | false | false | false |
statusbits/HomeKit-Demo | refs/heads/master | BetterHomeKit/ActionSetViewController.swift | mit | 1 | //
// ActionSetViewController.swift
// BetterHomeKit
//
// Created by Khaos Tian on 8/6/14.
// Copyright (c) 2014 Oltica. All rights reserved.
//
import UIKit
import HomeKit
class ActionSetViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var actionsTableView: UITableView!
weak var currentActionSet:HMActionSet?
var actions = [HMAction]()
override func viewDidLoad() {
super.viewDidLoad()
if let currentActionSet = currentActionSet {
self.title = "\(currentActionSet.name)"
}
updateActions()
}
func updateActions () {
actions.removeAll(keepCapacity: false)
if let currentActionSet = currentActionSet {
actions += currentActionSet.actions.allObjects as [HMAction]
}
actionsTableView.reloadData()
}
@IBAction func executeActionSet(sender: AnyObject) {
if let currentHome = Core.sharedInstance.currentHome {
currentHome.executeActionSet(currentActionSet) {
error in
if error != nil {
NSLog("Failed executing action set, error:\(error)")
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return actions.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ActionCell", forIndexPath: indexPath) as UITableViewCell
let action = actions[indexPath.row] as HMCharacteristicWriteAction
if let charDesc = HomeKitUUIDs[action.characteristic.characteristicType] {
cell.textLabel?.text = charDesc
}else{
cell.textLabel?.text = action.characteristic.characteristicType
}
cell.detailTextLabel?.text = "Accessory: \(action.characteristic.service.accessory.name) | Target Value: \(action.targetValue)"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let _action = actions[indexPath.row] as HMCharacteristicWriteAction
let object = _action.characteristic
var charDesc = object.characteristicType
charDesc = HomeKitUUIDs[object.characteristicType]
switch (object.metadata.format as NSString) {
case HMCharacteristicMetadataFormatBool:
let alert:UIAlertController = UIAlertController(title: "Target \(charDesc)", message: "Please choose the target state for this action", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "On", style: UIAlertActionStyle.Default, handler:
{
(action:UIAlertAction!) in
_action.updateTargetValue(true) {
error in
if error != nil {
NSLog("Failed adding action to action set, error: \(error)")
} else {
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}
}))
alert.addAction(UIAlertAction(title: "Off", style: UIAlertActionStyle.Default, handler:
{
(action:UIAlertAction!) in
_action.updateTargetValue(false) {
error in
if error != nil {
NSLog("Failed adding action to action set, error: \(error)")
} else {
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
dispatch_async(dispatch_get_main_queue(),
{
self.presentViewController(alert, animated: true, completion: nil)
})
case HMCharacteristicMetadataFormatInt,HMCharacteristicMetadataFormatFloat,HMCharacteristicMetadataFormatUInt8,HMCharacteristicMetadataFormatUInt16,HMCharacteristicMetadataFormatUInt32,HMCharacteristicMetadataFormatUInt64:
let alert:UIAlertController = UIAlertController(title: "Target \(charDesc)", message: "Enter the target state for this action from \(object.metadata.minimumValue) to \(object.metadata.maximumValue). Unit is \(object.metadata.units)", preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler(nil)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:
{
(action:UIAlertAction!) in
let textField = alert.textFields?[0] as UITextField
let f = NSNumberFormatter()
f.numberStyle = NSNumberFormatterStyle.DecimalStyle
_action.updateTargetValue(f.numberFromString(textField.text)) {
error in
if error != nil {
NSLog("Failed adding action to action set, error: \(error)")
} else {
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}
}))
dispatch_async(dispatch_get_main_queue(),
{
self.presentViewController(alert, animated: true, completion: nil)
})
case HMCharacteristicMetadataFormatString:
let alert:UIAlertController = UIAlertController(title: "Target \(charDesc)", message: "Enter the target \(charDesc) from \(object.metadata.minimumValue) to \(object.metadata.maximumValue). Unit is \(object.metadata.units)", preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler(nil)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:
{
(action:UIAlertAction!) in
let textField = alert.textFields?[0] as UITextField
_action.updateTargetValue(textField.text) {
error in
if error != nil {
NSLog("Failed adding action to action set, error: \(error)")
} else {
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}
}))
dispatch_async(dispatch_get_main_queue(),
{
self.presentViewController(alert, animated: true, completion: nil)
})
default:
NSLog("Unsupported")
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
let action = actions[indexPath.row]
self.currentActionSet?.removeAction(action) {
[weak self]
error in
if error != nil {
NSLog("Failed removing action from action set, error:\(error)")
} else {
self?.updateActions()
}
}
}
}
}
| 8586a899ecb4b6b9485f15449470d62f | 44.043956 | 269 | 0.58685 | false | false | false | false |
Ethenyl/JAMFKit | refs/heads/master | JamfKit/Sources/Models/PreciseDate.swift | mit | 1 | //
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
/// Represents a logical date within JSS api, contains 3 properties, the date itself, an epoch version of the date and an UTC version of the date.
@objc(JMFKPreciseDate)
public final class PreciseDate: NSObject, Requestable {
// MARK: - Constants
static let EpochKey = "_epoch"
static let UTCKey = "_utc"
// MARK: - Properties
private let node: String
@objc
public var date: Date?
@objc(epoch)
public var internalEpoch: NSNumber? {
guard let epoch = self.epoch else {
return 0
}
return NSNumber(value: epoch)
}
@nonobjc
public var epoch: UInt?
@objc
public var dateUTC: Date?
// MARK: - Initialization
public init?(json: [String: Any], node: String) {
self.node = node
if let rawDate = json[node] as? String {
date = PreciseDate.getDateFormatter().date(from: rawDate)
}
epoch = json[node + PreciseDate.EpochKey] as? UInt
if let rawDateUTC = json[node + PreciseDate.UTCKey] as? String {
dateUTC = PreciseDate.getUTCDateFormatter().date(from: rawDateUTC)
}
}
public func toJSON() -> [String: Any] {
var json = [String: Any]()
if let date = date {
json[node] = PreciseDate.getDateFormatter().string(from: date)
}
json[node + PreciseDate.EpochKey] = epoch
if let dateUTC = dateUTC {
json[node + PreciseDate.UTCKey] = PreciseDate.getUTCDateFormatter().string(from: dateUTC)
}
return json
}
// MARK: - Helpers
private static func getDateFormatter() -> DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
return dateFormatter
}
private static func getUTCDateFormatter() -> DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
return dateFormatter
}
}
| db8e5feb7fb31cb22add4f6e42aaf515 | 27.325581 | 146 | 0.629721 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformUIKit/Components/SelectionScreen/SelectionScreenViewController.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import RxCocoa
import RxRelay
import RxSwift
public final class SelectionScreenViewController: BaseScreenViewController {
// MARK: - IBOutlets
private let tableView: UITableView = .init()
// MARK: - Injected
private let presenter: SelectionScreenPresenter
// MARK: - Accessors
private let disposeBag = DisposeBag()
// MARK: - Lifecycle
public init(presenter: SelectionScreenPresenter) {
self.presenter = presenter
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
public required init?(coder: NSCoder) { nil }
override public func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
setupSearchController()
setupTableView()
view.backgroundColor = UIColor.white
view.isOpaque = true
presenter.dismiss
.emit(onNext: { [weak self] in
guard let self = self else { return }
let completion = {
self.removeFromHierarchy()
self.presenter.previousTapped()
}
if self.navigationItem.searchController?.isActive ?? false {
self.navigationItem.searchController?.dismiss(animated: true, completion: completion)
} else {
completion()
}
})
.disposed(by: disposeBag)
}
// MARK: - Setup
private func setupNavigationBar() {
titleViewStyle = .text(value: presenter.title)
setStandardDarkContentStyle()
}
private func setupSearchController() {
let searchController = SearchController(placeholderText: presenter.searchBarPlaceholder)
searchController.obscuresBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
definesPresentationContext = true
searchController.text
.bindAndCatch(to: presenter.searchTextRelay)
.disposed(by: disposeBag)
}
private func setupTableView() {
// Table view setup
view.addSubview(tableView)
tableView.layoutToSuperview(.leading, .trailing, .top, .bottom)
if let viewModel = presenter.tableHeaderViewModel {
let width = tableView.bounds.width
let height = SelectionScreenTableHeaderView.estimatedHeight(for: width, model: viewModel)
let headerView = SelectionScreenTableHeaderView(frame: .init(
origin: .zero,
size: .init(
width: width,
height: height
)
)
)
headerView.viewModel = viewModel
tableView.tableHeaderView = headerView
}
tableView.register(SelectionItemTableViewCell.self)
tableView.tableFooterView = UIView()
tableView.estimatedRowHeight = 72
tableView.rowHeight = UITableView.automaticDimension
tableView.separatorInset = UIEdgeInsets(top: 0, left: 24, bottom: 0, right: 24)
// Table view binding
let displayPresenters = presenter
.displayPresenters
.share(replay: 1)
displayPresenters
.bind(
to: tableView.rx.items(
cellIdentifier: SelectionItemTableViewCell.objectName,
cellType: SelectionItemTableViewCell.self
),
curriedArgument: { _, presenter, cell in
cell.presenter = presenter
}
)
.disposed(by: disposeBag)
displayPresenters
.filter { !$0.isEmpty }
.flatMap(weak: self) { (self, _) in
self.presenter.preselection
}
.take(1)
.asSingle()
.observe(on: MainScheduler.asyncInstance)
.subscribe(onSuccess: { [weak self] index in
self?.tableView.scrollToRow(
at: IndexPath(row: index, section: 0),
at: .middle,
animated: true
)
})
.disposed(by: disposeBag)
}
// MARK: - Navigation
override public func navigationBarLeadingButtonPressed() {
super.navigationBarLeadingButtonPressed()
presenter.previousTapped()
}
override public func navigationBarTrailingButtonPressed() {
super.navigationBarTrailingButtonPressed()
presenter.previousTapped()
}
}
| cdba3389b7d5a20c83b6b9f475a93d45 | 30.197368 | 105 | 0.594053 | false | false | false | false |
thankmelater23/relliK | refs/heads/master | relliK/GameViewController.swift | unlicense | 1 | //
// GameViewController.swift
// relliK
//
// Created by Andre Villanueva on 7/25/15.
// Copyright (c) 2015 Bang Bang Studios. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let size = CGSize(width: 2208, height: 1242)
let gameScene = GameScene(size: size)
let gameOverScene = GameOverScene.init(size: size, won: false)
let mainMenuScene = MainMenuScene.init(size: size)
// let scene = GameScene(size: CGSize(width: 1136, height: 640))
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
gameScene.scaleMode = .aspectFill
skView.presentScene(gameScene)
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| dc563bb13aa685f37c1958c82970518a | 29.288889 | 77 | 0.655172 | false | false | false | false |
PureSwift/Bluetooth | refs/heads/master | Sources/BluetoothGATT/GATTReportReference.swift | mit | 1 | //
// GATTReportReference.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Report Reference
/// GATT Report Reference Descriptor
///
/// Mapping information in the form of a Report ID and Report Type which maps the current parent characteristic to the Report ID(s) and Report Type (s) defined within the Report Map characteristic.
@frozen
public struct GATTReportReference: GATTDescriptor {
public static let uuid: BluetoothUUID = .reportReference
public static let length = 2
public var identifier: Identifier
public var type: ReportType
public init(identifier: Identifier, type: ReportType) {
self.identifier = identifier
self.type = type
}
public init?(data: Data) {
guard data.count == Swift.type(of: self).length
else { return nil }
guard let reportType = ReportType(rawValue: data[1])
else { return nil }
self.init(identifier: Identifier(rawValue: data[0]), type: reportType)
}
public var data: Data {
return Data([identifier.rawValue, type.rawValue])
}
public var descriptor: GATTAttribute.Descriptor {
return GATTAttribute.Descriptor(uuid: Swift.type(of: self).uuid,
value: data,
permissions: [.read])
}
}
public extension GATTReportReference {
/// GATT Report Type
enum ReportType: UInt8 {
/// Input Report
case input = 0x01
/// Output Report
case output = 0x02
/// Feature Report
case feature = 0x03
}
}
public extension GATTReportReference {
struct Identifier: RawRepresentable {
public var rawValue: UInt8
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
}
}
extension GATTReportReference.Identifier: Equatable {
public static func == (lhs: GATTReportReference.Identifier,
rhs: GATTReportReference.Identifier) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension GATTReportReference.Identifier: CustomStringConvertible {
public var description: String {
return rawValue.description
}
}
extension GATTReportReference.Identifier: ExpressibleByIntegerLiteral {
public init(integerLiteral value: UInt8) {
self.init(rawValue: value)
}
}
| f985bd6534384dfe168f12d0f29d6cdb | 23.453704 | 197 | 0.602045 | false | false | false | false |
Kekiiwaa/Localize | refs/heads/master | Tests/StringBaseTest.swift | mit | 2 | //
// StringBaseTest.swift
// Localize
//
// Copyright © 2019 @andresilvagomez.
//
import XCTest
import Localize
class StringBaseTest: XCTestCase {
override func setUp() {
super.setUp()
Localize.update(provider: .strings)
Localize.update(bundle: Bundle(for: type(of: self)))
Localize.update(language: "en")
}
func testLocalizeInAnyDictionary() {
let localized = "heymomhowareyoy".localized
XCTAssertEqual(localized, "heymomhowareyoy")
}
func testLocalizeProperty() {
let localized = "hello.world".localized
XCTAssertEqual(localized, "Hello world!")
}
func testLocalizeKey() {
let localized = "hello.world".localize()
XCTAssertEqual(localized, "Hello world!")
}
func testLocalizeKeyWithValue() {
let localized = "name".localize(value: "Andres")
XCTAssertEqual(localized, "Hello Andres")
}
func testLocalizeKeyWithValues() {
let localized = "values".localize(values: "Andres", "Software Developer")
XCTAssertEqual(localized, "Hello everyone my name is Andres and I'm Software Developer, see you soon")
}
func testLocalizeKeyWithThreeValues() {
let localized = "three_values".localize(values: "Hello" ,"Andres", "Software Developer")
XCTAssertEqual(localized, "Hello everyone my name is Andres and I'm Software Developer, see you soon")
}
func testLocalizeKeyWithFourValues() {
let localized = "four_values".localize(values: "Hello" ,"Andres", "Software Developer", "soon")
XCTAssertEqual(localized, "Hello everyone my name is Andres and I'm Software Developer, see you soon")
}
func testLocalizeKeyWithDictionary() {
let localized = "username".localize(dictionary: ["username": "andresilvagomez"])
XCTAssertEqual(localized, "My username is andresilvagomez")
}
func testLocalizeWithTableName() {
let localized = "other.key".localize(tableName: "Other")
XCTAssertEqual(localized, "This key exist in other file")
}
func testListOfAvailableLanguages() {
let languages = Localize.availableLanguages
let array = ["en", "es", "es-CO", "fr"]
for item in array {
XCTAssertTrue(languages.contains(item))
}
}
func testCurrentLanguage() {
let language = Localize.currentLanguage
XCTAssertEqual(language, "en")
}
}
| ec66fd048ca64c507f8893422bb472f4 | 31.157895 | 110 | 0.658347 | false | true | false | false |
to4iki/conference-app-2017-ios | refs/heads/master | conference-app-2017/data/extension/UIApplicationExtension.swift | apache-2.0 | 1 | import UIKit
extension UIApplication {
var topViewController: UIViewController? {
guard var topViewController = UIApplication.shared.keyWindow?.rootViewController else { return nil }
while case .some = topViewController.presentedViewController {
topViewController = topViewController.presentedViewController!
}
return topViewController
}
func findViewController<T: UIViewController>(_ type: T.Type) -> T? {
func go(childViewControllers: [UIViewController]) -> T? {
if let viewController: T = childViewControllers.convert(to: T.self).first {
return viewController
} else {
if childViewControllers.nonEmpty {
let grandsonViewControllers = childViewControllers.flatMap({ $0.childViewControllers })
return go(childViewControllers: grandsonViewControllers)
} else {
return nil
}
}
}
guard let topViewController = topViewController else { return nil }
if let viewController = topViewController as? T {
return viewController
} else {
return go(childViewControllers: topViewController.childViewControllers)
}
}
}
| 5b486c84f83d230135f85e9d947e78c5 | 38.393939 | 108 | 0.624615 | false | false | false | false |
WJachowicz/TableViewDemo | refs/heads/master | TableViewDemo/AnimalDetailsViewController.swift | mit | 1 | //
// AnimalDetailsViewController.swift
// TableViewDemo
//
// Created by Wojciech Jachowicz on 03.06.2014.
// Copyright (c) 2014 Wojciech Jachowicz. All rights reserved.
//
import UIKit
class AnimalDetailsViewController: UIViewController {
var animalName : String
var boshLabel : UILabel
init(animalName : String) {
self.animalName = animalName
self.boshLabel = UILabel();
self.boshLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
self.boshLabel.textColor = UIColor.blackColor()
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
self.title = animalName
self.boshLabel.text = "Bosh!\nYou've just selected \(self.animalName) in your first Swift app!"
self.boshLabel.textAlignment = NSTextAlignment.Center
self.boshLabel.numberOfLines = 0
self.boshLabel.preferredMaxLayoutWidth = 200.0
self.view.backgroundColor = UIColor.whiteColor()
self.view.addSubview(self.boshLabel)
self.view.addConstraint(NSLayoutConstraint(item: self.boshLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0))
self.view.addConstraint(NSLayoutConstraint(item: self.boshLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0))
}
}
| 1f8c43493cd80832c49183f31bb8bba1 | 41.361111 | 235 | 0.717377 | false | false | false | false |
JanGorman/Agrume | refs/heads/master | Example/Agrume Example/SingleImageViewController.swift | mit | 1 | //
// Copyright © 2016 Schnaub. All rights reserved.
//
import Agrume
import UIKit
final class SingleImageViewController: UIViewController {
private lazy var agrume = Agrume(image: UIImage(named: "MapleBacon")!, background: .blurred(.regular))
@IBAction private func openImage(_ sender: Any) {
let helper = makeHelper()
agrume.onLongPress = helper.makeSaveToLibraryLongPressGesture
agrume.show(from: self)
}
private func makeHelper() -> AgrumePhotoLibraryHelper {
let saveButtonTitle = NSLocalizedString("Save Photo", comment: "Save Photo")
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "Cancel")
let helper = AgrumePhotoLibraryHelper(saveButtonTitle: saveButtonTitle, cancelButtonTitle: cancelButtonTitle) { error in
guard error == nil else {
print("Could not save your photo")
return
}
print("Photo has been saved to your library")
}
return helper
}
}
| 25417f341b3dee2592876687268656b9 | 30.766667 | 124 | 0.712487 | false | false | false | false |
exponent/exponent | refs/heads/master | ios/versioned/sdk44/ExpoModulesCore/Swift/Functions/ConcreteFunction.swift | bsd-3-clause | 2 | import Dispatch
public final class ConcreteFunction<Args, ReturnType>: AnyFunction {
public typealias ClosureType = (Args) -> ReturnType
public let name: String
public var takesPromise: Bool {
return argTypes.last is PromiseArgumentType
}
public var argumentsCount: Int {
return argTypes.count - (takesPromise ? 1 : 0)
}
public var queue: DispatchQueue?
let closure: ClosureType
let argTypes: [AnyArgumentType]
init(
_ name: String,
argTypes: [AnyArgumentType],
_ closure: @escaping ClosureType
) {
self.name = name
self.argTypes = argTypes
self.closure = closure
}
public func call(args: [Any], promise: Promise) {
let takesPromise = self.takesPromise
let returnedValue: ReturnType?
do {
var finalArgs = try castArguments(args)
if takesPromise {
finalArgs.append(promise)
}
let tuple = try Conversions.toTuple(finalArgs) as! Args
returnedValue = closure(tuple)
} catch let error as CodedError {
promise.reject(error)
return
} catch let error {
promise.reject(UnexpectedError(error))
return
}
if !takesPromise {
promise.resolve(returnedValue)
}
}
public func callSync(args: [Any]) -> Any {
if takesPromise {
var result: Any?
let semaphore = DispatchSemaphore(value: 0)
let promise = Promise {
result = $0
semaphore.signal()
} rejecter: { error in
semaphore.signal()
}
call(args: args, promise: promise)
semaphore.wait()
return result as Any
} else {
do {
let finalArgs = try castArguments(args)
let tuple = try Conversions.toTuple(finalArgs) as! Args
return closure(tuple)
} catch let error {
return error
}
}
}
public func runOnQueue(_ queue: DispatchQueue?) -> Self {
self.queue = queue
return self
}
private func argumentType(atIndex index: Int) -> AnyArgumentType? {
return (0..<argTypes.count).contains(index) ? argTypes[index] : nil
}
private func castArguments(_ args: [Any]) throws -> [Any] {
if args.count != argumentsCount {
throw InvalidArgsNumberError(received: args.count, expected: argumentsCount)
}
return try args.enumerated().map { (index, arg) in
let expectedType = argumentType(atIndex: index)
// It's safe to unwrap since the arguments count matches.
return try expectedType!.cast(arg)
}
}
}
internal struct InvalidArgsNumberError: CodedError {
let received: Int
let expected: Int
var description: String {
"Received \(received) arguments, but \(expected) was expected."
}
}
| ad128c91ee1b9749e55b8e3c1f23cb00 | 23.436364 | 82 | 0.646577 | false | false | false | false |
edopelawi/CascadingTableDelegate | refs/heads/master | Example/CascadingTableDelegate/ViewModels/DestinationViewModel.swift | mit | 1 | //
// DestinationViewModel.swift
// CascadingTableDelegate
//
// Created by Ricardo Pramana Suranta on 10/31/16.
// Copyright © 2016 Ricardo Pramana Suranta. All rights reserved.
//
import UIKit
import CoreLocation
class DestinationViewModel {
// MARK: - Public properties
var destinationTitle: String?
var headerSectionObservers = [DestinationHeaderSectionViewModelObserver]()
var reviewSectionObservers = [DestinationReviewSectionViewModelObserver]()
var infoSectionObservers = [DestinationInfoSectionViewModelObserver]()
// MARK: - Private properties
fileprivate var _topPhoto: UIImage?
fileprivate var _description: String?
fileprivate var _destinationName: String?
fileprivate var _locationName: String?
fileprivate var _locationCoordinate: CLLocationCoordinate2D?
fileprivate var _locationInfo = [DestinationInfo]()
fileprivate var _averageRating = 0
fileprivate var _rowViewModels = [DestinationReviewUserRowViewModel]()
fileprivate var _remainingRowViewModels = 0
// MARK: - Public methods
/// Refreshes data that held by this instance, and invokes passed `completionHandler` when done.
func refreshData(_ completionHandler: (() -> Void)?) {
let delayTime = DispatchTime.now() + 2.0
let dispatchQueue = DispatchQueue.global(qos: .userInitiated)
dispatchQueue.asyncAfter(deadline: delayTime) {
self.destinationTitle = "Outdoor Adventures"
self.updateHeaderSectionProperties()
self.updateInfoSectionProperties()
self.updateReviewSectionProperties()
DispatchQueue.main.async(execute: {
self.executeUpdateClosures()
completionHandler?()
})
}
}
// MARK: - Private methods
fileprivate func updateHeaderSectionProperties() {
_topPhoto = UIImage(named: "vacation-place")
_destinationName = "Under The Stars"
_locationName = "Hyrum State Park, Utah"
_description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat tincidunt aliquet. Quisque dictum nisi felis, vel aliquet metus congue ac. Curabitur dui arcu, sagittis vel urna non, faucibus pellentesque sem."
}
fileprivate func updateInfoSectionProperties() {
_locationCoordinate = CLLocationCoordinate2D(
latitude: 41.6122648,
longitude: -111.8602992
)
let info = [
("Address", "Hyrum State Park, 405 W 300 S, Hyrum, UT 84319"),
("Website", "stateparks.utah.gov"),
("Phone", "+1 435-245-6866")
]
_locationInfo = info.map({ type, text -> DestinationInfo in
return DestinationInfo(type: type, text: text)
})
}
fileprivate func updateReviewSectionProperties() {
_averageRating = 4
let userReview = DestinationReviewUserRowViewModel(
userName: "Alice",
userReview: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat tincidunt aliquet. Quisque dictum nisi felis, vel aliquet metus congue ac.",
rating: 4
)
_rowViewModels = [DestinationReviewUserRowViewModel](repeating: userReview, count: 3)
_remainingRowViewModels = 2
}
fileprivate func executeUpdateClosures() {
notifyHeaderSectionObservers()
notifyReviewSectionObservers()
notifyInfoSectionObservers()
}
}
extension DestinationViewModel: DestinationHeaderSectionViewModel {
var topPhoto: UIImage? {
return _topPhoto
}
var description: String? {
return _description
}
var destinationName: String? {
return _destinationName
}
var locationName: String? {
return _locationName
}
}
extension DestinationViewModel: DestinationInfoSectionViewModel {
var locationCoordinate: CLLocationCoordinate2D? {
return _locationCoordinate
}
var locationInfo: [DestinationInfo] {
return _locationInfo
}
}
extension DestinationViewModel: DestinationReviewSectionViewModel {
var averageRating: Int {
return _averageRating
}
var rowViewModels: [DestinationReviewUserRowViewModel] {
return _rowViewModels
}
var remainingRowViewModels: Int {
return _remainingRowViewModels
}
func retrieveMoreRowViewModels(_ onCompleted: (() -> Void)?) {
let delayTime = DispatchTime.now() + 2.0
let queue = DispatchQueue.global(qos: .userInitiated)
queue.asyncAfter(deadline: delayTime) {
self.generateMoreRowViewModels()
DispatchQueue.main.async(execute: {
self.notifyReviewSectionObservers()
onCompleted?()
})
}
}
fileprivate func generateMoreRowViewModels() {
let userReview = DestinationReviewUserRowViewModel(
userName: "Bob",
userReview: "Quisque dictum nisi felis, vel aliquet metus congue ac. Curabitur dui arcu, sagittis vel urna non, faucibus pellentesque sem.",
rating: 4
)
let newReviews = [DestinationReviewUserRowViewModel](repeating: userReview, count: remainingRowViewModels)
_rowViewModels.append(contentsOf: newReviews)
_remainingRowViewModels = 0
}
}
| de77ac0d1c7a5c778dc487f8ce21c63c | 24.352632 | 233 | 0.742371 | false | false | false | false |
open-telemetry/opentelemetry-swift | refs/heads/main | Tests/ExportersTests/DatadogExporter/Persistence/FileWriterTests.swift | apache-2.0 | 1 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
@testable import DatadogExporter
import XCTest
class FileWriterTests: XCTestCase {
private let temporaryDirectory = obtainUniqueTemporaryDirectory()
override func setUp() {
super.setUp()
temporaryDirectory.create()
}
override func tearDown() {
temporaryDirectory.delete()
super.tearDown()
}
func testItWritesDataToSingleFile() throws {
let expectation = self.expectation(description: "write completed")
let writer = FileWriter(
dataFormat: DataFormat(prefix: "[", suffix: "]", separator: ","),
orchestrator: FilesOrchestrator(
directory: temporaryDirectory,
performance: PerformancePreset.default,
dateProvider: SystemDateProvider()
)
)
writer.write(value: ["key1": "value1"])
writer.write(value: ["key2": "value3"])
writer.write(value: ["key3": "value3"])
waitForWritesCompletion(on: writer.queue, thenFulfill: expectation)
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(try temporaryDirectory.files().count, 1)
XCTAssertEqual(
try temporaryDirectory.files()[0].read(),
#"{"key1":"value1"},{"key2":"value3"},{"key3":"value3"}"# .utf8Data
)
}
func testGivenErrorVerbosity_whenIndividualDataExceedsMaxWriteSize_itDropsDataAndPrintsError() throws {
let expectation1 = self.expectation(description: "write completed")
let expectation2 = self.expectation(description: "second write completed")
let writer = FileWriter(
dataFormat: .mockWith(prefix: "[", suffix: "]"),
orchestrator: FilesOrchestrator(
directory: temporaryDirectory,
performance: StoragePerformanceMock(
maxFileSize: .max,
maxDirectorySize: .max,
maxFileAgeForWrite: .distantFuture,
minFileAgeForRead: .mockAny(),
maxFileAgeForRead: .mockAny(),
maxObjectsInFile: .max,
maxObjectSize: 17 // 17 bytes is enough to write {"key1":"value1"} JSON
),
dateProvider: SystemDateProvider()
)
)
writer.write(value: ["key1": "value1"]) // will be written
waitForWritesCompletion(on: writer.queue, thenFulfill: expectation1)
wait(for: [expectation1], timeout: 1)
XCTAssertEqual(try temporaryDirectory.files()[0].read(), #"{"key1":"value1"}"# .utf8Data)
writer.write(value: ["key2": "value3 that makes it exceed 17 bytes"]) // will be dropped
waitForWritesCompletion(on: writer.queue, thenFulfill: expectation2)
wait(for: [expectation2], timeout: 1)
XCTAssertEqual(try temporaryDirectory.files()[0].read(), #"{"key1":"value1"}"# .utf8Data) // same content as before
}
/// NOTE: Test added after incident-4797
/// NOTE 2: Test disabled after random failures/successes
// func testWhenIOExceptionsHappenRandomly_theFileIsNeverMalformed() throws {
// let expectation = self.expectation(description: "write completed")
// let writer = FileWriter(
// dataFormat: DataFormat(prefix: "[", suffix: "]", separator: ","),
// orchestrator: FilesOrchestrator(
// directory: temporaryDirectory,
// performance: StoragePerformanceMock(
// maxFileSize: .max,
// maxDirectorySize: .max,
// maxFileAgeForWrite: .distantFuture, // write to single file
// minFileAgeForRead: .distantFuture,
// maxFileAgeForRead: .distantFuture,
// maxObjectsInFile: .max, // write to single file
// maxObjectSize: .max
// ),
// dateProvider: SystemDateProvider()
// )
// )
//
// let ioInterruptionQueue = DispatchQueue(label: "com.datadohq.file-writer-random-io")
//
// func randomlyInterruptIO(for file: File?) {
// ioInterruptionQueue.async { try? file?.makeReadonly() }
// ioInterruptionQueue.async { try? file?.makeReadWrite() }
// }
//
// struct Foo: Codable {
// var foo = "bar"
// }
//
// // Write 300 of `Foo`s and interrupt writes randomly
// (0..<300).forEach { _ in
// writer.write(value: Foo())
// randomlyInterruptIO(for: try? temporaryDirectory.files().first)
// }
//
// ioInterruptionQueue.sync {}
// waitForWritesCompletion(on: writer.queue, thenFulfill: expectation)
// waitForExpectations(timeout: 10, handler: nil)
// XCTAssertEqual(try temporaryDirectory.files().count, 1)
//
// let fileData = try temporaryDirectory.files()[0].read()
// let jsonDecoder = JSONDecoder()
//
// // Assert that data written is not malformed
// let writtenData = try jsonDecoder.decode([Foo].self, from: "[".utf8Data + fileData + "]".utf8Data)
// // Assert that some (including all) `Foo`s were written
// XCTAssertGreaterThan(writtenData.count, 0)
// XCTAssertLessThanOrEqual(writtenData.count, 300)
// }
private func waitForWritesCompletion(on queue: DispatchQueue, thenFulfill expectation: XCTestExpectation) {
queue.async { expectation.fulfill() }
}
}
| d442e29bdba39275782cc3bc5bf33019 | 39.772059 | 123 | 0.602164 | false | true | false | false |
ryuichis/swift-lint | refs/heads/master | Tests/LinuxMain.swift | apache-2.0 | 2 | /*
Copyright 2015-2017 Ryuichi Laboratories and the Yanagiba project contributors
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 XCTest
import CrithagraTests
import MetricTests
import LintTests
import RuleTests
import ReporterTests
var tests = [XCTestCaseEntry]()
tests += CrithagraTests.allTests()
tests += MetricTests.allTests()
tests += LintTests.allTests()
tests += RuleTests.allTests()
tests += ReporterTests.allTests()
XCTMain(tests)
| e82a407f08358c9e8390bc8a67cc447f | 30 | 81 | 0.768991 | false | true | false | false |
tskulbru/NBMaterialDialogIOS | refs/heads/master | Pod/Classes/NBMaterialDialog.swift | mit | 1 | //
// NBMaterialDialog.swift
// NBMaterialDialogIOS
//
// Created by Torstein Skulbru on 02/05/15.
// Copyright (c) 2015 Torstein Skulbru. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Torstein Skulbru
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import BFPaperButton
/**
Simple material dialog class
*/
@objc open class NBMaterialDialog : UIViewController {
// MARK: - Class variables
fileprivate var overlay: UIView?
fileprivate var titleLabel: UILabel?
fileprivate var containerView: UIView = UIView()
fileprivate var contentView: UIView = UIView()
fileprivate var okButton: BFPaperButton?
fileprivate var cancelButton: BFPaperButton?
fileprivate var tapGesture: UITapGestureRecognizer!
fileprivate var backgroundColor: UIColor!
fileprivate var windowView: UIView!
fileprivate var tappableView: UIView = UIView()
fileprivate var isStacked: Bool = false
fileprivate let kBackgroundTransparency: CGFloat = 0.7
fileprivate let kPadding: CGFloat = 16.0
fileprivate let kWidthMargin: CGFloat = 40.0
fileprivate let kHeightMargin: CGFloat = 24.0
internal var kMinimumHeight: CGFloat {
return 120.0
}
fileprivate var _kMaxHeight: CGFloat?
internal var kMaxHeight: CGFloat {
if _kMaxHeight == nil {
let window = UIScreen.main.bounds
_kMaxHeight = window.height - kHeightMargin - kHeightMargin
}
return _kMaxHeight!
}
internal var strongSelf: NBMaterialDialog?
internal var userAction: ((_ isOtherButton: Bool) -> Void)?
internal var constraintViews: [String: AnyObject]!
// MARK: - Constructors
public convenience init() {
self.init(color: UIColor.white)
}
public convenience init(color: UIColor) {
self.init(nibName: nil, bundle:nil)
view.frame = UIScreen.main.bounds
view.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth]
view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:kBackgroundTransparency)
tappableView.backgroundColor = UIColor.clear
tappableView.frame = view.frame
view.addSubview(tappableView)
backgroundColor = color
setupContainerView()
view.addSubview(containerView)
//Retaining itself strongly so can exist without strong refrence
strongSelf = self
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Dialog Lifecycle
/**
Hides the dialog
*/
open func hideDialog() {
hideDialog(-1)
}
/**
Hides the dialog, sending a callback if provided when dialog was shown
:params: buttonIndex The tag index of the button which was clicked
*/
internal func hideDialog(_ buttonIndex: Int) {
if buttonIndex >= 0 {
if let userAction = userAction {
userAction(buttonIndex > 0)
}
}
tappableView.removeGestureRecognizer(tapGesture)
for childView in view.subviews {
childView.removeFromSuperview()
}
view.removeFromSuperview()
strongSelf = nil
}
/**
Displays a simple dialog using a title and a view with the content you need
- parameter windowView: The window which the dialog is to be attached
- parameter title: The dialog title
- parameter content: A custom content view
*/
open func showDialog(_ windowView: UIView, title: String?, content: UIView) -> Self {
return showDialog(windowView, title: title, content: content, dialogHeight: nil, okButtonTitle: nil, action: nil, cancelButtonTitle: nil, stackedButtons: false)
}
/**
Displays a simple dialog using a title and a view with the content you need
- parameter windowView: The window which the dialog is to be attached
- parameter title: The dialog title
- parameter content: A custom content view
- parameter dialogHeight: The height of the dialog
*/
open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?) -> Self {
return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: nil, action: nil, cancelButtonTitle: nil, stackedButtons: false)
}
/**
Displays a simple dialog using a title and a view with the content you need
- parameter windowView: The window which the dialog is to be attached
- parameter title: The dialog title
- parameter content: A custom content view
- parameter dialogHeight: The height of the dialog
- parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response).
*/
open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?) -> Self {
return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: okButtonTitle, action: nil, cancelButtonTitle: nil, stackedButtons: false)
}
/**
Displays a simple dialog using a title and a view with the content you need
- parameter windowView: The window which the dialog is to be attached
- parameter title: The dialog title
- parameter content: A custom content view
- parameter dialogHeight: The height of the dialog
- parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response).
- parameter action: The action you wish to invoke when a button is clicked
*/
open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((_ isOtherButton: Bool) -> Void)?) -> Self {
return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: okButtonTitle, action: action, cancelButtonTitle: nil, stackedButtons: false)
}
/**
Displays a simple dialog using a title and a view with the content you need
- parameter windowView: The window which the dialog is to be attached
- parameter title: The dialog title
- parameter content: A custom content view
- parameter dialogHeight: The height of the dialog
- parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response).
- parameter action: The action you wish to invoke when a button is clicked
*/
open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((_ isOtherButton: Bool) -> Void)?, cancelButtonTitle: String?) -> Self {
return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: okButtonTitle, action: action, cancelButtonTitle: cancelButtonTitle, stackedButtons: false)
}
/**
Displays a simple dialog using a title and a view with the content you need
- parameter windowView: The window which the dialog is to be attached
- parameter title: The dialog title
- parameter content: A custom content view
- parameter dialogHeight: The height of the dialog
- parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response).
- parameter action: The action you wish to invoke when a button is clicked
- parameter cancelButtonTitle: The title of the first button (the left button), normally CANCEL or NO (negative response)
- parameter stackedButtons: Defines if a stackd button view should be used
*/
open func showDialog(_ windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((_ isOtherButton: Bool) -> Void)?, cancelButtonTitle: String?, stackedButtons: Bool) -> Self {
isStacked = stackedButtons
var totalButtonTitleLength: CGFloat = 0.0
self.windowView = windowView
let windowSize = windowView.bounds
windowView.addSubview(view)
view.frame = windowView.bounds
tappableView.frame = view.frame
tapGesture = UITapGestureRecognizer(target: self, action: #selector(NBMaterialDialog.tappedBg))
tappableView.addGestureRecognizer(tapGesture)
setupContainerView()
// Add content to contentView
contentView = content
setupContentView()
if let title = title {
setupTitleLabelWithTitle(title)
}
if let okButtonTitle = okButtonTitle {
totalButtonTitleLength += (okButtonTitle.uppercased() as NSString).size(attributes: [NSFontAttributeName: UIFont.robotoMediumOfSize(14)]).width + 8
if let cancelButtonTitle = cancelButtonTitle {
totalButtonTitleLength += (cancelButtonTitle.uppercased() as NSString).size(attributes: [NSFontAttributeName: UIFont.robotoMediumOfSize(14)]).width + 8
}
// Calculate if the combined button title lengths are longer than max allowed for this dialog, if so use stacked buttons.
let buttonTotalMaxLength: CGFloat = (windowSize.width - (kWidthMargin*2)) - 16 - 16 - 8
if totalButtonTitleLength > buttonTotalMaxLength {
isStacked = true
}
}
// Always display a close/ok button, but setting a title is optional.
if let okButtonTitle = okButtonTitle {
setupButtonWithTitle(okButtonTitle, button: &okButton, isStacked: isStacked)
if let okButton = okButton {
okButton.tag = 0
okButton.addTarget(self, action: #selector(NBMaterialDialog.pressedAnyButton(_:)), for: UIControlEvents.touchUpInside)
}
}
if let cancelButtonTitle = cancelButtonTitle {
setupButtonWithTitle(cancelButtonTitle, button: &cancelButton, isStacked: isStacked)
if let cancelButton = cancelButton {
cancelButton.tag = 1
cancelButton.addTarget(self, action: #selector(NBMaterialDialog.pressedAnyButton(_:)), for: UIControlEvents.touchUpInside)
}
}
userAction = action
setupViewConstraints()
// To get dynamic width to work we need to comment this out and uncomment the stuff in setupViewConstraints. But its currently not working..
containerView.frame = CGRect(x: kWidthMargin, y: (windowSize.height - (dialogHeight ?? kMinimumHeight)) / 2, width: windowSize.width - (kWidthMargin*2), height: fmin(kMaxHeight, (dialogHeight ?? kMinimumHeight)))
containerView.clipsToBounds = true
return self
}
// MARK: - View lifecycle
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
var sz = UIScreen.main.bounds.size
let sver = UIDevice.current.systemVersion as NSString
let ver = sver.floatValue
if ver < 8.0 {
// iOS versions before 7.0 did not switch the width and height on device roration
if UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) {
let ssz = sz
sz = CGSize(width:ssz.height, height:ssz.width)
}
}
}
// MARK: - User interaction
/**
Invoked when the user taps the background (anywhere except the dialog)
*/
internal func tappedBg() {
hideDialog(-1)
}
/**
Invoked when a button is pressed
- parameter sender: The button clicked
*/
internal func pressedAnyButton(_ sender: AnyObject) {
self.hideDialog((sender as! UIButton).tag)
}
// MARK: - View Constraints
/**
Sets up the constraints which defines the dialog
*/
internal func setupViewConstraints() {
if constraintViews == nil {
constraintViews = ["content": contentView, "containerView": containerView, "window": windowView]
}
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-24-[content]-24-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
if let titleLabel = self.titleLabel {
constraintViews["title"] = titleLabel
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-24-[title]-24-[content]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-24-[title]-24-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
} else {
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-24-[content]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
}
if okButton != nil || cancelButton != nil {
if isStacked {
setupStackedButtonsConstraints()
} else {
setupButtonConstraints()
}
} else {
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[content]-24-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
}
// TODO: Fix constraints for the containerView so we can remove the dialogheight var
//
// let margins = ["kWidthMargin": kWidthMargin, "kMinimumHeight": kMinimumHeight, "kMaxHeight": kMaxHeight]
// view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=kWidthMargin)-[containerView(>=80@1000)]-(>=kWidthMargin)-|", options: NSLayoutFormatOptions(0), metrics: margins, views: constraintViews))
// view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=kWidthMargin)-[containerView(>=48@1000)]-(>=kWidthMargin)-|", options: NSLayoutFormatOptions(0), metrics: margins, views: constraintViews))
// view.addConstraint(NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
// view.addConstraint(NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
}
/**
Sets up the constraints for normal horizontal styled button layout
*/
internal func setupButtonConstraints() {
if let okButton = self.okButton {
constraintViews["okButton"] = okButton
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[content]-24-[okButton(==36)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
// The cancel button is only shown when the ok button is visible
if let cancelButton = self.cancelButton {
constraintViews["cancelButton"] = cancelButton
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[cancelButton(==36)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[cancelButton(>=64)]-8-[okButton(>=64)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
} else {
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[okButton(>=64)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
}
}
}
/**
Sets up the constraints for stacked vertical styled button layout
*/
internal func setupStackedButtonsConstraints() {
constraintViews["okButton"] = okButton!
constraintViews["cancelButton"] = cancelButton!
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[content]-24-[okButton(==48)]-[cancelButton(==48)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[okButton]-16-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[cancelButton]-16-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews))
}
// MARK: Private view helpers / initializers
fileprivate func setupContainerView() {
containerView.backgroundColor = backgroundColor
containerView.layer.cornerRadius = 2.0
containerView.layer.masksToBounds = true
containerView.layer.borderWidth = 0.5
containerView.layer.borderColor = UIColor(hex: 0xCCCCCC, alpha: 1.0).cgColor
view.addSubview(containerView)
}
fileprivate func setupTitleLabelWithTitle(_ title: String) {
titleLabel = UILabel()
if let titleLabel = titleLabel {
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.font = UIFont.robotoMediumOfSize(20)
titleLabel.textColor = UIColor(white: 0.13, alpha: 1.0)
titleLabel.numberOfLines = 0
titleLabel.text = title
containerView.addSubview(titleLabel)
}
}
fileprivate func setupButtonWithTitle(_ title: String, button: inout BFPaperButton?, isStacked: Bool) {
if button == nil {
button = BFPaperButton()
}
if let button = button {
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(title.uppercased(), for: UIControlState())
button.setTitleColor(NBConfig.AccentColor, for: UIControlState())
button.isRaised = false
button.titleLabel?.font = UIFont.robotoMediumOfSize(14)
if isStacked {
button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.right
button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 20)
} else {
button.contentEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 8)
}
containerView.addSubview(button)
}
}
fileprivate func setupContentView() {
contentView.backgroundColor = UIColor.clear
contentView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(contentView)
}
}
| a2166ee75219ccb598dd5bcdbfc766e2 | 46.108747 | 231 | 0.690019 | false | false | false | false |
firebase/firebase-ios-sdk | refs/heads/master | FirebaseStorage/Sources/Storage.swift | apache-2.0 | 1 | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import FirebaseCore
import FirebaseAppCheckInterop
import FirebaseAuthInterop
#if COCOAPODS
import GTMSessionFetcher
#else
import GTMSessionFetcherCore
#endif
// Avoids exposing internal FirebaseCore APIs to Swift users.
@_implementationOnly import FirebaseCoreExtension
/**
* Firebase Storage is a service that supports uploading and downloading binary objects,
* such as images, videos, and other files to Google Cloud Storage. Instances of `Storage`
* are not thread-safe.
*
* If you call `Storage.storage()`, the instance will initialize with the default `FirebaseApp`,
* `FirebaseApp.app()`, and the storage location will come from the provided
* `GoogleService-Info.plist`.
*
* If you provide a custom instance of `FirebaseApp`,
* the storage location will be specified via the `FirebaseOptions.storageBucket` property.
*/
@objc(FIRStorage) open class Storage: NSObject {
// MARK: - Public APIs
/**
* The default `Storage` instance.
* - Returns: An instance of `Storage`, configured with the default `FirebaseApp`.
*/
@objc(storage) open class func storage() -> Storage {
return storage(app: FirebaseApp.app()!)
}
/**
* A method used to create `Storage` instances initialized with a custom storage bucket URL.
* Any `StorageReferences` generated from this instance of `Storage` will reference files
* and directories within the specified bucket.
* - Parameter url The `gs://` URL to your Firebase Storage bucket.
* - Returns: A `Storage` instance, configured with the custom storage bucket.
*/
@objc(storageWithURL:) open class func storage(url: String) -> Storage {
return storage(app: FirebaseApp.app()!, url: url)
}
/**
* Creates an instance of `Storage`, configured with a custom `FirebaseApp`. `StorageReference`s
* generated from a resulting instance will reference files in the Firebase project
* associated with custom `FirebaseApp`.
* - Parameter app The custom `FirebaseApp` used for initialization.
* - Returns: A `Storage` instance, configured with the custom `FirebaseApp`.
*/
@objc(storageForApp:) open class func storage(app: FirebaseApp) -> Storage {
let provider = ComponentType<StorageProvider>.instance(for: StorageProvider.self,
in: app.container)
return provider.storage(for: Storage.bucket(for: app))
}
/**
* Creates an instance of `Storage`, configured with a custom `FirebaseApp` and a custom storage
* bucket URL.
* - Parameters:
* - app: The custom `FirebaseApp` used for initialization.
* - url: The `gs://` url to your Firebase Storage bucket.
* - Returns: the `Storage` instance, configured with the custom `FirebaseApp` and storage bucket URL.
*/
@objc(storageForApp:URL:)
open class func storage(app: FirebaseApp, url: String) -> Storage {
let provider = ComponentType<StorageProvider>.instance(for: StorageProvider.self,
in: app.container)
return provider.storage(for: Storage.bucket(for: app, urlString: url))
}
/**
* The `FirebaseApp` associated with this Storage instance.
*/
@objc public let app: FirebaseApp
/**
* The maximum time in seconds to retry an upload if a failure occurs.
* Defaults to 10 minutes (600 seconds).
*/
@objc public var maxUploadRetryTime: TimeInterval {
didSet {
maxUploadRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxUploadRetryTime)
}
}
/**
* The maximum time in seconds to retry a download if a failure occurs.
* Defaults to 10 minutes (600 seconds).
*/
@objc public var maxDownloadRetryTime: TimeInterval {
didSet {
maxDownloadRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxDownloadRetryTime)
}
}
/**
* The maximum time in seconds to retry operations other than upload and download if a failure occurs.
* Defaults to 2 minutes (120 seconds).
*/
@objc public var maxOperationRetryTime: TimeInterval {
didSet {
maxOperationRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxOperationRetryTime)
}
}
/**
* A `DispatchQueue` that all developer callbacks are fired on. Defaults to the main queue.
*/
@objc public var callbackQueue: DispatchQueue {
get {
ensureConfigured()
guard let queue = fetcherService?.callbackQueue else {
fatalError("Internal error: Failed to initialize fetcherService callbackQueue")
}
return queue
}
set(newValue) {
ensureConfigured()
fetcherService?.callbackQueue = newValue
}
}
/**
* Creates a `StorageReference` initialized at the root Firebase Storage location.
* - Returns: An instance of `StorageReference` referencing the root of the storage bucket.
*/
@objc open func reference() -> StorageReference {
ensureConfigured()
let path = StoragePath(with: storageBucket)
return StorageReference(storage: self, path: path)
}
/**
* Creates a StorageReference given a `gs://`, `http://`, or `https://` URL pointing to a
* Firebase Storage location. For example, you can pass in an `https://` download URL retrieved from
* `StorageReference.downloadURL(completion:)` or the `gs://` URL from
* `StorageReference.description`.
* - Parameter url A gs:// or https:// URL to initialize the reference with.
* - Returns: An instance of StorageReference at the given child path.
* - Throws: Throws a fatal error if `url` is not associated with the `FirebaseApp` used to initialize
* this Storage instance.
*/
@objc open func reference(forURL url: String) -> StorageReference {
ensureConfigured()
do {
let path = try StoragePath.path(string: url)
// If no default bucket exists (empty string), accept anything.
if storageBucket == "" {
return StorageReference(storage: self, path: path)
}
// If there exists a default bucket, throw if provided a different bucket.
if path.bucket != storageBucket {
fatalError("Provided bucket: `\(path.bucket)` does not match the Storage bucket of the current " +
"instance: `\(storageBucket)`")
}
return StorageReference(storage: self, path: path)
} catch let StoragePathError.storagePathError(message) {
fatalError(message)
} catch {
fatalError("Internal error finding StoragePath: \(error)")
}
}
/**
* Creates a StorageReference given a `gs://`, `http://`, or `https://` URL pointing to a
* Firebase Storage location. For example, you can pass in an `https://` download URL retrieved from
* `StorageReference.downloadURL(completion:)` or the `gs://` URL from
* `StorageReference.description`.
* - Parameter url A gs:// or https:// URL to initialize the reference with.
* - Returns: An instance of StorageReference at the given child path.
* - Throws: Throws an Error if `url` is not associated with the `FirebaseApp` used to initialize
* this Storage instance.
*/
open func reference(for url: URL) throws -> StorageReference {
ensureConfigured()
var path: StoragePath
do {
path = try StoragePath.path(string: url.absoluteString)
} catch let StoragePathError.storagePathError(message) {
throw StorageError.pathError(message)
} catch {
throw StorageError.pathError("Internal error finding StoragePath: \(error)")
}
// If no default bucket exists (empty string), accept anything.
if storageBucket == "" {
return StorageReference(storage: self, path: path)
}
// If there exists a default bucket, throw if provided a different bucket.
if path.bucket != storageBucket {
throw StorageError
.bucketMismatch("Provided bucket: `\(path.bucket)` does not match the Storage " +
"bucket of the current instance: `\(storageBucket)`")
}
return StorageReference(storage: self, path: path)
}
/**
* Creates a `StorageReference` initialized at a location specified by the `path` parameter.
* - Parameter path A relative path from the root of the storage bucket,
* for instance @"path/to/object".
* - Returns: An instance of `StorageReference` pointing to the given path.
*/
@objc(referenceWithPath:) open func reference(withPath path: String) -> StorageReference {
return reference().child(path)
}
/**
* Configures the Storage SDK to use an emulated backend instead of the default remote backend.
* This method should be called before invoking any other methods on a new instance of `Storage`.
*/
@objc open func useEmulator(withHost host: String, port: Int) {
guard host.count > 0 else {
fatalError("Invalid host argument: Cannot connect to empty host.")
}
guard port >= 0 else {
fatalError("Invalid port argument: Port must be greater or equal to zero.")
}
guard fetcherService == nil else {
fatalError("Cannot connect to emulator after Storage SDK initialization. " +
"Call useEmulator(host:port:) before creating a Storage " +
"reference or trying to load data.")
}
usesEmulator = true
scheme = "http"
self.host = host
self.port = port
}
// MARK: - NSObject overrides
@objc override open func copy() -> Any {
let storage = Storage(app: app, bucket: storageBucket)
storage.callbackQueue = callbackQueue
return storage
}
@objc override open func isEqual(_ object: Any?) -> Bool {
guard let ref = object as? Storage else {
return false
}
return app == ref.app && storageBucket == ref.storageBucket
}
@objc override public var hash: Int {
return app.hash ^ callbackQueue.hashValue
}
// MARK: - Internal and Private APIs
private var fetcherService: GTMSessionFetcherService?
internal var fetcherServiceForApp: GTMSessionFetcherService {
guard let value = fetcherService else {
fatalError("Internal error: fetcherServiceForApp not yet configured.")
}
return value
}
internal let dispatchQueue: DispatchQueue
internal init(app: FirebaseApp, bucket: String) {
self.app = app
auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self,
in: app.container)
appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self,
in: app.container)
storageBucket = bucket
host = "firebasestorage.googleapis.com"
scheme = "https"
port = 443
fetcherService = nil // Configured in `ensureConfigured()`
// Must be a serial queue.
dispatchQueue = DispatchQueue(label: "com.google.firebase.storage")
maxDownloadRetryTime = 600.0
maxDownloadRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxDownloadRetryTime)
maxOperationRetryTime = 120.0
maxOperationRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxOperationRetryTime)
maxUploadRetryTime = 600.0
maxUploadRetryInterval = Storage.computeRetryInterval(fromRetryTime: maxUploadRetryTime)
}
/// Map of apps to a dictionary of buckets to GTMSessionFetcherService.
private static let fetcherServiceLock = NSObject()
private static var fetcherServiceMap: [String: [String: GTMSessionFetcherService]] = [:]
private static var retryWhenOffline: GTMSessionFetcherRetryBlock = {
(suggestedWillRetry: Bool,
error: Error?,
response: @escaping GTMSessionFetcherRetryResponse) in
var shouldRetry = suggestedWillRetry
// GTMSessionFetcher does not consider being offline a retryable error, but we do, so we
// special-case it here.
if !shouldRetry, error != nil {
shouldRetry = (error as? NSError)?.code == URLError.notConnectedToInternet.rawValue
}
response(shouldRetry)
}
private static func initFetcherServiceForApp(_ app: FirebaseApp,
_ bucket: String,
_ auth: AuthInterop,
_ appCheck: AppCheckInterop)
-> GTMSessionFetcherService {
objc_sync_enter(fetcherServiceLock)
defer { objc_sync_exit(fetcherServiceLock) }
var bucketMap = fetcherServiceMap[app.name]
if bucketMap == nil {
bucketMap = [:]
fetcherServiceMap[app.name] = bucketMap
}
var fetcherService = bucketMap?[bucket]
if fetcherService == nil {
fetcherService = GTMSessionFetcherService()
fetcherService?.isRetryEnabled = true
fetcherService?.retryBlock = retryWhenOffline
fetcherService?.allowLocalhostRequest = true
let authorizer = StorageTokenAuthorizer(
googleAppID: app.options.googleAppID,
fetcherService: fetcherService!,
authProvider: auth,
appCheck: appCheck
)
fetcherService?.authorizer = authorizer
bucketMap?[bucket] = fetcherService
}
return fetcherService!
}
private let auth: AuthInterop
private let appCheck: AppCheckInterop
private let storageBucket: String
private var usesEmulator: Bool = false
internal var host: String
internal var scheme: String
internal var port: Int
internal var maxDownloadRetryInterval: TimeInterval
internal var maxOperationRetryInterval: TimeInterval
internal var maxUploadRetryInterval: TimeInterval
/**
* Performs a crude translation of the user provided timeouts to the retry intervals that
* GTMSessionFetcher accepts. GTMSessionFetcher times out operations if the time between individual
* retry attempts exceed a certain threshold, while our API contract looks at the total observed
* time of the operation (i.e. the sum of all retries).
* @param retryTime A timeout that caps the sum of all retry attempts
* @return A timeout that caps the timeout of the last retry attempt
*/
internal static func computeRetryInterval(fromRetryTime retryTime: TimeInterval) -> TimeInterval {
// GTMSessionFetcher's retry starts at 1 second and then doubles every time. We use this
// information to compute a best-effort estimate of what to translate the user provided retry
// time into.
// Note that this is the same as 2 << (log2(retryTime) - 1), but deemed more readable.
var lastInterval = 1.0
var sumOfAllIntervals = 1.0
while sumOfAllIntervals < retryTime {
lastInterval *= 2
sumOfAllIntervals += lastInterval
}
return lastInterval
}
/**
* Configures the storage instance. Freezes the host setting.
*/
private func ensureConfigured() {
guard fetcherService == nil else {
return
}
fetcherService = Storage.initFetcherServiceForApp(app, storageBucket, auth, appCheck)
if usesEmulator {
fetcherService?.allowLocalhostRequest = true
fetcherService?.allowedInsecureSchemes = ["http"]
}
}
private static func bucket(for app: FirebaseApp) -> String {
guard let bucket = app.options.storageBucket else {
fatalError("No default Storage bucket found. Did you configure Firebase Storage properly?")
}
if bucket == "" {
return Storage.bucket(for: app, urlString: "")
} else {
return Storage.bucket(for: app, urlString: "gs://\(bucket)/")
}
}
private static func bucket(for app: FirebaseApp, urlString: String) -> String {
if urlString == "" {
return ""
} else {
guard let path = try? StoragePath.path(GSURI: urlString),
path.object == nil || path.object == "" else {
fatalError("Internal Error: Storage bucket cannot be initialized with a path")
}
return path.bucket
}
}
}
| 8e7560b8cdb9b5ee77eb7dc583c64cb4 | 37.804762 | 106 | 0.688612 | false | false | false | false |
paulopr4/quaddro-mm | refs/heads/master | AprendendoSwift/Desafios/Desafio6-Cartas-Blackjack.playground/section-1.swift | apache-2.0 | 2 | // Nested
// Blackjack ou 21
// 2...10 -> 2...10
// J, Q, K -> 10
// A -> 1 ou 11
struct Carta21 {
enum Naipes: Character {
case Paus = "♣️"
case Copas = "♥️"
case Espadas = "♠️"
case Ouros = "♦️"
}
enum Numeros: Int {
case Dois = 2, Tres, Quatro, Cinco, Seis, Sete, Oito, Nove, Dez
case Valete, Dama, Rei, As
struct Valores {
// podemos declarar em uma linha
// let primeiro: Int, segundo: Int?
// ou duas
let primeiro: Int
let segundo: Int?
}
var valores: Valores {
switch self {
case .As:
return Valores(primeiro: 1, segundo: 11)
case .Valete, .Dama, .Rei:
return Valores(primeiro: 10, segundo: nil)
default:
return Valores(primeiro: self.rawValue, segundo: nil)
}
}
}
let naipe: Naipes
let numero: Numeros
var descrição: String {
var retorno = "Naipe é \(naipe.rawValue), "
retorno += "valor é \(numero.valores.primeiro)"
if let segundo = numero.valores.segundo {
retorno += " ou \(segundo)"
}
return retorno
}
}
let asDeEspadas = Carta21(naipe: .Espadas, numero: .As)
asDeEspadas.descrição
Carta21.Numeros.Sete.rawValue
Carta21.Naipes.Ouros.rawValue
Carta21.Numeros.Valores(primeiro: 3, segundo: nil)
| 8e40127ca6790511964dc62a72214832 | 23.241935 | 71 | 0.508982 | false | false | false | false |
ro6lyo/UICollectionViewGallery | refs/heads/master | UICollectionViewGallery/Classes/VerticalFlowLayout.swift | mit | 1 | //
// File.swift
// Pods
//
// Created by Mehmed Kadir on 11/22/16.
//
//
import UIKit
open class VerticalFlowLayout: UICollectionViewFlowLayout {
var collectionViewOriginalSize = CGSize.zero
var used = false
open var inifiniteScroll = true // can be changed based on requared behaviour
open var scaleElements = true // can be changed based on requared behaviour
open var scalingOffset: CGFloat = 110
open var minimumScaleFactor: CGFloat = 0.5
//MARK:-Open Functions
public func recenterIfNeeded() {
guard used && inifiniteScroll && isReachedEndOrBegining() else {return}
self.collectionView!.contentOffset = self.preferredContentOffsetForElement(at: 0)
}
//
//MARK:-Open overrides
//
override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override open func prepare() {
assert(self.collectionView!.numberOfSections <= 1, "You cannot use UICollectionViewGallery with more than 2 sections")
self.used = self.collectionView!.numberOfItems(inSection: 0) >= MIN_NUMBER_OF_ITEMS_REQUIRED
self.scrollDirection = .vertical
self.sectionInset = UIEdgeInsetsMake(0, 0, 0, self.minimumLineSpacing)
self.collectionView!.showsHorizontalScrollIndicator = false
self.collectionView!.showsVerticalScrollIndicator = false
super.prepare()
self.collectionViewOriginalSize = super.collectionViewContentSize
}
override open var collectionViewContentSize: CGSize {
guard used && inifiniteScroll else {return collectionViewOriginalSize}
return CGSize(width: collectionViewOriginalSize.width, height: collectionViewOriginalSize.height * self.itemSize.height)
}
open override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collection = self.collectionView else {return proposedContentOffset}
let collectionViewSize = collection.bounds.size
let proposedRect = CGRect(x: 0, y: proposedContentOffset.y, width: collectionViewSize.height, height: collectionViewSize.width)
guard let layoutAttributes = self.layoutAttributesForElements(in: proposedRect) else {return proposedContentOffset}
var candidateAttributes: UICollectionViewLayoutAttributes?
let proposedContentOffsetCenterY = proposedContentOffset.y + collectionViewSize.height / 2
for attributes: UICollectionViewLayoutAttributes in layoutAttributes {
if attributes.representedElementCategory != .cell {
continue
}
if candidateAttributes == nil {
candidateAttributes = attributes
continue
}
if fabs(attributes.center.y - proposedContentOffsetCenterY) < fabs(candidateAttributes!.center.y - proposedContentOffsetCenterY) {
candidateAttributes = attributes
}
}
guard (candidateAttributes != nil) else {return proposedContentOffset}
var newOffsetX = candidateAttributes!.center.y - self.collectionView!.bounds.size.height / 2
let offset = newOffsetX - self.collectionView!.contentOffset.y
if (velocity.y < 0 && offset > 0) || (velocity.y > 0 && offset < 0) {
let pageWidth = self.itemSize.height + self.minimumLineSpacing
newOffsetX += velocity.y > 0 ? pageWidth : -pageWidth
}
return CGPoint(x: proposedContentOffset.x, y: newOffsetX)
}
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard used else {return super.layoutAttributesForElements(in: rect)!}
let position = rect.origin.y / collectionViewOriginalSize.height
let rectPosition = position - trunc(position)
var modifiedRect = CGRect(x: rect.origin.x, y: rectPosition * collectionViewOriginalSize.height, width: rect.size.width, height: rect.size.height)
var secondRect = CGRect.zero
if modifiedRect.maxY > collectionViewOriginalSize.height {
secondRect = CGRect(x: rect.origin.x, y: 0, width: rect.size.width, height: modifiedRect.maxY - collectionViewOriginalSize.height)
modifiedRect.size.height = collectionViewOriginalSize.height - modifiedRect.origin.y
}
let attributes = self.newAttributes(for: modifiedRect, offset: trunc(position) * collectionViewOriginalSize.height)
let attributes2 = self.newAttributes(for: secondRect, offset: (trunc(position) + 1) * collectionViewOriginalSize.height)
guard inifiniteScroll else { return attributes}
return attributes + attributes2
}
override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes {
return super.layoutAttributesForItem(at: indexPath)!
}
//
//MARK:-Private Function
//
/**
Finds current scroll position
returns true when it reaches end or begging of the scrollView
*/
private func isReachedEndOrBegining()->Bool {
let page = self.collectionView!.contentOffset.y / collectionViewOriginalSize.height
let radius = (self.collectionView!.contentOffset.y - trunc(page) * collectionViewOriginalSize.height) / collectionViewOriginalSize.height
if radius >= 0.0 && radius <= 0.0002 && page >= self.itemSize.width / 2 + 40 || page < 1.0 {
return true
}
return false
}
private func preferredContentOffsetForElement(at index: Int) -> CGPoint {
guard self.collectionView!.numberOfItems(inSection: 0) > 0 else { return CGPoint(x: CGFloat(0), y: CGFloat(0)) }
if used && inifiniteScroll {
return CGPoint(x:self.collectionView!.contentOffset.x, y:item(at: index)+tunc() - self.collectionView!.contentInset.bottom)
}
return CGPoint(x:self.collectionView!.contentOffset.x, y:item(at: index) - self.collectionView!.contentInset.bottom )
}
private func tunc()->CGFloat {
return trunc(self.itemSize.height / 2) * collectionViewOriginalSize.height
}
private func item(at index: Int) -> CGFloat{
return (self.itemSize.height + self.minimumLineSpacing) * CGFloat(index)
}
private func newAttributes(for rect: CGRect, offset: CGFloat) -> [UICollectionViewLayoutAttributes] {
let attributes = super.layoutAttributesForElements(in: rect)
return self.modifyLayoutAttributes(attributes!, offset: offset)
}
private func modifyLayoutAttributes(_ attributes: [UICollectionViewLayoutAttributes], offset: CGFloat) -> [UICollectionViewLayoutAttributes] {
let contentOffset = self.collectionView!.contentOffset
let size = self.collectionView!.bounds.size
let visibleRect = CGRect(x: contentOffset.x, y: contentOffset.y, width: size.width, height: size.height)
let mappedAttributes = attributes.flatMap({repositionAttributes(newAttr: $0,withOffset: offset,andCenter: visibleRect.midY)})
return mappedAttributes
}
private func repositionAttributes(newAttr:UICollectionViewLayoutAttributes,withOffset offset:CGFloat,andCenter center:CGFloat) ->UICollectionViewLayoutAttributes {
newAttr.center = CGPoint(x: newAttr.center.x , y: newAttr.center.y + offset)
let absDistanceFromCenter = min(abs(center - newAttr.center.y), self.scalingOffset)
guard scaleElements else {return newAttr}
let scale = absDistanceFromCenter * (self.minimumScaleFactor - 1) / self.scalingOffset + 1
newAttr.transform3D = CATransform3DScale(CATransform3DIdentity, scale, scale, 1)
return newAttr
}
}
| 42b6d8948bcc2da54d68dbd326adc35a | 43.715084 | 167 | 0.684408 | false | false | false | false |
bigtreenono/NSPTools | refs/heads/master | RayWenderlich/Introduction to Swift/10 . Enums/ChallengeEnums.playground/section-1.swift | mit | 1 | enum MicrosoftCEOs: Int {
case BillGates = 1
case SteveBallmer
case SatyaNadella
init() {
self = .SatyaNadella
}
func description() -> String {
switch (self) {
case .BillGates:
return "Bill Gates"
case .SteveBallmer:
return "Steve Ballmer"
case .SatyaNadella:
return "Satya Nadella"
}
}
}
let currentCEO = MicrosoftCEOs()
println(currentCEO.description())
let oFirstCEO = MicrosoftCEOs(rawValue: 1)
if let firstCEO = oFirstCEO {
println(firstCEO.description())
} else {
println("No such value")
}
| d6af9e2fee8c8ab178eb2ced7cd03fd9 | 19.392857 | 42 | 0.649737 | false | false | false | false |
CodaFi/swift | refs/heads/master | validation-test/compiler_crashers_2/0189-sr10033.swift | apache-2.0 | 17 | // RUN: not --crash %target-swift-frontend -typecheck %s
// REQUIRES: asserts
protocol P1 {
associatedtype A2 : P2 where A2.A1 == Self
}
protocol P2 {
associatedtype A1 : P1 where A1.A2 == Self
var property: Int { get }
}
extension P2 {
var property: Int { return 0 }
}
class C1 : P1 {
class A2 : P2 {
typealias A1 = C1
}
}
| 07cf7ee1648dfd8bd4fb2db11da1c79f | 14.681818 | 56 | 0.628986 | false | false | false | false |
CatchChat/Yep | refs/heads/master | Yep/Views/Cells/Contacts/ContactsCell.swift | mit | 1 | //
// ContactsCell.swift
// Yep
//
// Created by NIX on 15/3/20.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
final class ContactsCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var badgeImageView: UIImageView!
@IBOutlet weak var joinedDateLabel: UILabel!
@IBOutlet weak var lastTimeSeenLabel: UILabel!
var showProfileAction: (() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
separatorInset = YepConfig.ContactsCell.separatorInset
}
override func prepareForReuse() {
super.prepareForReuse()
}
func configureWithUser(user: User) {
let userAvatar = UserAvatar(userID: user.userID, avatarURLString: user.avatarURLString, avatarStyle: miniAvatarStyle)
avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
let tap = UITapGestureRecognizer(target: self, action: #selector(ContactsCell.tapAvatar))
avatarImageView.addGestureRecognizer(tap)
avatarImageView.userInteractionEnabled = true
nameLabel.text = user.nickname
if let badge = BadgeView.Badge(rawValue: user.badge) {
badgeImageView.image = badge.image
badgeImageView.tintColor = badge.color
} else {
badgeImageView.image = nil
}
joinedDateLabel.text = user.introduction
lastTimeSeenLabel.text = String(format:NSLocalizedString("Last seen %@", comment: ""), NSDate(timeIntervalSince1970: user.lastSignInUnixTime).timeAgo.lowercaseString)
}
@objc private func tapAvatar() {
showProfileAction?()
}
func configureForSearchWithUser(user: User) {
let userAvatar = UserAvatar(userID: user.userID, avatarURLString: user.avatarURLString, avatarStyle: miniAvatarStyle)
avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
nameLabel.text = user.compositedName
if let badge = BadgeView.Badge(rawValue: user.badge) {
badgeImageView.image = badge.image
badgeImageView.tintColor = badge.color
} else {
badgeImageView.image = nil
}
joinedDateLabel.text = user.introduction
lastTimeSeenLabel.text = String(format: NSLocalizedString("Last seen %@", comment: ""), NSDate(timeIntervalSince1970: user.lastSignInUnixTime).timeAgo.lowercaseString)
}
func configureWithDiscoveredUser(discoveredUser: DiscoveredUser) {
let plainAvatar = PlainAvatar(avatarURLString: discoveredUser.avatarURLString, avatarStyle: miniAvatarStyle)
avatarImageView.navi_setAvatar(plainAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
joinedDateLabel.text = discoveredUser.introduction
if let distance = discoveredUser.distance?.yep_format(".1") {
lastTimeSeenLabel.text = "\(distance)km | \(NSDate(timeIntervalSince1970: discoveredUser.lastSignInUnixTime).timeAgo)"
} else {
lastTimeSeenLabel.text = "\(NSDate(timeIntervalSince1970: discoveredUser.lastSignInUnixTime).timeAgo)"
}
nameLabel.text = discoveredUser.nickname
if let badgeName = discoveredUser.badge, badge = BadgeView.Badge(rawValue: badgeName) {
badgeImageView.image = badge.image
badgeImageView.tintColor = badge.color
} else {
badgeImageView.image = nil
}
}
func configureForSearchWithDiscoveredUser(discoveredUser: DiscoveredUser) {
let plainAvatar = PlainAvatar(avatarURLString: discoveredUser.avatarURLString, avatarStyle: miniAvatarStyle)
avatarImageView.navi_setAvatar(plainAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
joinedDateLabel.text = discoveredUser.introduction
if let distance = discoveredUser.distance?.yep_format(".1") {
lastTimeSeenLabel.text = "\(distance)km | \(NSDate(timeIntervalSince1970: discoveredUser.lastSignInUnixTime).timeAgo)"
} else {
lastTimeSeenLabel.text = "\(NSDate(timeIntervalSince1970: discoveredUser.lastSignInUnixTime).timeAgo)"
}
nameLabel.text = discoveredUser.compositedName
if let badgeName = discoveredUser.badge, badge = BadgeView.Badge(rawValue: badgeName) {
badgeImageView.image = badge.image
badgeImageView.tintColor = badge.color
} else {
badgeImageView.image = nil
}
}
}
| d44a7bf136c856025d1bc746d186f63b | 36.772358 | 175 | 0.696298 | false | false | false | false |
eduardoeof/Gollum | refs/heads/master | Workspace/Gollum/GollumTests/VersionTest.swift | mit | 1 | //
// VersionTest.swift
// Gollum
//
// Created by eduardo.ferreira on 5/28/16.
// Copyright © 2016 eduardoeof. All rights reserved.
//
import XCTest
@testable import Gollum
class VersionTest: XCTestCase {
var version: Version!
override func setUp() {
super.setUp()
version = Version(stringLiteral: "A:0.5")
}
//MARK: - Test cases
func testInitWithStringLiteralTypeValue() {
XCTAssertEqual(version.name, "A")
XCTAssertEqual(version.probability, 0.5)
}
func testInitWithExtendedGraphemeClusterLiteralTypeValue() {
version = Version(extendedGraphemeClusterLiteral: "A:0.4")
XCTAssertEqual(version.name, "A")
XCTAssertEqual(version.probability, 0.4)
}
func testInitWithUnicodeScalarLiteralTypeValue() {
version = Version(unicodeScalarLiteral: "A:0.3")
XCTAssertEqual(version.name, "A")
XCTAssertEqual(version.probability, 0.3)
}
func testInitWithValue() {
version = try! Version(value: "A:0.2")
XCTAssertEqual(version.name, "A")
XCTAssertEqual(version.probability, 0.2)
}
func testEqualableOperator() {
let version2 = Version(stringLiteral: "A:0.5")
XCTAssert(version == version2)
}
func testInitWithoutProbabilityValue() {
do {
version = try Version(value: "A")
} catch GollumError.versionSyntaxError(let message) {
XCTAssertEqual(message, "ABTest case expression must have name and probability values splitted by : (e.g. \"MyTestCaseA:0.5\")")
} catch {
XCTFail()
}
}
func testInitWithoutNameValue() {
do {
version = try Version(value: "0.5")
} catch GollumError.versionSyntaxError(let message) {
XCTAssertEqual(message, "ABTest case expression must have name and probability values splitted by : (e.g. \"MyTestCaseA:0.5\")")
} catch {
XCTFail()
}
}
func testInitWithProbabilityNotFloatValue() {
do {
version = try Version(value: "A:A")
} catch GollumError.versionSyntaxError(let message) {
XCTAssertEqual(message, "ABTest must have a probablity (e.g. 0.5)")
} catch {
XCTFail()
}
}
}
| 4b571a1df28e38471cb01e83f30a8ff4 | 26.976471 | 140 | 0.598402 | false | true | false | false |
mirai418/leaflet-ios | refs/heads/master | leaflet/Story.swift | mit | 1 | //
// Story.swift
// leaflet
//
// Created by Mirai Akagawa on 4/26/15.
// Copyright (c) 2015 parks-and-rec. All rights reserved.
//
import UIKit
class Story: NSObject {
var id: Int!
var title: String
var content: String
var pointsOfInterest: [FecPoi]
var color: CGColor
var picture: String
var storyIcon: String
init(id: Int, title: String, content: String, pointsOfInterest: [FecPoi], color: CGColor, picture: String, storyIcon: String) {
self.id = id
self.title = title
self.content = content
self.pointsOfInterest = pointsOfInterest
self.color = color
self.picture = picture
self.storyIcon = storyIcon
super.init()
}
}
| 8a0b8bdc37d580eca25f81208b49c71c | 22.25 | 131 | 0.620968 | false | false | false | false |
tensorflow/swift | refs/heads/main | Tests/SILTests/BitstreamTests.swift | apache-2.0 | 1 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import SIL
public final class BitstreamTests: XCTestCase {
public func testReads() {
// NB: The bytes are read from left to right, the bits are read from
// the LSB to MSB (i.e. right to left!).
var stream = Bitstream(Data([0b11110101, 0b01000111]))
for i in 0..<5 {
XCTAssertEqual(try! stream.nextBit(), i % 2 == 0)
}
XCTAssertEqual(try! stream.nextByte(), 0b00111111)
for i in 5..<8 {
XCTAssertEqual(try! stream.nextBit(), i % 2 == 0)
}
XCTAssertEqual(stream.isEmpty, true)
}
}
extension BitstreamTests {
public static let allTests = [
("testReads", testReads),
]
}
| d2892b2ff6b5d022997091e74dabd975 | 34.263158 | 76 | 0.662687 | false | true | false | false |
michael-lehew/swift-corelibs-foundation | refs/heads/master | Foundation/NSDictionary.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
open class NSDictionary : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding {
private let _cfinfo = _CFInfo(typeID: CFDictionaryGetTypeID())
internal var _storage: [NSObject: AnyObject]
open var count: Int {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
return _storage.count
}
open func object(forKey aKey: Any) -> Any? {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
if let val = _storage[_SwiftValue.store(aKey)] {
return _SwiftValue.fetch(val)
}
return nil
}
open func keyEnumerator() -> NSEnumerator {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
return NSGeneratorEnumerator(_storage.keys.map { _SwiftValue.fetch($0) }.makeIterator())
}
public override convenience init() {
self.init(objects: [], forKeys: [], count: 0)
}
public required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) {
_storage = [NSObject : AnyObject](minimumCapacity: cnt)
for idx in 0..<cnt {
let key = keys[idx].copy()
let value = objects[idx]
_storage[key as! NSObject] = value
}
}
public required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.objects") {
let keys = aDecoder._decodeArrayOfObjectsForKey("NS.keys").map() { return $0 as! NSObject }
let objects = aDecoder._decodeArrayOfObjectsForKey("NS.objects")
self.init(objects: objects as! [NSObject], forKeys: keys)
} else {
var objects = [AnyObject]()
var keys = [NSObject]()
var count = 0
while let key = aDecoder.decodeObject(forKey: "NS.key.\(count)"),
let object = aDecoder.decodeObject(forKey: "NS.object.\(count)") {
keys.append(key as! NSObject)
objects.append(object as! NSObject)
count += 1
}
self.init(objects: objects, forKeys: keys)
}
}
open func encode(with aCoder: NSCoder) {
if let keyedArchiver = aCoder as? NSKeyedArchiver {
keyedArchiver._encodeArrayOfObjects(self.allKeys._nsObject, forKey:"NS.keys")
keyedArchiver._encodeArrayOfObjects(self.allValues._nsObject, forKey:"NS.objects")
} else {
NSUnimplemented()
}
}
public static var supportsSecureCoding: Bool {
return true
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSDictionary.self {
// return self for immutable type
return self
} else if type(of: self) === NSMutableDictionary.self {
let dictionary = NSDictionary()
dictionary._storage = self._storage
return dictionary
}
return NSDictionary(objects: self.allValues, forKeys: self.allKeys.map({ $0 as! NSObject}))
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
// always create and return an NSMutableDictionary
let mutableDictionary = NSMutableDictionary()
mutableDictionary._storage = self._storage
return mutableDictionary
}
return NSMutableDictionary(objects: self.allValues, forKeys: self.allKeys.map { _SwiftValue.store($0) } )
}
public convenience init(object: Any, forKey key: NSCopying) {
self.init(objects: [object], forKeys: [key as! NSObject])
}
public convenience init(objects: [Any], forKeys keys: [NSObject]) {
let keyBuffer = UnsafeMutablePointer<NSObject>.allocate(capacity: keys.count)
keyBuffer.initialize(from: keys)
let valueBuffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: objects.count)
valueBuffer.initialize(from: objects.map { _SwiftValue.store($0) })
self.init(objects: valueBuffer, forKeys:keyBuffer, count: keys.count)
keyBuffer.deinitialize(count: keys.count)
valueBuffer.deinitialize(count: objects.count)
keyBuffer.deallocate(capacity: keys.count)
valueBuffer.deallocate(capacity: objects.count)
}
public convenience init(dictionary otherDictionary: [AnyHashable : Any]) {
self.init(objects: otherDictionary.values.map { $0 }, forKeys: otherDictionary.keys.map { _SwiftValue.store($0) })
}
open override func isEqual(_ value: Any?) -> Bool {
if let other = value as? Dictionary<AnyHashable, Any> {
return isEqual(to: other)
} else if let other = value as? NSDictionary {
return isEqual(to: Dictionary._unconditionallyBridgeFromObjectiveC(other))
}
return false
}
open override var hash: Int {
return self.count
}
open var allKeys: [Any] {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
return _storage.keys.map { $0 }
} else {
var keys = [Any]()
let enumerator = keyEnumerator()
while let key = enumerator.nextObject() {
keys.append(key)
}
return keys
}
}
open var allValues: [Any] {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
return _storage.values.map { $0 }
} else {
var values = [Any]()
let enumerator = keyEnumerator()
while let key = enumerator.nextObject() {
values.append(object(forKey: key)!)
}
return values
}
}
/// Alternative pseudo funnel method for fastpath fetches from dictionaries
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func getObjects(_ objects: inout [Any], andKeys keys: inout [Any], count: Int) {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
for (key, value) in _storage {
keys.append(_SwiftValue.fetch(key))
objects.append(_SwiftValue.fetch(value))
}
} else {
let enumerator = keyEnumerator()
while let key = enumerator.nextObject() {
let value = object(forKey: key)!
keys.append(key)
objects.append(value)
}
}
}
open subscript (key: Any) -> Any? {
return object(forKey: key)
}
open func allKeys(for anObject: Any) -> [Any] {
var matching = Array<Any>()
enumerateKeysAndObjects(options: []) { key, value, _ in
if let val = value as? AnyHashable,
let obj = anObject as? AnyHashable {
if val == obj {
matching.append(key)
}
}
}
return matching
}
/// A string that represents the contents of the dictionary, formatted as
/// a property list (read-only)
///
/// If each key in the dictionary is an NSString object, the entries are
/// listed in ascending order by key, otherwise the order in which the entries
/// are listed is undefined. This property is intended to produce readable
/// output for debugging purposes, not for serializing data. If you want to
/// store dictionary data for later retrieval, see
/// [Property List Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html#//apple_ref/doc/uid/10000048i)
/// and [Archives and Serializations Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Archiving/Archiving.html#//apple_ref/doc/uid/10000047i).
open override var description: String {
return description(withLocale: nil)
}
private func getDescription(of object: Any) -> String? {
switch object {
case is NSArray.Type:
return (object as! NSArray).description(withLocale: nil, indent: 1)
case is NSDecimalNumber.Type:
return (object as! NSDecimalNumber).description(withLocale: nil)
case is NSDate.Type:
return (object as! NSDate).description(with: nil)
case is NSOrderedSet.Type:
return (object as! NSOrderedSet).description(withLocale: nil)
case is NSSet.Type:
return (object as! NSSet).description(withLocale: nil)
case is NSDictionary.Type:
return (object as! NSDictionary).description(withLocale: nil)
default:
if let hashableObject = object as? Dictionary<AnyHashable, Any> {
return hashableObject._nsObject.description(withLocale: nil, indent: 1)
} else {
return nil
}
}
}
open var descriptionInStringsFileFormat: String {
var lines = [String]()
for key in self.allKeys {
let line = NSMutableString(capacity: 0)
line.append("\"")
if let descriptionByType = getDescription(of: key) {
line.append(descriptionByType)
} else {
line.append("\(key)")
}
line.append("\"")
line.append(" = ")
line.append("\"")
let value = self.object(forKey: key)!
if let descriptionByTypeValue = getDescription(of: value) {
line.append(descriptionByTypeValue)
} else {
line.append("\(value)")
}
line.append("\"")
line.append(";")
lines.append(line._bridgeToSwift())
}
return lines.joined(separator: "\n")
}
/// Returns a string object that represents the contents of the dictionary,
/// formatted as a property list.
///
/// - parameter locale: An object that specifies options used for formatting
/// each of the dictionary’s keys and values; pass `nil` if you don’t
/// want them formatted.
open func description(withLocale locale: Locale?) -> String {
return description(withLocale: locale, indent: 0)
}
/// Returns a string object that represents the contents of the dictionary,
/// formatted as a property list.
///
/// - parameter locale: An object that specifies options used for formatting
/// each of the dictionary’s keys and values; pass `nil` if you don’t
/// want them formatted.
///
/// - parameter level: Specifies a level of indentation, to make the output
/// more readable: the indentation is (4 spaces) * level.
///
/// - returns: A string object that represents the contents of the dictionary,
/// formatted as a property list.
open func description(withLocale locale: Locale?, indent level: Int) -> String {
if level > 100 { return "..." }
var lines = [String]()
let indentation = String(repeating: " ", count: level * 4)
lines.append(indentation + "{")
for key in self.allKeys {
var line = String(repeating: " ", count: (level + 1) * 4)
if key is NSArray {
line += (key as! NSArray).description(withLocale: locale, indent: level + 1)
} else if key is Date {
line += (key as! NSDate).description(with: locale)
} else if key is NSDecimalNumber {
line += (key as! NSDecimalNumber).description(withLocale: locale)
} else if key is NSDictionary {
line += (key as! NSDictionary).description(withLocale: locale, indent: level + 1)
} else if key is NSOrderedSet {
line += (key as! NSOrderedSet).description(withLocale: locale, indent: level + 1)
} else if key is NSSet {
line += (key as! NSSet).description(withLocale: locale)
} else {
line += "\(key)"
}
line += " = "
let object = self.object(forKey: key)!
if object is NSArray {
line += (object as! NSArray).description(withLocale: locale, indent: level + 1)
} else if object is Date {
line += (object as! NSDate).description(with: locale)
} else if object is NSDecimalNumber {
line += (object as! NSDecimalNumber).description(withLocale: locale)
} else if object is NSDictionary {
line += (object as! NSDictionary).description(withLocale: locale, indent: level + 1)
} else if object is NSOrderedSet {
line += (object as! NSOrderedSet).description(withLocale: locale, indent: level + 1)
} else if object is NSSet {
line += (object as! NSSet).description(withLocale: locale)
} else {
if let hashableObject = object as? Dictionary<AnyHashable, Any> {
line += hashableObject._nsObject.description(withLocale: nil, indent: level+1)
} else {
line += "\(object)"
}
}
line += ";"
lines.append(line)
}
lines.append(indentation + "}")
return lines.joined(separator: "\n")
}
open func isEqual(to otherDictionary: [AnyHashable : Any]) -> Bool {
if count != otherDictionary.count {
return false
}
for key in keyEnumerator() {
if let otherValue = otherDictionary[key as! AnyHashable] as? AnyHashable,
let value = object(forKey: key)! as? AnyHashable {
if otherValue != value {
return false
}
} else if let otherBridgeable = otherDictionary[key as! AnyHashable] as? _ObjectBridgeable,
let bridgeable = object(forKey: key)! as? _ObjectBridgeable {
if !(otherBridgeable._bridgeToAnyObject() as! NSObject).isEqual(bridgeable._bridgeToAnyObject()) {
return false
}
} else {
return false
}
}
return true
}
public struct Iterator : IteratorProtocol {
let dictionary : NSDictionary
var keyGenerator : Array<Any>.Iterator
public mutating func next() -> (key: Any, value: Any)? {
if let key = keyGenerator.next() {
return (key, dictionary.object(forKey: key)!)
} else {
return nil
}
}
init(_ dict : NSDictionary) {
self.dictionary = dict
self.keyGenerator = dict.allKeys.makeIterator()
}
}
internal struct ObjectGenerator: IteratorProtocol {
let dictionary : NSDictionary
var keyGenerator : Array<Any>.Iterator
mutating func next() -> Any? {
if let key = keyGenerator.next() {
return dictionary.object(forKey: key)!
} else {
return nil
}
}
init(_ dict : NSDictionary) {
self.dictionary = dict
self.keyGenerator = dict.allKeys.makeIterator()
}
}
open func objectEnumerator() -> NSEnumerator {
return NSGeneratorEnumerator(ObjectGenerator(self))
}
open func objects(forKeys keys: [Any], notFoundMarker marker: Any) -> [Any] {
var objects = [Any]()
for key in keys {
if let object = object(forKey: key) {
objects.append(object)
} else {
objects.append(marker)
}
}
return objects
}
open func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool {
return write(to: URL(fileURLWithPath: path), atomically: useAuxiliaryFile)
}
// the atomically flag is ignored if url of a type that cannot be written atomically.
open func write(to url: URL, atomically: Bool) -> Bool {
do {
let pListData = try PropertyListSerialization.data(fromPropertyList: self, format: PropertyListSerialization.PropertyListFormat.xml, options: 0)
try pListData.write(to: url, options: atomically ? .atomic : [])
return true
} catch {
return false
}
}
open func enumerateKeysAndObjects(_ block: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
enumerateKeysAndObjects(options: [], using: block)
}
open func enumerateKeysAndObjects(options opts: NSEnumerationOptions = [], using block: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
let count = self.count
var keys = [Any]()
var objects = [Any]()
getObjects(&objects, andKeys: &keys, count: count)
var stop = ObjCBool(false)
for idx in 0..<count {
withUnsafeMutablePointer(to: &stop, { stop in
block(keys[idx], objects[idx], stop)
})
if stop {
break
}
}
}
open func keysSortedByValue(comparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] {
return keysSortedByValue(options: [], usingComparator: cmptr)
}
open func keysSortedByValue(options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] {
let sorted = allKeys.sorted { lhs, rhs in
return cmptr(lhs, rhs) == .orderedSame
}
return sorted
}
open func keysOfEntries(passingTest predicate: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> {
return keysOfEntries(options: [], passingTest: predicate)
}
open func keysOfEntries(options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> {
var matching = Set<AnyHashable>()
enumerateKeysAndObjects(options: opts) { key, value, stop in
if predicate(key, value, stop) {
matching.insert(key as! AnyHashable)
}
}
return matching
}
override open var _cfTypeID: CFTypeID {
return CFDictionaryGetTypeID()
}
required public convenience init(dictionaryLiteral elements: (Any, Any)...) {
var keys = [NSObject]()
var values = [Any]()
for (key, value) in elements {
keys.append(_SwiftValue.store(key))
values.append(value)
}
self.init(objects: values, forKeys: keys)
}
}
extension NSDictionary : _CFBridgeable, _SwiftBridgeable {
internal var _cfObject: CFDictionary { return unsafeBitCast(self, to: CFDictionary.self) }
internal var _swiftObject: Dictionary<AnyHashable, Any> { return Dictionary._unconditionallyBridgeFromObjectiveC(self) }
}
extension NSMutableDictionary {
internal var _cfMutableObject: CFMutableDictionary { return unsafeBitCast(self, to: CFMutableDictionary.self) }
}
extension CFDictionary : _NSBridgeable, _SwiftBridgeable {
internal var _nsObject: NSDictionary { return unsafeBitCast(self, to: NSDictionary.self) }
internal var _swiftObject: [AnyHashable: Any] { return _nsObject._swiftObject }
}
extension Dictionary : _NSBridgeable, _CFBridgeable {
internal var _nsObject: NSDictionary { return _bridgeToObjectiveC() }
internal var _cfObject: CFDictionary { return _nsObject._cfObject }
}
open class NSMutableDictionary : NSDictionary {
open func removeObject(forKey aKey: Any) {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
_storage.removeValue(forKey: _SwiftValue.store(aKey))
}
/// - Note: this diverges from the darwin version that requires NSCopying (this differential preserves allowing strings and such to be used as keys)
open func setObject(_ anObject: Any, forKey aKey: AnyHashable) {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
_storage[(aKey as! NSObject)] = _SwiftValue.store(anObject)
}
public convenience required init() {
self.init(capacity: 0)
}
public convenience init(capacity numItems: Int) {
self.init(objects: [], forKeys: [], count: 0)
// It is safe to reset the storage here because we know is empty
_storage = [NSObject: AnyObject](minimumCapacity: numItems)
}
public required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) {
super.init(objects: objects, forKeys: keys, count: cnt)
}
public convenience init?(contentsOfFile path: String) {
self.init(contentsOfURL: URL(fileURLWithPath: path))
}
public convenience init?(contentsOfURL url: URL) {
do {
guard let plistDoc = try? Data(contentsOf: url) else { return nil }
let plistDict = try PropertyListSerialization.propertyList(from: plistDoc, options: [], format: nil) as? Dictionary<AnyHashable,Any>
guard let plistDictionary = plistDict else { return nil }
self.init(dictionary: plistDictionary)
} catch {
return nil
}
}
}
extension NSMutableDictionary {
open func addEntries(from otherDictionary: [AnyHashable : Any]) {
for (key, obj) in otherDictionary {
setObject(obj, forKey: key)
}
}
open func removeAllObjects() {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
_storage.removeAll()
} else {
for key in allKeys {
removeObject(forKey: key)
}
}
}
open func removeObjects(forKeys keyArray: [Any]) {
for key in keyArray {
removeObject(forKey: key)
}
}
open func setDictionary(_ otherDictionary: [AnyHashable : Any]) {
removeAllObjects()
for (key, obj) in otherDictionary {
setObject(obj, forKey: key)
}
}
/// - Note: See setObject(_:,forKey:) for details on the differential here
public subscript (key: AnyHashable) -> Any? {
get {
return object(forKey: key)
}
set {
if let val = newValue {
setObject(val, forKey: key)
} else {
removeObject(forKey: key)
}
}
}
}
extension NSDictionary : Sequence {
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
// MARK - Shared Key Sets
extension NSDictionary {
/* Use this method to create a key set to pass to +dictionaryWithSharedKeySet:.
The keys are copied from the array and must be copyable.
If the array parameter is nil or not an NSArray, an exception is thrown.
If the array of keys is empty, an empty key set is returned.
The array of keys may contain duplicates, which are ignored (it is undefined which object of each duplicate pair is used).
As for any usage of hashing, is recommended that the keys have a well-distributed implementation of -hash, and the hash codes must satisfy the hash/isEqual: invariant.
Keys with duplicate hash codes are allowed, but will cause lower performance and increase memory usage.
*/
open class func sharedKeySet(forKeys keys: [NSCopying]) -> AnyObject { NSUnimplemented() }
}
extension NSMutableDictionary {
/* Create a mutable dictionary which is optimized for dealing with a known set of keys.
Keys that are not in the key set can still be set into the dictionary, but that usage is not optimal.
As with any dictionary, the keys must be copyable.
If keyset is nil, an exception is thrown.
If keyset is not an object returned by +sharedKeySetForKeys:, an exception is thrown.
*/
public convenience init(sharedKeySet keyset: AnyObject) { NSUnimplemented() }
}
extension NSDictionary : ExpressibleByDictionaryLiteral { }
extension NSDictionary : CustomReflectable {
public var customMirror: Mirror { NSUnimplemented() }
}
extension NSDictionary : _StructTypeBridgeable {
public typealias _StructType = Dictionary<AnyHashable,Any>
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| 1ea14b1766fe623d583cbafe8f209cba | 37.602374 | 188 | 0.601084 | false | false | false | false |
OlegKetrar/TaskKit | refs/heads/master | Sources/Action.swift | mit | 1 | //
// LazyAction.swift
// TaskKit
//
// Created by Oleg Ketrar on 17.07.17.
// Copyright © 2017 Oleg Ketrar. All rights reserved.
//
/// `LazyAction` encapsulate async work.
/// Taking `Input` and produce `Output` value.
public struct LazyAction<Input, Output> {
var work: (Input, @escaping (Result<Output>) -> Void) -> Void
var completion: (Result<Output>) -> Void = { _ in }
public init(_ work: @escaping (Input, @escaping (Result<Output>) -> Void) -> Void) {
self.work = work
}
/// Convert to `Action` by providing input value.
/// - parameter input:
public func with(input: Input) -> LazyAction<Void, Output> {
return Action { ending in self.work(input, ending) }.onAny(completion)
}
/// Start action with input.
public func execute(with input: Input) {
work(input, completion)
}
}
// MARK: - Convenience
/// `Action` encapsulate async work.
public typealias Action<T> = LazyAction<Void, T>
public extension LazyAction {
/// Create `Action` implementing sync work.
/// - parameter work: Encapsulate sync work.
static func sync(_ work: @escaping (Input) throws -> Output) -> LazyAction {
return LazyAction<Input, Output> { input, ending in
ending(Result { try work(input) })
}
}
static func value(
_ val: @autoclosure @escaping () throws -> Output) -> LazyAction<Void, Output> {
return LazyAction<Void, Output>.sync(val)
}
}
public extension LazyAction where Input == Void {
init(_ work: @escaping (@escaping (Result<Output>) -> Void) -> Void) {
self.init { _, ending in work(ending) }
}
/// Start action.
func execute() {
execute(with: ())
}
/// Adds `successCompletion` as `onSuccess` and start action.
/// - parameter successCompletion: Closure will be called if action succeed.
func execute(_ successCompletion: @escaping (Output) -> Void) {
onSuccess(successCompletion).execute()
}
}
/// `Action` with result type `Void`.
public typealias NoResultAction = LazyAction<Void, Void>
/// `Action` with `Input` and result type `Void`.
public typealias NoResultLazyAction<T> = LazyAction<T, Void>
| a55009c0f32c7fa921591336e2d97c14 | 28.52 | 88 | 0.634598 | false | false | false | false |
swiftingio/alti-sampler | refs/heads/master | Sampler/Sampler.swift | mit | 1 | import Foundation
import CoreLocation
import CoreMotion
protocol SamplerDelegate: class {
func sampler(_ sampler: Sampler, didAdd sample: Sample)
}
class Sampler: NSObject {
weak var delegate: SamplerDelegate?
var locationName: String = ""
let queue: OperationQueue
let altimeter: CMAltimeter
let locationManager: CLLocationManager
fileprivate(set) var isRecording = false
fileprivate(set) var recentLocation: CLLocation?
fileprivate(set) var samples: [Sample] = [] {
didSet {
guard let sample = samples.last else { return }
DispatchQueue.main.async {
self.delegate?.sampler(self, didAdd: sample)
}
}
}
init(queue: OperationQueue = OperationQueue.AltimeterQueue,
altimeter: CMAltimeter = CMAltimeter(),
locationManager: CLLocationManager) {
self.queue = queue
self.altimeter = altimeter
self.locationManager = locationManager
super.init()
self.locationManager.delegate = self
}
}
extension Sampler {
func requestLocationPermissionIfNeeded() {
if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestAlwaysAuthorization()
}
}
func clearSamples() {
samples = []
}
func samplingAvailable() -> Bool {
return CMAltimeter.isRelativeAltitudeAvailable() &&
CLLocationManager.locationServicesEnabled()
}
func startSampling() {
guard samplingAvailable() else { return }
requestLocationPermissionIfNeeded()
isRecording = true
altimeter.startRelativeAltitudeUpdates(to: queue,
withHandler: { [weak self] in self?.altitudeUpdated($0, $1) })
locationManager.startUpdatingLocation()
}
func stopSampling() {
isRecording = false
altimeter.stopRelativeAltitudeUpdates()
locationManager.stopUpdatingLocation()
}
func altitudeUpdated(_ data: CMAltitudeData?, _ error: Error?) {
guard error == nil else { print(error!.localizedDescription); return; }
guard let data = data else { return }
guard let location = recentLocation else { return }
let sample = Sample(data: data, location: location, name: locationName)
samples.append(sample)
}
}
extension Sampler: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
recentLocation = locations.last
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
guard isRecording &&
status == .authorizedAlways ||
status == .authorizedWhenInUse
else { return }
locationManager.startUpdatingLocation()
}
}
| e6559f320c0f86d0531d1b54ad184231 | 30.813187 | 110 | 0.651468 | false | false | false | false |
CharlinFeng/TextField-InputView | refs/heads/master | UITextField+InputView/OneModelVC.swift | mit | 1 | //
// One+Original.swift
// TextField+InputView
//
// Created by 成林 on 15/8/24.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
class CityModel: PickerDataModel {
var spell: String!
init(title: String, spell: String){
super.init(title: title, modelObj: nil)
self.spell = spell
}
}
class OneModelVC: UIViewController {
@IBOutlet weak var tf: OneColTF!
override func viewDidLoad() {
super.viewDidLoad()
let city1 = CityModel(title: "成都市", spell: "ChengDu")
let city2 = CityModel(title: "南充市", spell: "NanChong")
let city3 = CityModel(title: "南部县", spell: "NanBu")
self.tf.emptyDataClickClosure = {
print("正在模拟下载数据,请稍等5秒")
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
/** 一句代码安装 */
self.tf.addOneColPickerViewWithModels([city1,city2,city3])
})
}
}
| 634c43d8d11bb69d4e6268aa0446946e | 21.340426 | 131 | 0.57619 | false | false | false | false |
mleiv/MEGameTracker | refs/heads/master | MEGameTracker/Models/Shepard/Shepard.Appearance/Shepard.AppearanceFormat.swift | mit | 1 | //
// Shepard.AppearanceFormat.swift
// MEGameTracker
//
// Created by Emily Ivie on 3/1/17.
// Copyright © 2017 Emily Ivie. All rights reserved.
//
import Foundation
extension Shepard {
/// A library of formatting functions for Appearance
public struct AppearanceFormat {
// MARK: Constants
public static let ExpectedCodeLength: [Gender: [Shepard.AppearanceGameVersion: Int]] = [
.male: [.game1: 35, .game2: 34, .game3: 34, .legendary: 35],
.female: [.game1: 37, .game2: 36, .game3: 36, .legendary: 37],
]
public static let CodeLengthIncorrect = "Warning: code length (%d) does not match game selected (expected %d)"
/// The alphabetic characters used in ME's hex-like int-to-char mapping.
public static let AvailableAlphabet = "123456789ABCDEFGHIJKLMNPQRSTUVW"
// MARK: Basic Actions
/// Returns a human-readable error message if the appearance code doesn't parse properly.
public static func codeLengthError(_ code: String, gender: Gender, game: Shepard.AppearanceGameVersion) -> String? {
let reportLength = ExpectedCodeLength[gender]?[game] ?? 0
if reportLength == code.count {
return nil
} else {
return String(format: CodeLengthIncorrect, code.count, reportLength)
}
}
/// Returns alphabetic character for the attribute int value.
public static func formatAttribute(_ attributeValue: Int?) -> String {
if attributeValue > 0 {
return AvailableAlphabet[attributeValue! - 1] // starts at 1, not 0
}
return "X"
}
/// Returns int value for the attribute alphabetic character.
public static func unformatAttribute(_ attributeString: Character?) -> Int {
return (AvailableAlphabet.intIndexOf(attributeString ?? "X") ?? -1) + 1
}
/// Unformats a string from XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.X into allowed characters
public static func unformatCode(_ code: String) -> String {
return code.uppercased().onlyCharacters(AvailableAlphabet + "X")
}
/// Formats an alphanumeric string into the XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.XXX.X format
public static func formatCode(_ code: String!, lastCode: String! = nil) -> String {
//strip to valid characters
var unformattedCode: String! = unformatCode(code)
if unformattedCode.isEmpty {
return ""
}
if lastCode != nil {
//if characters removed by user, change to remove valid characters instead of other formatting
let lastUnformattedCode = unformatCode(lastCode)
let requestedSubtractChars = lastCode.length - code.length
let actualSubtractChars = max(0, lastUnformattedCode.length - unformattedCode.length)
if requestedSubtractChars > 0 && actualSubtractChars < requestedSubtractChars {
let subtractChars = requestedSubtractChars - actualSubtractChars
unformattedCode = subtractChars >= unformattedCode.length
? ""
: unformattedCode.stringFrom(0, to: -1 * subtractChars)
}
}
//add formatting
var formattedCode = unformattedCode.replacingOccurrences(of: "([^\\.]{3})",
with: "$1.",
options: NSString.CompareOptions.regularExpression,
range: nil
)
if formattedCode.stringFrom(-1) == "." {
formattedCode = formattedCode.stringFrom(0, to: -1)
}
return formattedCode
}
public static func isEmpty(_ code: String) -> Bool {
return code.uppercased().onlyCharacters(AvailableAlphabet).isEmpty
}
}
}
| 4939b7ae0a3f0150289c31a0ea9a848c | 35.311828 | 124 | 0.707729 | false | false | false | false |
gitkong/FLTableViewComponent | refs/heads/master | FLComponentDemo/FLComponentDemo/FLTableViewHeaderFooterView.swift | mit | 2 | //
// FLTableViewHeaderFooterView.swift
// FLComponentDemo
//
// Created by gitKong on 2017/5/12.
// Copyright © 2017年 gitKong. All rights reserved.
//
import UIKit
// MARK : use FLTableViewHeaderFooterView, because extension can not store properties or override method
class FLTableViewHeaderFooterView: UITableViewHeaderFooterView {
// use this property because textLabel provided by UITableViewHeaderFooterView is not suitable
public var titleLabel : UILabel = UILabel()
public var section : Int?
weak var delegate : FLTableComponentEvent?
public var identifierType : FLIdentifierType?
// MARK : if you want header or footer view have accurate event handling capabilities, you should initialize with init(reuseIdentifier: String?, section: Int)
convenience init(reuseIdentifier: String?, section: Int){
self.init(reuseIdentifier: reuseIdentifier)
self.section = section
}
// MARK : dequeue will call init
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
// create titleLabel
titleLabel.numberOfLines = 0
titleLabel.textColor = UIColor.init(red: 0.43, green: 0.43, blue: 0.45, alpha: 1)
titleLabel.font = UIFont.systemFont(ofSize: 13)
self.contentView.addSubview(titleLabel)
self.identifierType = FLIdentifierType.type(of: reuseIdentifier)
// add gesture
let tapG : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(self.headerFooterDidClick))
self.contentView.addGestureRecognizer(tapG)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame = CGRect.init(x: 0, y: 0, width: self.bounds.size.width - FLHeaderFooterTitleLeftPadding * 2, height: self.bounds.size.height - FLHeaderFooterTitleTopPadding * 2)
titleLabel.center = self.contentView.center
}
// MARK : why not use textLabel, because textLabel always offset upwards
override var textLabel: UILabel?{
print("warnning : textLabel will always return nil, please use titleLabel instead")
return nil
}
// MARK : system warning Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead.so overide it,but still warning
override var backgroundColor: UIColor?{
willSet{
self.contentView.backgroundColor = newValue
}
}
}
extension FLTableViewHeaderFooterView : FLTableComponentEvent{
func headerFooterDidClick(){
guard let identifierType = self.identifierType , let section = self.section else {
return
}
switch identifierType {
case .Header:
delegate?.tableHeaderView!(self, didClickSectionAt: section)
case .Footer:
delegate?.tableFooterView!(self, didClickSectionAt: section)
default : break
}
}
}
| ce2f86ccd10e5413119d25aae69d26a7 | 36.428571 | 188 | 0.689885 | false | false | false | false |
julienbodet/wikipedia-ios | refs/heads/develop | Wikipedia/Code/OnThisDayTimelineView.swift | mit | 1 | import UIKit
public class OnThisDayTimelineView: UIView {
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
open func setup() {
}
public var shouldAnimateDots: Bool = false
public var minimizeUnanimatedDots: Bool = false
public var pauseDotsAnimation: Bool = true {
didSet {
displayLink?.isPaused = pauseDotsAnimation
}
}
private let dotRadius:CGFloat = 9.0
private let dotMinRadiusNormal:CGFloat = 0.4
public var dotsY: CGFloat = 0 {
didSet {
guard shouldAnimateDots == false else {
return
}
updateDotsRadii(to: minimizeUnanimatedDots ? 0.0 : 1.0, at: CGPoint(x: bounds.midX, y: dotsY))
}
}
override public func tintColorDidChange() {
super.tintColorDidChange()
outerDotShapeLayer.strokeColor = tintColor.cgColor
innerDotShapeLayer.fillColor = tintColor.cgColor
innerDotShapeLayer.strokeColor = tintColor.cgColor
setNeedsDisplay()
}
override public var backgroundColor: UIColor? {
didSet {
outerDotShapeLayer.fillColor = backgroundColor?.cgColor
}
}
private lazy var outerDotShapeLayer: CAShapeLayer = {
let shape = CAShapeLayer()
shape.fillColor = UIColor.white.cgColor
shape.strokeColor = UIColor.blue.cgColor
shape.lineWidth = 1.0
self.layer.addSublayer(shape)
return shape
}()
private lazy var innerDotShapeLayer: CAShapeLayer = {
let shape = CAShapeLayer()
shape.fillColor = UIColor.blue.cgColor
shape.strokeColor = UIColor.blue.cgColor
shape.lineWidth = 1.0
self.layer.addSublayer(shape)
return shape
}()
private lazy var displayLink: CADisplayLink? = {
guard self.shouldAnimateDots == true else {
return nil
}
let link = CADisplayLink(target: self, selector: #selector(maybeUpdateDotsRadii))
link.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
return link
}()
override public func removeFromSuperview() {
displayLink?.invalidate()
displayLink = nil
super.removeFromSuperview()
}
override public func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else {
return
}
drawVerticalLine(in: context, rect: rect)
}
public var extendTimelineAboveDot: Bool = true {
didSet {
if oldValue != extendTimelineAboveDot {
setNeedsDisplay()
}
}
}
private func drawVerticalLine(in context: CGContext, rect: CGRect){
context.setLineWidth(1.0)
context.setStrokeColor(tintColor.cgColor)
let lineTopY = extendTimelineAboveDot ? rect.minY : dotsY
context.move(to: CGPoint(x: rect.midX, y: lineTopY))
context.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))
context.strokePath()
}
// Returns CGFloat in range from 0.0 to 1.0. 0.0 indicates dot should be minimized.
// 1.0 indicates dot should be maximized. Approaches 1.0 as timelineView.dotY
// approaches vertical center. Approaches 0.0 as timelineView.dotY approaches top
// or bottom.
private func dotRadiusNormal(with y:CGFloat, in container:UIView) -> CGFloat {
let yInContainer = convert(CGPoint(x:0, y:y), to: container).y
let halfContainerHeight = container.bounds.size.height * 0.5
return max(0.0, 1.0 - (abs(yInContainer - halfContainerHeight) / halfContainerHeight))
}
private var lastDotRadiusNormal: CGFloat = -1.0 // -1.0 so dots with dotAnimationNormal of "0.0" are visible initially
@objc private func maybeUpdateDotsRadii() {
guard let containerView = window else {
return
}
// Shift the "full-width dot" point up a bit - otherwise it's in the vertical center of screen.
let yOffset = containerView.bounds.size.height * 0.15
var radiusNormal = dotRadiusNormal(with: dotsY + yOffset, in: containerView)
// Reminder: can reduce precision to 1 (significant digit) to reduce how often dot radii are updated.
let precision: CGFloat = 2
let roundingNumber = pow(10, precision)
radiusNormal = (radiusNormal * roundingNumber).rounded(.up) / roundingNumber
guard radiusNormal != lastDotRadiusNormal else {
return
}
updateDotsRadii(to: radiusNormal, at: CGPoint(x: bounds.midX, y: dotsY))
// Progressively fade the inner dot when it gets tiny.
innerDotShapeLayer.opacity = easeInOutQuart(number: Float(radiusNormal))
lastDotRadiusNormal = radiusNormal
}
private func updateDotsRadii(to radiusNormal: CGFloat, at center: CGPoint){
outerDotShapeLayer.updateDotRadius(dotRadius * max(radiusNormal, dotMinRadiusNormal), center: center)
innerDotShapeLayer.updateDotRadius(dotRadius * max((radiusNormal - dotMinRadiusNormal), 0.0), center: center)
}
private func easeInOutQuart(number:Float) -> Float {
return number < 0.5 ? 8.0 * pow(number, 4) : 1.0 - 8.0 * (number - 1.0) * pow(number, 3)
}
}
extension CAShapeLayer {
fileprivate func updateDotRadius(_ radius: CGFloat, center: CGPoint) {
path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0.0, endAngle:CGFloat.pi * 2.0, clockwise: true).cgPath
}
}
| dccd84951c33738d2b25ae1fbfda372d | 34.171779 | 130 | 0.637886 | false | false | false | false |
Draveness/RbSwift | refs/heads/master | RbSwift/String/String+Bool.swift | mit | 1 | //
// Exclude.swift
// SwiftPatch
//
// Created by draveness on 18/03/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Foundation
// MARK: - Bool
public extension String {
/// Returns `true` if receiver contains the given strings or characters array.
///
/// " ".isInclude("he") #=> false
/// "he".isInclude("he") #=> true
/// "ohe".isInclude("he") #=> true
/// "ohe".isInclude("he", "oooo") #=> true
/// "oe".isInclude("he", "dajkldjda") #=> false
///
/// - Parameter substrings: An array of strings or characters
/// - Returns: A bool value indicates whether the string includes the other string
func isInclude(_ substrings: String...) -> Bool {
return isInclude(substrings)
}
/// Returns `true` if receiver contains the given strings or characters array.
///
/// " ".isInclude("he") #=> false
/// "he".isInclude("he") #=> true
/// "ohe".isInclude("he") #=> true
/// "ohe".isInclude("he", "oooo") #=> true
/// "oe".isInclude("he", "dajkldjda") #=> false
///
/// - Parameter substrings: An array of strings or characters
/// - Returns: A bool value indicates whether the string includes the other string
func isInclude(_ substrings: [String]) -> Bool {
return substrings.compactMap(contains).isAny { $0 == true }
}
/// Returns `true` if receiver does not contains the given strings or characters array.
///
/// " ".isExlude("he") #=> true
/// "he".isExlude("he") #=> false
/// "ohe".isExlude("he") #=> false
/// "ohe".isExlude("he", "oooo") #=> false
/// "oe".isExlude("he", "dajkldjda") #=> true
///
/// - Parameter substrings: An array of strings or characters
/// - Returns: A bool value indicates whether the string excludes the other string
func isExlude(_ substrings: String...) -> Bool {
return isExlude(substrings)
}
/// Returns `true` if receiver does not contains the given strings or characters array.
///
/// " ".isExlude("he") #=> true
/// "he".isExlude("he") #=> false
/// "ohe".isExlude("he") #=> false
/// "ohe".isExlude("he", "oooo") #=> false
/// "oe".isExlude("he", "dajkldjda") #=> true
///
/// - Parameter substrings: An array of strings or characters
/// - Returns: A bool value indicates whether the string excludes the other string
func isExlude(_ substrings: [String]) -> Bool {
return substrings.compactMap(contains).isAll { $0 == false }
}
/// Returns true if str starts with one of the prefixes given.
///
/// "he".isStartWith("he") #=> true
/// "ohe".isStartWith("he", "oooo") #=> false
/// "oe".isStartWith("o", "dajkldjda") #=> true
///
/// - Parameter substrings: An array of prefixes
/// - Returns: A bool value indicates whether the string starts with another string in array
func isStartWith(_ substrings: String...) -> Bool {
return isStartWith(substrings)
}
/// Returns true if str starts with one of the prefixes given.
///
/// "he".isStartWith("he") #=> true
/// "ohe".isStartWith("he", "oooo") #=> false
/// "oe".isStartWith("o", "dajkldjda") #=> true
///
/// - Parameter substrings: An array of prefixes
/// - Returns: A bool value indicates whether the string starts with another string in array
func isStartWith(_ substrings: [String]) -> Bool {
return substrings.compactMap(hasPrefix).isAny { $0 == true }
}
/// Returns true if str ends with one of the suffixes given.
///
/// " ".isEndWith("he") #=> false
/// "he".isEndWith("he") #=> true
/// "ohe".isEndWith("he") #=> true
/// "ohe".isEndWith("he", "oooo") #=> true
/// "oe".isEndWith("he", "dajkldjda") #=> false
///
/// - Parameter substrings: An array of suffixes
/// - Returns: A bool value indicates whether the string ends with another string in array
func isEndWith(_ substrings: String...) -> Bool {
return isEndWith(substrings)
}
/// Returns true if str ends with one of the suffixes given.
///
/// " ".isEndWith("he") #=> false
/// "he".isEndWith("he") #=> true
/// "ohe".isEndWith("he") #=> true
/// "ohe".isEndWith("he", "oooo") #=> true
/// "oe".isEndWith("he", "dajkldjda") #=> false
///
/// - Parameter substrings: An array of suffixes
/// - Returns: A bool value indicates whether the string ends with another string in array
func isEndWith(_ substrings: [String]) -> Bool {
return substrings.compactMap(hasSuffix).isAny { $0 == true }
}
/// Converts pattern to a `NSReguarExpression`, then returns a bool value indicates whether
/// the `NSReguarExpression` is matched receiver or not.
///
/// " ".isMatch("he") #=> false
/// "he".isMatch("he") #=> true
/// "oe".isMatch("he") #=> false
/// "oe".isMatch(".e") #=> true
/// "abcdefghijklmnopqrstuvwxyz".isMatch(".*") #=> true
///
/// If the second parameter is present, it specifies the position in the string to begin the search.
///
/// "ohe".isMatch("he", 2) #=> false
///
/// - Parameters:
/// - pattern: A string pattern
/// - start: A int specifies the position in the string to begin the search
/// - Returns: a true or false indicates whether the `NSReguarExpression` is matched receiver or not
func isMatch(_ pattern: String, _ start: Int = 0) -> Bool {
let str = substring(from: start)
if let _ = str.match(pattern) { return true }
return false
}
/// Returns true is the recevier string's characters are all whitespaces, like `\r`, `\n`, `\t` and ` `.
///
/// " ".isBlank #=> true
/// "\t\n\r\n".isBlank #=> true
/// "\t\nblah".isBlank #=> false
///
var isBlank: Bool {
return self.chars.reduce(true) { $0 && ($1 =~ "[\r\n\t ]".to_regex) }
}
/// Returns true is the recevier string's characters are all downcase.
///
/// "HELLO".isDowncase #=> false
/// "HELLOo".isDowncase #=> false
/// "hello".isDowncase #=> true
///
var isDowncase: Bool {
return self.downcase == self
}
/// Returns true is the recevier string's characters are all upcase.
///
/// "HELLO".isUpcase #=> true
/// "HELLOo".isUpcase #=> false
///
var isUpcase: Bool {
return self.upcase == self
}
}
| 88ca85a2b1b44d8ed82708c5a572f369 | 40.104651 | 108 | 0.529562 | false | false | false | false |
pixelmaid/palette-knife | refs/heads/master | CanvasView.swift | mit | 2 | //
// CanvasView.swift
// Palette-Knife
//
// Created by JENNIFER MARY JACOBS on 5/4/16.
// Copyright © 2016 pixelmaid. All rights reserved.
//
import UIKit
class CanvasView: UIImageView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override func drawRect(rect: CGRect) {
}
func drawPath(fP: Point, tP: Point, w:Float, c:Color) {
UIGraphicsBeginImageContext(self.frame.size)
let context = UIGraphicsGetCurrentContext()!
self.image?.drawInRect(CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
let color = c.toCGColor();
let fromPoint = fP.toCGPoint();
let toPoint = tP.toCGPoint();
CGContextSetLineCap(context, CGLineCap.Round)
CGContextSetLineWidth(context, CGFloat(w))
CGContextSetStrokeColorWithColor(context, color)
CGContextSetBlendMode(context, CGBlendMode.Normal)
CGContextMoveToPoint(context, fromPoint.x,fromPoint.y)
CGContextAddLineToPoint(context, toPoint.x,toPoint.y)
CGContextStrokePath(context)
self.image = UIGraphicsGetImageFromCurrentImageContext()
self.alpha = 1
UIGraphicsEndImageContext()
}
func drawArc(center:Point, radius:Float,startAngle:Float,endAngle:Float, w:Float, c:Color){
UIGraphicsBeginImageContext(self.frame.size)
let context = UIGraphicsGetCurrentContext()!
self.image?.drawInRect(CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
let color = c.toCGColor();
let _center = center.toCGPoint()
let _radius = CGFloat(radius);
let _startAngle = CGFloat(Float(M_PI/180)*startAngle)
let _endAngle = CGFloat(Float(M_PI)/180*endAngle)
let path = CGPathCreateMutable();
CGPathAddArc(path, nil, _center.x, _center.y, _radius, _startAngle, _endAngle, false)
CGContextSetLineCap(context, CGLineCap.Round)
CGContextSetLineWidth(context, CGFloat(w))
CGContextSetStrokeColorWithColor(context, color)
CGContextSetBlendMode(context, CGBlendMode.Normal)
CGContextAddPath(context, path)
CGContextStrokePath(context)
self.image = UIGraphicsGetImageFromCurrentImageContext()
self.alpha = 1
UIGraphicsEndImageContext()
}
func drawPolygon(){
}
func clear(){
self.image = nil
}
func drawFlower(position:Point){
UIGraphicsBeginImageContext(self.frame.size)
let context = UIGraphicsGetCurrentContext()
self.image?.drawInRect(CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
let color3 = UIColor(red: 0.754, green: 0.101, blue: 0.876, alpha: 1.000)
//// Oval Drawing
let ovalPath = UIBezierPath(ovalInRect: CGRect(x: CGFloat(position.x.get(nil)-52/2), y: CGFloat(position.y.get(nil)-46/2), width: 52, height: 46))
color3.setFill()
ovalPath.fill()
self.image = UIGraphicsGetImageFromCurrentImageContext()
self.alpha = 1
UIGraphicsEndImageContext()
}
func drawLeaf(position:Point,angle:Float,scale:Float){
//// General Declarations
UIGraphicsBeginImageContext(self.frame.size)
let context = UIGraphicsGetCurrentContext()
self.image?.drawInRect(CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))
//// Color Declarations
let color = UIColor(red: 0.000, green: 1.000, blue: 0.069, alpha: 1.000)
let color2 = UIColor(red: 0.207, green: 0.397, blue: 0.324, alpha: 1.000)
//// Group
CGContextSaveGState(context!)
CGContextTranslateCTM(context!, position.toCGPoint().x, position.toCGPoint().y)
CGContextRotateCTM(context!,(50+CGFloat(angle)) * CGFloat(M_PI) / 180)
CGContextScaleCTM(context!, CGFloat(scale), CGFloat(scale))
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPoint(x: 0.54, y: 0))
bezierPath.addCurveToPoint(CGPoint(x: 48.17, y: -18.48), controlPoint1: CGPoint(x: 0.54, y: 0), controlPoint2: CGPoint(x: 34.57, y: -2.64))
bezierPath.addCurveToPoint(CGPoint(x: 54.98, y: -66), controlPoint1: CGPoint(x: 61.78, y: -34.32), controlPoint2: CGPoint(x: 54.98, y: -66))
bezierPath.addCurveToPoint(CGPoint(x: 7.35, y: -40.92), controlPoint1: CGPoint(x: 54.98, y: -66), controlPoint2: CGPoint(x: 17.56, y: -58.08))
bezierPath.addCurveToPoint(CGPoint(x: 0.54, y: 0), controlPoint1: CGPoint(x: -2.86, y: -23.76), controlPoint2: CGPoint(x: 0.54, y: 0))
bezierPath.closePath()
color.setFill()
bezierPath.fill()
color2.setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPoint(x: -0.32, y: 0))
bezier2Path.addCurveToPoint(CGPoint(x: 54.68, y: -66), controlPoint1: CGPoint(x: -0.32, y: 0), controlPoint2: CGPoint(x: 21.94, y: -49.18))
color.setFill()
bezier2Path.fill()
color2.setStroke()
bezier2Path.lineWidth = 1
bezier2Path.stroke()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.moveToPoint(CGPoint(x: 6.68, y: -12))
bezier3Path.addCurveToPoint(CGPoint(x: 47.68, y: -18), controlPoint1: CGPoint(x: 6.68, y: -12), controlPoint2: CGPoint(x: 34.68, y: -10))
color.setFill()
bezier3Path.fill()
color2.setStroke()
bezier3Path.lineWidth = 1
bezier3Path.stroke()
//// Bezier 4 Drawing
let bezier4Path = UIBezierPath()
bezier4Path.moveToPoint(CGPoint(x: 16.68, y: -29))
bezier4Path.addCurveToPoint(CGPoint(x: 56.68, y: -44), controlPoint1: CGPoint(x: 16.68, y: -29), controlPoint2: CGPoint(x: 48.47, y: -36))
color.setFill()
bezier4Path.fill()
color2.setStroke()
bezier4Path.lineWidth = 1
bezier4Path.stroke()
//// Bezier 5 Drawing
let bezier5Path = UIBezierPath()
bezier5Path.moveToPoint(CGPoint(x: 16.68, y: -29))
bezier5Path.addCurveToPoint(CGPoint(x: 12.68, y: -46), controlPoint1: CGPoint(x: 16.68, y: -29), controlPoint2: CGPoint(x: 8.68, y: -36))
color2.setStroke()
bezier5Path.lineWidth = 1
bezier5Path.stroke()
self.image = UIGraphicsGetImageFromCurrentImageContext()
self.alpha = 1
UIGraphicsEndImageContext()
}
}
| eafad64ec5bea66530153c7e298681d4 | 35.421875 | 154 | 0.620907 | false | false | false | false |
ckjavacoder/JSONExport | refs/heads/master | ClientCodeGen/Lang data models/UtilityMethod.swift | mit | 3 | //
// UtilityMethod.swift
//
// Create by Ahmed Ali on 14/11/2014
// Copyright (c) 2014 Mobile Developer. All rights reserved.
//
import Foundation
class UtilityMethod{
var body : String!
var bodyEnd : String!
var bodyStart : String!
var comment : String!
var forEachArrayOfCustomTypeProperty : String!
var forEachProperty : String!
var forEachCustomTypeProperty : String!
var returnStatement : String!
var signature : String!
var forEachPropertyWithSpecialStoringNeeds : String!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: NSDictionary){
forEachCustomTypeProperty = dictionary["forEachCustomTypeProperty"] as? String
body = dictionary["body"] as? String
bodyEnd = dictionary["bodyEnd"] as? String
bodyStart = dictionary["bodyStart"] as? String
comment = dictionary["comment"] as? String
forEachArrayOfCustomTypeProperty = dictionary["forEachArrayOfCustomTypeProperty"] as? String
forEachProperty = dictionary["forEachProperty"] as? String
returnStatement = dictionary["returnStatement"] as? String
signature = dictionary["signature"] as? String
forEachPropertyWithSpecialStoringNeeds = dictionary["forEachPropertyWithSpecialStoringNeeds"] as? String
}
} | 874cb8f3b35a552140c6ee1bf3018a5e | 29.952381 | 112 | 0.764434 | false | false | false | false |
GitHubCha2016/ZLSwiftFM | refs/heads/master | ZLSwiftFM/ZLSwiftFM/Classes/Tools/Global/XLTextView.swift | mit | 1 | //
// XLTextView.swift
// TodayNews
//
// Created by ZXL on 2017/2/21.
// Copyright © 2017年 zxl. All rights reserved.
// 输入中文时限制字符长度
import UIKit
class XLTextView: UITextView {
}
extension XLTextView: UITextViewDelegate{
func textViewDidChange(_ textView: UITextView) {
let toBeString = textView.text
// 获取输入法
let lang = textView.textInputMode?.primaryLanguage
// 如果输入法为中文
if lang == "zh-Hans" {
// 这个range就是指输入的拼音还没有转化成中文是的range
// 如果没有,就表示已经转成中文
let selectedRange = textView.markedTextRange
if selectedRange == nil && (toBeString?.characters.count)! > 5 {
// 截取前5个字符
let index = toBeString?.index((toBeString?.startIndex)!, offsetBy: 5)
textView.text = toBeString?.substring(to: index!)
}
}
else if (toBeString?.characters.count)! > 5{
// 截取前5个字符
let index = toBeString?.index((toBeString?.startIndex)!, offsetBy: 5)
textView.text = toBeString?.substring(to: index!)
}
}
}
| 9a6b69c48a89cc3160645f5ce32b98eb | 28.72973 | 85 | 0.588182 | false | false | false | false |
kevinmeresse/sefi-ios | refs/heads/master | sefi/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// sefi
//
// Created by Kevin Meresse on 4/7/15.
// Copyright (c) 2015 KM. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Check credentials
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.stringForKey(User.usernameKey) != nil && defaults.stringForKey(User.birthdateKey) != nil {
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
TryCatch.try({ () -> Void in
let splitViewController = storyboard.instantiateViewControllerWithIdentifier("mainSplitController") as! UISplitViewController
splitViewController.delegate = self
self.window?.rootViewController = splitViewController
self.window?.makeKeyAndVisible()
}, catch: { (exception) -> Void in
let navController = storyboard.instantiateViewControllerWithIdentifier("NewOffersNavigationController") as! UINavigationController
self.window?.rootViewController = navController
self.window?.makeKeyAndVisible()
}) { () -> Void in
//close resources
}
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
}
| c4878b850976955384ed46c192b7b247 | 50.779221 | 285 | 0.70755 | false | false | false | false |
eweill/Forge | refs/heads/master | Forge/Forge/Runner.swift | mit | 2 | /*
Copyright (c) 2016-2017 M.I. Hollemans
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 Metal
import MetalKit
import MetalPerformanceShaders
/**
To use your neural network with Runner it must conform to this protocol.
For optimal throughput we don't want the CPU to wait for the GPU, or vice
versa. This means the GPU can be working on several inputs at once. Runner
takes care of the synchronization for you.
However, the NeuralNetwork must allocate multiple output images so that each
independent GPU pass gets its own MPSImage. (You need to do this for all
MPSImages stored by the neural network, but not for MPSTemporaryImages.)
*/
public protocol NeuralNetwork {
associatedtype PredictionType
/**
Encodes the commands for the GPU.
- Parameters:
- texture: the MTLTexture with the image or video frame to process
- inflightIndex: which output image to use for this GPU pass
*/
func encode(commandBuffer: MTLCommandBuffer, texture: MTLTexture, inflightIndex: Int)
/**
Converts the output MPSImage into an array of predictions.
This is called from a background thread.
*/
func fetchResult(inflightIndex: Int) -> NeuralNetworkResult<PredictionType>
}
/**
This object is passed back to the UI thread after the neural network has
made a new prediction.
*/
public struct NeuralNetworkResult<PredictionType> {
public var predictions: [PredictionType] = []
// For debugging purposes it can be useful to look at the output from
// intermediate layers. To do so, make the layer write to a real MPSImage
// object (not MPSTemporaryImage) and fill in the debugTexture property.
// The UI thread can then display this texture as a UIImage.
public var debugTexture: MTLTexture?
public var debugScale: Float = 1 // for scaling down float images
public var debugOffset: Float = 0 // for images with negative values
// This is filled in by Runner to measure the latency between starting a
// prediction and receiving the answer. (NOTE: Because we can start a new
// prediction while the previous one is still being processed, the latency
// actually becomes larger the more inflight buffers you're using. It is
// therefore *not* a good indicator of throughput, i.e. frames per second.)
public var latency: CFTimeInterval = 0
public init() { }
}
/**
Runner is a simple wrapper around the neural network that takes care of
scheduling the GPU commands and so on. This leaves the NeuralNetwork object
free to just do neural network stuff.
*/
public class Runner {
public let device: MTLDevice
public let commandQueue: MTLCommandQueue
let inflightSemaphore: DispatchSemaphore
let inflightBuffers: Int
var inflightIndex = 0
/**
- Parameters:
- inflightBuffers: How many tasks the CPU and GPU can do in parallel.
Typical value is 3. Use 1 if you want the CPU to always wait until
the GPU is done (this is not recommended).
*/
public init(commandQueue: MTLCommandQueue, inflightBuffers: Int) {
self.device = commandQueue.device
self.commandQueue = commandQueue
self.inflightBuffers = inflightBuffers
self.inflightSemaphore = DispatchSemaphore(value: inflightBuffers)
}
/**
Encodes the commands for the GPU, commits the command buffer, and returns
immediately. It does not wait for the GPU to finish.
When the GPU finishes executing the buffer, the results are sent to the
completion handler, which will run on the specified queue.
- Note: This method *can* block until the GPU is ready to receive commands
again! You should call it from a background thread -- it's OK to use the
VideoCapture queue for this.
*/
public func predict<NeuralNetworkType: NeuralNetwork>(
network: NeuralNetworkType,
texture inputTexture: MTLTexture,
queue: DispatchQueue,
completion: @escaping (NeuralNetworkResult<NeuralNetworkType.PredictionType>) -> Void) {
// Block until the next GPU buffer is available.
inflightSemaphore.wait()
let startTime = CACurrentMediaTime()
//commandQueue.insertDebugCaptureBoundary()
autoreleasepool {
guard let commandBuffer = commandQueue.makeCommandBuffer() else { return }
network.encode(commandBuffer: commandBuffer, texture: inputTexture, inflightIndex: inflightIndex)
// The completion handler for the command buffer is called on some
// background thread. This may be the same thread that encoded the
// GPU commands (if not waiting on the semaphore), or another one.
commandBuffer.addCompletedHandler { [inflightIndex] commandBuffer in
var result = network.fetchResult(inflightIndex: inflightIndex)
result.latency = CACurrentMediaTime() - startTime
//print("GPU execution duration:", commandBuffer.gpuEndTime - commandBuffer.gpuStartTime)
//print("Elapsed time: \(endTime - startTime) sec")
queue.async { completion(result) }
// We're done, so wake up the encoder thread if it's waiting.
self.inflightSemaphore.signal()
}
inflightIndex = (inflightIndex + 1) % inflightBuffers
commandBuffer.commit()
}
}
}
| 7604efc37de3a35f95489b3a0af5e1d1 | 38.691824 | 110 | 0.729203 | false | false | false | false |
austinzmchen/guildOfWarWorldBosses | refs/heads/master | GoWWorldBosses/ViewControllers/Characters/WBCharactersTableViewController.swift | mit | 1 | //
// WBCharactersTableViewController.swift
// GoWWorldBosses
//
// Created by Austin Chen on 2016-12-13.
// Copyright © 2016 Austin Chen. All rights reserved.
//
import UIKit
import RealmSwift
class WBCharactersTableViewController: UITableViewController, WBDrawerItemViewControllerType {
@IBOutlet weak var leftBarButton: UIBarButtonItem!
@IBAction func leftBarButtonTapped(_ sender: Any) {
self.viewDelegate?.didTriggerToggleButton()
}
var characters: [WBCharacter]?
weak var viewDelegate: WBDrawerMasterViewControllerDelegate?
override func viewDidLayoutSubviews() {
print("here1")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let leftBarButtonItem = UIBarButtonItem.barButtonItem(withImageName:"icBurger",
title: "My Characters",
forTarget: self,
action: #selector(leftBarButtonTapped(_:)) )
self.navigationItem.setLeftBarButton(leftBarButtonItem, animated: true)
let realm = try! Realm()
let results = realm.objects(WBCharacter.self)
self.characters = Array(results)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.characters?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "charactersTableCell", for: indexPath) as! WBCharactersTableViewCell
// Configure the cell...
if let chars = self.characters,
indexPath.row < chars.count
{
let char = chars[indexPath.row]
cell.leftImageView.image = char.iconImage
cell.mainLabel.text = char.race?.uppercased()
cell.mainLabel.textColor = char.raceFontColor
cell.subLabel.text = char.name?.capitalized
cell.rightLabel.text = "\(char.level)"
if (indexPath.row % 2) > 0 {
// odd number
cell.contentView.backgroundColor = UIColor(red: 10/255.0, green: 10/255.0, blue: 10/255.0, alpha: 1)
} else {
// even number
cell.contentView.backgroundColor = UIColor.black
}
}
return cell
}
}
extension WBCharacter {
var iconImage: UIImage? {
// local icon file name is eg, "icGuardian"
let imgName = String(format: "ic%@", self.profession?.capitalized ?? "")
return UIImage(named: imgName)
}
var raceFontColor: UIColor { // race title color depends on profession, not race itself. just be mindful
var color = UIColor.clear
if self.profession?.lowercased() == "elementalist" {
color = UIColor(netHex:0xFF1881)
} else if self.profession?.lowercased() == "engineer" {
color = UIColor(netHex:0xC0908E)
} else if self.profession?.lowercased() == "guardian" {
color = UIColor(netHex:0x2CB3FF)
} else if self.profession?.lowercased() == "mesmer" {
color = UIColor(netHex:0xD01FFF)
} else if self.profession?.lowercased() == "necromancer" {
color = UIColor(netHex:0x72D15D)
} else if self.profession?.lowercased() == "ranger" {
color = UIColor(netHex:0xABD104)
} else if self.profession?.lowercased() == "revenant" {
color = UIColor(netHex:0xDC1313)
} else if self.profession?.lowercased() == "thief" {
color = UIColor(netHex:0xDE6155)
} else if self.profession?.lowercased() == "warrior" {
color = UIColor(netHex:0xFF7400)
}
return color
}
}
| 15b8a4c99b25b6a79f1e14e8a7f6fd8c | 37.132075 | 133 | 0.592281 | false | false | false | false |
296245482/ILab-iOS | refs/heads/master | Charts-master/ChartsRealm/Classes/Data/RealmLineScatterCandleRadarDataSet.swift | apache-2.0 | 4 | //
// RealmLineScatterCandleRadarDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import Charts
import Realm
import Realm.Dynamic
public class RealmLineScatterCandleRadarDataSet: RealmBarLineScatterCandleBubbleDataSet, ILineScatterCandleRadarChartDataSet
{
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// Enables / disables the horizontal highlight-indicator. If disabled, the indicator is not drawn.
public var drawHorizontalHighlightIndicatorEnabled = true
/// Enables / disables the vertical highlight-indicator. If disabled, the indicator is not drawn.
public var drawVerticalHighlightIndicatorEnabled = true
/// - returns: true if horizontal highlight indicator lines are enabled (drawn)
public var isHorizontalHighlightIndicatorEnabled: Bool { return drawHorizontalHighlightIndicatorEnabled }
/// - returns: true if vertical highlight indicator lines are enabled (drawn)
public var isVerticalHighlightIndicatorEnabled: Bool { return drawVerticalHighlightIndicatorEnabled }
/// Enables / disables both vertical and horizontal highlight-indicators.
/// :param: enabled
public func setDrawHighlightIndicators(enabled: Bool)
{
drawHorizontalHighlightIndicatorEnabled = enabled
drawVerticalHighlightIndicatorEnabled = enabled
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! RealmLineScatterCandleRadarDataSet
copy.drawHorizontalHighlightIndicatorEnabled = drawHorizontalHighlightIndicatorEnabled
copy.drawVerticalHighlightIndicatorEnabled = drawVerticalHighlightIndicatorEnabled
return copy
}
} | 77f9f4bec28e0e21add271ca84d8b1a5 | 34.175439 | 124 | 0.751996 | false | false | false | false |
bugcoding/macOSCalendar | refs/heads/master | MacCalendar/AppDelegate.swift | gpl-2.0 | 1 | //
// AppDelegate.swift
// MacCalendar
//
// Created by bugcode on 16/7/16.
// Copyright © 2016年 bugcode. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var settingController: SettingWindowController?
var toolsController: ToolsWindowController?
var calViewController:CalendarViewController?
var statusView: StatusBarView?
//var reminderTipController : ReminderTipWindowController?
// let icon: IconView
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
let calController = CalendarViewController()
//calController.showWindow(self)
self.calViewController = calController
}
// 窗口失去焦点的时候自动关闭
func applicationDidResignActive(_ notification: Notification) {
// 选中状态取消
self.statusView!.isSelected = false
// 窗口关闭
self.calViewController?.window?.close()
// 关闭时重置日期到今天
self.calViewController?.showToday()
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func showToday() {
self.calViewController?.showToday()
}
func openWindow() {
let eventFrame = NSApp.currentEvent?.window?.frame
let eventOrigin = eventFrame?.origin
let eventSize = eventFrame?.size
let window = calViewController?.window
let windowFrame = window?.frame
let windowSize = windowFrame?.size
// 设置状态栏窗口的位置
let windowTopLeftPosition = CGPoint(x: (eventOrigin?.x)! + (eventSize?.width)! / 2.0 - (windowSize?.width)! / 2.0, y: (eventOrigin?.y)! - 2)
window?.setFrameTopLeftPoint(windowTopLeftPosition)
window?.makeKeyAndOrderFront(self)
NSApp.activate(ignoringOtherApps: true)
}
override init()
{
// 加载状态栏
let bar = NSStatusBar.system
let length = NSStatusItem.variableLength
let item = bar.statusItem(withLength: length)
// 初始化状态栏图标
// self.icon = IconView(imageName: "icon", item: item)
self.statusView = StatusBarView.createFromNib()
self.statusView?.initItem(imageName: "icon", item: item)
item.view = self.statusView
super.init()
}
// 打开设置界面
func openSettingWindow() {
self.settingController = SettingWindowController()
self.settingController?.window?.makeKeyAndOrderFront(nil)
}
// 打开工具界面
func openToolsWindow() {
self.toolsController = ToolsWindowController()
self.toolsController?.window?.makeKeyAndOrderFront(nil)
}
// 重新显示面板
func refreshInterface() {
calViewController?.showMonthPanel()
calViewController?.setWeekendLabelColor()
}
override func awakeFromNib() {
self.statusView!.onMouseDown = {
if (self.statusView!.isSelected)
{
self.openWindow()
return
}
self.calViewController?.window?.close()
}
}
}
| ab7c3bd30210a782be373960c90a6b12 | 28.256881 | 148 | 0.633741 | false | false | false | false |
huangboju/Moots | refs/heads/master | Framework/Tests/PerformanceTests.swift | mit | 2 | //
// PerformanceTests.swift
// SpreadsheetView
//
// Created by Kishikawa Katsumi on 4/30/17.
// Copyright © 2017 Kishikawa Katsumi. All rights reserved.
//
import XCTest
@testable import SpreadsheetView
class PerformanceTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testHashPerformance1() {
var set = Set<Location>()
measure {
for r in 0..<400 {
for c in 0..<400 {
set.insert(Location(row: r, column: c))
}
}
}
}
func testHashPerformance2() {
var set = Set<Address>()
measure {
for r in 0..<400 {
for c in 0..<400 {
set.insert(Address(row: r, column: c, rowIndex: r, columnIndex: c))
}
}
}
}
func testHashPerformance3() {
var set = Set<IndexPath>()
measure {
for r in 0..<1000 {
for c in 0..<1000 {
set.insert(IndexPath(row: r, section: c))
}
}
}
}
func testCellRangePerformance1() {
var set = Set<CellRange>()
measure {
for r in 0..<400 {
for c in 0..<400 {
set.insert(CellRange(from: (r, c), to: (r + 1, c + 1)))
}
}
}
}
func testCellRangePerformance2() {
var set = Set<IndexPathCellRange>()
measure {
for r in 0..<400 {
for c in 0..<400 {
set.insert(IndexPathCellRange(from: (r, c), to: (r + 1, c + 1)))
}
}
}
}
func testForLoop() {
var mergedCellLayouts = [Location: CellRange]()
var mergedCells = [CellRange]()
for r in 0..<100 {
for c in 0..<100 {
mergedCells.append(CellRange(from: (r, c), to: (r + 1, c + 1)))
}
}
measure {
for mergedCell in mergedCells {
for column in mergedCell.from.column...mergedCell.to.column {
for row in mergedCell.from.row...mergedCell.to.row {
mergedCellLayouts[Location(row: row, column: column)] = mergedCell
}
}
}
}
}
func testForEach() {
var mergedCellLayouts = [Location: CellRange]()
var mergedCells = [CellRange]()
for r in 0..<100 {
for c in 0..<100 {
mergedCells.append(CellRange(from: (r, c), to: (r + 1, c + 1)))
}
}
measure {
mergedCells.forEach { (mergedCell) in
(mergedCell.from.column...mergedCell.to.column).forEach { (column) in
(mergedCell.from.row...mergedCell.to.row).forEach { (row) in
mergedCellLayouts[Location(row: row, column: column)] = mergedCell
}
}
}
}
}
func testSum() {
let numbers = [Int](repeating: 20, count: 100000)
measure {
var sum = 0
for n in numbers {
sum += n
}
}
}
func testReduce() {
let numbers = [Int](repeating: 20, count: 100000)
measure {
let _ = numbers.reduce(0) { $0 + $1 }
}
}
}
public final class IndexPathCellRange: NSObject {
public let from: IndexPath
public let to: IndexPath
public let columnCount: Int
public let rowCount: Int
var size: CGSize?
init(from: IndexPath, to: IndexPath) {
guard from.column <= to.column && from.row <= to.row else {
fatalError("The value of `from` must be less than or equal to the value of `to`")
}
self.from = from
self.to = to
columnCount = to.column - from.column + 1
rowCount = to.row - from.row + 1
}
public convenience init(from: (row: Int, column: Int), to: (row: Int, column: Int)) {
self.init(from: IndexPath(row: from.row, column: from.column),
to: IndexPath(row: to.row, column: to.column))
}
@available(*, unavailable)
@objc(initWithFromIndexPath:toIndexPath:)
public convenience init(from: NSIndexPath, to: NSIndexPath) {
self.init(from: from as IndexPath, to: to as IndexPath)
}
@available(*, unavailable)
@objc(cellRangeFromIndexPath:toIndexPath:)
public class func cellRange(from: NSIndexPath, to: NSIndexPath) -> IndexPathCellRange {
return self.init(from: from as IndexPath, to: to as IndexPath)
}
public func contains(indexPath: IndexPath) -> Bool {
return indexPath.row >= from.row && indexPath.row <= to.row &&
indexPath.column >= from.column && indexPath.column <= to.column
}
}
extension IndexPathCellRange {
public override var description: String {
return "R\(from.row)C\(from.column):R\(to.row)C\(to.column)"
}
public override var debugDescription: String {
return description
}
}
| 00aeb578e20a0ec0bb8246bdfd8298e6 | 27.489011 | 93 | 0.510511 | false | true | false | false |
joelrfcosta/regular-polygon-control | refs/heads/master | SCRegularPolygon/SCRegularPolygonControl.swift | mit | 1 | //
// SCRegularPolygonControl.swift
// SCRegularPolygon
//
// Created by Joel Costa on 26/11/15.
// Copyright © 2015 SadCoat. All rights reserved.
//
import UIKit
extension Int {
/// Convert the angle value to radian value
var scDegreesToRadians : CGFloat {
return CGFloat(self) * CGFloat(M_PI) / 180.0
}
}
@IBDesignable
class SCRegularPolygonControl: UIControl {
var _verticesCount:Int = 3
/// Polygon certices quantity. Min: 3; Max: 1000
@IBInspectable var verticesCount:Int {
set(newValue) {
_verticesCount = max(3, min(1000, newValue))
}
get {
return _verticesCount
}
}
/// Polygon fill color
@IBInspectable var color:UIColor = UIColor.whiteColor()
/// Polygon shadow color
@IBInspectable var shadowColor:UIColor = UIColor.blackColor()
/// Shadow blur radius
@IBInspectable var shadowBlurRadius:CGFloat = 0
/// Polygon shadow offset
@IBInspectable var shadowOffset:CGSize = CGSizeZero
/// Polygon rotation
@IBInspectable var rotation:Int = 0
/// Polygon translation
@IBInspectable var translation:CGPoint = CGPointZero
var _margin:CGFloat = 0
/// Polygon margin
@IBInspectable var margin:CGFloat {
set(newValue) {
_margin = max(0, newValue)
}
get {
return _margin
}
}
var _cornerRadius:CGFloat = 0
/// Polygon corners radius
@IBInspectable var cornerRadius:CGFloat {
set(newValue) {
_cornerRadius = max(0, newValue)
}
get {
return _cornerRadius
}
}
#if TARGET_INTERFACE_BUILDER
override func willMoveToSuperview(newSuperview: UIView?) {
//self.backgroundColor = UIColor.clearColor()
self.opaque = false
}
#endif
override init(frame: CGRect) {
super.init(frame: frame)
//self.backgroundColor = UIColor.clearColor()
self.opaque = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//self.backgroundColor = UIColor.clearColor()
self.opaque = false
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
let center = CGPointMake(rect.size.width / 2.0, rect.size.height / 2.0)
CGContextTranslateCTM(context, center.x + translation.x, center.y + translation.y);
/**
* Rotate the context to apply rotation, if necessary
*/
if (rotation > 0) {
CGContextRotateCTM(context, CGFloat(rotation.scDegreesToRadians));
}
/**
* Set context shadow, if necessary
*/
if (shadowBlurRadius > 0) {
CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadowColor.CGColor);
}
CGContextBeginPath(context)
CGContextSetFillColorWithColor(context, color.CGColor)
/**
* Calculate the angle for the custom vertices quantity
*/
let angle = 2 * M_PI / Double(verticesCount)
/**
* Calculate the edge length based on rect size and blur radius
*/
let size:Double = (Double( min(rect.size.height, rect.size.width)) / 2.0) - Double(margin)
/**
* Calculate all the necessary vertices coordinates
*/
var points = [CGPoint]()
for i in 1...verticesCount {
points.append(CGPoint(x: CGFloat(size * sin(Double(i) * angle )), y: CGFloat(size * cos(Double(i) * angle))))
}
/**
* Set context path
*/
CGContextMoveToPoint(context, (points[verticesCount-1].x + points[0].x) / 2, (points[verticesCount-1].y + points[0].y) / 2)
for i in 0...verticesCount-2 {
CGContextAddArcToPoint(context, points[i].x, points[i].y, points[i+1].x, points[i+1].y, cornerRadius)
}
CGContextAddArcToPoint(context, points[verticesCount-1].x, points[verticesCount-1].y, points[0].x, points[0].y, cornerRadius)
/**
* Close the path
*/
CGContextClosePath(context)
/**
* Draw the path by filling the area within the path
*/
CGContextDrawPath(context, CGPathDrawingMode.Fill);
CGContextRestoreGState(context);
}
} | 0628fa41d166f6258474d41c3276ac42 | 28.487013 | 133 | 0.5837 | false | false | false | false |
jiangteng/ContainerViewController | refs/heads/master | Example/ContainerViewController/Example2ControllerView.swift | mit | 1 | //
// Example2ControllerView.swift
// ContainerViewController
//
// Created by JiangTeng on 16/7/16.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import UIKit
import ContainerViewController
class Example2ControllerView: UIViewController {
var label:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
title = "example2"
label = UILabel.init(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 200))
label.backgroundColor = UIColor.red
label.text = "我是占位图"
setup()
view.addSubview(label)
// Do any additional setup after loading the view.
}
func setup() {
let sampleVC1:UIViewController = UIViewController()
sampleVC1.title = "sampleVC1"
sampleVC1.view.backgroundColor = UIColor.blue
let sampleVC2:UIViewController = UIViewController()
sampleVC2.title = "sampleVC2"
let contaninerVC = TNContainerViewController.init(controllers: [sampleVC1,sampleVC2], topBarHeight: 200, parentViewController: self)
contaninerVC.menuItemFont = UIFont.systemFont(ofSize: 16)
contaninerVC.menuBackGroudColor = UIColor.white
contaninerVC.menuWidth = self.view.frame.width * 0.5 - 10.0
contaninerVC.indicatorHeight = 1.0
contaninerVC.menuViewHeight = 80
contaninerVC.delegate = self
contaninerVC.menuIndicatorColor = UIColor.blue
contaninerVC.menuItemTitleColor = UIColor.black
contaninerVC.menuItemSelectedTitleColor = UIColor.blue
self.view.addSubview(contaninerVC.view)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension Example2ControllerView : TNContainerViewControllerDelegate{
func containerViewItem(_ index: NSInteger, currentController: UIViewController) {
currentController.viewWillAppear(true)
}
}
| 28227e2e3767ec281e6a6e35f79609f1 | 31.984127 | 140 | 0.680462 | false | false | false | false |
Connecthings/sdk-tutorial | refs/heads/master | ios/SWIFT/Zone/3-InApp-Action/Complete/InAppAction/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// InAppAction
//
// Created by sarra srairi on 11/08/2016.
// Copyright © 2016 Connecthings. All rights reserved.
//
import UIKit
import ConnectPlaceActions
import HerowAnalytics
import HerowConnection
import HerowLocationDetection
import ConnectPlaceCommon
class ViewController: UIViewController, HerowInAppActionDelegate, HerowInProximityInForegroundDelegate {
@IBOutlet weak var txtAlertMessage: UILabel!
@IBOutlet weak var buttonInAppAction: UIButton!
var currentPlaceInAppAction: PlaceInAppAction!
override func viewWillAppear(_ animated: Bool) {
super.viewDidAppear(animated);
HerowDetectionManager.shared.registerInAppActionDelegate(self)
HerowDetectionManager.shared.registerInProximityInForeground(self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewDidAppear(animated);
HerowDetectionManager.shared.unregisterInAppActionDelegate()
HerowDetectionManager.shared.unregisterInProximityInForeground(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func createInAppAction(_ placeInAppAction: HerowPlaceInAppAction, statusManager: InAppActionStatusManagerDelegate) -> Bool {
if ("restaurant" == placeInAppAction.getTag()) {
// show a view because the user is in a restaurant
GlobalLogger.shared.debug("Well done! now you have created your in-app action")
self.txtAlertMessage.text = placeInAppAction.getTag()
txtAlertMessage.setNeedsDisplay()
buttonInAppAction.isHidden = false
currentPlaceInAppAction = placeInAppAction
return true
}
self.txtAlertMessage.text = "No zone ready for action"
txtAlertMessage.setNeedsDisplay()
return false
}
func removeInAppAction(_ placeInAppAction: HerowPlaceInAppAction, inAppActionRemoveStatus: InAppActionRemoveStatus) -> Bool {
GlobalLogger.shared.debug("Well done! now you have removed your in-app action")
buttonInAppAction.isHidden = true
txtAlertMessage.text = "The In-App Action has been removed"
txtAlertMessage.setNeedsDisplay()
return true
}
func proximityContentsInForeground(_ contents: [HerowPlaceInAppAction]) {
for place in contents {
print("place: \(place)")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let alertViewController = segue.destination as? AlertViewControllerAction {
if let currentHerowPlaceInAppAction = currentPlaceInAppAction as? HerowPlaceInAppAction {
alertViewController.currentPlaceInAppAction = currentHerowPlaceInAppAction
}
}
}
}
| 282f51b50651b524bd51a9016edbf6ea | 37.202703 | 129 | 0.711001 | false | false | false | false |
onfoot/apusapus | refs/heads/master | apusapus-taxonomy.swift | mit | 1 | import Foundation
public enum JSONDescription {
case jsonDictionary([NSString:JSONDescription])
case jsonArray
case jsonString
case jsonNumber
case jsonBool
indirect case jsonOptional(JSONDescription)
}
public enum TaxonomyResult {
case valid
case invalid(field: String, message: String)
}
public extension JSONValue {
// swiftlint:disable cyclomatic_complexity
func matchesDescription(_ description: JSONDescription) -> Bool {
switch description {
case .jsonString:
if self.asString() != nil {
return true
}
case .jsonBool:
if self.asBool() != nil {
return true
}
case .jsonNumber:
if self.asNumber() != nil {
return true
}
case .jsonArray:
if self.asArray() != nil {
return true
}
case let .jsonOptional(optionalDescription):
if self.isNull() {
return true
}
switch optionalDescription {
case .jsonOptional:
return false
default:
return self.matchesDescription(optionalDescription)
}
case let .jsonDictionary(descriptionDictionary):
guard let dictionary = self.asDictionary() else {
return false
}
var isValid = true
for (key, value) in descriptionDictionary {
if dictionary[key] == nil ||
(dictionary[key] != nil && !dictionary[key]!.matchesDescription(value)) {
isValid = false
}
}
return isValid
}
return false
}
func validateDescription(_ description: JSONDescription) -> TaxonomyResult {
switch description {
case .jsonString:
if self.asString() != nil {
return .valid
}
return .invalid(field: self.description, message: "Should be String")
case .jsonBool:
if self.asBool() != nil {
return .valid
}
return .invalid(field: self.description, message: "Should be Bool")
case .jsonNumber:
if self.asNumber() != nil {
return .valid
}
return .invalid(field: self.description, message: "Should be a Number")
case .jsonArray:
if self.asArray() != nil {
return .valid
}
return .invalid(field: self.description, message: "Should be an Array")
case let .jsonOptional(optionalDescription):
if self.isNull() {
return .valid
}
switch optionalDescription {
case .jsonOptional:
return .invalid(field: self.description, message: "Should be an Optional")
default:
return self.validateDescription(optionalDescription)
}
case let .jsonDictionary(descriptionDictionary):
guard let dictionary = self.asDictionary() else {
return .invalid(field: self.description, message: "Should be a Dictionary")
}
for (key, value) in descriptionDictionary {
if dictionary[key] == nil {
continue
}
let elementResult = dictionary[key]!.validateDescription(value)
if case let .invalid(field, _) = elementResult {
return .invalid(field: key as String, message: "Value \(field) should be a \(value)")
}
}
return .valid
}
}
}
| b2679b4e1edc080d55c7adbc55d834d4 | 25.25 | 105 | 0.521164 | false | false | false | false |
ndevenish/KerbalHUD | refs/heads/master | KerbalHUD/Point2D.swift | mit | 1 | //
// Point2D.swift
// KerbalHUD
//
// Created by Nicholas Devenish on 28/08/2015.
// Copyright © 2015 Nicholas Devenish. All rights reserved.
//
import Foundation
import CoreGraphics
import GLKit
public protocol Point {
func flatten() -> [Float]
static var vertexAttributes : VertexAttributes { get }
}
public struct Point2D : Point, NilLiteralConvertible {
var x : Float
var y : Float
public init(fromCGPoint: CGPoint) {
x = Float(fromCGPoint.x)
y = Float(fromCGPoint.y)
}
init(_ x: Float, _ y: Float) {
self.x = x
self.y = y
}
public init(x: Float, y: Float) {
self.x = x
self.y = y
}
public init(nilLiteral: ()) {
x = 0
y = 0
}
public func flatten() -> [Float] {
return [x, y]
}
public static var vertexAttributes = VertexAttributes(pts: 2, tex: 0, col: false)
}
public struct TexturedPoint2D : Point {
var x : Float
var y : Float
var u : Float
var v : Float
public init(_ x: Float, _ y: Float, u: Float, v: Float) {
self.x = x
self.y = y
self.u = u
self.v = v
}
public func flatten() -> [Float] {
return [x, y, u, v]
}
public static var vertexAttributes = VertexAttributes(pts: 2, tex: 2, col: false)
}
public struct TexturedColoredPoint2D : Point {
var x : Float
var y : Float
var u : Float
var v : Float
var color : Color4
init(_ x: Float, _ y: Float, u: Float, v: Float, color: Color4) {
self.x = x
self.y = y
self.u = u
self.v = v
self.color = color
}
public func flatten() -> [Float] {
// Convert the rgba to a single float
let r = UInt8(color.r * 255)
let g = UInt8(color.g * 255)
let b = UInt8(color.b * 255)
let a = UInt8(color.a * 255)
let bytes:[UInt8] = [r, g, b, a]
let f32 = UnsafePointer<Float>(bytes).memory
// Flattened!
return [x, y, u, v, f32]
}
public static var vertexAttributes = VertexAttributes(pts: 2, tex: 2, col: true)
}
public func +(left: Point2D, right: Point2D) -> Point2D {
return Point2D(x: left.x+right.x, y: left.y+right.y)
} | d422e1b9eeeb803ba676f02f72f436f2 | 20.020202 | 83 | 0.602885 | false | false | false | false |
colemancda/Pedido | refs/heads/master | Pedido Admin/Pedido Admin/RelationshipViewController.swift | mit | 1 | //
// RelationshipViewController.swift
// Pedido Admin
//
// Created by Alsey Coleman Miller on 1/3/15.
// Copyright (c) 2015 ColemanCDA. All rights reserved.
//
import Foundation
import UIKit
import CoreData
import CorePedido
import CorePedidoClient
/** View controller for editing to-many relationships between entities. Displays the contents of a many-to-one relationship. */
class RelationshipViewController: FetchedResultsViewController {
// MARK: - Properties
var relationship: (NSManagedObject, String)? {
didSet {
// create fetch request
if relationship != nil {
let (managedObject, key) = self.relationship!
let relationshipDescription = managedObject.entity.relationshipsByName[key] as? NSRelationshipDescription
assert(relationshipDescription != nil, "Relationship \(key) not found on \(managedObject.entity.name!) entity")
assert(relationshipDescription!.toMany, "Relationship \(key) on \(managedObject.entity.name!) is not to-many")
assert(!relationshipDescription!.inverseRelationship!.toMany, "Inverse relationship \(!relationshipDescription!.inverseRelationship!.toMany) is to-many")
let fetchRequest = NSFetchRequest(entityName: relationshipDescription!.destinationEntity!.name!)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: Store.sharedStore.resourceIDAttributeName, ascending: true)]
fetchRequest.predicate = NSComparisonPredicate(leftExpression: NSExpression(forKeyPath: relationshipDescription!.inverseRelationship!.name), rightExpression: NSExpression(forConstantValue: managedObject), modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.EqualToPredicateOperatorType, options: NSComparisonPredicateOptions.NormalizedPredicateOption)
self.fetchRequest = fetchRequest
}
else {
self.fetchRequest = nil
}
}
}
}
| 5fae7d4e41cff86e00ac0df94ec59ba1 | 42.346154 | 410 | 0.649068 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.