问:
Using tryCatch append output of user-defined functions to a list and warnings/Error messages to a vector in R
Suppose I have a Null vector and Null List -

```<code>ot_vec = c()
msg_lst = list()
</code>```

Further, suppose I have many user-defined functions. Now I want to use a tryCatch to append the outputs of the user-defined functions in the Null list and the messages from tryCatch in the Null vector one by one without printing the outputs and messages from tryCatch.

For e.g., if I define two user-defined functions for Square_Calculator and SquareRoot_Calculator using tryCatch, after running the following lines of code No outputs or error messages should be given directly here -

The outputs and error or warning messages should be appended in the Null List and Null Vector i.e., that list and vector should now take the following form -

I was trying something like that -

Though it is appending the output and error message to the ot_list and msg_vec within the function, it is not appending to the original Null List and Null Vector we have created a the very beginning.

Body:
Suppose I have a Null vector and Null List -

ot_vec = c()
msg_lst = list()

Further, suppose I have many user-defined functions. Now I want to use a tryCatch to append the outputs of the user-defined functions in the Null list and the messages from tryCatch in the Null vector one by one without printing the outputs and messages from tryCatch.

For e.g., if I define two user-defined functions for Square_Calculator and SquareRoot_Calculator using tryCatch, after running the following lines of code No outputs or error messages should be given directly here -

The outputs and error or warning messages should be appended in the Null List and Null Vector i.e., that list and vector should now take the following form -

I was trying something like that -

Though it is appending the output and error message to the ot_list and msg_vec within the function, it is not appending to the original Null List and Null Vector we have created a the very beginning.


来源: stackexchange

问:
Entity Framework throws "Collection was modified" when using observable collection
I have a class Employee, and class Company, which contains a (observable) list of employees.
The observable list is derived from List<>, and basically looks like this:

```<code>public class ObservableList<T> : List<T>
{
   // declaration of delegates and events here
   new public virtual void Add(T item)
        {
            CollectionChangingEventArgs<T> e = new CollectionChangingEventArgs<T>(new T[] { item }, ObservableListChangeAction.Adding);
            OnAdding(e);
            if (e.CancelAction)
                return;

            base.Add(item);

            CollectionChangedEventArgs<T> ed = new CollectionChangedEventArgs<T>(new T[] { item }, ObservableListChangeAction.Added);
            OnAdded(ed);
        }
}
</code>```

The events are wired in Company constructor.
So the whole thing looks approximately like this:

```<code>public class Employee
    {
        // stuff here
    }

    public class Company
    {
        // stuff
        ObservableList<Employee> employees = new ObservableList<Employee>();
        public ObservableList<Employee> Employees { get { return this.employees; } }

        public Company()
        {
            Employees.Adding += new ObservableList<Employee>.CollectionChangingEventHandler(Employees_Adding);
        }

        void Employees_Adding(object sender, CollectionChangingEventArgs<Employee> e)
        {
            // do some checks.. none alter the collection
            *edit*
           // I have a line that does this:
           **employee.Employer = this;**
          //So if the employer was saved prior to this point, it errors out.
        }
    }
</code>```

Now, if I do this:

```<code>Company c = new Company();
Employee e = new Employee();
c.Employees.Adding(e);
c.Save();
</code>```

it works fine.

If, however, I save employee first, like this:

```<code>   Company c = new Company();
    Employee e = new Employee();
    e.Save();
    c.Employees.Adding(e);
    c.Save();
</code>```

then EF throws an exception: Collection was modified; enumeration operation may not execute.

Save() method comes from a base class, basically does this:

```<code>  this.dbContext.Set<T>().Add(instance);
  dbContext.SaveChanges();
</code>```

This is a stack trace:

at System.Collections.Generic.List1.Enumerator.MoveNextRare()    at
  System.Data.Objects.ObjectStateManager.PerformAdd(IList1 entries)

  at System.Data.Objects.ObjectStateManager.DetectChanges()    at
  System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean
  force)    at
  System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action,
  EntityState newState, Object entity, String methodName)    at
  System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity)

  at System.Data.Entity.DbSet`1.Add(TEntity entity)

If I change ObservableList to List<> - it works. If I don't hook up events - it works.
So basically EF doesn't like the events for some reason.
When I'm saving the Company, they're not fired, btw.

I am confused.. Any idea what could be causing this ?

ContentLicense: CC BY-SA 3.0

Body:
I have a class Employee, and class Company, which contains a (observable) list of employees.
The observable list is derived from List<>, and basically looks like this:

public class ObservableList<T> : List<T>
{
   // declaration of delegates and events here
   new public virtual void Add(T item)
        {
            CollectionChangingEventArgs<T> e = new CollectionChangingEventArgs<T>(new T[] { item }, ObservableListChangeAction.Adding);
            OnAdding(e);
            if (e.CancelAction)
                return;

            base.Add(item);

            CollectionChangedEventArgs<T> ed = new CollectionChangedEventArgs<T>(new T[] { item }, ObservableListChangeAction.Added);
            OnAdded(ed);
        }
}

The events are wired in Company constructor.
So the whole thing looks approximately like this:

public class Employee
    {
        // stuff here
    }

    public class Company
    {
        // stuff
        ObservableList<Employee> employees = new ObservableList<Employee>();
        public ObservableList<Employee> Employees { get { return this.employees; } }

        public Company()
        {
            Employees.Adding += new ObservableList<Employee>.CollectionChangingEventHandler(Employees_Adding);
        }

        void Employees_Adding(object sender, CollectionChangingEventArgs<Employee> e)
        {
            // do some checks.. none alter the collection
            *edit*
           // I have a line that does this:
           **employee.Employer = this;**
          //So if the employer was saved prior to this point, it errors out.
        }
    }

Now, if I do this:

Company c = new Company();
Employee e = new Employee();
c.Employees.Adding(e);
c.Save();

it works fine.

If, however, I save employee first, like this:

   Company c = new Company();
    Employee e = new Employee();
    e.Save();
    c.Employees.Adding(e);
    c.Save();

then EF throws an exception: Collection was modified; enumeration operation may not execute.

Save() method comes from a base class, basically does this:

  this.dbContext.Set<T>().Add(instance);
  dbContext.SaveChanges();

This is a stack trace:

at System.Collections.Generic.List1.Enumerator.MoveNextRare()    at
  System.Data.Objects.ObjectStateManager.PerformAdd(IList1 entries)

  at System.Data.Objects.ObjectStateManager.DetectChanges()    at
  System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean
  force)    at
  System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action,
  EntityState newState, Object entity, String methodName)    at
  System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity)

  at System.Data.Entity.DbSet`1.Add(TEntity entity)

If I change ObservableList to List<> - it works. If I don't hook up events - it works.
So basically EF doesn't like the events for some reason.
When I'm saving the Company, they're not fired, btw.

I am confused.. Any idea what could be causing this ?


问:
JWT cookie and refresh token issue in production environment
As mentioned in the title, the refresh token works completely fine inside the development environment (localhost). However, after the "refresh" endpoint was called a few times in the production environment, the cookie suddenly was not sent in the response header.

Note: Node.js/Express.js is used for the backend and it is deployed with vercel.

Below is the code for each of the relevant components:

Verification of token function:

```<code>const verifyToken = (req, res, next) => {
    const cookies = req.headers.cookie;
    const token = cookies.split("=")[1];
    if (!token) {
        return res.status(404).json({ message: "No token found" });
    }
    jwt.verify(String(token), process.env.JWT_SECRET, (err, user) => {
        if (err) {
            return res.status(400).json({ message: "Invalid Token" });
        }
        if (user) {
            req.id = user.id;
            next();
        }
    });
};

</code>```

Refresh token function.

```<code>const refreshToken = (req, res, next) => {
  const cookies = req.headers.cookie;
  const prevToken = cookies.split("=")[1];
  if (!prevToken) {
    return res.status(400).json({ message: "Couldn't find token" });
  }
  jwt.verify(String(prevToken), process.env.JWT_SECRET, (err, user) => {
    if (err) {
      console.log(err);
      return res.status(403).json({ message: "Authentication failed" });
    }

    const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, {
      expiresIn: "35s",
    });
    console.log("Regenerated Token\n", token);

    res.cookie(String(user.id), token, {
        path: "/",
        expires: new Date(Date.now() + 1000 * 35),
        // httpOnly: true,
        sameSite: "none",
        secure: true,
        overwrite: true
    });

    req.id = user.id;
    next();
  });
};
</code>```

Refresh endpoint:

```<code>router.get("/refresh", refreshToken, verifyToken, getMe);
</code>```

The video below shown what happened:
https://imgur.com/a/QBjr06U

ContentLicense: CC BY-SA 4.0

Body:
As mentioned in the title, the refresh token works completely fine inside the development environment (localhost). However, after the "refresh" endpoint was called a few times in the production environment, the cookie suddenly was not sent in the response header.

Note: Node.js/Express.js is used for the backend and it is deployed with vercel.

Below is the code for each of the relevant components:

Verification of token function:

const verifyToken = (req, res, next) => {
    const cookies = req.headers.cookie;
    const token = cookies.split("=")[1];
    if (!token) {
        return res.status(404).json({ message: "No token found" });
    }
    jwt.verify(String(token), process.env.JWT_SECRET, (err, user) => {
        if (err) {
            return res.status(400).json({ message: "Invalid Token" });
        }
        if (user) {
            req.id = user.id;
            next();
        }
    });
};

Refresh token function.

