How to use yaml-cpp in NS3 - linker

Does anyone know how to use the yaml-cpp lib in NS3 module?
I have finished the source code, but I have a hard time figuring out how to link it as it got the undefined reference to error when building with waf.

To use yaml-cpp you just have to write something like :
def options(opt):
opt.load("cxx_compiler")
def configure(conf):
conf.load("cxx_compiler")
conf.check_cfg(package = "yaml-cpp", args = ["--cflags", "--libs", ], uselib_store = "YAMLCPP")
def build(bld):
bld.program(source = "main.cpp", use = "YAMLCPP")
waf use pkg-config to get all the options. Main is the source file using yaml-cpp.

Related

Setting file path in imported C function inside Swift Framework

I am trying to use C library source files inside my Cocoa Framework which has function named
void swe_set_ephe_path(char *path);
Which will basically be
swe_set_ephe_path(”C:\\SWEPH\\EPHE”);
for windows.
This library contains other data files which only work after this function is set.
When imported to Swift the function looks like this
swe_set_ephe_path(path: UnsafeMutablePointer<Int8!>)
Since i want to bundle up all the data files in framework and use it in my application, i have done something like this
public class SwissEphemeris {
public init() {
let path = Bundle.main.bundlePath
let swePath = UnsafeMutablePointer<Int8>(mutating: (path as NSString).utf8String)
swe_set_ephe_path(swePath)
}
}
But it seems it's not working and the functions which needs data to be searched in files are not able to operate.
If anybody interested to look into Swiss library documentation, check here for the link,
https://www.astro.com/swisseph/swephprg.htm#_Toc505244836
There are two problems:
First, the resource files are in the “Resources” subdirectory of the framework, not in the top-level framework directory. You can obtain a path to that directory with
let resourcePath = Bundle(identifier: "com.Abhi.SwissFramework")!.resourcePath!
or with
let resourcePath = Bundle(for: type(of: self)).resourcePath!
I suggest to force-unwrap the optionals because you know that the bundle and the resources directory exist. A failure would indicate a build problem which should be detected early.
Second, the C function takes a char * argument even though it does not mutate the passed string. Here you can use the approach from UnsafeMutablePointer<Int8> from String in Swift:
resourcePath.withCString {
swe_set_ephe_path(UnsafeMutablePointer(mutating: $0))
}
Even better: use the dedicated method withUnsafeFileSystemRepresentation() to get the file system representation of the resource path as a C string:
let resourceURL = Bundle(for: type(of: self)).resourceURL!
resourceURL.withUnsafeFileSystemRepresentation {
swe_set_ephe_path(UnsafeMutablePointer(mutating: $0))
}

Bazel: using macros to generate build rules from lists

I'm new to Bazel and got a question regarding Bazel macros. I'm looking for the best way to structure our build.
Is it possible to iterate over a list containing the specifics to the build rules?
For example I have a list containing srcs,deps,hdrs,name etc. This list is combined into one larger list containing all modules i want to build creating one component.
If possible can someone give a short example how this would look in code?
Thanks for your time
ok i got it:
Content of Build.bazel:
load(":macro.bzl","buildmacro")
load(":SrcList.bzl","SrcLists","CommonDependencies")
[buildmacro(
current_module_name = Module[0][0],
current_module_srcs=Module[1],
current_module_hdrs=Module[2],
current_module_deps=Module[3] + CommonDependencies,
)for Module in SrcLists]
Content of macro.bzl:
def buildmacro(current_module_name,current_module_srcs,current_module_hdrs,current_module_deps):
native.cc_library(
name = current_module_name,
deps = current_module_deps,
srcs = current_module_srcs,
hdrs = current_module_hdrs,
linkstatic = 1,
visibility = ["//visibility:public"],
)
Example of the SrcLists-file:
listofcode = [["nameofrule"]["srcfiles"]["headers"]["deps"]...]
listofcode2 = ...
SrcLists = [listofcode] + [listofcode2] ...
execute bazel build :all

Finatra FeatureTests: How to manually deserialize returned json

