问:
Hibernate: use OneToMany without actually using any primary/foreign key relationship
I have seen hundreds of posts, which is not similar to mine :(

Pls consider the following case.

Mysql Schema:

```<code>create table parent(
id int,
col1 int,
col2 int,
primary key(id)
)

create table child(
id int,
col1 int,
col2 int,
primary key(id)
)
</code>```

Note that there is no explicit/key relationship between parent & child tables.

Now, all I want is to fetch all the 'child' objects which has same values of  'col1' & 'col2' along while fetching 'parent' [Unidirectional mapping is enough].

Sort of Hibernate entities that I tried,

```<code>@Entity
public class parent{

@Id
private int id;

@Column
private int col1;

@Column
private int col2;

@OneToMany
@JoinColumns({
    @JoinColumn(name = "col1"),
    @JoinColumn(name = "col2")
})
private List<Child> children;

/**
Other logic goes here..
**/

}
</code>```

And the Child entity as,

```<code>@Entity
public class Child{

@Id
private int id;

@Column
private int col1;

@Column
private int col2;

/**
Other logic goes here..
**/
}
</code>```

Result:
Hibernate error reporting that "A Foreign key refering 'Child' from 'Parent' has the wrong number of column. should be 1"

I interpret this expects as, @JoinColumn has to be done only using "id"

Questions:

1) Does all @OneToMany @ManyToOne etc of hibernate requires, explicit/key references between the tables/at the entities [annotated by @Id]?

2) What should I do to achieve this?

答:
Here TableA has OneToMany relationship with TableB i.e., one record in TableA can have multiple records in TableB. Since col1 in TableA is referenced as Foreign key in col1 of TableB. The below JPA code successfully fetch all the results.

```<code>DROP table x.TableA;
CREATE TABLE x.TableA (
    Id BIGINT IDENTITY(1,1) NOT NULL,
    col1 varchar(30) NOT NULL,
    CONSTRAINT PK_col1 PRIMARY KEY(col1)
);

DROP table x.TableB;
CREATE TABLE x.TableB (
    Id BIGINT IDENTITY(1,1)NOT NULL,
    col1 varchar(30) NOT NULL,
    col2 varchar(10) NULL
);

ALTER TABLE x.TableB
   ADD CONSTRAINT FK_TableB_col1 FOREIGN KEY (col1)
      REFERENCES x.TableA (col1)
;
</code>```

```<code>@Entity
@Table(name = "TableA", schema = "x")
public class ClassA implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "col1")
  private String col1;

  @OneToMany(
      cascade = {CascadeType.ALL},
      orphanRemoval = true,
      fetch = FetchType.EAGER)
  @JoinColumn(name = "col1", referencedColumnName = "col1")
  private List<ClassB> objB = new ArrayList<>();
}

----------------------------------

@Entity
@Table(name = "TableB", schema = "x")
public class ClassB implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "col1")
  private String col1;

  @Column(name = "col2")
  private String col2;

}

</code>```

Body:
I have seen hundreds of posts, which is not similar to mine :(

Pls consider the following case.

Mysql Schema:

create table parent(
id int,
col1 int,
col2 int,
primary key(id)
)

create table child(
id int,
col1 int,
col2 int,
primary key(id)
)

Note that there is no explicit/key relationship between parent & child tables.

Now, all I want is to fetch all the 'child' objects which has same values of  'col1' & 'col2' along while fetching 'parent' [Unidirectional mapping is enough].

Sort of Hibernate entities that I tried,

@Entity
public class parent{

@Id
private int id;

@Column
private int col1;

@Column
private int col2;

@OneToMany
@JoinColumns({
    @JoinColumn(name = "col1"),
    @JoinColumn(name = "col2")
})
private List<Child> children;

/**
Other logic goes here..
**/

}

And the Child entity as,

@Entity
public class Child{

@Id
private int id;

@Column
private int col1;

@Column
private int col2;

/**
Other logic goes here..
**/
}

Result:
Hibernate error reporting that "A Foreign key refering 'Child' from 'Parent' has the wrong number of column. should be 1"

I interpret this expects as, @JoinColumn has to be done only using "id"

Questions:

1) Does all @OneToMany @ManyToOne etc of hibernate requires, explicit/key references between the tables/at the entities [annotated by @Id]?

2) What should I do to achieve this?

Body:
Here TableA has OneToMany relationship with TableB i.e., one record in TableA can have multiple records in TableB. Since col1 in TableA is referenced as Foreign key in col1 of TableB. The below JPA code successfully fetch all the results.

DROP table x.TableA;
CREATE TABLE x.TableA (
    Id BIGINT IDENTITY(1,1) NOT NULL,
    col1 varchar(30) NOT NULL,
    CONSTRAINT PK_col1 PRIMARY KEY(col1)
);

DROP table x.TableB;
CREATE TABLE x.TableB (
    Id BIGINT IDENTITY(1,1)NOT NULL,
    col1 varchar(30) NOT NULL,
    col2 varchar(10) NULL
);

ALTER TABLE x.TableB
   ADD CONSTRAINT FK_TableB_col1 FOREIGN KEY (col1)
      REFERENCES x.TableA (col1)
;

@Entity
@Table(name = "TableA", schema = "x")
public class ClassA implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "col1")
  private String col1;

  @OneToMany(
      cascade = {CascadeType.ALL},
      orphanRemoval = true,
      fetch = FetchType.EAGER)
  @JoinColumn(name = "col1", referencedColumnName = "col1")
  private List<ClassB> objB = new ArrayList<>();
}

----------------------------------

@Entity
@Table(name = "TableB", schema = "x")
public class ClassB implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "col1")
  private String col1;

  @Column(name = "col2")
  private String col2;

}


来源: stackexchange

问:
Unexpected non-equality after assignment
Given the following code:

using System;

class MyClass
{
    public MyClass x;
}

public static class Program
{
    public static void Main()
    {
        var a = new MyClass();
        var b = new MyClass();
        a.x = (a = b);
        Console.WriteLine(a.x == a);
    }
}
```

The first two lines are very obvious, just two different objects.

I assume the third line to do the following:

The part (a = b) assigns b to a and returns b, so now a equals b.

Then, a.x is assigned to b.

That means, a.x equals to b, and also b equals to a. Which implies that a.x equals to a.

However, the code prints False.

What's going on?

答:
Interesting find, I've put your code into Sharplab and checked what happens.

Seems like compiler swaps left operands in your assignment, this is what it looks like decompiled back to C# (variable names are changed):

public static void Main()
{
    MyClass myClass = new MyClass();
    MyClass x = new MyClass();
    myClass = (myClass.x = x);
    Console.WriteLine(myClass.x == myClass);
}
```

<p>So what happens is <code>a.x</code> becomes <code>b</code> and then <code>b</code> is assigned to <code>a</code>. Both local variable <code>a</code> and attribute <code>a.x</code> now point to <code>b</code> object.
So:</p>

<ul>
<li><code>a</code> variable points to <code>b</code> object</li>
<li><code>b</code> variable points to <code>b</code> object</li>
<li><code>a</code> object's <code>x</code> attribute points to <code>b</code> object</li>
<li><code>b</code> object's <code>x</code> attribute is null </li>
</ul>

<p>I changed your code a bit to illustrate that better:</p>