const refreshToken = (req, res, next) => {
  const cookies = req.headers.cookie;
  const prevToken = cookies.split("=")[1];
  if (!prevToken) {
    return res.status(400).json({ message: "Couldn't find token" });
  }
  jwt.verify(String(prevToken), process.env.JWT_SECRET, (err, user) => {
    if (err) {
      console.log(err);
      return res.status(403).json({ message: "Authentication failed" });
    }

    const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, {
      expiresIn: "35s",
    });
    console.log("Regenerated Token\n", token);

    res.cookie(String(user.id), token, {
        path: "/",
        expires: new Date(Date.now() + 1000 * 35),
        // httpOnly: true,
        sameSite: "none",
        secure: true,
        overwrite: true
    });

    req.id = user.id;
    next();
  });
};

Refresh endpoint:

router.get("/refresh", refreshToken, verifyToken, getMe);

The video below shown what happened:
https://imgur.com/a/QBjr06U


问:
flutter - I need to call a function when I receive local notifications
I am trying to execute some code (a function) whenever I receive a minutely repeated local notification on android to mimic background tasks. (I want to track our employees when the app is in background, but without using background task packages)

So, simply I am doing a trick, and I don't know whether that works or not, but what I am trying to do is, I want to periodically send local notifications to myself, using **flutter_local_notifications **package, and I want to know if there is any way that I can execute some code when I receive the notification. (the local notification act as a background task and I want to do something when I get this local notification, to mimic using background tasks.)

I have tried a lot of packages for background tasks.
Including alarm_manager_plus, background_location, and work_manager package.
the best one was workmanager package, but the frequency of repeating the background task was 15 minutes, which is far more than I want.
So, this trick came to my mind, if it works.

So, I thought if sending the scheduled local notifications for every minute and executing some code when I receive them works, then I will go with this approach.

So, I am asking, is there any way to execute some code when receiving local notification?
or is there a better way of doing that?

Any Help is appreciated, thanks.


问:
Is there any function in Quicksight where I can count different customers who have purchased in various categories?
I have customers who paid in different categories, for example, SHOPPING, BEAUTY, FOOD etc.

And I'd like to count the number of customers who bought in two different categories, for example, SHOPPING and FOOD in a KPI visual

Quicksight does not allow the use of calculated fields with other calculated fields.If it could be possible I could calculate with a distinct_countIf.
The only way that I got is showing in a pivot table, and summarizing.

Can you think of any other more elegant way?


问:
React-select visual state resetting on scroll
I have this React website, with a spreadsheet (using ReactGrid). The spreadsheet has a column of dropdown cells (using React-Select).

When I select an item from the dropdown, the script updates the spreadsheet (that is saved as a state). And it displays like so:

Now, here is the issue. It's a long spreadsheet (100 columns). When I scroll all the way down and then scroll back up, the sheet "re-renders", and the option I just selected is not displayed anymore.

console.log shows that the sheet is in fact updated, and the correct value of "United States" is selected for the cell, but visually - it's gone. Important detail - I tried it with the text cells, but the issue isn't present with them.

I don't know what pieces of code to give here, so if you've any prompt on where to look for the issue, I'll provide the relevant lines. Thanks.


问:
Kendo React grid column on resizing to right or left by mouse dragging showing weird behavior having set the "Resizable" attribute to true
Kendo React grid column on resizing/ screeching to right or left by clicking and dragging using mouse showing weird behavior like jumping to uncertain positions having set the "Resizable" attribute to true. I have attached the video of this problem.

I have updated the kendo react dependencies to version 5.9 and resizable to true but not solving this issue.


问:
Is Niko scanner supporting in Windows 11 version? As per requirement I have installed latest version of Active Perl
Is Niko scanner supporting in Windows 11 version. When I try to run cmd e.g "perl nikto.pl -h URL" then it does nothing. Also doesn't showing any error. It was working fine with my old Windows 10 machine. Please help me.

When I try to run cmd e.g "perl nikto.pl -h URL" then it does nothing. Also doesn't showing any error.
Expecting: Atleast it should display the error or something else related to scanner.
Nikto scanner


问:
Amazon.QLDB.Model.LimitExceededException: 'Exceeded the limit of 5 active ledgers' when creating a ledger programmatically
I have a code for creating QLDB Ledgers on AWS. It works well but I can't find any documentation about this limitation.

```<code>Amazon.QLDB.Model.LimitExceededException: 'Exceeded the limit of 5 active ledgers'
</code>```

I have 5 ledgers within an account/region. If I try to create a new one from the aws console I get this error message: "Error: failed to create ledger."
In my company we plan to create as many ledgers as customer amount we have. How can I make this simple?

Thanks
Regards

Body:
I have a code for creating QLDB Ledgers on AWS. It works well but I can't find any documentation about this limitation.

Amazon.QLDB.Model.LimitExceededException: 'Exceeded the limit of 5 active ledgers'

I have 5 ledgers within an account/region. If I try to create a new one from the aws console I get this error message: "Error: failed to create ledger."
In my company we plan to create as many ledgers as customer amount we have. How can I make this simple?

Thanks
Regards


问:
Found unparsable section: 'EXECUTE IMMEDIATE\n ...' sqlfuff?
I'm using sqlfluff to check the sql code formatting.
conf of sqlfluff are here :

```<code>    sqlfluff = "^0.13.2"
    [tool.sqlfluff]
    sql_file_exts = [
    ".sql",
    ]
    [tool.sqlfluff.core]
    dialect = "bigquery"
    rules = "L001,L002,L003,L004,L005,L006,L008,L009,L010,L012,L013,L015,L016,L018,L019,L020,L022,L023,L024,L025,L035,L036,L037,L038,L039,L040,L041,L045,L046,L048,L049,L050,L051,L052,L053,L061,L063"
</code>```

I have a sql query that uses EXECUTE IMMEDIATE (dynamic bigquery sql)

DECLARE
  c_c string;
DECLARE
  ps ARRAY<string>;
DECLARE
  p_cc string;
DECLARE
  d_cc string;
CREATE TABLE IF NOT EXISTS
  `dataset.table` ( A STRING,
    B STRING,
    C STRING,
    D STRING,
    F STRING,
    E STRING,
    G STRING,
    H STRING,
    E STRING,
    J timestamp,
    K INT64 ) PARTITION BY
  RANGE_BUCKET(K, GENERATE_ARRAY(0,100,1));
SET
  c_c="code1";
SET
  ps = ["project-code1",
  "project-code2",
  "project-code3",
  "project-code4",
  "project-code5",
  "project-code6"];
SET
  p_cc = (
  WITH
    ps_cte AS (
    SELECT
      *
    FROM
      UNNEST(ps) ps
    WHERE
      ps LIKE CONCAT('%-', c_c))
  SELECT
    ps
  FROM
    ps_cte);
SET
  d_cc = CONCAT(p_cc,".sales_",c_c,".");
EXECUTE IMMEDIATE
  FORMAT( """
  CREATE OR REPLACE TEMP TABLE temp_table AS
SELECT
    cols
FROM
     `%ssat_table` sc
 """,d_cc)```
</div>
</div>
</p>
<p>:</p>
<p>when I want to apply sqlfluff lint :</p>
```  poetry run sqlfluff lint query.sql
```
<p>it gives:</p>
```   L:  47 | P:   1 |  PRS | Line 47, Position 1: Found unparsable section: 'EXECUTE
                   | IMMEDIATE\n FORMAT( """ \n CREAT...'
```

why sqlfluff don't know execute immediate ? is there any solution?

Thanks

Body:
I'm using sqlfluff to check the sql code formatting.
conf of sqlfluff are here :

    sqlfluff = "^0.13.2"
    [tool.sqlfluff]
    sql_file_exts = [
    ".sql",
    ]
    [tool.sqlfluff.core]
    dialect = "bigquery"
    rules = "L001,L002,L003,L004,L005,L006,L008,L009,L010,L012,L013,L015,L016,L018,L019,L020,L022,L023,L024,L025,L035,L036,L037,L038,L039,L040,L041,L045,L046,L048,L049,L050,L051,L052,L053,L061,L063"

I have a sql query that uses EXECUTE IMMEDIATE (dynamic bigquery sql)

DECLARE
  c_c string;
DECLARE
  ps ARRAY<string>;
DECLARE
  p_cc string;
DECLARE
  d_cc string;
CREATE TABLE IF NOT EXISTS
  `dataset.table` ( A STRING,
    B STRING,
    C STRING,
    D STRING,
    F STRING,
    E STRING,
    G STRING,
    H STRING,
    E STRING,
    J timestamp,
    K INT64 ) PARTITION BY
  RANGE_BUCKET(K, GENERATE_ARRAY(0,100,1));
SET
  c_c="code1";
SET
  ps = ["project-code1",
  "project-code2",
  "project-code3",
  "project-code4",
  "project-code5",
  "project-code6"];
SET
  p_cc = (
  WITH
    ps_cte AS (
    SELECT
      *
    FROM
      UNNEST(ps) ps
    WHERE
      ps LIKE CONCAT('%-', c_c))
  SELECT
    ps
  FROM
    ps_cte);
SET
  d_cc = CONCAT(p_cc,".sales_",c_c,".");
EXECUTE IMMEDIATE
  FORMAT( """
  CREATE OR REPLACE TEMP TABLE temp_table AS
SELECT
    cols
FROM
     `%ssat_table` sc
 """,d_cc)

:

when I want to apply sqlfluff lint :

  poetry run sqlfluff lint query.sql

it gives:

   L:  47 | P:   1 |  PRS | Line 47, Position 1: Found unparsable section: 'EXECUTE
                   | IMMEDIATE\n FORMAT( """ \n CREAT...'

why sqlfluff don't know execute immediate ? is there any solution?

Thanks


问:
IIS COM component failure - Azure VM
I am working on a website that uses Sage 50 Interop component dll and it all works fine in VS and my local IIS but on Azure VM IIS it throws an error.
(Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))