I read the Finatra getting started guide and I was able to write the HelloWorld Service and its feature test.
Currently my feature test looks like
server.httpPost(
path = "/hi",
postBody = """{"name": "Foo", "dob": 136190040000}""",
andExpect = Ok,
withBody = """{"msg":"Hello Foo. You are 15780 days old today"}""")
This works fine and my tests pass. However my requirement is that I extract the json returned by the server and then manually perform asserts on the object returned.
I changed my code to
val response = server.httpPost(
path = "/hi",
postBody = """{"name": "Abhishek", "dob": 136190040000}""",
andExpect = Ok,
withBody = """{"msg":"Hello Abhishek. You are 15780 days old today"}""")
val json = response.contentString
This also works and I can see the json returned in side the variable json.
My question is that if I have to deserialize this json into an object. Should I just pull in any json library like circe? and then deserialize the object?
or can I use the jackson framework which comes inside of Finatra.
In all examples I could find, I see that Finatra "automatically" handles the json serialization and deserialization. But in my case I want to perform this manually.
You can use the FinatraObjectMapper by calling (using your example) server.mapper. That wraps a Jackson ObjectMapper that you could use if you wanted to use the Jackson library without any of the Finatra add ons.
Or you can import your a different JSON library. If you are using SBT, you can restrict libraries to certain areas of your code, so if you wanted to use circe only in the test code, you could add the following to your build.sbt
"org.scalatest" %% "scalatest" % "2.2.6" % "test"

How to compile and simulate a modelica model that is part of a package with JModelica?

My question is similar to the question of janpeter. I study the ebook by Tiller and try to simulate the example 'Architecture Driven Approach' with OpenModelica and JModelica. I tried the minimal example 'BaseSystem' in OpenModelica and it works fine. But with JModelica version 1.14 I get errors in the compiling process and my script fail. My python script is:
import matplotlib.pyplot as plt
from pymodelica import compile_fmu
from pyfmi import load_fmu
# Variables: modelName, modelFile, extraLibPath
modelName = 'BaseSystem'
modelFile = 'BaseSystem.mo'
extraLibPath = 'C:\Users\Tom\Desktop\Tiller2015a\ModelicaByExample\Architectures'
compilerOption = {'extra_lib_dirs':[extraLibPath]}
# Compile model
fmuName = compile_fmu( modelName, modelFile, compiler_options=compilerOption)
# Load model
model = load_fmu( fmuName)
# Simulate model
res = model.simulate( start_time=0.0, final_time=5.0)
# Extract interesting values
res_w = res['sensor.w']
res_y = res['setpoint.y']
tSim = res['time']
# Visualize results
fig = plt.figure(1)
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.plot(tSim, res_w, 'g-')
ax2.plot(tSim, res_y, 'b-')
ax1.set_xlabel('t (s)')
ax1.set_ylabel('w (???)', color='g')
ax2.set_ylabel('y (???)', color='b')
plt.title('BaseSystem')
plt.legend()
plt.grid(True)
plt.show()
My problem is how to compile and simulate a model that is part of a package?
I am not a jModelica user, but I think I see some confusion in your script. You wrote:
modelName = 'BaseSystem'
modelFile = 'BaseSystem.mo'
extraLibPath = 'C:\Users\Tom\Desktop\Tiller2015a\ModelicaByExample\Architectures'
But that implies (to me) that the compiler should open the package stored at C:\Users\Tom\Desktop\Tiller2015a\ModelicaByExample\Architectures. But the top-level package is ModelicaByExample and the model you want is Architectures.BaseSystem. So I think something like this is probably more appropriate:
modelName = 'Architectures.BaseSystem'
modelFile = 'package.mo'
extraLibPath = 'C:\Users\Tom\Desktop\Tiller2015a\ModelicaByExample'
The essential point here is that you should be opening ModelicaByExample (specifically, the package.mo file in the ModelicaByExample directory). That opens the ModelicaByExample package. You need to open this package because it is the top-level package. You can't load just a sub-package (which is what it looked like you were trying to do). Then, once you've got ModelicaByExample loaded, you can ask the compiler to specifically compile Architectures.BaseSystem.
I suspect OpenModelica was "helping" you by opening the top-level package anyway, even if you were asking it to open the sub-package.
But again, I don't know jModelica very well and I have definitely not tested any of these suggestions.
Thank you Michael Tiller. With your support I found the solution.
First, the modelName has to be full qualified. Second, as you mentioned, the extraLibPath should end at the top-level directory of the library ModelicaByExample. But then I got errors, that JModelica couldn't find components or declarations which are part of the Modelica Standard Library (MSL).
So I added the modelicaLibPath to the MSL, but the error messages remained the same. After many attempts, I launched the command line with administrator privileges and any errors were gone.
Here is the executable python script: BaseSystem.py
### Attention!
# The script and/or the command line must be
# started with administrator privileges
import matplotlib.pyplot as plt
from pymodelica import compile_fmu
from pyfmi import load_fmu
# Variables: modelName, modelFile, extraLibPath
modelName = 'Architectures.SensorComparison.Examples.BaseSystem'
modelFile = ''
extraLibPath = 'C:\Users\Tom\Desktop\Tiller2015a\ModelicaByExample'
modelicaLibPath = 'C:\OpenModelica1.9.2\lib\omlibrary\Modelica 3.2.1'
compileToPath = 'C:\Users\Tom\Desktop\Tiller2015a'
# Set the compiler options
compilerOptions = {'extra_lib_dirs':[modelicaLibPath, extraLibPath]}
# Compile model
fmuName = compile_fmu( modelName, modelFile, compiler_options=compilerOptions, compile_to=compileToPath)
# Load model
model = load_fmu( fmuName)
# Simulate model
res = model.simulate( start_time=0.0, final_time=5.0)
# Extract interesting values
res_w = res['sensor.w']
res_y = res['setpoint.y']
tSim = res['time']
# Visualize results
fig = plt.figure(1)
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.plot(tSim, res_w, 'g-')
ax2.plot(tSim, res_y, 'b-')
ax1.set_xlabel('t (s)')
ax1.set_ylabel('sensor.w (rad/s)', color='g')
ax2.set_ylabel('setpoint.y (rad/s)', color='b')
plt.title('BaseSystem')
plt.legend()
plt.grid(True)
plt.show()