<pre class="lang-cs prettyprint-override"><code>public static void Main(string[] args)
{
    var a = new MyClass();
    var originalA = a;
    a.Name = "a";
    var b = new MyClass();
    b.Name = "b";
    a.x = (a = b);

    Console.WriteLine(a.x == a);

    Console.WriteLine("a           - " + a.Name);
    Console.WriteLine("a.x         - " + a.x?.Name);

    Console.WriteLine("b           - " + b.Name);
    Console.WriteLine("b.x         - " + b.x?.Name);

    Console.WriteLine("originalA   - " + originalA.Name);
    Console.WriteLine("originalA.x - " + originalA.x?.Name);
}
</code>```

That code returns:

```<code>False
a           - b
a.x         -
b           - b
b.x         -
originalA   - a
originalA.x - b
</code>```

Notice only originalA now points to actual a object, other local variables now point to b.

It's not a compiler bug - see Magnetron's answer.

ContentLicense: CC BY-SA 4.0

Body:
Given the following code:

using System;

class MyClass
{
    public MyClass x;
}

public static class Program
{
    public static void Main()
    {
        var a = new MyClass();
        var b = new MyClass();
        a.x = (a = b);
        Console.WriteLine(a.x == a);
    }
}

The first two lines are very obvious, just two different objects.

I assume the third line to do the following:

The part (a = b) assigns b to a and returns b, so now a equals b.

Then, a.x is assigned to b.

That means, a.x equals to b, and also b equals to a. Which implies that a.x equals to a.

However, the code prints False.

What's going on?

Body:
Interesting find, I've put your code into Sharplab and checked what happens.

Seems like compiler swaps left operands in your assignment, this is what it looks like decompiled back to C# (variable names are changed):

public static void Main()
{
    MyClass myClass = new MyClass();
    MyClass x = new MyClass();
    myClass = (myClass.x = x);
    Console.WriteLine(myClass.x == myClass);
}

So what happens is a.x becomes b and then b is assigned to a. Both local variable a and attribute a.x now point to b object.
So:

a variable points to b object

b variable points to b object

a object's x attribute points to b object

b object's x attribute is null

I changed your code a bit to illustrate that better:

public static void Main(string[] args)
{
    var a = new MyClass();
    var originalA = a;
    a.Name = "a";
    var b = new MyClass();
    b.Name = "b";
    a.x = (a = b);

    Console.WriteLine(a.x == a);

    Console.WriteLine("a           - " + a.Name);
    Console.WriteLine("a.x         - " + a.x?.Name);

    Console.WriteLine("b           - " + b.Name);
    Console.WriteLine("b.x         - " + b.x?.Name);

    Console.WriteLine("originalA   - " + originalA.Name);
    Console.WriteLine("originalA.x - " + originalA.x?.Name);
}

That code returns:

False
a           - b
a.x         -
b           - b
b.x         -
originalA   - a
originalA.x - b

Notice only originalA now points to actual a object, other local variables now point to b.

It's not a compiler bug - see Magnetron's answer.


问:
How can I align the hintText vertically of a TextField in Flutter?

Something strange happens, for some reason I can't put the hintText vertically aligned inside theTextField, the strangest thing happens when the text field has focus (see gif). The borderRadius is lost and apparently at that moment it is fixed. When the focus of the text field is lost it gets messy again. How can I correct it?

this is my code:

```<code>Widget _searchBar() {
 return Container(
  height: 40,
  child: TextField(
    textAlignVertical: TextAlignVertical.center,
    style: TextStyle(
      color: _styles["gris_oscuro1"]["color"],
    ),
    onChanged: (value) {},
    decoration: InputDecoration(
      filled: true,
      fillColor: _styles["gris_claro"]["color"],
      alignLabelWithHint: true,
      hintText: "Buscar por código",
      hintStyle: TextStyle(color: _styles["gris_oscuro2"]["color"]),
      prefixIcon:
          Icon(Icons.search, color: _styles["gris_oscuro2"]["color"]),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(40)),
        borderSide:
            BorderSide(color: _styles["gris_claro"]["color"], width: 1.0),
      ),
    ),
  ),
);

  Scaffold(
    key: _scaffoldKey,
    backgroundColor: _styles["fondo"]["bg"],
    drawer: MenuWidget(),
    body: SafeArea(
      child: _searchBar(),
    )
</code>```

答:
This is happening because of the height you are giving to the parent Container. There can be two ways to align the hint text vertically,
(They are independent of each other, chose either one)

```<code>child: Container(
  // height: 48, //ONE - Remove the static height
  child: TextField(
    textAlignVertical: TextAlignVertical.center,
    style: TextStyle(
      textBaseline: TextBaseline.alphabetic,
      color: Colors.red,
    ),
    onChanged: (value) {},
    decoration: InputDecoration(
      // contentPadding: EdgeInsets.all(8.0), //TWO - Specify the padding if you want your custom height.
      filled: true,
      alignLabelWithHint: true,
      hintText: "Buscar por código",
      hintStyle: TextStyle(color: Colors.red),
      prefixIcon: Icon(Icons.search, color: Colors.red),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(40)),
        borderSide: BorderSide(color: Colors.red, width: 1.0),
      ),
    ),
  ),
),
</code>```

Remove the Container's height

If you want to size the parent container according to your desire, you have to specify some inner padding for the content.

Edit: You will lose the border when you tap on the TextField as the you are not passing anything to the focusedBorder property of TextField. Follow the code below:

```<code>decoration: InputDecoration(
  filled: true,
  alignLabelWithHint: true,
  hintText: "Buscar por código",
  hintStyle: TextStyle(color: Colors.red),
  prefixIcon: Icon(Icons.search, color: Colors.red),
  enabledBorder: OutlineInputBorder(
    borderRadius: BorderRadius.all(Radius.circular(40)),
    borderSide: BorderSide(color: Colors.red, width: 1.0),
  ),
  focusedBorder: OutlineInputBorder( //Add this to your code...
    borderRadius: BorderRadius.all(Radius.circular(40)),
    borderSide: BorderSide(color: Colors.red, width: 1.0),
  ),
),
</code>```

Body:
Something strange happens, for some reason I can't put the hintText vertically aligned inside theTextField, the strangest thing happens when the text field has focus (see gif). The borderRadius is lost and apparently at that moment it is fixed. When the focus of the text field is lost it gets messy again. How can I correct it?

this is my code:

Widget _searchBar() {
 return Container(
  height: 40,
  child: TextField(
    textAlignVertical: TextAlignVertical.center,
    style: TextStyle(
      color: _styles["gris_oscuro1"]["color"],
    ),
    onChanged: (value) {},
    decoration: InputDecoration(
      filled: true,
      fillColor: _styles["gris_claro"]["color"],
      alignLabelWithHint: true,
      hintText: "Buscar por código",
      hintStyle: TextStyle(color: _styles["gris_oscuro2"]["color"]),
      prefixIcon:
          Icon(Icons.search, color: _styles["gris_oscuro2"]["color"]),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(40)),
        borderSide:
            BorderSide(color: _styles["gris_claro"]["color"], width: 1.0),
      ),
    ),
  ),
);

  Scaffold(
    key: _scaffoldKey,
    backgroundColor: _styles["fondo"]["bg"],
    drawer: MenuWidget(),
    body: SafeArea(
      child: _searchBar(),
    )

Body:
This is happening because of the height you are giving to the parent Container. There can be two ways to align the hint text vertically,
(They are independent of each other, chose either one)

child: Container(
  // height: 48, //ONE - Remove the static height
  child: TextField(
    textAlignVertical: TextAlignVertical.center,
    style: TextStyle(
      textBaseline: TextBaseline.alphabetic,
      color: Colors.red,
    ),
    onChanged: (value) {},
    decoration: InputDecoration(
      // contentPadding: EdgeInsets.all(8.0), //TWO - Specify the padding if you want your custom height.
      filled: true,
      alignLabelWithHint: true,
      hintText: "Buscar por código",
      hintStyle: TextStyle(color: Colors.red),
      prefixIcon: Icon(Icons.search, color: Colors.red),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.all(Radius.circular(40)),
        borderSide: BorderSide(color: Colors.red, width: 1.0),
      ),
    ),
  ),
),

Remove the Container's height

If you want to size the parent container according to your desire, you have to specify some inner padding for the content.

Edit: You will lose the border when you tap on the TextField as the you are not passing anything to the focusedBorder property of TextField. Follow the code below:

decoration: InputDecoration(
  filled: true,
  alignLabelWithHint: true,
  hintText: "Buscar por código",
  hintStyle: TextStyle(color: Colors.red),
  prefixIcon: Icon(Icons.search, color: Colors.red),
  enabledBorder: OutlineInputBorder(
    borderRadius: BorderRadius.all(Radius.circular(40)),
    borderSide: BorderSide(color: Colors.red, width: 1.0),
  ),
  focusedBorder: OutlineInputBorder( //Add this to your code...
    borderRadius: BorderRadius.all(Radius.circular(40)),
    borderSide: BorderSide(color: Colors.red, width: 1.0),
  ),
),


问:
Failed to create HTML page using GWT plugin for Eclipse
When i create a new GWT (version 2.3) project using the Eclipse (version 3.5) plugin, without enabling sample code, i failed to create a new HTML page by using the GWT->new HTML page. It opens the dialog window, i enter the name of the file and the module, but when i press 'finish', it does nothing! Bug or my mistake?</p>

答:
It's a bug.

Temporary Solution:
Just create GWT Project with sample contents. than you can see html file in war.
Copy that into your project. Modify it. (It's easy to inspect)

ContentLicense: CC BY-SA 3.0


答:
Here's my solution. Probably not perfect but it does the job.</p>

```<code>var ss = SpreadsheetApp.getActiveSpreadsheet();

function onOpen() {
  var menu = [{name:"Split in rows", functionName:"splitInRows"}];
  ss.addMenu("Extras", menu);
}

function splitInRows() {

  // Get the current sheet, row, and column.
  var sheet = ss.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var lastColumn = sheet.getLastColumn();

  var range = sheet.getRange(1, 1, lastRow, lastColumn);
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();

  for (var i = numRows; i > 0; i--) {
    for (var j = numCols; j > 0; j--) {

      var cell = range.getCell(i,j);
      var cellValue = cell.getDisplayValue();

      if ( j > 1 && cellValue ) {

        // check if previous cell has content
        var previousCellValue = range.getCell(i,j-1).getDisplayValue();

        if (previousCellValue){

          // create empty row
          sheet.insertRowsAfter(i, 1);

          // move cell value into cell just below
          var currentCell = sheet.getRange(i, j);
          var belowCell = sheet.getRange(i+1, j);

          currentCell.copyTo(belowCell, {contentsOnly:true});
          currentCell.clearContent();

        }
      }
    }
  }
}

</code>```

Title: Expand single row into multiple rows if next column has content in a spreadsheet

Body:
I have a tree structure defined in a Google spreadsheet. I need to modify the following structure:

+---+------------+-----------------+--------------------+-----+--------------+
|   |     A      |        B        |         C          |  D  |      E       |
+---+------------+-----------------+--------------------+-----+--------------+
| 1 | Techniques | Adduction d'eau | Conduites en fonte | Eau | Tuyaux       |
| 2 |            |                 |                    |     | Robinetterie |
| 3 |            |                 |                    |     | Outils       |
| 4 |            |                 |                    |     | Accessoires  |
| 5 |            |                 |                    | Gaz | Tuyaux       |
| 6 |            |                 |                    |     | Robinetterie |
| 7 |            |                 |                    |     | Outils       |
| 8 |            |                 |                    |     | Accessoires  |
+---+------------+-----------------+--------------------+-----+--------------+

into this:

+----+------------+-----------------+---------------------+-----+--------------+
|    |     A      |        B        |          C          |  D  |      E       |
+----+------------+-----------------+---------------------+-----+--------------+
|  1 | Techniques |                 |                     |     |              |
|  2 |            | Adduction d'eau |                     |     |              |
|  3 |            |                 | Conduites en fonte  |     |              |
|  4 |            |                 |                     | Eau |              |
|  5 |            |                 |                     |     | Tuyaux       |
|  6 |            |                 |                     |     | Robinetterie |
|  7 |            |                 |                     |     | Outils       |
|  8 |            |                 |                     |     | Accessoires  |
|  9 |            |                 |                     | Gaz |              |
| 10 |            |                 |                     |     | Tuyaux       |
| 11 |            |                 |                     |     | Robinetterie |
| 12 |            |                 |                     |     | Outils       |
| 13 |            |                 |                     |     | Accessoires  |
+----+------------+-----------------+---------------------+-----+--------------+

Any idea how to proceed? Thanks in advance

Body:
Here's my solution. Probably not perfect but it does the job.

var ss = SpreadsheetApp.getActiveSpreadsheet();

function onOpen() {
  var menu = [{name:"Split in rows", functionName:"splitInRows"}];
  ss.addMenu("Extras", menu);
}

function splitInRows() {

  // Get the current sheet, row, and column.
  var sheet = ss.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var lastColumn = sheet.getLastColumn();

  var range = sheet.getRange(1, 1, lastRow, lastColumn);
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();

  for (var i = numRows; i > 0; i--) {
    for (var j = numCols; j > 0; j--) {

      var cell = range.getCell(i,j);
      var cellValue = cell.getDisplayValue();

      if ( j > 1 && cellValue ) {

        // check if previous cell has content
        var previousCellValue = range.getCell(i,j-1).getDisplayValue();

        if (previousCellValue){

          // create empty row
          sheet.insertRowsAfter(i, 1);

          // move cell value into cell just below
          var currentCell = sheet.getRange(i, j);
          var belowCell = sheet.getRange(i+1, j);

          currentCell.copyTo(belowCell, {contentsOnly:true});
          currentCell.clearContent();

        }
      }
    }
  }
}


问:
Model validation in CakePHP check that atleast one or the other is set
Is there a way to validate data (using CakePHP's model validation) to make sure that at least "a" or "b" has data (does not have to have data in both).</p>

答:
In your model, do something like this.  The function will be called when you perform a save operation.

EDITED

```<code>public $validate = array(
    'a' => array(
        'customCheck' => array(
            'rule' => 'abCheck',
            'message' => 'You must enter data in a or b.'
        )
    ),
    'b' => array(
        'customCheck' => array(
            'rule' => 'abCheck',
            'message' => 'You must enter data in a or b.'
        )
    )
);