I have been at it for days now and have no idea what else to check or configure.

Note: I had an older version of this DLL and it worked well. All the newer versions are throwing this error on Azure.

Title: IIS COM component failure - Azure VM


问:
File type:ejs.I have a problem with syntacxis
```<code> <ul>
      <% if ('contacts'.length) { %> <% 'contacts'.forEach(({ link, name }) => { -%>
      <li>
        <a href="<%= link %>"><%= name %></a>
      </li>
      <% }) %> <% } %>
    </ul>
</code>```

I have a syntacxis problem with this part of ejs file.What would be the correct syntax?

I try ejslint,but he doesnt support me

Body:
      <% if ('contacts'.length) { %> <% 'contacts'.forEach(({ link, name }) => { -%>

        <a href="<%= link %>"><%= name %>

      <% }) %> <% } %>

I have a syntacxis problem with this part of ejs file.What would be the correct syntax?

I try ejslint,but he doesnt support me


问:
Moq C# UnitTest of FilterDefinition for MongoDB
Trying to create a unit test for the filter in the method. But the test failed due to I have no database. Trying to mock the database, so I can test that filter in the method. The database call test is separate from the integration test.

```<code>namespace Repository
        public async Task<IEnumerable<ContractCollection>> GetContractsForUpdate(DateTime date)
        {
            var builder = Builders<ContractCollection>.Filter;
            var filter = builder.Lte(x => x.StartDate, date) & builder.Gte(x => x.EndDate, date);

            return await _db.GetCollection<ContractCollection>().FindSync(filter).ToListAsync();
        }
</code>```

These are parts of my test class, I use the packages(FluentAssertions 6.8.0, Moq 4.18.4). Also, try using ReturnsAsync. It fails due ContractCollection is null.

```<code>        using FluentAssertions;
        using MongoDB.Driver;
        using Moq;
        namespace Repository.UnitTests

        public class RepositoryTests
        {
            private IRepositoryHelper _repositoryHelper;
            private Mock<IRepositoryHelper> _mockRepositoryHelper;
            private Repository _sut;
            private Mock<IDb> _dbMock;
            private readonly Mock<IMongoCollection<ContractCollection>> _collectionMock =
            new Mock<IMongoCollection<ContractCollection>>();

            protected override void OnTestInitialize()
            {
                base.OnTestInitialize();

                _repositoryHelper = new RepositoryHelper();
                _dbMock = new Mock<IDb>();
                _mockRepositoryHelper = new Mock<IRepositoryHelper>();

                _sut = new Repository(_dbMock.Object, _mockRepositoryHelper.Object);
            }

            [TestMethod]
            public async Task TestGetContractsForUpdate_FilterAsync()
            {
                //Arrange
                var date = new DateTime(2023, 1, 9);
                var expectedFilter = Builders<ContractCollection>.Filter.Lte(x => x.StartDate, date)
                    & Builders<ContractCollection>.Filter.Gte(x => x.EndDate, date);

                var expectedContracts = new[]
                {
                    new ContractCollection { StartDate = new DateTime(2023, 1, 1), EndDate = new DateTime(2023, 1, 31) },
                    new ContractCollection { StartDate = new DateTime(2023, 2, 1), EndDate = new DateTime(2023, 2, 28) }
                };

                _dbMock.Setup(db => db.GetCollection<ContractCollection>(It.IsAny<string>())).Returns(_collectionMock.Object);

                _collectionMock.Object.InsertMany(expectedContracts);

                var projection = Builders<ContractCollection>.Projection.Include(x => x.StartDate).Include(x => x.EndDate);
                var options = new FindOptions<ContractCollection, ContractCollection> { Projection = projection };

                //Act, Assert
                var enumerable = await _sut.GetContractsForUpdate(date);

                _collectionMock.Verify(x => x.FindAsync(
                    It.Is<FilterDefinition<ContractCollection>>(f => f.ToString() == expectedFilter.ToString()),
                    options, It.IsAny<CancellationToken>()), Times.Once());
            }

        }
</code>```

filter to be comparable against expectedFilter in the Unit test TestGetContractsForUpdate_FilterAsync

Body:
Trying to create a unit test for the filter in the method. But the test failed due to I have no database. Trying to mock the database, so I can test that filter in the method. The database call test is separate from the integration test.

namespace Repository
        public async Task<IEnumerable<ContractCollection>> GetContractsForUpdate(DateTime date)
        {
            var builder = Builders<ContractCollection>.Filter;
            var filter = builder.Lte(x => x.StartDate, date) & builder.Gte(x => x.EndDate, date);

            return await _db.GetCollection<ContractCollection>().FindSync(filter).ToListAsync();
        }

These are parts of my test class, I use the packages(FluentAssertions 6.8.0, Moq 4.18.4). Also, try using ReturnsAsync. It fails due ContractCollection is null.

        using FluentAssertions;
        using MongoDB.Driver;
        using Moq;
        namespace Repository.UnitTests

        public class RepositoryTests
        {
            private IRepositoryHelper _repositoryHelper;
            private Mock<IRepositoryHelper> _mockRepositoryHelper;
            private Repository _sut;
            private Mock<IDb> _dbMock;
            private readonly Mock<IMongoCollection<ContractCollection>> _collectionMock =
            new Mock<IMongoCollection<ContractCollection>>();

            protected override void OnTestInitialize()
            {
                base.OnTestInitialize();

                _repositoryHelper = new RepositoryHelper();
                _dbMock = new Mock<IDb>();
                _mockRepositoryHelper = new Mock<IRepositoryHelper>();

                _sut = new Repository(_dbMock.Object, _mockRepositoryHelper.Object);
            }

            [TestMethod]
            public async Task TestGetContractsForUpdate_FilterAsync()
            {
                //Arrange
                var date = new DateTime(2023, 1, 9);
                var expectedFilter = Builders<ContractCollection>.Filter.Lte(x => x.StartDate, date)
                    & Builders<ContractCollection>.Filter.Gte(x => x.EndDate, date);

                var expectedContracts = new[]
                {
                    new ContractCollection { StartDate = new DateTime(2023, 1, 1), EndDate = new DateTime(2023, 1, 31) },
                    new ContractCollection { StartDate = new DateTime(2023, 2, 1), EndDate = new DateTime(2023, 2, 28) }
                };

                _dbMock.Setup(db => db.GetCollection<ContractCollection>(It.IsAny<string>())).Returns(_collectionMock.Object);

                _collectionMock.Object.InsertMany(expectedContracts);

                var projection = Builders<ContractCollection>.Projection.Include(x => x.StartDate).Include(x => x.EndDate);
                var options = new FindOptions<ContractCollection, ContractCollection> { Projection = projection };

                //Act, Assert
                var enumerable = await _sut.GetContractsForUpdate(date);

                _collectionMock.Verify(x => x.FindAsync(
                    It.Is<FilterDefinition<ContractCollection>>(f => f.ToString() == expectedFilter.ToString()),
                    options, It.IsAny<CancellationToken>()), Times.Once());
            }

        }

filter to be comparable against expectedFilter in the Unit test TestGetContractsForUpdate_FilterAsync


问:
How to solve could not handle the request problem in dialogflow
I am trying to develop a chatbot using dialogflow. I am trying to develop the fulfilment in my local environment. But when I deploy the cloud functions and try to execute it I am having an error :

```<code>Error: could not handle the request
</code>```

I have watched a lot of tutorials online, and read documentations still I could not solve it. Is there anyone who could help me out ?

I used this command to deploy the application:

```<code>gcloud functions deploy dialogflowFirebaseFulfillment  --allow-unauthenticated
</code>```

I will attach some pictures so that you will see and understand what i am facing.

enter image description here

enter image description here
enter image description here

Body:
I am trying to develop a chatbot using dialogflow. I am trying to develop the fulfilment in my local environment. But when I deploy the cloud functions and try to execute it I am having an error :

Error: could not handle the request

I have watched a lot of tutorials online, and read documentations still I could not solve it. Is there anyone who could help me out ?

I used this command to deploy the application:

gcloud functions deploy dialogflowFirebaseFulfillment  --allow-unauthenticated

I will attach some pictures so that you will see and understand what i am facing.

enter image description here

enter image description here
enter image description here


问:
Text not splitting between two pages by generating a pdf
I'm building dynamic PDFs with the API pdfswitch https://pdfswitch.io. Unfortunately I got some problems if the content is more than one A4-page long. The API generates more pages, no problem, but the text will cut off at the end of a page. Do anybody using this API Service as well? How can I manage to define a content-block where is not splitting between two pages ? f.e. ..)?

Thanks for help.


问:
Saving a "Measurement File" (Trace) while debugging in C++ with GDB
I am facing the following issue: In our project, we have a main class with a main method called "run". This method calls hundreds of other functions, classes etc.

We are now calling this run method in a test in a for loop multiple times, something like that:

