How do I get my wire name to show up when using dynamic indexing? - chisel

When running something like
class Foo extends Module {
val io = IO(new Bundle {
val in = Input(Vec(4, Bool()))
val idx = Input(UInt(2.W))
val en = Input(Bool())
val out = Output(Bool())
})
val x = io.in(io.idx)
val y = x && io.en
io.out := y
}
The generated Verilog loses the x name:
module Foo(
input clock,
input reset,
input io_in_0,
input io_in_1,
input io_in_2,
input io_in_3,
input [1:0] io_idx,
input io_en,
output io_out
);
wire _GEN_1; // #[main.scala 15:13]
wire _GEN_2; // #[main.scala 15:13]
wire _GEN_3; // #[main.scala 15:13]
assign _GEN_1 = 2'h1 == io_idx ? io_in_1 : io_in_0; // #[main.scala 15:13]
assign _GEN_2 = 2'h2 == io_idx ? io_in_2 : _GEN_1; // #[main.scala 15:13]
assign _GEN_3 = 2'h3 == io_idx ? io_in_3 : _GEN_2; // #[main.scala 15:13]
assign io_out = _GEN_3 & io_en; // #[main.scala 16:10]
endmodule
How can I make sure the wire name shows up?

This can be worked around by creating a wire and connecting the dynamic index to the wire:
val x = WireInit(io.in(io.idx))
Which should return:
module Foo(
input clock,
input reset,
input io_in_0,
input io_in_1,
input io_in_2,
input io_in_3,
input [1:0] io_idx,
input io_en,
output io_out
);
wire _GEN_1;
wire _GEN_2;
wire x;
assign _GEN_1 = 2'h1 == io_idx ? io_in_1 : io_in_0;
assign _GEN_2 = 2'h2 == io_idx ? io_in_2 : _GEN_1;
assign x = 2'h3 == io_idx ? io_in_3 : _GEN_2;
assign io_out = x & io_en; // #[main.scala 16:10]
endmodule

Related

Wrong string format when i use persian and english together in Node Js

I have a node js project with MySql database. I have to use Persian data in my DB like:
UserModel = {id: 1200, firstName: 'صابر', lastName: 'سجادی' , nationalCode:'4640147800', displayName: 'saber-sajadi', status: 1, createDateTime: null };
so for run stored procedure i need to convert object to string with this Code:
let objectToString = (object) => {
let _string = "";
let i = 1;
for (let key in object) {
var val = object[key];
_string += (val == undefined || val == null) ? `null` : `'` + val + `' `;
if (i < Object.keys(object).length) {
_string += " , ";
i++;
}
}
return _string;
}
I expect the output of the function to be as follows:
but it return:
1200,'صابر','سجادی','4640147800','saber-sajadi','1',''
Please help me to solve this problem
we can use this function to solve problem:
function wrap(str){ return '\u202B' + str + '\u202C'; }

How to split an UInt() into a Vec of UInt to do subword extraction and assignment?

I have a 16bits register declared like that :
val counterReg = RegInit(0.U(16.W))
And I want to do indexed dibit assignment on module output like that :
//..
val io = IO(new Bundle {
val dibit = Output(UInt(2.W))
})
//..
var indexReg = RegInit(0.U(4.W))
//..
io.dibit = vectorizedCounter(indexReg)
But I have some difficulties to know how to declare vectorizedCounter().
I found some examples using Bundles, but for Vector I don't know. And I can't manage to do that with UInt():
val counterReg = RegInit(UInt(16.W))
//...
io.dibit := counterReg(indexReg*2.U + 1.U, indexReg*2.U)
You could dynamically shift and bit extract the result:
io.dibit := (counterReg >> indexReg)(1, 0)

Getting type from class

