text:
Q: Determining the rotation around each axis from OpenCV rotation vector I'm trying to better understand the calibrateCamera and SolvePnP functions in OpenCV, specifically the rotation vectors returned by these functions which I believe is an axis-angle rotation vector (NOT as I had thought initially the yaw,pitch,roll angles). I would like to know the rotation around the x,y and z axis of my checkerboard image. The OpenCV functions return a rotation vector in the form rot = [a,b,c]
Using this answer
as a guide I calculate the angle theta with theta = sqrt(a^2,b^2,c^2) and the rotation axis v = [a/theta, b/theta, c/theta];
Then I take these values and use the Axis-Angle To Euler conversion on euclideanspace.com. shown here:
heading = atan2(y * sin(angle)- x * z * (1 - cos(angle)) , 1 - (y^2 + z^2 ) * (1 - cos(angle)))
attitude = asin(x * y * (1 - cos(angle)) + z * sin(angle))
bank = atan2(x * sin(angle)-y * z * (1 - cos(angle)) , 1 - (x^2 + z^2) * (1 - cos(angle)))
I'm using one of the example OpenCV checkerboard images (Left01.jpg), shown below (note the frame axes in the upper left corner with red = x, green = y, blue = z
Using this image I get a rotation vector from calibrateCamera of [0.166,0.294,0.014]
Running these values through the calculations discussed and converting to degrees I get:
heading = 16.7 deg
attitude = 1.7 deg
bank = 9.3 deg
I believe these correspond to yaw,pitch,roll? The 16.7 degree heading seems high looking at the image, but it's hard to tell. Does this make sense? What would be the correct way to figure out the euler angles (angles around each axis) given the OpenCV rotation vector? Snippets of my code are shown below.

double RMSError = calibrateCamera(
        objectPointsArray,
        imagePointsArray,
        img.size(),
        intrinsics,
        distortion,
        rotation,
        translation,
        CALIB_ZERO_TANGENT_DIST |
        CALIB_FIX_K3 | CALIB_FIX_K4 | CALIB_FIX_K5 |
        CALIB_FIX_ASPECT_RATIO);
 Mat rvec =  rotation.at(0);
 //try and get the rotation angles here
 //https://stackoverflow.com/questions/12933284/rodrigues-into-eulerangles-and-vice-versa
 float theta = sqrt(pow(rvec.at<double>(0),2) + pow(rvec.at<double>(1),2) + pow(rvec.at<double>(2),2));
 Mat axis = (Mat_<double>(1, 3) << rvec.at<double>(0) / theta, rvec.at<double>(1) / theta, rvec.at<double>(2) / theta);
 float x_ = axis.at<double>(0);
 float y_ = axis.at<double>(1);
 float z_ = axis.at<double>(2);
 //this is yaw,pitch,roll respectively...maybe
 float heading = atan2(y_ * sin(theta) - x_ * z_ * (1 - cos(theta)), 1 - (pow(y_,2) + pow(z_,2)) * (1 - static_cast<double>(cos(theta))));
 float attitude = asin(x_ * y_ * (1 - cos(theta) + z_ * sin(theta)));
 float bank = atan2(x_ * sin(theta) - y_ * z_ * (1 - cos(theta)), 1 - (pow(x_, 2) + pow(z_, 2)) * (1 - static_cast<double>(cos(theta))));

 float headingDeg = heading * (180 / 3.14);
 float attitudeDeg = attitude * (180 / 3.14);
 float bankDeg = bank * (180 / 3.14);


text:
Q: sizeThatFits on view with constraints (auto layout view inside frame layout view)
View A layouts it's subviews by calculating and setting their frames in layoutSubviews.
View B uses constraints to layout it's subviews.
View A contains a number of View B instances.
View A needs to know the size of its subviews when it layouts them, so it calls sizeThatFits: on them.
View B's height depends on it's width. In my example it has a multiline UILabel inside it.
How should B implement it's sizeThatFits: so it returns the correct size taking both the size parameter passed to sizeThatFits: and the constraints in account?
What I've tried/considered so far:
systemLayoutSizeFittingSize: - doesn't work because it doesn't take into account an exact size passed to it. It can't be used to specify an exact width for e.g a view that grows vertically as it shrinks horizontally. It only gives either the most compressed size or the most expanded size.
intrinsicContentSize- this is used to pass information to Auto Layout as far as i understand from the docs. What we want is to get information from Auto Layout.
This is how i've reasoned so far. Please correct me if i've made a mistake. And please help me, i'd be very grateful if someone could point me to how this is done!
edit: Also, maybe there is some entirely different way to do this, without even using sizeThatFits:? The only requirement i have is that i can continue using frame layout in the "outer" view (View A) and auto layout in the "inner view" (View B).
edit2: Added a picture to illustrate the exact case i must solve
edit3: Forgot to mention, i need to support iOS 7.0

A: From the picture it would appear that a UIStackView might be a better approach for View A?
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIStackView_Class_Reference/
and then just constrain with a margin offset the bottom of the View A UIStackView to the bottom of the last View B

A: I would use Autolayout for the lot. You can still specify exact sizes and positions, you just do it with constraints instead of with frames.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamic repeating conditionalPanel in R shiny dashboard I am trying to create a dynamic conditional panel. So my conditions are as follows:
Input in UI:
selectInput('inpt','Input Number', seq(1,50,1), selectize = FALSE)

My conditional panel UI input is:
conditionalPanel(
  "input.inpt == 2",
  box(
   selectInput("id1", "Select number",
               seq(1, 24, 1), selected = 1),
   selectInput("id2", "Select number",
               seq(1, 24, 1), selected = 1),
   width = 2,
   status = "primary"
  )
 ),