Scala - Remove files from folder by file suffix name

I'm looking for an elegant way to remove all files in a folder that have the extension .jpg
I have the following to count the total jpg files in a folder:
Option(new File(path).list).map(_.filter(_.endsWith(".jpg")).size).getOrElse(0)
Thanks in advance, any help much appreciated :)
for {
files <- Option(new File(path).listFiles)
file <- files if file.getName.endsWith(".jpg")
} file.delete()
Some extra comment,
To extend #Debilski's answer:
Touching files obviously causes side effects. To make this functionally effectfull, please do something like:
def deleteFilesBySuffix[G[_]: Sync](suffix: String)(dirName: String): G[Unit] =
Sync[G].suspend(Sync[G].fromTry(Try(for {
files <- Option(new File(dirName).listFiles)
file <- files if file.getName.endsWith(suffix)
} file.delete())))
Then,
You'll have to run this code with an effect which can delay the
execution of this method like:
import cats.IO
import cats.syntax.foldable._
val r = deleteFilesBySuffix[IO]("jpg")("/tmp")
//Still nothing happened
//Another example with multiple dirs:
val dirNames = List("/tmp", "/tmp/myDir")
val res = dirNames.traverse_(deleteFilesBySuffix[IO]("jpg"))
//Actually run it..
r.unsafeRunSunc()
//Now files are deleted..
In my opinion this is much safer, and uses Scala's power of effects
os-lib lets you delete all files with a certain extension with a one liner:
os.list(os.pwd/"pics").filter(_.ext == "jpg").map(os.remove)
As described here, os-lib is the easiest way to perform filesystem operations with Scala. It lets you write beautiful, concise, Scala code without dealing with ugliness of the underlying Java libs.
Here's some setup code if you'd like to test this out on your machine:
os.makeDir(os.pwd/"pics")
os.write(os.pwd/"pics"/"family.jpg", "")
os.write(os.pwd/"pics"/"cousins.txt", "")
os.write(os.pwd/"pics"/"gf.jpg", "")
os.write(os.pwd/"pics"/"friend.gif", "")

Resources