//Function must be public for Validator to work
//Checks to see if either a or b properties are set and not empty
public function abCheck(){
    if((isset($this->data['Model']['a']) && !empty($this->data['Model']['a'])) || (isset($this->data['Model']['b']) && !empty($this->data['Model']['b']))){
         return true;
    }
    return false;
}
</code>```

Body:
In your model, do something like this.  The function will be called when you perform a save operation.

EDITED

public $validate = array(
    'a' => array(
        'customCheck' => array(
            'rule' => 'abCheck',
            'message' => 'You must enter data in a or b.'
        )
    ),
    'b' => array(
        'customCheck' => array(
            'rule' => 'abCheck',
            'message' => 'You must enter data in a or b.'
        )
    )
);

//Function must be public for Validator to work
//Checks to see if either a or b properties are set and not empty
public function abCheck(){
    if((isset($this->data['Model']['a']) && !empty($this->data['Model']['a'])) || (isset($this->data['Model']['b']) && !empty($this->data['Model']['b']))){
         return true;
    }
    return false;
}


问:
How do I find the width of a uint_fast32_t
I'd like to be able to portably fprintf() a uint_fast32_t as defined in stdint.h with all leading zeroes. For instance if my platform defined uint_fast32_t as a 64-bit unsigned integer, I would want to fprintf() with a format specifier like %016lX, but if it's a 32-bit unsigned integer, I would want to use %08lX.

Is there a macro like INTFAST32_BITS somewhere that I could use?

right now I'm using

```<code>#if UINT_FAST32_MAX == 0xFFFFFFFF
#    define FORMAT "08"PRIXFAST32
#elif UINT_FAST32_MAX == 0xFFFFFFFFFFFFFFFF
#    define FORMAT "016"PRIXFAST32
#endif
</code>```

But this only works with uint_fast32_t that is exactly 32 or 64 bits wide, and the code is also kinda clunky and hard to read

答:
You can find the size of a uint_fast32_t the same way you can find the size of any other type: by applying the sizeof operator to it.  The unit of the result is the size of type char.  Example:

```<code>size_t chars_in_a_uint_fast32_t = sizeof(uint_fast32_t);
</code>```

But this is not sufficient for printing one with one of the printf-family functions.  Undefined behavior arises in printf et. al. if any formatting directive is mismatched with the type of the corresponding argument, and the size of of uint_fast32_t is not sufficient information to make a proper match.

This is where the formatting macros already described in your other answer come in.  These provide the appropriate size modifier and conversion letter for each type and conversion.  For an X conversion of uint_fast32_t, the appropriate macro is PRIXFAST32.

You provide any flags, field width, and precision as normal.  If indeed you want to use a field width that is adapted to the actual size of uint_fast32_t, then a reasonable way to do that would be to avail yourself of the option to specify that the field width is passed as an argument (of type int).  Thus:

```<code>uint_fast32_t fast;
// ...
printf("%0*" PRIXFAST32 "\n", (int) sizeof(fast) * 2, fast);
</code>```

I note, however, that this seems a little questionable, inasmuch as you are making provision for values wider than generally you should allow any value of that type to become.  The printf function will not in any case print fewer digits than are required to express the value, supposing that it is indeed of the specified type, so I would be inclined to simply use a fixed field width sufficient for 32-bit integers (say 8).

Body:
I'd like to be able to portably fprintf() a uint_fast32_t as defined in stdint.h with all leading zeroes. For instance if my platform defined uint_fast32_t as a 64-bit unsigned integer, I would want to fprintf() with a format specifier like %016lX, but if it's a 32-bit unsigned integer, I would want to use %08lX.

Is there a macro like INTFAST32_BITS somewhere that I could use?

right now I'm using

#if UINT_FAST32_MAX == 0xFFFFFFFF
#    define FORMAT "08"PRIXFAST32
#elif UINT_FAST32_MAX == 0xFFFFFFFFFFFFFFFF
#    define FORMAT "016"PRIXFAST32
#endif

But this only works with uint_fast32_t that is exactly 32 or 64 bits wide, and the code is also kinda clunky and hard to read

Body:
You can find the size of a uint_fast32_t the same way you can find the size of any other type: by applying the sizeof operator to it.  The unit of the result is the size of type char.  Example:

size_t chars_in_a_uint_fast32_t = sizeof(uint_fast32_t);

But this is not sufficient for printing one with one of the printf-family functions.  Undefined behavior arises in printf et. al. if any formatting directive is mismatched with the type of the corresponding argument, and the size of of uint_fast32_t is not sufficient information to make a proper match.

This is where the formatting macros already described in your other answer come in.  These provide the appropriate size modifier and conversion letter for each type and conversion.  For an X conversion of uint_fast32_t, the appropriate macro is PRIXFAST32.

You provide any flags, field width, and precision as normal.  If indeed you want to use a field width that is adapted to the actual size of uint_fast32_t, then a reasonable way to do that would be to avail yourself of the option to specify that the field width is passed as an argument (of type int).  Thus:

uint_fast32_t fast;
// ...
printf("%0*" PRIXFAST32 "\n", (int) sizeof(fast) * 2, fast);

I note, however, that this seems a little questionable, inasmuch as you are making provision for values wider than generally you should allow any value of that type to become.  The printf function will not in any case print fewer digits than are required to express the value, supposing that it is indeed of the specified type, so I would be inclined to simply use a fixed field width sufficient for 32-bit integers (say 8).


问:
Conditional statement if a substring occurs 1 time in a line read from a file
Example file:

RDH205xxx 123 456 ABC
RDH205xxx 123 456 RDH205yyy
RDH205yyy 654 32A
RDxxxxxxx 456 789 BC205yyyy
```

<p>tried: </p>

<pre class="lang-perl prettyprint-override"><code>open and read a line from a file
if (/RDH{1,1}$/) { parse the line }
</code>```

答:
Using perl :</p>

```<code>perl -ne 'print if scalar s/\bRDH\b/RDH/g == 1' file
</code>```

Body:
Example file:

RDH205xxx 123 456 ABC
RDH205xxx 123 456 RDH205yyy
RDH205yyy 654 32A
RDxxxxxxx 456 789 BC205yyyy

tried:

open and read a line from a file
if (/RDH{1,1}$/) { parse the line }

Body:
Using perl :

perl -ne 'print if scalar s/\bRDH\b/RDH/g == 1' file


问:
Bad interpreter: No such file or directory
I am trying to deploy my site with EB CLI. Whenever I try to run $ eb --version, it always shows the error below, even though it works on my CMD. Can anyone help me with it? Thank you.</p>

```<code>     /c/Users/username/AppData/Local/Programs/Python/Python35/Scripts/eb:
     c:\users\user: bad interpreter: No such file or directory
</code>```

答:
This error is related to your terminal and the environment it runs on. You get the same error with e.g. cygwin using git bash. In a script I had something like this:

```<code>#!/c/Program Files/some_program/executable.exe
</code>```

Escaping the space with a backslash or using quotes didn't work.

The solution is to use the DOS' short filename:

Progra~1 for "Program Files"

Progra~2 for "Program Files (x86)"

So my line would turn into:

```<code>#!/c/Progra~1/some_program/executable.exe
</code>```

Body:
I am trying to deploy my site with EB CLI. Whenever I try to run $ eb --version, it always shows the error below, even though it works on my CMD. Can anyone help me with it? Thank you.

     /c/Users/username/AppData/Local/Programs/Python/Python35/Scripts/eb:
     c:\users\user: bad interpreter: No such file or directory

Body:
This error is related to your terminal and the environment it runs on. You get the same error with e.g. cygwin using git bash. In a script I had something like this:

#!/c/Program Files/some_program/executable.exe

Escaping the space with a backslash or using quotes didn't work.

The solution is to use the DOS' short filename:

Progra~1 for "Program Files"

Progra~2 for "Program Files (x86)"

So my line would turn into:

#!/c/Progra~1/some_program/executable.exe


问:
Removing non latin characters from a string in Python3
I'm passing a string to PIL's multiline_text() which, for some reason, doesn't support utf-8 but only Latin characters.

```<code>from PIL import Image, ImageDraw

input_string = "‘Hi’"

img_width = 500
img_height = 500
img = Image.new('RGB', (img_width, img_height), (255, 255, 255))
img_D = ImageDraw.Draw(img)
img_D.multiline_text((0, 0), input_string)    # <- bug here
img.save("test_img.jpeg", 'jpeg', optimize=True, quality = 200)
</code>```

I get this error message: UnicodeEncodeError: 'latin-1' codec can't encode character '\u2018' in position 0: ordinal not in range(256)

So I need to get rid of all non-Latin characters. How can I do that?

Note: I've seen this answer, namely input_string = regex.sub(ur'[^\p{Latin}]', u'', t1) but I'm pretty sure it's for Python2, I get the following error: SyntaxError: invalid syntax. If I remove either the u or the r or both, I get error: bad escape \p.

答:
Since your comment clarified your question is about rendering unicode characters rather than stripping unicode characters, I will provide an example of loading and drawing with a font that supports unicode characters.

For this example I used Roboto Mono Bold which you can download from Google Fonts.

from PIL import Image, ImageDraw, ImageFont

haiku = '''bruits de neige et d’encre
frôlement d’âmes et d’ailes
deux papillons s’aiment'''

font = ImageFont.truetype('RobotoMono-Bold.ttf', 18)
haiku_dimensions = font.getsize_multiline(haiku)

padding = 4
with Image.new('RGB', tuple(d + (4 * padding) for d in haiku_dimensions), color=(180, 180, 180)) as image:
    draw = ImageDraw.Draw(image)
    draw.multiline_text((padding, padding), haiku, font=font, fill=(20,20,20))
    image.save('output.png')
```