for(float test_time = 0; test_time < 10.0; test_time += 0.005){
    outputStruct = mainClass.run(inputStruct);
}
```

I now want to save all local variables of all functions and methods and all member variables of all included objects that are seen when this for loop is executed. And I want to have a snapshot of this for each loop iteration. So in this example, there should be like 2000 snapshots of all my variables.

Is this somehow possible? I see that GDB has some "trace" functionality, but it's not clear for me how I can tell GDB that it should save everything that was "seen" while executing the mainClass.run method. It should "only" remember the last state of each member and local variable. And when test_time increments, it can finalize the current snapshot and create a new one for the next time slot.

Is something like this possible? Since our usecase is some physics based scenario, it is every interesting to see how certain values change over time in a plot later. I don't mind what the format of the output file of GDB is, it will be parsed later anyway, as long as the information is somehow inside. Of course, the cleaner the file looks the better :).

Thank you for your support guys!

Body:
I am facing the following issue: In our project, we have a main class with a main method called "run". This method calls hundreds of other functions, classes etc.

We are now calling this run method in a test in a for loop multiple times, something like that:

for(float test_time = 0; test_time < 10.0; test_time += 0.005){
    outputStruct = mainClass.run(inputStruct);
}

I now want to save all local variables of all functions and methods and all member variables of all included objects that are seen when this for loop is executed. And I want to have a snapshot of this for each loop iteration. So in this example, there should be like 2000 snapshots of all my variables.

Is this somehow possible? I see that GDB has some "trace" functionality, but it's not clear for me how I can tell GDB that it should save everything that was "seen" while executing the mainClass.run method. It should "only" remember the last state of each member and local variable. And when test_time increments, it can finalize the current snapshot and create a new one for the next time slot.

Is something like this possible? Since our usecase is some physics based scenario, it is every interesting to see how certain values change over time in a plot later. I don't mind what the format of the output file of GDB is, it will be parsed later anyway, as long as the information is somehow inside. Of course, the cleaner the file looks the better :).

Thank you for your support guys!


问:
How to install gtk2.0 with OPKG package manager?
I'm using IMX6DL, there the OS which it is running on it contains OPKG package manager, but while install gtk2.0 I'm getting

```<code>$ opkg install libgtk-2.0-dev
opkg_prepare_url_for_install: Couldn't find anything to satisfy 'gtk+2.0'
</code>```

Can anyone tell me how manage this?

Body:
I'm using IMX6DL, there the OS which it is running on it contains OPKG package manager, but while install gtk2.0 I'm getting

$ opkg install libgtk-2.0-dev
opkg_prepare_url_for_install: Couldn't find anything to satisfy 'gtk+2.0'

Can anyone tell me how manage this?


问:
How to count at runtime a number of currently existing instances of object of type X?
So I can not change object code, I have X instances of it allocated from various assemblies. I want to count how many instances there are. How to count at runtime a number of currently existing instances of object of type X using reflection or something similar not changing the object type source code?</p>


问:
How does client credential flow work in Workload identity federation?
For my current ASP.NET Core MVC application I authenticate directly with a web app registered in Azure AD Portal. This provides me with an access token so on the backend of my web application I can use MS Graph with my users specific account (ie add files to their onedrive , email, etc). However, my organization also has Okta which a lot of applications authenticate against. So I was trying to determine to authenticate through Okta (which has a much cleaner sign in process IMO) as well as authenticate against Azure AD and get an access token. Through my research I found something in my web application registration in Azure AD called Workload Identity Federation. This led me to this useful video

https://www.youtube.com/watch?v=wZ0gCJYMUKI

and also microsofts info site:

https://learn.microsoft.com/en-us/azure/active-directory/develop/workload-identity-federation

This seems to answer what I want which is to use Okta but allow me to still use MS Graph for my users since it will authenticate against Azure AD (correct me if I am wrong and this is for something else). My issue is none of these resources really go into depth regarding how the access token is passed to my application so I can use MS Graph. My research this is called client credential flow since my application only has delegated permissions so it requires the users to log in and it basically allows my web app to act on their behalf when using MS Graph. So I am trying to understand and fill this void of information regarding how client credential flow fits into Workload Identity Federation and is this the solution to my problem.


问:
Threepenny GUI build fail
So I've been trying to install Threepenny GUI for a Haskell college assignment the last few hours without any avail. When stack attemps to build the 'snap-core' dependency, I get the following error:

snap-core      > configure
snap-core      > Configuring snap-core-1.0.5.0...
snap-core      > build
snap-core      > Preprocessing library for snap-core-1.0.5.0..
snap-core      > Building library for snap-core-1.0.5.0..
snap-core      > [ 1 of 18] Compiling Snap.Internal.Debug
snap-core      > [ 2 of 18] Compiling Snap.Types.Headers
snap-core      > [ 3 of 18] Compiling Snap.Internal.Http.Types
snap-core      >
snap-core      > src\Snap\Internal\Http\Types.hs:1285:11: error:
snap-core      >     * Variable not in scope:
snap-core      >         parseTime :: TimeLocale -> t0 -> String -> Maybe UTCTime
snap-core      >     * Perhaps you meant `parseTimeM' (imported from Data.Time.Format)
snap-core      >      |
snap-core      > 1285 |     prs = parseTime defaultTimeLocale "%a, %d %b %Y %H:%M:%S GMT"
snap-core      >      |           ^^^^^^^^^
Progress 1/4

--  While building package snap-core-1.0.5.0 (scroll up to its section to see the error) using:
      C:\Users\User\AppData\Roaming\stack\setup-exe-cache\x86_64-windows\Cabal-simple_Z6RU0evB_3.6.3.0_ghc-9.2.5.exe --verbose=1 --builddir=.stack-work\dist\8a54c84f build --ghc-options " -fdiagnostics-color=always"
    Process exited with code: ExitFailure 1
```

I have tried building the dependencies of snap-core with 'stack build --dependencies-only snap-core' with no avail. I've also tried to build the 'time' package on it's own with no avail either. My stack version is up to date also. Any ideas..?

Title: Threepenny GUI build fail

Body:
So I've been trying to install Threepenny GUI for a Haskell college assignment the last few hours without any avail. When stack attemps to build the 'snap-core' dependency, I get the following error:

snap-core      > configure
snap-core      > Configuring snap-core-1.0.5.0...
snap-core      > build
snap-core      > Preprocessing library for snap-core-1.0.5.0..
snap-core      > Building library for snap-core-1.0.5.0..
snap-core      > [ 1 of 18] Compiling Snap.Internal.Debug
snap-core      > [ 2 of 18] Compiling Snap.Types.Headers
snap-core      > [ 3 of 18] Compiling Snap.Internal.Http.Types
snap-core      >
snap-core      > src\Snap\Internal\Http\Types.hs:1285:11: error:
snap-core      >     * Variable not in scope:
snap-core      >         parseTime :: TimeLocale -> t0 -> String -> Maybe UTCTime
snap-core      >     * Perhaps you meant `parseTimeM' (imported from Data.Time.Format)
snap-core      >      |
snap-core      > 1285 |     prs = parseTime defaultTimeLocale "%a, %d %b %Y %H:%M:%S GMT"
snap-core      >      |           ^^^^^^^^^
Progress 1/4

--  While building package snap-core-1.0.5.0 (scroll up to its section to see the error) using:
      C:\Users\User\AppData\Roaming\stack\setup-exe-cache\x86_64-windows\Cabal-simple_Z6RU0evB_3.6.3.0_ghc-9.2.5.exe --verbose=1 --builddir=.stack-work\dist\8a54c84f build --ghc-options " -fdiagnostics-color=always"
    Process exited with code: ExitFailure 1

I have tried building the dependencies of snap-core with 'stack build --dependencies-only snap-core' with no avail. I've also tried to build the 'time' package on it's own with no avail either. My stack version is up to date also. Any ideas..?


问:
Import component dynamically in vue 3
I want to import screens based on user id. I created a wrapper component to do this but It doesn't work for nested routes. In vue 2 I can use app instance in router to decide which screen renders but vue 3 I can't do this approach

<template>
  <component
    v-if="decidedComponent"
    :is="decidedComponent"
    :key="`${decidedComponent.__file}`"
  ></component>
</template>
```
<pre class="lang-js prettyprint-override"><code>//router

    {
        path: "/customer/:customerId",
        name: "customer",
        component: DecideComponent,
        meta: {
          name: "MultiPages",
        },
        children: [
          {
            path: "details",
            name: "customer.details",
            component: DecideComponent,
            meta: {
              name: "CustomerDetails",
            },
          },
</code>```

It doesn't work for parent route.

Title: Import component dynamically in vue 3

Body:
I want to import screens based on user id. I created a wrapper component to do this but It doesn't work for nested routes. In vue 2 I can use app instance in router to decide which screen renders but vue 3 I can't do this approach

<template>
  <component
    v-if="decidedComponent"
    :is="decidedComponent"
    :key="`${decidedComponent.__file}`"
  ></component>
</template>

