How to use flatMap and compactMap in Swift

Issue #425 flatMap: map and flatten array of arrays compactMap: map and flatten array of optionals

September 19, 2019 路 1 min 路 Khoa Pham

How to use Firebase ID token

Issue #424 https://medium.com/@jwngr/demystifying-firebase-auth-tokens-e0c533ed330c One confusing point here that people often do not realize is that even though the custom token itself expires after one hour, a modern client SDK authenticated with that custom token will stay authenticated beyond that hour! What happens under the hood is that the custom token is sent to the Firebase Auth service in exchange for an ID token and refresh token pair which are used to keep the client SDK authenticated...

September 17, 2019 路 2 min 路 Khoa Pham

How to use custom domain for GitHub pages

Issue #423 In DNS settings Add 4 A records A @ 185.199.110.153 A @ 185.199.111.153 A @ 185.199.108.153 A @ 185.199.109.153 and 1 CNAME record CNAME www learntalks.github.io In GitHub Select custom domain and type learntalks.com In source public/CNAME learntalks.com

September 17, 2019 路 1 min 路 Khoa Pham

How to constrain to views inside UICollectionViewCell in iOS

Issue #422 To constrain views outside to elements inside UICollectionViewCell, we can use UILayoutGuide. Need to make layout guide the same constraints as the real elements let imageViewGuide = UILayoutGuide() collectionView.addLayoutGuide(imageViewGuide) NSLayoutConstraint.on([ imageViewGuide.topAnchor.constraint(equalTo: collectionView.topAnchor, constant: 16), imageViewGuide.heightAnchor.constraint(equalTo: collectionView.heightAnchor, multiplier: 0.5) ]) NSLayoutConstraint.on([ loadingIndicator.centerXAnchor.constraint(equalTo: collectionView.centerXAnchor), loadingIndicator.centerYAnchor.constraint(equalTo: imageViewGuide.centerYAnchor) ])

September 17, 2019 路 1 min 路 Khoa Pham

How to secure CVC in STPPaymentCardTextField in Stripe for iOS

Issue #421 private func maskCvcIfAny() { guard let view = paymentTextField.subviews.first(where: { !($0 is UIImageView) }), let cvcField = view.subviews .compactMap({ $0 as? UITextField }) .first(where: { $0.tag == 2 && ($0.accessibilityLabel ?? "").lowercased().contains("cvc") }) else { return } cvcField.isSecureTextEntry = true } where tag is in STPPaymentCardTextFieldViewModel.h typedef NS_ENUM(NSInteger, STPCardFieldType) { STPCardFieldTypeNumber, STPCardFieldTypeExpiration, STPCardFieldTypeCVC, STPCardFieldTypePostalCode, }; Also, need to check accessibilityLabel in STPPaymentCardTextField.m - (NSString *)defaultCVCPlaceholder { if (self.viewModel.brand == STPCardBrandAmex) { return STPLocalizedString(@"CVV", @"Label for entering CVV in text field"); } else { return STPLocalizedString(@"CVC", @"Label for entering CVC in text field"); } }

September 16, 2019 路 1 min 路 Khoa Pham

How to replace all occurrences of a string in Javascript

Issue #420 const normalized = string .replace(/\//g, '') .replace(/\"/g, '') .replace(/\(/g, '') .replace(/\)/g, '')

September 16, 2019 路 1 min 路 Khoa Pham

How to read and write file using fs in node

Issue #419 function write(json) { const data = JSON.stringify(json) const year = json.date.getFullYear() const directory = `collected/${slugify(className)}/${year}` fs.mkdirSync(directory, { recursive: true }) fs.writeFileSync( `${directory}/${slugify(studentName)}`, data, { overwrite: true } ) } async function readAll() { const classes = fs.readdirSync('classes') classes.forEach((class) => { const years = fs.readdirSync(`classes/${class}`) years.forEach((year) => { const students = fs.readdirSync(`classes/${class}/${year}`) students.forEach((student) => { const data = fs.readFileSync(`classes/${class}/${year}/${student}) const json = JSON.parse(data) }) }) }) }