The output looks like this:

Body:
I'm passing a string to PIL's multiline_text() which, for some reason, doesn't support utf-8 but only Latin characters.

from PIL import Image, ImageDraw

input_string = "‘Hi’"

img_width = 500
img_height = 500
img = Image.new('RGB', (img_width, img_height), (255, 255, 255))
img_D = ImageDraw.Draw(img)
img_D.multiline_text((0, 0), input_string)    # <- bug here
img.save("test_img.jpeg", 'jpeg', optimize=True, quality = 200)

I get this error message: UnicodeEncodeError: 'latin-1' codec can't encode character '\u2018' in position 0: ordinal not in range(256)

So I need to get rid of all non-Latin characters. How can I do that?

Note: I've seen this answer, namely input_string = regex.sub(ur'[^\p{Latin}]', u'', t1) but I'm pretty sure it's for Python2, I get the following error: SyntaxError: invalid syntax. If I remove either the u or the r or both, I get error: bad escape \p.

Body:
Since your comment clarified your question is about rendering unicode characters rather than stripping unicode characters, I will provide an example of loading and drawing with a font that supports unicode characters.

For this example I used Roboto Mono Bold which you can download from Google Fonts.

from PIL import Image, ImageDraw, ImageFont

haiku = '''bruits de neige et d’encre
frôlement d’âmes et d’ailes
deux papillons s’aiment'''

font = ImageFont.truetype('RobotoMono-Bold.ttf', 18)
haiku_dimensions = font.getsize_multiline(haiku)

padding = 4
with Image.new('RGB', tuple(d + (4 * padding) for d in haiku_dimensions), color=(180, 180, 180)) as image:
    draw = ImageDraw.Draw(image)
    draw.multiline_text((padding, padding), haiku, font=font, fill=(20,20,20))
    image.save('output.png')

The output looks like this:


问:
Get data from firestore using document id
I have two collections in my firestore database, the first is list of all the documents (BlockList), and the second for the users. when the user bookmark post on the app, send only the id of this post to sub-collection (Favourites).

so how can i display this sub-collection's documents from the first collection based on its ids.

```<code>firebaseFirestore.collection("Users")
                .document(userId).collection("Favorites").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    List<String> list = new ArrayList<>();
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        list.add(document.getId());
                    }
                    Log.d(TAG, list.toString());
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });
</code>```

I Use this code to reach the list of the sub-collection ids, but i want to know how to use it to get the documents that appropriate to this ids from the main collection(BlockList).

答:
```<code>    userRef.document(reference)
                    .collection(favCollect)
                    .get()
                    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if (task.isSuccessful()) {
                                task.getResult()
                                        .getQuery()
                                        .addSnapshotListener((queryDocumentSnapshots, e) -> {
List<DocumentChange> documentChanges = queryDocumentSnapshots.getDocumentChanges();
                                    for (int i = 0; i < documentChanges.size(); i++) {

}

}
</code>```

In this way you can reach the id you are looking for

Body:
I have two collections in my firestore database, the first is list of all the documents (BlockList), and the second for the users. when the user bookmark post on the app, send only the id of this post to sub-collection (Favourites).

so how can i display this sub-collection's documents from the first collection based on its ids.

firebaseFirestore.collection("Users")
                .document(userId).collection("Favorites").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    List<String> list = new ArrayList<>();
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        list.add(document.getId());
                    }
                    Log.d(TAG, list.toString());
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

I Use this code to reach the list of the sub-collection ids, but i want to know how to use it to get the documents that appropriate to this ids from the main collection(BlockList).

