Can't write to a csv file from a class in kotlin - csv

Im trying to write a class to csv. And I need or at least prefer a class that I could call that could both retrieve and eventually save the class objects as csv.
I have tried every imaginable way I can find to write files. Everytime it works flawlessly in the main activity .kt, but soon as I move any of it to a dedicated class I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference
or I get told thats is a read only file system.
Heres a copy of a class that ive tried and gotten the error.
package com.example.jobndays
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.PrintWriter
class DryTest: AppCompatActivity() {
fun main() {
var fileInputStream: FileOutputStream? = null
fileInputStream = openFileOutput("bobbin.csv", MODE_PRIVATE)
val bob = "fella"
fileInputStream.write(bob.toByteArray())
}
}

I believe I've found an answer. Apparently in order to write files you need 'context', not entirely sure why, but just ask for it and stick infront of stuff that says they're unresolved.

Related

How to keep val names under withClock() or withClockAndReset() scopes

Val names under withClock() & withClockAndReset() scopes tend to lose their coded names in the generated Verilog file.
So far in order to maintain to original names I used suggestName() function to force the original name.
However I wonder if there is a smarter way do it ? is there a way to force all vals to keep their names without adding suggestName() to each val declaration ?
As Kamyar mentioned in his comment, you should use the #chiselName macro
import chisel3._
import chisel3.experimental.chiselName
#chiselName
class MyModule extends Module {
...
withClock(otherClock) {
val importantReg = Reg(...) // <- this will now get a name
}
}
The way #chiselName works is it will automatically add a .suggestName to each val.

Scala toJson when using net.liftweb.mongodb.record.MongoRecord and Argonaut