conditionalPanel(
  "input.inpt == 3",
  box(
    selectInput("id1", "Select number",
                seq(1, 24, 1), selected = 1),
    selectInput("id2", "Select number",
                seq(1, 24, 1), selected = 1),
    selectInput("id3", "Select number",
                seq(1, 24, 1), selected = 1),
    width = 2,
    status = "primary"
  )

So this code is working great! But the problem is it is hardcoded.
As you can check in selectInput, I have total of 50 inputs.
I have the exactly same number of new selectInput panels depending on the input.
Example: If 3 is selected, I will have 3 selectInput with id1, id2, id3 (as shown in code above).
If 18 is selected, I will have 18 selectInput with id1, id2, ..., id18.
If 'n' is selected, I will have 'n' selectInput with id1, id2,... idn.
I don't want to write this code so many times.
P.S.: All changes are made in just box(). I don't want to create multiple boxes.
So how to generalised this? If I have 'n' number of inputs how to repeat this approach?

A: You could use a renderUI rather than a conditionalPanel:
output$selectors <- renderUI({
  n <- input$inpt
  selectors <- lapply(1:n, function(i){
    selectInput(paste0("id",i), "Select number", seq(1,24), selected = 1)
  })
  do.call(function(...){
    box(..., width = 2, status = "primary")
  }, selectors)
})

and uiOutput("selectors") in your Shiny UI.

Small example:
library(shiny)
library(shinydashboard)

ui <- fluidPage(
  br(),
  selectInput("inpt", "Input Number", seq(1,50), selectize = FALSE),
  br(),
  uiOutput("selectors")
)

server <- function(input, output, session){

  output[["selectors"]] <- renderUI({
    n <- input[["inpt"]]
    selectors <- lapply(1:n, function(i){
      selectInput(paste0("id",i), "Select number", seq(1,24), selected = 1)
    })
    do.call(function(...){
      box(..., width = 2, status = "primary")
    }, selectors)
  })

}

shinyApp(ui, server)


text:
Q: Can't run SQL query via AJAX request, same type of AJAX query used and works fine everywhere other than this I'm using this AJAX call everywhere else and it works like a charm but only this gives problem. I don't understand what is the problem? Why I'm getting "Error retried record:" still I don't see any problem and so easy.
PS: I echoed the values at AJAX side response and getting all three values there but database gives problem. More, same SQL query works fine at database side but when it deals with AJAX and PHP, it gives problem.
Values passed fine:

id1=get-version&id2=machine055&id3=vmlab

Database query seems fine:
SELECT `version` FROM `table1` where `machine` = 'machine055'

PHP+UI:
serverChange.on('change', function(){
            $("#progress").show();
            var selectedServer = $(this).val();

            $.ajax({
                type: "POST",
                url: "/web/scripts.php",
                data: { id1: "get-version", id2: selectedServer, id3: "vmlab" },
                success:function(msg){
                    $("#progress").hide();
                    alert(msg);
                }
            });

        });

PHP+Ajax:
if ($_POST['id1'] == "get-version" && $_POST['id3'] == "vmlab") {

    $conn = mysqli_connect("localhost", "root", "pwd", "db");
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT `version` FROM `table1` where `machine` = '" .trim($_POST['id2']). "'";
    if ($conn->query($sql) === TRUE) {
        echo "Machine retrieved successfully.";
    } else {
        echo "Error retried record: " . $conn->error;
    }

A: I tried different approach and its working fine so not exploring much, here is the solution:
    $conn = mysqli_connect("localhost", "root", "pwd", "db");
     if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT `version` FROM `table1` where `machine` = '" .trim($_POST['id2']). "'";
    $result = mysqli_query($conn, $sql);

    while($row =  mysqli_fetch_array($result)) {
        $rows[] = $row['version'];
    }

    echo ($rows[0]);

    $conn->close();

Thanks all for reading the issue and resolution.


text:
Q: UITableView and numberOfRowsInSection crash I have a problem when trying to delete rows from my UITableView:
The UITableView gets the number of rows from NSMutableArray:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return [alertsArray count];
}

I add objects to the NSMutableArray in this way:
- (void)saveButton:(id)sender {
[alertsArray addObject:
[self.tableView reloadData];
}

With this code I allow to delete rows:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source.
    [self.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [alertsArray removeObjectAtIndex:indexPath.row];
    [tableView reloadData];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}

From some reason, when trying to delete rows, the application crashes.
Thanks!

A: You should only do
if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source.
    [alertsArray removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

That is, correct your model first, and then call deleteRowsAtIndexPaths:
You will find the appropriate error message in the console window, BTW.
Also, in general no need to use reloadData here, when you didn't change other things as well.


text:
Q: discord python bot kick command i am  trying to make a discord bot that can kick people with the command .kick
I have it display a message that says (username) has been kicked from the server and the message still shows up, but it doesn't actually kick them.
Here is my code:
    import discord
    from discord.ext import commands

    client = commands.Bot(command_prefix=".")

    @client.event
    async def on_ready():
        print("Bot is Ready")

    @client.command(aliases=['c'])
    @commands.has_permissions(manage_messages = True)
    async def clear(ctx,amount=2):
        await ctx.channel.purge(limit = amount)

    @client.command(aliases=['k'])
    @commands.has_permissions(kick_members = True)
    async def kick(ctx,member : discord.Member,*,reason= "I do not need a reason"):
        await ctx.send(member.name + " has been kicked from the server, because "+reason)
        await member.kick(reason=reason)

    @client.command(aliases=['b'])
    @commands.has_permissions(ban_members = True)
    async def ban(ctx,member : discord.Member,*,reason= "I do not need a reason"):
        await ctx.send(member.name + " has been banned from the server, because"+reason)
        await member.ban(reason=reason)

the error message says:
    File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
        ret = await coro(*args, **kwargs)
      File "C:\Users\user\discordbot\bot.py", line 18, in kick
        await member.kick(reason=reason)
      File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\member.py", line 512, in kick
        await self.guild.kick(self, reason=reason)
      File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\guild.py", line 1849, in kick
        await self._state.http.kick(user.id, self.id, reason=reason)
      File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 241, in request
        raise Forbidden(r, data)
    discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

The above exception was the direct cause of the following exception:
    Traceback (most recent call last):
      File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
        await ctx.command.invoke(ctx)
      File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
        await injected(*ctx.args, **ctx.kwargs)
      File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
        raise CommandInvokeError(exc) from exc
    discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

please note that my .clear command is working perfectly fine, it is just kick and ban
please help, I am on python 3.9.0

A: @client.command()
@commands.has_permissions(administrator=True)
async def kick(ctx, member: discord.Member):
    await member.kick()
    await ctx.message.add_reaction("reaction")

    await ctx.send(f"{member.name} has been kicked by {ctx.author.name}!")

    await log_channel.send(f"{ctx.author.name} has kicked {member.display_name}")

This is what I used for my discord bot. It only lets the people with the kick permission use this command. I hope this helped.

A: This type of error comes when either user who is giving this command or your bot has not been given such admin permissions. In your server you can simply make one role for your bot or can give all privileges to your bot if it is managed by you.
link below may help you regarding this
https://support.discord.com/hc/en-us/articles/206029707-How-do-I-set-up-Permissions-


text:
Q: How can we control the size of a special character? I want to use the following character in a page:

▼

(it's a down arrow character). Is there a way to change its size? I'm not even sure how its initial size is determined anyway - can we apply a font size to it? Or is there some css scale attribute we can apply to it?
Or can I specify its exact width/height in pixels?
Thank you

A: You can use CSS to control it just like any other text.
https://developer.mozilla.org/en-US/docs/CSS/font-size

A: The size of the character is determined by the font family and the font size. Both of them can be set as usual in CSS, with the font-family and font-size properties (or even using old-fashioned HTML font tag). Setting font-size different from other text on the same line tends to cause uneven line spacing, but this does not matter if you are using the character in a block of its own, as the div markup suggests.
The character denoted by ▼ is not an arrow but U+25BC BLACK DOWN-POINTING TRIANGLE "▼". Its relative size (relative to font size) varies a lot by font family, so you should primarily consider the font family choice, using a reasonable list of font families (with comparable size for this character), and only if needed consider font size too.

A: Just like any other font is controlled

▼

A: The same way you control the size of any other character. Just set the font size.


text:
Q: Restricting access to mounted /var/run/docker.sock I am currently developing a webapp using docker-compose and Docker. Currently, there is a front-end Nginx reverse proxy-server in one container and a Rails app in another container.
Sometimes, the Rails app needs to make changes to the Nginx configuration files. I've implemented this by mounting the configuration directory as a shared volume in both containers.
However, to force Nginx to reload its configuration files after the Rails app modifies it, it needs to send a HUP signal to the Nginx process. At the moment, I am implementing this by mounting the host's /var/run/docker.sock into the Rails app container and using a gem to ask the host Docker to send the signal to the right container.
This works fine but now I'm worried about security. If the Rails container is compromised, then the attacker will have root access to the host.
I thought about creating another container who's sole job is to broker access to the socket and exposing a limited API to the main Rails app. But then we run into the same problem of what happens when the broker is also compromised. Not only that but surely there's an easier way?
I searched for some solutions to limit which APIs can be called on /var/run/docker.sock but I wasn't able to find any solutions.
Does anyone have any ideas? Perhaps there is some other way I can reload the Nginx configuration files without having to go through the Docker API?


text:
Q: How do I write a function to search for an element in two dimensional array? How do I write a function to search for an element in two dimensional array: if exists returns 1, otherwise returns no?
#include <stdio.h>

int search(int a[3][3],int x);

int main ()
{
    int Array[3][3]; // array of size 3*3
    int i,j;         //counters i,j
    int result,number;

    for(i=0;i<3;i++)
    {
        printf("\n");
        for(j=0;j<3;j++)
        {
            printf(" Array[%d][%d]= ",i,j);
            scanf("%d", &Array[i][j]);              //Fill The 3*3 array
        }
    }

    printf("Enter The number you want:>");
    scanf("%d",&number);

    result=search(Array,number);

    if(search(Array,number))
        printf("Number exists\n");
    else
       printf("Number does not exists\n");

    return 0;
}

int search(int a[3][3],int x){
    int i,j;
    for(i=0;i<3;i++){

        for(j=0;j<3;j++){

           if (x==a[i][j])
               return 1;
           return 0;
        }
    }
}

is this right ??

A: No, it's not. You need to move the return 0; out of the two for loops, and have it be the last statement in search.

A: No. The return 0; statement should be placed on the line before the very last closing brace.

A: Your program is not running because the search algorithm returns 1 if and only if the search element is in array[0][0], otherwise it returns zero and you think that the element doesn't exists. All you need to do is return 0 after traversing the full multi-dimensional array.
You can look into above answers. They have given good solutions.

A: No because your return 0; is inside the for loops.

A: I think what you want is that :
#include <stdio.h>

int search(int a[3][3],int x);

int main ()
{
    int Array[3][3]; // array of size 3*3
    int i,j; //counters i,j
    int result,number;

    for(i=0;i<3;i++)
    {     printf("\n");
        for(j=0;j<3;j++)
        {
            printf(" Array[%d][%d]= ",i,j);
            scanf("%d", &Array[i][j]);              //Fill The 3*3 array
        }
    }

    printf("Enter The number you want:>");
    scanf("%d",&number);

    result=search(Array,number);

    if(result)
        printf("Number exists\n");
    else
        printf("Number does not exists\n");

    return 0;
}

int search(int a[3][3],int x)
{
    int i,j;
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            if (x==a[i][j])
                return 1;
        }
    }
    return 0;
}

A: Jon gave you the answer you need, but there are some details to be aware of.
C's treatment of arrays is such that the search function doesn't receive a 3x3 array of int; rather, it receives a pointer to a 3-element array of int.  From the C language standard, draft n1256:

6.3.2.1 Lvalues, arrays, and function designators
...
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ''array of type'' is converted to an expression with type ''pointer to type'' that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

Thus, when you call result = search(Array, number);, the type of the expression Array is implicitly converted from a 3-element array of 3-element arrays of int (int [3][3]) to a pointer to a 3-element array of int (int (*)[3]).  In the context of a function parameter declaration, T a[] and T a[n] are synonymous with T *a.  You could change the function prototype to
int search(int (*a)[3], int x)

and it would behave exactly the same.
One consequence of this is that search can operate not just on 3x3 arrays, but on any Nx3 array.  You've written your function to assume that a is always 3x3; if you want to be able to handle arrays of different numbers of rows, you would need to pass in a separate parameter to specify the number of rows in the array:
int search(int (*a)[3], size_t rows, int x)
{
  size_t i, j;
  for (i = 0; i < rows; i++)
    for (j = 0; j < 3; j++)
      if (a[i][j] == x)
        return 1;
  return 0;
}

int main(void)
{
  int fiveRowArray[5][3] = {{ 1, 2, 3}, { 4, 5, 6}, { 7, 8, 9},
                            {10,11,12}, {13,14,15}};
  int twoRowArray[2][3]  = {{ 1, 2, 3}, { 4, 5, 6}};
  int number;

  printf("Gimme a number: ");
  fflush(stdout);
  scanf("%d", &number);

  if (search(array, sizeof fiveRowArray / sizeof *fiveRowArray, number))
    printf("Number exists in fiveRowArray\n");
  else
    printf("Number does not exist in fiveRowArray\n");

  if (search(array, sizeof twoRowArray / sizeof *twoRowArray , number))
    printf("Number exists in twoRowArray \n");
  else
    printf("Number does not exist in twoRowArray \n");

  return 0;
}

The sizeof arr / sizeof *arr expression calculates the number of elements in the array by getting the total array size in bytes (sizeof arr) and dividing that by the number of bytes in an individual array element (sizeof *arr or sizeof arr[0]).  Note that this only works for expressions of array type; it will not work for pointers that are being treated as arrays (such as the expression a in the search function).
If you want to handle different numbers of rows and columns, you'll have to take a different approach:
int search(int *a, size_t rows, size_t cols, int x)
{
  size_t i, j;
  for (i = 0; i < rows; i++)
    for (j = 0; j < cols; j++)
      if (a[i * cols + j] == x)
        return 1;
  return 0;
}

int main(void)
{
  int fiveByThree[5][3] = {...};
  int twoByFour[2][4] = {...};
  ...
  if (search(&fiveByThree[0][0],
             sizeof fiveByThree / sizeof *fiveByThree,
             sizeof fiveByThree[0] / sizeof *fiveByThree[0],
             number))
  ...
  if (search(&twoByFour[0][0],
             sizeof twoByFour / sizeof *twoByFour,
             sizeof twoByFour[0] / sizeof *twoByFour[0],
             number))
  ...
}

In this case, we explicitly pass a pointer to the first element in each array, so instead of receiving a pointer to an array of int, search receives a simple pointer to int, which we treat as a 1D array, and compute the offset manually as i * cols + j.  This code assumes that all elements in the 2D array are contiguous.
Edit
Note that in C99, you can have what are called Variable Length Arrays (VLAs), where the array dimension can be specified by a runtime variable rather than a constant expression; this allows us to write the prototype as
int search(size_t rows, size_t cols, int arr[rows][cols], int x)

and not mess with pointers.


text:
Q: Sqlite database supports blob....how to store image in sqlite in android? I want to store image in sqlite db in android.My question is
1)do I need to convert image to blob before inserting or  can simply insert bitmap/byte[]  that android may covert to blob and store?
2)If I need to convert to blob before storing then how can I convert byte[] to blob .....(I learned to convert drawable to bitmap to byte[])?
I am new to android..please help..