Body:
    userRef.document(reference)
                    .collection(favCollect)
                    .get()
                    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if (task.isSuccessful()) {
                                task.getResult()
                                        .getQuery()
                                        .addSnapshotListener((queryDocumentSnapshots, e) -> {
List<DocumentChange> documentChanges = queryDocumentSnapshots.getDocumentChanges();
                                    for (int i = 0; i < documentChanges.size(); i++) {

}

}

In this way you can reach the id you are looking for


问:
springboot 2.3.0 while connecting to h2 database
In Springboot 2.3.0.RELEASE
I am getting the the following error while connecting to h2 database in the console

Database "mem:testdb" not found, either pre-create it or allow remote
  database creation (not recommended in secure environments) [90149-200]
  90149/90149

答:
You can fix this by setting the spring.datasource.url property like so:

```<code>spring.datasource.url=jdbc:h2:mem:testdb
</code>```

Prior to Spring Boot 2.3.0-RELEASE this was the default, but I'm not sure where it's set. As of 2.3.0-RELEASE, the schema looks to be a randomly generated GUID.

Body:
You can fix this by setting the spring.datasource.url property like so:

spring.datasource.url=jdbc:h2:mem:testdb

Prior to Spring Boot 2.3.0-RELEASE this was the default, but I'm not sure where it's set. As of 2.3.0-RELEASE, the schema looks to be a randomly generated GUID.


问:
"MongoError: Topology is closed" error in EJS
okay so I've made a profile.ejs page,I get the following error when I reload the page.Can someone explain me whats happening.Ive attached all my code below.I am using node js and express as a server.I read this post but didnt understand whats happening.It would be grat if someone could explain the reason for the error .thanks.

profile.ejs

```<code>   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="Stylesheet" href="../addmie/css/styles.css">
    <link >
    <script src="../addmie/js/loadprofile.js"></script>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <title>Document</title>
</head>
<body>
    <%- include('header.ejs')%>
    <%var postlink="/sendpost/"+userobj.username; %>
    <div class="grid-container">
        <div class="grid-container-left">
            <div class="profile">
                <div id="profile_picture">this feature is not yet available</div>
                <div id="username"><%=userobj.username%></div>
            </div>
            <div class="container">
                <h1>friends</h1>
                <div id="friends-container">
                    <ul>
                        <%for(i=0;i< userobj.friends.length;i++){%>
                            <li><%- include('friends.ejs',{friend:userobj.friends[i]})%></li>
                        <%}%>
                    </ul>
                </div>
            </div>
        </div>
        <div class="grid-container-right">
            <div class="postform">

                <form  method="POST" action=<%=postlink%> >
                    <input type='text' name='text' value='Write Something Here'/>
                    <input id='post' type='submit' name='post' value='Post'/>
                </form>
            </div>
            <div class="post-container">
                <h1>your posts</h1>
                <ul>
                    <%for(i=0;i< postobj.length;i++){%>
                        <li><%-include('mypostcontainer.js',{postobj:postobj[i]});%></li>
                    <%}%>
                </ul>

            </div>
        </div>
    </div>
</body>
</html>
</code>```

fetch.js

```<code>const MongoClient = require('mongodb').MongoClient;
const uri = "somelink";
const client = new MongoClient(uri, {useUnifiedTopology:true});
var result=null;
var posts=null;
module.exports = async function dbconnect(from,res)
{
       try {
        // Connect to the MongoDB cluster
        await client.connect();
        console.log('client connected sucessfully');
        // Make the appropriate DB calls
        result=await client.db('profile').collection('user').findOne({username:from});
        posts=await client.db('profile').collection('post').find({username:from}).toArray();
        //console.log(result);
        //console.log(posts);
    } catch (e) {
        console.log('error connecting to db');
        console.error(e);
        res.render('addmie.ejs')
    } finally {
        console.log('closing client connection');
        await client.close();
        console.log(posts);
        res.render('profile.ejs',{userobj:result,postobj:posts});
    }

}
</code>```

controller.js

```<code>app.get('/profile/:username',function(req,res){
        console.log('get request to profile');
        var userobj={
            username:req.params.username,
        };
        let fetch=require('../dbconnect/fetch.js');
        const fname=null;
        fetch(req.params.username,res);
        console.log('profile loaded');

    });
</code>```

error

```<code>MongoError: Topology is closed, please connect
    at processWaitQueue (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\sdam\topology.js:998:42)
    at NativeTopology.selectServer (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\sdam\topology.js:440:5)
    at executeWithServerSelection (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\operations\execute_operation.js:137:12)
    at executeOperation (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\operations\execute_operation.js:75:7)
    at Cursor._initializeCursor (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\cursor.js:536:7)
    at Cursor._initializeCursor (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\cursor.js:185:11)
    at nextFunction (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\cursor.js:739:10)
    at Cursor._next (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\cursor.js:202:5)
    at C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\cursor.js:248:14
    at maybePromise (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\utils.js:719:3) {   [Symbol(mongoErrorContextSymbol)]: {} } Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:526:11)
    at ServerResponse.header (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\response.js:170:12)
    at done (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\response.js:1008:10)
    at tryHandleCache (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\ejs\lib\ejs.js:278:5)
    at View.exports.renderFile [as engine] (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\ejs\lib\ejs.js:489:10)
    at View.render (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\view.js:135:8)
    at tryRender (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\application.js:640:10)
    at Function.render (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\response.js:1012:7) get request to profile the options [servers] is not supported the options [caseTranslate] is not supported the options [dbName] is not supported the options [srvHost] is not supported the options [credentials] is not supported the options [username] is not supported the server/replset/mongos/db options are deprecated, all their options are supported at the top level of the options object [poolSize,ssl,sslValidate,sslCA,sslCert,sslKey,sslPass,sslCRL,autoReconnect,noDelay,keepAlive,keepAliveInitialDelay,connectTimeoutMS,family,socketTimeoutMS,reconnectTries,recon nectInterval,ha,haInterval,replicaSet,secondaryAcceptableLatencyMS,acceptableLatencyMS,connectWithNoPrimary,authSource,w,wtimeout,j,forceServerObjectId,serializeFunctions,ignoreUndefined,raw,bufferMaxEntries,readPreference,pkFactory,promiseLibrary,readConcern,maxStalenessSeconds,loggerLevel,logger,p romoteValues,promoteBuffers,promoteLongs,domainsEnabled,checkServerIdentity,validateOptions,appname,auth,user,password,authMechanism,compression,fsync,readPreferenceTags,numberOfRetries,auto_reconnect,minSize,monitorCommands,retryWrites,retryReads,useNewUrlParser,useUnifiedTopology,serverSelectionTi meoutMS,useRecoveryToken,autoEncryption,driverInfo,tls,tlsInsecure,tlsinsecure,tlsAllowInvalidCertificates,tlsAllowInvalidHostnames,tlsCAFile,tlsCertificateFile,tlsCertificateKeyFile,tlsCertificateKeyFilePassword,minHeartbeatFrequencyMS,heartbeatFrequencyMS,waitQueueTimeoutMS] the options [mode] is not supported the options [tags] is not supported the options [preference] is not supported the options [isValid] is not supported the options [slaveOk] is not supported the options [equals] is not supported the options [toJSON] is not supported the options [source] is not supported the options [mechanism] is not supported the options [mechanismProperties] is not supported
</code>```

答:
I have found a solution to this problem,look at this link

Actually it is recommended to not call client.connect again and again.so the solution Ive figured out is we call client.connect() when the server starts and then won't close it at all.to access the db,just pass the client as a variable in function like so-

```<code>module.exports = async function dbconnect(from,res,client)
{
       try {
        // Connect to the MongoDB cluster
        //await client.connect();
        console.log('client connected sucessfully');
        // Make the appropriate DB calls
        result=await client.db('profile').collection('user').findOne({username:from});
        posts=await client.db('profile').collection('post').find({username:from}).toArray();
        //console.log(result);
        //console.log(posts);
    } catch (e) {
        console.log('error connecting to db');
        console.error(e);
        await res.render('addmie.ejs')
    } finally {
        console.log('closing client connection');
        //await client.close();
        console.log(posts);
        await res.render('profile.ejs',{userobj:result,postobj:posts});
    }

}
</code>```

Body:
okay so I've made a profile.ejs page,I get the following error when I reload the page.Can someone explain me whats happening.Ive attached all my code below.I am using node js and express as a server.I read this post but didnt understand whats happening.It would be grat if someone could explain the reason for the error .thanks.

profile.ejs

   <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="Stylesheet" href="../addmie/css/styles.css">
    <link >

    <title>Document</title>

    <%- include('header.ejs')%>
    <%var postlink="/sendpost/"+userobj.username; %>

this feature is not yet available

<%=userobj.username%>

friends

                        <%for(i=0;i< userobj.friends.length;i++){%>

<%- include('friends.ejs',{friend:userobj.friends[i]})%>

                        <%}%>

                <form  method="POST" action=<%=postlink%> >
                    <input type='text' name='text' value='Write Something Here'/>
                    <input id='post' type='submit' name='post' value='Post'/>
                </form>

your posts

                    <%for(i=0;i< postobj.length;i++){%>

<%-include('mypostcontainer.js',{postobj:postobj[i]});%>

                    <%}%>

fetch.js

const MongoClient = require('mongodb').MongoClient;
const uri = "somelink";
const client = new MongoClient(uri, {useUnifiedTopology:true});
var result=null;
var posts=null;
module.exports = async function dbconnect(from,res)
{
       try {
        // Connect to the MongoDB cluster
        await client.connect();
        console.log('client connected sucessfully');
        // Make the appropriate DB calls
        result=await client.db('profile').collection('user').findOne({username:from});
        posts=await client.db('profile').collection('post').find({username:from}).toArray();
        //console.log(result);
        //console.log(posts);
    } catch (e) {
        console.log('error connecting to db');
        console.error(e);
        res.render('addmie.ejs')
    } finally {
        console.log('closing client connection');
        await client.close();
        console.log(posts);
        res.render('profile.ejs',{userobj:result,postobj:posts});
    }

}

controller.js

app.get('/profile/:username',function(req,res){
        console.log('get request to profile');
        var userobj={
            username:req.params.username,
        };
        let fetch=require('../dbconnect/fetch.js');
        const fname=null;
        fetch(req.params.username,res);
        console.log('profile loaded');

    });

error

MongoError: Topology is closed, please connect
    at processWaitQueue (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\sdam\topology.js:998:42)
    at NativeTopology.selectServer (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\sdam\topology.js:440:5)
    at executeWithServerSelection (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\operations\execute_operation.js:137:12)
    at executeOperation (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\operations\execute_operation.js:75:7)
    at Cursor._initializeCursor (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\cursor.js:536:7)
    at Cursor._initializeCursor (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\cursor.js:185:11)
    at nextFunction (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\cursor.js:739:10)
    at Cursor._next (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\core\cursor.js:202:5)
    at C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\cursor.js:248:14
    at maybePromise (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\mongodb\lib\utils.js:719:3) {   [Symbol(mongoErrorContextSymbol)]: {} } Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:526:11)
    at ServerResponse.header (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\response.js:170:12)
    at done (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\response.js:1008:10)
    at tryHandleCache (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\ejs\lib\ejs.js:278:5)
    at View.exports.renderFile [as engine] (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\ejs\lib\ejs.js:489:10)
    at View.render (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\view.js:135:8)
    at tryRender (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\application.js:640:10)
    at Function.render (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (C:\Users\Nikhil\Desktop\facebook by nick\Addmie\nodejs\node_modules\express\lib\response.js:1012:7) get request to profile the options [servers] is not supported the options [caseTranslate] is not supported the options [dbName] is not supported the options [srvHost] is not supported the options [credentials] is not supported the options [username] is not supported the server/replset/mongos/db options are deprecated, all their options are supported at the top level of the options object [poolSize,ssl,sslValidate,sslCA,sslCert,sslKey,sslPass,sslCRL,autoReconnect,noDelay,keepAlive,keepAliveInitialDelay,connectTimeoutMS,family,socketTimeoutMS,reconnectTries,recon nectInterval,ha,haInterval,replicaSet,secondaryAcceptableLatencyMS,acceptableLatencyMS,connectWithNoPrimary,authSource,w,wtimeout,j,forceServerObjectId,serializeFunctions,ignoreUndefined,raw,bufferMaxEntries,readPreference,pkFactory,promiseLibrary,readConcern,maxStalenessSeconds,loggerLevel,logger,p romoteValues,promoteBuffers,promoteLongs,domainsEnabled,checkServerIdentity,validateOptions,appname,auth,user,password,authMechanism,compression,fsync,readPreferenceTags,numberOfRetries,auto_reconnect,minSize,monitorCommands,retryWrites,retryReads,useNewUrlParser,useUnifiedTopology,serverSelectionTi meoutMS,useRecoveryToken,autoEncryption,driverInfo,tls,tlsInsecure,tlsinsecure,tlsAllowInvalidCertificates,tlsAllowInvalidHostnames,tlsCAFile,tlsCertificateFile,tlsCertificateKeyFile,tlsCertificateKeyFilePassword,minHeartbeatFrequencyMS,heartbeatFrequencyMS,waitQueueTimeoutMS] the options [mode] is not supported the options [tags] is not supported the options [preference] is not supported the options [isValid] is not supported the options [slaveOk] is not supported the options [equals] is not supported the options [toJSON] is not supported the options [source] is not supported the options [mechanism] is not supported the options [mechanismProperties] is not supported

Body:
I have found a solution to this problem,look at this link

Actually it is recommended to not call client.connect again and again.so the solution Ive figured out is we call client.connect() when the server starts and then won't close it at all.to access the db,just pass the client as a variable in function like so-

module.exports = async function dbconnect(from,res,client)
{
       try {
        // Connect to the MongoDB cluster
        //await client.connect();
        console.log('client connected sucessfully');
        // Make the appropriate DB calls
        result=await client.db('profile').collection('user').findOne({username:from});
        posts=await client.db('profile').collection('post').find({username:from}).toArray();
        //console.log(result);
        //console.log(posts);
    } catch (e) {
        console.log('error connecting to db');
        console.error(e);
        await res.render('addmie.ejs')
    } finally {
        console.log('closing client connection');
        //await client.close();
        console.log(posts);
        await res.render('profile.ejs',{userobj:result,postobj:posts});
    }

}


问:
header file and standard library
I am new to programming. learning C as of now. I understand that header file only contains the declarations and function prototypes, not the functions themselves. Am I correct?

I understand that Library is a single file that contains different object codes. Are these object codes necessarily written only in C language or other languages can also be used to generate such object codes?

On linking, does the entire library file get attached to the executable or just the object codes declared in the header file?

答:
I understand that header file only contains the declarations and function prototypes, not the functions themselves. Am I correct?

Yes, in most cases. Code can appear in headers which the compiler will try to "inline" (look that up).

Are these object codes necessarily
  written only in C language or other
  languages can also be used to generate
  such object codes?

They can be written in any complied language but the most common are C and C++.

does the entire library file get attached to the executable or just the object codes declared in the header file?

Linking just tells the executable how to call the underlying the library code, it does not "attached" the library unless you are doing "static" linking.

Title: header file and standard library


问:
How to get the time in am/pm format iphone NSDateFormatter?
Am working in an iPhone app with using the NSDateFormatter. Am getting the time from the webservice like "00:00:00", "16:00:00","15:30:00" and so on. I need to convert these time to
if the time is "00:00:00" to "12 AM", if the time is "16:00:00" to "4 PM", if the time is "15:30:00" to "3.30 PM". I have used the below code to this but when i have pass "16:00:00" the date returns null.

```<code> NSString *dats1 = @"16:00:00";
 NSDateFormatter *dateFormatter3 = [[[NSDateFormatter alloc] init] autorelease];
 [dateFormatter3 setDateStyle:NSDateFormatterMediumStyle];
 [dateFormatter3 setDateFormat:@"hh:mm:ss"];
 NSDate *date1 = [dateFormatter3 dateFromString:dats1];
 NSLog(@"date1 : %@", date1); **// Here returning (null)**

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
 [formatter setDateFormat:@"hh:mm a"];
 NSLog(@"Current Date: %@", [formatter stringFromDate:date1]); **// Here also returning (null)**
 [formatter release];
</code>```

When am passing "00:00:00" it is returning "12 AM" correctly. Can anyone please help me to solve this issue?

答:
Swift 5:</p>

```<code>let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh mm a"
let formattedDate = dateFormatter.string(from: Date())
</code>```

Body:
Am working in an iPhone app with using the NSDateFormatter. Am getting the time from the webservice like "00:00:00", "16:00:00","15:30:00" and so on. I need to convert these time to
if the time is "00:00:00" to "12 AM", if the time is "16:00:00" to "4 PM", if the time is "15:30:00" to "3.30 PM". I have used the below code to this but when i have pass "16:00:00" the date returns null.

 NSString *dats1 = @"16:00:00";
 NSDateFormatter *dateFormatter3 = [[[NSDateFormatter alloc] init] autorelease];
 [dateFormatter3 setDateStyle:NSDateFormatterMediumStyle];
 [dateFormatter3 setDateFormat:@"hh:mm:ss"];
 NSDate *date1 = [dateFormatter3 dateFromString:dats1];
 NSLog(@"date1 : %@", date1); **// Here returning (null)**

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
 [formatter setDateFormat:@"hh:mm a"];
 NSLog(@"Current Date: %@", [formatter stringFromDate:date1]); **// Here also returning (null)**
 [formatter release];

When am passing "00:00:00" it is returning "12 AM" correctly. Can anyone please help me to solve this issue?

Body:
Swift 5:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh mm a"
let formattedDate = dateFormatter.string(from: Date())


问:
Write and read the multiple byte[] into the file C#
I would like to write the three byte arrays into the file. And, later I need to read the same way. Is it possible in C#?. Consider the below example,

```<code>byte[] source = new byte[0];
byte[] delim = new byte[0];
byte[] dest = new byte[0];
</code>```

So, now I planned to write all this three byte arrays together with single file as like below,

```<code>byte[] writeData = new byte[source.Length + delim.Length + dest.Length];
Buffer.BlockCopy(source, 0, writeData, 0, source.Length);
Buffer.BlockCopy(delim, 0, writeData, source.Length, delim.Length);
Buffer.BlockCopy(dest, 0, writeData, source.Length + delim.Length, dest.Length);

File.WriteAllBytes("myfile.txt", writeData);
</code>```

After sometime, I would like to read the file and split the source and dest byte array based on delim. Is it possible?. If yes, how I can achieve this? Any sample code would be much appreciated.

Thanks in advance for your help.

答:
You could use a BinaryWriter and a BinaryReader as shown below.  First write the length of the array as an int32, then write the array bytes.  Repeat for the second array.  In reverse, read the length of the array as an int32, then read that many bytes.  Repeat for the second array:

```<code>byte[] source = new byte[2] { 1, 2 };
byte[] dest = new byte[6] { 2, 4, 8, 16, 32, 64 };

using (FileStream fs = new FileStream("myFile.txt", FileMode.OpenOrCreate))
{
    using (BinaryWriter bw = new BinaryWriter(fs))
    {
        bw.Write(source.Length);
        bw.Write(source, 0, source.Length);
        bw.Write(dest.Length);
        bw.Write(dest, 0, dest.Length);
    }
}

byte[] source2;
byte[] dest2;
using (FileStream fs = new FileStream("myFile.txt", FileMode.Open))
{
    using (BinaryReader br = new BinaryReader(fs))
    {
        source2 = br.ReadBytes(br.ReadInt32());
        dest2 = br.ReadBytes(br.ReadInt32());
    }
}

Console.WriteLine("source = " + String.Join(" ", source));
Console.WriteLine("dest = " + String.Join(" ", dest));
Console.WriteLine("source2 = " + String.Join(" ", source2));
Console.WriteLine("dest2 = " + String.Join(" ", dest2));
</code>```

Output:

```<code>source = 1 2
dest = 2 4 8 16 32 64
source2 = 1 2
dest2 = 2 4 8 16 32 64
</code>```

Body:
I would like to write the three byte arrays into the file. And, later I need to read the same way. Is it possible in C#?. Consider the below example,

byte[] source = new byte[0];
byte[] delim = new byte[0];
byte[] dest = new byte[0];

So, now I planned to write all this three byte arrays together with single file as like below,

byte[] writeData = new byte[source.Length + delim.Length + dest.Length];
Buffer.BlockCopy(source, 0, writeData, 0, source.Length);
Buffer.BlockCopy(delim, 0, writeData, source.Length, delim.Length);
Buffer.BlockCopy(dest, 0, writeData, source.Length + delim.Length, dest.Length);

File.WriteAllBytes("myfile.txt", writeData);

After sometime, I would like to read the file and split the source and dest byte array based on delim. Is it possible?. If yes, how I can achieve this? Any sample code would be much appreciated.

Thanks in advance for your help.

Body:
You could use a BinaryWriter and a BinaryReader as shown below.  First write the length of the array as an int32, then write the array bytes.  Repeat for the second array.  In reverse, read the length of the array as an int32, then read that many bytes.  Repeat for the second array:

byte[] source = new byte[2] { 1, 2 };
byte[] dest = new byte[6] { 2, 4, 8, 16, 32, 64 };

using (FileStream fs = new FileStream("myFile.txt", FileMode.OpenOrCreate))
{
    using (BinaryWriter bw = new BinaryWriter(fs))
    {
        bw.Write(source.Length);
        bw.Write(source, 0, source.Length);
        bw.Write(dest.Length);
        bw.Write(dest, 0, dest.Length);
    }
}

byte[] source2;
byte[] dest2;
using (FileStream fs = new FileStream("myFile.txt", FileMode.Open))
{
    using (BinaryReader br = new BinaryReader(fs))
    {
        source2 = br.ReadBytes(br.ReadInt32());
        dest2 = br.ReadBytes(br.ReadInt32());
    }
}

Console.WriteLine("source = " + String.Join(" ", source));
Console.WriteLine("dest = " + String.Join(" ", dest));
Console.WriteLine("source2 = " + String.Join(" ", source2));
Console.WriteLine("dest2 = " + String.Join(" ", dest2));

Output:

source = 1 2
dest = 2 4 8 16 32 64
source2 = 1 2
dest2 = 2 4 8 16 32 64


问:
Loop through two arrays containing emails
I have two arrays containing email addresses and then another array called emailgroup that contains the name of these two arrays.

I want to create a loop that loops around the emailgroup array to call the other 2 arrays in turn.

I thought for example on the first loop, the "emails" array would be called but the error message says type mismatch.

Can anyone help modify the code below?

```<code> Sub Email_Click()
 Dim myOutlook As Outlook.Application
 Dim objMailMessage As Outlook.MailItem

Dim emails As Variant
Dim moreemails As Variant
Dim emailgroup As Variant

Set myOutlook = Outlook.Application
Set objMailMessage = myOutlook.CreateItem(0)

emails = Array("a@a.com", "b@b.com")
moreemails = Array("c@c.com", "d@d.com")

emailgroup = Array("emails", "moreemails")

For Each i In emailgroup

currentemail = i

With objMailMessage
    .Display
    .To = Join(currentemail, ";")
    .Subject = ""
    .HTMLBody = ""

    .Save
    .Close olPromptForSave
End With
 Next
End Sub
</code>```

答:
```<code>emailgroup = Array("emails", "moreemails")
</code>```

is not the same as an array of arrays:

```<code>emailgroup = Array(emails, moreemails)
</code>```

Then, an array should be iterated over with LBound and UBound:

```<code>Dim i as Long
For i = LBound(emailgroup) to UBound(emailgroup)
    ...
    .To = Join(emailgroup(i), ";")
Next
</code>```

Body:
I have two arrays containing email addresses and then another array called emailgroup that contains the name of these two arrays.

I want to create a loop that loops around the emailgroup array to call the other 2 arrays in turn.

I thought for example on the first loop, the "emails" array would be called but the error message says type mismatch.

Can anyone help modify the code below?

 Sub Email_Click()
 Dim myOutlook As Outlook.Application
 Dim objMailMessage As Outlook.MailItem

Dim emails As Variant
Dim moreemails As Variant
Dim emailgroup As Variant

Set myOutlook = Outlook.Application
Set objMailMessage = myOutlook.CreateItem(0)

emails = Array("a@a.com", "b@b.com")
moreemails = Array("c@c.com", "d@d.com")

emailgroup = Array("emails", "moreemails")

For Each i In emailgroup

currentemail = i

With objMailMessage
    .Display
    .To = Join(currentemail, ";")
    .Subject = ""
    .HTMLBody = ""

    .Save
    .Close olPromptForSave
End With
 Next
End Sub

Body:
emailgroup = Array("emails", "moreemails")

is not the same as an array of arrays:

emailgroup = Array(emails, moreemails)

Then, an array should be iterated over with LBound and UBound:

Dim i as Long
For i = LBound(emailgroup) to UBound(emailgroup)
    ...
    .To = Join(emailgroup(i), ";")
Next


问:
Hough transformation calculation
hough transformation using the normal equation of a line.

For calculating the value of r while keeping the values of x and y same for different θ the following formula is used.

r = sin(θ)y + cos(θ)x

But the results are not the same as shown in the slides. Am I missing something? I am a newbie please be gentle.

答:
As @Ash explained in the comment section above the angles are expected to be expressed in radians not degree.

So r = sin(θ*pi/180)y + cos(θ*pi/180)x will give the correct answer.

Title: Hough transformation calculation


问:
Why is the BehaviorSubject not async?
I created a method to be able to return if the data has already been entered in the store and loaded, but this way it is not async.

It only looks async if I insert a variable outside, inside the subscribe.

What happens is that the value is "true" which is the initial value of the Behavior

SERVICE

```<code>export class StoreService {
    constructor(protected readonly userStore: UserStoreService, protected readonly chatStore: ChatStoreService) {}

    create(): void {
        this.userStore.setAll();
        this.chatStore.setAll();
    }

    get loading(): BehaviorSubject<boolean> {
        const isLoading = new BehaviorSubject(true);

        timer(1000).subscribe(() => {
            combineLatest([this.userStore.loading, this.chatStore.loading])
                .pipe(
                    filter(([userLoading, chatLoading]) => !userLoading && !chatLoading),
                    takeWhile(([userLoading, chatLoading]) => !userLoading && !chatLoading)
                )
                .subscribe(() => isLoading.next(false));
        });

        return isLoading;
    }
}
</code>```

COMPONENT:

```<code>export class AppComponent implements OnInit {
    constructor(public readonly store: StoreService) {}

    ngOnInit(): void {
        this.store.create();
    }
}

{{ store.loading | async | json }}
</code>```

答:
I would set it up differently

```<code>export class StoreService {
   public isLoading$ = new BehaviourSubject(true);

   constructor(protected readonly userStore: UserStoreService, protected readonly chatStore: ChatStoreService) {}

  create(): void {
    this.userStore.setAll();
    this.chatStore.setAll();
    this.load();
  }

  load(): void {
    const isLoading = new BehaviorSubject(true);

    timer(1000).subscribe(() => {
      combineLatest([this.userStore.loading, this.chatStore.loading])
        .pipe(filter(([userLoading, chatLoading]) => !userLoading && !chatLoading),takeWhile(([userLoading, chatLoading]) => !userLoading && !chatLoading))
     .subscribe(() => this.isLoading$.next(false));
    });
  }
}
</code>```

then in your AppComponent

```<code>export class AppComponent implements OnInit {
  constructor(private store: StoreService) {}

  ngOnInit(): void {
    this.store.create();
  }
}

{{ store.isLoading$ | async | json }}
</code>```

Title: Why is the BehaviorSubject not async?

Body:
I created a method to be able to return if the data has already been entered in the store and loaded, but this way it is not async.

It only looks async if I insert a variable outside, inside the subscribe.

What happens is that the value is "true" which is the initial value of the Behavior

SERVICE

export class StoreService {
    constructor(protected readonly userStore: UserStoreService, protected readonly chatStore: ChatStoreService) {}

    create(): void {
        this.userStore.setAll();
        this.chatStore.setAll();
    }

    get loading(): BehaviorSubject<boolean> {
        const isLoading = new BehaviorSubject(true);

        timer(1000).subscribe(() => {
            combineLatest([this.userStore.loading, this.chatStore.loading])
                .pipe(
                    filter(([userLoading, chatLoading]) => !userLoading && !chatLoading),
                    takeWhile(([userLoading, chatLoading]) => !userLoading && !chatLoading)
                )
                .subscribe(() => isLoading.next(false));
        });

        return isLoading;
    }
}

COMPONENT:

export class AppComponent implements OnInit {
    constructor(public readonly store: StoreService) {}

    ngOnInit(): void {
        this.store.create();
    }
}

{{ store.loading | async | json }}

Body:
I would set it up differently

export class StoreService {
   public isLoading$ = new BehaviourSubject(true);

   constructor(protected readonly userStore: UserStoreService, protected readonly chatStore: ChatStoreService) {}

  create(): void {
    this.userStore.setAll();
    this.chatStore.setAll();
    this.load();
  }

  load(): void {
    const isLoading = new BehaviorSubject(true);

    timer(1000).subscribe(() => {
      combineLatest([this.userStore.loading, this.chatStore.loading])
        .pipe(filter(([userLoading, chatLoading]) => !userLoading && !chatLoading),takeWhile(([userLoading, chatLoading]) => !userLoading && !chatLoading))
     .subscribe(() => this.isLoading$.next(false));
    });
  }
}

then in your AppComponent

export class AppComponent implements OnInit {
  constructor(private store: StoreService) {}

  ngOnInit(): void {
    this.store.create();
  }
}

{{ store.isLoading$ | async | json }}


问:
To deep copy or not to deep copy - and why should ngrx's state be immutable, anyway?
I'm new to ngrx (and never used redux) and am trying to make sense of it all - especially whether you need deep copies of the state. Here's what I've learned so far and what still confuses me (further down in bold).

The ngrx docs state that

Each reducer function takes the latest Action dispatched, the current state, and determines whether to return a newly modified state or the original state.

They also point out that state transitions need to happen immutably - if you change state, it needs to be on a copy:

Each action handles the state transition immutably. This means that the state transitions are not modifying the original state, but are returning a new state object using the spread operator.

They don't say why that is necessary, though, beyond promoting referential integrity (and I'm not quite sure how making sure your references are pointing to data - I only know the term from relational database contexts - plays into it all):

The spread syntax copies the properties from the current state into the object, creating a new reference. This ensures that a new state is produced with each change, preserving the purity of the change. This also promotes referential integrity, guaranteeing that the old reference was discarded when a state change occurred.

That (referential integrity and the section above) doesn't really explain why that is necessary, though.

Elsewhere on SO, I found a comment suggesting it allows to change Angular's change detection strategy to OnPush.

(I was also somewhat baffled by how, if an action can trigger several reducers, the resulting state copies can be consolidated, but that's apparently explained by each reducer exclusively looking after a separate slice of the state and redux being aware of that.)

The important thing seems to be, though, that a copy - shallow or deep - of the state creates a new reference, and that means ngrx is pushing a change to its subscribers:

If the returned object reference has changed, it will trigger any related RxJS state subscriptions for the particular piece of state in question. Which subscriptions are triggered can be minimised using some good ngrx selectors.

Generally speaking, the Redux FAQ have a list of why immutability is a good thing and why redux requires it:

increased performance, simpler debugging, easier reasoning, safer data handling, shallow equality checking

They also say that it

enables sophisticated change detection techniques to be implemented simply and cheaply, ensuring the computationally expensive process of updating the DOM occurs only when it absolutely has to

As just pointed out (as one of the requirements for immutability) redux does shallow equality checking.

Nrgx's docs, however, recommend deep cloning (plus, the state isn't truly immutable if the copy references old objects, I suppose):

Note: The spread operator only does shallow copying and does not handle deeply nested objects. You need to copy each level in the object to ensure immutability. There are libraries that handle deep copying including lodash and immer.

However, deep copies might have "nasty" side effects (when using the cloned items in an Angular component, say):

This question even extends to the way Angular's ngFor change detection
  works (and using a trackBy function complicates that even further!):
  when I clone every item in Thing[] and have my reducer return a new
  list of cloned Things, Angular will think it's a brand new list (which
  it technically is) and run change-detection for all items in the list:
  They will also be brand new, and as such, old list items get removed
  and new ones get added to the DOM.