I'm scala newbie and come from a Ruby background so and am having trouble rendering json response in my web service for which I use scalatra, mongodb with liftweb mongo record and argonaut for JSon serialisation and deserialisation.
However based on the examples given at http://argonaut.io/ I'm unable to figure out how this would work when using the net.liftweb.mongo.record library.
On compiling this i get a error which says a type mismatch. The error description follows the code snippet.
package firstscalatraapp
import org.scalatra
import net.liftweb.mongodb._
import net.liftweb.mongodb.record.MongoRecord
import net.liftweb.mongodb.record.field.ObjectIdPk
import net.liftweb.record.field.StringField
import net.liftweb.record.field.IntField
import net.liftweb.record.field.PasswordField
import net.liftweb.record.field.DateTimeField
import net.liftweb.mongodb.record.MongoMetaRecord
import argonaut._
import Argonaut._
case class Person private extends MongoRecord[Person] with ObjectIdPk[Person] {
def meta = Person
object age extends IntField(this, 3)
object name extends StringField(this, 29)
object created_at extends DateTimeField(this)
object password extends PasswordField(this)
}
object Person extends Person with MongoMetaRecord[Person] {
implicit def PersonCodecJson: CodecJson[Person] =
casecodec3(Person.apply, Person.unapply)("name", "age", "things")
}
The Error i get is
[error] found : () => firstscalatraapp.Person
[error] required: (?, ?, ?) => ?
[error] casecodec3(Person.apply, Person.unapply)("name", "age", "things")
[error] ^
[error] one error found
[error] (compile:compile) Compilation failed
which seems logical because the constructor does not accept any parameters and the mongo library seems to be generating the val for the fields that i need for the class (I still don't fully understand what the lift mongo wrapper does yet).
So how do i define the implicit to be able to find serialise an object of type person.
Also how do I define serialisation capabilities when i'm dealing with collections. For instance when I have a List[Person].
Thanks in advance. I would really appreciate any help i can get on this.
I'm just about to start using Argonaut so I'm no expert on that but with that said your initial problem seems obvious.
casecodec3 needs a constructor and a deconstructor for the class you're defining the codec for. In the examples of Argonaut they're using case classes and these have automatically generated companion objects with apply/unapply for the fields defined. Which for casecodec3 needs to be 3. In your case, the case class is of zero-arity - you have no case class fields at all. The fields of the record are defined as inner objects with their own apply-methods (very imperative stuff). That's just the way lifts records are defined. So your apply method is just () => Person.
casecodec3 wants a function from a 3-tuple to Person and from Person to a 3-tuple. I would suggest skipping the case definition if you're going to use lift record. And create functions on the side instead. Something like:
object Person extends Person with MongoMetaRecord[Person] {
implicit def PersonCodecJson: CodecJson[Person] =
casecodec3(parse, serialize)("name", "age", "things")
// Something like
def parse(name: String, age: Int, things: Something) = {
val p = Person.createRecord
p.name(name)
...
}
def serialize(p: Person) = (p.name.get, p.age.get, p.things.get)
}
As for your other questions I think you can head back to argonaut.io again. Their documentation seems quite alright - maybe it was worse when you posted this question as it is kind of old?
I'm going to try to replace all my serialization from lift-json to argonaut right now so if you're still stuck (probably not) I might be able to answer better in a bit.

1137: Incorrect number of arguments. Expected no more than 0. statement copied from tutorial but not working

I was following an adobe tutorial in which we make a text field and the text i update in it is from function sayHello()
import flash.display.MovieClip
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.events.TextEvent;
import flash.text.TextField;
var myGreeter:Greeter = new Greeter();
mainText.text = myGreeter.sayHello("Bob");
This is written in first frame^^^^^
SayHello function is in the other actionscript file in same folder with the following code
package
{
import flash.display.MovieClip;
public class Greeter
{
public function sayHello():String
{
var greeting:String;
greeting = "Hello World!";
return greeting;
}
}
}
Maybe some would ask that did you put a TextField on the stage and give it an instance name and the answer is yes i did.
The tutorial i followed i don't know why after telling code told us correct errors if there are in it so there is a possibility that they wanted to train us maybe.
i am a little confuse with greeter class myself as why we write
sayHello("Bob")
Why not
sayHello()
i say this because the variable only has string hellow world what it has to with that man Bob
It would be kind of you if you can also explain me that,
I am asking this too becuase i also need to have complete understanding of code.
I'm not sure, but you may have conflated two steps in the tutorial. You're right that with your definition of sayHello, you should call
sayHello();
To have the function take an argument, you need to define the function to take an argument:
public function sayHello(user:String):String {
return "Hello, " + user + "!";
}
You would then call:
sayHello('Hamza');
and it would return
"Hello, Hamza!"
In short words: "The tutorial is wrong or it is incomplete". You call sayHello with one param but sayHello are declared without params. And the compiler give you right error for this call.

How to connect Gaia Framework with Facebook Graph API?

I'm trying to include a Facebook app in a section of a Flash website developed in GAIA Framework. I've followed many examples and tutorials and I've tried to do a simple login on the Nav Page.
My imported classes (ALL of the facebook api?):
import com.adobe.serialization.json.JSON;
import com.facebook.graph.Facebook;
import com.facebook.graph.controls.*;
import com.facebook.graph.core.*;
import com.facebook.graph.data.*;
import com.facebook.graph.net.*;
import com.facebook.graph.utils.*;
My var with facebook id:
private var FB_app_id:String = 'my app id goes here :)';
My constructor:
public function NavPage()
{
super();
alpha = 0;
init();
Facebook.init(FB_app_id);
}
So, every time I try to publish, the following error appears:
C:\PROJECT ZERO\1 - Proyectos\2p -
WEB\src\com\facebook\graph\data\FQLMultiQuery.as, Line 80 1061: Call
to a possibly undefined method encode through a reference with static
type Class.
Line 80 of FQLMultiQuery.as refers to the following code:
public function toString():String {
return JSON.encode(queries);
}
What could be wrong? What am I doing wrong? I'm starting to think it might be an incompatibility issue between GAIA and the Facebook API.
It seems like you have a conflict with native JSON (since flash player 11) and the JSON from com.adobe.serialization.json package.
My solution for this is to rename the second one. Or start using the new JSON instead and exclude com.adobe.serialization.* from project.
reference:
http://www.pippoflash.com/index.php/2012/06/20/flash-player-10-and-flash-player-11-json-json-conflict-solved/

Writing a parameterized test fails with: There was an error retrieving the parameters for the testcase: cause invalid value for parameterized field

I have a few unit tests that require very large strings for the test data. I do not want to declare the HTML string in the test itself as this can obscure that actual test. Rather, I would like to load these strings from an external resource for each test.
Though I am not running the same test with different sets of data, parameterized tests looks to be a viable solution; however, I am having difficulty getting the following example to work.
Note: This code is based on the TestNG example.
package flexUnitTests
{
import helpers.HTMLDataHelper;
import org.flexunit.runners.Parameterized;
import org.hamcrest.assertThat;
import org.hamcrest.text.containsString;
[RunWith("org.flexunit.runners.Parameterized")]
public class SimpleTestCase
{
private var parameterized:Parameterized;
public static var dataLoader:HTMLDataHelper = new HTMLDataHelper("data/layer.html");
[DataPoint(loader="dataLoader")]
public static var htmlContent:String;
[Test(dataprovider="htmlContent", description="Tests something.")]
public function mustPassThisSimpleTest(htmlContentParam:String):void
{
assertThat(htmlContentParam, containsString("head"));
}
}
}
When I run this test I receive the following error message:
Error: There was an error retrieving the parameters for the testcase:
cause invalid value for parameterized field htmlContent: null
Any thoughts as to what might be the solution to this problem might be?
One solution I found was to run the tests in the class with the Theories runner as shown below.
package flexUnitTests
{
import helpers.HTMLDataHelper;
import org.flexunit.experimental.theories.Theories;
import org.flexunit.runners.Parameterized;
import org.hamcrest.assertThat;
import org.hamcrest.object.equalTo;
import org.hamcrest.text.containsString;
[RunWith("org.flexunit.experimental.theories.Theories")]
public class SimpleTestCase
{
public static var dataLoader:HTMLDataHelper = new HTMLDataHelper("data/layer.html");
[DataPoint(loader="dataLoader")]
public static var htmlContent:String;
[Test(dataprovider="htmlContent", description="Tests something.")]
public function mustPassThisSimpleTest(htmlContentParam:String):void
{
assertThat(htmlContentParam, containsString("head"));
}
}
}
However the side effect is that all of your tests within the test class will display cryptic error messages when the tests fail. For example,
Error: mustWorkWithRegularTests
instead of the much more useful
Error: Expected: a string containing "head"
but: was "this is some text"
Though this does "solve" the problem I was having, IMHO the trade off in message clarity is not worth being able to load data from external sources.