repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
NoodleOfDeath/PastaParser
refs/heads/master
runtime/swift/Example/GrammarKit_Tests/SampleTests.swift
mit
1
// // GrammarKit // // Copyright © 2020 NoodleOfDeath. All rights reserved. // import XCTest import SwiftyUTType import GrammarKit /// Runs GrammarLooder and GrammaticalScanner tests. class SampleTests: XCTestCase { var resourcePath: String = "" var grammarsDirectory: String { return resourcePath +/ "grammars" } var samplesDirectory: String { return resourcePath +/ "samples" } lazy var grammarLoader: GrammarLoader = GrammarLoader(searchPaths: grammarsDirectory) enum Expectation: String { case lexerRuleCount } override func setUp() { super.setUp() guard let resourcePath = Bundle(for: type(of: self)).resourcePath else { XCTFail(); return } self.resourcePath = resourcePath } func testXML() { test(sample: "Sample.xml", expectations: [ .lexerRuleCount: 18, ]) } func testHTML() { test(sample: "Sample.html", expectations: [ .lexerRuleCount: 18, ]) } func testSwift() { test(sample: "Sample.swift", expectations: [ .lexerRuleCount: 48, ]) } func testJava() { test(sample: "Sample.java", expectations: [ .lexerRuleCount: 44, ]) } fileprivate func test(sample: String, expectations: [Expectation: Any] = [:]) { let sampleFile = samplesDirectory +/ sample do { print("----- Testing \(sampleFile.fileURL.uttype.rawValue) -----") guard let grammar = grammarLoader.loadGrammar(for: sampleFile.fileURL.uttype.rawValue) else { XCTFail(); return } //print(grammar) print("------------") let text = try String(contentsOfFile: sampleFile) // Run GrammarLoader tests. XCTAssertEqual(expectations[.lexerRuleCount] as? Int, grammar.lexerRules.count) // Run ExampleScanner tests. let scanner = ExampleScanner(grammar: grammar) scanner.scan(text) } catch { print(error) XCTFail() } } }
25829d04c48755b7bbd9c8b2ab4582ff
25.782051
125
0.591671
false
true
false
false
ProfileCreator/ProfileCreator
refs/heads/master
ProfileCreator/ProfileCreator/Profile Editor TableView CellViews/PayloadCellViewTableView.swift
mit
1
// // TableCellViewTextField.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Cocoa import ProfilePayloads class PayloadCellViewTableView: PayloadCellView, ProfileCreatorCellView, TableViewCellView { // MARK: - // MARK: Instance Variables var scrollView: NSScrollView? var tableView: NSTableView? var progressIndicator = NSProgressIndicator() var textFieldProgress = NSTextField() var imageViewDragDrop = NSImageView() var buttonImport: NSSegmentedControl? var isImporting = false var tableViewContent = [Any]() var tableViewColumns = [PayloadSubkey]() var tableViewContentSubkey: PayloadSubkey? var tableViewContentType: PayloadValueType = .undefined var valueDefault: Any? let buttonAddRemove = NSSegmentedControl() private var dragDropType = NSPasteboard.PasteboardType(rawValue: "private.table-row") // MARK: - // MARK: Initialization required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(subkey: PayloadSubkey, payloadIndex: Int, enabled: Bool, required: Bool, editor: ProfileEditor) { super.init(subkey: subkey, payloadIndex: payloadIndex, enabled: enabled, required: required, editor: editor) // --------------------------------------------------------------------- // Set Value Type // --------------------------------------------------------------------- if subkey.typeInput == .dictionary { self.tableViewContentSubkey = subkey } else if subkey.typeInput == .array { self.tableViewContentSubkey = subkey.subkeys.first } self.tableViewContentType = self.tableViewContentSubkey?.type ?? .undefined // --------------------------------------------------------------------- // Setup Custom View Content // --------------------------------------------------------------------- self.scrollView = EditorTableView.scrollView(height: 100.0, constraints: &self.cellViewConstraints, target: self, cellView: self) if let tableView = self.scrollView?.documentView as? NSTableView { tableView.allowsMultipleSelection = true tableView.registerForDraggedTypes([dragDropType]) self.tableView = tableView } self.setupScrollView() // --------------------------------------------------------------------- // Setup Table View Content // --------------------------------------------------------------------- if let aTableView = self.tableView { self.setupContent(forTableView: aTableView, subkey: subkey) } // --------------------------------------------------------------------- // Setup Button Add/Remove // --------------------------------------------------------------------- self.setupButtonAddRemove() // --------------------------------------------------------------------- // Setup Footer // --------------------------------------------------------------------- super.setupFooter(belowCustomView: self.buttonAddRemove) // --------------------------------------------------------------------- // Set Default Value // --------------------------------------------------------------------- if let valueDefault = subkey.defaultValue() { self.valueDefault = valueDefault } // --------------------------------------------------------------------- // Set Drag n Drop support // --------------------------------------------------------------------- if self.valueImportProcessor != nil { self.tableView?.registerForDraggedTypes([.backwardsCompatibleFileURL]) self.setupButtonImport() self.setupProgressIndicator() self.setupTextFieldProgress() self.setupImageViewDragDrop() } // --------------------------------------------------------------------- // Set Value // --------------------------------------------------------------------- self.tableViewContent = self.getTableViewContent() // --------------------------------------------------------------------- // Setup KeyView Loop Items // --------------------------------------------------------------------- self.leadingKeyView = self.buttonAddRemove self.trailingKeyView = self.buttonAddRemove // --------------------------------------------------------------------- // Activate Layout Constraints // --------------------------------------------------------------------- NSLayoutConstraint.activate(self.cellViewConstraints) // --------------------------------------------------------------------- // Reload TableView // --------------------------------------------------------------------- self.tableView?.reloadData() } private func getTableViewContent() -> [Any] { var valueTableView: Any? if let value = self.profile.settings.value(forSubkey: self.subkey, payloadIndex: self.payloadIndex) { valueTableView = value } else if let valueDefault = self.valueDefault { valueTableView = valueDefault } if let value = valueTableView, let tableViewContent = self.tableViewContent(fromValue: value) { return tableViewContent } else { return [Any]() } } private func tableViewReloadData() { self.tableViewContent = self.getTableViewContent() self.tableView?.reloadData() } private func tableViewContent(fromValue value: Any) -> [Any]? { if subkey.typeInput == .dictionary, let valueDict = value as? [String: Any] { var newValueArray = [[String: Any]]() if let subkeyKey = subkey.subkeys.first(where: { $0.key == ManifestKeyPlaceholder.key }), let subkeyValue = subkey.subkeys.first(where: { $0.key == ManifestKeyPlaceholder.value }) { for (key, value) in valueDict { var newValue = [String: Any]() newValue[subkeyKey.key] = key newValue[subkeyValue.key] = value newValueArray.append(newValue) } } return newValueArray } else if subkey.typeInput == .array, let valueArray = value as? [Any] { return valueArray } else { Log.shared.debug(message: "Input type: \(subkey.typeInput) is not currently handled by CellViewTableView", category: String(describing: self)) } return nil } private func tableViewContentSave() { switch self.subkey.type { case .dictionary: guard let tableViewContent = self.tableViewContent as? [[String: Any]] else { return } var valueSave = [String: Any]() for rowValue in tableViewContent { let key = rowValue[ManifestKeyPlaceholder.key] as? String ?? "" if let value = rowValue[ManifestKeyPlaceholder.value] { valueSave[key] = value } } self.profile.settings.setValue(valueSave, forSubkey: self.subkey, payloadIndex: self.payloadIndex) case .array: self.profile.settings.setValue(self.tableViewContent, forSubkey: self.subkey, payloadIndex: self.payloadIndex) default: Log.shared.debug(message: "Type: \(subkey.typeInput) is not currently handled by CellViewTableView", category: String(describing: self)) } } // MARK: - // MARK: PayloadCellView Functions override func enable(_ enable: Bool) { self.isEnabled = enable self.tableView?.isEnabled = enable self.buttonAddRemove.isEnabled = enable if let buttonImport = self.buttonImport { buttonImport.isEnabled = enable } } // MARK: - // MARK: Button Actions @objc private func clickedImport(_ segmentedControl: NSSegmentedControl) { guard let window = self.window else { return } // --------------------------------------------------------------------- // Setup open dialog // --------------------------------------------------------------------- let openPanel = NSOpenPanel() // FIXME: Should use the name from file import as the prompt openPanel.prompt = NSLocalizedString("Select File", comment: "") openPanel.canChooseFiles = true openPanel.canChooseDirectories = false openPanel.canCreateDirectories = false openPanel.allowsMultipleSelection = true if let allowedFileTypes = subkey.allowedFileTypes { openPanel.allowedFileTypes = allowedFileTypes } // --------------------------------------------------------------------- // Get open dialog allowed file types // --------------------------------------------------------------------- if let allowedFileTypes = self.subkey.allowedFileTypes { openPanel.allowedFileTypes = allowedFileTypes } openPanel.beginSheetModal(for: window) { response in if response == .OK { _ = self.importURLs(openPanel.urls) } } } @objc private func clicked(_ segmentedControl: NSSegmentedControl) { if segmentedControl.selectedSegment == 0 { // Add self.addRow() } else if segmentedControl.selectedSegment == 1 { // Remove if let rowIndexes = self.tableView?.selectedRowIndexes { self.removeRow(indexes: rowIndexes) } } } private func addRow() { // Verify there isn't a limit on maximum number or items in the array. if let repetitionMax = self.subkey.repetitionMax { if repetitionMax <= self.tableViewContent.count { // FIXME: This must be notified to the user Log.shared.info(message: "Only \(repetitionMax) rows are allowd in the array for subkey: \(self.subkey.keyPath)", category: String(describing: self)) return } } // Verify the values unique is set and if all values are already set if self.tableViewContentType != .dictionary, self.tableViewContentSubkey?.valueUnique ?? false { if let subkey = self.tableViewContentSubkey, let rangeList = subkey.rangeList, self.tableViewContent.contains(values: rangeList, ofType: subkey.type, sorted: true) { Log.shared.info(message: "All supported values are already in the array, cannot create another row because values must be unique", category: String(describing: self)) return } } var newRow: Any if self.tableViewContentType == .dictionary { var newRowDict = [String: Any]() for tableViewColumn in self.tableViewColumns { // Do not set a default value for keys that will copy their values if tableViewColumn.valueCopy != nil || tableViewColumn.valueDefaultCopy != nil { continue } let relativeKeyPath = tableViewColumn.valueKeyPath.deletingPrefix(self.subkey.valueKeyPath + ".") guard let newRowValue = tableViewColumn.defaultValue() ?? PayloadUtility.emptyValue(valueType: tableViewColumn.type) else { continue } newRowDict.setValue(value: newRowValue, forKeyPath: relativeKeyPath) } newRow = newRowDict } else { if let rangeList = self.tableViewContentSubkey?.rangeList, let newRowValue = rangeList.first(where: { !self.tableViewContent.containsAny(value: $0, ofType: self.tableViewContentType) }) { newRow = newRowValue } else { guard let newRowValue = self.tableViewContentSubkey?.defaultValue() ?? PayloadUtility.emptyValue(valueType: self.tableViewContentType) else { return } newRow = newRowValue } } var newIndex: Int if let index = self.tableView?.selectedRowIndexes.last, (index + 1) <= self.tableViewContent.count { self.tableViewContent.insert(newRow, at: (index + 1)) newIndex = index + 1 } else { self.tableViewContent.append(newRow) newIndex = self.tableViewContent.count - 1 } self.tableViewContentSave() self.tableViewReloadData() self.tableView?.selectRowIndexes(IndexSet(integer: newIndex), byExtendingSelection: false) } private func removeRow(indexes: IndexSet) { guard 0 <= indexes.count, let indexMax = indexes.max(), indexMax < self.tableViewContent.count else { Log.shared.error(message: "Index too large: \(String(describing: indexes.max())). self.tableViewContent.count: \(self.tableViewContent.count)", category: String(describing: self)) return } self.tableViewContent.remove(at: indexes) self.tableView?.removeRows(at: indexes, withAnimation: .slideDown) self.tableViewContentSave() let rowCount = self.tableViewContent.count if 0 < rowCount { if indexMax < rowCount { self.tableView?.selectRowIndexes(IndexSet(integer: indexMax), byExtendingSelection: false) } else { self.tableView?.selectRowIndexes(IndexSet(integer: (rowCount - 1)), byExtendingSelection: false) } } } private func tableColumn(forSubkey subkey: PayloadSubkey, profile: Profile) -> NSTableColumn { let tableColumn = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(subkey.keyPath)) tableColumn.isEditable = true tableColumn.title = profile.settings.titleString(forSubkey: subkey) tableColumn.headerToolTip = subkey.description tableColumn.isHidden = profile.settings.showHiddenKeys ? false : subkey.hidden == .all if subkey.type == .bool { tableColumn.sizeToFit() tableColumn.maxWidth = tableColumn.headerCell.cellSize.width + 1 tableColumn.minWidth = 17.0 } return tableColumn } func setValue(_ value: Any?, forSubkey subkey: PayloadSubkey, row: Int) { if self.subkey.type != .dictionary { let subkeyValueKeyPath = PayloadUtility.expandKeyPath(subkey.valueKeyPath, withRootKeyPath: self.subkey.valueKeyPath + ".\(row)") guard let newValue = value else { return } self.profile.settings.setValue(newValue, forValueKeyPath: subkeyValueKeyPath, subkey: subkey, domainIdentifier: subkey.domainIdentifier, payloadType: subkey.payloadType, payloadIndex: self.payloadIndex) self.tableViewContent = self.getTableViewContent() } else { // --------------------------------------------------------------------- // Get the current row settings // --------------------------------------------------------------------- var tableViewContent = self.tableViewContent // --------------------------------------------------------------------- // Update the current row settings // --------------------------------------------------------------------- var rowContent: Any? if let newValue = value { if self.tableViewContentType == .dictionary { guard var rowContentDict = tableViewContent[row] as? [String: Any] else { return } // Calculate relative key path and use KeyPath adding let relativeKeyPath = subkey.valueKeyPath.deletingPrefix(self.subkey.valueKeyPath + ".") rowContentDict.setValue(value: newValue, forKeyPath: relativeKeyPath) rowContent = rowContentDict } else { rowContent = newValue } } else if self.tableViewContentType == .dictionary { guard var rowContent = tableViewContent[row] as? [String: Any] else { return } rowContent.removeValue(forKey: subkey.key) } else { rowContent = PayloadUtility.emptyValue(valueType: subkey.type) } guard let newRowContent = rowContent else { return } tableViewContent[row] = newRowContent // --------------------------------------------------------------------- // Save the changes internally and to the payloadSettings // --------------------------------------------------------------------- self.tableViewContent = tableViewContent self.tableViewContentSave() } } func setupContent(forTableView tableView: NSTableView, subkey: PayloadSubkey) { // FIXME: Highly temporary implementation if let tableViewSubkey = self.tableViewContentSubkey { if self.tableViewContentSubkey?.rangeList != nil { let tableColumnReorder = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("Reorder")) tableColumnReorder.isEditable = false tableColumnReorder.title = "" tableColumnReorder.sizeToFit() tableColumnReorder.maxWidth = 4.0 tableColumnReorder.minWidth = 4.0 tableView.addTableColumn(tableColumnReorder) } switch tableViewSubkey.typeInput { case .dictionary: if subkey.subkeys.contains(where: { $0.key == ManifestKeyPlaceholder.key }) { var subkeys = [PayloadSubkey]() if let subkeyKey = subkey.subkeys.first(where: { $0.key == ManifestKeyPlaceholder.key }) { subkeys.append(subkeyKey) } if let subkeyValue = subkey.subkeys.first(where: { $0.key == ManifestKeyPlaceholder.value }) { if subkeyValue.type == .dictionary, subkeyValue.hidden == .container { subkeys.append(contentsOf: self.columnSubkeys(forSubkeys: subkeyValue.subkeys)) } else { subkeys.append(subkeyValue) } } for tableViewColumnSubkey in subkeys { if !self.profile.settings.isAvailableForSelectedPlatform(subkey: tableViewColumnSubkey) { continue } self.tableViewColumns.append(tableViewColumnSubkey) // --------------------------------------------------------------------- // Setup TableColumn // --------------------------------------------------------------------- tableView.addTableColumn(self.tableColumn(forSubkey: tableViewColumnSubkey, profile: self.profile)) } } else { for tableViewColumnSubkey in self.columnSubkeys(forSubkeys: tableViewSubkey.subkeys) { if !profile.settings.isAvailableForSelectedPlatform(subkey: tableViewColumnSubkey) { continue } self.tableViewColumns.append(tableViewColumnSubkey) // --------------------------------------------------------------------- // Setup TableColumn // --------------------------------------------------------------------- tableView.addTableColumn(self.tableColumn(forSubkey: tableViewColumnSubkey, profile: profile)) } } if tableViewSubkey.subkeys.count < 2 { self.tableView?.headerView = nil self.tableView?.toolTip = tableViewSubkey.subkeys.first?.description } case .array: // FIXME: Handle arrays in arrays for tableViewColumnSubkey in tableViewSubkey.subkeys where tableViewColumnSubkey.type == .array { for nextSubkey in tableViewColumnSubkey.subkeys { if !self.profile.settings.isAvailableForSelectedPlatform(subkey: nextSubkey) { continue } self.tableViewColumns.append(nextSubkey) // --------------------------------------------------------------------- // Setup TableColumn // --------------------------------------------------------------------- tableView.addTableColumn(self.tableColumn(forSubkey: nextSubkey, profile: self.profile)) } } case .bool, .string, .integer: if !self.profile.settings.isAvailableForSelectedPlatform(subkey: tableViewSubkey) { return } self.tableViewColumns.append(tableViewSubkey) // --------------------------------------------------------------------- // Setup TableColumn // --------------------------------------------------------------------- tableView.addTableColumn(self.tableColumn(forSubkey: tableViewSubkey, profile: self.profile)) default: Log.shared.error(message: "Unhandled PayloadValueType in TableView: \(tableViewSubkey.typeInput)", category: String(describing: self)) } } else { Log.shared.error(message: "Subkey: \(subkey.keyPath) subkey count is: \(subkey.subkeys.count). Only 1 subkey is currently supported", category: "") } self.tableView?.columnAutoresizingStyle = .uniformColumnAutoresizingStyle } private func columnSubkeys(forSubkeys subkeys: [PayloadSubkey]) -> [PayloadSubkey] { var columnSubkeys = [PayloadSubkey]() for subkey in subkeys { if subkey.typeInput == .dictionary, subkey.hidden == .container { columnSubkeys.append(contentsOf: self.columnSubkeys(forSubkeys: subkey.subkeys)) } else { columnSubkeys.append(subkey) } } return columnSubkeys } func rowValue(forColumnSubkey subkey: PayloadSubkey, row: Int) -> Any? { let rowContent = self.tableViewContent[row] var rowValue: Any? if self.tableViewContentType == .dictionary, let rowContentDict = rowContent as? [String: Any] { let relativeKeyPath = subkey.valueKeyPath.deletingPrefix(self.subkey.valueKeyPath + ".") rowValue = rowContentDict.valueForKeyPath(keyPath: relativeKeyPath) } else { rowValue = rowContent } if let valueProcessorIdentifier = subkey.valueProcessor, let value = rowValue { let valueProcessor = PayloadValueProcessors.shared.processor(withIdentifier: valueProcessorIdentifier, subkey: subkey, inputType: subkey.type, outputType: subkey.typeInput) if let valueProcessed = valueProcessor.process(value: value) { rowValue = valueProcessed } } return rowValue } func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { guard let keyPath = menuItem.identifier?.rawValue, let tableColumnSubkey = self.tableViewColumns.first(where: { $0.keyPath == keyPath }) else { // FIXME: Correct Error return false } guard let selectedValue = PayloadUtility.value(forRangeListTitle: menuItem.title, subkey: tableColumnSubkey) else { Log.shared.error(message: "Subkey: \(self.subkey.keyPath) Failed to get value for selected title: \(String(describing: menuItem.title)) ", category: String(describing: self)) return false } if menuItem.tag < self.tableViewContent.count, valueIsEqual(payloadValueType: tableColumnSubkey.type, a: selectedValue, b: self.tableViewContent[menuItem.tag]) { return true } else { return !self.tableViewContent.containsAny(value: selectedValue, ofType: tableColumnSubkey.type) } } } // MARK: - // MARK: EditorTableViewProtocol Functions extension PayloadCellViewTableView: EditorTableViewProtocol { @objc func select(_ menuItem: NSMenuItem) { guard let keyPath = menuItem.identifier?.rawValue, let tableColumnSubkey = self.tableViewColumns.first(where: { $0.keyPath == keyPath }) else { // FIXME: Correct Error return } guard let selectedValue = PayloadUtility.value(forRangeListTitle: menuItem.title, subkey: tableColumnSubkey) else { Log.shared.error(message: "Subkey: \(self.subkey.keyPath) Failed to get value for selected title: \(String(describing: menuItem.title)) ", category: String(describing: self)) return } self.setValue(selectedValue, forSubkey: tableColumnSubkey, row: menuItem.tag) } @objc func selected(_ popUpButton: NSPopUpButton) { guard let keyPath = popUpButton.identifier?.rawValue, let tableColumnSubkey = self.tableViewColumns.first(where: { $0.keyPath == keyPath }) else { // FIXME: Correct Error return } guard let selectedTitle = popUpButton.titleOfSelectedItem, let selectedValue = PayloadUtility.value(forRangeListTitle: selectedTitle, subkey: tableColumnSubkey) else { Log.shared.error(message: "Subkey: \(self.subkey.keyPath) Failed to get value for selected title: \(String(describing: popUpButton.titleOfSelectedItem)) ", category: String(describing: self)) return } self.setValue(selectedValue, forSubkey: tableColumnSubkey, row: popUpButton.tag) } } // MARK: - // MARK: NSButton Functions extension PayloadCellViewTableView { @objc func buttonClicked(_ button: NSButton) { // --------------------------------------------------------------------- // Get all required objects // --------------------------------------------------------------------- guard let keyPath = button.identifier?.rawValue, let tableColumnSubkey = self.tableViewColumns.first(where: { $0.keyPath == keyPath }) else { // FIXME: Correct Error return } self.setValue(button.state == .on ? true : false, forSubkey: tableColumnSubkey, row: button.tag) } } // MARK: - // MARK: NSTextFieldDelegate Functions extension PayloadCellViewTableView { internal func controlTextDidChange(_ notification: Notification) { self.isEditing = true if (notification.object as? NSComboBox) != nil { self.saveCurrentComboBoxEdit(notification) } else { self.saveCurrentEdit(notification) } } internal func controlTextDidEndEditing(_ notification: Notification) { if self.isEditing { self.isEditing = false if (notification.object as? NSComboBox) != nil { self.saveCurrentComboBoxEdit(notification) } else { self.saveCurrentEdit(notification) } } } private func saveCurrentEdit(_ notification: Notification) { // --------------------------------------------------------------------- // Verify we are editing and get the current value // --------------------------------------------------------------------- guard let userInfo = notification.userInfo, let fieldEditor = userInfo["NSFieldEditor"] as? NSTextView, let stringValue = fieldEditor.textStorage?.string else { return } // --------------------------------------------------------------------- // Get the keyPath assigned the TextField being edited // --------------------------------------------------------------------- guard let textField = notification.object as? NSTextField, let keyPath = textField.identifier?.rawValue else { return } // --------------------------------------------------------------------- // Get the subkey using the keyPath assigned the TextField being edited // --------------------------------------------------------------------- guard let textFieldSubkey = ProfilePayloads.shared.payloadSubkey(forKeyPath: keyPath, domainIdentifier: self.subkey.domainIdentifier, type: self.subkey.payloadType) else { Log.shared.error(message: "Found no subkey that matches TextField identifier keyPath: \(keyPath)", category: String(describing: self)) return } // --------------------------------------------------------------------- // Set TextColor (red if not matching format) // --------------------------------------------------------------------- textField.highlighSubstrings(for: textFieldSubkey) // --------------------------------------------------------------------- // Update Value // --------------------------------------------------------------------- self.setValue(stringValue, forSubkey: textFieldSubkey, row: textField.tag) } private func saveCurrentComboBoxEdit(_ notification: Notification) { guard let comboBox = notification.object as? NSComboBox, let keyPath = comboBox.identifier?.rawValue else { return } guard let comboBoxSubkey = self.subkey.subkeys.first(where: { $0.keyPath == keyPath }) ?? self.subkey.subkeys.first(where: { $0.subkeys.contains(where: { $0.keyPath == keyPath }) }) else { Log.shared.error(message: "Found no subkey that matches ComboBox identifier keyPath: \(keyPath)", category: String(describing: self)) return } if let selectedValue = comboBox.objectValue { var newValue: Any? if comboBox.objectValues.contains(value: selectedValue, ofType: self.subkey.type), let selectedTitle = selectedValue as? String, let value = PayloadUtility.value(forRangeListTitle: selectedTitle, subkey: self.subkey) { newValue = value } else { newValue = selectedValue } comboBox.highlighSubstrings(for: self.subkey) self.setValue(newValue, forSubkey: comboBoxSubkey, row: comboBox.tag) } } } // MARK: - // MARK: NSComboBoxDelegate Functions extension PayloadCellViewTableView: NSComboBoxDelegate { func comboBoxSelectionDidChange(_ notification: Notification) { guard let comboBox = notification.object as? NSComboBox, let keyPath = comboBox.identifier?.rawValue else { return } guard let comboBoxSubkey = self.subkey.subkeys.first(where: { $0.keyPath == keyPath }) ?? self.subkey.subkeys.first(where: { $0.subkeys.contains(where: { $0.keyPath == keyPath }) }) else { Log.shared.error(message: "Found no subkey that matches ComboBox identifier keyPath: \(keyPath)", category: String(describing: self)) return } if let selectedValue = comboBox.objectValueOfSelectedItem { var newValue: Any? if comboBox.objectValues.contains(value: selectedValue, ofType: self.subkey.type), let selectedTitle = selectedValue as? String, let value = PayloadUtility.value(forRangeListTitle: selectedTitle, subkey: self.subkey) { newValue = value } else { newValue = selectedValue } comboBox.highlighSubstrings(for: self.subkey) self.setValue(newValue, forSubkey: comboBoxSubkey, row: comboBox.tag) } } } // MARK: - // MARK: NSTableViewDataSource Functions extension PayloadCellViewTableView: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { self.tableViewContent.count } func allowedUTIs() -> [String]? { var allowedUTIs = [String]() guard let allowedFileTypes = self.allowedFileTypes else { return nil } for type in allowedFileTypes { if type.contains(".") { allowedUTIs.append(type) } else if let typeUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, "kext" as CFString, nil)?.takeUnretainedValue() as String? { allowedUTIs.append(typeUTI) } } return allowedUTIs } // ------------------------------------------------------------------------- // Drag/Drop Support // ------------------------------------------------------------------------- func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? { let item = NSPasteboardItem() item.setString(String(row), forType: self.dragDropType) return item } func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation { guard !self.isImporting else { return NSDragOperation() } if info.draggingPasteboard.availableType(from: [dragDropType]) != nil, dropOperation == .above { return .move } else if info.draggingPasteboard.availableType(from: [.backwardsCompatibleFileURL]) != nil { if let allowedFileTypes = self.allowedUTIs() { if info.draggingPasteboard.canReadObject(forClasses: [NSURL.self], options: [.urlReadingContentsConformToTypes: allowedFileTypes]) { tableView.setDropRow(-1, dropOperation: .on) return .copy } } else { tableView.setDropRow(-1, dropOperation: .on) return .copy } } return NSDragOperation() } func importURLs(_ urls: [URL]) -> Bool { guard let valueImportProcessor = self.valueImportProcessor else { return false } self.isImporting = true self.progressIndicator.startAnimation(self) let dispatchQueue = DispatchQueue(label: "serial") let dispatchGroup = DispatchGroup() let dispatchSemaphore = DispatchSemaphore(value: 0) dispatchQueue.async { for url in urls { dispatchGroup.enter() DispatchQueue.main.async { self.textFieldProgress.stringValue = "Processing \(url.lastPathComponent)…" } do { try valueImportProcessor.addValue(forFile: url, toCurrentValue: self.tableViewContent, subkey: self.subkey, cellView: self) { updatedValue in if let updatedTableViewContent = updatedValue as? [Any] { self.tableViewContent = updatedTableViewContent self.tableViewContentSave() DispatchQueue.main.async { self.tableView?.reloadData() } } dispatchSemaphore.signal() dispatchGroup.leave() } } catch { DispatchQueue.main.async { self.showAlert(withMessage: error.localizedDescription) dispatchSemaphore.signal() dispatchGroup.leave() } } dispatchSemaphore.wait() } } dispatchGroup.notify(queue: dispatchQueue) { DispatchQueue.main.async { self.isImporting = false self.progressIndicator.stopAnimation(self) self.textFieldProgress.stringValue = "" self.tableViewReloadData() } } return true } func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool { guard !self.isImporting else { return false } if info.draggingPasteboard.availableType(from: [dragDropType]) != nil { var oldIndexes = [Int]() info.enumerateDraggingItems(options: [], for: tableView, classes: [NSPasteboardItem.self], searchOptions: [:]) { dragItem, _, _ in // swiftlint:disable:next force_cast if let str = (dragItem.item as! NSPasteboardItem).string(forType: self.dragDropType), let index = Int(str) { oldIndexes.append(index) } } var oldIndexOffset = 0 var rowsToMoveIndex = row var rowsToMove = [Any]() for oldIndex in oldIndexes { rowsToMove.append(self.tableViewContent.remove(at: oldIndex + oldIndexOffset)) // Decrease the index for the next item by 1 each time one is removed as the indexes are in ascending order. oldIndexOffset -= 1 if oldIndex < row { rowsToMoveIndex -= 1 } } self.tableViewContent.insert(contentsOf: rowsToMove, at: rowsToMoveIndex) self.tableViewContentSave() self.tableViewReloadData() return true } else if let allowedFileTypes = self.allowedUTIs(), let urls = info.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingContentsConformToTypes: allowedFileTypes]) as? [URL] { return self.importURLs(urls) } return false } } // MARK: - // MARK: NSTableViewDelegate Functions extension PayloadCellViewTableView: NSTableViewDelegate { func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { 21.0 } func tableView(_ tableView: NSTableView, viewFor column: NSTableColumn?, row: Int) -> NSView? { guard row <= self.tableViewContent.count, let tableColumn = column, let tableColumnSubkey = self.tableViewColumns.first(where: { $0.keyPath == tableColumn.identifier.rawValue }) else { return nil } let rowValue = self.rowValue(forColumnSubkey: tableColumnSubkey, row: row) if let rangeList = tableColumnSubkey.rangeList, rangeList.count <= ProfilePayloads.rangeListConvertMax { if tableColumnSubkey.rangeListAllowCustomValue { return EditorTableViewCellViewComboBox(cellView: self, keyPath: tableColumnSubkey.keyPath, value: rowValue, subkey: tableColumnSubkey, row: row) } else { return EditorTableViewCellViewPopUpButton(cellView: self, keyPath: tableColumnSubkey.keyPath, value: rowValue, subkey: tableColumnSubkey, row: row) } } switch tableColumnSubkey.typeInput { case .array: return EditorTableViewCellViewArray(cellView: self, subkey: tableColumnSubkey, keyPath: tableColumnSubkey.keyPath, value: rowValue as? [Any] ?? [Any](), row: row) case .bool: return EditorTableViewCellViewCheckbox(cellView: self, keyPath: tableColumnSubkey.keyPath, value: rowValue as? Bool ?? false, row: row) case .integer: return EditorTableViewCellViewTextFieldNumber(cellView: self, keyPath: tableColumnSubkey.keyPath, value: rowValue as? NSNumber, placeholderValue: tableColumnSubkey.valuePlaceholder as? NSNumber, type: tableColumnSubkey.type, row: row) case .string: return EditorTableViewCellViewTextField(cellView: self, keyPath: tableColumnSubkey.keyPath, value: rowValue as? String, placeholderString: tableColumnSubkey.valuePlaceholder as? String ?? tableColumn.title, row: row) default: Log.shared.error(message: "Unknown TableColumn Subkey Type: \(tableColumnSubkey.type)", category: String(describing: self)) } return nil } func tableViewSelectionDidChange(_ notification: Notification) { if let tableView = notification.object as? NSTableView { self.buttonAddRemove.setEnabled((tableView.selectedRowIndexes.count) == 0 ? false : true, forSegment: 1) } } } // MARK: - // MARK: Setup NSLayoutConstraints extension PayloadCellViewTableView { private func setupScrollView() { guard let scrollView = self.scrollView else { return } // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Below self.addConstraints(forViewBelow: scrollView) // Leading self.addConstraints(forViewLeading: scrollView) // Trailing self.addConstraints(forViewTrailing: scrollView) } private func setupProgressIndicator() { self.progressIndicator.translatesAutoresizingMaskIntoConstraints = false self.progressIndicator.style = .spinning self.progressIndicator.controlSize = .small self.progressIndicator.isIndeterminate = true self.progressIndicator.isDisplayedWhenStopped = false // --------------------------------------------------------------------- // Add ProgressIndicator to TableCellView // --------------------------------------------------------------------- self.addSubview(self.progressIndicator) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Leading self.cellViewConstraints.append(NSLayoutConstraint(item: self.progressIndicator, attribute: .leading, relatedBy: .equal, toItem: self.buttonImport ?? self.buttonAddRemove, attribute: .trailing, multiplier: 1.0, constant: 6.0)) // Center self.cellViewConstraints.append(NSLayoutConstraint(item: self.buttonAddRemove, attribute: .centerY, relatedBy: .equal, toItem: self.progressIndicator, attribute: .centerY, multiplier: 1.0, constant: 0.0)) } private func setupImageViewDragDrop() { self.imageViewDragDrop.translatesAutoresizingMaskIntoConstraints = false self.imageViewDragDrop.image = NSImage(named: "DragDrop") self.imageViewDragDrop.imageScaling = .scaleProportionallyUpOrDown self.imageViewDragDrop.setContentHuggingPriority(.required, for: .horizontal) self.imageViewDragDrop.toolTip = NSLocalizedString("This payload key supports Drag and Drop", comment: "") self.imageViewDragDrop.isHidden = self.valueImportProcessor == nil // --------------------------------------------------------------------- // Add ImageView to TableCellView // --------------------------------------------------------------------- self.addSubview(self.imageViewDragDrop) // Height self.cellViewConstraints.append(NSLayoutConstraint(item: self.imageViewDragDrop, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 20.0)) // Width self.cellViewConstraints.append(NSLayoutConstraint(item: self.imageViewDragDrop, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 30.0)) // Center self.cellViewConstraints.append(NSLayoutConstraint(item: self.progressIndicator, attribute: .centerY, relatedBy: .equal, toItem: self.imageViewDragDrop, attribute: .centerY, multiplier: 1.0, constant: 2.0)) // Leading self.cellViewConstraints.append(NSLayoutConstraint(item: self.imageViewDragDrop, attribute: .leading, relatedBy: .greaterThanOrEqual, toItem: self.textFieldProgress, attribute: .trailing, multiplier: 1.0, constant: 6.0)) // Trailing self.cellViewConstraints.append(NSLayoutConstraint(item: self.imageViewDragDrop, attribute: .trailing, relatedBy: .equal, toItem: self.scrollView, attribute: .trailing, multiplier: 1.0, constant: 2.0)) } private func setupTextFieldProgress() { self.textFieldProgress.translatesAutoresizingMaskIntoConstraints = false self.textFieldProgress.lineBreakMode = .byWordWrapping self.textFieldProgress.isBordered = false self.textFieldProgress.isBezeled = false self.textFieldProgress.drawsBackground = false self.textFieldProgress.isEditable = false self.textFieldProgress.isSelectable = false self.textFieldProgress.textColor = .secondaryLabelColor self.textFieldProgress.font = NSFont.systemFont(ofSize: NSFont.systemFontSize(for: .regular), weight: .regular) self.textFieldProgress.preferredMaxLayoutWidth = kEditorTableViewColumnPayloadWidth self.textFieldProgress.stringValue = "" self.textFieldProgress.setContentHuggingPriority(.defaultLow, for: .horizontal) // --------------------------------------------------------------------- // Add TextField to TableCellView // --------------------------------------------------------------------- self.addSubview(self.textFieldProgress) // Leading self.cellViewConstraints.append(NSLayoutConstraint(item: self.textFieldProgress, attribute: .leading, relatedBy: .equal, toItem: self.progressIndicator, attribute: .trailing, multiplier: 1.0, constant: 6.0)) // Trailing // self.addConstraints(forViewTrailing: self.textFieldProgress) // Center self.cellViewConstraints.append(NSLayoutConstraint(item: self.textFieldProgress, attribute: .centerY, relatedBy: .equal, toItem: self.progressIndicator, attribute: .centerY, multiplier: 1.0, constant: 0.0)) } private func setupButtonAddRemove() { guard let scrollView = self.scrollView else { return } self.buttonAddRemove.translatesAutoresizingMaskIntoConstraints = false self.buttonAddRemove.segmentStyle = .roundRect self.buttonAddRemove.segmentCount = 2 self.buttonAddRemove.trackingMode = .momentary self.buttonAddRemove.setImage(NSImage(named: NSImage.addTemplateName), forSegment: 0) self.buttonAddRemove.setImage(NSImage(named: NSImage.removeTemplateName), forSegment: 1) self.buttonAddRemove.setEnabled(false, forSegment: 1) self.buttonAddRemove.action = #selector(clicked(_:)) self.buttonAddRemove.target = self // --------------------------------------------------------------------- // Add Button to TableCellView // --------------------------------------------------------------------- self.addSubview(self.buttonAddRemove) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Leading self.addConstraints(forViewLeading: self.buttonAddRemove) // Top self.cellViewConstraints.append(NSLayoutConstraint(item: self.buttonAddRemove, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .bottom, multiplier: 1.0, constant: 8.0)) self.updateHeight((8 + self.buttonAddRemove.intrinsicContentSize.height)) } private func setupButtonImport() { let buttonImport = NSSegmentedControl() buttonImport.translatesAutoresizingMaskIntoConstraints = false buttonImport.segmentStyle = .roundRect buttonImport.segmentCount = 1 buttonImport.trackingMode = .momentary buttonImport.setLabel(NSLocalizedString("Import", comment: ""), forSegment: 0) buttonImport.action = #selector(self.clickedImport(_:)) buttonImport.target = self // --------------------------------------------------------------------- // Add Button to TableCellView // --------------------------------------------------------------------- self.addSubview(buttonImport) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Center self.cellViewConstraints.append(NSLayoutConstraint(item: self.buttonAddRemove, attribute: .centerY, relatedBy: .equal, toItem: buttonImport, attribute: .centerY, multiplier: 1.0, constant: 0.0)) // Leading self.cellViewConstraints.append(NSLayoutConstraint(item: buttonImport, attribute: .leading, relatedBy: .equal, toItem: self.buttonAddRemove, attribute: .trailing, multiplier: 1.0, constant: 6.0)) self.buttonImport = buttonImport } }
ac8be5719124fcd136c3e168fae864c8
46.800175
214
0.506307
false
false
false
false
antonio081014/LeeCode-CodeBase
refs/heads/main
Swift/rank-transform-of-an-array.swift
mit
2
/** * https://leetcode.com/problems/rank-transform-of-an-array/ * * */ // Date: Mon Aug 9 16:53:13 PDT 2021 class Solution { func arrayRankTransform(_ arr: [Int]) -> [Int] { let sorted = arr.sorted() var map: [Int : Int] = [:] var rank = 1 for n in sorted { if map[n] == nil { map[n] = rank rank += 1 } } var result = [Int]() for n in arr { result.append(map[n, default: -1]) } return result } }
04712f5137212fd85cbad2c9521c81c8
21.44
60
0.433929
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/Welcome/WelcomeReducer.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import BlockchainNamespace import Combine import ComposableArchitecture import ComposableNavigation import DIKit import FeatureAuthenticationDomain import ToolKit import WalletPayloadKit // MARK: - Type public enum WelcomeAction: Equatable, NavigationAction { // MARK: - Start Up case start // MARK: - Deep link case deeplinkReceived(URL) // MARK: - Wallet case requestedToCreateWallet(String, String) case requestedToDecryptWallet(String) case requestedToRestoreWallet(WalletRecovery) // MARK: - Navigation case route(RouteIntent<WelcomeRoute>?) // MARK: - Local Action case createWallet(CreateAccountStepOneAction) case emailLogin(EmailLoginAction) case restoreWallet(SeedPhraseAction) case setManualPairingEnabled // should only be on internal build case manualPairing(CredentialsAction) // should only be on internal build case informSecondPasswordDetected case informForWalletInitialization case informWalletFetched(WalletFetchedContext) case triggerAuthenticate // needed for legacy wallet flow case triggerCancelAuthenticate // needed for legacy wallet flow // MARK: - Utils case none } // MARK: - Properties /// The `master` `State` for the Single Sign On (SSO) Flow public struct WelcomeState: Equatable, NavigationState { public var buildVersion: String public var route: RouteIntent<WelcomeRoute>? public var createWalletState: CreateAccountStepOneState? public var emailLoginState: EmailLoginState? public var restoreWalletState: SeedPhraseState? public var manualPairingEnabled: Bool public var manualCredentialsState: CredentialsState? public init() { buildVersion = "" route = nil createWalletState = nil restoreWalletState = nil emailLoginState = nil manualPairingEnabled = false manualCredentialsState = nil } } public struct WelcomeEnvironment { let app: AppProtocol let mainQueue: AnySchedulerOf<DispatchQueue> let passwordValidator: PasswordValidatorAPI let sessionTokenService: SessionTokenServiceAPI let deviceVerificationService: DeviceVerificationServiceAPI let buildVersionProvider: () -> String let featureFlagsService: FeatureFlagsServiceAPI let errorRecorder: ErrorRecording let externalAppOpener: ExternalAppOpener let analyticsRecorder: AnalyticsEventRecorderAPI let walletRecoveryService: WalletRecoveryService let walletCreationService: WalletCreationService let walletFetcherService: WalletFetcherService let accountRecoveryService: AccountRecoveryServiceAPI let recaptchaService: GoogleRecaptchaServiceAPI let checkReferralClient: CheckReferralClientAPI let nativeWalletEnabled: () -> AnyPublisher<Bool, Never> public init( app: AppProtocol, mainQueue: AnySchedulerOf<DispatchQueue>, passwordValidator: PasswordValidatorAPI = resolve(), sessionTokenService: SessionTokenServiceAPI = resolve(), deviceVerificationService: DeviceVerificationServiceAPI, featureFlagsService: FeatureFlagsServiceAPI, recaptchaService: GoogleRecaptchaServiceAPI, buildVersionProvider: @escaping () -> String, errorRecorder: ErrorRecording = resolve(), externalAppOpener: ExternalAppOpener = resolve(), analyticsRecorder: AnalyticsEventRecorderAPI = resolve(), walletRecoveryService: WalletRecoveryService = DIKit.resolve(), walletCreationService: WalletCreationService = DIKit.resolve(), walletFetcherService: WalletFetcherService = DIKit.resolve(), accountRecoveryService: AccountRecoveryServiceAPI = DIKit.resolve(), checkReferralClient: CheckReferralClientAPI = DIKit.resolve(), nativeWalletEnabled: @escaping () -> AnyPublisher<Bool, Never> ) { self.app = app self.mainQueue = mainQueue self.passwordValidator = passwordValidator self.sessionTokenService = sessionTokenService self.deviceVerificationService = deviceVerificationService self.buildVersionProvider = buildVersionProvider self.featureFlagsService = featureFlagsService self.errorRecorder = errorRecorder self.externalAppOpener = externalAppOpener self.analyticsRecorder = analyticsRecorder self.walletRecoveryService = walletRecoveryService self.walletCreationService = walletCreationService self.walletFetcherService = walletFetcherService self.accountRecoveryService = accountRecoveryService self.checkReferralClient = checkReferralClient self.nativeWalletEnabled = nativeWalletEnabled self.recaptchaService = recaptchaService } } public let welcomeReducer = Reducer.combine( createAccountStepOneReducer .optional() .pullback( state: \.createWalletState, action: /WelcomeAction.createWallet, environment: { CreateAccountStepOneEnvironment( mainQueue: $0.mainQueue, passwordValidator: $0.passwordValidator, externalAppOpener: $0.externalAppOpener, analyticsRecorder: $0.analyticsRecorder, walletRecoveryService: $0.walletRecoveryService, walletCreationService: $0.walletCreationService, walletFetcherService: $0.walletFetcherService, featureFlagsService: $0.featureFlagsService, recaptchaService: $0.recaptchaService, checkReferralClient: $0.checkReferralClient, app: $0.app ) } ), emailLoginReducer .optional() .pullback( state: \.emailLoginState, action: /WelcomeAction.emailLogin, environment: { EmailLoginEnvironment( app: $0.app, mainQueue: $0.mainQueue, sessionTokenService: $0.sessionTokenService, deviceVerificationService: $0.deviceVerificationService, featureFlagsService: $0.featureFlagsService, errorRecorder: $0.errorRecorder, externalAppOpener: $0.externalAppOpener, analyticsRecorder: $0.analyticsRecorder, walletRecoveryService: $0.walletRecoveryService, walletCreationService: $0.walletCreationService, walletFetcherService: $0.walletFetcherService, accountRecoveryService: $0.accountRecoveryService, recaptchaService: $0.recaptchaService ) } ), seedPhraseReducer .optional() .pullback( state: \.restoreWalletState, action: /WelcomeAction.restoreWallet, environment: { SeedPhraseEnvironment( mainQueue: $0.mainQueue, externalAppOpener: $0.externalAppOpener, analyticsRecorder: $0.analyticsRecorder, walletRecoveryService: $0.walletRecoveryService, walletCreationService: $0.walletCreationService, walletFetcherService: $0.walletFetcherService, accountRecoveryService: $0.accountRecoveryService, errorRecorder: $0.errorRecorder, recaptchaService: $0.recaptchaService, featureFlagsService: $0.featureFlagsService ) } ), credentialsReducer .optional() .pullback( state: \.manualCredentialsState, action: /WelcomeAction.manualPairing, environment: { CredentialsEnvironment( mainQueue: $0.mainQueue, deviceVerificationService: $0.deviceVerificationService, errorRecorder: $0.errorRecorder, featureFlagsService: $0.featureFlagsService, analyticsRecorder: $0.analyticsRecorder, walletRecoveryService: $0.walletRecoveryService, walletCreationService: $0.walletCreationService, walletFetcherService: $0.walletFetcherService, accountRecoveryService: $0.accountRecoveryService, recaptchaService: $0.recaptchaService ) } ), Reducer< WelcomeState, WelcomeAction, WelcomeEnvironment // swiftlint:disable closure_body_length > { state, action, environment in switch action { case .route(let route): guard let routeValue = route?.route else { state.createWalletState = nil state.emailLoginState = nil state.restoreWalletState = nil state.manualCredentialsState = nil state.route = route return .none } switch routeValue { case .createWallet: state.createWalletState = .init(context: .createWallet) case .emailLogin: state.emailLoginState = .init() case .restoreWallet: state.restoreWalletState = .init(context: .restoreWallet) case .manualLogin: state.manualCredentialsState = .init() } state.route = route return .none case .start: state.buildVersion = environment.buildVersionProvider() if BuildFlag.isInternal { return environment.app .publisher(for: blockchain.app.configuration.manual.login.is.enabled, as: Bool.self) .prefix(1) .replaceError(with: false) .flatMap { isEnabled -> Effect<WelcomeAction, Never> in guard isEnabled else { return .none } return Effect(value: .setManualPairingEnabled) } .eraseToEffect() } return .none case .setManualPairingEnabled: state.manualPairingEnabled = true return .none case .deeplinkReceived(let url): // handle deeplink if we've entered verify device flow guard let loginState = state.emailLoginState, loginState.verifyDeviceState != nil else { return .none } return Effect(value: .emailLogin(.verifyDevice(.didReceiveWalletInfoDeeplink(url)))) case .requestedToCreateWallet, .requestedToDecryptWallet, .requestedToRestoreWallet: // handled in core coordinator return .none case .createWallet(.triggerAuthenticate): return Effect(value: .triggerAuthenticate) case .createWallet(.informWalletFetched(let context)): return Effect(value: .informWalletFetched(context)) case .emailLogin(.verifyDevice(.credentials(.seedPhrase(.informWalletFetched(let context))))): return Effect(value: .informWalletFetched(context)) // TODO: refactor this by not relying on access lower level reducers case .emailLogin(.verifyDevice(.credentials(.walletPairing(.decryptWalletWithPassword(let password))))), .emailLogin(.verifyDevice(.upgradeAccount(.skipUpgrade(.credentials(.walletPairing(.decryptWalletWithPassword(let password))))))): return Effect(value: .requestedToDecryptWallet(password)) case .emailLogin(.verifyDevice(.credentials(.seedPhrase(.restoreWallet(let walletRecovery))))): return Effect(value: .requestedToRestoreWallet(walletRecovery)) case .restoreWallet(.restoreWallet(let walletRecovery)): return Effect(value: .requestedToRestoreWallet(walletRecovery)) case .restoreWallet(.importWallet(.createAccount(.importAccount))): return Effect(value: .requestedToRestoreWallet(.importRecovery)) case .manualPairing(.walletPairing(.decryptWalletWithPassword(let password))): return Effect(value: .requestedToDecryptWallet(password)) case .emailLogin(.verifyDevice(.credentials(.secondPasswordNotice(.returnTapped)))), .manualPairing(.secondPasswordNotice(.returnTapped)): return .dismiss() case .manualPairing(.seedPhrase(.informWalletFetched(let context))): return Effect(value: .informWalletFetched(context)) case .manualPairing(.seedPhrase(.importWallet(.createAccount(.walletFetched(.success(.right(let context))))))): return Effect(value: .informWalletFetched(context)) case .manualPairing: return .none case .restoreWallet(.triggerAuthenticate): return Effect(value: .triggerAuthenticate) case .emailLogin(.verifyDevice(.credentials(.seedPhrase(.triggerAuthenticate)))): return Effect(value: .triggerAuthenticate) case .restoreWallet(.restored(.success(.right(let context)))), .emailLogin(.verifyDevice(.credentials(.seedPhrase(.restored(.success(.right(let context))))))): return Effect(value: .informWalletFetched(context)) case .restoreWallet(.importWallet(.createAccount(.walletFetched(.success(.right(let context)))))): return Effect(value: .informWalletFetched(context)) case .restoreWallet(.restored(.success(.left(.noValue)))), .emailLogin(.verifyDevice(.credentials(.seedPhrase(.restored(.success(.left(.noValue))))))): return environment.nativeWalletEnabled() .eraseToEffect() .map { isEnabled -> WelcomeAction in guard isEnabled else { return .none } return .informForWalletInitialization } case .restoreWallet(.restored(.failure)), .emailLogin(.verifyDevice(.credentials(.seedPhrase(.restored(.failure))))): return Effect(value: .triggerCancelAuthenticate) case .createWallet(.accountCreation(.failure)): return Effect(value: .triggerCancelAuthenticate) case .informSecondPasswordDetected: switch state.route?.route { case .emailLogin: return Effect(value: .emailLogin(.verifyDevice(.credentials(.navigate(to: .secondPasswordDetected))))) case .manualLogin: return Effect(value: .manualPairing(.navigate(to: .secondPasswordDetected))) case .restoreWallet: return Effect(value: .restoreWallet(.setSecondPasswordNoticeVisible(true))) default: return .none } case .triggerAuthenticate, .triggerCancelAuthenticate, .informForWalletInitialization, .informWalletFetched: // handled in core coordinator return .none case .createWallet, .emailLogin, .restoreWallet: return .none case .none: return .none } } ) .analytics() extension Reducer where Action == WelcomeAction, State == WelcomeState, Environment == WelcomeEnvironment { func analytics() -> Self { combined( with: Reducer< WelcomeState, WelcomeAction, WelcomeEnvironment > { _, action, environment in switch action { case .route(let route): guard let routeValue = route?.route else { return .none } switch routeValue { case .emailLogin: environment.analyticsRecorder.record( event: .loginClicked() ) case .restoreWallet: environment.analyticsRecorder.record( event: .recoveryOptionSelected ) default: break } return .none default: return .none } } ) } }
b1da7257c3b4a651bf37e6c5b8c1cca2
38.738095
143
0.619233
false
false
false
false
blokadaorg/blokada
refs/heads/main
ios/App/UI/Payment/PaymentListView.swift
mpl-2.0
1
// // This file is part of Blokada. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // // Copyright © 2020 Blocka AB. All rights reserved. // // @author Karol Gusak // import SwiftUI struct PaymentListView: View { @ObservedObject var vm: PaymentGatewayViewModel let showType: String @State var showLocationSheet = false var body: some View { VStack { ForEach(self.vm.options.filter({ it in it.product.type == self.showType}), id: \.self) { option in Button(action: { withAnimation { self.vm.buy(option.product) } }) { PaymentView(vm: option) } } } .padding(.bottom, 8) } } struct PaymentListView_Previews: PreviewProvider { static var previews: some View { let working = PaymentGatewayViewModel() working.working = true let error = PaymentGatewayViewModel() error.error = "Bad error" return Group { PaymentListView(vm: PaymentGatewayViewModel(), showType: "plus") .previewLayout(.sizeThatFits) PaymentListView(vm: error, showType: "plus") .previewLayout(.sizeThatFits) PaymentListView(vm: working, showType: "cloud") .previewLayout(.sizeThatFits) } } }
39c9a9404ada6ae454156f065e04e63c
26.103448
110
0.571247
false
false
false
false
ktmswzw/jwtSwiftDemoClient
refs/heads/master
TempTests/TempTests.swift
apache-2.0
1
// // TempTests.swift // TempTests // // Created by vincent on 7/2/16. // Copyright © 2016 xecoder. All rights reserved. // import JWT import XCTest class TempTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { let jwt = JWT.encode(.HS256("secret")) { builder in builder.issuer = "fuller.li" builder.audience = "123123" builder["custom"] = "Hi" } print("\(jwt)") } func testDecode() { do { let payload = try JWT.decode("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmdWxsZXIubGkiLCJhdWQiOiIxMjMxMjMiLCJvb29vb28iOiIxMTExMTExMTExMTExIn0.K00sztVpajtv3rKBr-4uJzTnG2RHLeM0vkpI7RKBblg", algorithm: .HS256("secret")) print(payload) } catch { print("Failed to decode JWT: \(error)") } } }
32f4682e2ca19e3381c8f2412cc49696
27.829268
233
0.609983
false
true
false
false
jverdi/Gramophone
refs/heads/master
Source/Client/DecodingUtils.swift
mit
1
// // Array.swift // Gramophone // // Copyright (c) 2017 Jared Verdi. All Rights Reserved // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import protocol Decodable.Decodable import protocol Decodable.DynamicDecodable import Decodable public struct Array<T: Decodable>: Decodable { /// The resources which are part of the given array public let items: [T] internal static func parseItems(json: Any) throws -> [T] { return try (json as! [AnyObject]).flatMap { return try T.decode($0) } } public static func decode(_ json: Any) throws -> Array<T> { return try Array(items: parseItems(json: json).flatMap{ $0 }) } } extension UInt: Decodable, DynamicDecodable { public static var decoder: (Any) throws -> UInt = { try cast($0) } } extension Data: Decodable, DynamicDecodable { public static var decoder: (Any) throws -> Data = { try cast($0) } } extension URL { public static var decoder: (Any) throws -> URL = { object in let string = try String.decode(object) guard let url = URL(string: string) else { let metadata = DecodingError.Metadata(object: object) throw DecodingError.rawRepresentableInitializationError(rawValue: string, metadata) } return url } }
1f564d6cf47ab112c1bb5723f5a15d41
36.603175
95
0.700295
false
false
false
false
tevelee/CodeGenerator
refs/heads/master
output/swift/RecordLenses.swift
mit
1
import Foundation extension Record { struct Lenses { static let name: Lens<Record, String> = Lens( get: { $0.name }, set: { (record, name) in var builder = RecordBuilder(existingRecord: record) return builder.withName(name).build() } ) static let creator: Lens<Record, Person> = Lens( get: { $0.creator }, set: { (record, creator) in var builder = RecordBuilder(existingRecord: record) return builder.withCreator(creator).build() } ) static let date: Lens<Record, Date> = Lens( get: { $0.date }, set: { (record, date) in var builder = RecordBuilder(existingRecord: record) return builder.withDate(date).build() } ) } } struct BoundLensToRecord<Whole>: BoundLensType { typealias Part = Record let storage: BoundLensStorage<Whole, Part> var name: BoundLens<Whole, String> { return BoundLens<Whole, String>(parent: self, sublens: Record.Lenses.name) } var creator: BoundLensToPerson<Whole> { return BoundLensToPerson<Whole>(parent: self, sublens: Record.Lenses.creator) } var date: BoundLens<Whole, Date> { return BoundLens<Whole, Date>(parent: self, sublens: Record.Lenses.date) } } extension Record { var lens: BoundLensToRecord<Record> { return BoundLensToRecord<Record>(instance: self, lens: createIdentityLens()) } }
778628fbe3d7204c0b5e59a6e850097d
30.22
85
0.58296
false
false
false
false
dropbox/PhotoWatch
refs/heads/master
PhotoWatch/PhotoViewController.swift
mit
1
// // PhotoViewController.swift // PhotoWatch // // Created by Leah Culver on 5/14/15. // Copyright (c) 2015 Dropbox. All rights reserved. // import UIKit import ImageIO import SwiftyDropbox class PhotoViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var noPhotosLabel: UILabel! var filename: String? override func viewDidLoad() { // Display photo for page if let filename = self.filename { // Get app group shared by phone and watch let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.Dropbox.DropboxPhotoWatch") if let fileURL = containerURL?.appendingPathComponent(filename) { print("Finding file at URL: \(fileURL)") if let data = try? Data(contentsOf: fileURL) { print("Image found in cache.") // Display image self.imageView.image = UIImage(data: data) } else { print("Image not cached!") let destination : (URL, HTTPURLResponse) -> URL = { temporaryURL, response in let fileManager = FileManager.default let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] // generate a unique name for this file in case we've seen it before let UUID = Foundation.UUID().uuidString let pathComponent = "\(UUID)-\(response.suggestedFilename!)" return directoryURL.appendingPathComponent(pathComponent) } _ = DropboxClientsManager.authorizedClient!.files.getThumbnail(path: "/\(filename)", format: .png, size: .w640h480, destination: destination).response { response, error in if let (metadata, url) = response { if let data = try? Data(contentsOf: url) { if let image = UIImage(data: data) { print("Dowloaded file name: \(metadata.name)") // Resize image for watch (so it's not huge) let resizedImage = self.resizeImage(image) // Display image self.imageView.image = resizedImage // Save image to local filesystem app group - allows us to access in the watch let resizedImageData = resizedImage.jpegData(compressionQuality: 1.0) try? resizedImageData!.write(to: fileURL) } } } else { print("Error downloading file from Dropbox: \(error!)") } } } } } else { // No photos in the folder to display. print("No photos to display") self.activityIndicator.isHidden = true self.noPhotosLabel.isHidden = false } } fileprivate func resizeImage(_ image: UIImage) -> UIImage { // Resize and crop to fit Apple watch (square for now, because it's easy) let maxSize: CGFloat = 200.0 var size: CGSize? if image.size.width >= image.size.height { size = CGSize(width: (maxSize / image.size.height) * image.size.width, height: maxSize) } else { size = CGSize(width: maxSize, height: (maxSize / image.size.width) * image.size.height) } let hasAlpha = false let scale: CGFloat = 0.0 // Automatically use scale factor of main screen UIGraphicsBeginImageContextWithOptions(size!, !hasAlpha, scale) let rect = CGRect(origin: CGPoint.zero, size: size!) UIRectClip(rect) image.draw(in: rect) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage! } }
9a88af324be8e57ddd034ddcfb9e5040
40.8
191
0.50696
false
false
false
false
thedistance/TheDistanceForms
refs/heads/master
FormsDemo/EventFormViewController.swift
mit
1
// // FormsTableViewController.swift // TheDistanceForms // // Created by Josh Campion on 26/04/2016. // Copyright © 2016 The Distance. All rights reserved. // import UIKit import SwiftyJSON import TheDistanceForms import TheDistanceCore import KeyboardResponder class EventFormViewController: UIViewController, FormContainer { @IBOutlet weak var scrollContainer:UIScrollView! @IBOutlet weak var formContainer:UIView! var form:Form? var buttonTargets: [ObjectTarget<UIButton>] = [] var keyboardResponder:KeyboardResponder? override func viewDidLoad() { super.viewDidLoad() guard let jsonURL = Bundle.main.url(forResource: "EventForm", withExtension: "json"), let form = addFormFromURL(jsonURL, ofType: EventForm.self, toContainerView: formContainer, withInsets: UIEdgeInsets.zero) else { return } self.form = form keyboardResponder = setUpKeyboardResponder(onForm: form, withScrollView: scrollContainer) } func buttonTappedForQuestion(_ question: FormQuestion) { } }
ba75123700e4dbc8540dac27c6795632
26.45
133
0.708561
false
false
false
false
Quaggie/Quaggify
refs/heads/master
Quaggify/API.swift
mit
1
// // API.swift // Quaggify // // Created by Jonathan Bijos on 31/01/17. // Copyright © 2017 Quaggie. All rights reserved. // struct API { static func fetchCurrentUser (service: SpotifyService = SpotifyService.shared, completion: @escaping (User?, Error?) -> Void) { service.fetchCurrentUser(completion: completion) } static func requestToken (code: String, service: SpotifyService = SpotifyService.shared, completion: @escaping (Error?) -> Void) { service.requestToken(code: code, completion: completion) } static func fetchSearchResults (query: String, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifySearchResponse?, Error?) -> Void) { service.fetchSearchResults(query: query, completion: completion) } static func fetchAlbums (query: String, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Album>?, Error?) -> Void) { service.fetchAlbums(query: query, limit: limit, offset: offset, completion: completion) } static func fetchAlbumTracks (album: Album?, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Track>?, Error?) -> Void) { service.fetchAlbumTracks(album: album, limit: limit, offset: offset, completion: completion) } static func fetchArtist (artist: Artist?, service: SpotifyService = SpotifyService.shared, completion: @escaping (Artist?, Error?) -> Void) { service.fetchArtist(artist: artist, completion: completion) } static func fetchArtists (query: String, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Artist>?, Error?) -> Void) { service.fetchArtists(query: query, limit: limit, offset: offset, completion: completion) } static func fetchArtistAlbums (artist: Artist?, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Album>?, Error?) -> Void) { service.fetchArtistAlbums(artist: artist, limit: limit, offset: offset, completion: completion) } static func fetchTrack (track: Track?, service: SpotifyService = SpotifyService.shared, completion: @escaping (Track?, Error?) -> Void) { service.fetchTrack(track: track, completion: completion) } static func fetchTracks (query: String, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Track>?, Error?) -> Void) { service.fetchTracks(query: query, limit: limit, offset: offset, completion: completion) } static func fetchNewReleases (limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Album>?, Error?) -> Void) { service.fetchNewReleases(limit: limit, offset: offset, completion: completion) } static func fetchPlaylists (query: String, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Playlist>?, Error?) -> Void) { service.fetchPlaylists(query: query, limit: limit, offset: offset, completion: completion) } static func fetchPlaylistTracks (playlist: Playlist?, limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<PlaylistTrack>?, Error?) -> Void) { service.fetchPlaylistTracks(playlist: playlist, limit: limit, offset: offset, completion: completion) } static func removePlaylistTrack (track: Track?, position: Int?, playlist: Playlist?, service: SpotifyService = SpotifyService.shared, completion: @escaping(String?, Error?) -> Void) { service.removePlaylistTrack(track: track, position: position, playlist: playlist, completion: completion) } static func addTrackToPlaylist (track: Track?, playlist: Playlist?, service: SpotifyService = SpotifyService.shared, completion: @escaping (String?, Error?) -> Void) { service.addTrackToPlaylist(track: track, playlist: playlist, completion: completion) } static func fetchCurrentUsersPlaylists (limit: Int = 20, offset: Int = 0, service: SpotifyService = SpotifyService.shared, completion: @escaping (SpotifyObject<Playlist>?, Error?) -> Void) { service.fetchCurrentUsersPlaylists(limit: limit, offset: offset, completion: completion) } static func createNewPlaylist (name: String, service: SpotifyService = SpotifyService.shared, completion: @escaping (Playlist?, Error?) -> Void) { service.createNewPlaylist(name: name, completion: completion) } }
7df166134ce3dc12c8f29e4b7d499d63
58.628205
211
0.732316
false
false
false
false
bgayman/bikeServer
refs/heads/master
Sources/Kitura-Starter/GBFSStationInformation.swift
apache-2.0
1
// // GBFSStationInformation.swift // BikeShare // // Created by Brad G. on 2/15/17. // Copyright © 2017 B Gay. All rights reserved. // import Foundation struct GBFSStationInformation { let stationID: String let name: String let coordinates: Coordinates let shortName: String? let address: String? let crossStreet: String? let regionID: String? let postCode: String? let rentalMethods: [String]? let capacity: Int? var stationStatus: GBFSStationStatus? = nil var jsonDict: JSONDictionary { return [ "station_id": self.stationID, "name": self.name, "short_name": self.shortName ?? "", "lat": self.coordinates.latitude, "lon": self.coordinates.longitude, "address": self.address ?? "", "cross_street": self.crossStreet ?? "", "region_id": self.regionID ?? "", "post_code": self.postCode ?? "", "rental_methods": self.rentalMethods ?? [String](), "capacity": self.capacity ?? 0, "stationStatus": self.stationStatus?.jsonDict ?? JSONDictionary() ] } } extension GBFSStationInformation { init?(json: JSONDictionary) { guard let stationID = json["station_id"] as? String, let name = json["name"] as? String, let lat = json["lat"] as? Double, let lon = json["lon"] as? Double else { return nil} self.stationID = stationID self.name = name self.coordinates = Coordinates(latitude: lat, longitude: lon) self.shortName = json["short_name"] as? String self.address = json["address"] as? String self.crossStreet = json["cross_street"] as? String self.regionID = json["region_id"] as? String self.postCode = json["post_code"] as? String self.rentalMethods = json["rental_methods"] as? [String] self.capacity = json["capacity"] as? Int } }
db6a5566135252b9464bf88c9a6a93e6
30.68254
77
0.587675
false
false
false
false
mownier/photostream
refs/heads/master
Photostream/UI/User Timeline/UserTimelineView.swift
mit
1
// // UserTimelineView.swift // Photostream // // Created by Mounir Ybanez on 12/12/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import UIKit class UserTimelineView: UIView { var userPostView: UICollectionView? var header: UserTimelineHeader! override init(frame: CGRect) { super.init(frame: frame) initSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initSetup() } override func addSubview(_ view: UIView) { super.addSubview(view) if view.subviews.count > 0 && view.subviews[0] is UICollectionView { userPostView = view.subviews[0] as? UICollectionView } else if view is UserProfileView { let userProfileView = view as! UserProfileView header.addSubview(userProfileView) } } override func layoutSubviews() { guard let postView = userPostView, header.userProfileView != nil else { return } var rect = header.frame rect.size.width = frame.width rect.size.height = header.dynamicHeight header.frame = rect postView.frame = bounds postView.scrollIndicatorInsets.top = rect.maxY postView.contentInset.top = rect.maxY bringSubview(toFront: header) } func initSetup() { backgroundColor = UIColor.white header = UserTimelineHeader() addSubview(header) } } extension UserTimelineView { var spacing: CGFloat { return 4 } }
86e022c557e746bf40a1a817573afdb8
22.7
79
0.589512
false
false
false
false
macostea/SpotifyWrapper
refs/heads/master
SpotifyWrapper/SWWebView.swift
mit
1
// // SWWebView.swift // SpotifyWrapper // // Created by Mihai Costea on 13/04/15. // Copyright (c) 2015 Skobbler. All rights reserved. // import Cocoa import WebKit class SWWebView: WebView { private var warnedAboutPlugin = false override func webView(sender: WebView!, plugInFailedWithError error: NSError!, dataSource: WebDataSource!) { if (!self.warnedAboutPlugin) { self.warnedAboutPlugin = true; let pluginName = error.userInfo![WebKitErrorPlugInNameKey] as! String let pluginUrl = NSURL(string: error.userInfo![WebKitErrorPlugInPageURLStringKey] as! String) let reason = error.userInfo![NSLocalizedDescriptionKey] as! String let alert = NSAlert() alert.messageText = reason alert.addButtonWithTitle("Download plug-in update...") alert.addButtonWithTitle("OK") alert.informativeText = "\(pluginName) plug-in could not be loaded and may be out-of-date. You will need to download the latest plug-in update from within Safari, and restart Spotify Wrapper once it is installed." let response = alert.runModal() if (response == NSAlertFirstButtonReturn) { NSWorkspace.sharedWorkspace().openURL(pluginUrl!) } } } }
97ee8e292d9d9652ca65a9c77496e45d
36.944444
225
0.636896
false
false
false
false
Melon-IT/base-view-controller-swift
refs/heads/master
MelonBaseViewController/MelonBaseViewController/MBFTransition.swift
mit
1
// // MBFTransition.swift // MelonBaseViewController // // Created by Tomasz Popis on 15/06/16. // Copyright © 2016 Melon. All rights reserved. // import UIKit open class MBFTransition: UIPercentDrivenInteractiveTransition, UIViewControllerTransitioningDelegate { open var animator: MBFBaseTransitionAnimator? public override init() { super.init() } public init(animator: MBFBaseTransitionAnimator) { self.animator = animator super.init() } //MARK: - UIViewControllerTransitioningDelegate open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.animator?.presented = true return self.animator } open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.animator?.presented = false return self.animator } open func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { var result: UIViewControllerInteractiveTransitioning? if self.animator?.interaction == true { result = self } return result } open func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { var result: UIViewControllerInteractiveTransitioning? if self.animator?.interaction == true { result = self } return result } }
e588e5132508a40e4dfe0896409e70e7
26.344262
150
0.714628
false
false
false
false
peferron/algo
refs/heads/master
EPI/Sorting/Merge two sorted arrays/swift/main.swift
mit
1
public func mergeInPlace(target a: inout [Int?], source b: [Int]) { // ai is the index of the last non-nil element in a. var ai = -1 for av in a { if av == nil { break } ai += 1 } // bi is the index of the last element in b. var bi = b.count - 1 // We can stop iterating after all elements in b have been processed, since the remaining // elements in a are already sorted. while bi >= 0 { // ti is the index at which the max of a[ai] and b[bi] should be copied. let ti = ai + bi + 1 if (ai >= 0 && a[ai]! > b[bi]) { a[ti] = a[ai]! ai -= 1 } else { a[ti] = b[bi] bi -= 1 } } }
70440d3ad3e26755ee19b00b2c795ea1
25.535714
93
0.477793
false
false
false
false
toggl/superday
refs/heads/develop
teferi/Interactors/GetSingleTimeSlotForDate.swift
bsd-3-clause
1
import Foundation import RxSwift class GetSingleTimeSlotForDate: Interactor { let repositoryService: RepositoryService let appLifecycleService: AppLifecycleService let date: Date init(repositoryService: RepositoryService, appLifecycleService: AppLifecycleService, date: Date) { self.repositoryService = repositoryService self.appLifecycleService = appLifecycleService self.date = date } func execute() -> Observable<TimeSlotEntity?> { let refresh = Observable.merge([ NotificationCenter.default.rx.typedNotification(OnTimeSlotCreated.self).mapTo(()), NotificationCenter.default.rx.typedNotification(OnTimeSlotDeleted.self).mapTo(()), NotificationCenter.default.rx.typedNotification(OnTimeSlotStartTimeEdited.self).mapTo(()), NotificationCenter.default.rx.typedNotification(OnTimeSlotCategoriesEdited.self).mapTo(()), appLifecycleService.movedToForegroundObservable.mapTo(()) ]) .startWith(()) .throttle(0.3, latest: false, scheduler: MainScheduler.instance) return refresh .flatMapLatest(fetchTimeSlot) } private func fetchTimeSlot() -> Observable<TimeSlotEntity?> { return repositoryService.getTimeSlots(forDay: date) .map { [unowned self] timeSlots in return timeSlots .filter{ $0.startTime == self.date } .first } } } // Free functions (Might be moved to static functions on TimeSlot) fileprivate func belongs(to date: Date) -> (TimeSlot) -> Bool { return { timeSlot in return timeSlot.belongs(toDate: date) } } fileprivate func allBelong(to date: Date) -> ([TimeSlot]) -> Bool { return { timeSlots in return timeSlots.filter(belongs(to: date)).count == timeSlots.count } }
a269b8ad8fdd89cc998d7b90b7e1a538
31.583333
107
0.645013
false
false
false
false
SafeCar/iOS
refs/heads/master
Pods/CameraEngine/CameraEngine/CameraEngineDeviceInput.swift
mit
1
// // CameraEngineDeviceInput.swift // CameraEngine2 // // Created by Remi Robert on 01/02/16. // Copyright © 2016 Remi Robert. All rights reserved. // import UIKit import AVFoundation public enum CameraEngineDeviceInputErrorType: ErrorType { case UnableToAddCamera case UnableToAddMic } class CameraEngineDeviceInput { private var cameraDeviceInput: AVCaptureDeviceInput? private var micDeviceInput: AVCaptureDeviceInput? func configureInputCamera(session: AVCaptureSession, device: AVCaptureDevice) throws { let possibleCameraInput: AnyObject? = try AVCaptureDeviceInput(device: device) if let cameraInput = possibleCameraInput as? AVCaptureDeviceInput { if let currentDeviceInput = self.cameraDeviceInput { session.removeInput(currentDeviceInput) } self.cameraDeviceInput = cameraInput if session.canAddInput(self.cameraDeviceInput) { session.addInput(self.cameraDeviceInput) } else { throw CameraEngineDeviceInputErrorType.UnableToAddCamera } } } func configureInputMic(session: AVCaptureSession, device: AVCaptureDevice) throws { if self.micDeviceInput != nil { return } try self.micDeviceInput = AVCaptureDeviceInput(device: device) if session.canAddInput(self.micDeviceInput) { session.addInput(self.micDeviceInput) } else { throw CameraEngineDeviceInputErrorType.UnableToAddMic } } }
7dd0dbbd18c4bbde1371ce5e957a6189
30.8
90
0.67275
false
false
false
false
snowpunch/AppLove
refs/heads/develop
App Love/UI/ViewControllers/HelpVC.swift
mit
1
// // HelpVC.swift // App Love // // Created by Woodie Dovich on 2016-03-28. // Copyright © 2016 Snowpunch. All rights reserved. // // Help info (includes number of territories selected). // import UIKit import SpriteKit import SwiftyGlyphs class HelpVC: ElasticModalViewController { @IBOutlet weak var textView: UITextView! @IBOutlet weak var skview: SKView! var glyphSprites:SpriteGlyphs? = nil override func viewDidLoad() { super.viewDidLoad() populateHelpText() } func populateHelpText() { let territoriesSelected = TerritoryMgr.sharedInst.getSelectedCountryCodes().count let allTerritories = TerritoryMgr.sharedInst.getTerritoryCount() let helpText = "TIPS:\n\nCurrently there are \(territoriesSelected) territories selected out of a possible \(allTerritories).\n\nWhen selecting territories manually, the ALL button toggles between ALL and CLEAR.\n\nAfter viewing a translation, return back to this app by tapping the top left corner.\n" textView.backgroundColor = .clearColor() textView.text = helpText textView.userInteractionEnabled = false textView.selectable = false } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) showAnimatedText() } func fixCutOffTextAfterRotation() { textView.scrollEnabled = false textView.scrollEnabled = true } override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { fixCutOffTextAfterRotation() } func showAnimatedText() { if glyphSprites == nil { glyphSprites = SpriteGlyphs(fontName: "HelveticaNeue-Light", size:24) } if let glyphs = glyphSprites { glyphs.text = "At Your Service!" glyphs.setLocation(skview, pos: CGPoint(x:0,y:20)) glyphs.centerTextToView() HelpAnimation().startAnimation(glyphs, viewWidth:skview.frame.width) } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { dismissViewControllerAnimated(true, completion: nil) } }
3e830041bdcf9a6d0366affba68d27a8
32.014706
310
0.681514
false
false
false
false
linchaosheng/CSSwiftWB
refs/heads/master
SwiftCSWB 3/SwiftCSWB/Class/Home/C/WBQRcodeViewController.swift
apache-2.0
1
// // WBQRcodeViewController.swift // SwiftCSWB // // Created by LCS on 16/4/24. // Copyright © 2016年 Apple. All rights reserved. // import UIKit import AVFoundation class WBQRcodeViewController: UIViewController { @IBOutlet weak var mainView: UIView! @IBOutlet weak var scanLineView: UIImageView! @IBOutlet weak var containerView: UIView! @IBOutlet weak var containerViewHeight: NSLayoutConstraint! @IBOutlet weak var tabBar: UITabBar! @IBOutlet weak var topConstraint: NSLayoutConstraint! @IBOutlet weak var resultLabel: UILabel! // 会话对象 lazy var session : AVCaptureSession = AVCaptureSession() // 输入对象 lazy var input : AVCaptureInput? = { let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do{ let inputDevice = try AVCaptureDeviceInput(device: device) return inputDevice }catch{ print(error) return nil } }() // 输出对象 lazy var output : AVCaptureMetadataOutput = AVCaptureMetadataOutput() // 预览图层 lazy var previewLayer : AVCaptureVideoPreviewLayer = { let preview = AVCaptureVideoPreviewLayer(session: self.session) preview?.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) return preview! }() // 用于添加二维码定位边线的图层 fileprivate lazy var drawLayer : CALayer = { let layer = CALayer() layer.frame = UIScreen.main.bounds return layer }() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.done, target: self, action: #selector(WBQRcodeViewController.closeVC)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: UIBarButtonItemStyle.done, target: self, action: #selector(WBQRcodeViewController.save)) self.navigationController?.navigationBar.barTintColor = UIColor.black tabBar.selectedItem = tabBar.items![0] tabBar.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // 1. 开始扫描动画 startAnimation() // 2. 开始扫描二维码 startScan() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } func closeVC(){ dismiss(animated: true, completion: nil) } func save(){ } func startAnimation(){ topConstraint.constant = -containerViewHeight.constant self.scanLineView.layoutIfNeeded() // 执行动画 UIView.animate(withDuration: 2.0, animations: { () -> Void in UIView.setAnimationRepeatCount(MAXFLOAT) self.topConstraint.constant = self.containerViewHeight.constant // 如果动画是通过约束实现的则需要加上layoutIfNeeded self.scanLineView.layoutIfNeeded() }) } func startScan(){ // 2.1 判断是否能够将输入添加到会话中 if (!session.canAddInput(input)){ return } // 2.2 判断是否能够将输出添加到会话中 if (!session.canAddOutput(output)){ return } // 2.3 将输入输出添加到会话 session.addInput(input) session.addOutput(output) // 2.4 设置输出能够解析的数据类型(iOS系统所支持的所有类型) 可支持类型在AVMetadataObject.h output.metadataObjectTypes = output.availableMetadataObjectTypes // 2.5 设置可扫描区域(需要自己研究一下,默认0,0,1,1) output.rectOfInterest = CGRect(x: 0, y: 0, width: 1, height: 1) // 2.6 设置输出对象的代理, 只要解析成功就会通知代理 output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) // 2.7 设置预览图层 mainView.layer.insertSublayer(previewLayer, at: 0) // 2.8 告诉session开始扫描 session.startRunning() } @IBAction func QRcodeCardOnClick(_ sender: AnyObject) { let QRcodeCardVC = WBQRCodeCardViewController() navigationController?.pushViewController(QRcodeCardVC, animated: true) } } extension WBQRcodeViewController : UITabBarDelegate{ func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { if item.tag == 1{ containerViewHeight.constant = 300 }else{ containerViewHeight.constant = 150 } // 停止动画 self.scanLineView.layer.removeAllAnimations() // 重新开始动画 startAnimation() } } extension WBQRcodeViewController : AVCaptureMetadataOutputObjectsDelegate{ func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!){ // 0.清空drawLayer上的shapeLayer clearCorners() // 1.获取扫描到的数据 resultLabel.text = (metadataObjects.last as AnyObject).stringValue // 2.获取二维码位置 // 2.1 转换坐标 for object in metadataObjects{ // 2.1.1 判断数据是否是机器可识别类型 if object is AVMetadataMachineReadableCodeObject{ // 2.1.2 将坐标转换成界面可识别坐标 let codeObject = previewLayer.transformedMetadataObject(for: object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject // 2.1.3绘制图形 drawCorners(codeObject) } } } // (根据corner中的4个点绘制图形)绘制图形 func drawCorners(_ codeObject : AVMetadataMachineReadableCodeObject){ if codeObject.corners.isEmpty{ return } // 1. 创建绘图图层 let shapeLayer = CAShapeLayer() shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = UIColor.red.cgColor // 2. 创建路径 let path = UIBezierPath() var point = CGPoint.zero var index : Int = 0 // 从corners数组中取出第一个点,将字典中的X/Y赋值给point index = index + 1; point = CGPoint.init(dictionaryRepresentation: (codeObject.corners[index] as! CFDictionary))! path.move(to: point) // 移动到其它点 while index < codeObject.corners.count{ index = index + 1; point = CGPoint.init(dictionaryRepresentation: (codeObject.corners[index] as! CFDictionary))! path.addLine(to: point) } // 关闭路径 path.close() // 绘制路径 shapeLayer.path = path.cgPath // 3. 将图层添加到drawLayer图层 drawLayer.addSublayer(shapeLayer) } func clearCorners(){ if drawLayer.sublayers == nil || drawLayer.sublayers?.count == 0{ return } for subLayer in drawLayer.sublayers!{ subLayer.removeFromSuperlayer() } } }
d021c58d1f150be4bd6c2de5cc3d5ac2
30.198157
170
0.614476
false
false
false
false
einsteinx2/iSub
refs/heads/master
Classes/Server Loading/Loaders/New Model/StatusLoader.swift
gpl-3.0
1
// // StatusLoader.swift // Pods // // Created by Benjamin Baron on 2/12/16. // // import Foundation final class StatusLoader: ApiLoader { fileprivate(set) var server: Server? fileprivate(set) var url: String fileprivate(set) var username: String fileprivate(set) var password: String fileprivate(set) var basicAuth: Bool fileprivate(set) var versionString: String? fileprivate(set) var majorVersion: Int? fileprivate(set) var minorVersion: Int? convenience init(server: Server) { let password = server.password ?? "" self.init(url: server.url, username: server.username, password: password, basicAuth: server.basicAuth) self.server = server } init(url: String, username: String, password: String, basicAuth: Bool = false, serverId: Int64? = nil) { self.url = url self.username = username self.password = password self.basicAuth = basicAuth if let serverId = serverId { super.init(serverId: serverId) } else { super.init() } } override func createRequest() -> URLRequest? { return URLRequest(subsonicAction: .ping, baseUrl: url, username: username, password: password, basicAuth: basicAuth) } override func processResponse(root: RXMLElement) -> Bool { if root.tag == "subsonic-response" { self.versionString = root.attribute("version") if let versionString = self.versionString { let splitVersion = versionString.components(separatedBy: ".") let count = splitVersion.count if count > 0 { self.majorVersion = Int(splitVersion[0]) if count > 1 { self.minorVersion = Int(splitVersion[1]) } } } return true } else { // This is not a Subsonic server, so fail DispatchQueue.main.async { self.failed(error: NSError(iSubCode: .notSubsonicServer)) } return false } } override func failed(error: Error?) { if let error = error { if error.code == 40 { // Incorrect credentials, so fail super.failed(error: NSError(iSubCode: .invalidCredentials)) return } else if error.code == 60 { // Subsonic trial ended super.failed(error: NSError(iSubCode: .subsonicTrialExpired)) return } } super.failed(error: error) } }
f15cf752717303397d475b1c2e166815
30.821429
124
0.561167
false
false
false
false
vector-im/vector-ios
refs/heads/master
Riot/Modules/Common/Recents/Views/RootTabEmptyView.swift
apache-2.0
1
// // Copyright 2020 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import Reusable /// `RootTabEmptyView` is a view to display when there is no UI item to display on a screen. @objcMembers final class RootTabEmptyView: UIView, NibLoadable { // MARK: - Properties // MARK: Outlets @IBOutlet private weak var imageView: UIImageView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var informationLabel: UILabel! @IBOutlet private(set) weak var contentView: UIView! // MARK: Private private var theme: Theme! // MARK: Public // MARK: - Setup class func instantiate() -> RootTabEmptyView { let view = RootTabEmptyView.loadFromNib() view.theme = ThemeService.shared().theme return view } // MARK: - Life cycle override func awakeFromNib() { super.awakeFromNib() self.informationLabel.text = VectorL10n.homeEmptyViewInformation } // MARK: - Public func fill(with image: UIImage, title: String, informationText: String) { self.imageView.image = image self.titleLabel.text = title self.informationLabel.text = informationText } } // MARK: - Themable extension RootTabEmptyView: Themable { func update(theme: Theme) { self.theme = theme self.backgroundColor = theme.backgroundColor self.titleLabel.textColor = theme.textPrimaryColor self.informationLabel.textColor = theme.textSecondaryColor } }
2e42c9cbb10cda8d4c987d804e0ea9c3
27.333333
92
0.671059
false
false
false
false
mackoj/GOTiPad
refs/heads/master
GOTIpad/GameLogic/Game.swift
mit
1
// // Game.swift // GOTIpad // // Created by jeffreymacko on 29/12/2015. // Copyright © 2015 jeffreymacko. All rights reserved. // import Foundation class Game { var turn : UInt var wildingTrack : UInt let players : [Player] var startTime : Date let lands : [Land] let westerosCardDeck1 : EventCardDeck let westerosCardDeck2 : EventCardDeck let westerosCardDeck3 : EventCardDeck let wildingsCardDeck : WildingsCardDeck // utiliser un pointeur ? var ironThroneTrack : [Player] var valerianSwordTrack : [Player] var kingsCourtTrack : [Player] let bank : Bank var gamePhase : GamePhase = .globaleGameStateInit func setGamePhase(actualGamePhase : GamePhase) { gamePhase = actualGamePhase self.executeNextGamePhase(gamePhase: actualGamePhase) } // var delegate : GameProtocol init(players inputPlayer : [Player]) { players = inputPlayer ironThroneTrack = inputPlayer valerianSwordTrack = inputPlayer kingsCourtTrack = inputPlayer bank = Bank() turn = 0 startTime = Current.date() // filling decks westerosCardDeck1 = EventCardDeck(deckType: .deck1) westerosCardDeck2 = EventCardDeck(deckType: .deck2) westerosCardDeck3 = EventCardDeck(deckType: .deck3) wildingsCardDeck = WildingsCardDeck(cards: []) // Fill Lands self.lands = LandFactory.fillLands(seed: Current.seed) // Position on wildings Track wildingTrack = 0; // Suffle Decks setGamePhase(actualGamePhase: .globaleGameStateInit) } func pause() {} func stop() {} func restart() { turn = 0 setGamePhase(actualGamePhase: .globaleGameStateInit) } func processNextTurn() {} // + (instancetype)sharedGOTGame; // + (void)killInstance; // + (instancetype)getInstance; func executeNextGamePhase(gamePhase : GamePhase) { switch gamePhase { case .globaleGameStateInit: // Allows Player to Select Familys // Set Defaut Pawns // Set Defaut power token // Position on influence Track // Position on supply Track // Position on victory Track // Set Game Limit & misc Parameters setGamePhase(actualGamePhase: .globaleGameStateStartFirstTurn) case .globaleGameStateStartFirstTurn: break case .gamePhaseStartWesteros: break case .gameStateForWesterosGamePhaseAdvanceGameRoundMarker: if self.turn == Current.endGameTurn { setGamePhase(actualGamePhase: .gamePhaseWinningResolution) // fin du jeu } else { self.turn += 1 setGamePhase(actualGamePhase: .gameStateForWesterosGamePhaseDrawEventCards) } case .gameStateForWesterosGamePhaseDrawEventCards: break case .gameStateForWesterosGamePhaseAdvanceWildlingsTrack: break case .gameStateForWesterosGamePhaseWildlingsAttack: break case .gameStateForWesterosGamePhaseResolveEventCards: break case .gamePhaseEndWesteros: break case .gamePhaseStartPlanning: // Dis a l'UI que la phase X commande si elle veut jouer une animation ou quoi setGamePhase(actualGamePhase: .gameStateForPlanningGamePhaseAssignOrders) case .gameStateForPlanningGamePhaseAssignOrders: // demander aux joueurs de positionner leur pions d'action // player in order + completion ? for player in self.ironThroneTrack { self.assignOrders(player: player) // future ??? } // une fois que tout les joueurs on jouer if self.allOrdersHasBeenPlayed() { setGamePhase(actualGamePhase: .gameStateForPlanningGamePhaseRevealOrders) } case .gameStateForPlanningGamePhaseRevealOrders: // player in order + completion ? for player in self.ironThroneTrack { for orderToken in player.house.orderTokens { if orderToken.isOnBoard { orderToken.isFold } } } self.revealOrders() // future ??? setGamePhase(actualGamePhase: .gameStateForPlanningGamePhaseUseMessengerRaven) case .gameStateForPlanningGamePhaseUseMessengerRaven: self.useMessageRaven(player: self.kingsCourtTrack.first!) // useNonEmptyArray let ravenAction = RavenMessengerAction.changeOrder switch ravenAction { case .nothing: break case .changeOrder: break case .lookIntoWildingsDeck: break } setGamePhase(actualGamePhase: .gamePhaseEndPlanning) case .gamePhaseEndPlanning: self.endPlanningPhase() setGamePhase(actualGamePhase: .gamePhaseStartAction) case .gamePhaseStartAction: break case .gameStateForActionGamePhaseResolveRaidOrders: break case .gameStateForActionGamePhaseResolveMarchOrders: break case .gamePhaseStartCombat: break case .gamePhaseCombatCallForSupport: break case .gamePhaseCombatCalculateInitialCombatStrength: break case .gamePhaseCombatChooseandRevealHouseCards: break case .gamePhaseCombatUseValyrianSteelBlade: break case .gamePhaseCombatCalculateFinalCombatStrength: break case .gamePhaseCombatResolution: break case .gamePhaseCombatResolutionDetermineVictor: break case .gamePhaseCombatResolutionCasualties: break case .gamePhaseCombatResolutionRetreatsandRouting: break case .gamePhaseCombatResolutionCombatCleanUp: break case .gamePhaseEndCombat: break case .gameStateForActionGamePhaseResolveConsolidatePowerOrders: break case .gameStateForActionGameCleanUp: break case .gamePhaseEndAction: break case .gamePhaseWinningResolution: break case .globaleGameStateFinish: break } } }
d6ec528d654d566d054648cdc5408b23
27.173267
84
0.710596
false
false
false
false
miradesne/gamepoll
refs/heads/master
gamepoll/GPGamerProfileViewController.swift
mit
1
// // GPGameProfileViewController.swift // // // Created by Mira Chen on 1/12/16. // // import UIKit import Charts class GPGamerProfileViewController: UIViewController { var traits: [String]! @IBOutlet weak var parentScrollView: UIScrollView! @IBOutlet weak var radarChartView: RadarChartView! @IBAction func dismissSelf(sender: UIButton) { self.dismissViewControllerAnimated(true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() //round up scoll view corners parentScrollView.layer.cornerRadius = 10 parentScrollView.layer.masksToBounds = true radarChartView.noDataText = "no data" //offscreen radarChartView.setDescriptionTextPosition(x: 1000, y: 1000) traits = ["Graphics", "Story", "Sound", "Learning Curve", "Novelty"] let scores = [3.9, 4.0, 1.0, 3.5, 5.0] setData(traits, scores: scores) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setData(traits: [String], scores: [Double]) { var yAxisScores: [ChartDataEntry] = [ChartDataEntry]() var xAxisTraits: [String] = [String]() for var i = 0; i < scores.count; i++ { yAxisScores.append(ChartDataEntry(value: scores[i], xIndex: i)) } for var i = 0; i < traits.count; i++ { xAxisTraits.append(traits[i]) } let dataset: RadarChartDataSet = RadarChartDataSet(yVals: yAxisScores, label: "Traits") dataset.drawFilledEnabled = true dataset.lineWidth = 2.0 dataset.colors = [UIColor.flatGreenSeaColor()] dataset.setDrawHighlightIndicators(false) dataset.drawValuesEnabled = false // Configure Radar Chart radarChartView.yAxis.customAxisMax = 5.0 radarChartView.yAxis.customAxisMin = 0 radarChartView.yAxis.startAtZeroEnabled = false radarChartView.yAxis.drawLabelsEnabled = false radarChartView.userInteractionEnabled = false let data: RadarChartData = RadarChartData(xVals: xAxisTraits, dataSets: [dataset]) radarChartView.data = data let bgColor = UIColor(red: 239.0/255.0, green: 239.0/255.0, blue: 244.0/255.0, alpha: 1) radarChartView.backgroundColor = bgColor } /* // 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. } */ }
43ec6383424aefb0abf8eb7809fb28a3
32.352941
106
0.643739
false
false
false
false
Zverik/omim
refs/heads/master
iphone/Maps/UI/Search/Filters/FilterCollectionHolderCell.swift
apache-2.0
1
@objc(MWMFilterCollectionHolderCell) final class FilterCollectionHolderCell: MWMTableViewCell { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet private weak var collectionViewHeight: NSLayoutConstraint! private weak var tableView: UITableView? override var frame: CGRect { didSet { guard #available(iOS 10, *) else { if (frame.size.height < 1 /* minimal correct height */) { frame.size.height = collectionViewHeight.constant tableView?.refresh() } return } } } private func layout() { collectionView.setNeedsLayout() collectionView.layoutIfNeeded() collectionViewHeight.constant = collectionView.contentSize.height } func config(tableView: UITableView?) { layout() collectionView.allowsMultipleSelection = true; isSeparatorHidden = true backgroundColor = UIColor.pressBackground() guard #available(iOS 10, *) else { self.tableView = tableView return } } override func layoutSubviews() { super.layoutSubviews() layout() } }
d68c8ae66be7a23d0ca5c6272caaaf24
25.463415
70
0.688479
false
false
false
false
bastienFalcou/FindMyContacts
refs/heads/master
Missed Contacts Widget/TodayViewModel.swift
mit
1
// // TodayViewModel.swift // FindMyContacts // // Created by Bastien Falcou on 7/15/17. // Copyright © 2017 Bastien Falcou. All rights reserved. // import Foundation import ReactiveSwift import DataSource final class TodayViewModel: NSObject { var syncedPhoneContacts = MutableProperty<Set<PhoneContact>>([]) var dataSource = MutableProperty<DataSource>(EmptyDataSource()) func updateDataSource() { let existingContacts = self.syncedPhoneContacts.value.filter { !$0.hasBeenSeen } var sections: [DataSourceSection<ContactTableViewCellModel>] = existingContacts .splitBetween { return floor($0.0.dateAdded.timeIntervalSince1970 / (60 * 60 * 24)) != floor($0.1.dateAdded.timeIntervalSince1970 / (60 * 60 * 24)) }.map { contacts in return DataSourceSection(items: contacts.map { ContactTableViewCellModel(contact: $0) }) } let newContacts = self.syncedPhoneContacts.value.filter { $0.hasBeenSeen } if !newContacts.isEmpty { sections.append(DataSourceSection(items: newContacts.map { ContactTableViewCellModel(contact: $0) })) } self.dataSource.value = StaticDataSource(sections: sections) } }
60d7bddf42e3ca93ab7ee67dd18a0e4b
34.40625
135
0.750221
false
false
false
false
RemyDCF/tpg-offline
refs/heads/master
tpg offline/Departures/Cells/AddToSiriTableViewCell.swift
mit
1
// // AddToSiriTableViewCell.swift // tpg offline // // Created by Rémy on 30/08/2018. // Copyright © 2018 Remy. All rights reserved. // import UIKit import IntentsUI @available(iOS 12.0, *) class AddToSiriTableViewCell: UITableViewCell, INUIAddVoiceShortcutViewControllerDelegate { // swiftlint:disable:next line_length func addVoiceShortcutViewController(_ controller: INUIAddVoiceShortcutViewController, didFinishWith voiceShortcut: INVoiceShortcut?, error: Error?) { controller.dismiss(animated: true, completion: nil) } func addVoiceShortcutViewControllerDidCancel(_ controller: INUIAddVoiceShortcutViewController) { // swiftlint:disable:previous line_length controller.dismiss(animated: true, completion: nil) } @IBOutlet weak var stackView: UIStackView! override func awakeFromNib() { super.awakeFromNib() } var shortcut: INShortcut? var parent: UIViewController? = nil { didSet { for x in stackView.subviews { x.removeFromSuperview() } let textLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) textLabel.textColor = App.textColor textLabel.text = "Do you want to see the departures of this stop at a glance?".localized textLabel.numberOfLines = 0 textLabel.textAlignment = .center self.stackView.addArrangedSubview(textLabel) self.backgroundColor = App.cellBackgroundColor let selectedBackgroundView = UIView() selectedBackgroundView.backgroundColor = App.cellBackgroundColor self.selectedBackgroundView = selectedBackgroundView if INPreferences.siriAuthorizationStatus() != .authorized { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) button.setTitle("Enable Siri in the settings".localized, for: .normal) self.stackView.addArrangedSubview(button) } else { let button = INUIAddVoiceShortcutButton(style: App.darkMode ? .blackOutline : .whiteOutline) button.translatesAutoresizingMaskIntoConstraints = false button.widthAnchor.constraint(equalToConstant: 150).isActive = true button.heightAnchor.constraint(equalToConstant: 50).isActive = true button.addTarget(self, action: #selector(addToSiri), for: .touchUpInside) stackView.addArrangedSubview(button) } } } @objc func addToSiri() { if let shortcut = self.shortcut, let parent = self.parent { let viewController = INUIAddVoiceShortcutViewController(shortcut: shortcut) viewController.modalPresentationStyle = .formSheet viewController.delegate = self parent.present(viewController, animated: true, completion: nil) } } }
82219f3a92fccfbdd59f5efffd31c93e
36.972973
98
0.693238
false
false
false
false
wenghengcong/Coderpursue
refs/heads/master
BeeFun/BeeFun/View/Event/EventCell/BFEventBaseCell.swift
mit
1
// // BFEventBaseCell.swift // BeeFun // // Created by WengHengcong on 23/09/2017. // Copyright © 2017 JungleSong. All rights reserved. // import UIKit class BFEventBaseCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // for view in self.subviews where view.isKind(of: UIScrollView.self) { // let scroll = view as? UIScrollView // scroll?.canCancelContentTouches = true // scroll?.delaysContentTouches = false // break // } selectionStyle = .none backgroundView?.backgroundColor = .clear contentView.backgroundColor = .clear backgroundColor = .clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
2204840fb31965bd817d3c87965d0acd
27.709677
78
0.646067
false
false
false
false
mlilback/rc2SwiftClient
refs/heads/master
Networking/Rc2FileManager.swift
isc
1
// // Rc2FileManager.swift // // Copyright ©2016 Mark Lilback. This file is licensed under the ISC license. // import Rc2Common import Foundation import MJLLogger import ReactiveSwift let FileAttrVersion = "io.rc2.FileAttr.Version" let FileAttrChecksum = "io.rc2.FileAttr.SHA256" public enum FileError: Error, Rc2DomainError { case failedToSave case failedToDownload } ///Protocol for functions of NSFileManager that we use so we can inject a mock version in unit tests public protocol Rc2FileManager { func Url(for directory: Foundation.FileManager.SearchPathDirectory, domain: Foundation.FileManager.SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: Bool) throws -> URL func moveItem(at: URL, to: URL) throws func copyItem(at: URL, to: URL) throws func removeItem(at: URL) throws // func createDirectory(at url: URL, withIntermediateDirectories createIntermediates: Bool, attributes: [String : Any]?) throws func createDirectoryHierarchy(at url: URL) throws /// synchronously move the file setting xattrs func move(tempFile: URL, to toUrl: URL, file: AppFile?) throws } open class Rc2DefaultFileManager: Rc2FileManager { let fm: FileManager public init(fileManager: FileManager = FileManager.default) { fm = fileManager } public func moveItem(at: URL, to: URL) throws { do { try fm.moveItem(at: at, to: to) } catch { throw Rc2Error(type: .file, nested: error) } } public func copyItem(at: URL, to: URL) throws { do { try fm.copyItem(at: at, to: to) } catch { throw Rc2Error(type: .file, nested: error, severity: .error, explanation: "failed to copy \(to.lastPathComponent)") } } public func removeItem(at: URL) throws { do { try fm.removeItem(at: at) } catch { throw Rc2Error(type: .file, nested: error) } } public func createDirectoryHierarchy(at url: URL) throws { do { try fm.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) } catch { throw Rc2Error(type: .file, nested: error) } } public func Url(for directory: FileManager.SearchPathDirectory, domain: FileManager.SearchPathDomainMask, appropriateFor url: URL? = nil, create shouldCreate: Bool = false) throws -> URL { do { return try fm.url(for: directory, in: domain, appropriateFor: url, create: shouldCreate) } catch { throw Rc2Error(type: .file, nested: error) } } ///copies url to a new location in a temporary directory that can be passed to the user or another application /// (i.e. it is not in our sandbox/app support/cache directories) public func copyURLToTemporaryLocation(_ url: URL) throws -> URL { //all errors are already wrapped since we only call internal methods let tmpDir = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("Rc2", isDirectory: true) _ = try createDirectoryHierarchy(at: tmpDir) let destUrl = URL(fileURLWithPath: url.lastPathComponent, relativeTo: tmpDir) _ = try? removeItem(at: destUrl) try copyItem(at: url, to: destUrl) return destUrl } ///Synchronously moves the tmpFile downloaded via NSURLSession (or elsewhere) to toUrl, setting the appropriate /// metadata including xattributes for validating cached File objects public func move(tempFile: URL, to toUrl: URL, file: AppFile?) throws { do { if let _ = try? toUrl.checkResourceIsReachable() { try self.removeItem(at: toUrl) } try self.moveItem(at: tempFile, to: toUrl) //if a File, set mod/creation date, ignoring any errors if let fileRef = file { var fileUrl = toUrl var resourceValues = URLResourceValues() resourceValues.creationDate = fileRef.dateCreated resourceValues.contentModificationDate = fileRef.lastModified try fileUrl.setResourceValues(resourceValues) let attrs: [FileAttributeKey: Any] = [.posixPermissions: fileRef.fileType.isExecutable ? 0o775 : 0o664] try fm.setAttributes(attrs, ofItemAtPath: fileUrl.path) fileRef.writeXAttributes(fileUrl) } } catch { Log.warn("got error downloading file \(tempFile.lastPathComponent): \(error.localizedDescription)", .network) throw Rc2Error(type: .cocoa, nested: error, explanation: tempFile.lastPathComponent) } } } public extension AppFile { /// checks to see if the file at url has the same version information as this file func versionXAttributesMatch(url: URL) -> Bool { if let versionData = dataForXAttributeNamed(FileAttrVersion, atURL: url).data, let readString = String(data: versionData, encoding: .utf8), let readVersion = Int(readString) { return readVersion == version } return false } /// checks to see if file at url is the file we represent func urlXAttributesMatch(_ url: URL) -> Bool { if let versionData = dataForXAttributeNamed(FileAttrVersion, atURL: url).data, let readString = String(data: versionData, encoding: .utf8), let readVersion = Int(readString), let shaData = dataForXAttributeNamed(FileAttrChecksum, atURL: url).data, let readShaData = dataForXAttributeNamed(FileAttrChecksum, atURL: url).data { return readVersion == version && shaData == readShaData } return false } /// writes data to xattributes to later validate if a url points to a file reprsented this object func writeXAttributes(_ toUrl: URL) { let versionData = String(version).data(using: String.Encoding.utf8) setXAttributeWithName(FileAttrVersion, data: versionData!, atURL: toUrl) if let fileData = try? Data(contentsOf: toUrl) { let shaData = fileData.sha256() setXAttributeWithName(FileAttrChecksum, data: shaData, atURL: toUrl) } else { Log.error("failed to create sha256 checksum for \(toUrl.path)", .network) } } }
02186eade4b5f909a79116ab5ff2a2e7
35.541935
188
0.735876
false
false
false
false
alex-d-fox/iDoubtIt
refs/heads/master
iDoubtIt/Code/PlayScene.swift
gpl-3.0
1
// // GameScene.swift // iDoubtIt // // Created by Alexander Fox on 8/30/16. // Copyright © 2016 // import Foundation import SpriteKit enum CardLevel :CGFloat { case board = 20 case moving = 40 case enlarged = 60 } class PlayScene: SKScene { override init() { super.init(size: screenSize.size) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMove(to view: SKView) { let deck = Deck(wacky: isWacky) let bg = SKSpriteNode(imageNamed: background) bg.anchorPoint = CGPoint.zero bg.position = CGPoint.zero bg.size = CGSize(width: screenWidth, height: screenHeight) addChild(bg) let infoButton = button(image: "outerCircle", name:"Info", color: .white, label: "i") infoButton.colorBlendFactor = 0.75 infoButton.position = CGPoint(x: screenWidth - 50, y: screenHeight - 50) addChild(infoButton) let human = Player(human: true, playerName: "Human", level: Difficulty.easy) let ai1 = Player(human: false, playerName: "AI 1", level: Difficulty.easy) let ai2 = Player(human: false, playerName: "AI 2", level: Difficulty.easy) let ai3 = Player(human: false, playerName: "AI 3", level: Difficulty.easy) let players = [human,ai1,ai2,ai3] // let aiplayers = [ai1,ai2,ai3] deck.naturalShuffle() deck.randShuffle() deck.naturalShuffle() var p = 0 for card in deck.gameDeck { players[p%4].addCard(card: card) card.position = CGPoint(x: p * 10, y: 0) p += 1 } for player in players { print(player.name!) for c in 0...12 { print(player.playerHand[c].getIcon()) } player.color = .red player.colorBlendFactor = 1 addChild(player) } let texture = SKTexture(imageNamed: "invisible") let discardPile = SKSpriteNode(texture: texture, color: .yellow, size: CGSize.init(width: 140, height: 190)) discardPile.blendMode = .subtract discardPile.colorBlendFactor = 1 discardPile.position = CGPoint(x: screenWidth/2, y: screenHeight/2) addChild(discardPile) players[0].position = CGPoint(x: screenWidth/4, y: screenHeight/2 - players[0].size.height) players[1].position = CGPoint(x: screenWidth/4, y: screenHeight/2) players[2].position = CGPoint(x: screenWidth/4, y: screenHeight/2) players[3].position = CGPoint(x: screenWidth/4, y: screenHeight/2) players[0].zRotation = CGFloat(0 * Double.pi/2 / 360) players[1].zRotation = CGFloat(90 * Double.pi/2 / 360) players[2].zRotation = CGFloat(180 * Double.pi/2 / 360) players[3].zRotation = CGFloat(270 * Double.pi/2 / 360) for p in 0..<players.count { for card in players[p].playHand(currValue: .Ace) { let moveCard = SKAction.move(to: discardPile.position, duration: 1) card.run(moveCard) card.move(toParent: discardPile) } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self) if let card = atPoint(location) as? Card { card.zPosition = CardLevel.moving.rawValue if touch.tapCount == 2 { card.flipOver() return } let rotR = SKAction.rotate(byAngle: 0.15, duration: 0.2) let rotL = SKAction.rotate(byAngle: -0.15, duration: 0.2) let cycle = SKAction.sequence([rotR, rotL, rotL, rotR]) let wiggle = SKAction.repeatForever(cycle) card.run(wiggle, withKey: "wiggle") card.removeAction(forKey: "drop") card.run(SKAction.scale(to: 1.3, duration: 0.25), withKey: "pickup") print(card.getIcon()) print(card.cardName) } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self) if let card = atPoint(location) as? Card { card.position = location } } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self) let node = atPoint(location) if let card = node as? Card { card.zPosition = CardLevel.board.rawValue card.removeAction(forKey: "wiggle") card.run(SKAction.rotate(toAngle: 0, duration: 0.2), withKey:"rotate") card.removeAction(forKey: "pickup") card.run(SKAction.scale(to: 1.0, duration: 0.25), withKey: "drop") // let parent = card.parent card.removeFromParent() addChild(card) } if (node.name == "Infobtn" || node.name == "Infolabel") { let scene = MainMenu() view?.showsFPS = true view?.showsNodeCount = true view?.ignoresSiblingOrder = false scene.scaleMode = .aspectFill view?.presentScene(scene) } } } }
9e6142fc8ddb2d62141fca4c832d68c8
31.576923
112
0.612554
false
false
false
false
moonrailgun/OpenCode
refs/heads/master
OpenCode/Classes/RepositoryDetail/View/RepoInfoView.swift
gpl-2.0
1
// // RepositoryInfoBlock.swift // OpenCode // // Created by 陈亮 on 16-5-8. // Copyright (c) 2016年 moonrailgun. All rights reserved. // import UIKit class RepoInfoView: UIView { var infoNameLabel:UILabel! var infoValueLabel:UILabel! init(frame: CGRect, name:String,value:Int) { super.init(frame: frame) self.backgroundColor = UIColor.whiteColor() infoValueLabel = UILabel(frame: CGRect(x: 0, y: 2, width: frame.width, height: 20)) infoValueLabel.text = value.description infoValueLabel.font = UIFont.systemFontOfSize(18) infoValueLabel.textAlignment = .Center infoNameLabel = UILabel(frame: CGRect(x: 0, y: 20, width: frame.width, height: 18)) infoNameLabel.text = name infoNameLabel.font = UIFont.systemFontOfSize(14) infoNameLabel.textAlignment = .Center self.addSubview(infoNameLabel) self.addSubview(infoValueLabel) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setName(name:String){ self.infoNameLabel.text = name } func setValue(value:Int!){ self.infoValueLabel.text = String(value) } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
c5ae044c8166005787d1531a19d38d6c
26.622642
91
0.641393
false
false
false
false
lanjing99/RxSwiftDemo
refs/heads/master
09-combining-operators/challenge/Challenge1-Finished/RxSwift.playground/Contents.swift
mit
1
//: Please build the scheme 'RxSwiftPlayground' first import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true import RxSwift example(of: "Challenge 1 - solution using zip") { let source = Observable.of(1, 3, 5, 7, 9) let scanObservable = source.scan(0, accumulator: +) let observable = Observable.zip(source, scanObservable) { value, runningTotal in (value, runningTotal) } observable.subscribe(onNext: { tuple in print("Value = \(tuple.0) Running total = \(tuple.1)") }) } example(of: "Challenge 1 - solution using just scan and a tuple") { let source = Observable.of(1, 3, 5, 7, 9) let observable = source.scan((0,0)) { acc, current in return (current, acc.1 + current) } observable.subscribe(onNext: { tuple in print("Value = \(tuple.0) Running total = \(tuple.1)") }) } /*: Copyright (c) 2014-2016 Razeware LLC 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. */
313d2a6601905eaffc673e46cc8534a3
35.074074
82
0.735113
false
false
false
false
FredrikSjoberg/KFDataStructures
refs/heads/master
KFDataStructures/Swift/BinarySearchTree.swift
mit
1
// // BinarySearchTree.swift // KFDataStructures // // Created by Fredrik Sjöberg on 14/11/16. // Copyright © 2016 Fredrik Sjoberg. All rights reserved. // import Foundation //: Playground - noun: a place where people can play import UIKit public class BinarySearchTree<T: Comparable> { fileprivate var root: BinarySearchNode<T>? public init(value: T) { self.root = BinarySearchNode(value: value) } } extension BinarySearchTree: Sequence { public func makeIterator() -> BinarySearchTreeInOrderIterator<T> { return BinarySearchTreeInOrderIterator(tree: self) } } /// Performance: O(h) extra memory required to store the stack, where h == height of tree public struct BinarySearchTreeInOrderIterator<T: Comparable>: IteratorProtocol { private var current: BinarySearchNode<T>? private var stack: ContiguousArray<BinarySearchNode<T>> init(tree: BinarySearchTree<T>) { current = tree.root stack = ContiguousArray() } mutating public func next() -> T? { while current != nil { stack.append(current!) current = current?.left } guard !stack.isEmpty else { return nil } current = stack.removeLast() let result = current?.value current = current?.right return result } } /*public enum BinarySearchTreeTraversalOrder { //In-order (or depth-first): first look at the left child of a node, then at the node itself, and finally at its right child. case inOrder //Pre-order: first look at a node, then its left and right children. case preOrder //Post-order: first look at the left and right children and process the node itself last. case postOrder }*/ /// Find Items extension BinarySearchTree { /// Finds the "highest" node with specified value /// Performance: O(h) where h is height of tree public func contains(value: T) -> Bool { guard let r = root else { return false } let t = r.node(for: value) return t != nil } /// Finds the minimum value /// Performance: O(h) public func min() -> T? { return root?.min().value } /// Finds the maximum value /// Performance: O(h) public func max() -> T? { return root?.max().value } /*public func traverse(order: BinarySearchTreeTraversalOrder, callback: (T) -> Void) { root?.traverse(order: order, callback: callback) }*/ } /// Inserting items extension BinarySearchTree { public func insert(value: T) { guard let root = root else { self.root = BinarySearchNode(value: value) return } root.insert(value: value) } } /// Removing items extension BinarySearchTree { public func remove(value: T) { guard let root = root else { return } guard let present = root.node(for: value) else { return } guard let replacement = present.remove() else { return } if present === root { self.root = replacement } } } /// Node fileprivate class BinarySearchNode<T: Comparable> { fileprivate(set) public var value: T fileprivate(set) var parent: BinarySearchNode? fileprivate(set) var left: BinarySearchNode? fileprivate(set) var right: BinarySearchNode? public init(value: T) { self.value = value } } /// Find items extension BinarySearchNode { fileprivate func min() -> BinarySearchNode { return left?.min() ?? self } fileprivate func max() -> BinarySearchNode { return right?.max() ?? self } fileprivate func node(for value: T) -> BinarySearchNode? { if value < self.value { return left?.node(for: value) } else if value > self.value { return right?.node(for: value) } else { return self } } fileprivate var isLeftChild: Bool { return parent?.left === self } fileprivate var isRightChild: Bool { return parent?.right === self } /*fileprivate func traverse(order: BinarySearchTreeTraversalOrder, callback: (T) -> Void) { switch order { case .inOrder: traverse(inOrder: callback) case .preOrder: traverse(preOrder: callback) case .postOrder: traverse(postOrder: callback) } } fileprivate func traverse(inOrder callback: (T) -> Void) { left?.traverse(inOrder: callback) callback(value) right?.traverse(inOrder: callback) } fileprivate func traverse(preOrder callback: (T) -> Void) { callback(value) left?.traverse(preOrder: callback) right?.traverse(preOrder: callback) } fileprivate func traverse(postOrder callback: (T) -> Void) { left?.traverse(postOrder: callback) right?.traverse(postOrder: callback) callback(value) }*/ } /// Inserting items extension BinarySearchNode { fileprivate func insert(value: T) { if value < self.value { if let left = left { left.insert(value: value) } else { left = BinarySearchNode(value: value) left?.parent = self } } else { if let right = right { right.insert(value: value) } else { right = BinarySearchNode(value: value) right?.parent = self } } } } /// Deleting items extension BinarySearchNode { /// Returns the node that replaces the removed one (or nil if removed was leaf node) fileprivate func remove() -> BinarySearchNode? { let replacement = findReplacement() if let parent = parent { if isLeftChild { parent.left = replacement } else { parent.right = replacement } } replacement?.parent = parent parent = nil left = nil right = nil return replacement } fileprivate func findReplacement() -> BinarySearchNode? { if let left = left { if let right = right { // This node has two children. It must be replaced by the smallest // child that is larger than this node's value, which is the leftmost // descendent of the right child. let successor = right.min() // If this in-order successor has a right child of its own (it cannot // have a left child by definition), then that must take its place. let _ = successor.remove() // Connect our left child with the new node. successor.left = left //left.parent = successor // Connect our right child with the new node. If the right child does // not have any left children of its own, then the in-order successor // *is* the right child. if right !== successor { successor.right = right //right.parent = successor } else { successor.right = nil } // And finally, connect the successor node to our parent. return successor } else { return left } } else { return right } } }
be3fedf642714af1ff08ab8f67ffcba2
27.372694
129
0.562622
false
false
false
false
ocadaruma/museswift
refs/heads/master
MuseSwift/Source/Render/SingleLineScore/SingleLineScore.swift
mit
1
import Foundation @IBDesignable public class SingleLineScore: UIView { public var layout: SingleLineScoreLayout = SingleLineScoreLayout.defaultLayout { didSet { setNeedsDisplay() } } private var staffTop: CGFloat { return (bounds.size.height - layout.staffHeight) / 2 } private var staffInterval: CGFloat { return layout.staffHeight / CGFloat(staffNum - 1) } /// score elemeents will be added to this view. private var _canvas: UIView! = nil public var canvas: UIView { return _canvas } public func loadVoice(tuneHeader: TuneHeader, voiceHeader: VoiceHeader, voice: Voice, initialOffset: CGFloat = 0) -> Void { if let c = _canvas { c.removeFromSuperview() } _canvas = UIView(frame: bounds) addSubview(canvas) let renderer = SingleLineScoreRenderer( unitDenominator: tuneHeader.unitNoteLength.denominator, layout: layout, bounds: bounds) var noteUnitMap = [CGFloat:NoteUnit]() var tieLocations = [CGFloat]() var elementsInBeam: [(xOffset: CGFloat, element: BeamMember)] = [] var xOffset: CGFloat = initialOffset var beamContinue = false // render clef let clef = renderer.createClef(xOffset, clef: voiceHeader.clef) canvas.addSubview(clef) xOffset += clef.frame.width // render key signature let keySignature = renderer.createKeySignature(xOffset, key: tuneHeader.key) for k in keySignature { canvas.addSubview(k) } xOffset = keySignature.map({$0.frame.maxX}).maxElement()! // render meter let meter = renderer.createMeter(xOffset, meter: tuneHeader.meter) canvas.addSubview(meter) xOffset += meter.frame.width // render voice for element in voice.elements { beamContinue = false switch element { case let simple as Simple: switch simple { case .BarLine: canvas.addSubview( RectElement(frame: CGRect( x: xOffset - layout.barMarginRight, y: staffTop, width: layout.stemWidth, height: layout.staffHeight))) case .DoubleBarLine: canvas.addSubview( DoubleBarElement(frame: CGRect( x: xOffset - layout.barMarginRight, y: staffTop, width: layout.stemWidth * 3, height: layout.staffHeight))) case .Space: break case .LineBreak: break case .RepeatEnd: break //TODO case .RepeatStart: break //TODO case .Tie: tieLocations.append(xOffset) case .SlurEnd: break //TODO case .SlurStart: break //TODO case .End: break } case let note as Note: switch calcDenominator(note.length.absoluteLength(renderer.unitDenominator)) { case .Whole, .Half, .Quarter: let unit = renderer.createNoteUnit(xOffset, note: note) unit.renderToView(canvas) noteUnitMap[unit.xOffset] = unit default: elementsInBeam.append((xOffset: xOffset, element: note)) beamContinue = true } xOffset += renderer.rendereredWidthForNoteLength(note.length) case let chord as Chord: switch calcDenominator(chord.length.absoluteLength(renderer.unitDenominator)) { case .Whole, .Half, .Quarter: let unit = renderer.createNoteUnit(xOffset, chord: chord) unit.renderToView(canvas) noteUnitMap[unit.xOffset] = unit default: elementsInBeam.append((xOffset: xOffset, element: chord)) beamContinue = true } xOffset += renderer.rendereredWidthForNoteLength(chord.length) case let tuplet as Tuplet: let tupletUnit = renderer.createTupletUnit(tuplet, xOffset: xOffset) tupletUnit.renderToView(canvas) for unit in tupletUnit.toNoteUnits() { noteUnitMap[unit.xOffset] = unit } xOffset += tuplet.elements.map({renderer.rendereredWidthForNoteLength($0.length) * CGFloat(tuplet.ratio)}).sum() case let rest as Rest: renderer.createRestUnit(xOffset, rest: rest).renderToView(canvas) xOffset += renderer.rendereredWidthForNoteLength(rest.length) case let rest as MultiMeasureRest: xOffset += renderer.rendereredWidthForNoteLength(NoteLength(numerator: rest.num, denominator: 1)) default: break } if !beamContinue && elementsInBeam.nonEmpty { for beam in renderer.createBeamUnit(elementsInBeam) { beam.renderToView(canvas) for unit in beam.toNoteUnits() { noteUnitMap[unit.xOffset] = unit } } elementsInBeam = [] } } if elementsInBeam.nonEmpty { for beam in renderer.createBeamUnit(elementsInBeam) { beam.renderToView(canvas) for unit in beam.toNoteUnits() { noteUnitMap[unit.xOffset] = unit } } } let noteUnitLocations = noteUnitMap.keys.sort() for x in tieLocations { if let i = noteUnitLocations.indexOf(x) { let start = noteUnitLocations.get(i - 1).flatMap({noteUnitMap[$0]}) let end = noteUnitMap[x] renderer.createTie(start, end: end).foreach({self.canvas.addSubview($0)}) } } } private func drawStaff() { let width = bounds.size.width let top = staffTop let ctx = UIGraphicsGetCurrentContext() CGContextSetLineWidth(ctx, layout.staffLineWidth) CGContextSetStrokeColorWithColor(ctx, UIColor.lightGrayColor().CGColor) for i in 0..<staffNum { let offset = staffInterval * CGFloat(i) CGContextMoveToPoint(ctx, 0, top + offset) CGContextAddLineToPoint(ctx, width, top + offset) CGContextStrokePath(ctx) } } public override func drawRect(rect: CGRect) { drawStaff() } }
65eeed232db69a6e0c5786b6633152d3
31.655367
125
0.647924
false
false
false
false
leolanzinger/readory
refs/heads/master
Readory_test/ViewController.swift
mit
1
// // ViewController.swift // Created by Kyle Weiner on 10/17/14. // import UIKit class ViewController: UIViewController { @IBOutlet weak var playersLabel: UILabel! @IBOutlet weak var lionPic: UIImageView! @IBOutlet weak var parrotPic: UIImageView! @IBOutlet weak var wolfPic: UIImageView! @IBOutlet weak var foxPic: UIImageView! @IBOutlet weak var lamaPic: UIImageView! var selectedPlayers:Int! var players:Int! = -1 override func viewDidLoad() { super.viewDidLoad() // set the number of players label only if // number of players is set if (players > 0) { playersLabel.text = "YOU ARE PLAYING WITH " + String(players) + " PLAYER" if (players > 1) { playersLabel.text = playersLabel.text! + "S" // show lion picture lionPic.hidden = false if (players > 2) { // show parrot pic parrotPic.hidden = false if (players > 3) { // show wolf pic wolfPic.hidden = false if (players > 4) { // show fox pic foxPic.hidden = false } } } } } } @IBAction func onePlayer(sender: AnyObject) { self.selectedPlayers = 1 performSegueWithIdentifier("confirmGame", sender: self) } @IBAction func twoPlayers(sender: AnyObject) { self.selectedPlayers = 2 performSegueWithIdentifier("confirmGame", sender: self) } @IBAction func threePlayers(sender: AnyObject) { self.selectedPlayers = 3 performSegueWithIdentifier("confirmGame", sender: self) } @IBAction func fourPlayers(sender: AnyObject) { self.selectedPlayers = 4 performSegueWithIdentifier("confirmGame", sender: self) } @IBAction func fivePlayers(sender: AnyObject) { self.selectedPlayers = 5 performSegueWithIdentifier("confirmGame", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "startGame") { Game.init() Game.swiftSharedInstance.setPlayers(self.players) } else if (segue.identifier == "confirmGame") { let secondViewController = segue.destinationViewController as! ViewController let plyrs = self.selectedPlayers as Int secondViewController.players = plyrs } } @IBAction func prepareForUnwind(segue: UIStoryboardSegue) { } }
f6b6c269886dd793b52985001f49d974
30.11236
89
0.561777
false
false
false
false
shadanan/mado
refs/heads/master
Mado/ExprEvaluate.swift
mit
1
// // MadoExprEvaluate.swift // Mado // // Created by Shad Sharma on 2/5/17. // Copyright © 2017 Shad Sharma. All rights reserved. // import Antlr4 import Foundation class Expr: MadoBaseVisitor<Double> { let W: Double let H: Double let x: Double let y: Double let w: Double let h: Double var msg: String? var error: ANTLRError? = nil init(W: Double, H: Double, x: Double, y: Double, w: Double, h: Double) { self.W = W self.H = H self.x = x self.y = y self.w = w self.h = h } class MadoErrorListener: ANTLRErrorListener { let expr: Expr init(expr: Expr) { self.expr = expr } func syntaxError<T : ATNSimulator>(_ recognizer: Recognizer<T>, _ offendingSymbol: AnyObject?, _ line: Int, _ charPositionInLine: Int, _ msg: String, _ e: AnyObject?) { expr.error = ANTLRError.illegalArgument(msg: msg) } func reportAmbiguity(_ recognizer: Parser, _ dfa: DFA, _ startIndex: Int, _ stopIndex: Int, _ exact: Bool, _ ambigAlts: BitSet, _ configs: ATNConfigSet) throws { } func reportContextSensitivity(_ recognizer: Parser, _ dfa: DFA, _ startIndex: Int, _ stopIndex: Int, _ prediction: Int, _ configs: ATNConfigSet) throws { } func reportAttemptingFullContext(_ recognizer: Parser, _ dfa: DFA, _ startIndex: Int, _ stopIndex: Int, _ conflictingAlts: BitSet?, _ configs: ATNConfigSet) throws { } } override func visitNumber(_ ctx: MadoParser.NumberContext) -> Double { return Double(ctx.getText())! } override func visitAtomNumberExpr(_ ctx: MadoParser.AtomNumberExprContext) -> Double { return visitChildren(ctx)! } override func visitVariable(_ ctx: MadoParser.VariableContext) -> Double { switch ctx.getText() { case "W": return W case "H": return H case "x": return x case "y": return y case "w": return w case "h": return h default: error = ANTLRError.illegalState(msg: "Invalid Variable: \(ctx.getText())") return 0 } } override func visitAtomVariableExpr(_ ctx: MadoParser.AtomVariableExprContext) -> Double { return visitChildren(ctx)! } override func visitOperatorExpr(_ ctx: MadoParser.OperatorExprContext) -> Double { if let lop = visit(ctx.lop), let rop = visit(ctx.rop), let op = ctx.op.getText() { switch op { case "*": return lop * rop case "/": return lop / rop case "+": return lop + rop case "-": return lop - rop default: error = ANTLRError.illegalState(msg: "Invalid Operator: \(op)") } } return 0 } override func visitMultiplyExpr(_ ctx: MadoParser.MultiplyExprContext) -> Double { return visit(ctx.number()!)! * visit(ctx.variable()!)! } override func visitParenExpr(_ ctx: MadoParser.ParenExprContext) -> Double { return visit(ctx.expr()!)! } static func evaluate(exprStr: String, W: Double, H: Double, x: Double, y: Double, w: Double, h: Double) -> Double? { do { let lexer = MadoLexer(ANTLRInputStream(exprStr)) let parser = try MadoParser(CommonTokenStream(lexer)) parser.setErrorHandler(BailErrorStrategy()) let visitor = Expr(W: W, H: H, x: x, y: y, w: w, h: h) lexer.addErrorListener(MadoErrorListener(expr: visitor)) let expr = try parser.expr() if visitor.error != nil { return nil } if let result = visitor.visit(expr) { return result } } catch {} return nil } }
6822b4eb3ca50077f5f5293087f54b0d
31.04065
176
0.559503
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/ConversationList/Container/ViewModel/ConversationListViewControllerViewModel.swift
gpl-3.0
1
// Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UserNotifications import WireDataModel import WireSyncEngine import WireCommonComponents typealias Completion = () -> Void typealias ResultHandler = (_ succeeded: Bool) -> Void protocol ConversationListContainerViewModelDelegate: AnyObject { init(viewModel: ConversationListViewController.ViewModel) func scrollViewDidScroll(scrollView: UIScrollView!) func setState(_ state: ConversationListState, animated: Bool, completion: Completion?) func showNoContactLabel(animated: Bool) func hideNoContactLabel(animated: Bool) func openChangeHandleViewController(with handle: String) func showNewsletterSubscriptionDialogIfNeeded(completionHandler: @escaping ResultHandler) func updateArchiveButtonVisibilityIfNeeded(showArchived: Bool) func removeUsernameTakeover() func showUsernameTakeover(suggestedHandle: String, name: String) func showPermissionDeniedViewController() @discardableResult func selectOnListContentController(_ conversation: ZMConversation!, scrollTo message: ZMConversationMessage?, focusOnView focus: Bool, animated: Bool, completion: (() -> Void)?) -> Bool var hasUsernameTakeoverViewController: Bool { get } } extension ConversationListViewController: ConversationListContainerViewModelDelegate {} extension ConversationListViewController { final class ViewModel: NSObject { weak var viewController: ConversationListContainerViewModelDelegate? { didSet { guard viewController != nil else { return } updateNoConversationVisibility(animated: false) updateArchiveButtonVisibility() showPushPermissionDeniedDialogIfNeeded() } } let account: Account let selfUser: SelfUserType let conversationListType: ConversationListHelperType.Type var selectedConversation: ZMConversation? var userProfileObserverToken: Any? fileprivate var initialSyncObserverToken: Any? fileprivate var userObserverToken: Any? /// observer tokens which are assigned when viewDidLoad var allConversationsObserverToken: Any? var connectionRequestsObserverToken: Any? var actionsController: ConversationActionController? init(account: Account, selfUser: SelfUserType, conversationListType: ConversationListHelperType.Type = ZMConversationList.self) { self.account = account self.selfUser = selfUser self.conversationListType = conversationListType } } } extension ConversationListViewController.ViewModel { func setupObservers() { if let userSession = ZMUserSession.shared() { userObserverToken = UserChangeInfo.add(observer: self, for: userSession.selfUser, in: userSession) as Any initialSyncObserverToken = ZMUserSession.addInitialSyncCompletionObserver(self, userSession: userSession) } updateObserverTokensForActiveTeam() } func savePendingLastRead() { ZMUserSession.shared()?.enqueue({ self.selectedConversation?.savePendingLastRead() }) } /// Select a conversation and move the focus to the conversation view. /// /// - Parameters: /// - conversation: the conversation to select /// - message: scroll to this message /// - focus: focus on the view or not /// - animated: perform animation or not /// - completion: the completion block func select(conversation: ZMConversation, scrollTo message: ZMConversationMessage? = nil, focusOnView focus: Bool = false, animated: Bool = false, completion: Completion? = nil) { selectedConversation = conversation viewController?.setState(.conversationList, animated: animated) { [weak self] in self?.viewController?.selectOnListContentController(self?.selectedConversation, scrollTo: message, focusOnView: focus, animated: animated, completion: completion) } } fileprivate var userProfile: UserProfile? { return ZMUserSession.shared()?.userProfile } func requestSuggestedHandlesIfNeeded() { guard let session = ZMUserSession.shared(), let userProfile = userProfile else { return } if nil == session.selfUser.handle, session.hasCompletedInitialSync == true, session.isPendingHotFixChanges == false { userProfileObserverToken = userProfile.add(observer: self) userProfile.suggestHandles() } } func setSuggested(handle: String) { userProfile?.requestSettingHandle(handle: handle) } private var isComingFromRegistration: Bool { return ZClientViewController.shared?.isComingFromRegistration ?? false } /// show PushPermissionDeniedDialog when necessary /// /// - Returns: true if PushPermissionDeniedDialog is shown @discardableResult func showPushPermissionDeniedDialogIfNeeded() -> Bool { // We only want to present the notification takeover when the user already has a handle // and is not coming from the registration flow (where we alreday ask for permissions). guard selfUser.handle != nil else { return false } guard !isComingFromRegistration else { return false } guard !AutomationHelper.sharedHelper.skipFirstLoginAlerts else { return false } guard false == viewController?.hasUsernameTakeoverViewController else { return false } guard Settings.shared.pushAlertHappenedMoreThan1DayBefore else { return false } UNUserNotificationCenter.current().checkPushesDisabled({ [weak self] pushesDisabled in DispatchQueue.main.async { if pushesDisabled, let weakSelf = self { Settings.shared[.lastPushAlertDate] = Date() weakSelf.viewController?.showPermissionDeniedViewController() } } }) return true } } extension ConversationListViewController.ViewModel: ZMInitialSyncCompletionObserver { func initialSyncCompleted() { requestSuggestedHandlesIfNeeded() } } extension Settings { var pushAlertHappenedMoreThan1DayBefore: Bool { guard let date: Date = self[.lastPushAlertDate] else { return true } return date.timeIntervalSinceNow < -86400 } }
1b4368293fb0d22978a4671884533175
35.27
189
0.693548
false
false
false
false
prebid/prebid-mobile-ios
refs/heads/master
InternalTestApp/PrebidMobileDemoRenderingUITests/UITests/XCTestCaseExt.swift
apache-2.0
1
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Foundation import XCTest protocol Failable: ObjcFailable { func failWithMessage(_ message: String, file: String, line: UInt, nothrow: Bool) } extension Failable { func failWithMessage(_ message: String, file: String, line: UInt) { failWithMessage(message, file: file, line: line, nothrow: false) } } extension XCTestCase { // MARK: - Helper methods (wait) func waitForEnabled(element: XCUIElement, failElement: XCUIElement? = nil, waitSeconds: TimeInterval = 5, file: StaticString = #file, line: UInt = #line) { let enabledPredicate = NSPredicate(format: "enabled == true") var error: String = "Failed to find enabled element \(element) after \(waitSeconds) seconds" if let failElement = failElement { error += " or element \(failElement) became enabled earlier." } else { error += "." } waitFor(element: element, predicate: enabledPredicate, failElement: failElement, failPredicate: enabledPredicate, message: error, waitSeconds: waitSeconds, file: file, line: line) } func waitForHittable(element: XCUIElement, waitSeconds: TimeInterval = 5, file: StaticString = #file, line: UInt = #line) { let existsPredicate = NSPredicate(format: "hittable == true") let error = "Failed to find \(element) after \(waitSeconds) seconds." waitFor(element: element, predicate: existsPredicate, message: error, waitSeconds: waitSeconds, file: file, line: line) } func waitForNotHittable(element: XCUIElement, waitSeconds: TimeInterval = 5, file: StaticString = #file, line: UInt = #line) { let hittablePredicate = NSPredicate(format: "hittable == false") let error = "Failed to find \(element) after \(waitSeconds) seconds." waitFor(element: element, predicate: hittablePredicate, message: error, waitSeconds: waitSeconds, file: file, line: line) } func waitForExists(element: XCUIElement, waitSeconds: TimeInterval = 5, file: StaticString = #file, line: UInt = #line) { let existsPredicate = NSPredicate(format: "exists == true") let error = "Failed to find \(element) after \(waitSeconds) seconds." waitFor(element: element, predicate: existsPredicate, message: error, waitSeconds: waitSeconds, file: file, line: line) } func waitForNotExist(element: XCUIElement, waitSeconds: TimeInterval = 5, file: StaticString = #file, line: UInt = #line) { let predicate = NSPredicate(format: "exists != true") let error = "Element \(element) failed to be hidden after \(waitSeconds) seconds." waitFor(element: element, predicate: predicate, message: error, waitSeconds: waitSeconds, file: file, line: line) } func waitFor(element: XCUIElement, predicate: NSPredicate, message: String, waitSeconds: TimeInterval, file: StaticString, line: UInt) { waitFor(element: element, predicate: predicate, failElement: nil, failPredicate: nil, message: message, waitSeconds: waitSeconds, file: file, line: line) } private func waitFor(element: XCUIElement, predicate: NSPredicate, failElement: XCUIElement?, failPredicate: NSPredicate?, message: String, waitSeconds: TimeInterval, file: StaticString, line: UInt) { if let failElement = failElement, let failPredicate = failPredicate { let finishPredicate = NSPredicate { [weak self] (obj, bindings) -> Bool in guard let targets = obj as? [XCUIElement], targets.count == 2 else { return false } let positiveOutcome = predicate.evaluate(with: targets[0]) let negativeOutcome = failPredicate.evaluate(with: targets[1]) if (negativeOutcome) { self?.failHelper(message: "\(message) [early fail detection triggerred]", file: file, line: line, nothrow: true) } return positiveOutcome || negativeOutcome } let finishArgs = [element, failElement] expectation(for: finishPredicate, evaluatedWith: finishArgs, handler: nil) } else { expectation(for: predicate, evaluatedWith: element, handler: nil) } waitForExpectations(timeout: waitSeconds) { [weak self] (error) -> Void in if let error = error { self?.failHelper(message: "\(message) [error: \(error.localizedDescription)]", file: file, line: line, nothrow: true) } } guard predicate.evaluate(with: element) else { failHelper(message: "\(message) [predicate returned false]", file: file, line: line) return } if let failElement = failElement, let failPredicate = failPredicate { guard failPredicate.evaluate(with: failElement) == false else { failHelper(message: "\(message) [failPredicate returned true]", file: file, line: line) return } } } // MARK: - Helper methods (navigation) fileprivate func navigateToExample(app: XCUIApplication, title: String, file: StaticString = #file, line: UInt = #line) { let listItem = app.tables.staticTexts[title] waitForExists(element: listItem, waitSeconds: 5, file: file, line: line) listItem.tap() let navBar = app.navigationBars[title] waitForExists(element: navBar, waitSeconds: 5, file: file, line: line) } fileprivate func pickSegment(app: XCUIApplication, segmentedIndex: Int, segment: String?, file: StaticString = #file, line: UInt = #line) { app.segmentedControls.allElementsBoundByIndex[segmentedIndex].buttons[segment ?? "All"].tap() } fileprivate func navigateToSection(app: XCUIApplication, title: String, file: StaticString = #file, line: UInt = #line) { let adapter = app.tabBars.buttons[title] waitForExists(element: adapter, waitSeconds: 5) adapter.tap() } // MARK: - Helper Methods (app management) class AppLifebox { var app: XCUIApplication! private var interruptionMonitor: NSObjectProtocol? private var removeMonitorClosure: (NSObjectProtocol) -> () init(addMonitorClosure: (String, @escaping (XCUIElement) -> Bool) -> NSObjectProtocol?, removeMonitorClosure: @escaping (NSObjectProtocol) -> ()) { app = XCUIApplication() app.launchArguments.append("-keyUITests") app.launch() interruptionMonitor = addMonitorClosure("System Dialog") { (alert) -> Bool in alert.buttons["Don’t Allow"].tap() return true } app.navigationBars.firstMatch.tap() self.removeMonitorClosure = removeMonitorClosure } deinit { if let monitor = interruptionMonitor { interruptionMonitor = nil removeMonitorClosure(monitor) } if app.state != .notRunning { app.terminate() } } } func constructApp() -> AppLifebox { return AppLifebox( addMonitorClosure: self.addUIInterruptionMonitor, removeMonitorClosure: self.removeUIInterruptionMonitor) } // MARK: - Private Helpers (failing) private func failHelper(message: String, file: StaticString, line: UInt, nothrow: Bool = false) { let screenshot = XCUIScreen.main.screenshot() let attachment = XCTAttachment(screenshot: screenshot) add(attachment) if let failable = self as? Failable { failable.failWithMessage(message, file: "\(file)", line: line, nothrow: nothrow) } else { XCTFail(message, file: file, line: line) } } } extension BaseUITestCase { enum Tag: String, CaseIterable { // Note: order defines search priority during the detection case native = "Native" case mraid = "MRAID" case video = "Video" case interstitial = "Interstitial" case banner = "Banner" } enum AdServer: String, CaseIterable { // Note: order defines search priority during the detection case inapp = "In-App" case gam = "GAM" } private func detect<T: RawRepresentable & CaseIterable>(from exampleTitle: String) -> T? where T.RawValue == String { if let rawVal = T .allCases .map({ $0.rawValue }) .filter({ exampleTitle.contains($0.replacingOccurrences(of: " ", with: "")) }) .first { return T.init(rawValue: rawVal) } else { return nil } } func navigateToExample(_ title: String, file: StaticString = #file, line: UInt = #line) { applyFilter(adServer: detect(from: title)) applyFilter(tag: detect(from: title)) navigateToExample(app: app, title: title, file: file, line: line) } func applyFilter(tag: Tag?, file: StaticString = #file, line: UInt = #line) { pickSegment(app: app, segmentedIndex: 0, segment: tag?.rawValue, file: file, line: line) } func applyFilter(adServer: AdServer?, file: StaticString = #file, line: UInt = #line) { pickSegment(app: app, segmentedIndex: 1, segment: adServer?.rawValue, file: file, line: line) } func navigateToExamplesSection(file: StaticString = #file, line: UInt = #line) { navigateToSection(app: app, title: "Examples", file: file, line: line) } }
5e736c1ed41f62ae672be931469e405e
43.58952
204
0.634806
false
false
false
false
coodly/SlimTimerAPI
refs/heads/master
Tests/SlimTimerAPITests/LoadMultipleEntriesTests.swift
apache-2.0
1
/* * Copyright 2017 Coodly 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 XCTest import SWXMLHash @testable import SlimTimerAPI class LoadMultipleEntriesTests: XCTestCase { func testLoadMultipleEntries() { let input = """ <?xml version="1.0" encoding="UTF-8"?> <time-entries> <time-entry> <end-time type="datetime">2017-12-02T15:19:22Z</end-time> <created-at type="datetime">2017-12-03T06:12:31Z</created-at> <comments nil="true"></comments> <updated-at type="datetime">2017-12-03T06:12:31Z</updated-at> <tags></tags> <id type="integer">34493713</id> <duration-in-seconds type="integer">79</duration-in-seconds> <task> <coworkers> </coworkers> <name>Review apps</name> <created-at type="datetime">2014-01-11T16:51:43Z</created-at> <completed-on nil="true"></completed-on> <owners> <person> <name>Apple</name> <user-id type="integer">119695</user-id> <email>[email protected]</email> </person> </owners> <updated-at type="datetime">2014-01-11T16:51:43Z</updated-at> <role>owner</role> <tags></tags> <id type="integer">2267906</id> <reporters> </reporters> <hours type="float">10.04</hours> </task> <in-progress type="boolean">false</in-progress> <start-time type="datetime">2017-12-02T15:18:02Z</start-time> </time-entry> <time-entry> <end-time type="datetime">2017-12-02T15:50:45Z</end-time> <created-at type="datetime">2017-12-02T15:50:29Z</created-at> <comments nil="true"></comments> <updated-at type="datetime">2017-12-02T15:50:46Z</updated-at> <tags></tags> <id type="integer">34493460</id> <duration-in-seconds type="integer">60</duration-in-seconds> <task> <coworkers> </coworkers> <name>The Secret Project</name> <created-at type="datetime">2015-03-07T13:21:28Z</created-at> <completed-on nil="true"></completed-on> <owners> <person> <name>Apple</name> <user-id type="integer">119695</user-id> <email>[email protected]</email> </person> </owners> <updated-at type="datetime">2015-03-07T13:21:28Z</updated-at> <role>owner</role> <tags></tags> <id type="integer">2536936</id> <reporters> </reporters> <hours type="float">0.02</hours> </task> <in-progress type="boolean">false</in-progress> <start-time type="datetime">2017-12-02T15:50:28Z</start-time> </time-entry> <time-entry> <end-time type="datetime">2017-12-02T15:26:37Z</end-time> <created-at type="datetime">2017-12-02T15:19:31Z</created-at> <comments nil="true"></comments> <updated-at type="datetime">2017-12-02T15:26:39Z</updated-at> <tags></tags> <id type="integer">34493451</id> <duration-in-seconds type="integer">427</duration-in-seconds> <task> <coworkers> </coworkers> <name>Reading</name> <created-at type="datetime">2015-03-07T13:22:24Z</created-at> <completed-on nil="true"></completed-on> <owners> <person> <name>Apple</name> <user-id type="integer">119695</user-id> <email>[email protected]</email> </person> </owners> <updated-at type="datetime">2015-03-07T13:22:24Z</updated-at> <role>owner</role> <tags></tags> <id type="integer">2536937</id> <reporters> </reporters> <hours type="float">4.52</hours> </task> <in-progress type="boolean">false</in-progress> <start-time type="datetime">2017-12-02T15:19:30Z</start-time> </time-entry> </time-entries> """ let xml = SWXMLHash.parse(input) guard let entries = Entries(xml: xml) else { XCTAssertFalse(true) return } XCTAssertEqual(3, entries.entries.count) } }
d56af2823c08a761b0536bbf297a21d9
37.992537
75
0.523445
false
false
false
false
schibsted/layout
refs/heads/master
LayoutTool/main.swift
mit
1
// Copyright © 2017 Schibsted. All rights reserved. import Foundation /// The current LayoutTool version let version = "0.7.0" extension String { var inDefault: String { return "\u{001B}[39m\(self)" } var inRed: String { return "\u{001B}[31m\(self)\u{001B}[0m" } var inGreen: String { return "\u{001B}[32m\(self)\u{001B}[0m" } var inYellow: String { return "\u{001B}[33m\(self)\u{001B}[0m" } } extension FileHandle: TextOutputStream { public func write(_ string: String) { if let data = string.data(using: .utf8) { write(data) } } } private var stderr = FileHandle.standardError func printHelp() { print("") print("LayoutTool, version \(version)") print("copyright (c) 2017 Schibsted") print("") print("help") print(" - prints this help page") print("") print("version") print(" - prints the currently installed LayoutTool version") print("") print("format <files>") print(" - formats all xml files found at the specified path(s)") print("") print("list <files>") print(" - lists all Layout xml files found at the specified path(s)") print("") print("rename <files> <old> <new>") print(" - renames all classes or symbols named <old> to <new> in <files>") print("") print("strings <files>") print(" - lists all Localizable.strings keys used in <files>") print("") } enum ExitResult: Int32 { case success = 0 case failure = 1 } func timeEvent(block: () throws -> Void) rethrows -> String { let start = CFAbsoluteTimeGetCurrent() try block() let time = round((CFAbsoluteTimeGetCurrent() - start) * 100) / 100 // round to nearest 10ms return String(format: "%gs", time) } func processArguments(_ args: [String]) -> ExitResult { var errors = [FormatError]() guard args.count > 1 else { print("error: missing command argument", to: &stderr) print("LayoutTool requires a command argument".inRed, to: &stderr) return .failure } switch args[1] { case "help": printHelp() case "version": print(version) case "format": let paths = Array(args.dropFirst(2)) if paths.isEmpty { errors.append(.options("format command expects one or more file paths as input")) break } var filesChecked = 0, filesUpdated = 0 let time = timeEvent { (filesChecked, filesUpdated, errors) = format(paths) } if errors.isEmpty { print("LayoutTool format completed. \(filesUpdated)/\(filesChecked) files updated in \(time)".inGreen) } case "list": let paths = Array(args.dropFirst(2)) if paths.isEmpty { errors.append(.options("list command expects one or more file paths to search")) break } errors += list(paths) case "rename": var paths = Array(args.dropFirst(2)) guard let new = paths.popLast(), let old = paths.popLast(), !new.contains("/"), !old.contains("/") else { errors.append(.options("rename command expects a name and replacement")) break } if paths.isEmpty { errors.append(.options("rename command expects one or more file paths to search")) break } errors += rename(old, to: new, in: paths) case "strings": let paths = Array(args.dropFirst(2)) if paths.isEmpty { errors.append(.options("list command expects one or more file paths to search")) break } errors += listStrings(in: paths) case let arg: print("error: unknown command \(arg)", to: &stderr) print("LayoutTool \(arg) is not a valid command".inRed, to: &stderr) return .failure } for error in errors { print("error: \(error)", to: &stderr) } if errors.isEmpty { return .success } else { print("LayoutTool \(args[1]) failed".inRed, to: &stderr) return .failure } } // Pass in arguments and exit let result = processArguments(CommandLine.arguments) exit(result.rawValue)
b36fef1f62d75838df4190a624248d23
31.015385
114
0.59851
false
false
false
false
adityaaggarwal1/CMLibrary
refs/heads/master
Example/CMLibrary/ViewController.swift
mit
1
// // ViewController.swift // CMLibrary // // Created by adityaaggarwal1 on 09/23/2015. // Copyright (c) 2015 adityaaggarwal1. All rights reserved. // import UIKit import CMLibrary class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let toggleButton = UIButton(frame: CGRect(x: 10, y: 60, width: 200, height: 30)) toggleButton.setTitle("Webservice Call", forState: .Normal) toggleButton.setTitleColor(UIColor.redColor(), forState: .Normal) toggleButton.addTarget(self, action: "getTokenService", forControlEvents: .TouchUpInside) view.addSubview(toggleButton) let toggleButton1 = UIButton(frame: CGRect(x: 10, y: 120, width: 200, height: 30)) toggleButton1.setTitle("Webservice Call With Auth", forState: .Normal) toggleButton1.setTitleColor(UIColor.redColor(), forState: .Normal) toggleButton1.addTarget(self, action: "getFromKeyChain", forControlEvents: .TouchUpInside) view.addSubview(toggleButton1) } func callWebservice() { let webserviceCall = WebserviceCall(responseType: WebserviceCallResponseJSON, requestType: WebserviceCallRequestTypeJson, cachePolicy: WebserviceCallCachePolicyRequestFromUrlNoCache) webserviceCall.isShowLoader = true // http://jsonplaceholder.typicode.com/comments?postId=1 // webserviceCall.GET(NSURL(string: "http://jsonplaceholder.typicode.com/posts"), parameters: nil, withSuccessHandler: { (response: WebserviceResponse!) -> Void in // // let responseDict = response as WebserviceResponse // // print(responseDict.webserviceResponse) // // }) { (error: NSError!) -> Void in // // } webserviceCall.shouldDisableInteraction = false webserviceCall.GET(NSURL(string: "http://jsonplaceholder.typicode.com/comments"), parameters: ["postId":"1"], withSuccessHandler: { (response: WebserviceResponse!) -> Void in let responseDict = response as WebserviceResponse print(responseDict.webserviceResponse) }) { (error: NSError!) -> Void in } } func callPatchWebservice() { let webserviceCall = WebserviceCall(responseType: WebserviceCallResponseJSON, requestType: WebserviceCallRequestTypeJson, cachePolicy: WebserviceCallCachePolicyRequestFromUrlNoCache) webserviceCall.isShowLoader = true // http://jsonplaceholder.typicode.com/comments?postId=1 // webserviceCall.GET(NSURL(string: "http://jsonplaceholder.typicode.com/posts"), parameters: nil, withSuccessHandler: { (response: WebserviceResponse!) -> Void in // // let responseDict = response as WebserviceResponse // // print(responseDict.webserviceResponse) // // }) { (error: NSError!) -> Void in // // } webserviceCall.headerFieldsDict = ["Authorization" : "Bearer PuJq65INyxSipxFDipCXdyhJPBhUws"] webserviceCall.shouldDisableInteraction = false webserviceCall.DELETE(NSURL(string: "http://172.16.13.206:8009/app/api/delsrvc/20123/"), parameters: ["postId":"1"], withSuccessHandler: { (response: WebserviceResponse!) -> Void in let responseDict = response as WebserviceResponse print(responseDict.webserviceResponse) }) { (error: NSError!) -> Void in } } func uploadFileUsingMultipartUpload() { let webserviceCall = WebserviceCall(responseType: WebserviceCallResponseString, requestType: WebserviceCallRequestTypeJson, cachePolicy: WebserviceCallCachePolicyRequestFromUrlNoCache) webserviceCall.isShowLoader = true let fileData = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("iOS Simulator Screen.png", ofType: nil)!) webserviceCall.uploadFile(fileData, withFileName: "iOS Simulator Screen.png", withFieldName: "file", mimeType: "image/png", onUrl: NSURL(string: "http://posttestserver.com/post.php?dir=example"), withSuccessHandler: { (response: WebserviceResponse!) -> Void in let responseDict = response as WebserviceResponse print(responseDict.webserviceResponse) }) { (error: NSError!) -> Void in } } @IBAction func btnDummyTapped(sender: AnyObject) { print("test >>>>>>>>>>>>>>>>>>>>>>>>>") callWebservice() } func saveInKeyChain() { let token = AuthToken() token.access_token = "abc123" FXKeychain.defaultKeychain().setObject(token, forKey: "Key") } func getFromKeyChain() { let webserviceCall = WebserviceCall(responseType: WebserviceCallResponseJSON, requestType: WebserviceCallRequestTypeJson, cachePolicy: WebserviceCallCachePolicyRequestFromUrlNoCache) webserviceCall.isShowLoader = true webserviceCall.addAuthTokenInHeaderFromKey("AuthToken") webserviceCall.POST(NSURL(string: "http://172.16.13.33:8009/app/api/signup/"), parameters: ["name":"test2", "email":"[email protected]", "password":"test2", "mobile":"8765657700", "device_id":"123awd1233", "device_token":"23424234sdfsd234234", "device_type":"1"], withSuccessHandler: { (response: WebserviceResponse!) -> Void in let responseDict = (response as WebserviceResponse).webserviceResponse as! NSDictionary NSLog("responseDict >>>>>>> %@", responseDict.description) }) { (error: NSError!) -> Void in } } func getTokenService() { let webserviceCall = WebserviceCall(responseType: WebserviceCallResponseJSON, requestType: WebserviceCallRequestTypeFormURLEncoded, cachePolicy: WebserviceCallCachePolicyRequestFromUrlNoCache) webserviceCall.isShowLoader = true webserviceCall.fetchAuthTokenForClientSecret("lkeg7r@IQDwrFa7NHbNnV?e:oOs=UeHQ0j=83sJWux5mCOV6EX_DJx?vu0uLnwvlk1KM@BXX?.LBRrgWbW:rSF-ll_eCG!BwtkYIGn04JtVoLi=VYE3EAk:A.zS3u0VF", clientId: "qUiOEFk9Uyjw1z2pDUKW8=PMSv9FasXkYpgFa0P2", grantType: "client_credentials", andStoreAtKey: "AuthToken") webserviceCall.POST(NSURL(string: "http://172.16.13.33:8009/o/token/"), parameters: nil, withSuccessHandler: { (response: WebserviceResponse!) -> Void in let responseDict = (response as WebserviceResponse).webserviceResponse as! NSDictionary NSLog("responseDict >>>>>>> %@", responseDict.description) }) { (error: NSError!) -> Void in } } }
5994e18afdf23c9d2c2591bace8022fa
41.575163
338
0.687903
false
false
false
false
cloudinary/cloudinary_ios
refs/heads/master
Cloudinary/Classes/Core/Features/CacheSystem/StorehouseLibrary/Core/StorehouseAccess/StorehouseAccessor.swift
mit
1
// // StorehouseAccessor.swift // // Copyright (c) 2020 Cloudinary (http://cloudinary.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import Dispatch /// /// /// internal class StorehouseAccessor<StoredItem> { /// MARK: - Typealias internal typealias Item = StoredItem /// MARK: - Public Properties internal var storehouse : StorehouseHybrid<Item> internal let accessQueue : DispatchQueue internal var memoryCapacity : Int { var value : Int! accessQueue.sync { value = storehouse.memoryCapacity } return value } internal var diskCapacity : Int { var value : Int! accessQueue.sync { value = storehouse.diskCapacity } return value } internal var currentMemoryUsage : Int { var value : Int! accessQueue.sync { value = storehouse.currentMemoryUsage } return value } internal var currentDiskUsage: Int { var value : Int! accessQueue.sync { value = storehouse.currentDiskUsage } return value } /// MARK: - Initializers internal init(storage: StorehouseHybrid<Item>, queue: DispatchQueue) { self.storehouse = storage self.accessQueue = queue } internal func replaceStorage(_ storage: StorehouseHybrid<Item>) { accessQueue.sync(flags: [.barrier]) { self.storehouse = storage } } } extension StorehouseAccessor : StorehouseProtocol { @discardableResult internal func entry(forKey key: String) throws -> StorehouseEntry<Item> { var entry : StorehouseEntry<Item>! try accessQueue.sync { entry = try storehouse.entry(forKey: key) } return entry } internal func removeObject(forKey key: String) throws { try accessQueue.sync(flags: [.barrier]) { try self.storehouse.removeObject(forKey: key) } } internal func setObject(_ object: Item, forKey key: String, expiry: StorehouseExpiry? = nil) throws { try accessQueue.sync(flags: [.barrier]) { try storehouse.setObject(object, forKey: key, expiry: expiry) } } internal func removeAll() throws { try accessQueue.sync(flags: [.barrier]) { try storehouse.removeAll() } } internal func removeExpiredObjects() throws { try accessQueue.sync(flags: [.barrier]) { try storehouse.removeExpiredObjects() } } internal func removeStoredObjects(since date: Date) throws { try accessQueue.sync(flags: [.barrier]) { try storehouse.removeStoredObjects(since: date) } } internal func removeObjectIfExpired(forKey key: String) throws { try accessQueue.sync(flags: [.barrier]) { try storehouse.removeObjectIfExpired(forKey: key) } } }
5daae28b1854bda6313673601e5d1ac0
29.823077
103
0.649863
false
false
false
false
pusher-community/pusher-websocket-swift
refs/heads/master
Sources/Helpers/EventParser.swift
mit
2
import Foundation struct EventParser { /** Parse a string to extract Pusher event information from it - parameter string: The string received over the websocket connection containing Pusher event information - returns: A dictionary of Pusher-relevant event data */ static func getPusherEventJSON(from string: String) -> [String: AnyObject]? { let data = (string as NSString).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false) do { if let jsonData = data, let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: AnyObject] { return jsonObject } else { Logger.shared.debug(for: .unableToParseStringAsJSON, context: string) } } catch let error as NSError { Logger.shared.error(for: .genericError, context: error.localizedDescription) } return nil } /** Parse a string to extract Pusher event data from it - parameter string: The data string received as part of a Pusher message - returns: The object sent as the payload part of the Pusher message */ static func getEventDataJSON(from string: String) -> Any? { let data = (string as NSString).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false) do { if let jsonData = data, let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: []) { return jsonObject } else { Logger.shared.debug(for: .unableToParseStringAsJSON, context: string) } } return nil } }
93d4e2731ad59a62f200ba6b968c3e82
34.471698
117
0.573404
false
false
false
false
lazerwalker/storyboard-iOS
refs/heads/master
Storyboard-Example/ProjectListViewController.swift
mit
1
import UIKit class ProjectListViewController : UITableViewController { let projects:[String] let handler:(String?) -> Void required init(projects:[String], handler:@escaping ((String?) -> Void)) { self.projects = projects self.handler = handler super.init(style: .plain) self.title = "Projects" self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(ProjectListViewController.cancel)) } required init?(coder aDecoder: NSCoder) { projects = [] handler = { _ in } super.init(coder: aDecoder) } //- @objc func cancel() { self.handler(nil) } //- UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.tableView.deselectRow(at: indexPath, animated: true) let project = projects[indexPath.row] self.handler(project) } //- UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return projects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = projects[indexPath.row] return cell } }
002e94c39556db6ad6a13e038995974a
29.58
160
0.669065
false
false
false
false
quickthyme/PUTcat
refs/heads/master
PUTcat/Application/Data/Service/Entity/PCService.swift
apache-2.0
1
import Foundation final class PCService: PCItem, PCCopyable, PCLocal { var id: String var name: String var transactions : PCList<PCTransaction>? init(id: String, name: String) { self.id = id self.name = name } convenience init(name: String) { self.init(id: UUID().uuidString, name: name) } convenience init() { self.init(name: "New Service") } required convenience init(copy: PCService) { self.init(name: copy.name) self.transactions = copy.transactions?.copy() } required init(fromLocal: [String:Any]) { self.id = fromLocal["id"] as? String ?? "" self.name = fromLocal["name"] as? String ?? "" } func toLocal() -> [String:Any] { return [ "id" : self.id, "name" : self.name ] } } extension PCService : PCLocalExport { func toLocalExport() -> [String:Any] { var local = self.toLocal() if let array = self.transactions?.toLocalExport() { local["transactions"] = array } return local } }
3fb3b8cb268e218a83395717556c6fba
22.163265
59
0.548018
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
refs/heads/master
Solutions/SolutionsTests/Medium/Medium_075_Sort_Colors_Test.swift
mit
1
// // Medium_075_Sort_Colors_Test.swift // Solutions // // Created by Di Wu on 7/30/15. // Copyright © 2015 diwu. All rights reserved. // import XCTest class Medium_075_Sort_Colors_Test: XCTestCase, SolutionsTestCase { func test_001() { var input: [Int] = [2, 1, 1, 2, 2, 1, 0, 0, 1, 2] let expected: [Int] = [0, 0, 1, 1, 1, 1, 2, 2, 2, 2] asyncHelper(input: &input, expected: expected) } private func asyncHelper(input: inout [Int], expected: [Int]) { weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName()) var localInput = input serialQueue().async(execute: { () -> Void in Medium_075_Sort_Colors.sortColors(&localInput) let result = localInput assertHelper(result == expected, problemName:self.problemName(), input: localInput, resultValue: result, expectedValue: expected) if let unwrapped = expectation { unwrapped.fulfill() } }) waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in if error != nil { assertHelper(false, problemName:self.problemName(), input: localInput, resultValue:self.timeOutName(), expectedValue: expected) } } } }
cd4120f893de8de4c5348944a1d8e66c
37.205882
143
0.603541
false
true
false
false
icylydia/PlayWithLeetCode
refs/heads/master
260. Single Number III/solution.swift
mit
1
class Solution { func singleNumber(nums: [Int]) -> [Int] { let xor = nums.reduce(0){$0^$1} var diffBit = 1 while(diffBit & xor == 0) { diffBit <<= 1 } var groupA = Array<Int>() var groupB = Array<Int>() for num in nums { if num & diffBit == 0 { groupA.append(num) } else { groupB.append(num) } } let a = groupA.reduce(0){$0^$1} let b = groupB.reduce(0){$0^$1} return [a, b] } }
8be73d51fa6001ab04c6f8776cb39012
21.809524
45
0.485356
false
false
false
false
Drusy/auvergne-webcams-ios
refs/heads/master
Carthage/Checkouts/Eureka/Example/Example/Controllers/ListSectionsController.swift
apache-2.0
4
// // ListSectionsController.swift // Example // // Created by Mathias Claassen on 3/15/18. // Copyright © 2018 Xmartlabs. All rights reserved. // import Eureka class ListSectionsController: FormViewController { override func viewDidLoad() { super.viewDidLoad() let continents = ["Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America"] form +++ SelectableSection<ImageCheckRow<String>>() { section in section.header = HeaderFooterView(title: "Where do you live?") } for option in continents { form.last! <<< ImageCheckRow<String>(option){ lrow in lrow.title = option lrow.selectableValue = option lrow.value = nil } } let oceans = ["Arctic", "Atlantic", "Indian", "Pacific", "Southern"] form +++ SelectableSection<ImageCheckRow<String>>("And which of the following oceans have you taken a bath in?", selectionType: .multipleSelection) for option in oceans { form.last! <<< ImageCheckRow<String>(option){ lrow in lrow.title = option lrow.selectableValue = option lrow.value = nil }.cellSetup { cell, _ in cell.trueImage = UIImage(named: "selectedRectangle")! cell.falseImage = UIImage(named: "unselectedRectangle")! cell.accessoryType = .checkmark } } } override func valueHasBeenChanged(for row: BaseRow, oldValue: Any?, newValue: Any?) { if row.section === form[0] { print("Single Selection:\((row.section as! SelectableSection<ImageCheckRow<String>>).selectedRow()?.baseValue ?? "No row selected")") } else if row.section === form[1] { print("Mutiple Selection:\((row.section as! SelectableSection<ImageCheckRow<String>>).selectedRows().map({$0.baseValue}))") } } }
1c5890a877188d128047e1b910ea3329
36
155
0.589089
false
false
false
false
visualitysoftware/swift-sdk
refs/heads/master
CloudBoost/CloudFile.swift
mit
1
// // CloudFile.swift // CloudBoost // // Created by Randhir Singh on 31/03/16. // Copyright © 2016 Randhir Singh. All rights reserved. // import Foundation public class CloudFile { var document = NSMutableDictionary() private var data: NSData? private var strEncodedData: String? public init(name: String, data: NSData, contentType: String){ self.data = data self.strEncodedData = data.base64EncodedStringWithOptions([]) document["_id"] = nil document["_type"] = "file" document["ACL"] = ACL().getACL() document["name"] = name document["size"] = data.length document["url"] = nil document["expires"] = nil document["contentType"] = contentType } public init(id: String){ document["_id"] = id } public init(doc: NSMutableDictionary){ self.document = doc self.data = nil } // MARK: Getters public func getId() -> String? { return document["_id"] as? String } public func getContentType() -> String? { return document["contentType"] as? String } public func getFileUrl() -> String? { return document["url"] as? String } public func getFileName() -> String? { return document["name"] as? String } public func getACL() -> ACL? { if let acl = document["ACL"] as? NSMutableDictionary { return ACL(acl: acl) } return nil } public func getData() -> NSData? { return data } public func getExpires() -> NSDate? { if let expires = document["expires"] as? String { return CloudBoostDateFormatter.getISOFormatter().dateFromString(expires) } return nil } public func setExpires(date: NSDate) { document["expires"] = CloudBoostDateFormatter.getISOFormatter().stringFromDate(date) } // MARK: Setters public func setId(id: String){ document["_id"] = id } public func setContentType(contentType: String){ document["contentType"] = contentType } public func setFileUrl(url: String){ document["url"] = url } public func setFileName(name: String){ document["name"] = name } public func setACL(acl: ACL){ document["ACL"] = acl.getACL() } public func setDate(data: NSData) { self.data = data self.strEncodedData = data.base64EncodedStringWithOptions([]) } // Save a CloudFile object public func save(callback: (response: CloudBoostResponse) -> Void){ let params = NSMutableDictionary() params["key"] = CloudApp.getAppKey()! params["fileObj"] = self.document params["data"] = self.strEncodedData let url = CloudApp.getApiUrl() + "/file/" + CloudApp.getAppId()! CloudCommunications._request("POST", url: NSURL(string: url)!, params: params, callback: { (response: CloudBoostResponse) in if(response.success) { self.document = (response.object as? NSMutableDictionary)! } callback(response: response) }) } // Save an array of CloudFile public static func saveAll(array: [CloudFile], callback: (CloudBoostResponse)->Void) { // Ready the response let resp = CloudBoostResponse() resp.success = true var count = 0 // Iterate through the array for object in array { let url = CloudApp.serverUrl + "/file/" + CloudApp.appID! let params = NSMutableDictionary() params["key"] = CloudApp.appKey! params["fileObj"] = object.document params["data"] = object.strEncodedData CloudCommunications._request("POST", url: NSURL(string: url)!, params: params, callback: {(response: CloudBoostResponse) in count += 1 if(response.success){ if let newDocument = response.object { object.document = newDocument as! NSMutableDictionary } }else{ resp.success = false resp.message = "one or more objects were not saved" } if(count == array.count){ resp.object = count callback(resp) } }) } } // delete a CloudFile public func delete(callback: (response: CloudBoostResponse) -> Void) throws { guard let _ = document["url"] else{ throw CloudBoostError.InvalidArgument } let params = NSMutableDictionary() params["fileObj"] = document params["key"] = CloudApp.getAppKey()! let url = CloudApp.getApiUrl() + "/file/" + CloudApp.getAppId()! + "/" + self.getId()! CloudCommunications._request("DELETE", url: NSURL(string: url)!, params: params, callback: { (response: CloudBoostResponse) in if response.success && (response.status >= 200 || response.status < 300) { self.document = [:] } callback(response: response) }) } public static func getFileFromUrl(url: NSURL, callback: (response: CloudBoostResponse)->Void){ let cbResponse = CloudBoostResponse() cbResponse.success = false let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "GET" NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { data, response, error -> Void in guard let httpRes = response as? NSHTTPURLResponse else { cbResponse.message = "Proper response not received" callback(response: cbResponse) return } cbResponse.status = httpRes.statusCode if( httpRes.statusCode == 200){ guard let strEncodedData = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String else { cbResponse.message = "Error in encoding/decoding" callback(response: cbResponse) return } let nsData = NSData(base64EncodedString: strEncodedData, options: []) cbResponse.success = true cbResponse.object = nsData } else { cbResponse.message = "\(httpRes.statusCode) error" } callback(response: cbResponse) }).resume() } public func uploadSave(progressCallback : (response: CloudBoostProgressResponse)->Void){ let params = NSMutableDictionary() params["key"] = CloudApp.getAppKey()! params["fileObj"] = self.document params["data"] = self.strEncodedData let url = CloudApp.getApiUrl() + "/file/" + CloudApp.getAppId()! CloudCommunications()._requestFile("POST", url: NSURL(string: url)!, params: params, data: data, uploadCallback: { uploadResponse in progressCallback(response: uploadResponse) }) } public func fetch(callback: (CloudBoostResponse)->Void){ let res = CloudBoostResponse() let query = CloudQuery(tableName: "_File") if getId() == nil { res.message = "ID not set in the object" callback(res) }else{ try! query.equalTo("id", obj: getId()!) query.setLimit(1) query.find({ res in if res.success { if let obj = res.object as? [NSMutableDictionary] { self.document = obj[0] callback(res) }else{ res.success = false res.message = "Invalid response received" callback(res) } } }) } } }
5607748f151073f5dddde5d036fa88ac
31.375
122
0.536262
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/2 - Primitives/Media/Media.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AVKit import CasePaths import Extensions import Nuke import NukeUI import SwiftUI import UniformTypeIdentifiers public typealias Media = NukeUI.Image @MainActor public struct AsyncMedia<Content: View>: View { private let url: URL? private let transaction: Transaction private let content: (AsyncPhase<Media>) -> Content @Environment(\.resizingMode) var resizingMode public init( url: URL?, transaction: Transaction = Transaction(), @ViewBuilder content: @escaping (AsyncPhase<Media>) -> Content ) { self.url = url self.transaction = transaction self.content = content } public var body: some View { LazyImage( url: url, content: { state in withTransaction(transaction) { which(state) } } ) } @ViewBuilder private func which(_ state: LazyImageState) -> some View { if let image: NukeUI.Image = state.image { #if os(macOS) content(.success(image)) #else content(.success(image.resizingMode(resizingMode.imageResizingMode))) #endif } else if let error = state.error { content(.failure(error)) } else { content(.empty) } } } extension AsyncMedia { public init( url: URL?, transaction: Transaction = Transaction() ) where Content == _ConditionalContent<Media, ProgressView<EmptyView, EmptyView>>? { self.init(url: url, transaction: transaction, placeholder: { ProgressView() }) } public init<I: View, P: View>( url: URL?, transaction: Transaction = Transaction(), @ViewBuilder content: @escaping (Media) -> I, @ViewBuilder placeholder: @escaping () -> P ) where Content == _ConditionalContent<_ConditionalContent<I, EmptyView>, P> { self.init(url: url, transaction: transaction, content: content, failure: { _ in EmptyView() }, placeholder: placeholder) } public init<I: View, F: View, P: View>( url: URL?, transaction: Transaction = Transaction(), @ViewBuilder content: @escaping (Media) -> I, @ViewBuilder failure: @escaping (Error) -> F, @ViewBuilder placeholder: @escaping () -> P ) where Content == _ConditionalContent<_ConditionalContent<I, F>, P> { self.init(url: url, transaction: transaction) { phase in switch phase { case .success(let media): content(media) case .failure(let error): failure(error) case .empty: placeholder() } } } public init<P: View>( url: URL?, transaction: Transaction = Transaction(), @ViewBuilder placeholder: @escaping () -> P ) where Content == _ConditionalContent<Media, P>? { self.init( url: url, transaction: transaction, content: { phase in if case .success(let media) = phase { media } else if case .empty = phase { placeholder() } } ) } } extension URL { var uniformTypeIdentifier: UTType? { UTType(filenameExtension: pathExtension) } } extension EnvironmentValues { public var resizingMode: MediaResizingMode { get { self[ImageResizingModeEnvironmentKey.self] } set { self[ImageResizingModeEnvironmentKey.self] = newValue } } } private struct ImageResizingModeEnvironmentKey: EnvironmentKey { static var defaultValue = MediaResizingMode.aspectFit } extension View { @warn_unqualified_access @inlinable public func resizingMode(_ resizingMode: MediaResizingMode) -> some View { environment(\.resizingMode, resizingMode) } } public enum MediaResizingMode: String, Codable { case fill case aspectFit = "aspect_fit" case aspectFill = "aspect_fill" case center case top case bottom case left case right case topLeft = "top_left" case topRight = "top_right" case bottomLeft = "bottom_left" case bottomRight = "bottom_right" } extension MediaResizingMode { @usableFromInline var imageResizingMode: ImageResizingMode { switch self { case .fill: return .fill case .aspectFit: return .aspectFit case .aspectFill: return .aspectFill case .center: return .center case .top: return .top case .bottom: return .bottom case .left: return .left case .right: return .right case .topLeft: return .topLeft case .topRight: return .topRight case .bottomLeft: return .bottomLeft case .bottomRight: return .bottomRight } } }
72813ece76e70c3ae91482e45491df1a
27.439306
128
0.6
false
false
false
false
Electrode-iOS/ELHybridWeb
refs/heads/master
Source/Web View/WebViewController.swift
mit
2
// // WebViewController.swift // ELHybridWeb // // Created by Angelo Di Paolo on 4/16/15. // Copyright (c) 2015 WalmartLabs. All rights reserved. // import Foundation import JavaScriptCore import UIKit /** Defines methods that a delegate of a WebViewController object can optionally implement to interact with the web view's loading cycle. */ @objc public protocol WebViewControllerDelegate { /** Sent before the web view begins loading a frame. - parameter webViewController: The web view controller loading the web view frame. - parameter request: The request that will load the frame. - parameter navigationType: The type of user action that started the load. - returns: Return true to */ @objc optional func webViewController(_ webViewController: WebViewController, shouldStartLoadWithRequest request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool /** Sent before the web view begins loading a frame. - parameter webViewController: The web view controller that has begun loading the frame. */ @objc optional func webViewControllerDidStartLoad(_ webViewController: WebViewController) /** Sent after the web view as finished loading a frame. - parameter webViewController: The web view controller that has completed loading the frame. */ @objc optional func webViewControllerDidFinishLoad(_ webViewController: WebViewController) /** Sent if the web view fails to load a frame. - parameter webViewController: The web view controller that failed to load the frame. - parameter error: The error that occured during loading. */ @objc optional func webViewController(_ webViewController: WebViewController, didFailLoadWithError error: Error) /** Sent when the web view creates the JS context for the frame. parameter webViewController: The web view controller that failed to load the frame. parameter context: The newly created JavaScript context. */ @objc optional func webViewControllerDidCreateJavaScriptContext(_ webViewController: WebViewController, context: JSContext) } /** A view controller that integrates a web view with the hybrid JavaScript API. # Usage Initialize a web view controller and call `loadURL()` to asynchronously load the web view with a URL. ``` let webController = WebViewController() webController.loadURL(NSURL(string: "foo")!) window?.rootViewController = webController ``` Call `addBridgeAPIObject()` to add the bridged JavaScript API to the web view. The JavaScript API will be accessible to any web pages that are loaded in the web view controller. ``` let webController = WebViewController() webController.addBridgeAPIObject() webController.loadURL(NSURL(string: "foo")!) window?.rootViewController = webController ``` To utilize the navigation JavaScript API you must provide a navigation controller for the web view controller. ``` let webController = WebViewController() webController.addBridgeAPIObject() webController.loadURL(NSURL(string: "foo")!) let navigationController = UINavigationController(rootViewController: webController) window?.rootViewController = navigationController ``` */ open class WebViewController: UIViewController { public enum AppearenceCause { case unknown, webPush, webPop, webModal, webDismiss, external } /// The URL that was loaded with `loadURL()` private(set) public var url: URL? /// The web view used to load and render the web content. @objc private(set) public lazy var webView: UIWebView = { let webView = UIWebView(frame: CGRect.zero) webView.delegate = self WebViewManager.addBridgedWebView(webView: webView) webView.translatesAutoresizingMaskIntoConstraints = false return webView }() fileprivate(set) public var bridgeContext: JSContext! = JSContext() private var storedScreenshotGUID: String? = nil private var firstLoadCycleCompleted = true fileprivate (set) var disappearedBy = AppearenceCause.unknown private var storedAppearence = AppearenceCause.webPush // TODO: make appearedFrom internal in Swift 2 with @testable private (set) public var appearedFrom: AppearenceCause { get { switch disappearedBy { case .webPush: return .webPop case .webModal: return .webDismiss default: return storedAppearence } } set { storedAppearence = newValue } } private lazy var placeholderImageView: UIImageView = { return UIImageView(frame: self.view.bounds) }() public var errorView: UIView? public var errorLabel: UILabel? public var reloadButton: UIButton? public weak var hybridAPI: HybridAPI? private (set) weak var externalPresentingWebViewController: WebViewController? private(set) public var externalReturnURL: URL? /// Handles web view controller events. @objc public weak var delegate: WebViewControllerDelegate? /// Set `false` to disable error message UI. public var showErrorDisplay = true /// An optional custom user agent string to be used in the header when loading the URL. @objc public var userAgent: String? /// Host for NSURLSessionDelegate challenge @objc public var challengeHost: String? lazy public var urlSession: URLSession = { let configuration: URLSessionConfiguration = URLSessionConfiguration.default if let agent = self.userAgent { configuration.httpAdditionalHeaders = [ "User-Agent": agent ] } let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) return session }() /// A NSURLSessionDataTask object used to load the URLs public var dataTask: URLSessionDataTask? /** Initialize a web view controller instance with a web view and JavaScript bridge. The newly initialized web view controller becomes the delegate of the web view. :param: webView The web view to use in the web view controller. :param: bridge The bridge instance to integrate int */ public required init(webView: UIWebView, context: JSContext) { super.init(nibName: nil, bundle: nil) self.bridgeContext = context self.webView = webView self.webView.delegate = self } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { if webView.delegate === self { webView.delegate = nil } } open override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white edgesForExtendedLayout = [] view.addSubview(placeholderImageView) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) switch appearedFrom { case .webPush, .webModal, .webPop, .webDismiss, .external: webView.delegate = self webView.removeFromSuperview() // remove webView from previous view controller's view webView.frame = view.bounds view.addSubview(webView) // add webView to this view controller's view // Pin web view top and bottom to top and bottom of view if #available(iOS 11.0, *) { webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true webView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true } else { self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[webView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["webView" : webView])) } // Pin web view sides to sides of view self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[webView]|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["webView" : webView])) view.removeDoubleTapGestures() if let storedScreenshotGUID = storedScreenshotGUID { placeholderImageView.image = UIImage.loadImageFromGUID(guid: storedScreenshotGUID) view.bringSubviewToFront(placeholderImageView) } case .unknown: break } } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) hybridAPI?.view.appeared() switch appearedFrom { case .webPop, .webDismiss: addBridgeAPIObject() case .webPush, .webModal, .external, .unknown: break } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) switch disappearedBy { case .webPop, .webDismiss, .webPush, .webModal: // only store screen shot when disappearing by web transition placeholderImageView.frame = webView.frame // must align frames for image capture if let screenshotImage = webView.captureImage() { placeholderImageView.image = screenshotImage storedScreenshotGUID = screenshotImage.saveImageToGUID() } view.bringSubviewToFront(placeholderImageView) webView.isHidden = true case .unknown: if isMovingFromParent { webView.isHidden = true } case .external: break } if disappearedBy != .webPop && isMovingFromParent { hybridAPI?.navigation.back() } hybridAPI?.view.disappeared() // needs to be called in viewWillDisappear not Did switch disappearedBy { // clear out parent reference to prevent the popping view's onAppear from // showing the web view too early case .webPop, .unknown where isMovingFromParent: hybridAPI?.parentViewController = nil default: break } } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) switch disappearedBy { case .webPop, .webDismiss, .webPush, .webModal, .external: // we're gone. dump the screenshot, we'll load it later if we need to. placeholderImageView.image = nil case .unknown: // we don't know how it will appear if we don't know how it disappeared appearedFrom = .unknown } } public final func showWebView() { webView.isHidden = false placeholderImageView.image = nil view.sendSubviewToBack(placeholderImageView) } // MARK: Request Loading /** Load the web view with the provided URL. :param: url The URL used to load the web view. */ @objc final public func load(url: URL) { self.dataTask?.cancel() // cancel any running task hybridAPI = nil firstLoadCycleCompleted = false self.url = url let request = self.request(url: url) self.dataTask = self.urlSession.dataTask(with: request as URLRequest) { (data, response, error) -> Void in DispatchQueue.main.async { if let httpError = error { // render error display if self.showErrorDisplay { self.renderFeatureErrorDisplayWithError(error: httpError, featureName: self.featureName(forError: httpError)) } } else if let urlResponse = response as? HTTPURLResponse { if urlResponse.statusCode >= 400 { // render error display if self.showErrorDisplay { let httpError = NSError(domain: "WebViewController", code: urlResponse.statusCode, userInfo: ["response" : urlResponse, NSLocalizedDescriptionKey : "HTTP Response Status \(urlResponse.statusCode)"]) self.renderFeatureErrorDisplayWithError(error: httpError, featureName: self.featureName(forError: httpError)) } } else if let data = data, let MIMEType = urlResponse.mimeType, let textEncodingName = urlResponse.textEncodingName, let url = urlResponse.url { self.webView.load(data, mimeType: MIMEType, textEncodingName: textEncodingName, baseURL: url) } } } } self.dataTask?.resume() } /** Create a request with the provided URL. :param: url The URL for the request. */ public func request(url: URL) -> URLRequest { return URLRequest(url: url) } fileprivate func didInterceptRequest(_ request: URLRequest) -> Bool { if appearedFrom == .external { // intercept requests that match external return URL if let url = request.url, shouldInterceptExternalURL(url: url) { returnFromExternal(returnURL: url) return true } } return false } // MARK: Web Controller Navigation /** Push a new web view controller on the navigation stack using the existing web view instance. Does not affect web view history. Uses animation. */ public func pushWebViewController() { pushWebViewController(options: nil) } /** Push a new web view controller on the navigation stack using the existing web view instance. Does not affect web view history. Uses animation. :param: hideBottomBar Hides the bottom bar of the view controller when true. */ public func pushWebViewController(options: WebViewControllerOptions?) { disappearedBy = .webPush let webViewController = newWebViewController(options: options) webViewController.appearedFrom = .webPush navigationController?.pushViewController(webViewController, animated: true) } /** Pop a web view controller off of the navigation. Does not affect web view history. Uses animation. */ public func popWebViewController() { disappearedBy = .webPop if let navController = self.navigationController, navController.viewControllers.count > 1 { navController.popViewController(animated: true) } } /** Present a navigation controller containing a new web view controller as the root view controller. The existing web view instance is reused. */ public func presentModalWebViewController(options: WebViewControllerOptions?) { disappearedBy = .webModal let webViewController = newWebViewController(options: options) webViewController.appearedFrom = .webModal let navigationController = UINavigationController(rootViewController: webViewController) navigationController.modalPresentationStyle = .overCurrentContext if let tabBarController = tabBarController { tabBarController.present(navigationController, animated: true, completion: nil) } else { present(navigationController, animated: true, completion: nil) } } /// Pops until there's only a single view controller left on the navigation stack. public func popToRootWebViewController(animated: Bool) { disappearedBy = .webPop let _ = navigationController?.popToRootViewController(animated: animated) } /** Return `true` to have the web view controller push a new web view controller on the stack for a given navigation type of a request. */ public func pushesWebViewControllerForNavigationType(navigationType: UIWebView.NavigationType) -> Bool { return false } public func newWebViewController(options: WebViewControllerOptions?) -> WebViewController { let webViewController = type(of: self).init(webView: webView, context: bridgeContext) webViewController.addBridgeAPIObject() webViewController.hybridAPI?.navigationBar.title = options?.title webViewController.hidesBottomBarWhenPushed = options?.tabBarHidden ?? false webViewController.hybridAPI?.view.onAppearCallback = options?.onAppearCallback?.asValidValue if let navigationBarButtons = options?.navigationBarButtons { webViewController.hybridAPI?.navigationBar.configureButtons(navigationBarButtons, callback: options?.navigationBarButtonCallback) } return webViewController } // MARK: External Navigation final var shouldDismissExternalURLModal: Bool { return !webView.canGoBack } final func shouldInterceptExternalURL(url: URL) -> Bool { if let requestedURLString = url.absoluteStringWithoutQuery, let returnURLString = externalReturnURL?.absoluteStringWithoutQuery, (requestedURLString as NSString).range(of: returnURLString).location != NSNotFound { return true } return false } // TODO: make internal after migrating to Swift 2 and @testable @discardableResult final public func presentExternalURL(options: ExternalNavigationOptions) -> WebViewController { let externalWebViewController = type(of: self).init() externalWebViewController.externalPresentingWebViewController = self externalWebViewController.addBridgeAPIObject() externalWebViewController.load(url: options.url) externalWebViewController.appearedFrom = .external externalWebViewController.externalReturnURL = options.returnURL externalWebViewController.title = options.title let backText = NSLocalizedString("Back", tableName: nil, bundle: Bundle.main, value: "", comment: "") externalWebViewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: backText, style: .plain, target: externalWebViewController, action: #selector(WebViewController.externalBackButtonTapped)) let doneText = NSLocalizedString("Done", tableName: nil, bundle: Bundle.main, value: "", comment: "") externalWebViewController.navigationItem.rightBarButtonItem = UIBarButtonItem(title: doneText, style: .done, target: externalWebViewController, action: #selector(WebViewController.dismissExternalURL)) let navigationController = UINavigationController(rootViewController: externalWebViewController) present(navigationController, animated: true, completion: nil) return externalWebViewController } @objc final func externalBackButtonTapped() { if shouldDismissExternalURLModal { externalPresentingWebViewController?.showWebView() dismissExternalURL() } webView.goBack() } final func returnFromExternal(returnURL url: URL) { externalPresentingWebViewController?.load(url: url) dismissExternalURL() } @objc final func dismissExternalURL() { dismiss(animated: true, completion: nil) } // MARK: Error UI private func createErrorLabel() -> UILabel? { let height = CGFloat(50) let y = view.bounds.midY - (height / 2) - 100 let label = UILabel(frame: CGRect(x: 0, y: y, width: view.bounds.width, height: height)) label.lineBreakMode = NSLineBreakMode.byWordWrapping label.numberOfLines = 0 label.textAlignment = NSTextAlignment.center label.backgroundColor = view.backgroundColor label.font = UIFont.boldSystemFont(ofSize: 12) return label } private func createReloadButton() -> UIButton? { let button = UIButton(type: .custom) let size = CGSize(width: 170, height: 38) let x = view.bounds.midX - (size.width / 2) var y = view.bounds.midY - (size.height / 2) if let label = errorLabel { y = label.frame.maxY + 20 } button.setTitle(NSLocalizedString("Try again", comment: "Try again"), for: UIControl.State.normal) button.frame = CGRect(x: x, y: y, width: size.width, height: size.height) button.backgroundColor = UIColor.lightGray button.titleLabel?.backgroundColor = UIColor.lightGray button.titleLabel?.textColor = UIColor.white return button } // MARK: Error Display Events /// Override to completely customize error display. Must also override `removeErrorDisplay` open func renderErrorDisplay(error: Error, message: String) { let errorView = UIView(frame: view.bounds) view.addSubview(errorView) self.errorView = errorView self.errorLabel = createErrorLabel() self.reloadButton = createReloadButton() if let errorLabel = errorLabel { errorLabel.text = NSLocalizedString(message, comment: "Web View Load Error") errorView.addSubview(errorLabel) } if let button = reloadButton { button.addTarget(self, action: #selector(WebViewController.reloadButtonTapped), for: .touchUpInside) errorView.addSubview(button) } } /// Override to handle custom error display removal. public func removeErrorDisplay() { errorView?.removeFromSuperview() errorView = nil showWebView() } /// Override to customize the feature name that appears in the error display. open func featureName(forError error: Error) -> String { return "This feature" } /// Override to customize the error message text. open func renderFeatureErrorDisplayWithError(error: Error, featureName: String) { let message = "Sorry!\n \(featureName) isn't working right now." webView.isHidden = true renderErrorDisplay(error: error, message: message) } /// Removes the error display and attempts to reload the web view. @objc open func reloadButtonTapped(sender: AnyObject) { guard let url = url else { return } load(url: url) } // MARK: Bridge API @objc open func addBridgeAPIObject() { if let bridgeObject = hybridAPI { bridgeContext.setObject(bridgeObject, forKeyedSubscript: HybridAPI.exportName as NSString) } else { let platform = HybridAPI(parentViewController: self) bridgeContext.setObject(platform, forKeyedSubscript: HybridAPI.exportName as NSString) hybridAPI = platform } } } // MARK: - NSURLSessionDelegate extension WebViewController: URLSessionDelegate { public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let host = challengeHost, let serverTrust = challenge.protectionSpace.serverTrust, challenge.protectionSpace.host == host { let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) } else { completionHandler(.performDefaultHandling, nil) } } } } // MARK: - UIWebViewDelegate extension WebViewController: UIWebViewDelegate { final public func webViewDidStartLoad(_ webView: UIWebView) { delegate?.webViewControllerDidStartLoad?(self) } public func webViewDidFinishLoad(_ webView: UIWebView) { delegate?.webViewControllerDidFinishLoad?(self) if self.errorView != nil { self.removeErrorDisplay() } } final public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool { if pushesWebViewControllerForNavigationType(navigationType: navigationType) { pushWebViewController() } if didInterceptRequest(request) { return false } else { return delegate?.webViewController?(self, shouldStartLoadWithRequest: request, navigationType: navigationType) ?? true } } final public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { if (error as NSError).code != NSURLErrorCancelled && showErrorDisplay { renderFeatureErrorDisplayWithError(error: error, featureName: featureName(forError: error)) } delegate?.webViewController?(self, didFailLoadWithError: error) } } // MARK: - JavaScript Context extension WebViewController: WebViewBridging { /** Update the bridge's JavaScript context by attempting to retrieve a context from the web view. */ final public func updateBridgeContext() { if let context = webView.javaScriptContext { configureBridgeContext(context: context) } else { print("Failed to retrieve JavaScript context from web view.") } } public func didCreateJavaScriptContext(context: JSContext) { configureBridgeContext(context: context) delegate?.webViewControllerDidCreateJavaScriptContext?(self, context: context) configureContext(context: context) if let hybridAPI = hybridAPI, let readyCallback = context.objectForKeyedSubscript("nativeBridgeReady") { if !readyCallback.isUndefined { readyCallback.call(withData: hybridAPI) } } } /** Explictly set the bridge's JavaScript context. */ final public func configureBridgeContext(context: JSContext) { bridgeContext = context } public func configureContext(context: JSContext) { addBridgeAPIObject() } } // MARK: - UIView Utils extension UIView { func captureImage() -> UIImage? { guard let context = UIGraphicsGetCurrentContext() else { return nil } UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0) layer.render(in: context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func removeDoubleTapGestures() { for view in self.subviews { view.removeDoubleTapGestures() } if let gestureRecognizers = gestureRecognizers { for gesture in gestureRecognizers { if let gesture = gesture as? UITapGestureRecognizer, gesture.numberOfTapsRequired == 2 { removeGestureRecognizer(gesture) } } } } } // MARK: - UIImage utils extension UIImage { // saves image to temp directory and returns a GUID so you can fetch it later. func saveImageToGUID() -> String? { let guid = UUID().uuidString DispatchQueue.global().async { if let imageData = self.jpegData(compressionQuality: 1.0), let filePath = UIImage.absoluteFilePath(guid: guid) { FileManager.default.createFile(atPath: filePath, contents: imageData, attributes: nil) } } return guid } class func loadImageFromGUID(guid: String) -> UIImage? { guard let filePath = UIImage.absoluteFilePath(guid: guid) else { return nil } return UIImage(contentsOfFile: filePath) } private class func absoluteFilePath(guid: String) -> String? { return NSURL(string: NSTemporaryDirectory())?.appendingPathComponent(guid)!.absoluteString } } // MARK: - JSContext Event @objc(WebViewBridging) public protocol WebViewBridging { func didCreateJavaScriptContext(context: JSContext) } private var globalWebViews = NSHashTable<UIWebView>.weakObjects() @objc(WebViewManager) public class WebViewManager: NSObject { // globalWebViews is a weak hash table. No need to remove items. @objc static public func addBridgedWebView(webView: UIWebView?) { if let webView = webView { globalWebViews.add(webView) } } } public extension NSObject { private struct AssociatedKeys { static var uniqueIDKey = "nsobject_uniqueID" } @objc var uniqueWebViewID: String! { if let currentValue = objc_getAssociatedObject(self, &AssociatedKeys.uniqueIDKey) as? String { return currentValue } else { let newValue = UUID().uuidString objc_setAssociatedObject(self, &AssociatedKeys.uniqueIDKey, newValue as NSString?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return newValue } } @objc func webView(_ webView: AnyObject, didCreateJavaScriptContext context: JSContext, forFrame frame: AnyObject) { let notifyWebviews = { () -> Void in let allWebViews = globalWebViews.allObjects for webView in allWebViews { let cookie = "__thgWebviewCookie\(webView.hash)" let js = "var \(cookie) = '\(cookie)'" webView.stringByEvaluatingJavaScript(from: js) let contextCookie = context.objectForKeyedSubscript(cookie).toString() if contextCookie == cookie { if let bridgingDelegate = webView.delegate as? WebViewBridging { bridgingDelegate.didCreateJavaScriptContext(context: context) } } } } let webFrameClass1: AnyClass! = NSClassFromString("WebFrame") // Most web-views let webFrameClass2: AnyClass! = NSClassFromString("NSKVONotifying_WebFrame") // Objc webviews accessed via swift if (type(of: frame) === webFrameClass1) || (type(of: frame) === webFrameClass2) { if Thread.isMainThread { notifyWebviews() } else { DispatchQueue.main.async(execute: notifyWebviews) } } } } extension URL { /// Get the absolute URL string value without the query string. var absoluteStringWithoutQuery: String? { var components = URLComponents(url: self, resolvingAgainstBaseURL: false) components?.query = nil return components?.string } }
04c8b5c0967dc3e2c5a74e560241b117
36.997555
226
0.652468
false
false
false
false
kzietek/SampleApp
refs/heads/master
KZSampleApp/Modules/RootNavigation/DemoFlowNavigation.swift
mit
1
// // DemoFlowNavigation.swift // KZSampleApp // // Created by Kamil Ziętek on 03.07.2017. // Copyright © 2017 Kamil Ziętek. All rights reserved. // import UIKit final class DemoFlowNavigation { let navigationController: UINavigationController init(with navigationController: UINavigationController) { self.navigationController = navigationController } func startFlow() { let factory = SelectionScreenFactory() factory.onSelection = { [weak self] (result) in self?.goToTable(with: result) } let selectionScreen = factory.createWithoutContext() navigationController.setViewControllers([selectionScreen], animated: false) } func goToTable(with result:SelectionResult) -> () { NSLog("Instantinate another view controller!") let factory = SelectionDetailsScreenFactory() let selectionDetailsVC = factory.create(for: result) push(selectionDetailsVC) } fileprivate func push(_ viewController: UIViewController) { navigationController.pushViewController(viewController, animated: true) } fileprivate func createRedScreen() -> (UIViewController) { let emptyScreen = UIViewController() emptyScreen.view = UIView() emptyScreen.view.backgroundColor = UIColor.red return emptyScreen } }
60668533239a0177e92a8a359f522dca
30.409091
83
0.682344
false
false
false
false
sweetmans/SMInstagramPhotoPicker
refs/heads/master
Demo/Demo/ViewController.swift
mit
1
// // ViewController.swift // Demo // // Created by MacBook Pro on 2017/4/21. // Copyright © 2017年 Sweetman, Inc. All rights reserved. // import UIKit import SMInstagramPhotoPicker import Photos class ViewController: UIViewController, SMPhotoPickerViewControllerDelegate { var picker: SMPhotoPickerViewController? @IBOutlet var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() /* First. It is importance to do this step. Be sour your app have Authorization to assecc your photo library. */ PHPhotoLibrary.requestAuthorization { (status) in if status == .authorized { self.picker = SMPhotoPickerViewController() self.picker?.delegate = self } } } //show picker. You need use present. @IBAction func show(_ sender: UIButton) { if picker != nil { present(picker!, animated: true, completion: nil) } } //No things to show here. @IBAction func nothings(_ sender: UIButton) { let alert = UIAlertController.init(title: "都说啥都没有啦,还点。。。", message: "Do not understan Chinaese? You need google translate.", preferredStyle: .alert) let cancel = UIAlertAction.init(title: "我错了😯", style: .cancel, handler: { (action) in }) alert.addAction(cancel) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } func didCancelPickingPhoto() { print("User cancel picking image") } func didFinishPickingPhoto(image: UIImage, meteData: [String : Any]) { imageView.image = image } }
2a1e206a58afc1a4a5faada941c013b8
22.776316
156
0.588268
false
false
false
false
AdamZikmund/strv
refs/heads/master
strv/strv/Classes/Handler/CitiesHandler.swift
mit
1
// // CitiesHandler.swift // strv // // Created by Adam Zikmund on 22.05.15. // Copyright (c) 2015 Adam Zikmund. All rights reserved. // import UIKit import Alamofire class CitiesHandler: NSObject { class func getCitiesForName(name : String, completionHandler : ([City]) -> Void){ let url = "http://api.geonames.org/searchJSON" let parameters = ["q" : name, "maxRows" : 10, "username" : "funn3r"] as [String : AnyObject] Alamofire.request(.GET, url, parameters: parameters, encoding: ParameterEncoding.URL) .responseJSON(options: NSJSONReadingOptions.MutableContainers) { (_, _, json, error) -> Void in if error == nil { if let json = json as? [String : AnyObject], geonames = json["geonames"] as? [[String : AnyObject]] { var cities = [City]() for geoname in geonames { if let cityName = geoname["name"] as? String, stateCode = geoname["countryCode"] as? String { cities.append(City(stateCode: stateCode, name: cityName)) } } completionHandler(cities) } } } } }
79ea1d770e393c1dd46c214699a51311
38.121212
121
0.529047
false
false
false
false
cconeil/Standard-Template-Protocols
refs/heads/master
STP/Moveable.swift
mit
1
// // Moveable.swift // Standard Template Protocols // // Created by Chris O'Neil on 9/20/15. // Copyright (c) 2015 Because. All rights reserved. // import UIKit public protocol Moveable { func makeMoveable() func didStartMoving() func didFinishMoving(velocity:CGPoint) func canMoveToX(x:CGFloat) -> Bool func canMoveToY(y:CGFloat) -> Bool func translateCenter(translation:CGPoint, velocity:CGPoint, startPoint:CGPoint, currentPoint:CGPoint) -> CGPoint func animateToMovedTransform(transform:CGAffineTransform) } public extension Moveable where Self:UIView { func makeMoveable() { var startPoint:CGPoint = CGPointZero var currentPoint:CGPoint = CGPointZero let gestureRecognizer = UIPanGestureRecognizer { [unowned self] (recognizer) -> Void in let pan = recognizer as! UIPanGestureRecognizer let velocity = pan.velocityInView(self.superview) let translation = pan.translationInView(self.superview) switch recognizer.state { case .Began: startPoint = self.center currentPoint = self.center self.didStartMoving() case .Ended, .Cancelled, .Failed: self.didFinishMoving(velocity) default: let point = self.translateCenter(translation, velocity:velocity, startPoint: startPoint, currentPoint: currentPoint) self.animateToMovedTransform(self.transformFromCenter(point, currentPoint: currentPoint)) currentPoint = point } } self.addGestureRecognizer(gestureRecognizer) } func animateToMovedTransform(transform:CGAffineTransform) { UIView.animateWithDuration(0.01) { () -> Void in self.transform = transform; } } func translateCenter(translation:CGPoint, velocity:CGPoint, startPoint:CGPoint, currentPoint:CGPoint) -> CGPoint { var point = startPoint if (self.canMoveToX(point.x + translation.x)) { point.x += translation.x } else { point.x = translation.x > 0.0 ? maximumPoint().x : minimumPoint().x } if (self.canMoveToY(point.y + translation.y)) { point.y += translation.y } else { point.y = translation.y > 0.0 ? maximumPoint().y : minimumPoint().y } return point } func transformFromCenter(center:CGPoint, currentPoint:CGPoint) -> CGAffineTransform { return CGAffineTransformTranslate(self.transform, center.x - currentPoint.x , center.y - currentPoint.y) } func didStartMoving() { return } func didFinishMoving(velocity:CGPoint) { return } func canMoveToX(x:CGFloat) -> Bool { if let superviewFrame = self.superview?.frame { let diameter = self.frame.size.width / 2.0 if x + diameter > superviewFrame.size.width { return false } if x - diameter < 0.0 { return false } } return true } func canMoveToY(y:CGFloat) -> Bool { if let superviewFrame = self.superview?.frame { let diameter = self.frame.size.height / 2.0 if y + diameter > superviewFrame.size.height { return false } if y - diameter < 0.0 { return false } } return true } func maximumPoint() -> CGPoint { if let superviewFrame = self.superview?.frame { let x = superviewFrame.size.width - self.frame.size.width / 2.0 let y = superviewFrame.size.height - self.frame.size.height / 2.0 return CGPointMake(x, y) } else { return CGPoint.zero } } func minimumPoint() -> CGPoint { let x = self.frame.size.width / 2.0 let y = self.frame.size.height / 2.0 return CGPointMake(x, y) } }
da7b88003c0fcdef9b591ac685fbb97f
31.024
132
0.598051
false
false
false
false
Legoless/ViewModelable
refs/heads/master
Demo/Demo/CarViewModel.swift
mit
1
// // CarViewModel.swift // Demo // // Created by Dal Rupnik on 09/07/16. // Copyright © 2016 Unified Sense. All rights reserved. // import Foundation import ViewModelable class CarViewModel : ViewModel { // // MARK: Input of the view model, must be // var car : Car? // // MARK: Output of view model, must be populated at all times, so screen can be // private(set) var loading : Bool = false private(set) var carDescription = "" private(set) var engineDescription = "" override func startSetup() { super.startSetup() // // View model should handle data, here we just pull a car if it was not set. // loading = true } override func startLoading() { loading = true carDescription = "Loading..." engineDescription = "" DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2.0) { self.loading = false if self.car == nil { self.car = Car.lamborghiniAvendator() } // // Call to finish loading, to ensure state transition is correct. // self.finishLoading() } } override func updateOutput() { // // This method is called multiple times during state transitions and // should just set output variables in a synchronous way. // if let car = car { carDescription = "\(car.make) \(car.model)" engineDescription = "\(car.engine.displacement) cc, \(car.engine.brakeHorsepower) BHP" } else if loading == true { carDescription = "Loading..." engineDescription = "" } else { carDescription = "Unknown" engineDescription = "" } } }
54674a09b88b2ecc6e992171cd492093
24.12987
98
0.525581
false
false
false
false
CatchChat/Yep
refs/heads/master
Yep/Views/MessageToolbar/VoiceRecordButton.swift
mit
1
// // VoiceRecordButton.swift // Yep // // Created by NIX on 15/4/2. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit final class VoiceRecordButton: UIView { var touchesBegin: (() -> Void)? var touchesEnded: ((needAbort: Bool) -> Void)? var touchesCancelled: (() -> Void)? var checkAbort: ((topOffset: CGFloat) -> Bool)? var abort = false var titleLabel: UILabel? var leftVoiceImageView: UIImageView? var rightVoiceImageView: UIImageView? enum State { case Default case Touched } var state: State = .Default { willSet { let color: UIColor switch newValue { case .Default: color = UIColor.yepMessageToolbarSubviewBorderColor() case .Touched: color = UIColor.yepTintColor() } layer.borderColor = color.CGColor leftVoiceImageView?.tintColor = color rightVoiceImageView?.tintColor = color switch newValue { case .Default: titleLabel?.textColor = tintColor case .Touched: titleLabel?.textColor = UIColor.yepTintColor() } } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) abort = false touchesBegin?() titleLabel?.text = NSLocalizedString("Release to Send", comment: "") } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event) touchesEnded?(needAbort: abort) titleLabel?.text = NSLocalizedString("Hold for Voice", comment: "") } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { super.touchesCancelled(touches, withEvent: event) touchesCancelled?() titleLabel?.text = NSLocalizedString("Hold for Voice", comment: "") } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesMoved(touches, withEvent: event) if let touch = touches.first { let location = touch.locationInView(touch.view) if location.y < 0 { abort = checkAbort?(topOffset: abs(location.y)) ?? false } } } override func didMoveToSuperview() { super.didMoveToSuperview() makeUI() } private func makeUI() { let titleLabel = UILabel() titleLabel.font = UIFont.systemFontOfSize(15.0) titleLabel.text = NSLocalizedString("Hold for Voice", comment: "") titleLabel.textAlignment = .Center titleLabel.textColor = self.tintColor self.titleLabel = titleLabel self.addSubview(titleLabel) titleLabel.translatesAutoresizingMaskIntoConstraints = false let leftVoiceImageView = UIImageView(image: UIImage.yep_iconVoiceLeft) leftVoiceImageView.contentMode = .Center leftVoiceImageView.tintColor = self.tintColor self.leftVoiceImageView = leftVoiceImageView self.addSubview(leftVoiceImageView) leftVoiceImageView.translatesAutoresizingMaskIntoConstraints = false let rightVoiceImageView = UIImageView(image: UIImage.yep_iconVoiceRight) rightVoiceImageView.contentMode = .Center rightVoiceImageView.tintColor = self.tintColor self.rightVoiceImageView = rightVoiceImageView self.addSubview(rightVoiceImageView) rightVoiceImageView.translatesAutoresizingMaskIntoConstraints = false let viewsDictionary: [String: AnyObject] = [ "leftVoiceImageView": leftVoiceImageView, "titleLabel": titleLabel, "rightVoiceImageView": rightVoiceImageView, ] let leftVoiceImageViewConstraintCenterY = NSLayoutConstraint(item: leftVoiceImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) let constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[leftVoiceImageView(20)][titleLabel][rightVoiceImageView(==leftVoiceImageView)]-10-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints([leftVoiceImageViewConstraintCenterY]) NSLayoutConstraint.activateConstraints(constraintsH) } }
8a9d42e3ec76dfbab23f19c1849cad55
31.167832
254
0.652391
false
false
false
false
brentsimmons/Frontier
refs/heads/master
BeforeTheRename/FrontierVerbs/FrontierVerbs/VerbTables/KBVerbs.swift
gpl-2.0
1
// // KBVerbs.swift // FrontierVerbs // // Created by Brent Simmons on 4/15/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import Foundation import FrontierData struct KBVerbs: VerbTable { private enum Verb: String { case optionKey = "optionkey" case cmdKey = "cmdkey" case shiftKey = "shiftkey" case controlKey = "controlkey" } static func evaluate(_ lowerVerbName: String, _ params: VerbParams, _ verbAppDelegate: VerbAppDelegate) throws -> Value { guard let verb = Verb(rawValue: lowerVerbName) else { throw LangError(.verbNotFound) } do { switch verb { case .optionKey: return try isOptionKeyDown(params) case .cmdKey: return try isCmdKeyDown(params) case .shiftKey: return try isShiftKeyDown(params) case .controlKey: return try isControlKeyDown(params) } } catch { throw error } } } private extension KBVerbs { static func isOptionKeyDown(_ params: VerbParams) throws -> Value { throw LangError(.unimplementedVerb) } static func isCmdKeyDown(_ params: VerbParams) throws -> Value { throw LangError(.unimplementedVerb) } static func isShiftKeyDown(_ params: VerbParams) throws -> Value { throw LangError(.unimplementedVerb) } static func isControlKeyDown(_ params: VerbParams) throws -> Value { throw LangError(.unimplementedVerb) } }
96974591ad364fd9fc981915d04feea2
19.893939
122
0.699057
false
false
false
false
ShiWeiCN/JESAlertView
refs/heads/master
Demo/Demo/JESAlertView/Maker/AlertMakerAlertPromptable.swift
mit
2
// // AlertMakerAlertPromptable.swift // Demo // // Created by Jerry on 17/10/2016. // Copyright © 2016 jerryshi. All rights reserved. // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // #if os(iOS) import UIKit #endif public class AlertMakerAlertPromptable: AlertMakerEditable { internal func prompt(of prompt: AlertPrompt, content: String, file: String, line: UInt) -> AlertMakerAlertPromptable { self.description.prompt = prompt if prompt.isTitlePrompt() { self.description.title = content } else { self.description.message = content } return self } @discardableResult public func title(_ title: String, _ file: String = #file, _ line: UInt = #line) -> AlertMakerAlertPromptable { return self.prompt(of: .title, content: title, file: file, line: line) } @discardableResult public func message(_ message: String, _ file: String = #file, _ line: UInt = #line) -> AlertMakerAlertPromptable { return self.prompt(of: .message, content: message, file: file, line: line) } }
1bdbdd65470fcc2f768aa7a7816a7513
30.594595
122
0.650128
false
false
false
false
wj2061/ios7ptl-swift3.0
refs/heads/master
ch24-DeepObjc/Runtime/Runtime/RunMyMsgSend.swift
mit
1
// // RunMyMsgSend.swift // Runtime // // Created by wj on 15/12/3. // Copyright © 2015年 wj. All rights reserved. // import Foundation typealias MyvoidIMP = @convention(c)(NSObject,Selector)->() func myMsgSend(_ receiver:NSObject,name:String){ let selector = sel_registerName(name) let methodIMP = class_getMethodImplementation(receiver.classForCoder, selector) let callBack = unsafeBitCast(methodIMP, to: MyvoidIMP.self) return callBack(receiver,Selector( name)) } func RunMyMsgSend(){ // let cla = objc_getClass("NSObject") as! AnyClass let object = NSObject() myMsgSend(object, name: "init") let description = object.description let cstr = description.utf8 print(cstr) }
30edf9e6ce0050165a31afabb0b06c1b
22.935484
83
0.687332
false
false
false
false
yangalex/WeMeet
refs/heads/master
WeMeet/View Controllers/ByUsernameViewController.swift
mit
1
// // ByUsernameViewController.swift // WeMeet // // Created by Alexandre Yang on 8/5/15. // Copyright (c) 2015 Alex Yang. All rights reserved. // import UIKit class ByUsernameViewController: UIViewController { @IBOutlet weak var usernameTextField: UITextField! var currentGroup: Group! override func viewDidLoad() { super.viewDidLoad() setupUsernameTextField() self.navigationController?.navigationBar.topItem?.backBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() } func setupUsernameTextField() { let borderColor = UIColor(red: 210/255, green: 210/255, blue: 210/255, alpha: 1.0) var bottomBorder = CALayer() bottomBorder.frame = CGRectMake(0, usernameTextField.frame.height-1, usernameTextField.frame.width, 1.0) bottomBorder.backgroundColor = borderColor.CGColor usernameTextField.layer.addSublayer(bottomBorder) var topBorder = CALayer() topBorder.frame = CGRectMake(0, 0, usernameTextField.frame.width, 1.0) topBorder.backgroundColor = borderColor.CGColor usernameTextField.layer.addSublayer(topBorder) // set a left margin (can also be used for images later on let leftView = UIView(frame: CGRectMake(0, 0, 10, usernameTextField.frame.height)) leftView.backgroundColor = usernameTextField.backgroundColor usernameTextField.leftView = leftView usernameTextField.leftViewMode = UITextFieldViewMode.Always } @IBAction func addPressed(sender: AnyObject) { var usersQuery = PFUser.query()! usersQuery.whereKey("username", equalTo: usernameTextField.text) usersQuery.findObjectsInBackgroundWithBlock { results, error in if let results = results as? [PFUser] { // if user was not found if results.count == 0 { let errorController = UIAlertController(title: "Invalid Username", message: "This user does not exist", preferredStyle: .Alert) errorController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(errorController, animated: true, completion: nil) } else { var userAlreadyInGroup: Bool = false for user in self.currentGroup!.users { if user.username == results[0].username { userAlreadyInGroup = true } } if userAlreadyInGroup { let errorController = UIAlertController(title: "Inavlid User", message: "User is already in this group", preferredStyle: .Alert) errorController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(errorController, animated: true, completion: nil) } else { self.currentGroup?.users.append(results[0]) self.currentGroup?.saveInBackground() self.navigationController?.popViewControllerAnimated(true) } } } } } @IBAction func cancelPressed(sender: AnyObject) { navigationController?.popViewControllerAnimated(true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
1321de968a8d2beffa0b71094224c1e1
41.72043
169
0.6222
false
false
false
false
TimurBK/Swift500pxMobile
refs/heads/develop
Swift500pxMobile/Code/Architecture/Services/Network/Networking.swift
mit
1
// // Networking.swift // Swift500pxMobile // // Created by Timur Kuchkarov on 05.03.17. // Copyright © 2017 Timur Kuchkarov. All rights reserved. // import Foundation import Moya import ReactiveCocoa import ReactiveSwift typealias ListUpdate<T> = ([T], String?) -> () class Networking { let provider: MoyaProvider<PXAPI> init() { self.provider = MoyaProvider<PXAPI>() } func fetchPhotos(page:Int64, category: String, completion:@escaping ListUpdate<PhotoModel>) { self.provider.request(.photos(page: page, category: category)) { result in switch result { case let .success(moyaResponse): let data = moyaResponse.data let statusCode = moyaResponse.statusCode if statusCode > 399 { completion([], "Error detected") return } let parsed: [PhotoModel]? = try? unbox(data: data, atKeyPath: "photos", allowInvalidElements: false) if parsed != nil { completion(parsed!, nil) } else { completion([], "Parse error") } // do something with the response data or statusCode case let .failure(error): print("error = \(error)") switch error { case .underlying(let nsError): // now can access NSError error.code or whatever // e.g. NSURLErrorTimedOut or NSURLErrorNotConnectedToInternet completion([], nsError.localizedDescription) return default: break } guard let error = error as? CustomStringConvertible else { completion([], "Unknown error") return } completion([], error.description) // this means there was a network failure - either the request // wasn't sent (connectivity), or no response was received (server // timed out). If the server responds with a 4xx or 5xx error, that // will be sent as a ".success"-ful response. } } } } enum PXAPI { case photos(page: Int64, category: String) } extension PXAPI : TargetType { public var parameterEncoding: ParameterEncoding { return URLEncoding.default } var baseURL: URL { return URL(string: Constants.API.Paths.baseAddress)! } var path : String { switch self { case .photos(_): return Constants.API.Paths.photosPath } } var method : Moya.Method { switch self { case .photos(_): return .get } } var parameters: [String: Any]? { switch self { case .photos(let page, let category): var params = [ Constants.API.ParametersKeys.apiKey: Constants.API.apiKey, Constants.API.ParametersKeys.feature: Constants.API.ParametersValues.feature, Constants.API.ParametersKeys.imageSize: Constants.API.ParametersValues.imageSize, Constants.API.ParametersKeys.page: page, Constants.API.ParametersKeys.pageSize: Constants.API.ParametersValues.pageSize] as [String : Any] if category != Constants.API.noFilterCategory { params[Constants.API.ParametersKeys.categoryFilter] = category } return params } } var sampleData: Data { switch self { case .photos(_): return "{}".utf8Encoded } } var task: Task { switch self { case .photos(_): return .request } } } private extension String { var urlEscaped: String { return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } var utf8Encoded: Data { return self.data(using: .utf8)! } }
735c4e654968ef4479afd0ee8b0a0248
24.390625
104
0.688923
false
false
false
false
ConradoMateu/Swift-Basics
refs/heads/master
Basic/Closures.playground/Contents.swift
apache-2.0
1
//Github: Conradomateu /* Closures: usually enclosed in {} (argument) -> (return type) Anonimous functions -> blocks in Objective-C and lambda in other languages */ func calculate(x:Int, _ y: Int, _ operation: (Int , Int) -> Int) -> Int{ return operation(x,y) } func divide(x: Int, y: Int) -> Int { return x / y } calculate(10, 5, divide) // Inlining -> passing the function as parameter calculate(10, 5, {(x: Int, y: Int) -> Int in return x / y }) // Type inference calculate(10, 5, {(x,y) in return x / y }) // Delete braces and the `return` statement. calculate(10, 5, {a, b in a / b}) // Shorthand arguments calculate(10, 5, {$0 / $1}) // Trailing closures: last argument in the function call.Closure argument just goes out of braces. calculate(3, 7){$0 * $1} // Capturing values (Apple Sample) func makeIncrementer(forIncrement amount: Int) -> () -> Int { var runningTotal = 0 func incrementer() -> Int { runningTotal += amount return runningTotal } return incrementer } let incrementByTen = makeIncrementer(forIncrement: 10) incrementByTen() incrementByTen() // Nonescaping Closures: Adding @noescape guarantees that the closure will not be stored somewhere, used at a later time, or used asynchronously. var foo: (()->Void)? func noEscapeClosure(@noescape preparations: () -> Void) { /* closure trying to scape foo = preparations tryToScape(){preparations} */ preparations() //noescape } func tryToScape(closure: () -> ()){ foo = closure } //Autoclosures: If you pass expression as an argument of a function, it will be automatically wrapped by `autoclosure`, also applies @noescape for that closure parameter. func num(n: () -> Int) -> Int { return n()*2 } var a = 10 var b = 15 num({a*b}) num(){a * b} //Trailing closures func num(@autoclosure n: () -> Int) -> Int { return n()*2 } var c = 10 var d = 15 num (c*d)
a7ad0d2cc43864cf8954463ad5466b42
20.21978
170
0.655101
false
false
false
false
ErAbhishekChandani/ACFloatingTextfield
refs/heads/master
Source-Swift/ACFloatingTextfield.swift
mit
1
// // ACFloatingTextfield.swift // ACFloatingTextField // // Created by Er Abhishek Chandani on 31/07/16. // Copyright © 2016 Abhishek. All rights reserved. // import UIKit @IBDesignable @objc open class ACFloatingTextfield: UITextField { fileprivate var bottomLineView : UIView? fileprivate var labelPlaceholder : UILabel? fileprivate var labelErrorPlaceholder : UILabel? fileprivate var showingError : Bool = false fileprivate var bottomLineViewHeight : NSLayoutConstraint? fileprivate var placeholderLabelHeight : NSLayoutConstraint? fileprivate var errorLabelHieght : NSLayoutConstraint? /// Disable Floating Label when true. @IBInspectable open var disableFloatingLabel : Bool = false /// Shake Bottom line when Showing Error ? @IBInspectable open var shakeLineWithError : Bool = true /// Change Bottom Line Color. @IBInspectable open var lineColor : UIColor = UIColor.black { didSet{ self.floatTheLabel() } } /// Change line color when Editing in textfield @IBInspectable open var selectedLineColor : UIColor = UIColor(red: 19/256.0, green: 141/256.0, blue: 117/256.0, alpha: 1.0){ didSet{ self.floatTheLabel() } } /// Change placeholder color. @IBInspectable open var placeHolderColor : UIColor = UIColor.lightGray { didSet{ self.floatTheLabel() } } /// Change placeholder color while editing. @IBInspectable open var selectedPlaceHolderColor : UIColor = UIColor(red: 19/256.0, green: 141/256.0, blue: 117/256.0, alpha: 1.0){ didSet{ self.floatTheLabel() } } /// Change Error Text color. @IBInspectable open var errorTextColor : UIColor = UIColor.red{ didSet{ self.labelErrorPlaceholder?.textColor = errorTextColor self.floatTheLabel() } } /// Change Error Line color. @IBInspectable open var errorLineColor : UIColor = UIColor.red{ didSet{ self.floatTheLabel() } } //MARK:- Set Text override open var text:String? { didSet { if showingError { self.hideErrorPlaceHolder() } floatTheLabel() } } override open var placeholder: String? { willSet { if newValue != "" { self.labelPlaceholder?.text = newValue } } } open var errorText : String? { willSet { self.labelErrorPlaceholder?.text = newValue } } //MARK:- UITtextfield Draw Method Override override open func draw(_ rect: CGRect) { super.draw(rect) self.upadteTextField(frame: CGRect(x:self.frame.minX, y:self.frame.minY, width:rect.width, height:rect.height)); } // MARK:- Loading From NIB override open func awakeFromNib() { super.awakeFromNib() self.initialize() } // MARK:- Intialization override public init(frame: CGRect) { super.init(frame: frame) self.initialize() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.initialize() } // MARK:- Text Rect Management override open func textRect(forBounds bounds: CGRect) -> CGRect { return CGRect(x:4, y:4, width:bounds.size.width, height:bounds.size.height); } override open func editingRect(forBounds bounds: CGRect) -> CGRect { return CGRect(x:4, y:4, width:bounds.size.width, height:bounds.size.height); } //MARK:- UITextfield Becomes First Responder override open func becomeFirstResponder() -> Bool { let result = super.becomeFirstResponder() self.textFieldDidBeginEditing() return result } //MARK:- UITextfield Resigns Responder override open func resignFirstResponder() -> Bool { let result = super.resignFirstResponder() self.textFieldDidEndEditing() return result } //MARK:- Show Error Label public func showError() { showingError = true; self.showErrorPlaceHolder(); } public func hideError() { showingError = false; self.hideErrorPlaceHolder(); floatTheLabel() } public func showErrorWithText(errorText : String) { self.errorText = errorText; self.labelErrorPlaceholder?.text = self.errorText showingError = true; self.showErrorPlaceHolder(); } } fileprivate extension ACFloatingTextfield { //MARK:- ACFLoating Initialzation. func initialize() -> Void { self.clipsToBounds = true /// Adding Bottom Line addBottomLine() /// Placeholder Label Configuration. addFloatingLabel() /// Error Placeholder Label Configuration. addErrorPlaceholderLabel() /// Checking Floatibility if self.text != nil && self.text != "" { self.floatTheLabel() } } //MARK:- ADD Bottom Line func addBottomLine(){ if bottomLineView?.superview != nil { return } //Bottom Line UIView Configuration. bottomLineView = UIView() bottomLineView?.backgroundColor = lineColor bottomLineView?.translatesAutoresizingMaskIntoConstraints = false self.addSubview(bottomLineView!) let leadingConstraint = NSLayoutConstraint.init(item: bottomLineView!, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0) let trailingConstraint = NSLayoutConstraint.init(item: bottomLineView!, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint.init(item: bottomLineView!, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0) bottomLineViewHeight = NSLayoutConstraint.init(item: bottomLineView!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 1) self.addConstraints([leadingConstraint,trailingConstraint,bottomConstraint]) bottomLineView?.addConstraint(bottomLineViewHeight!) self.addTarget(self, action: #selector(self.textfieldEditingChanged), for: .editingChanged) } @objc func textfieldEditingChanged(){ if showingError { hideError() } } //MARK:- ADD Floating Label func addFloatingLabel(){ if labelPlaceholder?.superview != nil { return } var placeholderText : String? = labelPlaceholder?.text if self.placeholder != nil && self.placeholder != "" { placeholderText = self.placeholder! } labelPlaceholder = UILabel() labelPlaceholder?.text = placeholderText labelPlaceholder?.textAlignment = self.textAlignment labelPlaceholder?.textColor = placeHolderColor labelPlaceholder?.font = UIFont.init(name: (self.font?.fontName ?? "helvetica")!, size: 12) labelPlaceholder?.isHidden = true labelPlaceholder?.sizeToFit() labelPlaceholder?.translatesAutoresizingMaskIntoConstraints = false self.attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: placeHolderColor]) if labelPlaceholder != nil { self.addSubview(labelPlaceholder!) } let leadingConstraint = NSLayoutConstraint.init(item: labelPlaceholder!, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5) let trailingConstraint = NSLayoutConstraint.init(item: labelPlaceholder!, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0) let topConstraint = NSLayoutConstraint.init(item: labelPlaceholder!, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0) placeholderLabelHeight = NSLayoutConstraint.init(item: labelPlaceholder!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 15) self.addConstraints([leadingConstraint,trailingConstraint,topConstraint]) labelPlaceholder?.addConstraint(placeholderLabelHeight!) } func addErrorPlaceholderLabel() -> Void { if self.labelErrorPlaceholder?.superview != nil{ return } labelErrorPlaceholder = UILabel() labelErrorPlaceholder?.text = self.errorText labelErrorPlaceholder?.textAlignment = self.textAlignment labelErrorPlaceholder?.textColor = errorTextColor labelErrorPlaceholder?.font = UIFont(name: (self.font?.fontName ?? "helvetica")!, size: 12) labelErrorPlaceholder?.sizeToFit() labelErrorPlaceholder?.translatesAutoresizingMaskIntoConstraints = false self.addSubview(labelErrorPlaceholder!) let trailingConstraint = NSLayoutConstraint.init(item: labelErrorPlaceholder!, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0) let topConstraint = NSLayoutConstraint.init(item: labelErrorPlaceholder!, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0) errorLabelHieght = NSLayoutConstraint.init(item: labelErrorPlaceholder!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0) self.addConstraints([trailingConstraint,topConstraint]) labelErrorPlaceholder?.addConstraint(errorLabelHieght!) } func showErrorPlaceHolder() { bottomLineViewHeight?.constant = 2; if self.errorText != nil && self.errorText != "" { errorLabelHieght?.constant = 15; UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: { self.bottomLineView?.backgroundColor = self.errorLineColor; self.layoutIfNeeded() }, completion: nil) }else{ errorLabelHieght?.constant = 0; UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: { self.bottomLineView?.backgroundColor = self.errorLineColor; self.layoutIfNeeded() }, completion: nil) } if shakeLineWithError { bottomLineView?.shake() } } func hideErrorPlaceHolder(){ showingError = false; if errorText == nil || errorText == "" { return } errorLabelHieght?.constant = 0; UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: { self.layoutIfNeeded() }, completion: nil) } //MARK:- Float & Resign func floatTheLabel() -> Void { DispatchQueue.main.async { if self.text == "" && self.isFirstResponder { self.floatPlaceHolder(selected: true) }else if self.text == "" && !self.isFirstResponder { self.resignPlaceholder() }else if self.text != "" && !self.isFirstResponder { self.floatPlaceHolder(selected: false) }else if self.text != "" && self.isFirstResponder { self.floatPlaceHolder(selected: true) } } } //MARK:- Upadate and Manage Subviews func upadteTextField(frame:CGRect) -> Void { self.frame = frame; self.initialize() } //MARK:- Float UITextfield Placeholder Label func floatPlaceHolder(selected:Bool) -> Void { labelPlaceholder?.isHidden = false if selected { bottomLineView?.backgroundColor = showingError ? self.errorLineColor : self.selectedLineColor; bottomLineViewHeight?.constant = 2; labelPlaceholder?.textColor = self.selectedPlaceHolderColor; self.attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: selectedPlaceHolderColor]) } else { bottomLineView?.backgroundColor = showingError ? self.errorLineColor : self.lineColor; bottomLineViewHeight?.constant = 1; self.labelPlaceholder?.textColor = self.placeHolderColor self.attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: placeHolderColor]) } if disableFloatingLabel == true { labelPlaceholder?.isHidden = true return } if placeholderLabelHeight?.constant == 15 { return } placeholderLabelHeight?.constant = 15; labelPlaceholder?.font = UIFont(name: (self.font?.fontName)!, size: 12) UIView.animate(withDuration: 0.2, animations: { self.layoutIfNeeded() }) } //MARK:- Resign the Placeholder func resignPlaceholder() -> Void { self.attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor: placeHolderColor]) bottomLineView?.backgroundColor = showingError ? self.errorLineColor : self.lineColor; bottomLineViewHeight?.constant = 1; if disableFloatingLabel { labelPlaceholder?.isHidden = true self.labelPlaceholder?.textColor = self.placeHolderColor; UIView.animate(withDuration: 0.2, animations: { self.layoutIfNeeded() }) return } placeholderLabelHeight?.constant = self.frame.height UIView.animate(withDuration: 0.3, animations: { self.labelPlaceholder?.font = self.font self.labelPlaceholder?.textColor = self.placeHolderColor self.layoutIfNeeded() }) { (finished) in self.labelPlaceholder?.isHidden = true self.placeholder = self.labelPlaceholder?.text } } //MARK:- UITextField Begin Editing. func textFieldDidBeginEditing() -> Void { if showingError { self.hideErrorPlaceHolder() } if !self.disableFloatingLabel { self.placeholder = "" } self.floatTheLabel() self.layoutSubviews() } //MARK:- UITextField Begin Editing. func textFieldDidEndEditing() -> Void { self.floatTheLabel() } } //MARK:- Shake extension UIView { func shake() { let animation = CAKeyframeAnimation(keyPath: "transform.translation.x") animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = 0.6 animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ] layer.add(animation, forKey: "shake") } }
78fec9039d1fdfe4ac798916c21708b9
35.435714
191
0.630661
false
false
false
false
volodg/iAsync.social
refs/heads/master
Pods/iAsync.network/Lib/JURLConnectionCallbacks.swift
mit
1
// // JURLConnectionCallbacks.swift // JNetwork // // Created by Vladimir Gorbenko on 25.09.14. // Copyright (c) 2014 EmbeddedSources. All rights reserved. // import Foundation public typealias JDidReceiveResponseHandler = (response: NSHTTPURLResponse) -> () public typealias JDidFinishLoadingHandler = (error: NSError?) -> () public typealias JDidReceiveDataHandler = (data: NSData) -> () public typealias JDidUploadDataHandler = (progress: Float) -> () public typealias JShouldAcceptCertificateForHost = (host: String) -> Bool
7ac1e21185a4bf27c751bde3ba483d67
36.733333
86
0.713781
false
false
false
false
ferdinandurban/HUDini
refs/heads/master
HUDini/Views/Base/HUDiniBaseAnimatedView.swift
mit
1
// // HUDiniBaseAnimatedView.swift // HUDini // // Created by Ferdinand Urban on 17/10/15. // Copyright © 2015 Ferdinand Urban. All rights reserved. // import UIKit public class HUDiniBaseAnimatedView: HUDiniBaseSquareView, HUDiniAnimation { let defaultAnimationShapeLayer: CAShapeLayer = { let defaultPath = UIBezierPath() defaultPath.moveToPoint(CGPointMake(4.0, 27.0)) defaultPath.addLineToPoint(CGPointMake(34.0, 56.0)) defaultPath.addLineToPoint(CGPointMake(88.0, 0.0)) let layer = CAShapeLayer() layer.frame = CGRectMake(3.0, 3.0, 88.0, 56.0) layer.path = defaultPath.CGPath layer.fillMode = kCAFillModeForwards layer.lineCap = kCALineCapRound layer.lineJoin = kCALineJoinRound layer.fillColor = nil layer.strokeColor = UIColor(red: 0.15, green: 0.15, blue: 0.15, alpha: 1.0).CGColor layer.lineWidth = 6.0 return layer }() var shapeLayer: CAShapeLayer? public override init() { super.init(frame: HUDiniBaseSquareView.defaultBaseFrame) shapeLayer = defaultAnimationShapeLayer } public init(withShape shape: HUDiniAnimatedShapeLayers.Code) { super.init(frame: HUDiniBaseSquareView.defaultBaseFrame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
efa59c68f588badd806c573b757f07a1
30.510638
93
0.630405
false
false
false
false
tlax/looper
refs/heads/master
looper/View/Camera/Filter/BlenderOverlay/VCameraFilterBlenderOverlayListAdd.swift
mit
1
import UIKit class VCameraFilterBlenderOverlayListAdd:UIButton { weak var layoutLeft:NSLayoutConstraint! private weak var image:UIImageView! private let kAnimationImagesDuration:TimeInterval = 0.15 private let kAnimationDuration:TimeInterval = 0.5 init() { super.init(frame:CGRect.zero) clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false backgroundColor = UIColor.clear let animatingImages:[UIImage] = [ #imageLiteral(resourceName: "assetCameraFilterBlenderAdd1"), #imageLiteral(resourceName: "assetCameraFilterBlenderAdd2"), #imageLiteral(resourceName: "assetCameraFilterBlenderAdd3"), #imageLiteral(resourceName: "assetCameraFilterBlenderAdd4"), #imageLiteral(resourceName: "assetCameraFilterBlenderAdd5"), #imageLiteral(resourceName: "assetCameraFilterBlenderAdd0")] let image:UIImageView = UIImageView() image.isUserInteractionEnabled = false image.translatesAutoresizingMaskIntoConstraints = false image.clipsToBounds = true image.contentMode = UIViewContentMode.center image.image = #imageLiteral(resourceName: "assetCameraFilterBlenderAdd0") image.animationImages = animatingImages image.animationDuration = kAnimationImagesDuration self.image = image addSubview(image) NSLayoutConstraint.equals( view:image, toView:self) } required init?(coder:NSCoder) { return nil } deinit { image.stopAnimating() } //MARK: public func animateHide() { guard let width:CGFloat = superview?.bounds.maxX else { return } let halfWidth:CGFloat = width / 2.0 let halfSelfWidth:CGFloat = bounds.midX let totalWidth:CGFloat = width + halfWidth - halfSelfWidth image.startAnimating() layoutLeft.constant = totalWidth UIView.animate( withDuration:kAnimationDuration, animations: { [weak self] in self?.superview?.layoutIfNeeded() }) { [weak self] (done:Bool) in self?.image.stopAnimating() } } func animateShow() { guard let width:CGFloat = superview?.bounds.maxX else { return } let selfWidth:CGFloat = bounds.maxX let remainLeft:CGFloat = width - selfWidth let marginLeft:CGFloat = remainLeft / 2.0 image.startAnimating() layoutLeft.constant = marginLeft UIView.animate( withDuration:kAnimationDuration, animations: { [weak self] in self?.superview?.layoutIfNeeded() }) { [weak self] (done:Bool) in self?.image.stopAnimating() } } }
58daec57930f562d35de95d37650b42e
26.350877
81
0.5805
false
false
false
false
raychrd/tada
refs/heads/master
tada/AppDelegate.swift
mit
1
// // AppDelegate.swift // tada // // Created by Ray on 15/1/24. // Copyright (c) 2015年 Ray. All rights reserved. // import UIKit import EventKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var eventStore:EKEventStore? var events:[EKReminder] = Array() var events2:[EKReminder] = Array() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. //UINavigationBar.clipsToBounds = true //UINavigationBar.appearance().tintColor = UIColor.whiteColor() /* UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "HelveticaNeue", size: 22)!, NSForegroundColorAttributeName : UIColor.whiteColor()] //UINavigationBar.appearance().clipsToBounds = true */ /* if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) { UINavigationBar.navigationController?.interactivePopGestureRecognizer.delegate = nil } */ UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) //appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate return true } /* func application(application: UIApplication , didReceiveLocalNotification notification: EKEventStoreChangedNotification) { alertView.show() } */ 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:. println("BYE") } }
1c22cc336a0cc7c83b4f7be2e98b6cae
41.166667
285
0.719064
false
false
false
false
ccrama/Slide-iOS
refs/heads/master
Slide for Reddit/AutoplayScrollViewHandler.swift
apache-2.0
1
// // AutoplayScrollViewHandler.swift // Slide for Reddit // // Created by Carlos Crane on 9/17/19. // Copyright © 2019 Haptic Apps. All rights reserved. // import UIKit //Abstracts logic for playing AutoplayBannerLinkCellView videos /* To enable on any vc, include this line func scrollViewDidScroll(_ scrollView: UIScrollView) { scrollDelegate.scrollViewDidScroll(scrollView) } */ protocol AutoplayScrollViewDelegate: class { func didScrollExtras(_ currentY: CGFloat) var isScrollingDown: Bool { get set } var lastScrollDirectionWasDown: Bool { get set } var lastYUsed: CGFloat { get set } var lastY: CGFloat { get set } var currentPlayingIndex: [IndexPath] { get set } func getTableView() -> UICollectionView } class AutoplayScrollViewHandler { weak var delegate: AutoplayScrollViewDelegate? init(delegate: AutoplayScrollViewDelegate) { self.delegate = delegate } func scrollViewDidScroll(_ scrollView: UIScrollView) { let currentY = scrollView.contentOffset.y guard let delegate = self.delegate else { return } delegate.isScrollingDown = currentY > delegate.lastY delegate.didScrollExtras(currentY) delegate.lastScrollDirectionWasDown = delegate.isScrollingDown let center = CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY) delegate.lastYUsed = currentY delegate.lastY = currentY if SettingValues.autoPlayMode == .ALWAYS || (SettingValues.autoPlayMode == .WIFI && LinkCellView.cachedCheckWifi) { let visibleVideoIndices = delegate.getTableView().indexPathsForVisibleItems let mapping: [(index: IndexPath, cell: LinkCellView)] = visibleVideoIndices.compactMap { index in // Collect just cells that are autoplay video if let cell = delegate.getTableView().cellForItem(at: index) as? LinkCellView { return (index, cell) } else { return nil } }.sorted { (item1, item2) -> Bool in delegate.isScrollingDown ? item1.index.row > item2.index.row : item1.index.row < item2.index.row } for currentIndex in delegate.currentPlayingIndex { if let currentCell = delegate.getTableView().cellForItem(at: currentIndex) as? LinkCellView, currentCell is AutoplayBannerLinkCellView || currentCell is GalleryLinkCellView { let videoViewCenter = currentCell.videoView.convert(currentCell.videoView.bounds, to: nil) //print("Diff for scroll down is \(abs(videoViewCenter.y - center.y)) and \(scrollView.frame.size.height / 4 )") if abs(videoViewCenter.midY - center.y) > scrollView.frame.size.height / 2 && currentCell.videoView.player != nil { currentCell.endVideos() } } } var chosenPlayItems = [(index: IndexPath, cell: LinkCellView)]() for item in mapping { if item.cell is AutoplayBannerLinkCellView || item.cell is GalleryLinkCellView { let videoViewCenter = item.cell.videoView.convert(item.cell.videoView.bounds, to: nil) if abs(videoViewCenter.midY - center.y) > scrollView.frame.size.height / 2 { continue } chosenPlayItems.append(item) } } for item in chosenPlayItems { if !delegate.currentPlayingIndex.contains(where: { (index2) -> Bool in return item.index.row == index2.row }) { item.cell.doLoadVideo() } } delegate.currentPlayingIndex = chosenPlayItems.map({ (item) -> IndexPath in return item.index }) } } func autoplayOnce(_ scrollView: UICollectionView) { guard let delegate = self.delegate else { return } if SettingValues.autoPlayMode == .ALWAYS || (SettingValues.autoPlayMode == .WIFI && LinkCellView.cachedCheckWifi) { let visibleVideoIndices = delegate.getTableView().indexPathsForVisibleItems let mapping: [(index: IndexPath, cell: LinkCellView)] = visibleVideoIndices.compactMap { index in // Collect just cells that are autoplay video if let cell = delegate.getTableView().cellForItem(at: index) as? LinkCellView { return (index, cell) } else { return nil } }.sorted { (item1, item2) -> Bool in delegate.isScrollingDown ? item1.index.row > item2.index.row : item1.index.row < item2.index.row } var chosenPlayItems = [(index: IndexPath, cell: LinkCellView)]() for item in mapping { if item.cell is AutoplayBannerLinkCellView { chosenPlayItems.append(item) } } for item in chosenPlayItems { if !delegate.currentPlayingIndex.contains(where: { (index2) -> Bool in return item.index.row == index2.row }) { (item.cell as! AutoplayBannerLinkCellView).doLoadVideo() } } delegate.currentPlayingIndex = chosenPlayItems.map({ (item) -> IndexPath in return item.index }) } } }
6e97c08c782b068b858ed0636f931dbd
40.345324
190
0.577867
false
false
false
false
apparata/ProjectKit
refs/heads/master
Sources/ProjectKit/Project File Objects/Base/ObjectID.swift
mit
1
import Foundation public class ObjectID { public let id: String public required init(id: String) { self.id = id } } extension ObjectID: Equatable { public static func ==(lhs: ObjectID, rhs: ObjectID) -> Bool { return lhs.id == rhs.id } } extension ObjectID: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(id) } }
695d9356217e1d0b6ebeba83916d2a17
14.807692
65
0.596107
false
false
false
false
KYawn/myiOS
refs/heads/master
Questions/Questions/ViewController.swift
apache-2.0
1
// // ViewController.swift // Questions // // Created by K.Yawn Xoan on 3/23/15. // Copyright (c) 2015 K.Yawn Xoan. All rights reserved. // import UIKit class ViewController: UIViewController,NSXMLParserDelegate{ required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBOutlet weak var btnSubmit: UIButton! @IBOutlet weak var tfInputAnswer: UITextField! @IBOutlet weak var lAnswerD: UILabel! @IBOutlet weak var lAnswerC: UILabel! @IBOutlet weak var lAnswerB: UILabel! @IBOutlet weak var lAnswerA: UILabel! @IBOutlet weak var lQuestion: UILabel! var questions:Array<Question> = [] var currentQuestion:Question var currentShowQuestion:Question override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var parser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("questions", ofType: "xml")!)) parser?.delegate = self parser?.parse() } func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) { if elementName == "question"{ currentQuestion = Question() questions.append(currentQuestion) currentQuestion.question = attributeDict["text"]! as String currentQuestion.right = attributeDict["right"]! as String } else if elementName == "answer"{ var tag = attributeDict["tag"]! as String if tag == "A"{ currentQuestion.answerA = attributeDict["text"]! as String }else if tag == "B"{ currentQuestion.answerB = attributeDict["text"]! as String }else if tag == "C"{ currentQuestion.answerC = attributeDict["text"]! as String }else if tag == "D"{ currentQuestion.answerD = attributeDict["text"]! as String } } } func parserDidEndDocument(parser: NSXMLParser!) { // println("Size of array:\(questions.count)") var q = questions[0] lQuestion.text = currentShowQuestion.question lAnswerA.text = currentShowQuestion.answerA lAnswerB.text = currentShowQuestion.answerB lAnswerC.text = currentShowQuestion.answerC lAnswerD.text = currentShowQuestion.answerD } @IBAction func btnPressed(sender: UIButton) { if tfInputAnswer.text == currentShowQuestion.right{ println("right") }else{ println("wrong") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
acc56135f074190d3faf84f96c621142
31.706522
181
0.609837
false
false
false
false
midoks/Swift-Learning
refs/heads/master
GitHubStar/GitHubStar/GitHubStar/Controllers/common/repos/GsRepoDetailViewController.swift
apache-2.0
1
// // GsRepoDViewController.swift // GitHubStar // // Created by midoks on 16/1/28. // Copyright © 2016年 midoks. All rights reserved. // import UIKit import SwiftyJSON //项目详情页 class GsRepoDetailViewController: GsHomeViewController { var _tableData:JSON = JSON.parse("") var _repoBranchNum = 1 var _repoReadmeData:JSON = JSON.parse("") var _fixedUrl = "" var isStar = false var asynGetStar = false var _rightButton:GsRepoButton? deinit { print("deinit GsRepoDetailViewController") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.removeNotify() //GitHubApi.instance.close() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.registerNotify() self.initView() } override func viewDidLoad() { super.viewDidLoad() _rightButton = GsRepoButton() self.navigationItem.rightBarButtonItem = _rightButton?.createButton(target: self) self.navigationItem.rightBarButtonItem?.isEnabled = false self.initView() } func initShareButton(){ print("test") } func initView(){ if _tableData != nil { initHeadView() initHeadIconView() } } func initHeadView(){ self.setAvatar(url: _tableData["owner"]["avatar_url"].stringValue) self.setName(name: _tableData["name"].stringValue) self.setDesc(desc: _tableData["description"].stringValue) } func initHeadIconView(){ var v = Array<GsIconView>() let stargazerts = GsIconView() stargazerts.key.text = _tableData["stargazers_count"].stringValue stargazerts.desc.text = "Stargazers" v.append(stargazerts) let watchers = GsIconView() //let subscribers_count = _tableData["subscribers_count"].int watchers.key.text = _tableData["subscribers_count"].stringValue watchers.desc.text = "Watchers" v.append(watchers) let forks = GsIconView() forks.key.text = _tableData["forks_count"].stringValue forks.desc.text = "Forks" v.append(forks) self.setIconView(icon: v) _headView.listClick = {(type) -> () in switch type { case 0: let stargazers = GsUserListViewController() stargazers.title = self.sysLang(key: "Stargazerts") let url = "/repos/" + self._tableData["full_name"].stringValue + "/stargazers" stargazers.setUrlData(url: url) self.push(v: stargazers) break case 1: let watchers = GsUserListViewController() watchers.title = self.sysLang(key: "Watchers") //watchers_count watchers.setUrlData(url: "/repos/" + self._tableData["full_name"].stringValue + "/subscribers") self.push(v: watchers) break case 2: let forks = GsRepoForksViewController() forks.title = self.sysLang(key: "Forks") forks.setUrlData(url: "/repos/" + self._tableData["full_name"].stringValue + "/forks") self.push(v: forks) break default:break } } } //MARK: - Private Method - func setTableData(data:JSON){ self.endRefresh() self._tableData = data self.initView() self.reloadData() } func setUrlData(url:String){ _fixedUrl = url } func setUrlWithData(data:JSON){ _fixedUrl = data["full_name"].stringValue //print(data["owner"]["avatar_url"].stringValue, data["name"].stringValue) self.setAvatar(url: data["owner"]["avatar_url"].stringValue) self.setName(name: data["name"].stringValue) } func setPUrlWithData(data:JSON){ _fixedUrl = data["parent"]["full_name"].stringValue self.setAvatar(url: data["owner"]["avatar_url"].stringValue) self.setName(name: data["name"].stringValue) } override func refreshUrl(){ super.refreshUrl() if _fixedUrl != "" { self.startRefresh() GitHubApi.instance.getRepo(name: _fixedUrl, callback: { (data) in self.endRefresh() self._tableData = data self.initView() self.reloadData() }) } } func reloadData(){ self.asynTask { self._tableView?.reloadData() self.postNotify() } } } extension GsRepoDetailViewController { override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) self.initView() } } //MARK: - UITableViewDelegate & UITableViewDataSource - extension GsRepoDetailViewController { private func numberOfSectionsInTableView(tableView: UITableView) -> Int { if _tableData.count == 0 { return 0 } if _tableData["homepage"].stringValue != "" { return 5 } return 4 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 0 } else if section == 1 { var i1 = 4 let v = self._tableData["parent"] if v.count>0 { i1 += 1 } return i1 } else if section == 2 { var i2 = 1 if self._tableData["has_issues"].boolValue || _tableData["open_issues"].intValue > 0 { i2 += 1 } if self._tableData.count > 0 { i2 += 1 } return i2 } else if section == 3 { return 3 } else if section == 4{ return 1 } return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 1 { if indexPath.row == 0 { let cell = GsRepo2RowCell(style: .default, reuseIdentifier: nil) cell.row1.setImage(UIImage(named: "repo_access"), for: .normal) let v1 = _tableData["private"].boolValue ? sysLang(key: "Private") : sysLang(key: "Public") cell.row1.setTitle(v1, for: .normal) cell.row2.setImage(UIImage(named: "repo_language"), for: .normal) let lang = _tableData["language"].stringValue == "" ? "N/A" : _tableData["language"].stringValue cell.row2.setTitle(lang, for: .normal) return cell } else if indexPath.row == 1 { let cell = GsRepo2RowCell(style: .default, reuseIdentifier: nil) cell.row1.setImage(UIImage(named: "repo_issues"), for: .normal) cell.row1.setTitle(_tableData["open_issues"].stringValue + sysLang(key: " Issues"), for: .normal ) cell.row2.setImage(UIImage(named: "repo_branch"), for: .normal) cell.row2.setTitle(String(_repoBranchNum) + sysLang(key: " Branches"), for: .normal) return cell } else if indexPath.row == 2 { let cell = GsRepo2RowCell(style: .default, reuseIdentifier: nil) cell.row1.setImage(UIImage(named: "repo_date"), for: .normal) let date = _tableData["created_at"].stringValue cell.row1.setTitle(gitTimeYmd(ctime: date), for: .normal) cell.row2.setImage(UIImage(named: "repo_size"), for: .normal) _ = _tableData["size"].float cell.row2.setTitle(gitSize(s: 1, i: _tableData["size"].int!), for: .normal) return cell } else if indexPath.row == 3 { let cell = UITableViewCell(style: .value1, reuseIdentifier: nil) cell.textLabel?.text = sysLang(key: "Owner") cell.textLabel?.font = UIFont.systemFont(ofSize: 14) cell.imageView?.image = UIImage(named: "repo_owner") cell.detailTextLabel?.text = _tableData["owner"]["login"].stringValue cell.accessoryType = .disclosureIndicator return cell } else if indexPath.row == 4 { let cell = UITableViewCell(style: .value1, reuseIdentifier: nil) cell.imageView?.image = UIImage(named: "repo_branch") cell.textLabel?.text = sysLang(key: "Forked from") cell.textLabel?.font = UIFont.systemFont(ofSize: 14) cell.detailTextLabel?.text = _tableData["parent"]["owner"]["login"].stringValue cell.accessoryType = .disclosureIndicator return cell } } else if indexPath.section == 2 { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.font = UIFont.systemFont(ofSize: 14) if indexPath.row == 0 { cell.textLabel?.text = sysLang(key: "Events") cell.imageView?.image = UIImage(named: "repo_events") } else { if _tableData["has_issues"].boolValue || _tableData["open_issues"].intValue > 0 { if indexPath.row == 1 { cell.textLabel?.text = sysLang(key: "Issues") cell.imageView?.image = UIImage(named: "repo_issues") } else if indexPath.row == 2 { cell.textLabel?.text = sysLang(key: "Readme") cell.imageView?.image = UIImage(named: "repo_readme") } } else { cell.textLabel?.text = sysLang(key: "Readme") cell.imageView?.image = UIImage(named: "repo_readme") } } cell.accessoryType = .disclosureIndicator return cell } else if indexPath.section == 3 { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.font = UIFont.systemFont(ofSize: 14) if indexPath.row == 0 { cell.textLabel?.text = "Commits" cell.imageView?.image = UIImage(named: "repo_commits") } else if indexPath.row == 1 { cell.textLabel?.text = "Pull Requests" cell.imageView?.image = UIImage(named: "repo_pullrequests") } else if indexPath.row == 2 { cell.textLabel?.text = "Source" cell.imageView?.image = UIImage(named: "repo_source") } cell.accessoryType = .disclosureIndicator return cell } else if indexPath.section == 4 { let cell = UITableViewCell(style: .value1, reuseIdentifier: nil) cell.imageView?.image = UIImage(named: "repo_website") cell.textLabel?.text = "Website" cell.textLabel?.font = UIFont.systemFont(ofSize: 14) cell.accessoryType = .disclosureIndicator return cell } let cell = UITableViewCell(style: .default, reuseIdentifier: nil) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 1 { if indexPath.row == 3 { tableView.deselectRow(at: indexPath as IndexPath, animated: true) let author = GsUserHomeViewController() author.setUrlWithData(data: _tableData["owner"]) self.push(v: author) } else if indexPath.row == 4 { tableView.deselectRow(at: indexPath as IndexPath, animated: true) let forked_from = GsRepoDetailViewController() forked_from.setPUrlWithData(data: _tableData) self.push(v: forked_from) } } else { tableView.deselectRow(at: indexPath as IndexPath, animated: true) if indexPath.section == 2 { let cell = tableView.cellForRow(at: indexPath as IndexPath) let cellText = cell?.textLabel?.text if cellText == sysLang(key: "Events") { let event = GsEventsViewController() event.setUrlData(url: "/repos/" + _tableData["full_name"].stringValue + "/events") self.push(v: event) } else if cellText == sysLang(key: "Issues") { let issue = GsIssuesViewController() let url = GitHubApi.instance.buildUrl(path: "/repos/" + _tableData["full_name"].stringValue + "/issues") issue.setUrlData(url: url) self.push(v: issue) } else if cellText == sysLang(key: "Readme") { let repoReadme = GsRepoReadmeViewController() repoReadme.setReadmeData(data: _repoReadmeData) self.push(v: repoReadme) } } else if indexPath.section == 3 { if indexPath.row == 0 { //go to commit list info page,if have only one branch. // if _repoBranchNum == 1 { // let repoCommitMaster = GsCommitsListViewController() // let url = GitHubApi.instance().buildUrl("/repos/" + _tableData["full_name"].stringValue + "/commits?sha=master") // repoCommitMaster.setUrlData(url) // self.push(repoCommitMaster) // } else { //go to commit branch page let repoCommits = GsCommitsViewController() let url = GitHubApi.instance.buildUrl(path: "/repos/" + _tableData["full_name"].stringValue + "/branches") repoCommits.setUrlData( url: url ) self.push(v: repoCommits) //} } else if indexPath.row == 1 { let repoPull = GsPullListViewController() repoPull.setUrlData( url: "/repos/" + _tableData["full_name"].stringValue + "/pulls" ) self.push(v: repoPull) } else if indexPath.row == 2 { let repoSource = GsRepoSourceViewController() repoSource.setUrlData( url: "/repos/" + _tableData["full_name"].stringValue + "/branches" ) self.push(v: repoSource) } } else if indexPath.section == 4 { if indexPath.row == 0 { let url = _tableData["homepage"].stringValue UIApplication.shared.openURL(NSURL(string: url)! as URL) } } } } } //MARK: - 通知相关方法 - extension GsRepoDetailViewController{ func registerNotify(){ let center = NotificationCenter.default center.addObserver(self, selector: Selector(("getRepoBranch:")), name: NSNotification.Name(rawValue: "getRepoBranch"), object: nil) center.addObserver(self, selector: Selector(("getRepoReadme:")), name: NSNotification.Name(rawValue: "getRepoReadme"), object: nil) center.addObserver(self, selector: Selector(("getRepoStarStatus:")), name: NSNotification.Name(rawValue: "getRepoStarStatus"), object: nil) } func removeNotify(){ let center = NotificationCenter.default center.removeObserver(self, name: NSNotification.Name(rawValue: "getRepoBranch"), object: nil) center.removeObserver(self, name: NSNotification.Name(rawValue: "getRepoReadme"), object: nil) center.removeObserver(self, name: NSNotification.Name(rawValue: "getRepoStarStatus"), object: nil) } //添加通知 func postNotify(){ let center = NotificationCenter.default center.post(name: NSNotification.Name(rawValue: "getRepoBranch"), object: nil) center.post(name: NSNotification.Name(rawValue: "getRepoReadme"), object: nil) if self.isLogin() { center.post(name: NSNotification.Name(rawValue: "getRepoStarStatus"), object: nil) } } //获取项目分支数据 func getRepoBranch(notify:NSNotification){ let branchValue = self._tableData["full_name"].stringValue let repoBranch = "/repos/" + branchValue + "/branches" //print(repoBranch) GitHubApi.instance.urlGet(url: repoBranch) { (data, response, error) -> Void in if data != nil { var count = self.gitJsonParse(data: data!).count if response != nil { let rep = response as! HTTPURLResponse if rep.allHeaderFields["Link"] != nil { let r = self.gitParseLink(urlLink: rep.allHeaderFields["Link"] as! String) if r.lastPage != "" { let pageCount = r.lastNum - 1 GitHubApi.instance.webGet(absoluteUrl: r.lastPage, callback: { (data, response, error) -> Void in if data != nil { count = pageCount*30 + self.gitJsonParse(data: data!).count } self._repoBranchNum = count self._tableView?.reloadData() self.asynIsLoadSuccessToEnableEdit() }) } } else { self._repoBranchNum = count self._tableView?.reloadData() } } } } } //get repo readme func getRepoReadme(notify:NSNotification){ let repoReadme = "/repos/" + _tableData["full_name"].stringValue + "/readme" GitHubApi.instance.urlGet(url: repoReadme) { (data, response, error) -> Void in if data != nil { let _dataJson = self.gitJsonParse(data: data!) self._repoReadmeData = _dataJson self._tableView?.reloadData() } } } //get repo star status func getRepoStarStatus(notify:NSNotification){ self.isStar = false self.asynGetStar = false let args = "/user/starred/" + _tableData["full_name"].stringValue let url = GitHubApi.instance.buildUrl(path: args) //print(url) GitHubApi.instance.webGet(absoluteUrl: url, callback: { (data, response, error) in self.asynGetStar = true self.asynIsLoadSuccessToEnableEdit() if data != nil { //print(response) let resp = response as! HTTPURLResponse if resp.statusCode == 204 { if !self.isStar { self.isStar = true self.setStarStatus(status: true) } } } }) } func asynIsLoadSuccessToEnableEdit(){ if (self.asynGetStar){ MDTask.shareInstance.asynTaskFront(callback: { self.navigationItem.rightBarButtonItem?.isEnabled = true }) } } } class GsRepoButton: NSObject { var _target: GsRepoDetailViewController? func createButton(target: GsRepoDetailViewController) -> UIBarButtonItem { _target = target let button = UIButton() button.frame = CGRect(x: 0.0, y: 0.0, width: 30.0, height: 30.0) button.setImage(UIImage(named: "repo_share"), for: .normal) button.addTarget(self, action: Selector(("buttonTouched:")), for: UIControlEvents.touchUpInside) return UIBarButtonItem(customView: button) } func buttonTouched(sender: AnyObject) { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) if _target!.isStar { let unstar = UIAlertAction(title: "Unstar This Repo", style: .default) { (UIAlertAction) in let args = "/user/starred/" + self._target!._tableData["full_name"].stringValue let url = GitHubApi.instance.buildUrl(path: args) GitHubApi.instance.delete(url: url, callback: { (data, response, error) in if data != nil { let resp = response as! HTTPURLResponse if resp.statusCode == 204 { self._target?.isStar = false self._target?.removeStarStatus() self._target?.showTextWithTime(msg: "SUCCESS", time: 2) } else { self._target?.isStar = true self._target?.showTextWithTime(msg: "FAIL", time: 2) } } self._target!.asynIsLoadSuccessToEnableEdit() }) } alert.addAction(unstar) } else { let star = UIAlertAction(title: "Star This Repo", style: .default) { (UIAlertAction) in let args = "/user/starred/" + self._target!._tableData["full_name"].stringValue let url = GitHubApi.instance.buildUrl(path: args) GitHubApi.instance.put(url: url, callback: { (data, response, error) in if data != nil { let resp = response as! HTTPURLResponse if resp.statusCode == 204 { self._target?.isStar = true self._target?.setStarStatus(status: true) self._target?.showTextWithTime(msg: "SUCCESS", time: 2) } else { self._target?.isStar = false self._target?.showTextWithTime(msg: "FAIL", time: 2) } } self._target!.asynIsLoadSuccessToEnableEdit() }) } alert.addAction(star) } let cancal = UIAlertAction(title: "Cancel", style: .cancel) { (UIAlertAction) in } alert.addAction(cancal) _target!.present(alert, animated: true) { } } }
8440a880802ee8c360312279704e41d9
37.334395
158
0.504694
false
false
false
false
bixubot/AcquainTest
refs/heads/master
ChatRoom/ChatRoom/CustomFoldingCell.swift
mit
1
// // CustomFoldingCell.swift // ChatRoom // // Created by Mutian on 4/28/17. // Copyright © 2017 Binwei Xu. All rights reserved. // import UIKit import Firebase class CustomFoldingCell: FoldingCell { @IBOutlet weak var closeNumberLabel: UILabel! @IBOutlet weak var openNumberLabel: UILabel! var number: Int = 0 { didSet { closeNumberLabel.text = String(number) openNumberLabel.text = String(number) } } override func awakeFromNib() { foregroundView.layer.cornerRadius = 10 foregroundView.layer.masksToBounds = true super.awakeFromNib() } override func animationDuration(_ itemIndex:NSInteger, type:AnimationType)-> TimeInterval { let durations = [0.26, 0.2, 0.2] return durations[itemIndex] } } // MARK: Actions extension CustomFoldingCell { @IBAction func buttonHandler(_ sender: AnyObject) { print("tap") } }
651e5dcbdf01e413002de9a6655d5545
22.093023
95
0.623364
false
false
false
false
fsproru/ScoutReport
refs/heads/master
ScoutReport/FeedViewController.swift
mit
1
import UIKit class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! let refreshControl = UIRefreshControl() var posts: [InstagramPost] = [] var instagramClient: InstagramClientType = InstagramClient() var presenter: PresenterType = Presenter() override func viewDidLoad() { setupTableView() setupRefreshControl() authenticateWithInstagramIfNeeded() } override func viewWillAppear(animated: Bool) { fetchContentIfPossible() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier("instagramPostCell") { if let imageURL = NSURL(string: posts[indexPath.row].imageURLString), imageData = NSData(contentsOfURL: imageURL) { cell.imageView?.image = UIImage(data: imageData) } return cell } return UITableViewCell() } func fetchContentIfPossible() { if let instagramUsername = Suspect.chosenSuspect?.instagramUsername where Suspect.chosenSuspect?.instagramAccessToken != nil { instagramClient.getContent(username: instagramUsername, success: { [weak self] instagramPosts in self?.refreshPosts(instagramPosts) }, failure: { error in } ) } } private func authenticateWithInstagramIfNeeded() { if Suspect.chosenSuspect?.instagramAccessToken == nil { let instagramAuthViewController = UIStoryboard.loadViewController(storyboardName: "Feed", identifier: "instagramAuthViewController") as! InstagramAuthViewController presenter.present(underlyingViewController: self, viewControllerToPresent: instagramAuthViewController, animated: true, completion: nil) } } private func refreshPosts(instagramPosts: [InstagramPost]) { posts = instagramPosts dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() if self.refreshControl.refreshing { self.refreshControl.endRefreshing() } }) } private func setupTableView() { tableView.delegate = self tableView.dataSource = self } private func setupRefreshControl() { refreshControl.addTarget(self, action: "fetchContentIfPossible", forControlEvents: .ValueChanged) tableView.addSubview(refreshControl) } }
789ef1161a4fd0f15ab01ae33ab6782e
36.671233
176
0.662423
false
false
false
false
nsagora/validation-toolkit
refs/heads/main
Sources/Constraints/Standard/RequiredConstraint.swift
mit
1
import Foundation /** A `Constraint` that check whether the input collection is empty. ```swift enum Failure: Error { case required case invalidEmail } ``` ```swift let constraint = RequiredConstraint<String, Failure>(error: .required) let result = constraint.evaluate(with: "[email protected]") ``` */ public struct RequiredConstraint<T: Collection, E: Error>: Constraint { private let predicate = RequiredPredicate<T>() private let errorBuilder: (T) -> E /** Returns a new `RequiredConstraint` instance. ```swift enum Failure: Error { case required case invalidEmail } ``` ```swift let constraint = RequiredConstraint<String, Failure>(error: .required) let result = constraint.evaluate(with: "[email protected]") ``` - parameter error: An `Error` that describes why the evaluation has failed. */ public init(error: E) { self.errorBuilder = { _ in return error } } /** Returns a new `RequiredConstraint` instance. ```swift enum Failure: Error { case required case invalidEmail } ``` ```swift let constraint = RequiredConstraint<String, Failure> { _ in .required } let result = constraint.evaluate(with: "[email protected]") ``` - parameter error: A generic closure that dynamically builds an `Error` to describe why the evaluation has failed. */ public init(errorBuilder: @escaping (T) -> E) { self.errorBuilder = errorBuilder } /** Returns a new `RequiredConstraint` instance. ```swift enum Failure: Error { case required case invalidEmail } ``` ```swift let constraint = RequiredConstraint<String, Failure> { .required } let result = constraint.evaluate(with: "[email protected]") ``` - parameter error: A generic closure that dynamically builds an `Error` to describe why the evaluation has failed. */ public init(errorBuilder: @escaping () -> E) { self.errorBuilder = { _ in return errorBuilder() } } /** Evaluates whether the input collection is empty or not. - parameter input: The input collection to be validated. - returns: `.success` if the input is valid,`.failure` containing the `Summary` with the provided `Error`. */ public func evaluate(with input: T) -> Result<Void, Summary<E>> { let result = predicate.evaluate(with: input) if result { return .success(()) } let error = errorBuilder(input) let summary = Summary(errors: [error]) return .failure(summary) } }
8e0fa587d4d79ec9d7d35e03e4faa71e
26.196078
119
0.604182
false
false
false
false
danieldias25/SDCollectionView-Swift
refs/heads/master
Example/Example/SDPresentationView.swift
mit
1
// // PresentationView.swift // ScrollTest // // Created by Daniel Dias on 19/10/17. // Copyright © 2017 Daniel.Dias. All rights reserved. // import UIKit class SDPresentationView: UIView { var imageView: UIImageView? var blackView: UIView? var x:CGFloat = 0.0 var y:CGFloat = 0.0 override init(frame:CGRect) { super.init(frame:frame) } init(frame:CGRect ,AndImage image:UIImage, AndSize size: CGSize, AndScale scale: CGFloat){ self.blackView = UIView(frame: frame) self.blackView?.backgroundColor = UIColor.black self.blackView?.alpha = 0.0 self.imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height)) self.imageView?.transform = CGAffineTransform(scaleX: scale, y: scale) self.x = (frame.size.width - (self.imageView?.frame.size.width)!)/2.0 self.y = (frame.size.height - (self.imageView?.frame.size.height)!)/2.0 let height = self.imageView?.frame.size.height let width = self.imageView?.frame.size.width self.imageView?.frame = CGRect(x: self.x, y: self.y, width: width!, height: height!) self.imageView?.backgroundColor = UIColor.clear self.imageView?.image = image super.init(frame: frame) self.backgroundColor = UIColor.clear self.addSubview(self.blackView!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { UIView.animate(withDuration: 0.5, animations: { self.alpha = 0 }) { (true) in self.removeFromSuperview() } } func presentImage() { let x = (frame.size.width - CGFloat(1))/2.0 let y = (frame.size.height - CGFloat(1))/2.0 let animateView = UIView(frame: CGRect(x: x, y: y, width: 1.00, height: 1.00)) animateView.backgroundColor = UIColor.white animateView.alpha = 0.85 self.addSubview(animateView) let horizontal = (self.imageView?.frame.size.width)! + CGFloat(5) let vertical = (self.imageView?.frame.size.height)! + CGFloat(5) UIView.animate(withDuration: 0.5, animations: { animateView.transform = CGAffineTransform(scaleX: horizontal, y: 1) }, completion: { (true) in UIView.animate(withDuration: 0.5, animations: { animateView.transform = CGAffineTransform(scaleX: horizontal, y: vertical) }, completion: { (true) in self.imageView?.alpha = 0 self.addSubview(self.imageView!) UIView.animate(withDuration: 0.2, animations: { self.imageView?.alpha = 1 }, completion: nil) }) }) } }
29482dd00f0316d618f1aab3db76b3de
30.690722
103
0.56799
false
false
false
false
BradLarson/GPUImage2
refs/heads/develop
GPUImage-Swift/examples/Linux-RPi/SimpleVideoFilter/Source/main.swift
apache-2.0
4
import GPUImage // For now, rendering requires the window to be created first let renderWindow = RPiRenderWindow(width:1280, height:720) let camera = V4LCamera(size:Size(width:1280.0, height:720.0)) let edgeDetection = SobelEdgeDetection() camera --> edgeDetection --> renderWindow var terminate:Int = 0 camera.startCapture() while (terminate == 0) { camera.grabFrame() }
5fcba08716f13b7f8d0f4acec74708ba
24.133333
61
0.757979
false
false
false
false
quran/quran-ios
refs/heads/main
Tests/BatchDownloaderTests/DownloadingObserverCollectionTests.swift
apache-2.0
1
// // DownloadingObserverCollectionTests.swift // // // Created by Mohamed Afifi on 2022-02-02. // @testable import BatchDownloader import XCTest class DownloadingObserverCollectionTests: XCTestCase { private var observers: DownloadingObserverCollection<AudioDownload>! private var recorder: DownloadObserversRecorder<AudioDownload>! private let item1 = AudioDownload(name: "item1") private let item2 = AudioDownload(name: "item2") private let item3 = AudioDownload(name: "item3") override func setUpWithError() throws { observers = DownloadingObserverCollection() recorder = DownloadObserversRecorder(observer: observers) } private func waitForProgressUpdates() { // wait for the main thread dispatch async as completion is called on main thread wait(for: DispatchQueue.main) } func testStartingDownloadCompletedSuccessfully() { XCTAssertEqual(recorder.diffSinceLastCalled, []) // prepare response let response = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil) response.progress.totalUnitCount = 1 // start downloading observers.observe([item1, item2, item3], responses: [:]) observers.startDownloading(item: item2, response: response) XCTAssertEqual(recorder.diffSinceLastCalled, [ .itemsUpdated([item1, item2, item3]), .itemsUpdated([item1, item2, item3]), ]) waitForProgressUpdates() // at the start, we get 0% XCTAssertEqual(recorder.diffSinceLastCalled, [ .progress(item2, 1, 0), ]) response.progress.completedUnitCount = 0.5 response.progress.completedUnitCount = 1 waitForProgressUpdates() // get 50% then 100% XCTAssertEqual(recorder.diffSinceLastCalled, [ .progress(item2, 1, 0.5), .progress(item2, 1, 1.0), ]) response.fulfill() waitForProgressUpdates() XCTAssertEqual(recorder.diffSinceLastCalled, [ .itemsUpdated([item1, item2, item3]), .completed(item2, 1), ]) } func testStartingDownloadFailedToComplete() { // start downloading and immediately fail it let response = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil) response.progress.totalUnitCount = 1 observers.observe([item1, item2, item3], responses: [:]) observers.startDownloading(item: item3, response: response) response.reject(FileSystemError(error: CocoaError(.fileWriteOutOfSpace))) waitForProgressUpdates() XCTAssertEqual(recorder.diffSinceLastCalled, [ .itemsUpdated([item1, item2, item3]), .itemsUpdated([item1, item2, item3]), .progress(item3, 2, 0), // failed .itemsUpdated([item1, item2, item3]), .failed(item3, 2, FileSystemError.noDiskSpace as NSError), ]) } func testObserveMethod() { let response1 = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil) let response2 = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil) let response3 = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil) for response in [response1, response2, response3] { response.progress.totalUnitCount = 1 } observers.observe([item1, item2, item3], responses: [ item1: response1, item2: response2, item3: response3, ]) waitForProgressUpdates() XCTAssertEqual(Set(recorder.diffSinceLastCalled), [ .itemsUpdated([item1, item2, item3]), .progress(item1, 0, 0), .progress(item2, 1, 0), .progress(item3, 2, 0), ]) } func testStopDownloading() { let response = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil) response.progress.totalUnitCount = 1 observers.observe([item1, item2, item3], responses: [item1: response]) observers.stopDownloading(item1) observers.stopDownloading(item2) waitForProgressUpdates() XCTAssertEqual(recorder.diffSinceLastCalled, [ .itemsUpdated([item1, item2, item3]), .cancel(response: response), .itemsUpdated([item1, item2, item3]), .itemsUpdated([item1, item2, item3]), ]) // if promise fulfilled, we don't get notified response.fulfill() waitForProgressUpdates() XCTAssertTrue(recorder.diffSinceLastCalled.isEmpty) } func testStopDownloadingThenRedownloading() { let response = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil) response.progress.totalUnitCount = 1 observers.observe([item1, item2, item3], responses: [item1: response]) observers.stopDownloading(item1) observers.preparingDownloading(item1) observers.startDownloading(item: item1, response: response) response.fulfill() waitForProgressUpdates() XCTAssertEqual(recorder.diffSinceLastCalled, [ .itemsUpdated([item1, item2, item3]), .cancel(response: response), .itemsUpdated([item1, item2, item3]), .itemsUpdated([item1, item2, item3]), .progress(item1, 0, 0), // completed .itemsUpdated([item1, item2, item3]), .completed(item1, 0), ]) } func testCantRestartDownloadImmediately() { let response = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil) response.progress.totalUnitCount = 1 observers.observe([item1, item2, item3], responses: [item1: response]) observers.stopDownloading(item1) observers.startDownloading(item: item1, response: response) waitForProgressUpdates() XCTAssertEqual(recorder.diffSinceLastCalled, [ .itemsUpdated([item1, item2, item3]), .cancel(response: response), .itemsUpdated([item1, item2, item3]), .cancel(response: response), ]) } func testRemoveAllResponses() { let response1 = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil) let response2 = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil) let response3 = DownloadBatchResponse(batchId: -1, responses: [], cancellable: nil) for response in [response1, response2, response3] { response.progress.totalUnitCount = 1 } observers.observe([item1, item2, item3], responses: [ item1: response1, item2: response2, item3: response3, ]) waitForProgressUpdates() // start the diff now _ = recorder.diffSinceLastCalled observers.removeAll() waitForProgressUpdates() XCTAssertEqual(recorder.diffSinceLastCalled, [ .itemsUpdated([]), ]) response1.fulfill() XCTAssertEqual(recorder.diffSinceLastCalled, []) } }
600fb6e7d7f9e63d98de24bcc6c0653b
34.676617
91
0.631293
false
true
false
false
TheBudgeteers/CartTrackr
refs/heads/master
CartTrackr/CartTrackr/Item.swift
mit
1
// // Item.swift // CartTrackr // // Created by Christina Lee on 4/10/17. // Copyright © 2017 Christina Lee. All rights reserved. // import Foundation class Item { var price : String var originalPrice : Float var cost : Float var description : String var quantity : String { didSet { self.cost = (self.originalPrice * Float(self.quantity)!) } } init(price: String, description: String, quantity: String) { self.price = price self.originalPrice = Float(price)! self.cost = (Float(price)! * Float(quantity)!) self.description = description self.quantity = quantity } } //MARK: Format extension extension String { func format() -> String { return String(format: "%.2f" , self) } }
2a3d018f79336b9435347aa21b09efbb
20.051282
68
0.589525
false
false
false
false
0Mooshroom/Learning-Swift
refs/heads/master
7_闭包.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit //: 闭包表达式 let names = ["Chris","Alex","Ewa","Barry","Daniella"] // >>>>> 1 func backward(_ s1: String, _ s2: String) -> Bool{ return s1 > s2 } var reverseNames_1 = names.sorted(by: backward) // >>>>> 2 var reverseNames_2 = names.sorted { (s1: String, s2: String) -> Bool in return s1 > s2 } // >>>>> 3 var reverseNames_3 = names.sorted(by: { s1, s2 in return s1 > s2 }) // >>>>> 4 var reveseNames_4 = names.sorted(by: { s1, s2 in s1 > s2 }) // >>>>> 5 var reverseNames_5 = names.sorted(by: { $0 > $1 }) // >>>>> 6 var reverseNames_6 = names.sorted(by: >) //: 尾随闭包 // 尾随闭包是一个被书写在函数形式参数的括号外面(后面)的闭包表达式 func fetchMooshroomName(closure:() -> Void) { closure() } fetchMooshroomName(closure: { }) var reverseNames_7 = names.sorted() { $0 > $1 } var reverseNames_8 = names.sorted { $0 > $1 } let digitNames = [ 0: "Zero",1: "One",2: "Two", 3: "Three",4: "Four", 5: "Five",6: "Six",7: "Seven",8: "Eight",9: "Nine" ] let numbers = [16,58,510] let strings = numbers.map { (number) -> String in var number = number var output = "" repeat { output = digitNames[number % 10]! + output number /= 10 } while number > 0 return output } strings //: 捕获值 struct CatchValue { static func makeIncrementer(forIncrement amount: Int) -> () -> Int { var runningTotal = 0 func incrementer() -> Int { runningTotal += amount return runningTotal } return incrementer } } let incrementByTen = CatchValue.makeIncrementer(forIncrement: 10) print(incrementByTen()) print(incrementByTen()) print(incrementByTen()) print(incrementByTen()) //: 闭包是引用类型 // //: 逃逸闭包 // 非逃逸: 我们平时使用的Masonry 和 Snapkit的添加约束的方法是非逃逸的。因为闭包马上就执行了。 // 逃逸: 网络请求结束后的回调闭包则是逃逸的,因为发起请求后过了一段时间后这个闭包才执行。 //: 自动闭包
21efacd9165ee4605189650182c7039b
19.666667
72
0.610005
false
false
false
false
MHaroonBaig/Swift-Beautify
refs/heads/master
Picker/SideBarTableViewController.swift
apache-2.0
2
// // SideBarTableViewController.swift // BlurrySideBar // // Created by Training on 01/09/14. // Copyright (c) 2014 Training. All rights reserved. // import UIKit protocol SideBarTableViewControllerDelegate{ func sideBarControlDidSelectRow(indexPath:NSIndexPath) } class SideBarTableViewController: UITableViewController { var delegate:SideBarTableViewControllerDelegate? var tableData:Array<String> = [] // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell if cell == nil{ cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") // Configure the cell... cell!.backgroundColor = UIColor.clearColor() cell!.textLabel.textColor = UIColor.darkTextColor() let selectedView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height)) selectedView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3) cell!.selectedBackgroundView = selectedView } cell!.textLabel.text = tableData[indexPath.row] var value = tableData[indexPath.row] switch (value){ case "Turquoise": cell!.backgroundColor = UIColor(red: 0.102, green: 0.737, blue: 0.612, alpha: 1.0) break case "Greensea": cell!.backgroundColor = UIColor(red:0.086, green:0.627, blue:0.522, alpha:1) break case "Emerland": cell!.backgroundColor = colorWithHexString("2ecc71") break case "Nephritis": cell!.backgroundColor = colorWithHexString("27ae60") break case "Peterriver": cell!.backgroundColor = colorWithHexString("3498db") break case "Belizehole": cell!.backgroundColor = colorWithHexString("2980b9") break case "Amethyst": cell!.backgroundColor = colorWithHexString("9b59b6") break case "Wisteria": cell!.backgroundColor = colorWithHexString("8e44ad") break case "Wetasphalt": cell!.backgroundColor = colorWithHexString("34495e") break case "Midnightblue": cell!.backgroundColor = colorWithHexString("2c3e50") break case "Sunflower": cell!.backgroundColor = colorWithHexString("f1c40f") break case "Orange": cell!.backgroundColor = colorWithHexString("f39c12") break case "Carrot": cell!.backgroundColor = colorWithHexString("e67e22") break case "Pumpkin": cell!.backgroundColor = colorWithHexString("d35400") break case "Alizarin": cell!.backgroundColor = colorWithHexString("e74c3c") break case "Pomegranate": cell!.backgroundColor = colorWithHexString("c0392b") break case "Clouds": cell!.backgroundColor = colorWithHexString("ecf0f1") break case "Silver": cell!.backgroundColor = colorWithHexString("bdc3c7") break case "Concrete": cell!.backgroundColor = colorWithHexString("95a5a6") break case "Asbestos": cell!.backgroundColor = colorWithHexString("7f8c8d") break case "Wistful": cell!.backgroundColor = colorWithHexString("AEA8D3") break case "Snuff": cell!.backgroundColor = colorWithHexString("DCC6E0") break default: cell!.backgroundColor = UIColor.clearColor() break } return cell! } func colorWithHexString (hex:String) -> UIColor { var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString if (cString.hasPrefix("#")) { cString = (cString as NSString).substringFromIndex(1) } if (countElements(cString) != 6) { return UIColor.grayColor() } var rString = (cString as NSString).substringToIndex(2) var gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2) var bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2) var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; NSScanner(string: rString).scanHexInt(&r) NSScanner(string: gString).scanHexInt(&g) NSScanner(string: bString).scanHexInt(&b) return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1)) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 65.0 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { delegate?.sideBarControlDidSelectRow(indexPath) } }
021915062d452ce5724fb72a13832539
34.209877
135
0.604137
false
false
false
false
huangboju/GesturePassword
refs/heads/master
GesturePassword/Classes/LockAdapter.swift
mit
1
// // LockMediator.swift // GesturePassword // // Created by 黄伯驹 on 2018/5/5. // Copyright © 2018 xiAo_Ju. All rights reserved. // public protocol LockViewPresentable: class { var lockMainView: LockView { get } } public protocol SetPatternDelegate: LockViewPresentable { var password: String { set get } func firstDrawedState() func tooShortState() func mismatchState() func successState() } protocol VerifyPatternDelegate: LockViewPresentable { func successState() func errorState(_ remainTimes: Int) func overTimesState() } struct LockAdapter {} /// SetPatternDelegate extension LockAdapter { static func setPattern(with controller: SetPatternDelegate) { let password = controller.lockMainView.password if password.count < LockCenter.passwordMinCount { controller.tooShortState() return } if controller.password.isEmpty { controller.password = password controller.firstDrawedState() return } guard controller.password == password else { controller.mismatchState() return } controller.successState() } static func reset(with controller: SetPatternDelegate) { controller.lockMainView.reset() controller.password = "" } } /// VerifyPatternDelegate extension LockAdapter { static func verifyPattern(with controller: VerifyPatternDelegate) { let inputPassword = controller.lockMainView.password let localPassword = LockCenter.password() if inputPassword == localPassword { // 成功了删除一些之前的错误 LockCenter.removeErrorTimes() controller.successState() return } var errorTimes = LockCenter.errorTimes() errorTimes -= 1 LockCenter.setErrorTimes(errorTimes) guard errorTimes == 0 else { controller.errorState(errorTimes) return } controller.overTimesState() } }
0f952c5591902fe2c4f24a9d084228ec
23.626506
71
0.644325
false
false
false
false
Yurssoft/QuickFile
refs/heads/master
QuickFile/Additional_Classes/YSTabBarController.swift
mit
1
// // YSTabBarController.swift // YSGGP // // Created by Yurii Boiko on 10/21/16. // Copyright © 2016 Yurii Boiko. All rights reserved. // import UIKit class YSTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() var driveTopViewController: YSDriveTopViewController? = nil for navigationVC in childViewControllers { for topVC in navigationVC.childViewControllers { if let drTopVC = topVC as? YSDriveTopViewController { driveTopViewController = drTopVC } } } let coordinator = YSDriveTopCoordinator() YSAppDelegate.appDelegate().driveTopCoordinator = coordinator coordinator.start(driveTopVC: driveTopViewController!) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) YSAppDelegate.appDelegate().playerCoordinator.start(tabBarController: self) } }
826c1eaaea63935caa695de3dd6f7728
30.741935
83
0.66565
false
false
false
false
feialoh/FFImageDrawingTool
refs/heads/master
FFImageDrawingTool/MainViewController.swift
mit
1
// // MainViewController.swift // FFImageDrawingTool // // Created by feialoh on 31/03/16. // Copyright © 2016 Feialoh Francis. All rights reserved. // import UIKit class MainViewController: UIViewController,ImageSelectorDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIScrollViewDelegate { @IBOutlet weak var selectedImage: UIImageView! @IBOutlet weak var imageContainerScrollView: UIScrollView! var imagePicker = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() imagePicker.delegate = self imagePicker.allowsEditing = false imageContainerScrollView.minimumZoomScale = 1.0 imageContainerScrollView.maximumZoomScale = 2.0 imageContainerScrollView.delegate = self // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func imagePickerAction(_ sender: UIButton) { let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertController.Style.actionSheet) let cameraAction = UIAlertAction(title: "Take Photo", style: UIAlertAction.Style.default) { UIAlertAction in self.openCamera() } let photoLibraryAction = UIAlertAction(title: "Photo Library", style: UIAlertAction.Style.default) { UIAlertAction in self.openLibrary() } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) { UIAlertAction in } // Add the actions imagePicker.delegate = self alert.addAction(photoLibraryAction) alert.addAction(cameraAction) alert.addAction(cancelAction) // Present the controller if UIDevice.current.userInterfaceIdiom == .phone { self.present(alert, animated: true, completion: nil) } else { if let popoverController = alert.popoverPresentationController { popoverController.sourceView = sender popoverController.sourceRect = sender.bounds } self.present(alert, animated: true, completion: nil) } } /*===============================================================================*/ // MARK: - Image picker helper methods /*===============================================================================*/ //To open camera func openCamera() { if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerController.SourceType.camera)) { imagePicker.sourceType = UIImagePickerController.SourceType.camera self .present(imagePicker, animated: true, completion: nil) } else { let alert = UIAlertView(title: "Camera is unavailable", message: "Error", delegate: [], cancelButtonTitle: "Ok") alert.show() } } //To open photo library func openLibrary() { imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary if UIDevice.current.userInterfaceIdiom == .phone { self.present(imagePicker, animated: true, completion: nil) } else { imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary self.present(imagePicker, animated: true, completion: nil) } } /*===============================================================================*/ // MARK: - Custom Image view delegate methods /*===============================================================================*/ func selectedWithImage(_ chosenImage: UIImage, parent: AnyObject) { selectedImage.image = chosenImage imageContainerScrollView.zoomScale = 1 imageContainerScrollView.minimumZoomScale = 1.0 imageContainerScrollView.maximumZoomScale = 2.0 } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func viewForZooming(in scrollView: UIScrollView) -> UIView? { return selectedImage } /*===============================================================================*/ // MARK: - UIImagePickerControllerDelegate /*===============================================================================*/ func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: { () -> Void in }) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // Local variable inserted by Swift 4.2 migrator. let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) let chosenImage = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as! UIImage //2 picker.dismiss(animated: true, completion: { () -> Void in }) let imageView = self.storyboard?.instantiateViewController(withIdentifier: "ImageView") as! ImageViewController imageView.delegate = self imageView.selectedImage = chosenImage imageView.viewType = "Picker" self.present(imageView, animated: true, completion: nil) } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String { return input.rawValue }
39b8e175dd03f7436a54f961bfdce457
34.604396
153
0.602006
false
false
false
false
planvine/Line-Up-iOS-SDK
refs/heads/master
Pod/Classes/Line-Up_ExtCoreData.swift
mit
1
/** * Copyright (c) 2016 Line-Up * * 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 CoreData extension LineUp { //MARK: - CoreData methods /** * Get the event (PVEvent) with id: 'id' from CoreData. * - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device. */ class func getEventFromCoreData(id: NSNumber) -> PVEvent? { let fetchRequest : NSFetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVEvent, inManagedObjectContext: PVCoreData.managedObjectContext)! fetchRequest.predicate = NSPredicate(format:"eventID = %@",id) do { let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) if objects.count > 0 { return (objects.lastObject as? PVEvent)! } } catch { return nil } return nil } class func getVenueFromCoreData(id: NSNumber) -> PVVenue? { let fetchRequest : NSFetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVVenue, inManagedObjectContext: PVCoreData.managedObjectContext)! fetchRequest.predicate = NSPredicate(format:"venueID = %@",id) do { let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) if objects.count > 0 { return (objects.lastObject as? PVVenue)! } } catch { return nil } return nil } /** * Get the performance (PVPerformance) with id: 'id' from CoreData * - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device. */ public class func getPerformanceFromCoreData(id: NSNumber) -> PVPerformance? { let fetchRequest : NSFetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVPerformance, inManagedObjectContext: PVCoreData.managedObjectContext)! fetchRequest.predicate = NSPredicate(format:"performanceID = %@",id) do { let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) if objects.count > 0 { return (objects.lastObject as? PVPerformance)! } } catch { return nil } return nil } /** * It returns true if the performance with id: 'id' has tickets, false otherwise */ class func performanceHasTickets(id: NSNumber) -> Bool { var perf : PVPerformance? = getPerformanceFromCoreData(id) if perf == nil { perf = getPerformance(id) } if perf != nil && perf!.hasTickets == true { return true } return false } /** * Get the user (PVUser) with accessToken: 'userToken' from CoreData * - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device. */ public class func getUserWithTokenFromCoreData(userToken: String) -> PVUser? { let fetchRequest : NSFetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVUser, inManagedObjectContext: PVCoreData.managedObjectContext)! fetchRequest.predicate = NSPredicate(format:"accessToken = %@",userToken) do { let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) if objects.count > 0 { return (objects.lastObject as? PVUser)! } } catch { return nil } return nil } /** * Get the ticket (PVTicket) with id: 'id' from CoreData * - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device. */ public class func getTicketFromCoreData(id: NSNumber) -> PVTicket? { let fetchRequest : NSFetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVTicket, inManagedObjectContext: PVCoreData.managedObjectContext)! fetchRequest.predicate = NSPredicate(format:"id = %@",id) do { let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) if objects.count > 0 { return (objects.lastObject as? PVTicket)! } } catch { return nil } return nil } /** * Get the receipts (array of PVReceipt) for the usen with token: 'userToken' from CoreData * - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device. */ class func getTicketsReceiptsFromCoreData(userToken: String) -> [PVReceipt]? { let fetchRequest : NSFetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVReceipt, inManagedObjectContext: PVCoreData.managedObjectContext)! fetchRequest.predicate = NSPredicate(format:"user.accessToken = %@",userToken) do { let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) guard objects.count > 0 else { return nil } return objects as? Array<PVReceipt> } catch { return nil } } /** * Get the receipt (PVReceipt) with id: 'id' from CoreData * - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device. */ class func getReceiptFromCoreData(id: NSNumber) -> PVReceipt? { let fetchRequest : NSFetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVReceipt, inManagedObjectContext: PVCoreData.managedObjectContext)! fetchRequest.predicate = NSPredicate(format:"id = %@",id) do { let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) guard objects.count > 0 else { return nil } return (objects.lastObject as? PVReceipt) } catch { return nil } } /** * Get list of tickets (array of PVTicket) available for the performance with id: 'performanceId' from CoreData * - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device. */ class func getTicketsFromCoreDataOfPerformance(performanceId: NSNumber) -> [PVTicket] { let fetchRequest : NSFetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVPerformance, inManagedObjectContext: PVCoreData.managedObjectContext)! fetchRequest.predicate = NSPredicate(format:"performanceID = %@",performanceId) do { let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) if objects.count > 0 && (objects.lastObject as! PVPerformance).tickets != nil && (objects.lastObject as! PVPerformance).tickets!.allObjects.count > 0{ return (objects.lastObject as? PVPerformance)!.tickets!.allObjects as! Array<PVTicket> } } catch { return Array() } return Array() } /** * Get list of credit cards (array of PVCard for the user with Line-Up token: 'userToken' from CoreData * - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device. */ class func getCardsFromCoreData(userToken: String) -> (NSFetchRequest, [PVCard]?) { let fetchRequest : NSFetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)! let sortDescriptor1 = NSSortDescriptor(key: "selectedCard", ascending: false) let sortDescriptor2 = NSSortDescriptor(key: "brand", ascending: false) let sortDescriptor3 = NSSortDescriptor(key: "expYear", ascending: false) let sortDescriptor4 = NSSortDescriptor(key: "expMonth", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor1,sortDescriptor2,sortDescriptor3,sortDescriptor4] fetchRequest.predicate = NSPredicate(format: "user.accessToken = %@",userToken) do { return (fetchRequest,try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) as? Array<PVCard>) } catch { return (fetchRequest,nil) } } /** * Get list of credit cards (array of PVCard for the user with Line-Up token: 'userToken' from CoreData * - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device. */ class func getCardFromCoreData(id: String) -> PVCard? { let fetchRequest : NSFetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)! fetchRequest.predicate = NSPredicate(format:"id = %@",id) do { let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) if objects.count > 0 { return (objects.lastObject as? PVCard)! } } catch { return nil } return nil } /** * Delete all the credit cards from CoreData except the cards in 'listOfCards' */ public class func deleteCardsFromCoreDataExcept(listOfCards: Array<PVCard>, userToken: String) { let fetchRequest : NSFetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)! let sortDescriptor1 = NSSortDescriptor(key: "selectedCard", ascending: false) let sortDescriptor2 = NSSortDescriptor(key: "brand", ascending: false) let sortDescriptor3 = NSSortDescriptor(key: "expYear", ascending: false) let sortDescriptor4 = NSSortDescriptor(key: "expMonth", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor1,sortDescriptor2,sortDescriptor3,sortDescriptor4] var listOfIds: Array<String> = Array() for card in listOfCards { if card.id != nil { listOfIds.append(card.id!) } } fetchRequest.predicate = NSPredicate(format: "user.accessToken = %@ && NOT id IN %@",userToken, listOfIds) do { let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) for managedObject in objects { PVCoreData.managedObjectContext.deleteObject(managedObject as! NSManagedObject) } try PVCoreData.managedObjectContext.save() } catch { } } /** * Set the card (PVCard) as selected card (default one) on the device (CoreData) */ public class func setSelectedCard(card: PVCard) { let fetchRequest : NSFetchRequest = NSFetchRequest() fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)! do { let objects : Array<PVCard> = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) as! Array<PVCard> for obj in objects { if obj.id != card.id { obj.selectedCard = false } else { obj.selectedCard = true } } try PVCoreData.managedObjectContext.save() } catch { } } }
36cf39ac119b6c4f5806f267e145bace
46.637363
162
0.665283
false
false
false
false
m-alani/contests
refs/heads/master
leetcode/pascalsTriangleII.swift
mit
1
// // pascalsTriangleII.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/pascals-triangle-ii/ // Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code // class Solution { func getRow(_ rowIndex: Int) -> [Int] { var row = Array(repeating: 0, count: rowIndex + 1) var num = Double(rowIndex), den = 1.0, idx = 1 row[0] = 1 // Cover the edge case of index = 0 if rowIndex == 0 { return row } // Find the values for the first half while num >= den { row[idx] = Int(Double(row[idx-1]) * num / den) num -= 1 den += 1 idx += 1 } // Mirror the values to the second half let half = row.count / 2 row[row.count-half...rowIndex] = ArraySlice(row[0..<half].reversed()) return row } }
87384abc65b2a02ccf395d9f578c27ad
27.28125
117
0.61326
false
false
false
false
NoryCao/zhuishushenqi
refs/heads/master
zhuishushenqi/TXTReader/BookDetail/Models/BookShelfInfo.swift
mit
1
// // BokShelfInfo.swift // zhuishushenqi // // Created by Nory Cao on 2017/3/6. // Copyright © 2017年 QS. All rights reserved. // import UIKit class BookShelfInfo: NSObject { static let books = BookShelfInfo() private override init() { } let bookShelfInfo = "bookShelfInfo" let readHistoryKey = "readHistoryKey" let bookshelfSaveKey = "bookshelfSaveKey" var readHistory:[BookDetail]{ get{ var data:[BookDetail]? = [] let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last?.appending("/\(readHistoryKey.md5())") if let filePath = path { let file:NSDictionary? = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? NSDictionary data = file?[readHistoryKey] as? [BookDetail] } return data ?? [] } set{ let dict = [readHistoryKey:newValue] let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last?.appending("/\(readHistoryKey.md5())") if let filePath = path { do { let url = URL(string: filePath) try FileManager.default.removeItem(at: url!) } catch _{} NSKeyedArchiver.archiveRootObject(dict, toFile: filePath) } } } public func delete(book:BookDetail) { } }
486d28e2efbde2c528874f4eb07d8223
28.529412
145
0.571049
false
false
false
false
aryaxt/SwiftInjection
refs/heads/master
SwiftInjection/DIBindingProvider.swift
mit
1
// // DIBindingInfo.swift // SwiftInjection // // Created by Aryan Ghassemi on 4/24/16. // Copyright © 2016 Aryan Ghassemi. All rights reserved. // import Foundation internal class DIBindingProvider { private var namedBindings = [String: DINamedBinding]() private static let defaultBindingName = "default" func addBinding(closure: @escaping ()->Any, named: String? = nil, asSingleton: Bool) { let named = named ?? DIBindingProvider.defaultBindingName namedBindings[named] = DINamedBinding(closure: closure, asSingleton: asSingleton) } func provideInstance(named: String? = nil) -> Any { let named = named ?? DIBindingProvider.defaultBindingName guard let namedBinding = namedBindings[named] else { fatalError("Did not find binding named \(named)") } return namedBinding.provideInstance() } func provideAllInstances() -> [Any] { return namedBindings.values.map { $0.provideInstance() } } }
69bbe0f6262e98a537fdbf8e5cf466d1
28.741935
106
0.734273
false
false
false
false
andrewgrant/TodoApp
refs/heads/master
Shared/TodoEntry.swift
mit
1
// // TodoEntry.swift // TodoApp // // Created by Andrew Grant on 6/23/15. // Copyright (c) 2015 Andrew Grant. All rights reserved. // import Foundation class TodoEntry : TodoItem { var title : String! var parentUuid : String? var completed = false var priority : Int = 0 init (title : String) { self.title = title super.init() } required init(record: RemoteRecord) { super.init(record: record) } override func decodeSelf(record : RemoteRecord) { self.title = record["title"] as! String self.parentUuid = record["parentUuid"] as? String self.completed = record["completed"] as! Bool self.priority = record["priority"] as! Int } override func encodeSelf(record : RemoteRecord) { super.encodeSelf(record) record["title"] = self.title record["parentUuid"] = self.parentUuid record["completed"] = self.completed record["priority"] = self.priority } }
da7ac36ae52583f075c214aaf1f3e0f5
22.727273
57
0.591954
false
false
false
false
cfilipov/MuscleBook
refs/heads/master
MuscleBook/DebugMenuViewController.swift
gpl-3.0
1
/* Muscle Book Copyright (C) 2016 Cristian Filipov This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import UIKit import Eureka import JSQNotificationObserverKit class DebugMenuViewController : FormViewController { private let db = DB.sharedInstance private let mainQueue = NSOperationQueue.mainQueue() private var observer: CocoaObserver? = nil override func viewDidLoad() { super.viewDidLoad() let notification = CocoaNotification(name: UIApplicationDidReceiveMemoryWarningNotification) observer = CocoaObserver(notification, queue: self.mainQueue, handler: { (notification: NSNotification) in self.tableView?.reloadData() }) title = "Debug Menu" form +++ Section() { $0.header = HeaderFooterView(title: "Warning") $0.footer = HeaderFooterView(title: "Don't mess with the debug settings unless you know what you are doing.\n\nSome of the options here may cause data loss or other craziness.") } +++ Section() <<< LabelRow() { $0.title = "Timers" }.cellSetup { cell, row in cell.accessoryType = .DisclosureIndicator }.onCellSelection { cell, row in let vc = DebugTimersViewController() self.showViewController(vc, sender: nil) } <<< LabelRow() { $0.title = "Color Palette" }.cellSetup { cell, row in cell.accessoryType = .DisclosureIndicator }.onCellSelection { cell, row in let vc = ColorPaletteViewController() self.showViewController(vc, sender: nil) } <<< LabelRow() { $0.title = "Anatomy" }.cellSetup { cell, row in cell.accessoryType = .DisclosureIndicator }.onCellSelection { cell, row in let vc = AnatomyDebugViewController2() self.showViewController(vc, sender: nil) } // <<< LabelRow("import_csv") { // $0.title = "Import CSV" // $0.disabled = "$import_csv != nil" // $0.hidden = Dropbox.authorizedClient == nil ? true : false // }.onCellSelection(onImportCSV) // // <<< LabelRow("sync_dropbox") { // $0.title = "Sync Dropbox" // $0.disabled = "$sync_dropbox != nil" // $0.hidden = Dropbox.authorizedClient == nil ? true : false // }.onCellSelection(onSyncWithDropbox) +++ Section() <<< ButtonRow() { $0.title = "Recalculate All Workouts" $0.cellUpdate { cell, _ in cell.textLabel?.textColor = UIColor.redColor() } $0.onCellSelection { _, _ in WarnAlert(message: "Are you sure? This will be slow and the UI will be unresponsive while calculating.") { try! self.db.recalculateAll() } } } <<< ButtonRow() { $0.title = "Export Exercises" $0.cellUpdate { cell, _ in cell.textLabel?.textColor = UIColor.redColor() } $0.onCellSelection { _, _ in let url = NSFileManager .defaultManager() .URLsForDirectory( .CachesDirectory, inDomains: .UserDomainMask )[0] .URLByAppendingPathComponent("exercises.yaml") try! self.db.exportYAML(Exercise.self, toURL: url) let vc = UIActivityViewController( activityItems: [url], applicationActivities: nil ) self.presentViewController(vc, animated: true, completion: nil) } } } // private func onSyncWithDropbox(cell: LabelCell, row: LabelRow) { // WarnAlert(message: "Are you sure you want to sync?") { _ in // row.value = "Syncing..." // row.reload() // Workset.importFromDropbox("/WorkoutLog.yaml") { status in // guard .Success == status else { // Alert(message: "Failed to sync with dropbox") // return // } // row.value = nil // row.disabled = false // row.reload() // Alert(message: "Sync Complete") // } // } // } // private func onImportCSV(cell: LabelCell, row: LabelRow) { // guard db.count(Workset) == 0 else { // Alert(message: "Cannot import data, you already have data.") // return // } // WarnAlert(message: "Import Data from Dropbox?") { _ in // row.value = "Importing..." // row.reload() // Workset.downloadFromDropbox("/WorkoutLog.csv") { url in // guard let url = url else { // row.value = nil // row.reload() // Alert(message: "Failed to import CSV data") // return // } // row.value = "Importing..." // row.reload() // do { // let importCount = try self.db.importCSV(Workset.self, fromURL: url) // row.value = nil // row.disabled = false // row.reload() // Alert("Import Complete", message: "\(importCount) records imported.") { _ in //// let vc = VerifyWorksetsViewController() //// self.presentModalViewController(vc) // } // } catch { // row.value = nil // row.reload() // Alert(message: "Failed to import CSV data") // return // } // } // } // } }
e4dfcbaf248d8157da01bbe584ed2e9b
35.398876
189
0.528014
false
false
false
false
guillermo-ag-95/App-Development-with-Swift-for-Students
refs/heads/master
1 - Getting Started/4 - Control Flow/lab/Lab - Control Flow.playground/Pages/2. Exercise - If and If-Else Statements.xcplaygroundpage/Contents.swift
mit
1
/*: ## Exercise - If and If-Else Statements Imagine you're creating a machine that will count your money for you and tell you how wealthy you are based on how much money you have. A variable `dollars` has been given to you with a value of 0. Write an if statement that prints "Sorry, kid. You're broke!" if `dollars` has a value of 0. Observe what is printed to the console. */ var dollars = 0 if dollars == 0 { print("Sorry, kid. You're broke!") } /*: `dollars` has been updated below to have a value of 10. Write an an if-else statement that prints "Sorry, kid. You're broke!" if `dollars` has a value of 0, but prints "You've got some spending money!" otherwise. Observe what is printed to the console. */ dollars = 10 if dollars == 0 { print("Sorry, kid. You're broke!") } else { print("You've got some spending money!") } /*: `dollars` has been updated below to have a value of 105. Write an an if-else-if statement that prints "Sorry, kid. You're broke!" if `dollars` has a value of 0, prints "You've got some spending money!" if `dollars` is less than 100, and prints "Looks to me like you're rich!" otherwise. Observe what is printed to the console. */ dollars = 105 if dollars == 0 { print("Sorry, kid. You're broke!") } else if dollars < 100 { print("You've got some spending money!") } else { print("Looks to me like you're rich!") } //: [Previous](@previous) | page 2 of 9 | [Next: App Exercise - Fitness Decisions](@next)
be9aef1aa8d1dc3f4f81cfb453196b8d
43.69697
331
0.687458
false
false
false
false
zmeyc/telegram-bot-swift
refs/heads/master
Sources/TelegramBotSDK/BotName.swift
apache-2.0
1
// // BotName.swift // // This source file is part of the Telegram Bot SDK for Swift (unofficial). // // Copyright (c) 2015 - 2020 Andrey Fidrya and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information // See AUTHORS.txt for the list of the project authors // import Foundation public class BotName { let underscoreBotSuffix = "_bot" let botSuffix = "bot" public var withoutSuffix: String public init(username: String) { let lowercase = username.lowercased() if lowercase.hasSuffix(underscoreBotSuffix) { withoutSuffix = String(username.dropLast(underscoreBotSuffix.count)) } else if lowercase.hasSuffix(botSuffix) { withoutSuffix = String(username.dropLast(botSuffix.count)) } else { withoutSuffix = username } } } extension BotName: Equatable { } public func ==(lhs: BotName, rhs: BotName) -> Bool { return lhs.withoutSuffix == rhs.withoutSuffix } extension BotName: Comparable { } public func <(lhs: BotName, rhs: BotName) -> Bool { return lhs.withoutSuffix < rhs.withoutSuffix }
a0b8a0fc400c0ece1099a68fefe7a022
24.217391
75
0.69569
false
false
false
false
ITzTravelInTime/TINU
refs/heads/development
TINU/FilesystemObserver.swift
gpl-2.0
1
/* TINU, the open tool to create bootable macOS installers. Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import Foundation public class FileSystemObserver { private var fileHandle: CInt? private var eventSource: DispatchSourceProtocol? private var observingStarted: Bool = false private let path: String private let handler: () -> Void public var isObserving: Bool{ return fileHandle != nil && eventSource != nil && observingStarted } deinit { stop() } public required init(path: String, changeHandler: @escaping ()->Void, startObservationNow: Bool = true) { assert(!path.isEmpty, "The filesystem object to observe must have a path!") self.path = path self.handler = changeHandler if startObservationNow{ start() } } public convenience init(url: URL, changeHandler: @escaping ()->Void, startObservationNow: Bool = true) { self.init(path: url.path, changeHandler: { changeHandler() }, startObservationNow: startObservationNow) } public func stop() { self.eventSource?.cancel() if fileHandle != nil{ close(fileHandle!) } self.eventSource = nil self.fileHandle = nil self.observingStarted = false } public func start() { if fileHandle != nil || eventSource != nil{ stop() } self.fileHandle = open(path, O_EVTONLY) self.eventSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: self.fileHandle!, eventMask: .all, queue: DispatchQueue.global(qos: .utility)) self.eventSource!.setEventHandler { self.handler() } self.eventSource!.resume() self.observingStarted = true } }
c6d9233e33b102b996d3ee02953e908f
26.578313
157
0.736129
false
false
false
false
Noirozr/UIColorExtension
refs/heads/master
nipponColor.swift
mit
1
// // nipponColor.swift // Surf // // Created by Noirozr on 15/3/26. // Copyright (c) 2015年 Yongjia Liu. All rights reserved. // import UIKit //http://nipponcolors.com extension UIColor { class func MOMOColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 245.0/255.0, green: 150.0/255.0, blue: 170.0/255.0, alpha: alpha) } class func KUWAZOMEColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 100.0/255.0, green: 54.0/255.0, blue: 60.0/255.0, alpha: alpha) } class func IKKONZOMEColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 244.0/255.0, green: 167.0/255.0, blue: 185.0/255.0, alpha: alpha) } class func TAIKOHColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 248.0/255.0, green: 195.0/255.0, blue: 205.0/255.0, alpha: alpha) } class func SUOHColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 142.0/255.0, green: 53.0/255.0, blue: 74.0/255.0, alpha: alpha) } class func KOHBAIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 225.0/255.0, green: 107.0/255.0, blue: 140.0/255.0, alpha: alpha) } class func NADESHIKOColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 220.0/255.0, green: 159.0/255.0, blue: 180.0/255.0, alpha: alpha) } class func KARAKURENAIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 208.0/255.0, green: 16.0/255.0, blue: 76.0/255.0, alpha: alpha) } class func UMENEZUMIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 158.0/255.0, green: 122.0/255.0, blue: 122.0/255.0, alpha: alpha) } class func SAKURAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 254.0/255.0, green: 223.0/255.0, blue: 225.0/255.0, alpha: alpha) } class func NAKABENIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 219.0/255.0, green: 77.0/255.0, blue: 109.0/255.0, alpha: alpha) } class func IMAYOHColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 208.0/255.0, green: 90.0/255.0, blue: 110.0/255.0, alpha: alpha) } class func USUBENIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 232.0/255.0, green: 122.0/255.0, blue: 144.0/255.0, alpha: alpha) } class func ICHIGOColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 181.0/255.0, green: 73.0/255.0, blue: 91.0/255.0, alpha: alpha) } class func JINZAMOMIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 235.0/255.0, green: 122.0/255.0, blue: 119.0/255.0, alpha: alpha) } class func SAKURANEZUMIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 177.0/255.0, green: 150.0/255.0, blue: 147.0/255.0, alpha: alpha) } class func KOKIAKEColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 134.0/255.0, green: 71.0/255.0, blue: 63.0/255.0, alpha: alpha) } class func CYOHSYUNColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 191.0/255.0, green: 103.0/255.0, blue: 102.0/255.0, alpha: alpha) } class func TOKIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 238.0/255.0, green: 169.0/255.0, blue: 169.0/255.0, alpha: alpha) } class func KURENAIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 203.0/255.0, green: 27.0/255.0, blue: 69.0/255.0, alpha: alpha) } class func ENJIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 159.0/255.0, green: 53.0/255.0, blue: 58.0/255.0, alpha: alpha) } class func EBICHAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 115.0/255.0, green: 67.0/255.0, blue: 56.0/255.0, alpha: alpha) } class func KURIUMEColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 144.0/255.0, green: 72.0/255.0, blue: 64.0/255.0, alpha: alpha) } class func HAIZAKURAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 215.0/255.0, green: 196.0/255.0, blue: 187.0/255.0, alpha: alpha) } class func SHINSYUColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 171.0/255.0, green: 59.0/255.0, blue: 58.0/255.0, alpha: alpha) } class func AKABENIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 203.0/255.0, green: 64.0/255.0, blue: 66.0/255.0, alpha: alpha) } class func SUOHKOHColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 169.0/255.0, green: 99.0/255.0, blue: 96.0/255.0, alpha: alpha) } class func AZUKIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 149.0/255.0, green: 74.0/255.0, blue: 69.0/255.0, alpha: alpha) } class func SANGOSYUColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 241.0/255.0, green: 124.0/255.0, blue: 103.0/255.0, alpha: alpha) } class func MIZUGAKIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 185.0/255.0, green: 136.0/255.0, blue: 125.0/255.0, alpha: alpha) } class func BENIKABAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 181.0/255.0, green: 68.0/255.0, blue: 52.0/255.0, alpha: alpha) } class func AKEBONOColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 241.0/255.0, green: 148.0/255.0, blue: 131.0/255.0, alpha: alpha) } class func BENITOBIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 153.0/255.0, green: 70.0/255.0, blue: 57.0/255.0, alpha: alpha) } class func KUROTOBIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 85.0/255.0, green: 66.0/255.0, blue: 54.0/255.0, alpha: alpha) } class func GINSYUColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 199.0/255.0, green: 62.0/255.0, blue: 58.0/255.0, alpha: alpha) } class func AKEColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 204.0/255.0, green: 84.0/255.0, blue: 58.0/255.0, alpha: alpha) } class func KAKISHIBUColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 163.0/255.0, green: 94.0/255.0, blue: 71.0/255.0, alpha: alpha) } class func HIWADAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 133.0/255.0, green: 72.0/255.0, blue: 54.0/255.0, alpha: alpha) } class func SHIKANCHAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 181.0/255.0, green: 93.0/255.0, blue: 76.0/255.0, alpha: alpha) } class func ENTANColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 215.0/255.0, green: 84.0/255.0, blue: 85.0/255.0, alpha: alpha) } class func SYOJYOHIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 232.0/255.0, green: 48.0/255.0, blue: 21.0/255.0, alpha: alpha) } class func BENIHIWADAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 136.0/255.0, green: 76.0/255.0, blue: 58.0/255.0, alpha: alpha) } class func ARAISYUColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 251.0/255.0, green: 150.0/255.0, blue: 110.0/255.0, alpha: alpha) } class func EDOCHAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 175.0/255.0, green: 95.0/255.0, blue: 60.0/255.0, alpha: alpha) } class func TERIGAKIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 196.0/255.0, green: 98.0/255.0, blue: 67.0/255.0, alpha: alpha) } class func BENGARAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 154.0/255.0, green: 80.0/255.0, blue: 52.0/255.0, alpha: alpha) } class func KURIKAWACHAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 106.0/255.0, green: 64.0/255.0, blue: 40.0/255.0, alpha: alpha) } class func BENIHIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 247.0/255.0, green: 92.0/255.0, blue: 47.0/255.0, alpha: alpha) } class func TOBIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 114.0/255.0, green: 72.0/255.0, blue: 50.0/255.0, alpha: alpha) } class func KABACHAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 179.0/255.0, green: 92.0/255.0, blue: 55.0/255.0, alpha: alpha) } class func ENSYUCHAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 202.0/255.0, green: 120.0/255.0, blue: 83.0/255.0, alpha: alpha) } class func SOHIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 237.0/255.0, green: 120.0/255.0, blue: 74.0/255.0, alpha: alpha) } class func OHNIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 240.0/255.0, green: 94.0/255.0, blue: 28.0/255.0, alpha: alpha) } class func TOKIGARACHAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 219.0/255.0, green: 142.0/255.0, blue: 113.0/255.0, alpha: alpha) } class func KARACHAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 180.0/255.0, green: 113.0/255.0, blue: 87.0/255.0, alpha: alpha) } class func MOMOSHIOCHAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 114.0/255.0, green: 73.0/255.0, blue: 56.0/255.0, alpha: alpha) } class func KOKIKUCHINASHIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 251.0/255.0, green: 153.0/255.0, blue: 102.0/255.0, alpha: alpha) } class func KABAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 193.0/255.0, green: 105.0/255.0, blue: 60.0/255.0, alpha: alpha) } class func SODENKARACHAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 160.0/255.0, green: 103.0/255.0, blue: 75.0/255.0, alpha: alpha) } class func SHISHIColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 240.0/255.0, green: 169.0/255.0, blue: 134.0/255.0, alpha: alpha) } class func SUZUMECHAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 143.0/255.0, green: 90.0/255.0, blue: 60.0/255.0, alpha: alpha) } class func AKAKOHColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 227.0/255.0, green: 145.0/255.0, blue: 110.0/255.0, alpha: alpha) } class func KOGECHAColor(alpha: CGFloat = 1.0) -> UIColor { return UIColor.init(red: 86.0/255.0, green: 68.0/255.0, blue: 46.0/255.0, alpha: alpha) } }
87901e2a86e49087b76196f58c6a411e
40.348315
98
0.605616
false
false
false
false
velvetroom/columbus
refs/heads/master
Source/View/CreateSearch/VCreateSearchBaseListCell.swift
mit
1
import MapKit final class VCreateSearchBaseListCell:UICollectionViewCell { private weak var label:UILabel! let attributesTitle:[NSAttributedStringKey:Any] let attributesTitleHighlighted:[NSAttributedStringKey:Any] let attributesSubtitle:[NSAttributedStringKey:Any] let attributesSubtitleHighlighted:[NSAttributedStringKey:Any] let breakLine:NSAttributedString private var text:NSAttributedString? override init(frame:CGRect) { let colourLabelTitle:UIColor = UIColor(white:0, alpha:0.7) let colourLabelSubtitle:UIColor = UIColor(white:0, alpha:0.4) let colourLabelHighlighted:UIColor = UIColor.colourBackgroundDark attributesTitle = [ NSAttributedStringKey.font : UIFont.regular(size:VCreateSearchBaseListCell.Constants.titleFontSize), NSAttributedStringKey.foregroundColor : colourLabelTitle] attributesTitleHighlighted = [ NSAttributedStringKey.font : UIFont.bold(size:VCreateSearchBaseListCell.Constants.titleFontSize), NSAttributedStringKey.foregroundColor : colourLabelHighlighted] attributesSubtitle = [ NSAttributedStringKey.font : UIFont.regular(size:VCreateSearchBaseListCell.Constants.subtitleFontSize), NSAttributedStringKey.foregroundColor : colourLabelSubtitle] attributesSubtitleHighlighted = [ NSAttributedStringKey.font : UIFont.medium(size:VCreateSearchBaseListCell.Constants.subtitleFontSize), NSAttributedStringKey.foregroundColor : colourLabelHighlighted] breakLine = NSAttributedString(string:"\n") super.init(frame:frame) clipsToBounds = true let label:UILabel = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = UIColor.clear label.isUserInteractionEnabled = false label.numberOfLines = 0 self.label = label addSubview(label) NSLayoutConstraint.topToTop( view:label, toView:self, constant:VCreateSearchBaseListCell.Constants.marginTop) NSLayoutConstraint.heightGreaterOrEqual( view:label) NSLayoutConstraint.equalsHorizontal( view:label, toView:self, margin:VCreateSearchBaseListCell.Constants.marginHorizontal) } required init?(coder:NSCoder) { return nil } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: private private func hover() { if isSelected || isHighlighted { backgroundColor = UIColor.colourSuccess label.textColor = UIColor.white } else { backgroundColor = UIColor.white label.attributedText = text } } //MARK: internal func config(model:MKLocalSearchCompletion) { text = factoryText(model:model) hover() } }
7824b64fe4d409f4a31f6465b249a938
29.6
115
0.641457
false
false
false
false
hulinSun/MyRx
refs/heads/master
MyRx/MyRx/Classes/Core/Category/Response+HandyJSON.swift
mit
1
// Response+HandyJSON.swift // MyRx // // Created by Hony on 2016/12/29. // Copyright © 2016年 Hony. All rights reserved. // import Foundation import Moya import HandyJSON public extension Response { /// 整个 Data Model public func mapObject<T: HandyJSON>(_ type: T.Type) -> T? { guard let dataString = String.init(data: self.data, encoding: .utf8), let object = JSONDeserializer<T>.deserializeFrom(json: dataString) else { return nil } return object } /// 制定的某个 Key 对应的模型 public func mapObject<T: HandyJSON>(_ type: T.Type ,designatedPath: String) -> T?{ guard let dataString = String(data: self.data, encoding: .utf8), let object = JSONDeserializer<T>.deserializeFrom(json: dataString, designatedPath: designatedPath) else { return nil } return object } /// Data 对应的 [Model] public func mapArray<T: HandyJSON>(_ type: T.Type) -> [T?]? { guard let dataString = String(data: self.data, encoding: .utf8), let object = JSONDeserializer<T>.deserializeModelArrayFrom(json: dataString) else { return nil } return object } /// Data 某个Key 下对应的 的 [Model] public func mapArray<T: HandyJSON>(_ type: T.Type ,designatedPath: String ) -> [T?]? { guard let dataString = String(data: self.data, encoding: .utf8), let object = JSONDeserializer<T>.deserializeModelArrayFrom(json: dataString , designatedPath: designatedPath) else { return nil } return object } }
7711f1af0388c0642a6edf6a77028ba2
24.761194
121
0.573001
false
false
false
false
sessionm/ios-swift-sdk-example
refs/heads/master
swift-3/complete/ios-swift-sdk-example/achievements/custom/AchievementViewController.swift
mit
1
// // AchievementViewController.swift // ios-swift-sdk-example // // Copyright © 2016 SessionM. All rights reserved. // import UIKit open class AchievementViewController: UIViewController { @IBOutlet weak var achievementIcon: UIImageView! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var pointsLabel: UILabel! var _achievement : SMAchievementData?; var _achievementActivity : SMAchievementActivity?; open var achievement : SMAchievementData? { set { _achievement = newValue; if let achieveData = _achievement { _achievementActivity = SMAchievementActivity(data: achieveData); if let achieve = _achievementActivity { achieve.notifyPresented(); } showAchieve(achieveData); } } get { return nil; } }; func showAchieve(_ achievement : SMAchievementData) { messageLabel.text = achievement.message; nameLabel.text = achievement.name; pointsLabel.text = "\(achievement.pointValue)"; if let url = achievement.achievementIconURL { loadFromUrl(url) { (image : UIImage?) in if let draw = image { self.achievementIcon.image = draw; } } } } @IBAction func onClaim(_ sender: UIButton) { self.presentingViewController!.dismiss(animated: true, completion: { if let achieve = self._achievementActivity { achieve.notifyDismissed(dismissType: .claimed); } }); } @IBAction func onCancel(_ sender: UIButton) { if let achieve = _achievementActivity { achieve.notifyDismissed(dismissType: .canceled); } self.presentingViewController?.dismiss(animated: true, completion: nil); } // Not optimal, but gets URL load off UI Thread func loadFromUrl(_ url : String, callback : @escaping ((UIImage?) -> Void)) { let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated); queue.async { if let imageData = try? Data(contentsOf: URL(string: url)!) { let image = UIImage(data: imageData); DispatchQueue.main.async(execute: { callback(image); }); } } } }
b685e025e06a25a6b400855799b5558a
30.649351
82
0.589249
false
false
false
false
mkoehnke/WKZombie
refs/heads/master
Sources/WKZombie/Parser.swift
mit
1
// // Parser.swift // // Copyright (c) 2015 Mathias Koehnke (http://www.mathiaskoehnke.de) // // 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 hpple /// Base class for the HTMLParser and JSONParser. public class Parser : CustomStringConvertible { /// The URL of the page. public fileprivate(set) var url : URL? /** Returns a (HTML or JSON) parser instance for the specified data. - parameter data: The encoded data. - parameter url: The URL of the page. - returns: A HTML or JSON page. */ required public init(data: Data, url: URL? = nil) { self.url = url } public var description: String { return "\(type(of: self))" } } //======================================== // MARK: HTML //======================================== /// A HTML Parser class, which wraps the functionality of the TFHpple class. public class HTMLParser : Parser { fileprivate var doc : TFHpple? required public init(data: Data, url: URL? = nil) { super.init(data: data, url: url) self.doc = TFHpple(htmlData: data) } public func searchWithXPathQuery(_ xPathOrCSS: String) -> [AnyObject]? { return doc?.search(withXPathQuery: xPathOrCSS) as [AnyObject]? } public var data: Data? { return doc?.data } override public var description: String { return (NSString(data: doc?.data ?? Data(), encoding: String.Encoding.utf8.rawValue) ?? "") as String } } /// A HTML Parser Element class, which wraps the functionality of the TFHppleElement class. public class HTMLParserElement : CustomStringConvertible { fileprivate var element : TFHppleElement? public internal(set) var XPathQuery : String? required public init?(element: AnyObject, XPathQuery : String? = nil) { if let element = element as? TFHppleElement { self.element = element self.XPathQuery = XPathQuery } else { return nil } } public var innerContent : String? { return element?.raw as String? } public var text : String? { return element?.text() as String? } public var content : String? { return element?.content as String? } public var tagName : String? { return element?.tagName as String? } public func objectForKey(_ key: String) -> String? { return element?.object(forKey: key.lowercased()) as String? } public func childrenWithTagName<T: HTMLElement>(_ tagName: String) -> [T]? { return element?.children(withTagName: tagName).flatMap { T(element: $0 as AnyObject) } } public func children<T: HTMLElement>() -> [T]? { return element?.children.flatMap { T(element:$0 as AnyObject) } } public func hasChildren() -> Bool { return element?.hasChildren() ?? false } public var description : String { return element?.raw ?? "" } } //======================================== // MARK: JSON //======================================== /// A JSON Parser class, which represents a JSON document. public class JSONParser : Parser { fileprivate var json : JSON? required public init(data: Data, url: URL? = nil) { super.init(data: data, url: url) let result : Result<JSON> = parseJSON(data) switch result { case .success(let json): self.json = json case .error: Logger.log("Error parsing JSON!") } } public func content() -> JSON? { return json } override public var description : String { return "\(String(describing: json))" } }
b1a0a828c6893aac746f08e5ad231fdb
29.490446
109
0.618968
false
false
false
false
PD-Jell/Swift_study
refs/heads/master
SwiftStudy/RxSwift/RxSwift-Chameleon/RxChameleonViewController.swift
mit
1
// // RxChameleonViewController.swift // SwiftStudy // // Created by YooHG on 7/8/20. // Copyright © 2020 Jell PD. All rights reserved. // import ChameleonFramework import UIKit import RxSwift import RxCocoa class RXChameleonViewController: UIViewController { var circleView: UIView! var circleViewModel: CircleViewModel! var disposeBag: DisposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() setup() } func setup() { circleView = UIView(frame: CGRect(origin: view.center, size: CGSize(width: 100.0, height: 100.0))) circleView.layer.cornerRadius = circleView.frame.width / 2.0 circleView.center = view.center circleView.backgroundColor = .green view.addSubview(circleView) circleViewModel = CircleViewModel() circleView .rx.observe(CGPoint.self, "center") .bind(to: circleViewModel.centerVariable) .disposed(by: disposeBag) // CircleView의 중앙 지점을 centerObservable에 묶는다.(bind) // ViewModel의 새로운 색을 얻기 위해 backgroundObservable을 구독한다. circleViewModel.backgroundColorObservable .subscribe(onNext: {[weak self] backgroundColor in UIView.animate(withDuration: 0.1, animations: { self?.circleView.backgroundColor = backgroundColor // 주어진 배경색의 보색을 구한다. let viewBackgroundColor = UIColor(complementaryFlatColorOf: backgroundColor) if viewBackgroundColor != backgroundColor { self?.view.backgroundColor = viewBackgroundColor } }) }) .disposed(by: disposeBag) let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(circleMoved(_:))) circleView.addGestureRecognizer(gestureRecognizer) } @objc func circleMoved(_ recognizer: UIPanGestureRecognizer) { let location = recognizer.location(in: view) UIView.animate(withDuration: 0.1, animations: { self.circleView.center = location }) } }
8f611b0d834d549bc4978bbe011385fc
33.296875
106
0.620501
false
false
false
false
jad6/DataStore
refs/heads/master
Example/Places/Settings.swift
bsd-2-clause
1
// // Settings.swift // Places // // Created by Jad Osseiran on 28/06/2015. // Copyright © 2015 Jad Osseiran. All rights reserved. // import Foundation var sharedSettings = Settings() struct Settings { enum Thread: Int { case Main = 0, Background, Mixed } var thread = Thread.Main enum DelayDuration: Int { case None = 0 case OneSecond case FiveSeconds case TenSeconds case ThirtySeconds } var delayDuration = DelayDuration.None enum BatchSize: Int { case OneItem = 1 case TwoItems case FiveItems case TwentyItems case FiftyItems case HunderdItems } var batchSize = BatchSize.OneItem var atomicBatchSave = false // Index Path Helpers let threadSection = 0 var checkedThreadIndexPath: NSIndexPath { let row: Int switch thread { case .Main: row = 0 case .Background: row = 1 case .Mixed: row = 2 } return NSIndexPath(forRow: row, inSection: 0) } let delaySection = 1 var checkedDelayIndexPath: NSIndexPath { let row: Int switch delayDuration { case .None: row = 0 case .OneSecond: row = 1 case .FiveSeconds: row = 2 case .TenSeconds: row = 3 case .ThirtySeconds: row = 4 } return NSIndexPath(forRow: row, inSection: 1) } let batchSection = 2 var checkedBatchIndexPath: NSIndexPath { let row: Int switch batchSize { case .OneItem: row = 1 case .TwoItems: row = 2 case .FiveItems: row = 3 case .TwentyItems: row = 4 case .FiftyItems: row = 5 case .HunderdItems: row = 6 } return NSIndexPath(forRow: row, inSection: 2) } }
9855b70b0ce7c71e38ec8526a7c94c2f
20.554348
55
0.533535
false
false
false
false