September 16, 2019 路 1 min 路 Khoa Pham

How to get videos from vimeo in node

Issue #418 Code Path for user users/nsspain/videos Path for showcase https://developer.vimeo.com/api/reference/albums#get_album Path for Channels, Groups and Portfolios const Vimeo = require('vimeo').Vimeo const vimeoClient = new Vimeo(vimeoClientId, vimeoClientSecret, vimeoAccessToken) async getVideos(path) { const options = { path: `channels/staffpicks/videos`, query: { page: 1, per_page: 100, fields: 'uri,name,description,created_time,pictures' } } return new Promise((resolve, reject) => { try { vimeoClient.request(options, (error, body, status_code, headers) => { if (isValid(body)) { resolve(body) } else { throw error } }) } catch (e) { reject(e) console....

September 16, 2019 路 2 min 路 Khoa Pham

How to get videos from youtube in node

Issue #417 class Youtube { async getVideos(playlistId, pageToken) { const options = { key: clientKey, part: 'id,contentDetails,snippet', playlistId: playlistId, maxResult: 100, pageToken } return new Promise((resolve, reject) => { try { youtube.playlistItems.list(options, (error, result) => { if (isValid(result)) { resolve(result) } else { throw error } }) } catch (e) { reject(e) } }) } } Response look like { "kind": "youtube#playlistItemListResponse", "etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/ZNTrH71d3sV6gR6BWPeamXI1HhE\"", "nextPageToken": "CAUQAA", "pageInfo": { "totalResults": 32, "resultsPerPage": 5 }, "items": [ { "kind": "youtube#playlistItem", "etag": "\"p4VTdlkQv3HQeTEaXgvLePAydmU/pt-bElhU3f7Q6c1Wc0URk9GJN-w\"", "id": "UExDbDVOTTRxRDN1X0w4ZEpyV1liTEI4RmNVYW9BSERGdC4yODlGNEE0NkRGMEEzMEQy", "snippet": { "publishedAt": "2019-04-11T06:09:26....

September 13, 2019 路 1 min 路 Khoa Pham

How to convert callback to Promise in Javascript

Issue #416 // @flow const toPromise = (f: (any) => void) => { return new Promise<any>((resolve, reject) => { try { f((result) => { resolve(result) }) } catch (e) { reject(e) } }) } const videos = await toPromise(callback) If a function accepts many parameters, we need to curry https://onmyway133.github.io/blog/Curry-in-Swift-and-Javascript/ function curry2(f) { return (p1) => { return (p2) => { return f(p1, p2) } } } const callback = curry2(aFunctionThatAcceptsOptionsAndCallback)(options) const items = await toPromise(callback)

September 13, 2019 路 1 min 路 Khoa Pham

How to fix electron issues

Issue #415 Electron require() is not defined https://stackoverflow.com/questions/44391448/electron-require-is-not-defined function createWindow () { win = new BrowserWindow({ title: 'MyApp', width: 600, height: 500, resizable: false, icon: __dirname + '/Icon/Icon.icns', webPreferences: { nodeIntegration: true } }) } DevTools was disconnected from the page npm install babel-cli@latest --save-dev npm install react@16.2.0 win.openDevTools() This leads to Cannot find module 'react/lib/ReactComponentTreeHook' If we鈥檙e using binary, then rebuild, it is the problem that cause devTools not work...

September 12, 2019 路 1 min 路 Khoa Pham

How to easily parse deep json in Swift

Issue #414 Codable is awesome, but sometimes we just need to quickly get value in a deepy nested JSON. In the same way I did for Dart How to resolve deep json object in Dart, let鈥檚 make that in Swift. See https://github.com/onmyway133/Omnia/blob/master/Sources/Shared/JSON.swift public func resolve<T>(_ jsonDictionary: [String: Any], keyPath: String) -> T? { var current: Any? = jsonDictionary keyPath.split(separator: ".").forEach { component in if let maybeInt = Int(component), let array = current as?...

September 12, 2019 路 1 min 路 Khoa Pham