A: Store image in sqlite:
Convert bitmap to byte array.
public static byte[] getBytes(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 0, stream);
    return stream.toByteArray();
}

Insert Image byte array (blob) in Database:
public void addEntry( String name, byte[] image) throws SQLiteException{
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues cv = new  ContentValues();
    cv.put(KEY_IMAGE,   image);
    database.insert( DB_TABLE, null, cv );
}

Retrieve image from sqlite:
Retrieving byte array (blob) data from database :
byte[] image = cursor.getBlob(1); // set your column index instead of 1

Convert byte array to bitmap.
public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}

A: Store an Image from Android to a SQlite and retrieve it
DBHelper.java
public class DBHelper {

public static final String IMAGE_ID = "id";
public static final String IMAGE = "image";
private final Context mContext;

private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

private static final String DATABASE_NAME = "Images.db";
private static final int DATABASE_VERSION = 1;

private static final String IMAGES_TABLE = "ImagesTable";

private static final String CREATE_IMAGES_TABLE =
        "CREATE TABLE " + IMAGES_TABLE + " (" +
                IMAGE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + IMAGE + " BLOB NOT NULL );";

private static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_IMAGES_TABLE);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + CREATE_IMAGES_TABLE);
        onCreate(db);
    }
}

public void Reset() {
    mDbHelper.onUpgrade(this.mDb, 1, 1);
}

public DBHelper(Context ctx) {
    mContext = ctx;
    mDbHelper = new DatabaseHelper(mContext);
}

public DBHelper open() throws SQLException {
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close() {
    mDbHelper.close();
}

// Insert the image to the Sqlite DB
public void insertImage(byte[] imageBytes) {
    ContentValues cv = new ContentValues();
    cv.put(IMAGE, imageBytes);
    mDb.insert(IMAGES_TABLE, null, cv);
}

// Get the image from SQLite DB
// We will just get the last image we just saved for convenience...
public byte[] retreiveImageFromDB() {
    Cursor cur = mDb.query(true, IMAGES_TABLE, new String[]{IMAGE,},
                           null, null, null, null,
                           IMAGE_ID + " DESC", "1");
    if (cur.moveToFirst()) {
        byte[] blob = cur.getBlob(cur.getColumnIndex(IMAGE));
        cur.close();
        return blob;
    }
    cur.close();
    return null;
   }
}

Utils.java
public class Utils {

public static byte[] getImageBytes(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    return stream.toByteArray();
}

public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}

public static byte[] getBytes(InputStream inputStream) throws IOException {
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];

    int len = 0;
    while ((len = inputStream.read(buffer)) != -1) {
        byteBuffer.write(buffer, 0, len);
    }
    return byteBuffer.toByteArray();
  }

}

you can follow this complete tutorial to store/retrieve  image from sqlite
Store an Image from Android to a SQlite and retrieve it


text:
Q: Is it possible to play audio to a line after making a call with Inbound socket mode? I'm working on a CRON or some other external event triggered action which is supposed to make a call and play a sound file using FreeSwitch. I suppose I have to use Inbound event socket mode for that.
When using Outbound mode (triggerd by incoming calls), I can play a file since all DialPlanTools are available. For Inbound mode, only a limited number of commands called, mod_socket is available, and playback is not one of them . I also intend to use say, record, read and maybe others.
I use Outbound socket mode in a separate server to handle the incoming calls, and it doesn't seem to be an easy task to pass the context over. I cannot use Outbound socket, as it is not persistent and FreeSwitch immediately drops connection once the call is over.

A: I guess you missed the "full" parameter:
http://wiki.freeswitch.org/wiki/Event_socket_outbound

A: Freeswitch is tricky. Stanislav Sinyagin has advised uuid_broadcast, but it didn't work alone. You need to add another command (uuid_phone_event) immediately for it to work. The overall code is as follows:
originate sofia/external/sip:+<phone_number_here>@<freeswitch_ip_here> &park
# wait for remote side to pick up the call
uuid_broadcast <uuid_from_originate> speak::cepstral|david|'Some text in single quotes here' aleg
uuid_phone_event <uuid_from_originate>

uuid_broadcast <uuid_from_originate> playback::'<absolute_path_to_mp3_or_wav>' aleg
uuid_phone_event <uuid_from_originate>

sched_hangup +1 <uuid_from_originate>

There a bit less than none documentation on the uuid_phone_event command in FS wiki, and I have accidently spotted it in fs_cli.
And yes, you need another Inbound socket connection to monitor the events (at least no Ruby library supports for listening for server-generated events and issuing commands on the same socket connection).

A: Did you try:
uuid_displace call_uuid start /path/to/file


text:
Q: How to get around some rounding errors? I have a method that deals with some geographic coordinates in .NET, and I have a struct that stores a coordinate pair such that if 256 is passed in for one of the coordinates, it becomes 0. However, in one particular instance a value of approximately 255.99999998 is calculated, and thus stored in the struct. When it's printed in ToString(), it becomes 256, which should not happen - 256 should be 0. I wouldn't mind if it printed 255.9999998 but the fact that it prints 256 when the debugger shows 255.99999998 is a problem. Having it both store and display 0 would be even better.
Specifically there's an issue with comparison. 255.99999998 is sufficiently close to 256 such that it should equal it. What should I do when comparing doubles? use some sort of epsilon value?

EDIT: Specifically, my problem is that I take a value, perform some calculations, then perform the opposite calculations on that number, and I need to get back the original value exactly.

