I m creating code detector using follwing library
https://github.com/Meniny/HighlightJS.swift
But its not with line numbers. Their is one library available which can be integrated with highlight.js https://github.com/wcoder/highlightjs-line-numbers.js/ I m struggling to integrate it with Highlighter.js but no luck
bellow is the code snippet
jsContext = JSContext()
jsContext.evaluateScript("var window = {};")
bundle = Bundle(for: Highlightr.self)
guard let hgPath = bundle.path(forResource: "highlight.min", ofType: "js") else
{
return nil
}
guard let ngPath = bundle.path(forResource: "highlightjs-line-numbers.min", ofType: "js") else
{
return nil
}
let hgJs = try! String.init(contentsOfFile: hgPath)
let ngJs = try! String.init(contentsOfFile: ngPath)
var value = jsContext.evaluateScript(hgJs)
value = jsContext.evaluateScript(ngJs)
if !(value?.toBool())!
{
return nil
}
guard setTheme(to: "pojoaque") else
{
return nil
}
Can anyone help me in this, Thanks
Related
I have already copy the file absolute path and paste in simulator browser, the image can be opened. But the fileExists is fail, i dont know why..... Can anyone help
let defaultImage = "302C3FA1-E4E1-4CD8-B6DF-2FF4E4E24C11.jpeg"
loadImage(at: defaultImage)
func fileExists(at path: String) -> Bool {
return FileManager.default.fileExists(atPath: path)
}
func loadImage(at path: String) -> UIImage? {
let tempPath = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
let imagePath = "\(tempPath)\(path.trimmingCharacters(in: .whitespacesAndNewlines))"
guard fileExists(at: imagePath) else { return nil }
guard let image = UIImage(contentsOfFile: imagePath) else { return nil }
return image
}
You need split filename and extension filename.
If you use main bundle. you can follow this code
let stringPath = Bundle.main.path(forResource: "your_filename", ofType: "txt")
let urlPath = Bundle.main.url(forResource: "your_filename", withExtension: "txt")
or you can use my code.
func readConfigFromBundle(fileExtension: String) -> TCBConfigure? {
let bundle = Bundle.main
if let resPath = bundle.resourcePath {
do {
let dirContents = try FileManager.default.contentsOfDirectory(atPath: resPath)
let filteredFiles = dirContents.filter { $0.contains(fileExtension) }
for fileName in filteredFiles {
let sourceURL = bundle.bundleURL.appendingPathComponent(fileName)
let data: NSData? = NSData.init(contentsOf: sourceURL)
if let fileData = data {
// implement your logic
}
}
} catch {
// implement when error
}
}
return nil
}
I need to run a tensorflow lite model in iOS, from input it receives an array (1, 4500, 1), but I don't understand how to send it to input without transforming it as data.
If I print it out to the Interpreter and the Input tells me exactly what I need, but when I run the code it prints out nil output.
I found this in the internet guides:
let resultArray = (
boundingBox: [Float](unsafeData: outputBoundingBox.data) ??
)
But the Float unsafedata function tells me it doesn't exist.
Here's my code:
import UIKit
import TensorFlowLite
import SwiftyJSON
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var opt1 = Interpreter.Options()
opt1.threadCount = 2
let model_path = Bundle.main.path(forResource: "model1", ofType: "tflite")
let int1 = try? Interpreter(modelPath: model_path!, options: opt1)
try? int1?.allocateTensors()
let input = try? int1?.input(at: 0).shape
if let filepath = Bundle.main.path(forResource: "numpytest", ofType: "txt") {
do {
let contents = try String(contentsOfFile: filepath)
let data2 = Data(filepath.utf8)
try? int1!.copy(data2, toInputAt: 0)
try? int1?.invoke()
let salida = try? int1?.output(at: 0)
} catch {
// contents could not be loaded
}
} else {
// example.txt not found!
}
}
}
What am I doing wrong, what do I need to add?
Does anyone have any advice or suggestions?
Greetings!
I have a query on a Cloud CKRecord, which checks to see if a documents exists (i.e. has been uploaded as an CKAsset) and if not checks if a URL exists (i.e. has been uploaded as a String). All works well if either exist on their own for a given record, however if both exist when clicking on the link nothing happens.
I feel it is something to do with the if and else if statements -
if filename1 != nil {
let asset1 = record.object(forKey: "courseDocument1") as? CKAsset
let filename = record.object(forKey: "courseDocument1Filename") as! String
let path = (NSTemporaryDirectory() as NSString).appendingPathComponent(filename)
let doc1Data : NSData? = NSData(contentsOf:(asset1?.fileURL)!)
do {
try doc1Data!.write(to: URL(fileURLWithPath: path), options: .atomic)
let url = URL(fileURLWithPath: path)
let urlRequest = URLRequest(url: url)
self.courseDoc1WebView?.loadRequest(urlRequest)
self.venueDocButton1.setTitle(cseDocument1,for: [])
self.venueDocButton1.isHidden = false
self.courseDocumentLabel.isHidden = false
} catch {
print(error)
}
} else if cseDocument1URL != nil && filename1 == nil {
let url1 = URL (string: cseDocument1URL!)
let request1 = URLRequest(url: url1! as URL );
self.courseDoc2WebView.loadRequest(request1 as URLRequest);
self.venueDocButton1.setTitle(cseDocument1,for: [])
self.venueDocButton1.isHidden = false
self.courseDocumentLabel.isHidden = false
} else {
print("No Document Found")
}
Any thoughts?
This turned out to be a simple typo rather than logic -
self.courseDoc2WebView.loadRequest(request1 as URLRequest);
which should actually be -
self.courseDoc1WebView.loadRequest(request1 as URLRequest);
This was solved by printing responses and using the debugger - thanks Phillip Mills
Duncan C, you make a good point too - thank-you.
I'd like to use readStringFromURL method to obtain a file from a plist and then use it on insertDataInArrayFromPlist in order to display it or put it on CoreData, substituting let path = Bundle.main.path(forResource: plistFileName, ofType: plistFileExtension).
the ISSUE the try statement gives me this ERROR
Argument labels '(contentsOfURL:, usedEncoding:)' do not match any available overloads
in my viewDidLoad:
let obtainedfile = readStringFromURL(stringURL: kremoteSamplePlist)
print(obtainedfile ?? "nothing to print")
I retrive the file from web
func readStringFromURL(stringURL:String)-> String!{
if let url = NSURL(string: stringURL) {
do {
return try String(contentsOfURL: url, usedEncoding: nil)
} catch {
print("Cannot load contents")
return nil
}
} else {
print("String was not a URL")
return nil
}
}
then I put the data in a struct
func insertDataInArrayFromPlist(arrayOfEntities: inout [product]) {
let path = Bundle.main.path(forResource: plistFileName, ofType: plistFileExtension)
let localArray = NSArray(contentsOfFile: path!)!
for dict in localArray {
var futureEntity = product()
let bdict = dict as! [String: AnyObject]
futureEntity.name = bdict["Name"] as? String
futureEntity.ProductId = bdict["Product Id"] as? String
arrayOfEntities.append(futureEntity)
}
for element in arrayOfEntities {
print("name is \(element.name!), the id is \(element.ProductId!)")
}
}
Theres a library available via Cocoapods, CSV.swift by Yaslab. Allows you to import a csv directly in Swift code and convert to a data type of your own. Does the job for me.
https://github.com/yaslab/CSV.swift
I have two variable called "Countries" and "Places" and I'm trying to read a Data.plist and retrieve some values
This is the Data.plist:
Data.plist
I can't read the plist from the variables.
Let use as an example, the value of Countries is "Italia" and the value of Places is "Naples", how can I retrieve the two different values written in "Item 0" and "Item 1".
I've been searching for days in internet some tutorial who could help me but I couldn't make any of these working for my case (I used more tutorial examples but due my low reputation I can't post more than 2 links).
I tried to follow these tutorial:
Swift - searching through dictionaries in an array in a plist
http://sweettutos.com/2015/06/03/swift-how-to-read-and-write-into-plist-files/
I tried, for example, to use this code without use the "variables", but even this is not working:
let path = NSBundle.mainBundle().pathForResource("Dati", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)
let value: AnyObject = (dict!.objectForKey("Italia")!.objectForKey("Naples")?.objectForKey("Item 0"))!
Can you please help me on this?
Thanks in advance.
This is a pure Swift solution using only Swift native types:
if let url = NSBundle.mainBundle().URLForResource("Dati", withExtension: "plist"), data = NSData(contentsOfURL: url) {
do {
let dictionary = try NSPropertyListSerialization.propertyListWithData(data, options: [], format: nil) as! [String:AnyObject]
if let city = dictionary["Italia"]?["Naples"] as? [AnyObject] {
let item0 = city[0] as! Int
let item1 = city[1] as! String
} else {
print("Italia or Naples doesn't exist")
}
} catch let error as NSError {
print("Property List Serialization Error: \(error)")
}
} else {
fatalError("File couldn't be read")
}
If you change the plist file to use only String values you can avoid some type casting
if let url = NSBundle.mainBundle().URLForResource("Dati", withExtension: "plist"), data = NSData(contentsOfURL: url) {
do {
let dictionary = try NSPropertyListSerialization.propertyListWithData(data, options: [], format: nil) as! [String:[String:[String]]]
if let city = dictionary["Italia"]?["Naples"] {
let item0 = city[0]
let item1 = city[1]
} else {
print("Italia or Naples doesn't exist")
}
} catch let error as NSError {
print("Property List Serialization Error: \(error)")
}
} else {
fatalError("File couldn't be read")
}