//router

    {
        path: "/customer/:customerId",
        name: "customer",
        component: DecideComponent,
        meta: {
          name: "MultiPages",
        },
        children: [
          {
            path: "details",
            name: "customer.details",
            component: DecideComponent,
            meta: {
              name: "CustomerDetails",
            },
          },

It doesn't work for parent route.


问:
Manipulating property transfer SOAPUI
I have a few test steps set up in SOAPUI with a property transfer step in between to transfer the sessionkey from one response to the next. The problem is, that the response is putting "" around the session key, and these need to be removed in the property transfer.

I used to have a working script that did just that:

def response = messageExchange.responseContent
response = response.replace("""","")
messageExchange.modelItem.testStep.testCase.setPropertyValue("jsonResponse",response)

However, this is no longer working and gives the following error: "Content not allowed in prolog".

Has anyone got any idea what causes this? It was working fine, but after having used SOAPUI for a few years, its now throwing this error..

Thanks!

Title: Manipulating property transfer SOAPUI


问:
Invoke-WebRequest permanent error of an unexpected error occurred on a send
using PowerShell v5.1 on windows server 2016, for monitoring the availability of the following CrowdStrike Cloud Endpoint: https://ts01-b.cloudsink.net, with a dedicated proxy in our organization:

```<code>$URLAddress = "https://ts01-b.cloudsink.net"
$ProxyAddress = "http://proxyout.dev:8080"

$response = $null
$errorcode = $null

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"

try
{
$request = Invoke-WebRequest -Uri $URLAddress -Method Get -UseBasicParsing -DisableKeepAlive -MaximumRedirection 0 -Proxy $ProxyAddress -ProxyUseDefaultCredentials

$response = $request.StatusCode
Write-Host "Status Code -- $response"
}
catch
{
$errormessage = $_.Exception.Message
$errorcode = $_.Exception.Response.StatusCode.Value__
}

IF ($response -eq '200')
{
IF ($errorcode -eq $null)
{
  Write-Host "url: ""$URLAddress"" is avalible. `nStatus Code: $response"

}
ELSE
{
  Write-Host "url: ""$URLAddress"" is avalible but porxy: ""$proxydev"" has an error, `nError Code: $errorcode `nError Message:`n$errormessage. `nStatus Code: $response"
}
}
ELSE
{
  Write-Host "url: ""$URLAddress"" is not avalible. `nStatus Code: $response `nError Code: $errorcode `nError Message:`n$errormessage"
}

$request.BaseResponse.Close()
</code>```

But I'm experiencing a strange behavior with the above script, for some reason i will get a permanent error of:

The underlying connection was closed: An unexpected error occurred on a send.

Even though when I'm running the script locally on target server, the script is working without any problems.

Running an analysis using SSL Report, i can verify that ts01-b.cloudsink.net is using TLS version 1.2. so i don't need to bypass the SSL certificate check [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} which is something that i saw mentioned frequently in other Stack Overflow posts, like:

Unexpected error occurred running a simple unauthorized Rest query

Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send

It is worth mentioning that the problematic window server is used by all the other developers in the organization, which run their own PowerShell scripts frequently manually or schedules by using a monitoring agent named SCOM by Microsoft.

I'm struggling to understand the root cause of this problem, has anyone experienced this kind of issue?

Body:
using PowerShell v5.1 on windows server 2016, for monitoring the availability of the following CrowdStrike Cloud Endpoint: https://ts01-b.cloudsink.net, with a dedicated proxy in our organization:

$URLAddress = "https://ts01-b.cloudsink.net"
$ProxyAddress = "http://proxyout.dev:8080"

$response = $null
$errorcode = $null

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"

try
{
$request = Invoke-WebRequest -Uri $URLAddress -Method Get -UseBasicParsing -DisableKeepAlive -MaximumRedirection 0 -Proxy $ProxyAddress -ProxyUseDefaultCredentials

$response = $request.StatusCode
Write-Host "Status Code -- $response"
}
catch
{
$errormessage = $_.Exception.Message
$errorcode = $_.Exception.Response.StatusCode.Value__
}

IF ($response -eq '200')
{
IF ($errorcode -eq $null)
{
  Write-Host "url: ""$URLAddress"" is avalible. `nStatus Code: $response"

}
ELSE
{
  Write-Host "url: ""$URLAddress"" is avalible but porxy: ""$proxydev"" has an error, `nError Code: $errorcode `nError Message:`n$errormessage. `nStatus Code: $response"
}
}
ELSE
{
  Write-Host "url: ""$URLAddress"" is not avalible. `nStatus Code: $response `nError Code: $errorcode `nError Message:`n$errormessage"
}

$request.BaseResponse.Close()

But I'm experiencing a strange behavior with the above script, for some reason i will get a permanent error of:

The underlying connection was closed: An unexpected error occurred on a send.

Even though when I'm running the script locally on target server, the script is working without any problems.

Running an analysis using SSL Report, i can verify that ts01-b.cloudsink.net is using TLS version 1.2. so i don't need to bypass the SSL certificate check [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} which is something that i saw mentioned frequently in other Stack Overflow posts, like:

Unexpected error occurred running a simple unauthorized Rest query

Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send

It is worth mentioning that the problematic window server is used by all the other developers in the organization, which run their own PowerShell scripts frequently manually or schedules by using a monitoring agent named SCOM by Microsoft.

I'm struggling to understand the root cause of this problem, has anyone experienced this kind of issue?


问:
Avoiding anti-aliasing with round painting in react-konva
I am trying to create a app with Konva and react-konva where the user can freely draw anything he wants on the stage, but mainly to use the mouse as a pen or a erasor.

The user can only use two colors: red and green. Although, the user have to see the background. So the colors I am using are actually rgba(255,0,0,125) and rgba(0,255,0,125), so they can see the image in the Konva.Stage while they draw on it.

The free drawing region:

const Region = forwardRef(({ lines }, ref) => {
  const [stroke, setStroke] = useState(30);
  const line1Ref = useRef(null);
  const line2Ref = useRef(null);
  console.log(line1Ref?.current);
  return (
    <Layer ref={ref}>
      {lines.map((line, i) => (
        <>
          <Line
            ref={line1Ref}
            points={line.points}
            stroke="black"
            strokeWidth={stroke}
            lineCap="round"
            lineJoin="round"
            tension={0.5}
            globalCompositeOperation="destination-out"
          />
          <Line
            ref={line2Ref}
            points={line.points}
            stroke={line.color}
            strokeWidth={stroke}
            tension={0.5}
            lineCap="round"
            lineJoin="round"
          />
        </>
      ))}
    </Layer>
  );
});```
</div>
</div>
</p>
<p>The stage is drawn as follows</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Konva = (props) => {

const regionRef = useRef(null);
  const [drawing, setDrawing] = useState(false);
  const [lines, setLines] = useState([]);
  const [finish, setFinish] = useState(false);
  const [image, setImage] = useState(null);
  const [color, setColor] = useState('rgba(255,0,0,0.49)');
  const stageRef = useRef(null);

 useEffect(() => {
    if (props.url) {
      const { url } = props;
      const img = new Image();
      img.onload = () => {
        setImage(img);
        setFinish(true);
      };
      img.src = url;
    }
  }, [matchingFrame]);

const handleMouseDown = (e) => {
    setDrawing(true);
    const pos = e.target.getStage().getPointerPosition();
    setLines((prevLines) => {
      return [...prevLines, { color, points: [pos.x, pos.y] }];
    });
  };
  const handleMouseUp = () => {
    setDrawing(false);
  };

  const handleMouseMove = (e) => {
    if (!drawing) {
      return;
    }
    const stage = e.target.getStage();
    const point = stage.getPointerPosition();
    const lastLine = lines[lines.length - 1];
    // add point
    lastLine.points = lastLine.points.concat([point.x, point.y]);

    // replace last
    lines.splice(lines.length - 1, 1, lastLine);
    setLines(lines.concat());
  };

  if(!image) return null;

  return (<Stage
              ref={stageRef}
              width={image.width}
              height={image.height}
              onMouseDown={handleMouseDown}
              onMouseUp={handleMouseUp}
              onMouseMove={handleMouseMove}
              onMouseLeave={handleMouseUp}
            >
              <Layer ref={imgRef}>
                <KonvaImage image={image} />
              </Layer>

              <Region ref={regionRef} lines={lines} color={color} />
            </Stage>)
  }</code>```

After the drawing I convert the data to an encoded array mask. Althought, the joint points between the colors have different rgba besides the ones I desired due to the   anti-aliasing that make the pen looks curved. If I ignore this mix of colors, there will be pixels with no color when they should have, like in the image

Is there any way to avoid this colors interpolation? The idea I have now is to set this pixels into a nearest neighbor approach where I would fill them with the nearest color, red or green.

The code developed is based on the demos developed by Anton Lavrenov. Image labeling and Free drawing

Body:
I am trying to create a app with Konva and react-konva where the user can freely draw anything he wants on the stage, but mainly to use the mouse as a pen or a erasor.

The user can only use two colors: red and green. Although, the user have to see the background. So the colors I am using are actually rgba(255,0,0,125) and rgba(0,255,0,125), so they can see the image in the Konva.Stage while they draw on it.

The free drawing region:

const Region = forwardRef(({ lines }, ref) => {
  const [stroke, setStroke] = useState(30);
  const line1Ref = useRef(null);
  const line2Ref = useRef(null);
  console.log(line1Ref?.current);
  return (
    <Layer ref={ref}>
      {lines.map((line, i) => (
        <>
          <Line
            ref={line1Ref}
            points={line.points}
            stroke="black"
            strokeWidth={stroke}
            lineCap="round"
            lineJoin="round"
            tension={0.5}
            globalCompositeOperation="destination-out"
          />
          <Line
            ref={line2Ref}
            points={line.points}
            stroke={line.color}
            strokeWidth={stroke}
            tension={0.5}
            lineCap="round"
            lineJoin="round"
          />
        </>
      ))}
    </Layer>
  );
});

The stage is drawn as follows

const Konva = (props) => {

const regionRef = useRef(null);
  const [drawing, setDrawing] = useState(false);
  const [lines, setLines] = useState([]);
  const [finish, setFinish] = useState(false);
  const [image, setImage] = useState(null);
  const [color, setColor] = useState('rgba(255,0,0,0.49)');
  const stageRef = useRef(null);

 useEffect(() => {
    if (props.url) {
      const { url } = props;
      const img = new Image();
      img.onload = () => {
        setImage(img);
        setFinish(true);
      };
      img.src = url;
    }
  }, [matchingFrame]);

const handleMouseDown = (e) => {
    setDrawing(true);
    const pos = e.target.getStage().getPointerPosition();
    setLines((prevLines) => {
      return [...prevLines, { color, points: [pos.x, pos.y] }];
    });
  };
  const handleMouseUp = () => {
    setDrawing(false);
  };

  const handleMouseMove = (e) => {
    if (!drawing) {
      return;
    }
    const stage = e.target.getStage();
    const point = stage.getPointerPosition();
    const lastLine = lines[lines.length - 1];
    // add point
    lastLine.points = lastLine.points.concat([point.x, point.y]);

    // replace last
    lines.splice(lines.length - 1, 1, lastLine);
    setLines(lines.concat());
  };

  if(!image) return null;

  return (<Stage
              ref={stageRef}
              width={image.width}
              height={image.height}
              onMouseDown={handleMouseDown}
              onMouseUp={handleMouseUp}
              onMouseMove={handleMouseMove}
              onMouseLeave={handleMouseUp}
            >
              <Layer ref={imgRef}>
                <KonvaImage image={image} />
              </Layer>

              <Region ref={regionRef} lines={lines} color={color} />
            </Stage>)
  }

After the drawing I convert the data to an encoded array mask. Althought, the joint points between the colors have different rgba besides the ones I desired due to the   anti-aliasing that make the pen looks curved. If I ignore this mix of colors, there will be pixels with no color when they should have, like in the image

Is there any way to avoid this colors interpolation? The idea I have now is to set this pixels into a nearest neighbor approach where I would fill them with the nearest color, red or green.

The code developed is based on the demos developed by Anton Lavrenov. Image labeling and Free drawing


问:
How to use SDB when sda is full
I am a beginner to linux. but I should install a blockchain node on ubuntu server(4T SSD).
SDA6 is only 500G and SDB is 3.5T. so I have to use SDB if sda is full.

```<code>root@UK270-1G:~# df -h
Filesystem      Size  Used Avail Use% Mounted on
udev             32G     0   32G   0% /dev
tmpfs           6.3G  1.4M  6.3G   1% /run
/dev/sda6       437G  2.2G  413G   1% /
tmpfs            32G     0   32G   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs            32G     0   32G   0% /sys/fs/cgroup
/dev/sda5       1.9G   81M  1.8G   5% /boot
tmpfs           6.3G     0  6.3G   0% /run/user/0
root@UK270-1G:~#
</code>```

SDB is not mounted yet. but for my problem, I wanna know underlying principle and need detailed instruction since I am a beginner of linux.

Thanks in advance.

Title: How to use SDB when sda is full

Body:
I am a beginner to linux. but I should install a blockchain node on ubuntu server(4T SSD).
SDA6 is only 500G and SDB is 3.5T. so I have to use SDB if sda is full.

root@UK270-1G:~# df -h
Filesystem      Size  Used Avail Use% Mounted on
udev             32G     0   32G   0% /dev
tmpfs           6.3G  1.4M  6.3G   1% /run
/dev/sda6       437G  2.2G  413G   1% /
tmpfs            32G     0   32G   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs            32G     0   32G   0% /sys/fs/cgroup
/dev/sda5       1.9G   81M  1.8G   5% /boot
tmpfs           6.3G     0  6.3G   0% /run/user/0
root@UK270-1G:~#

SDB is not mounted yet. but for my problem, I wanna know underlying principle and need detailed instruction since I am a beginner of linux.

Thanks in advance.


问:
Prometheus access in Gitlab SaaS
Is it possible to access metrics created in a Gitlab CI pipeline (artifact: reports: metrics:)? They show up in the Merge request metrics report but I would like to use them from outside gitlab with Grafana.</p>

Title: Prometheus access in Gitlab SaaS


问:
not able to get instance of custom parent filter in floating filter
Following are the custom parent filter and floating filter which has dropdown for option selection.
On selecting an option, I'm getting the following error:

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

```<code>/* parent filter */

    import React, {
      forwardRef,
      useCallback,
      useEffect,
      useImperativeHandle,
      useState,
    } from 'react';
    import {
      FormControl,
      MenuItem,
      Select,
      TextField,
    } from '@material-ui/core';
    // import Autocomplete from '@material-ui/lab/Autocomplete';

    export default forwardRef((props, ref) => {
      const inputRef = useRef(null);
      const [filterState, setFilterState] = useState('');
      const allValues = props.filterParams.values;
      // expose AG Grid Filter Lifecycle callbacks
      useImperativeHandle(ref, () => ({
        isFilterActive() {
          return filterState;
        },

        doesFilterPass(params) {
          // const field = props.colDef.field;
          // return params.data[field] == filterState;

          return false;
        },

        getModel() {
          if (!filterState) {
            return undefined;
          }

          return {
            state: filterState,
          };
        },

        setModel(model) {

          if (model == null) {
            setFilterState('');
          } else {
            console.log('setmodel', model.state);
            setFilterState(model.state);
          }
        },
        setValue(value) {

          setFilterState(value);
        },
      }));

      useEffect(() => {
        props.filterChangedCallback();
      }, [filterState]);

      const handleChange = ev => {

        setFilterState(ev.target.value);
      };

      return (
        <div style={{ padding: '4px' }}>
          State = {filterState}
          <FormControl fullWidth>
            <Select
            ref={inputRef}
              labelId="filter-select"
              id="selectFilter"
              value={filterState}
              onChange={handleChange}
            >
              {allValues.map(el => (
                <MenuItem value={el.value}>{el.name}</MenuItem>
              ))}
            </Select>
          </FormControl>
        </div>
      );
    });

    /**** floating filter ****/
    import React, {
      forwardRef,
      useCallback,
      useEffect,
      useImperativeHandle,
      useRef,
      useState,
    } from 'react';

    import {
      FormControl,
      MenuItem,
      Select,
      TextField,
    } from '@material-ui/core';
    // import Autocomplete from '@material-ui/lab/Autocomplete';

    export default forwardRef((props, ref) => {
      const inputRef = useRef(null);
      const [value, setValue] = useState();

      const allValues = props.filterParams.values;

      useEffect(() => {
        console.log('Floating Filter Created');
        return () => console.log('Floating Filter Destroyed');
      }, []);

      useImperativeHandle(ref, () => ({
        onParentModelChanged(parentModel) {
          if (parentModel) {

            setValue(parentModel.state);
          } else {
            setValue();
          }
        },
      }));

      const handleChange = ev => {
        const { value } = ev.target;
        if (!value) {
          // Remove the filter
          props.parentFilterInstance(instance => {

            instance.setValue(null);
          });
          return;
        }

        props.parentFilterInstance(instance => {

          instance.setValue(value);
        });
      };

      return (
        <div style={{ padding: '4px' }}>
          <FormControl fullWidth>
            <Select
              ref={inputRef}
              labelId="filter-select"
              id="selectFilter"
              value={value}
              onChange={handleChange}
            >
              {allValues.map(el => (
                <MenuItem value={el.value}>{el.name}</MenuItem>
              ))}
            </Select>
          </FormControl>
        </div>
      );
    });
</code>```

Not able to capture the instance of parent and its breaking on selecting the dropdown option.

Body:
Following are the custom parent filter and floating filter which has dropdown for option selection.
On selecting an option, I'm getting the following error:

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

/* parent filter */

    import React, {
      forwardRef,
      useCallback,
      useEffect,
      useImperativeHandle,
      useState,
    } from 'react';
    import {
      FormControl,
      MenuItem,
      Select,
      TextField,
    } from '@material-ui/core';
    // import Autocomplete from '@material-ui/lab/Autocomplete';

    export default forwardRef((props, ref) => {
      const inputRef = useRef(null);
      const [filterState, setFilterState] = useState('');
      const allValues = props.filterParams.values;
      // expose AG Grid Filter Lifecycle callbacks
      useImperativeHandle(ref, () => ({
        isFilterActive() {
          return filterState;
        },

        doesFilterPass(params) {
          // const field = props.colDef.field;
          // return params.data[field] == filterState;

          return false;
        },

        getModel() {
          if (!filterState) {
            return undefined;
          }

          return {
            state: filterState,
          };
        },

        setModel(model) {

          if (model == null) {
            setFilterState('');
          } else {
            console.log('setmodel', model.state);
            setFilterState(model.state);
          }
        },
        setValue(value) {

          setFilterState(value);
        },
      }));

      useEffect(() => {
        props.filterChangedCallback();
      }, [filterState]);

      const handleChange = ev => {

        setFilterState(ev.target.value);
      };

      return (

          State = {filterState}
          <FormControl fullWidth>
            <Select
            ref={inputRef}
              labelId="filter-select"
              id="selectFilter"
              value={filterState}
              onChange={handleChange}
            >
              {allValues.map(el => (
                <MenuItem value={el.value}>{el.name}</MenuItem>
              ))}
            </Select>
          </FormControl>

      );
    });

    /**** floating filter ****/
    import React, {
      forwardRef,
      useCallback,
      useEffect,
      useImperativeHandle,
      useRef,
      useState,
    } from 'react';

    import {
      FormControl,
      MenuItem,
      Select,
      TextField,
    } from '@material-ui/core';
    // import Autocomplete from '@material-ui/lab/Autocomplete';

    export default forwardRef((props, ref) => {
      const inputRef = useRef(null);
      const [value, setValue] = useState();

      const allValues = props.filterParams.values;

      useEffect(() => {
        console.log('Floating Filter Created');
        return () => console.log('Floating Filter Destroyed');
      }, []);

      useImperativeHandle(ref, () => ({
        onParentModelChanged(parentModel) {
          if (parentModel) {

            setValue(parentModel.state);
          } else {
            setValue();
          }
        },
      }));

      const handleChange = ev => {
        const { value } = ev.target;
        if (!value) {
          // Remove the filter
          props.parentFilterInstance(instance => {

            instance.setValue(null);
          });
          return;
        }

        props.parentFilterInstance(instance => {

          instance.setValue(value);
        });
      };

      return (

          <FormControl fullWidth>
            <Select
              ref={inputRef}
              labelId="filter-select"
              id="selectFilter"
              value={value}
              onChange={handleChange}
            >
              {allValues.map(el => (
                <MenuItem value={el.value}>{el.name}</MenuItem>
              ))}
            </Select>
          </FormControl>

      );
    });

Not able to capture the instance of parent and its breaking on selecting the dropdown option.


问:
SQL Server Agent Job cannot kill a task on a machine
I have SSIS package which starts a task and then kills it via cmd. This works when executed directly from Visual Studio. However, task is not killed when SQL Server Agent executes a job with this package. Job has proxy with a user.

I created a separate CmdExec job with this proxy and taskkill command but it throws "Access denied" error. Proxy is the same as the user that started the task on that machine.

How to kill a process on a server machine?


问:
Why does closing socket used in a SslStream result in TCP RST instead of FIN
I have noticed that when using an SslStream, when I close the socket I get a TCP RST packet instead of a TCP FIN packet like I would if I closed the socket without the SslStream wrapping it.

For example

```<code>var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(IPAddres.Loopback, 1234);
socket.Send(new byte[] {0xc3, 0x45});
socket.Shutdown(Shutdown.Both);
</code>```

Results in the remote getting a TCP FIN packet, whereas this

```<code>var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(IPAddres.Loopback, 1234);
var ns = new NetworkStream(socket, false); // owns socket = false
var ssl = new SslStream(ns, true); // leaveInnerStreamOpen = true
ssl.AuthenticateAsClient("foobar.com");
ssl.Write(new byte[] {0xc3, 0x45});
socket.Shutdown(Shutdown.Both);
</code>```

The remote receive a TCP RST packet. I would have expected a TCP FIN packet here just as if I had not used the SslStream at all. I have specified that the NetworkStream does not own the socket. I have told the SslStream to not close the inner stream.

I am using wireshark so I know for sure what packets are coming through.

UPDATE 1: If I use socket.Shutdown(Shutdown.Send) then I get a TCP FIN packet. But I can use socket.Shutdown(Shutdown.Both) when using a normal socket to get a TCP FIN packet.

UPDATE 2: I noticed that if I swapped my AuthAsServer and AuthAsClient around but did everything else the same, then I get the desired TCP FIN packet.

So I guess the question is why does AuthenticateAsClient produce TCP RST when closing the socket.

Body:
I have noticed that when using an SslStream, when I close the socket I get a TCP RST packet instead of a TCP FIN packet like I would if I closed the socket without the SslStream wrapping it.

For example

var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(IPAddres.Loopback, 1234);
socket.Send(new byte[] {0xc3, 0x45});
socket.Shutdown(Shutdown.Both);

Results in the remote getting a TCP FIN packet, whereas this

var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(IPAddres.Loopback, 1234);
var ns = new NetworkStream(socket, false); // owns socket = false
var ssl = new SslStream(ns, true); // leaveInnerStreamOpen = true
ssl.AuthenticateAsClient("foobar.com");
ssl.Write(new byte[] {0xc3, 0x45});
socket.Shutdown(Shutdown.Both);

The remote receive a TCP RST packet. I would have expected a TCP FIN packet here just as if I had not used the SslStream at all. I have specified that the NetworkStream does not own the socket. I have told the SslStream to not close the inner stream.

I am using wireshark so I know for sure what packets are coming through.

UPDATE 1: If I use socket.Shutdown(Shutdown.Send) then I get a TCP FIN packet. But I can use socket.Shutdown(Shutdown.Both) when using a normal socket to get a TCP FIN packet.

UPDATE 2: I noticed that if I swapped my AuthAsServer and AuthAsClient around but did everything else the same, then I get the desired TCP FIN packet.

So I guess the question is why does AuthenticateAsClient produce TCP RST when closing the socket.


问:
how do I customize my widgets or buttons borders and other advanced properties?
I'm a bit new to winform and I dont know how to change stuff like widget borders or make smooth hover animations for buttons or other widgets, in css we do it like transition: 1s; but in C# I cannot find any property called transition, I'd appreciate if someone who knows what im talking about helps, thank you.

example: in this image here you can see that i've set my button's background color to purple but the border color hasn't changed.


问:
How can I run RSpec tests on Gitlab CI using structure.sql for creating the DB?
I have a Rails project and I want to run the RSpec tests on every commit via Gitlab CI. Since the Docker container of Gitlab CI uses 'postgres' as host and not 'localhost' I configured this in database.yml. If I use the schema.rb everything works fine. It doesn't work anymore if I set 'config.active_record.schema_format = :sql' in application.rb since we use structure.sql for our project and not schema.rb.

The following error message appears:

```<code>$ bundle exec rake db:reset RAILS_ENV=test

Dropped database 'my_project_test'
Created database 'my_project_test'
rake aborted!
failed to execute:
psql -v ON_ERROR_STOP=1 -q -X -f /builds/my_project/db/structure.sql my_project_test
Please check the output above for any errors and make sure that `psql` is installed in your PATH and has proper permissions.
</code>```

My database.yml looks like this:

```<code>default: &default
  username: admin
  password: 1234
  adapter: postgresql
  encoding: unicode
  pool: 5

development:
  <<: *default
  database: my_project_development

test:
  <<: *default
  database: my_project_test
  host: postgres
  port: 5432
</code>```

And this is the .gitlab-ci.yml:

```<code>stages:
    - build
    - test

build-job:
    stage: build
    script:
        - echo "Hello"
test-job:
    stage: test
    image: ruby:2.6.3
    # Cache gems in between builds
    cache:
        key: ${CI_COMMIT_REF_SLUG}
        paths:
            - vendor/ruby
    services:
        - postgres:15.1
    variables:
        POSTGRES_DB: my_project_test
        POSTGRES_USER: admin
        POSTGRES_PASSWORD: 1234
        POSTGRES_HOST_AUTH_METHOD: trust
        RAILS_ENV: test
        BUNDLE_PATH: vendor/bundle
    before_script:
        # Bundler is not installed with the image
        - gem install bundler -v 1.17.2
        # Install dependencies into ./vendor/ruby
        - bundle install -j $(nproc) --path vendor
    script:
        - bundle exec rake db:reset RAILS_ENV=test
        - bundle exec rspec
</code>```

Body:
I have a Rails project and I want to run the RSpec tests on every commit via Gitlab CI. Since the Docker container of Gitlab CI uses 'postgres' as host and not 'localhost' I configured this in database.yml. If I use the schema.rb everything works fine. It doesn't work anymore if I set 'config.active_record.schema_format = :sql' in application.rb since we use structure.sql for our project and not schema.rb.

The following error message appears:

$ bundle exec rake db:reset RAILS_ENV=test

Dropped database 'my_project_test'
Created database 'my_project_test'
rake aborted!
failed to execute:
psql -v ON_ERROR_STOP=1 -q -X -f /builds/my_project/db/structure.sql my_project_test
Please check the output above for any errors and make sure that `psql` is installed in your PATH and has proper permissions.

My database.yml looks like this:

default: &default
  username: admin
  password: 1234
  adapter: postgresql
  encoding: unicode
  pool: 5

development:
  <<: *default
  database: my_project_development

test:
  <<: *default
  database: my_project_test
  host: postgres
  port: 5432

And this is the .gitlab-ci.yml:

stages:
    - build
    - test

build-job:
    stage: build
    script:
        - echo "Hello"
test-job:
    stage: test
    image: ruby:2.6.3
    # Cache gems in between builds
    cache:
        key: ${CI_COMMIT_REF_SLUG}
        paths:
            - vendor/ruby
    services:
        - postgres:15.1
    variables:
        POSTGRES_DB: my_project_test
        POSTGRES_USER: admin
        POSTGRES_PASSWORD: 1234
        POSTGRES_HOST_AUTH_METHOD: trust
        RAILS_ENV: test
        BUNDLE_PATH: vendor/bundle
    before_script:
        # Bundler is not installed with the image
        - gem install bundler -v 1.17.2
        # Install dependencies into ./vendor/ruby
        - bundle install -j $(nproc) --path vendor
    script:
        - bundle exec rake db:reset RAILS_ENV=test
        - bundle exec rspec


问:
Playwright don't work proper after update to Version 1.29
I write e2e-Tests for a Web-Application with playwright. Now I have made a update to version 1.29.2.

Have anyone the same problem and maybe a solution?

The marked Register should be on the top of the Site.


问:
how to run print JavaScript function when sweet alert script is running
```<code>var TotalValue = parseFloat($('#totalValue').text().replace(/,/g, "").replace("₤",""));

          if(TotalValue > qtynum){
            swal("خطأ","لا يمكن إدخال قيمة أصغر من المبلغ المطلوب","error");
          }else{
            change = parseInt(value,10) - parseFloat(TotalValue);
            $.ajax({
              url:"insert_sales.php",
              method:"POST",
              data:{totalvalue:TotalValue, product:product, price:price, user:user, customer:customer, quantity:quantity, discount:discount},
              success: function(data){

                if( data == "success"){
                  swal({
                    title: "الباقي " + accounting.formatMoney(change,{symbol:"₤",format: "%s %v"}),
                    icon: "success",
                    buttons: "Okay",
                  })
                  .then((okay)=>{
                    if(okay){
                      window.location.href='main.php';
                    }
                  })
                }else{
                  window.location.href='main.php?'+data;
                }

              }
            });
          }
</code>```

print function :

```<code>function PrintDiv() {
            var contents = document.getElementById("what_i_want_to_print").innerHTML;
            var frame1 = document.createElement('iframe');
            frame1.name = "frame1";
            frame1.style.position = "absolute";
            frame1.style.top = "-1000000px";
            document.body.appendChild(frame1);
            var frameDoc = (frame1.contentWindow) ? frame1.contentWindow : (frame1.contentDocument.document) ? frame1.contentDocument.document : frame1.contentDocument;
            frameDoc.document.open();
            frameDoc.document.write('<html><head><title>"طلب جديد"</title>');
            frameDoc.document.write('<link rel="stylesheet" href="css/print.css" media="print"/>\n')
            frameDoc.document.write('</head><body>');
            frameDoc.document.write(contents);
            frameDoc.document.write('</body></html>');
            frameDoc.document.close();
            setTimeout(function () {
                window.frames["frame1"].focus();
                window.frames["frame1"].print();
                document.body.removeChild(frame1);
            }, 500);
            return false;
        }
</code>```

I want to run print function when click (Okay) , i tried to add another button but didnt work , i try add print function after IF(okay) condition but still not work , then i want to print directly without open a new window print , can it be done ??

Body:
var TotalValue = parseFloat($('#totalValue').text().replace(/,/g, "").replace("₤",""));

          if(TotalValue > qtynum){
            swal("خطأ","لا يمكن إدخال قيمة أصغر من المبلغ المطلوب","error");
          }else{
            change = parseInt(value,10) - parseFloat(TotalValue);
            $.ajax({
              url:"insert_sales.php",
              method:"POST",
              data:{totalvalue:TotalValue, product:product, price:price, user:user, customer:customer, quantity:quantity, discount:discount},
              success: function(data){

                if( data == "success"){
                  swal({
                    title: "الباقي " + accounting.formatMoney(change,{symbol:"₤",format: "%s %v"}),
                    icon: "success",
                    buttons: "Okay",
                  })
                  .then((okay)=>{
                    if(okay){
                      window.location.href='main.php';
                    }
                  })
                }else{
                  window.location.href='main.php?'+data;
                }

              }
            });
          }

print function :

function PrintDiv() {
            var contents = document.getElementById("what_i_want_to_print").innerHTML;
            var frame1 = document.createElement('iframe');
            frame1.name = "frame1";
            frame1.style.position = "absolute";
            frame1.style.top = "-1000000px";
            document.body.appendChild(frame1);
            var frameDoc = (frame1.contentWindow) ? frame1.contentWindow : (frame1.contentDocument.document) ? frame1.contentDocument.document : frame1.contentDocument;
            frameDoc.document.open();
            frameDoc.document.write('<title>"طلب جديد"</title>');
            frameDoc.document.write('<link rel="stylesheet" href="css/print.css" media="print"/>\n')
            frameDoc.document.write('');
            frameDoc.document.write(contents);
            frameDoc.document.write('');
            frameDoc.document.close();
            setTimeout(function () {
                window.frames["frame1"].focus();
                window.frames["frame1"].print();
                document.body.removeChild(frame1);
            }, 500);
            return false;
        }

I want to run print function when click (Okay) , i tried to add another button but didnt work , i try add print function after IF(okay) condition but still not work , then i want to print directly without open a new window print , can it be done ??


问:
UINavigationController with UIHostingController correct way to navigate between screens
I have an existing app build with UIKit, Storyboards and existing UINavigationController. I want to add SwiftUI screens using UIHostingController, from this screen I want to navigate to another one. I embedded my Views in NavigationView and learned that now there are two navigation bar titles. I removed the NavigationView and just used navigationLink without it. I found out I can set navigation title on the hostingVC before I present it and with navigationTitle modifier, but they are changing the same thing.

How does this work and what should I use for navigation inside UIHostingController, should I build some custom UIKit solution for navigation?


问:
libclntsh.so.12.1: undefined symbol: ons_init_wconfig_ctx
i have a python script which was running fine.But now i am getting the below error:

```<code> symbol lookup error: /oracle-client/12.1.0.1/x86_64-linux-2.6-libc6/libclntsh.so.12.1: undefined symbol: ons_init_wconfig_ctx
</code>```

Can someone help with what is required to overcome this.
Thanks.

Body:
i have a python script which was running fine.But now i am getting the below error:

 symbol lookup error: /oracle-client/12.1.0.1/x86_64-linux-2.6-libc6/libclntsh.so.12.1: undefined symbol: ons_init_wconfig_ctx

Can someone help with what is required to overcome this.
Thanks.


问:
How to extract lists whitin lists in Power Query?
I'm facing a problem when following this explanation: Power Query - How to extract values in the list of the list?

Basically, I'm into the same situation of the user, but I'm getting an error, just like the image attached.(https://i.stack.imgur.com/6F61G.jpg)

I don't really understand why I'm getting an error, could someone help?

Recreating the steps in the tutorial


问:
Filevault enable with -defer option not working on Ventura
I have been using the following script for a while on Mac to enable FileVault remotely. It is launched via an RMM and enables Filevault when a user logs in due to the authentication and then generates the key and puts it in the defined plist file where I can read it later if necessary.

It has always worked for me but it doesn't on Mac OS Ventura 13. It enables the Filevault on user log-in but doesn't seem to create the .plist file.

fdesetup enable -defer /MykeyandInfo.plist

Has anything changed in the OS that this command isn't working anymore?


问:
PHP Server Code to Process an Image Upload
I would like to write some code in PHP to process the server side of an image stream being uploaded via a socket connection. I already have the client side code which is written in java

```<code>    Socket soc;
    BufferedImage img = null;
    soc = new Socket("127.0.0.1", 4000);
    try
    {
        img = ImageIO.read(new File("blake-rig.jpg"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, "jpg", baos);
        baos.flush();
        byte[] bytes = baos.toByteArray();
        baos.close();
        OutputStream out = soc.getOutputStream();
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeInt(bytes.length);
        dos.write(bytes, 0, bytes.length);
        dos.close();
        out.close();
    }
    catch (Exception ex)
    {
        System.err.println("Exception " + ex);
        soc.close();
    }
    soc.close();
}
</code>```

I have found this [server code] to process the image, but it is also written in java rather than PHP:

```<code>  class Server {
  public static void main(String  args[]) throws Exception{
  ServerSocket server=null;
  Socket socket;
  server = new ServerSocket(4000);
  System.out.println("Server Waiting for image");

  socket = server.accept();
  System.out.println("Client connected.");

  InputStream in = socket.getInputStream();
  DataInputStream dis = new DataInputStream(in);

  int len = dis.readInt();
  System.out.println("Image Size: " + len/1024 + "KB");

  byte[] data = new byte[len];
  dis.readFully(data);
  dis.close();
  in.close();

  InputStream ian = new ByteArrayInputStream(data);
  BufferedImage bImage = ImageIO.read(ian);
  }
  }
</code>```

The problem I am having is that I am unable to find any code examples or explanations which would help me write the equivalent code to read the incoming image stream in PHP. I would really appreciate it if anyone can point me in the right direction.

Many thanks

Body:
I would like to write some code in PHP to process the server side of an image stream being uploaded via a socket connection. I already have the client side code which is written in java

    Socket soc;
    BufferedImage img = null;
    soc = new Socket("127.0.0.1", 4000);
    try
    {
        img = ImageIO.read(new File("blake-rig.jpg"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, "jpg", baos);
        baos.flush();
        byte[] bytes = baos.toByteArray();
        baos.close();
        OutputStream out = soc.getOutputStream();
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeInt(bytes.length);
        dos.write(bytes, 0, bytes.length);
        dos.close();
        out.close();
    }
    catch (Exception ex)
    {
        System.err.println("Exception " + ex);
        soc.close();
    }
    soc.close();
}

I have found this [server code] to process the image, but it is also written in java rather than PHP:

  class Server {
  public static void main(String  args[]) throws Exception{
  ServerSocket server=null;
  Socket socket;
  server = new ServerSocket(4000);
  System.out.println("Server Waiting for image");

  socket = server.accept();
  System.out.println("Client connected.");

  InputStream in = socket.getInputStream();
  DataInputStream dis = new DataInputStream(in);

  int len = dis.readInt();
  System.out.println("Image Size: " + len/1024 + "KB");

  byte[] data = new byte[len];
  dis.readFully(data);
  dis.close();
  in.close();

  InputStream ian = new ByteArrayInputStream(data);
  BufferedImage bImage = ImageIO.read(ian);
  }
  }

The problem I am having is that I am unable to find any code examples or explanations which would help me write the equivalent code to read the incoming image stream in PHP. I would really appreciate it if anyone can point me in the right direction.

Many thanks


问:
Retain layout on orientation change and keep same position for elements
Trying to create a camera app that keeps the capture button at the bottom but does support orientation changes so that the gestures, status bar and notifications will be correctly aligned.

Tried to create a custom view that onMeasure changes all the links of the constraint view but this makes the view sometimes jitter and morph the camera stream.