Suppose you have a ThingComponent for each Thing in the ngFor list. In
  that component, ngOnChanges will fire. But here's the thing: the
  SimpleChanges passed to ngOnChanges will never contain previousValues,
  because the whole list got replaced, and so there is previous value:
  everything is brand new, from Angulars perspective.

The author also points to a solution (trackBy), but I'm now wondering:

is using deep copy really a good idea with ngrx (and do you really need deep copies if all that is required to make the library work is a new object reference for the root/state object)? The last quote sounds a bit like it would be a better idea to only swap the root object, the state, out, to get a new reference that then triggers subscriptions, but leave the nested objects - lists, especially - alone.

答:
Deep copy

Our goal to keep our apps as fast as possible what means to reduce calculation when it's not needed or redundant.

Angular has 2 change detection strategies onPush and Default, the first one checks pointers of variables passed into inputs, the second one does deep check and quite heavy on heavy objects. But they have one thing - they rerender only when data has been changed.

Deep copy is bad because it causes the same data to be presented under new object pointers, this causes render cycles and because data is the same rerendered result will be the same too, unless it's time dependent app.

Immutable state

The best way for the data flow is from top to bottom, and bottom can notify top to change the data.

In such circumstances we can always find how data came here via checking parents and what they do with the data, and we have a single point where data is changing and we can find there who causes the change.