A: This sounds like a problem with how the number is printed, not how it is stored. A double has about 15 significant figures, so it can tell 255.99999998 from 256 with precision to spare.

A: You can choose format strings which should let you display as much of the number as you like.
The usual way to compare doubles for equality is to subtract them and see if the absolute value is less than some predefined epsilon, maybe 0.000001.

A: You could use the epsilon approach, but the epsilon is typically a fudge to get around the fact that floating-point arithmetic is lossy.
You might consider avoiding binary floating-points altogether and use a nice Rational class.
The calculation above was probably destined to be 256 if you were doing lossless arithmetic as you would get with a Rational type.
Rational types can go by the name of Ratio or Fraction class, and are fairly simple to write
Here's one example.
Here's another

Edit....
To understand your problem consider that when the decimal value 0.01 is converted to a binary representation it cannot be stored exactly in finite memory.  The Hexidecimal representation for this value is 0.028F5C28F5C  where the "28F5C" repeats infinitely.  So even before doing any calculations, you loose exactness just by storing 0.01 in binary format.
Rational and Decimal classes are used to overcome this problem, albeit with a performance cost. Rational types avoid this problem by storing a numerator and a denominator to represent your value.  Decimal type use a binary encoded decimal format, which can be lossy in division, but can store common decimal values exactly.
For your purpose I still suggest a Rational type.

A: You have to decide yourself on a threshold under which two values are equal. This amounts to using so-called fixed point numbers (as opposed to floating point). Then, you have to perform the round up manually.
I would go with some unsigned type with known size (eg. uint32 or uint64 if they're available, I don't know .NET) and treat it as a fixed point number type mod 256.
Eg.
typedef uint32 fixed;

inline fixed to_fixed(double d)
{
    return (fixed)(fmod(d, 256.) * (double)(1 << 24))
}

inline double to_double(fixed f)
{
    return (double)f / (double)(1 << 24);
}

or something more elaborated to suit a rounding convention (to nearest, to lower, to higher, to odd, to even). The highest 8 bits of fixed hold the integer part, the 24 lower bits hold the fractional part. Absolute precision is 2^{-24}.
Note that adding and substracting such numbers naturally wraps around at 256. For multiplication, you should beware.


text:
Q: Is it worth updating the database every time a page is visited? I am working on a very simple and small visitor counter and I am wondering myself if it is not too heavy to on the server resources to open a MySQL database every time a visitor enters on a page of the website.
Some people store the visits on a plain-text file and maybe I could store the number in a session (in an array with a key for each page), and when the session is closed, I copy it in the database in one time?
What is the lightest way to do this?

A: In most robust web applications, the database is queried on every page load anyway for some reason or another, so unless you have serious resource limits you're not going to break the bank with your counter query or save much load time by avoid it.
One consideration might be to increase the value of the database update so that one update can be queried for multiple uses. In your case, you could have a view log, like :
INSERT INTO view_log
VALUES (user_name, ip_address, visit_timestamp, page_name)

Which could be used for reporting on popularity of specific pages, tracking user activity, debugging, etc. And the hit count would simply be:
SELECT COUNT(1) FROM view_log

A: If your site has a database already, use it!
Connections are most likely pooled between opens and take very little effort.
If you write to a file the site requires write access to it and you risk concurrency problems during multiple user connections.
Only persisting when session closes is also a risk if the server is closed abruptly..

A: Most sites open a MySQL connection anyway, so if you do, you won't have to open it twice. Writing to disk also takes resources (although probably less), and additionally you might wear out a small part of your disk very fast if you have a file based counter on a busy website. And those file writes will have to wait for each other, while MySQL handles multiple requests more flexible.
Anyway, I would write a simple counter interface that abstracts this, so you can switch to file, MySQL or any other storage easily without having to modify your website too much.


text:
Q: how to DRY chained ActiveRecord calls Consider this bit of code:
if ids.blank?
  UptimeSummary.
    where("start_time >= ?", start_time).
    group(:uptime_monitor_id).
    select("uptime_monitor_id, sum(uptime)/count(*) AS uptime_average")
else
  UptimeSummary.
    where(:uptime_monitor_id => ids).
    where("start_time >= ?", start_time).
    group(:uptime_monitor_id).
    select("uptime_monitor_id, sum(uptime)/count(*) AS uptime_average")
end

The only difference between the two clauses is the additional (:uptime_monitor_id => ids) in the latter clause.
This seems rather un-DRY.  How can I clean that up?

A: I figured out an answer as I was typing in the question.  Because the calls to ActiveRecord query chains are deferred, you can do this:
q = UptimeSummary.
      where("start_time >= ?", start_time).
      group(:uptime_monitor_id).
      select("uptime_monitor_id, sum(uptime)/count(*) AS uptime_average")
q = q.where(:uptime_monitor_ids => ids) unless ids.blank?

If you know of cleaner approach, I'd love to learn about it.


text:
Q: Update json column's individual values So I have a user structure like so:
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('username');
        $table->text('phone');
        $table->string('address');
        $table->string('city');
        $table->string('state');
        $table->string('country');
        $table->string('postal');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('google2fa_secret');
        $table->text('balance');
        $table->rememberToken();
        $table->timestamps();
    });

Now, I am storing values in the 'balance' column like so
{
    "usd": 10,
    "gbp": 10,
    "eur": 10
}

How can I edit for example usd value but keep the others in the array with attributes?
How I am getting the attributes:
/**
 * Get the user's balance
 *
 * @return decimal
 */
public function getBalanceAttribute()
{
    return json_decode( $this->attributes['balance'] );
}

A: Suppose in your users you want to fetch by id and then update then you can do something like this:
DB::table('users')
        ->where('id', 1)
        ->update(['balance->usd' => 12]);

But make sure that is an json column I mean you need to define $table->json('balance'); in your migration. Then you won't be requiring accessor to get json_encode attribute.
For more information check documentation part.


text:
Q: Renaming Red Hat Enterprise Linux Network Interfaces I have a virtual machine on vmware ESXi 6.0 running Red Hat Enterprise Linux 7.2.
I have two network interfaces that I want to be named "eth0" and "eth1" respectively. They were originally named with the prefix "eno..." and then a string of numbers.
I edited the ifcfg files for both interfaces by changing the name and device parameters to "eth0" and "eth1".
I then renamed the ifcfg files to ifcfg-eth0 and ifcfg-eth1.
When I run systemctl restart network I get an error stating that the connection "eth0" is not available on the device "eno167".

It appears that the device name needs to be changed somewhere else in addition to the files in /etc/sysconfig/network-scripts/, where else could I verify that I need to change the network adapter name?

A: udev changed (ruined) it's interface naming scheme a while back.  One of the easiest ways to get the old method back is to add 'net.ifnames=0' as a kernel parameter in your grub.conf file

A: Also worth noting if you don't like the new interface naming convention it is possible to name interfaces whatever you like.
In /etc/sysconfig/network-scripts/ create a file ifcfg-[desired-name]
Add:
DEVICE=[desired-name]
HWADDR=[mac address of the interface]

You can add all the usual settings to this file as well. This will name the interface whatever you like and pairs it up based on the MAC address of your device.
So if you wanted an interface named ftp-interface using the interface with a MAC address 00:00:00:00:00:00 and wanted it to have an IP 1.1.1.1/24 you could use:
/etc/sysconfig/network-scripts/ifcfg-ftp-interface
--------------------------------------------------

DEVICE="ftp-interface"
HWADDR=00:00:00:00:00:00
IPADDR=1.1.1.1
PREFIX=24

You can find more details about how the naming works on the Red Hat site: https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Networking_Guide/sec-Understanding_the_Device_Renaming_Procedure.html

A: Centimane's method works also with centos 7 (redhat based).. Big thanks !
I also have in /etc/NetworkManager/NetworkManager.conf  for plugings just plugins=ifcfg-rh , not keyfile.
this is/was the simplest way to change the interface name.. and I googled a lot!
of course NetworkManager will make a new interface so you have to configure it again... like disable dhcp from it.. so don't block your self out.
if you put just mac and new name to the ifcfg file NetworkManager will fill the rest.


text:
Q: How Does Wordpress Uninclude/Deactivate A Plugin? Wordpress uses the Observer Pattern for its plugin system and operates on the premise of checking if a plugin is activated, scanning the plugins directory and storing everything in an array in the plugins class.
Once it gets the activated plugins, it then proceeds to include the plugin script files, however I am curious as to how Wordpress un-includes plugins when they are deactivated in the admin? If Wordpress is merely including the file via a standard include_once or require_once, how does Wordpress deactivate a plugin and therefore un-include it?
It's from my understanding that you cannot include and then un-include a file in PHP (not that I know of). Can anyone point to me specific files where the plugins are included, and the appropriate functions and files where they are deactivated?
If Wordpress is storing activated plugins in an array of activated plugins, then including them; how does Wordpress know not to let a function inside of a deactivated plugin be called if it's already included?

