I am parsing files with the ast package.
I have been looking at the documentation for a bit and I can't find a way to determine if a token is a package declaration, e.g: package main at the beggining of the file.
func find_package(node ast.Node) bool {
switch x := node.(type) {
// This works with *ast.Ident or *ast.FuncDecl ... but not
// with *ast.Package
case *ast.Package:
fmt.Print(x.Name)
}
return true
}
I am looking for a clean way to do this with the ast package, I am almost sure I am just missing something in the documentation.
So basically, it seems like you have to look for a File instead of a package:
func find_package(node ast.Node) bool {
switch x := node.(type) {
case *ast.File:
fmt.Print(x.Name)
}
return true
}
https://golang.org/pkg/go/ast/#File
Related
I tried to optimize a reactive endpoint streaming input of an audio file based on Quarkus REST Score Console. I replaced generic Response with Reactive RestResponse. It increased the score to 100 but it is using ServerStringMessageBodyHandler instead of ServerInputStreamMessageBodyHandler now. Is there a way to tell Quarkus what MessageBodyHandler to use? Now it is calling .toString() method on inputStream object. I tried to return directly ByteArray, but the issue is the same. Any idea what is going on wrong here?
#GET
#Path("/{lectureId}/stream")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
fun getLectureStreamById(
#RestHeader("Range") rangeParam: String?,
#RestPath lectureId: LectureId
): Uni<RestResponse<InputStream>> {
return lectureAudioService.getAudioFile(lectureId).map { lectureStream ->
downloadResponse(ByteArrayInputStream(lectureStream.data), filename = "$lectureId.mp3").build()
}
}
fun downloadResponse(
data: InputStream,
filename: String,
): ResponseBuilder<InputStream> {
return ResponseBuilder.ok(data)
.header("Content-Disposition", "attachment;filename=$filename")
}
Based on answer in github issue it should be fixed in upcoming releases but original approach was not good as well because it blocked event loop. Better approach will be:
#Path("/{filename}/async-file")
#GET
#Produces(MediaType.APPLICATION_OCTET_STREAM)
fun getAsyncFile(filename: String): Uni<RestResponse<AsyncFile>> {
return Uni.createFrom().emitter { emitter: UniEmitter<in RestResponse<AsyncFile>> ->
vertx.fileSystem().open(
"$filename.mp3", OpenOptions()
) { result: AsyncResult<AsyncFile> ->
if (result.succeeded()) emitter.complete(
ResponseBuilder.ok(result.result()).header("Content-Disposition", "attachment;filename=$filename.mp3").build()
) else emitter.fail(result.cause())
}
}
}
Thanks to #geoand
suspend fun heyStackOverFlow(): Int {
val flow1 = flow<Int> { 1 }
val flow2 = flow<Int> { 2 }
return flow1.combine(flow2) { f1, f2 -> f1 + f2 }.single()
}
I use this in build.gradle
sourceSets {
val commonMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2-native-mt")
...
}
}
I get this error
kotlin.IllegalStateException: There is no event loop. Use runBlocking { ... } to start one.
I've tried playing around with actual / expected dispatchers from other questions but no success.
On android this works perfectly, on ios it doesn't.
You could check gradle dependencies as some 3rd party might be pulling in a non native-mt version of coroutines.
If that's the case you can force using the native-mt version as suggested by Philip:
version {
strictly("1.5.2-native-mt")
}
I'm calling shared files created by Golang from ruby-ffi.
However, when I run Golang alone, the process works, but when I run it via ruby-ffi, the comparison doesn't work.
package main
import (
"C"
"fmt"
)
//export zen_roma_to_han_roma
func zen_roma_to_han_roma(s string) string {
if s=="test" {
return "10"
}
return s
}
func main(){
fmt.Println(zen_roma_to_han_roma("test"))
}
$ go run replace.go
10
Here's an example of what can go wrong.
First, create a go build and load it.
go build -buildmode=c-shared -o replace.so replace.go
module Sample
extend FFI::Library
ffi_lib 'replace.so'
attach_function :zen_roma_to_han_roma, [:string], :string
end
[5] pry(main)> Sample.zen_roma_to_han_roma("test")
=> "test
I don't know the cause of this and I need your help.
Is there anything else I should try?
I am not a Golang programmer but still here is a quote from the FFI gem documentation
:string should be considered to be const char * and the Ruby string must not be changed as long as it’s accessed by the library. If the string buffer shall be modified from C or Ruby side, use :pointer and FFI::MemoryPointer instead.
So you should pass *C.char as an argument and return a value of the same type instead of string.
package main
import (
"C"
"fmt"
)
//export zen_roma_to_han_roma
func zen_roma_to_han_roma(s *C.char) *C.char {
test_string := C.GoString(s)
if test_string == "test" {
return C.CString("10")
}
return s
}
func main() {
fmt.Println(C.GoString(zen_roma_to_han_roma(C.CString("test"))))
}
new approach to ask my question. I thought it was clear but apparently
not. :-D 2nd chance.
I use SWXMLhash to get information from websites. For each website i need a different struct, because the datastructure of each website is different.
I have a good working function (using 1 website as source) which i would like to transform to a general function depending on the chosen website.
The best solution i have got so far (see code below) got me a compile error on:
TorrentProviderItem = try xmlTorrent["rss"]["channel"]["item"].value()
compile error = Ambiguous reference to member 'subscript'
code of function:
private func setResultsToEqualData(result: String, Torrentprovider: TorrentProviders) {
var TorrentProviderItem: [XMLIndexerDeserializable]
var xmlTorrent: XMLIndexer!
xmlTorrent = SWXMLHash.parse(result)
switch Torrentprovider {
case .ExtraTorrent:
TorrentProviderItem = [ExtraTorrentItem]()
default:
TorrentProviderItem = [Torrentz2Item]()
}
do {
TorrentProviderItem = try xmlTorrent["rss"]["channel"]["item"].value()
} catch {
print("FOUT in torrent!!")
return
}
selectBestResult()
}
I have no clue how to fix this. Anyone else?
ps in the original function for 1 website i use:
var TorrentProviderItem: [ExtraTorrentItem]
and without the switch, that works fine.
Some showed me the options of a function within a struct. So i used this to build a workaround. I wrote a function in each struct for each website, the returning value of each function is of the same datatype.
For me it is a workaround and not the solution. I still have to add every website to the function (see below).
private func setResultsToEqualData(result: String, Torrentprovider: TorrentProviders) -> torrentProviderItem? {
var TorrentProviderItem = [torrentProviderItem]()
var xmlTorrent: XMLIndexer!
xmlTorrent = SWXMLHash.parse(result)
switch Torrentprovider {
case .ExtraTorrent:
var tempExtraTorrentItem: [ExtraTorrentItem]
do {
tempExtraTorrentItem = try xmlTorrent["rss"]["channel"]["item"].value()
for item in tempExtraTorrentItem {
TorrentProviderItem.append(item.result())
}
} catch {
print("FOUT in torrent!!")
return nil
}
case .Torrentz2:
var tempTorrentz2Item: [Torrentz2Item]
do {
tempTorrentz2Item = try xmlTorrent["rss"]["channel"]["item"].value()
for item in tempTorrentz2Item {
TorrentProviderItem.append(item.result())
}
} catch {
print("FOUT in torrent!!")
return nil
}
}
return (selectBestResult(results: TorrentProviderItem))
}
I think the solution to create a general function lay's within the Strucs. To use one struct for all websites in stead of a struct for each website. I just don't know how to do this. Jet.
While using PMD code analyser,
I have shown several duplicates which includes framework classes and delegates and datasource methods too, I just want to suppress those findings. I tried with Suppress warnings not works. Also I can't find syntax for Objective-c. Can any one give me how to suppress duplicate findings in PMD?
I tried the below command for excluding the directory,
./run.sh cpd --files
/Users/Arun/Documents/Projects/Sample
--language objectivec --minimum-tokens 100 --format xml --exclude /Users/Arun/Documents/Projects/Sample/ExternalFrameworks.
I don't see any duplicate suppression syntax for objective-c.
There is currently no support to have CPD ignore chunks of code in any other language than Java. The only option available is to fully ignore files using the --exclude flag.
Supporting it through comments (// CPD-[OFF|ON] | /* CPD-[OFF|ON] */) should be relatively easy since Objective-C is implemented using JavaCC.
The source code is tokenized here. CPD suppression consists merely of dropping the ignored tokens from tokenEntries.
To do so, you first need to find comments, this is done by checking if currentToken.specialToken is not null.
Token st = currentToken.specialToken;
while (st != null) {
if (st.image.contains("CPD-OFF") {
suppressing = true;
break;
}
if (st.image.contains("CPD-ON") {
suppressing = false;
break;
}
st = st.specialToken;
}
and then checking if the value of suppressing before adding (or not) the token here
Final code should look something such as:
boolean suppressing = false;
while (currentToken.image.length() > 0) {
if (!suppressing) {
tokenEntries.add(new TokenEntry(currentToken.image, sourceCode.getFileName(), currentToken.beginLine));
}
currentToken = (Token) tokenManager.getNextToken();
Token st = currentToken.specialToken;
while (st != null) {
if (st.image.contains("CPD-OFF") {
suppressing = true;
break;
}
if (st.image.contains("CPD-ON") {
suppressing = false;
break;
}
st = st.specialToken;
}
}
PRs are always welcomed. This along with a couple unit tests should be enough to get this merged for the next release.