I've been working on a project that stores case classes in a database and can take them back out again, storing them works fine but I am having trouble with getting them back out.
For items like Strings, Ints, Floats, etc, are being stored as they are but other types are converted to a JSON string using json4s like so
private def convertToString(obj: AnyRef, objType: Class[_]): String = {
implicit val formats = Serialization.formats(NoTypeHints)
objType match {
case t if t == classOf[String] => obj.asInstanceOf[String]
case t if t == classOf[Int] => obj.toString
case t if t == classOf[Integer] => obj.toString
case t if t == classOf[Boolean] => if (obj.asInstanceOf[Boolean]) "true" else "false"
case t if t == classOf[Short] => obj.toString
case t if t == classOf[Double] => obj.toString
case t if t == classOf[Long] => obj.toString
case t if t == classOf[Float] => obj.toString
case t if t == classOf[Byte] => obj.toString
case _ => write(obj)(formats)
}
}
This is working fine and store items just like I would expect it to, but the problem is converting the items back from JSON.
Lets say I have the case class Test(testInt: Int, testString: String, testMap: Map[String, _]) and I get the data back as 3,'blablabla','{"Test": "Map"}'
I can put all values into a new instance of the class expect for the map, here is the code I am using
private def restoreTypes(objClass: Class[_], argList: Array[Object]): Array[_ <: Object] = {
var correctTypes = Array.empty[Object]
val fields = objClass.getDeclaredFields
for(i <- 0 until fields.length) {
val giveType = argList(i).getClass
val wantedType = fields(i).getType
if(giveType != wantedType && giveType == classOf[String])
read[/*HERE*/](argList(i).asInstanceOf[String])
else
correctTypes = correctTypes :+ argList(i)
}
correctTypes
}
And this method is called list so
objClass.getConstructors()(0).newInstance(restoreTypes(objClass, args): _*)
I am getting stuck on how to pass the wanted type to the read method

Compare json equality in Scala