A: The active plugins are stored in the 'active_plugins' option, like this:
array(
  'akismet/akismet.php',
  'hello-dolly.php',
);

On each page load, WP just loops through that array and includes those files. It's up to each plugin to include any additional files that it may have.
When a plugin is deactivated, it's just removed from that array. On the next page load, it won't be included anymore.
No "un-including" required.


text:
Q: Android how to detect device rotation for portrait configured activity? I am developing a single activity application. It means I have a host activity and several different fragments. In the manifest, there is an attribute for activity android:screenOrientation="portrait" to suppress screen rotation. But in one of my fragments, I need to handle the device rotation to enable landscape orientation. Is there any way to handle the configuration change with attribute screenOrientation="portrait" for a specific fragment?

A: I found an elegant solution for such case.
In the specific fragment just set required orientation.
   override fun onResume() {
        super.onResume()
        requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
    }

    override fun onPause() {
        super.onPause()
        requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }


text:
Q: DocumentDB Spatial Distance Query - Empty Set I am trying to get a valid result from the following DocumentDB spatial query.
In both LINQ or SQL -
SELECT * FROM root
WHERE (ST_Distance(root["Address"]["Location"]["Queryable"],
{"type": "Point", "coordinates": [-36.******, 174.******]}) < 10000)

...and/or:
FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableScanInQuery = true };
IQueryable<Store> documentQuery = client.CreateDocumentQuery<Store>(
UriFactory.CreateDocumentCollectionUri(this.databaseName, this.collection), queryOptions)
.Where(s => s.Address.Location.Queryable.Distance(store.Address.Location.Queryable) < 10000);

...both approaches give me the same result - empty set.
But there are two "Store" documents in the database that should be resolved by this query.
My DB instance is in Australia East - that should be fine apparently.
What am I doing wrong here? My Collection does not have a spatial index on it - is it required?

A: In GeoJSON, points are specified with [longitude, latitude] to make it match with our normal expectations of x being east-west, and y being north-south. Unfortunately, this is the opposite of the traditional way of showing GEO coordinates.
174.xxx is not a valid value for latitude. The range for latitude is -90 to +90. Longitude is specified -180 to +180.
Swap the coordinates and it should work as expected.


text:
Q: Multiple types of build for different build triggers I have a setup where our code builds to dev every 5 hours on a schedule trigger. This works great, but the downside that the code could sit in teamcity for hours before it triggers and alerts us to a build error.
Is there a way to have a VCS trigger also run the build as soon as its checked in, but passing something to our NANT script to say "just build, don't deploy"?
I know I must be missing something.. is there any way to achieve this?
The only way I could think of was to have an entirely separate build configuration, but that seemed rather wasteful

A: You can setup a new build with a VCS trigger and then have that build have a env/system variable set that your build script can read to determine whether or not to deploy to dev.
See TeamCity Docs for information around this. I've used something like this in setting up builds before and it works well.


text:
Q: Efficiency of Fortran stream access vs. MPI-IO I have a parallel section of the code where I write out n large arrays (representing a numerical mesh) in blocks that are later read in different sized blocks. To do this I used Stream access so each processor writes their block independently, but I've seen inconsistent timings taking from 0.5-4 seconds in this section testing with 2 processor groups.
I am aware you can do something similar with MPI-IO, but I'm not sure what the benefits would be since there is no synchronization necessary. I would like to know if there is a way to either improve performance of my writes, or if there is a reason MPI-IO would be a better choice for this section.
Here is a sample of the code section where I create the files to write norb arrays using two groups (mygroup = 0 or 1]:
do irbsic=1,norb
  [various operations]

  blocksize=int(nmsh_tot/ngroups)
  OPEN(unit=iunit,FILE='ZPOT',STATUS='UNKNOWN',ACCESS='STREAM')
  mypos = 1 + (IRBSIC-1)*nmsh_tot*8     ! starting point for writing IRBSIC
  mypos = mypos + mygroup*(8*blocksize) ! starting point for mesh group
  WRITE(iunit,POS=mypos) POT(1:nmsh)
  CLOSE(iunit)

  OPEN(unit=iunit,FILE='RHOI',STATUS='UNKNOWN',ACCESS='STREAM')
  mypos = 1 + (IRBSIC-1)*nmsh_tot*8     ! starting point for writing IRBSIC
  mypos = mypos + mygroup*(8*blocksize) ! starting point for mesh group
  WRITE(iunit,POS=mypos) RHOG(1:nmsh,1,1)
  CLOSE(iunit)

  [various operations]
end do

A: (As discussed in the comments) I would strongly recommend against using Fortran stream access for this. Standard Fortran I/O is only guaranteed to work if the file is being accessed by a single process, and in my own work I have seen random corruptions of files when multiple processes try to write to them at once, even if the processes are writing to different parts of the file. MPI-I/O, or a library such as HDF5 or NetCDF which uses MPI-I/O is the only sensible way to achieve this. Below is a simple program illustrating the use of mpi_file_write_at_all
ian@eris:~/work/stack$ cat at.f90
Program write_at

  Use mpi

  Implicit None

  Integer, Parameter :: n = 4

  Real, Dimension( 1:n ) :: a

  Real, Dimension( : ), Allocatable :: all_of_a

  Integer :: me, nproc
  Integer :: handle
  Integer :: i
  Integer :: error

  ! Set up MPI
  Call mpi_init( error )
  Call mpi_comm_size( mpi_comm_world, nproc, error )
  Call mpi_comm_rank( mpi_comm_world, me   , error )

  ! Provide some data
  a = [ ( i, i = n * me, n * ( me + 1 ) - 1 ) ]

  ! Open the file
  Call mpi_file_open( mpi_comm_world, 'stuff.dat', &
       mpi_mode_create + mpi_mode_wronly, mpi_info_null, handle, error )

  ! Describe how the processes will view the file - in this case
  ! simply a stream of mpi_real
  Call mpi_file_set_view( handle, 0_mpi_offset_kind, &
       mpi_real, mpi_real, 'native', &
       mpi_info_null, error )

  ! Write the data using a collective routine - generally the most efficent
  ! but as collective all processes within the communicator must call the routine
  Call mpi_file_write_at_all( handle, Int( me * n,mpi_offset_kind ) , &
       a, Size( a ), mpi_real, mpi_status_ignore, error )

  ! Close the file
  Call mpi_file_close( handle, error )

  ! Read the file on rank zero using Fortran to check the data
  If( me == 0 ) Then
     Open( 10, file = 'stuff.dat', access = 'stream' )
     Allocate( all_of_a( 1:n * nproc ) )
     Read( 10, pos = 1 ) all_of_a
     Write( *, * ) all_of_a
  End If

  ! Shut down MPI
  Call mpi_finalize( error )