How to work with Hardened runtime and sandbox in macOS

Issue #413 Hardened Runtime and Sandboxing Resolving Common Notarization Issues macOS Code Signing In Depth

September 11, 2019 路 1 min 路 Khoa Pham

How to speed up GMSMarker in Google Maps for iOS

Issue #412 Google Maps with a lot of pin, and no clustering can have bad performance if there are complex view in the marker. The workaround is to use manual layout and rasterization shouldRasterize When the value of this property is true, the layer is rendered as a bitmap in its local coordinate space and then composited to the destination with any other content. Shadow effects and any filters in the filters property are rasterized and included in the bitmap....

September 10, 2019 路 2 min 路 Khoa Pham

How to support drag and drop in UICollectionView iOS

Issue #411 See DragAndDrop example class ViewController: UIViewController, UICollectionViewDropDelegate, UICollectionViewDragDelegate { // MARK:- UICollectionViewDragDelegate func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { let controller = leftController let provider = NSItemProvider( object: controller.imageForCell(indexPath: indexPath) ) let dragItem = UIDragItem(itemProvider: provider) dragItem.localObject = indexPath return [dragItem] } // MARK:- UICollectionViewDropDelegate func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) { let destinationIndexPath: IndexPath if let indexPath = coordinator.destinationIndexPath { destinationIndexPath = indexPath } else { destinationIndexPath = IndexPath(row: 0, section: 0) } let controller = rightController let dragItemIndexPath = coordinator....

September 10, 2019 路 1 min 路 Khoa Pham

How to support drag and drop in NSView

Issue #410 import AppKit import Anchors class DraggingView: NSView { var didDrag: ((FileInfo) -> Void)? let highlightView = NSView() override init(frame frameRect: NSRect) { super.init(frame: frameRect) registerForDraggedTypes([ .fileURL ]) highlightView.isHidden = true addSubview(highlightView) activate(highlightView.anchor.edges) highlightView.wantsLayer = true highlightView.layer?.borderColor = NSColor(hex: "#FF6CA8").cgColor highlightView.layer?.borderWidth = 6 } required init?(coder decoder: NSCoder) { fatalError() } override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { highlightView.isHidden = false return NSDragOperation() } override func draggingEnded(_ sender: NSDraggingInfo) { guard let pathAlias = sender....

September 10, 2019 路 1 min 路 Khoa Pham

How to use NSStepper in Appkit

Issue #409 let stepper = NSStepper() let textField = NSTextField(wrappingLabelWithString: "\(myLocalCount)") stepper.integerValue = myLocalCount stepper.minValue = 5 stepper.maxValue = 24 stepper.valueWraps = false stepper.target = self stepper.action = #selector(onStepperChange(_:)) @objc func onStepperChange(_ sender: NSStepper) { myLocalCount = sender.integerValue textField.stringValue = "\(sender.integerValue)" }

September 8, 2019 路 1 min 路 Khoa Pham

How to handle shortcut in AppKit

Issue #408 Podfile pod 'MASShortcut' let shortcut = MASShortcut(keyCode: kVK_ANSI_K, modifierFlags: [.command, .shift]) MASShortcutMonitor.shared()?.register(shortcut, withAction: { self.showPopover(sender: self.statusItem.button) })

September 8, 2019 路 1 min 路 Khoa Pham

How to select file in its directory in AppKit

Issue #407 https://developer.apple.com/documentation/appkit/nsworkspace/1524399-selectfile In macOS 10.5 and later, this method does not follow symlinks when selecting the file. If the fullPath parameter contains any symlinks, this method selects the symlink instead of the file it targets. If you want to select the target file, use the resolvingSymlinksInPath method to resolve any symlinks before calling this method. It is safe to call this method from any thread of your app....

September 7, 2019 路 1 min 路 Khoa Pham

How to use NSProgressIndicator in AppKit

Issue #406 let progressIndicator = NSProgressIndicator() progressIndicator.isIndeterminate = true progressIndicator.style = .spinning progressIndicator.startAnimation(nil)

September 7, 2019 路 1 min 路 Khoa Pham