If we mutate data where we need the change instead of notifying the top, with time we can't easily find who does it anymore because these places will be everywhere in the code and we need to check all of them to find the issue.


问:
I am trying to add JFrame background image but it is not is not showing up in java
I am trying to add a background image to an JFrame.

I tried every possible solution but it's not working, all I want to do is to add a background image to the JFrame and then print shapes in it as you can see in my code.

Can anyone help me to fix it?

```<code>public class Triangle {
    Oval o;

    public static void main(String[] args) {
        new Triangle();
    }

    public Triangle() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.setSize(400, 400);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {
        private Polygon poly;

        {
            BufferedImage img = null;
            try {
                img = ImageIO.read(new File("apple.PNG"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            Image dimg = img.getScaledInstance(800, 508, Image.SCALE_SMOOTH);
            ImageIcon imageIcon = new ImageIcon(dimg);
            setContentPane(new JLabel(imageIcon));

            poly = new Polygon(
                    new int[] { 110, 150, 50 },
                    new int[] { 200, 0, 0 },
                    3);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        private void setContentPane(JLabel jLabel) {
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.setColor(Color.blue);
            g2.fill(poly);
            g2.setColor(Color.red);
            g2.fillRect(0, 0, 25, 75);
            g2.setColor(Color.green);
            g2.fillOval(200, 100, 100, 50);
            g2.setColor(Color.green);
            g2.fillOval(300, 300, 250, 250);
        }
    }
}
</code>```

答:
Try this. It's fine for me.</p>

```<code>package model;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Polygon;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;

public class Triangle {

    public static void main(String[] args) {
        new Triangle();
    }

    public Triangle() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.setSize(400, 400);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {
        private Polygon poly;

        {
            poly = new Polygon(
                    new int[]{110, 150, 50},
                    new int[]{200, 0, 0},
                    3);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            try {
                BufferedImage img = ImageIO.read(new File("apple.PNG"));
                Image dimg = img.getScaledInstance(800, 508, Image.SCALE_SMOOTH);
                g.drawImage(dimg, 0, 0, this.getWidth(), this.getHeight(), null);
            } catch (IOException e) {
                e.printStackTrace();
            }

            Graphics2D g2 = (Graphics2D) g;
            g2.setColor(Color.blue);
            g2.fill(poly);
            g2.setColor(Color.red);
            g2.fillRect(0, 0, 25, 75);
            g2.setColor(Color.green);
            g2.fillOval(200, 100, 100, 50);
            g2.setColor(Color.green);
            g2.fillOval(300, 300, 250, 250);
        }
    }
}

</code>```

Body:
I am trying to add a background image to an JFrame.

I tried every possible solution but it's not working, all I want to do is to add a background image to the JFrame and then print shapes in it as you can see in my code.

Can anyone help me to fix it?

public class Triangle {
    Oval o;

    public static void main(String[] args) {
        new Triangle();
    }