End Program write_at
ian@eris:~/work/stack$ mpif90 --version
GNU Fortran (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

ian@eris:~/work/stack$ mpif90 -Wall -Wextra -fcheck=all -std=f2008 at.f90
ian@eris:~/work/stack$ mpirun -np 2 ./a.out
   0.00000000       1.00000000       2.00000000       3.00000000       4.00000000       5.00000000       6.00000000       7.00000000
ian@eris:~/work/stack$ mpirun -np 5 ./a.out
   0.00000000       1.00000000       2.00000000       3.00000000       4.00000000       5.00000000       6.00000000       7.00000000       8.00000000       9.00000000       10.0000000       11.0000000       12.0000000       13.0000000       14.0000000       15.0000000       16.0000000       17.0000000       18.0000000       19.0000000
ian@eris:~/work/stack$


text:
Q: How to apply default holo light theme to ExpandableListView Please refer to the linked image.

I applied the light theme by using appTheme for my application with
<resources>
    <style name="AppTheme" parent="android:Theme.Light" />
</resources>

in styles.xml
I try to conform to standards so I did minimal styling. The result however, looks faded, it gives an inactive feel. Concerns:

*

*Somehow the groups and childs get styled because they look different than the edittext added for reference - especially the checkboxes to the right are almost invisible.

How to fix? I know I can just set text color, but I try to inherit from standard styles here.
Note: I added style holo.light.expandablelistview randomly, no effect
main layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical" >

    <!-- style="@android:style/Widget.ExpandableListView.White" -->
    <ExpandableListView
        android:id="@+id/targetsList"
        style="@android:style/Widget.Holo.Light.ExpandableListView"
        android:layout_width="match_parent"
        android:layout_height="250dp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="dummyText" />

</LinearLayout>

Group
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="fill"
                style="@android:style/Widget.Holo.Light.ExpandableListView">

    <!-- PARENT -->
    <TextView android:id="@+id/parentname"
              android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
              android:layout_centerVertical="true"
              android:layout_height="wrap_content"
              android:layout_width="wrap_content" />

    <CheckBox android:id="@+id/checkbox"
              android:focusable="false"
              android:layout_alignParentRight="true"
              android:freezesText="false"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content" />

</RelativeLayout>

Child
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="0px"
                android:minHeight="35dp">

    <!-- CHILD -->
    <TextView android:id="@+id/childname"
              android:focusable="false"
              android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
              android:gravity="center_vertical"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content" />

    <CheckBox android:id="@+id/checkbox"
              android:focusable="false"
              android:layout_alignParentRight="true"
              android:freezesText="false"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginTop="5px" />

</RelativeLayout>


text:
Q: How to handle different nodes by type in a parse tree in TypeScript? I have a lexer and parser which I am trying to convert to TypeScript. You can see the full code (JavaScript-only now) here. I tried to boil it down to a simpler example, and I think I might demonstrate the point with this example pseudocode:
type X = {
  type: string
}

type A = X & {
  list: Array<A | B | C>
}

type B = X & {
  value: A | B | number
}

type C = X & {
  value: string
}

const a1: A = { type: 'a', list: [] }
const a2: A = { type: 'a', list: [] }
const a3: A = { type: 'a', list: [] }

const b1: B = { type: 'b', value: a1 }
const b2: B = { type: 'b', value: b1 }
const b3: B = { type: 'b', value: 200 }

const c1: C = { type: 'c', value: 'foo' }
const c2: C = { type: 'c', value: 'bar' }
const c3: C = { type: 'c', value: 'baz' }

a1.list.push(b1, a2, b2, b3)
a2.list.push(a1, a3, b3, c1)
a3.list.push(b2, c2, c3)

const x = { type: 'a', list: [a1, a2, a3] }

handle(x)

function handle(x: A | B) {
  if (x.type === 'a') {
    x.list.forEach(handle)
  } else if (x.type === 'b') {
    if (typeof x.value === 'number') {
      console.log(x.value)
    } else {
      handle(x.value)
    }
  } else { // c
    console.log(x.value)
  }
}

Notice there is no typing used at all in that handle function, I don't know how to do it there....
You'll notice in the parser code (also in there is a lexer in a separate module), there is stuff like this:
while (i < list.length) {
  const token = list[i++]
  // console.log(token.form, stack)
  switch (token.form) {
    case `term-open`: {
      const node = stack[stack.length - 1]
      const term = {
        form: 'term',
        link: []
      }
      node.leaf.push(term)
      stack.push(term)
      break
    }
    case `term-close`: {
      stack.pop()
      break
    }
    case `open-parenthesis`: {
      const node = stack[stack.length - 1]
      const site = {
        form: 'site',
        leaf: [],
        site: []
      }
      node.site.push(site)
      stack.push(site)
      break
    }
    case `close-parenthesis`: {
      stack.pop()
      break
    }
  }

Key thing being const node = stack[stack.length - 1]. This could be any node depending on the context, similar how in my pseudocode we don't know what node we are going to expect.
How do you handle this sort of situation in TypeScript? I can easily do const node = stack[stack.length - 1] as SomeType, but that is hacking it and doesn't seem safe. Or is that the correct approach, I'm not too sure?
How would you correctly iterate through the pseudocode (TypeScript above) and log the leaf values, so everything is properly typed?

A: The "correct" way to do this, or at least the way best supported by TypeScript, is to make your base node type X a discriminated union in which the type property has a string literal type that can be used to distinguish the union member from the other ones.  For your example code that could look like:
interface A {
    type: 'a'; // <-- literal type
    list: Array<A | B | C>
}

interface B {
    type: 'b'; // <-- literal type
    value: A | B | number
}

interface C {
    type: 'c'; // <-- literal type
    value: string
}

type X = A | B | C; // <-- discriminated union

const x: X = { type: 'a', list: [a1, a2, a3] } // okay

And then your handle() function compiles as-is without error:
function handle(x: X) {
    if (x.type === 'a') {
        x.list.forEach(handle)
    } else if (x.type === 'b') {
        if (typeof x.value === 'number') {
            console.log(x.value)
        } else {
            handle(x.value)
        }
    } else { // c
        console.log(x.value)
    }
}

That all works because your tests like x.type === "a" allow the compiler to narrow the apparent type of x.  So in a code block where x.type === "a" is known to be true, then x is known to be of type A.
Playground link to code


text:
Q: QML Row how to transition items from the right? So I have a Row connected to a model and a delegate, when a new item is appended to the row I'd like to animate it from the right.  This works if the width of the new item is "58":
Row {
    id: myRow
    add: Transition {
        NumberAnimation {
            properties: "x"
            from: width + 58
            easing.type: Easing.OutBounce
            duration: 1000
        }
    }

    Repeater {
        model: myModel
        delegate: myDelegate
    }
}

How do I set that width to the width of the item being added instead of hard-coding it?


text:
Q: How to retrieve list of dates that is partially stored in the database and bind it in gridview in c# I want to dynamically display list of dates in grid view. The dates should be row by row and retrieved from the database.
Below are the example of data from database :
DSB_Date   GloveID    DSB_BalQty  DSB_Sizes
3/7/2017    ABC123     100          M
3/7/2017    ABC123     200          XL
7/7/2017    ABC123     150          L
7/7/2017    ABC123     780          M

As you can see there are no records from 4th July to 6th July.
But I still want them to be in the grid view. I want to have below kind of output:
GloveID : ABC123
Date          M     L    XL
3/7/2017     100    0   200
4/7/2017      0     0    0
5/7/2017      0     0    0
6/7/2017      0     0    0
7/7/2017     780   150   0

it should be listing the whole date for respective month. I am not using any drop down list to populate the data.
The record which displayed the grid view is retrieved from another page by Glove ID. Let say from Page A, click at the hyperlink and the URL will pass the Glove ID and redirect to Page B which list all the information.
Below are the SQL Query that I used to display the size and quantity
 select DSB.GloveID, G.GloveCode, DSB_Month, DSB_Year, DSB_Date,

      max(case when DSB_Sizes = 'M' then DSB_BalQty else 0 end) M,
      max(case when DSB_Sizes = 'L' then DSB_BalQty else 0 end) L,
      max(case when DSB_Sizes = 'XL' then DSB_BalQty else 0 end) XL

  from tblDailyStockBal DSB

    left join tblGlove G on G.GloveID = DSB.GloveID

    where DSB.GloveID = @GloveID
    group by DSB.GloveID, G.GloveCode, DSB_Month, DSB_Year, DSB_Date

How can I achieved that date things in C#?
I've tried below approached but still not getting what I wish for.

*

*How to create a Gridview that has number of days as column based on month selection

*display dates row wish of select month in gridview using asp.net

A: you have to use two date string to check is data available or not between two string like,
SqlCommand cmd = new SqlCommand("SELECT * (or column name,column name)FROM dbo.name where Date between '" + @date1+ "' and '" +@date2 + "' order by Date desc", connection);
                SqlDataAdapter sd1 = new SqlDataAdapter();
                sd1.SelectCommand = cmd;
                DataSet dst1 = new DataSet();
                sd1.Fill(dst1, "table name");

               yourgridview.DataSource = dst1.Tables[0];

this is basic idea for this,i hope you get the logic,and use proper secure connection as well,,,


text:
Q: Laravel : unsigned with index I want to create a foreign key in the review table. Here is my table structure.
 public function up()
{
    Schema::create('reviews', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('product_id')->unsigned()->index();
        $table->foreign('product_id')->references('id')->on('products')->onDelete(
            'cascade'
        );
        $table->string('customer');
        $table->text('review');
        $table->integer('star');

        $table->timestamps();
    });
}

Now my question is: I do not understand the below statements.
$table->integer('product_id')->unsigned()->index();

I do not want to execute this query without understanding this particular statement.
What does unsigned()->index() mean in laravel?
I read the official documentation of laravel for several times. They tell that unsigned() means Set INTEGER to UNSIGNED. Lacking limitation of mine. I do not understand a single piece of the word that they tell about this particular query. Please explain in simple words if you can.
Another question: If I do not declare unsigned()->index() with the integer('product_id') then what is to be the problem? Thank you in advance for your presence.


text:
Q: Weird pymc3 bug I've encountered really weird bug in pymc3:
The following code works fine:
import pymc3 as pm
for amplitude in range(10):
    kernel = amplitude**2*pm.gp.cov.Matern52(1, ls = 0.5)

The following throws an error:
import pymc3 as pm
import numpy as np

for amplitude in np.arange(10):
    kernel = amplitude**2*pm.gp.cov.Matern52(1, ls = 0.5)

Output
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-191-254ac7914bea> in <module>
      1 for i in np.arange(10):
----> 2     k = i**2*pm.gp.cov.Matern52(1, ls = 0.5)

~/anaconda3/envs/pymc3_env/lib/python3.6/site-packages/pymc3/gp/cov.py in __array_wrap__(self, result)
     91         Required to allow radd/rmul by numpy arrays.
     92         """
---> 93         r, c = result.shape
     94         A = np.zeros((r, c))
     95         for i in range(r):

ValueError: not enough values to unpack (expected 2, got 0)

Any idea on what is going on? I'm really curious.


text:
Q: Berkeley DB Error: BDB0590: files containing multiple databases may only be opened read-only I am attempting to open a *.bdb file using python package: bsddb . I have confirmed the file is a Berkeley DB (Btree, version 9) by using file command in Linux.
However, when I attempt to open using the following script in Python:
    db2 = bsddb.btopen('FeatureVector.bdb')
I get the error BDB0590: files containing multiple databases may only be opened read-only.
I attempted to open as read-only by adding a r flag, and it opens, but when I try to iterate through all values, only one key is returned without a value.
Any ideas?
Here is the code in full
import bsddb

db2 = bsddb.btopen('FeatureVector.bdb')

for k, v in db2.iteritems():
    print k, v

And it is returning:
FeatureVector, which is the name of the file. I guess a follow-up question is how do I view the different databases inside of the file?


text:
Q: Typeset R character vectors I have two vectors in R that I want to typeset. The first vector includes the titles and the second the body texts.
Please consider the following MWE
\documentclass{article}

\begin{document}

<<data>>=
title <- c("1","2","3","4")
body <- c("one","two","three","four")
@

% Expected result in TeX
%
% 1
% one
%
% 2
% two
%
% 3
% three
%
% 4
% four

\end{document}

This task requires a loop but I am not sure whether I should prepare the TeX markdowns directly in the R chunk with the option results=asis or whether I should use a combination of \forloop and \rinline{x} directly in TeX.

A: Not sure is the most elegant solution. But it works.
<<r-loop, echo=FALSE, results='asis', warning=FALSE>>=
for (i in 1:length(title)) {
  cat(title[i])
  cat(body[i])
}
@

A: I think you can just paste() the two vectors along with an empty character vector, and pass the result to \rinline{}.
\rinline{paste(title, body, '', sep = '\n', collapse = '\n')}

You can certainly do this in a code chunk with results='asis'. The two approaches are basically equivalent.


text:
Q: Need to display layout in fragment -android I need to display fragment layout when the user clicks an item in navigation drawer.
Activity class : -
Fragment fragment = new PreferencesFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
    .replace(R.id.mainContent, fragment)
    .commit();

mDrawerList.setItemChecked(position, true);
setTitle(mNavItems.get(position).mTitle);

// Close the drawer
mDrawerLayout.closeDrawer(mDrawerPane);

In fragment class:-
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.scorefragment, container, false);
    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    //fetching results from db
 }

My problem is, it is displaying an exception like
02-22 10:55:24.113: E/AndroidRuntime(31725):    java.lang.IllegalStateException: ScrollView can host only one direct child
02-22 10:55:24.113: E/AndroidRuntime(31725):    at android.widget.ScrollView.addView(ScrollView.java:248)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:905)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at android.app.BackStackRecord.run(BackStackRecord.java:834)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1454)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at android.app.FragmentManagerImpl$1.run(FragmentManager.java:447)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at android.os.Handler.handleCallback(Handler.java:739)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at android.os.Handler.dispatchMessage(Handler.java:95)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at android.os.Looper.loop(Looper.java:135)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at android.app.ActivityThread.main(ActivityThread.java:5343)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at java.lang.reflect.Method.invoke(Native Method)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at java.lang.reflect.Method.invoke(Method.java:372)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
02-22 10:55:24.113: E/AndroidRuntime(31725):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

Activity layout file containing the navigation drawer list
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
    android:id="@+id/mainContent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F5F5DC">

   <FrameLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent" >

<LinearLayout android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="15dp">

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         android:layout_marginTop="10dp"
        android:weightSum="3">

        <com.example.android.animationsdemo.TouchHighlightImageButton
            android:id="@+id/thumb_button_1"
            android:layout_width="100dp"
            android:layout_height="200dp"
            android:layout_marginRight="1dp"
            android:contentDescription="@string/description_image_1"
            android:scaleType="centerCrop"
            android:src="@drawable/thirteenone"
            android:layout_weight="1" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>

        <com.example.android.animationsdemo.TouchHighlightImageButton
            android:id="@+id/thumb_button_2"
            android:layout_width="100dp"
            android:layout_height="200dp"
            android:contentDescription="@string/description_image_2"
            android:scaleType="centerCrop"
            android:src="@drawable/thirteentwo"
            android:layout_weight="1" />

    </LinearLayout>

   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:weightSum="3" >

        <CheckBox
            android:id="@+id/checkBox1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="A"
            android:layout_weight="1"/>

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            />

        <CheckBox
            android:id="@+id/checkBox2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="B"
            android:layout_weight="1"/>

    </LinearLayout>

             <LinearLayout
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:weightSum="3"
                  android:layout_marginTop="10dp">

                 <com.example.android.animationsdemo.TouchHighlightImageButton
                     android:id="@+id/thumb_button_3"
                     android:layout_width="100dp"
                     android:layout_height="200dp"
                     android:contentDescription="@string/description_image_3"
                     android:scaleType="centerCrop"
                     android:src="@drawable/thirteenthree"
                     android:layout_weight="1" />

                 <TextView
                     android:id="@+id/textView6"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                   android:layout_weight="1" />

                 <com.example.android.animationsdemo.TouchHighlightImageButton
                     android:id="@+id/thumb_button_4"
                     android:layout_width="100dp"
                     android:layout_height="200dp"
                     android:contentDescription="@string/description_image_4"
                     android:scaleType="centerCrop"
                     android:src="@drawable/thirteenfour"
                     android:layout_weight="1" />

             </LinearLayout>

             <LinearLayout
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:layout_weight="1"
                 android:weightSum="3">

                 <CheckBox
                     android:id="@+id/checkBox3"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:text="C"
                      android:layout_weight="1" />

                  <TextView
                     android:id="@+id/textView4"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:layout_weight="1"  />
                 <CheckBox
                     android:id="@+id/checkBox4"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:text="D"
                     android:layout_weight="1"  />

             </LinearLayout>

</LinearLayout>

 <ImageView
    android:id="@+id/expanded_image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="invisible"
    android:contentDescription="@string/description_zoom_touch_close" />

  </FrameLayout>

  </ScrollView>

  <!-- The navigation drawer -->
  <RelativeLayout
    android:layout_width="280dp"
    android:layout_height="match_parent"
    android:id="@+id/drawerPane"
    android:layout_gravity="start">

  <!-- Profile Box -->

  <RelativeLayout
        android:id="@+id/profileBox"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@color/material_blue_grey_800"
        android:padding="8dp" >

   <ImageView
     android:id="@+id/avatar"
     android:layout_width="50dp"
      android:layout_height="50dp"

            android:layout_marginTop="15dp" />

<LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="42dp"
            android:layout_centerVertical="true"
            android:layout_marginLeft="15dp"
            android:layout_toRightOf="@+id/avatar"
            android:orientation="vertical" >

 <TextView
                android:id="@+id/userName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:textColor="#fff"
                android:textSize="16sp"
                android:textStyle="bold" />
        </LinearLayout>
    </RelativeLayout>

    <!-- List of Actions (pages) -->
    <ListView
        android:id="@+id/navList"
        android:layout_width="280dp"
        android:layout_height="match_parent"
        android:layout_below="@+id/profileBox"
        android:choiceMode="singleChoice"
        android:background="#ffffffff" />

</RelativeLayout>

</android.support.v4.widget.DrawerLayout>

Scorefragment layout file.
     <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_margin="5dp"
        android:background="#ffffff"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/TextView01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <LinearLayout
            android:id="@+id/one"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ffffff"
            android:weightSum="3" >

     <Button
        android:id="@+id/bone"
        android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                   android:layout_weight="1"
                    android:background="#3f51b5"
                    android:text="Q1" />

                <TextView
                    android:id="@+id/textView1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                     />

                <Button
                    android:id="@+id/btwo"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="#3f51b5"
                    android:text="Q2" />

            </LinearLayout>

<LinearLayout
    android:id="@+id/two"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="2" >
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:src="@drawable/abc_ab_share_pack_mtrl_alpha" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        />

    <RatingBar
        android:id="@+id/rtwo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:max="3"
        android:numStars="3"
        android:progressTint="#FFD700"
        android:stepSize="3"
        android:layout_weight="1"/>

</LinearLayout>

<!-- second -->
 <LinearLayout
     android:id="@+id/three"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:weightSum="3" >

                <Button
                    android:id="@+id/bthree"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="#3f51b5"
                    android:text="Q3" />

                <TextView

                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                     />

                <Button
                    android:id="@+id/bfour"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="#3f51b5"
                    android:text="Q4" />

            </LinearLayout>

<LinearLayout
    android:id="@+id/four"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="2" >

    <RatingBar
        android:id="@+id/rthree"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:max="3"
        android:numStars="3"
        android:progressTint="#FFD700"
        android:stepSize="3" />

    <TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        />

    <RatingBar
        android:id="@+id/rfour"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:max="3"
        android:numStars="3"
        android:progressTint="#FFD700"
        android:stepSize="3" />

</LinearLayout>

<!-- third -->

 <LinearLayout
     android:id="@+id/five"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:weightSum="3" >

                <Button
                    android:id="@+id/bfive"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="#3f51b5"
                    android:text="Q5" />

                <TextView

                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                     />

                <Button
                    android:id="@+id/bsix"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="#3f51b5"
                    android:text="Q6" />

            </LinearLayout>

<LinearLayout
    android:id="@+id/six"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="2" >

    <RatingBar
        android:id="@+id/rfive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:max="3"
        android:numStars="3"
        android:progressTint="#FFD700"
        android:stepSize="3" />

    <TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        />

    <RatingBar
        android:id="@+id/rsix"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:max="3"
        android:numStars="3"
        android:progressTint="#FFD700"
        android:stepSize="3" />

</LinearLayout>

<!-- four -->

 <LinearLayout
     android:id="@+id/seven"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:weightSum="3" >

                <Button
                    android:id="@+id/bseven"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="#3f51b5"
                    android:text="Q7" />

                <TextView

                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                     />

                <Button
                    android:id="@+id/beight"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="#3f51b5"
                    android:text="Q8" />

            </LinearLayout>

<LinearLayout
    android:id="@+id/eight"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="2" >

    <RatingBar
        android:id="@+id/rseven"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:max="3"
        android:numStars="3"
        android:progressTint="#FFD700"
        android:stepSize="3" />

    <TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        />

    <RatingBar
        android:id="@+id/reight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:max="3"
        android:numStars="3"
        android:progressTint="#FFD700"
        android:stepSize="3" />

</LinearLayout>

<!-- five -->

 <LinearLayout
     android:id="@+id/nine"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:weightSum="3" >

                <Button
                    android:id="@+id/bnine"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="#3f51b5"
                    android:text="Q9" />

                <TextView

                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                     />

                <Button
                    android:id="@+id/bten"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="#3f51b5"
                    android:text="Q10" />

            </LinearLayout>

<LinearLayout
    android:id="@+id/ten"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="2" >

    <RatingBar
        android:id="@+id/rnine"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:max="3"
        android:numStars="3"
        android:progressTint="#FFD700"
        android:stepSize="3" />

    <TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        />

    <RatingBar
        android:id="@+id/rten"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:max="3"
        android:numStars="3"
        android:progressTint="#FFD700"
        android:stepSize="3" />

</LinearLayout>
</LinearLayout>

And I'm not able to display the layout i.e scorefragment also.
Please help me.

A: Scrollview contains only one child...
   <android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ScrollView
        android:id="@+id/mainContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#F5F5DC">

       <RelativeLayout
            android:id="@+id/rel_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="15dp">

        <TextView
            android:id="@+id/textView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_weight="1"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
             android:layout_marginTop="10dp"
            android:weightSum="3">

            <com.example.android.animationsdemo.TouchHighlightImageButton
                android:id="@+id/thumb_button_1"
                android:layout_width="100dp"
                android:layout_height="200dp"
                android:layout_marginRight="1dp"
                android:contentDescription="@string/description_image_1"
                android:scaleType="centerCrop"
                android:src="@drawable/thirteenone"
                android:layout_weight="1" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>

            <com.example.android.animationsdemo.TouchHighlightImageButton
                android:id="@+id/thumb_button_2"
                android:layout_width="100dp"
                android:layout_height="200dp"
                android:contentDescription="@string/description_image_2"
                android:scaleType="centerCrop"
                android:src="@drawable/thirteentwo"
                android:layout_weight="1" />

        </LinearLayout>

       <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:weightSum="3" >

            <CheckBox
                android:id="@+id/checkBox1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="A"
                android:layout_weight="1"/>

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                />

            <CheckBox
                android:id="@+id/checkBox2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="B"
                android:layout_weight="1"/>

        </LinearLayout>

                 <LinearLayout
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:weightSum="3"
                      android:layout_marginTop="10dp">

                     <com.example.android.animationsdemo.TouchHighlightImageButton
                         android:id="@+id/thumb_button_3"
                         android:layout_width="100dp"
                         android:layout_height="200dp"
                         android:contentDescription="@string/description_image_3"
                         android:scaleType="centerCrop"
                         android:src="@drawable/thirteenthree"
                         android:layout_weight="1" />

                     <TextView
                         android:id="@+id/textView6"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                       android:layout_weight="1" />

                     <com.example.android.animationsdemo.TouchHighlightImageButton
                         android:id="@+id/thumb_button_4"
                         android:layout_width="100dp"
                         android:layout_height="200dp"
                         android:contentDescription="@string/description_image_4"
                         android:scaleType="centerCrop"
                         android:src="@drawable/thirteenfour"
                         android:layout_weight="1" />

                 </LinearLayout>

                 <LinearLayout
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:layout_weight="1"
                     android:weightSum="3">

                     <CheckBox
                         android:id="@+id/checkBox3"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                         android:text="C"
                          android:layout_weight="1" />

                      <TextView
                         android:id="@+id/textView4"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                         android:layout_weight="1"  />
                     <CheckBox
                         android:id="@+id/checkBox4"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                         android:text="D"
                         android:layout_weight="1"  />

                 </LinearLayout>

    </LinearLayout>

     <ImageView
        android:id="@+id/expanded_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="invisible"
        android:contentDescription="@string/description_zoom_touch_close" />

    </RelativeLayout>
      </ScrollView>

      <!-- The navigation drawer -->
      <RelativeLayout
        android:layout_width="280dp"
        android:layout_height="match_parent"
        android:id="@+id/drawerPane"
        android:layout_gravity="start">

      <!-- Profile Box -->

      <RelativeLayout
            android:id="@+id/profileBox"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="@color/material_blue_grey_800"
            android:padding="8dp" >

       <ImageView
         android:id="@+id/avatar"
         android:layout_width="50dp"
          android:layout_height="50dp"

                android:layout_marginTop="15dp" />

    <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="42dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="15dp"
                android:layout_toRightOf="@+id/avatar"
                android:orientation="vertical" >

     <TextView
                    android:id="@+id/userName"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"

                    android:textColor="#fff"
                    android:textSize="16sp"
                    android:textStyle="bold" />
            </LinearLayout>
        </RelativeLayout>

        <!-- List of Actions (pages) -->
        <ListView
            android:id="@+id/navList"
            android:layout_width="280dp"
            android:layout_height="match_parent"
            android:layout_below="@+id/profileBox"
            android:choiceMode="singleChoice"
            android:background="#ffffffff" />

    </RelativeLayout>

    </android.support.v4.widget.DrawerLayout>

A: In Your layout file you should have only one Layout inside ScrollView.

A: Yep, as the others have said, it seems like you're adding more that one view to a ScrollView which is not possible. The good practice would be for the ScrollView to have a LinearLayout as its only child and then you add your desired widgets and views to that LinearLayout.
Edit after you added the layouts.
I believe the problem is that you are trying to load (or replace) your fragments onto a ScrollView. I tried looking at the source code for the replace method and it seems that it adds your fragment's layout to the parent (in this case a ScrollView) and hides the other children (It does not delete them, thus the IllegalStateException exception). It actually does not delete the other children because you might want to manipulate them later.
In your case, you must replace your fragments with the content of the ScrollView (which should be a FrameLayout for the reason I said earlier) not the ScrollView itself. Hope this solves the issue.

A: You are getting this exception because you are taking multiple childs inside your scrollView.
Try to merge all your layout inside a single Linear Layout inside the ScrollView. This might solve your problem!
Let me know if this works .. :)


text:
Q: React Modal from Material-UI: Invalid value for prop `className` on  tag As the title implies I keep getting this className invalid value, which I assume is from the way i use makeStyles.
Since I'm more used to using "class" and all my other materials on this page are in classes, I also tried to translate the code from https://material-ui.com/components/modal/ to class and ended up with:
const modalStyle = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  };

const paperStyle = makeStyles(theme => ({
    backgroundColor: theme.palette.background.paper,
    border: '2px solid #000',
    boxShadow: theme.shadows[5],
    padding: theme.spacing(2, 4, 3),
}));

And the jsx code:
       <Modal
          aria-labelledby="transition-modal-title"
          aria-describedby="transition-modal-description"
          className={modalStyle}
          open={this.state.open}
          onClose={this.handleClose}
          closeAfterTransition
          BackdropComponent={Backdrop}
          BackdropProps={{
            timeout: 500,
          }}
        >
          <Fade in={this.state.open}>
            <div className={paperStyle}>  <----- ISSUE HERE
            <ItemsTable EBELN_={this.state.clickedEBELN} />
            </div>
          </Fade>
        </Modal>

Edit:
Tried to pass as:
const paperStyle = makeStyles(theme =>
  createStyles({
    paper:{
      backgroundColor: theme.palette.background.paper,
      border: '2px solid #000',
      boxShadow: theme.shadows[5],
      padding: theme.spacing(2, 4, 3),
    }
}));

And then call at className as: paperStyle.paper, the error was gone however it's not using the style at all.