How can I compare if two json structures are the same in scala?
For example, if I have:
{
resultCount: 1,
results: [
{
artistId: 331764459,
collectionId: 780609005
}
]
}
and
{
results: [
{
collectionId: 780609005,
artistId: 331764459
}
],
resultCount: 1
}
They should be considered equal
You should be able to simply do json1 == json2, if the json libraries are written correctly. Is that not working for you?
This is with spray-json, although I would expect the same from every json library:
import spray.json._
import DefaultJsonProtocol._
Welcome to Scala version 2.10.4 (OpenJDK 64-Bit Server VM, Java 1.7.0_51).
Type in expressions to have them evaluated.
Type :help for more information.
scala> val json1 = """{ "a": 1, "b": [ { "c":2, "d":3 } ] }""".parseJson
json1: spray.json.JsValue = {"a":1,"b":[{"c":2,"d":3}]}
scala> val json2 = """{ "b": [ { "d":3, "c":2 } ], "a": 1 }""".parseJson
json2: spray.json.JsValue = {"b":[{"d":3,"c":2}],"a":1}
scala> json1 == json2
res1: Boolean = true
Spray-json uses an immutable scala Map to represent a JSON object in the abstract syntax tree resulting from a parse, so it is just Map's equality semantics that make this work.
You can also use scalatest-json
Example:
it("should fail on slightly different json explaining why") {
val input = """{"someField": "valid json"}""".stripMargin
val expected = """{"someField": "different json"}""".stripMargin
input should matchJson(expected)
}
When the 2 jsons doesn't match, a nice diff will be display which is quite useful when working with big jsons.
Can confirm that it also works just fine with the Jackson library using == operator:
val simpleJson =
"""
|{"field1":"value1","field2":"value2"}
""".stripMargin
val simpleJsonNode = objectMapper.readTree(simpleJson)
val simpleJsonNodeFromString = objectMapper.readTree(simpleJsonNode.toString)
assert(simpleJsonNode == simpleJsonNodeFromString)
spray-json is definitely great, but I use Gson since I already had dependency on Gson library on my project. I am using these in my unit tests, works well for simple json.
import com.google.gson.{JsonParser}
import org.apache.flume.event.JSONEvent
import org.scalatest.FunSuite
class LogEnricherSpec extends FunSuite {
test("compares json to json") {
val parser = new JsonParser()
assert(parser.parse("""
{
"eventType" : "TransferItems",
"timeMillis" : "1234567890",
"messageXml":{
"TransferId" : 123456
}
} """.stripMargin)
==
parser.parse("""
{
"timeMillis" : "1234567890",
"eventType" : "TransferItems",
"messageXml":{
"TransferId" : 123456
}
}
""".stripMargin))
}
Calling the method compare_2Json(str1,str2) will return a boolean value.
Please make sure that the two string parameters are json.
Welcome to use and test.
def compare_2Json(js1:String,js2:String): Boolean = {
var js_str1 = js1
var js_str2 = js2
js_str1=js_str1.replaceAll(" ","")
js_str2=js_str2.replaceAll(" ","")
var issame = false
val arrbuff1 = ArrayBuffer[String]()
val arrbuff2 = ArrayBuffer[String]()
if(js_str1.substring(0,1)=="{" && js_str2.substring(0,1)=="{" || js_str1.substring(0,1)=="["&&js_str2.substring(0,1)=="["){
for(small_js1 <- split_JsonintoSmall(js_str1);small_js2 <- split_JsonintoSmall((js_str2))) {
issame = compare_2Json(small_js1,small_js2)
if(issame == true){
js_str1 = js_str1.substring(0,js_str1.indexOf(small_js1))+js_str1.substring(js_str1.indexOf(small_js1)+small_js1.length)
js_str2 = js_str2.substring(0,js_str2.indexOf(small_js2))+js_str2.substring(js_str2.indexOf(small_js2)+small_js2.length)
}
}
js_str1 = js_str1.substring(1,js_str1.length-1)
js_str2 = js_str2.substring(1,js_str2.length-1)
for(str_js1 <- js_str1.split(","); str_js2 <- js_str2.split(",")){
if(str_js1!="" && str_js2!="")
if(str_js1 == str_js2){
js_str1 = js_str1.substring(0,js_str1.indexOf(str_js1))+js_str1.substring(js_str1.indexOf(str_js1)+str_js1.length)
js_str2 = js_str2.substring(0,js_str2.indexOf(str_js2))+js_str2.substring(js_str2.indexOf(str_js2)+str_js2.length)
}
}
js_str1=js_str1.replace(",","")
js_str2=js_str2.replace(",","")
if(js_str1==""&&js_str2=="")return true
else return false
}
else return false
}
def split_JsonintoSmall(js_str: String):ArrayBuffer[String]={
val arrbuff = ArrayBuffer[String]()
var json_str = js_str
while(json_str.indexOf("{",1)>0 || json_str.indexOf("[",1)>0){
if (json_str.indexOf("{", 1) < json_str.indexOf("[", 1) && json_str.indexOf("{",1)>0 || json_str.indexOf("{", 1) > json_str.indexOf("[", 1) && json_str.indexOf("[",1)<0 ) {
val right = findrealm(1, json_str, '{', '}')
arrbuff += json_str.substring(json_str.indexOf("{", 1), right + 1)
json_str = json_str.substring(0,json_str.indexOf("{",1))+json_str.substring(right+1)
}
else {
if(json_str.indexOf("[",1)>0) {
val right = findrealm(1, json_str, '[', ']')
arrbuff += json_str.substring(json_str.indexOf("[", 1), right + 1)
json_str = json_str.substring(0, json_str.indexOf("[", 1)) + json_str.substring(right + 1)
}
}
}
arrbuff
}
def findrealm(begin_loc: Int, str: String, leftch: Char, rightch: Char): Int = {
var left = str.indexOf(leftch, begin_loc)
var right = str.indexOf(rightch, left)
left = str.indexOf(leftch, left + 1)
while (left < right && left > 0) {
right = str.indexOf(rightch, right + 1)
left = str.indexOf(leftch, left + 1)
}
right
}

scala swing: draggable / resizable component trait

I'm looking for a scala trait that I can mix in to a scala.swing.Component that will allow that component to be positioned and resized using mouse input.
Ideally it would add little boxes as "handles" to indicate to the user that the component can be resized:
I feel like this is a fairly common task, and there should be some traits out there that support it.
I'm using these in my current project. You probably need to replace the Vector library with your own and add implicit defs. Or use Point/Dimension from swing. The Components need to be in a panel which allows custom positions and sizes, like NullPanel from http://dgronau.wordpress.com/2010/08/28/eine-frage-des-layouts/
trait Movable extends Component{
var dragstart:Vec2i = null
listenTo(mouse.clicks, mouse.moves)
reactions += {
case e:MouseDragged =>
if( dragstart != null )
peer.setLocation(location - dragstart + e.point)
case e:MousePressed =>
this match {
case component:Resizable =>
if( component.resizestart == null )
dragstart = e.point
case _ =>
dragstart = e.point
}
case e:MouseReleased =>
dragstart = null
}
}
trait Resizable extends Component{
var resizestart:Vec2i = null
var oldsize = Vec2i(0)
def resized(delta:Vec2i) {}
listenTo(mouse.clicks, mouse.moves)
reactions += {
case e:MouseDragged =>
if( resizestart != null ){
val delta = e.point - resizestart
peer.setSize(max(oldsize + delta, minimumSize))
oldsize += delta
resizestart += delta
resized(delta)
revalidate
}
case e:MousePressed =>
if( size.width - e.point.x < 15
&& size.height - e.point.y < 15 ){
resizestart = e.point
oldsize = size
this match {
case component:Movable =>
component.dragstart = null
case _ =>
}
}
case e:MouseReleased =>
resizestart = null
}
}
The only Component I know of that is Dragable and resizeable is the InternalFrame on the JDesktop. here is an example:
import swing._
import event._
import javax.swing.{UIManager,JComponent}
import javax.swing.KeyStroke.getKeyStroke
import java.awt.{Graphics2D,Graphics}
object InternalFrameDemo extends SimpleSwingApplication{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName)
val top = new MainFrame{
title = "InternalFrameDemo"
preferredSize = new Dimension(640,480)
val desktop = new javax.swing.JDesktopPane
val jc = new JComponent{
override def paint(g:Graphics){
import g._
drawLine(0,0,20,20)
drawLine(0,20,20,0)
println("yay draw")
}
setVisible(true)
}
desktop add jc
contents = Component.wrap(desktop)
menuBar = new MenuBar{
contents += new Menu("Document"){
mnemonic = Key.D
contents += new MenuItem("New"){
mnemonic = Key.N
action = new Action("new"){
def apply = createFrame
accelerator = Some(getKeyStroke("alt N"))
}
}
contents += new MenuItem("Quit"){
mnemonic = Key.Q
action = new Action("quit"){
def apply(){
quit()
}
accelerator = Some(getKeyStroke("alt Q"))
}
}
}
}
def createFrame{
val newFrame = MyInternalFrame()
newFrame setVisible true
desktop add newFrame
newFrame setSelected true
}
}
}
import javax.swing.{JDesktopPane,JInternalFrame}
import collection.mutable.ArrayBuffer
object MyInternalFrame{
var openFrameCount = 0;
val xOffset, yOffset = 30;
def apply() = {
openFrameCount += 1
val jframe = new javax.swing.JInternalFrame("Document #" + openFrameCount,true,true,true,true)
jframe.setSize(300,300)
jframe.setLocation(xOffset*openFrameCount,yOffset*openFrameCount)
jframe //Component.wrap(jframe)
}
}
but both JInternalFrame and JDesktop are not integrated in the scala swing package and need to be wrapped manually.