    public Triangle() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.setSize(400, 400);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {
        private Polygon poly;

        {
            BufferedImage img = null;
            try {
                img = ImageIO.read(new File("apple.PNG"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            Image dimg = img.getScaledInstance(800, 508, Image.SCALE_SMOOTH);
            ImageIcon imageIcon = new ImageIcon(dimg);
            setContentPane(new JLabel(imageIcon));

            poly = new Polygon(
                    new int[] { 110, 150, 50 },
                    new int[] { 200, 0, 0 },
                    3);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        private void setContentPane(JLabel jLabel) {
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.setColor(Color.blue);
            g2.fill(poly);
            g2.setColor(Color.red);
            g2.fillRect(0, 0, 25, 75);
            g2.setColor(Color.green);
            g2.fillOval(200, 100, 100, 50);
            g2.setColor(Color.green);
            g2.fillOval(300, 300, 250, 250);
        }
    }
}

Body:
Try this. It's fine for me.

package model;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Polygon;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;

public class Triangle {

    public static void main(String[] args) {
        new Triangle();
    }

    public Triangle() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.setSize(400, 400);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {
        private Polygon poly;

        {
            poly = new Polygon(
                    new int[]{110, 150, 50},
                    new int[]{200, 0, 0},
                    3);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            try {
                BufferedImage img = ImageIO.read(new File("apple.PNG"));
                Image dimg = img.getScaledInstance(800, 508, Image.SCALE_SMOOTH);
                g.drawImage(dimg, 0, 0, this.getWidth(), this.getHeight(), null);
            } catch (IOException e) {
                e.printStackTrace();
            }

            Graphics2D g2 = (Graphics2D) g;
            g2.setColor(Color.blue);
            g2.fill(poly);
            g2.setColor(Color.red);
            g2.fillRect(0, 0, 25, 75);
            g2.setColor(Color.green);
            g2.fillOval(200, 100, 100, 50);
            g2.setColor(Color.green);
            g2.fillOval(300, 300, 250, 250);
        }
    }
}


问:
Having a camera follow a ball in unity without having the camera roll
I'm working on a golf game in unity, where I have a camera orbitting a ball based on mouse x and y input. The camera controller code works fine until I start applying force to the ball. Please see camera controller code below:

```<code>void ControlCamera()
{
    // Do Nothing if Locked
    if (cameraLocked)
        return;

    // Handle Zoom
    myCamera.transform.position = Vector3.MoveTowards(myCamera.transform.position, transform.position, Input.mouseScrollDelta.y);

    // Handle Y Transformation
    Transform yTransform = myCamera.transform;
    yTransform.RotateAround(transform.position, Vector3.left, Input.GetAxis("Mouse Y") * cameraSensitivity);
    if (yTransform.rotation.eulerAngles.x < maxXRot && yTransform.rotation.eulerAngles.x > minXRot)
    {
        myCamera.transform.rotation = yTransform.rotation;
        myCamera.transform.position = yTransform.position;
    }

    // Handle X Transformation
    myCamera.transform.RotateAround(transform.position, Vector3.down, Input.GetAxis("Mouse X") * cameraSensitivity);

    // Prevent Z Skew
    Quaternion currentRotation = myCamera.transform.rotation;
    float xRot = currentRotation.eulerAngles.x;
    float yRot = currentRotation.eulerAngles.y;
    currentRotation.eulerAngles = new Vector3(xRot, yRot, 0);
    myCamera.transform.rotation = currentRotation;
}
</code>```

The camera object is a child of the ball object, and rolls with the ball when a force is applied. I've tried detatching the camera object from the ball object which breaks the camera object (it no longer follows the ball because it's no longer a child).

Any ideas as to how I can keep this code nice and simple as it it is now and prevent the roll of the camera while still following the ball?

答:
One solution could be to have inside the ball gameObject 2 childs, one with the ball that will rotate, and another one with the camera. This way the camera will follow the parent gameObject, who doesn't rotate (but you should update the position).

The other one, and the one I like it the most is to do not child the camera on to the ball gameObject, just update the camera position from the ball position, JUST the position, not the rotation. Something like:

```<code>public class CameraFollow : MonoBehaviour
{
      public GameObject ball;

      void Update()
      {
          Vector3 pos = ball.transform.position;
          transform.position = pos;
      }
  }
</code>```

Body:
I'm working on a golf game in unity, where I have a camera orbitting a ball based on mouse x and y input. The camera controller code works fine until I start applying force to the ball. Please see camera controller code below:

void ControlCamera()
{
    // Do Nothing if Locked
    if (cameraLocked)
        return;

    // Handle Zoom
    myCamera.transform.position = Vector3.MoveTowards(myCamera.transform.position, transform.position, Input.mouseScrollDelta.y);

    // Handle Y Transformation
    Transform yTransform = myCamera.transform;
    yTransform.RotateAround(transform.position, Vector3.left, Input.GetAxis("Mouse Y") * cameraSensitivity);
    if (yTransform.rotation.eulerAngles.x < maxXRot && yTransform.rotation.eulerAngles.x > minXRot)
    {
        myCamera.transform.rotation = yTransform.rotation;
        myCamera.transform.position = yTransform.position;
    }

    // Handle X Transformation
    myCamera.transform.RotateAround(transform.position, Vector3.down, Input.GetAxis("Mouse X") * cameraSensitivity);

    // Prevent Z Skew
    Quaternion currentRotation = myCamera.transform.rotation;
    float xRot = currentRotation.eulerAngles.x;
    float yRot = currentRotation.eulerAngles.y;
    currentRotation.eulerAngles = new Vector3(xRot, yRot, 0);
    myCamera.transform.rotation = currentRotation;
}

The camera object is a child of the ball object, and rolls with the ball when a force is applied. I've tried detatching the camera object from the ball object which breaks the camera object (it no longer follows the ball because it's no longer a child).

Any ideas as to how I can keep this code nice and simple as it it is now and prevent the roll of the camera while still following the ball?

Body:
One solution could be to have inside the ball gameObject 2 childs, one with the ball that will rotate, and another one with the camera. This way the camera will follow the parent gameObject, who doesn't rotate (but you should update the position).

The other one, and the one I like it the most is to do not child the camera on to the ball gameObject, just update the camera position from the ball position, JUST the position, not the rotation. Something like:

public class CameraFollow : MonoBehaviour
{
      public GameObject ball;

      void Update()
      {
          Vector3 pos = ball.transform.position;
          transform.position = pos;
      }
  }


问:
Read only the last 3 characters from the end of a file and save them as an int
I am trying to write a function which should read the last three characters from a certain .txt file and return me the value as int.

example of what the file contains:"***** ***** 505" .

when I run the code the function returns me "505" but also gives me "/377? below.
I noticed a similar existing post yet I was not able to resolve the issue I am looking for a bit more help.

function:

```<code>int readClientiD(){
    FILE *fp;
     char ch;
     int num=4;
     long length;

     fp = fopen("ClientList.txt", "r");
     if (fp == NULL) {
        puts("cannot open this file");
        exit(1);
     }

     fseek(fp, 0, SEEK_END);
     length = ftell(fp);
     fseek(fp, (length - num), SEEK_SET);

     do {
        ch = fgetc(fp);
         cout<< ch;
     } while (ch != EOF);
     cout<<endl;
     fclose(fp);
     return(0);
}
</code>```

答:
You are printing out the value of ch immediately after reading it and before you check it for EOF.  You need to do the check first.

do {
    ch = fgetc(fp);
    if (ch == EOF) break;
    cout << ch;
} while (true);
```

<p>Or:</p>

<pre class="lang-cpp prettyprint-override"><code>while ((ch = fgetc(fp)) != EOF) {
    cout << ch;
}
</code>```

Whether a char is signed or unsigned is unspecified in the C and C++ standards, so it is up to the compiler implementation to decide. EOF is defined as having a negative value, which is usually -1 in most implementations.  When -1 is treated as an unsigned char, it has a value of decimal 255, hex 0xFF, octal 377, which means char is likely unsigned on your system.

Body:
I am trying to write a function which should read the last three characters from a certain .txt file and return me the value as int.

example of what the file contains:"***** ***** 505" .

when I run the code the function returns me "505" but also gives me "/377? below.
I noticed a similar existing post yet I was not able to resolve the issue I am looking for a bit more help.

function:

int readClientiD(){
    FILE *fp;
     char ch;
     int num=4;
     long length;

     fp = fopen("ClientList.txt", "r");
     if (fp == NULL) {
        puts("cannot open this file");
        exit(1);
     }

     fseek(fp, 0, SEEK_END);
     length = ftell(fp);
     fseek(fp, (length - num), SEEK_SET);

     do {
        ch = fgetc(fp);
         cout<< ch;
     } while (ch != EOF);
     cout<<endl;
     fclose(fp);
     return(0);
}

Body:
You are printing out the value of ch immediately after reading it and before you check it for EOF.  You need to do the check first.

do {
    ch = fgetc(fp);
    if (ch == EOF) break;
    cout << ch;
} while (true);

Or:

while ((ch = fgetc(fp)) != EOF) {
    cout << ch;
}

Whether a char is signed or unsigned is unspecified in the C and C++ standards, so it is up to the compiler implementation to decide. EOF is defined as having a negative value, which is usually -1 in most implementations.  When -1 is treated as an unsigned char, it has a value of decimal 255, hex 0xFF, octal 377, which means char is likely unsigned on your system.


问:
PyOWM installed but not recognized?
Disclaimer - I am quite new to Python.

I wanted to use the OWM API to make a simple Python weather program. I found some guides to using this key on the web, and they said to use the PyOWM library.
I DuckDuckGoed how to install it and I downloaded Pip. I put it in C:/pip and tried to run 'python get-pip.py' (yes, I was in the directory in CMD).

It didn't work, and it sent me to the Microsoft Store page for Python.
I installed it (even though i had the normal ver installed) and tried again. Pip installed.

I ran pip install pyowm and it installed. Everything seemed fine.
When I went back into PyCharm, it wouldn't work. This is the code from the tutorial I am watching:

```<code>import pyowm
owm = pyowm.OWM('<api_key>') # TODO: Replace <api_key> with your API key
la = owm.three_hours_forecast('Los Angeles, US')
print(la.will_have_clouds())
</code>```

Any ideas?

答:
In Pycharm, you have to install your library in the project interpreter.

In your Pycharm go to File -> settings -> Project:test(In my case test means my project name) -> select project interpreter -> click add button

After clicking add button and search pyowm then install it.

Title: PyOWM installed but not recognized?

Body:
Disclaimer - I am quite new to Python.

I wanted to use the OWM API to make a simple Python weather program. I found some guides to using this key on the web, and they said to use the PyOWM library.
I DuckDuckGoed how to install it and I downloaded Pip. I put it in C:/pip and tried to run 'python get-pip.py' (yes, I was in the directory in CMD).

It didn't work, and it sent me to the Microsoft Store page for Python.
I installed it (even though i had the normal ver installed) and tried again. Pip installed.

I ran pip install pyowm and it installed. Everything seemed fine.
When I went back into PyCharm, it wouldn't work. This is the code from the tutorial I am watching:

import pyowm
owm = pyowm.OWM('<api_key>') # TODO: Replace <api_key> with your API key
la = owm.three_hours_forecast('Los Angeles, US')
print(la.will_have_clouds())

Any ideas?