问:
How can I get my API to generate my desired multi-tiered JSON scaffolding?
This is what I want my JSON object to look like. Note: the JSON below includes an 'artworks' node, but I am not actually able to generate this. This is the problem that I am trying to solve.

```<code>{
    "idArtist": 2,
    "artistName": "Alice Waters",
    "indexArtworks": [
        {
            "id": 2,
            "idArtist": 2,
            "idArtwork": 1,
            "artworks": [
                {
                    "idArtwork": 1,
                    "artworkTitle": "The Collaborative Artwork",
                }
            ]
        }
    ]
}
</code>```

Pasted below is a diagram of my table structure. The blue arrow represents an existing FK. The Orange arrow represents a nonexistant FK that would be a circular reference. Based on my current knowledge of how the .NET Core Web API JSON scaffolding is generated, in order to create a JSON sub-sub-node using the _context.<Object>.Include().ThenInclude() API, I would need to define the orange-arrow FK. But this would introduce a circular reference in the DB, and my attempt to create this FK resulted in an error.

This is my table structure, including FKs:

```<code>CREATE TABLE [dbo].[Artists](
    [ID_Artist] [int] NOT NULL,
    [Artist_Name] [nvarchar](255) NULL,
 CONSTRAINT [PK_Artists] PRIMARY KEY CLUSTERED
(
    [ID_Artist] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

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

CREATE TABLE [dbo].[Artworks](
    [ID_Artwork] [int] NOT NULL,
    [Artwork_Title] [nvarchar](255) NULL
 CONSTRAINT [PK_Artworks] PRIMARY KEY CLUSTERED
(
    [ID_Artwork] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

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

CREATE TABLE [dbo].[Index_Artworks](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ID_Artwork] [int] NOT NULL,
    [ID_Artist] [int] NOT NULL
 CONSTRAINT [PK_Index_Artworks] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Index_Artworks]  WITH CHECK ADD  CONSTRAINT [FK__Index_Art__ID_Ar__1C1305F7] FOREIGN KEY([ID_Artwork])
REFERENCES [dbo].[Artworks] ([ID_Artwork])
GO

ALTER TABLE [dbo].[Index_Artworks] CHECK CONSTRAINT [FK__Index_Art__ID_Ar__1C1305F7]
GO

ALTER TABLE [dbo].[Index_Artworks]  WITH CHECK ADD  CONSTRAINT [FK__Index_Art__ID_Ar__1D072A30] FOREIGN KEY([ID_Artist])
REFERENCES [dbo].[Artists] ([ID_Artist])
GO

ALTER TABLE [dbo].[Index_Artworks] CHECK CONSTRAINT [FK__Index_Art__ID_Ar__1D072A30]
GO
</code>```

This is my Artist object in the Web API.

```<code>    public partial class Artists
    {
        public Artists()
        {
            IndexArtworks = new HashSet<IndexArtworks>();
        }

        public int Id { get; set; }
        public string ArtistName { get; set; }

        public virtual ICollection<IndexArtworks> IndexArtworks { get; set; }
    }
</code>```

This is where I am issuing the HttpGet in the Web API. I have pointed out the invalid line below. I realize that this is because the Artist object does not have the orange FK.

```<code>        // GET: api/Artists/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Artists>> GetArtists(int id)
        {
            var artists = await _context.Artists
                .Include(i => i.IndexArtworks)
                    .ThenInclude(i => i.Artworks) // <----------- this is not valid.
                .Where(i => i.Id == id)
                .FirstOrDefaultAsync();

            if (artists == null)
            {
                return NotFound();
            }

            return artists;
        }
</code>```

My question: What do I need to change in the the API request, the Artist object in the API, or the tables and their relationships in order to include the "artworks" sub-sub node in the JSON?

Edits -----------------------------------------

@Guru Stron:
Not sure if I understand your suggestion - please correct me if I'm wrong. The FK between Index_Artworks and Artworks points from Index_Artworks to Artworks. I would need to create an FK that points in the opposite direction, but the DB won't allow it (and it's a circular ref, so it's bad design).

In case your suggestion does not involve creating the orange-arrow FK, I made the following update to my IndexArtworks object in the API layer: I added a HashSet reference to Artworks and added the virtual ICollection<Artworks>. When I uncommented the .ThenInclude(i => i.Artworks) in my ArtistController and ran the API, it gave me the following error: SqlException: Invalid column name 'IndexArtworksId'. Invalid column name 'IndexArtworksId'. I don't know what this is about, because I searched the solution for IndexArtworksId and could not find it.

```<code>public partial class IndexArtworks
    {
        public IndexArtworks()
        {
            Artworks = new HashSet<Artworks>();
        }

        public int Id { get; set; }
        public int IdArtwork { get; set; }
        public int IdArtist { get; set; }
        public bool AVisibleYn { get; set; }
        public string AVisibleIdAdmin { get; set; }

        public virtual Artists IdArtistNavigation { get; set; }
        public virtual Artworks IdArtworkNavigation { get; set; }
        public virtual ICollection<Artworks> Artworks { get; set; }
    }
</code>```

答:
You don't need the orange relation to use ThenInclude. You already have FK from IndexArtworks to Artworks so this should be fine:

```<code>class IndexArtworks
{
    public int ID { get; set; }
    public int ID_Artist { get; set; }
    public int ID_Artwork { get; set; }
    [ForeignKey("ID_Artist")]
    public virtual Artists Artist { get; set; }
    [ForeignKey("ID_Artwork")]
    public virtual Artworks Artwork { get; set; }
}
</code>```

And query:

```<code> var artists = await _context.Artists
            .Include(i => i.IndexArtworks)
                .ThenInclude(i => i.Artwork)
            .Where(i => i.Id == id)
            .FirstOrDefaultAsync();
</code>```

UPD

With your naming conventions this should look like:

```<code>public partial class IndexArtworks
{
    public int Id { get; set; }
    public int IdArtwork { get; set; }
    public int IdArtist { get; set; }
    public bool AVisibleYn { get; set; }
    public string AVisibleIdAdmin { get; set; }

    public virtual Artists IdArtistNavigation { get; set; }
    public virtual Artworks IdArtworkNavigation { get; set; }
}
</code>```

And query:

```<code> var artists = await _context.Artists
            .Include(i => i.IndexArtworks)
                .ThenInclude(i => i.IdArtworkNavigation)
            .Where(i => i.Id == id)
            .FirstOrDefaultAsync();
</code>```

Body:
This is what I want my JSON object to look like. Note: the JSON below includes an 'artworks' node, but I am not actually able to generate this. This is the problem that I am trying to solve.

{
    "idArtist": 2,
    "artistName": "Alice Waters",
    "indexArtworks": [
        {
            "id": 2,
            "idArtist": 2,
            "idArtwork": 1,
            "artworks": [
                {
                    "idArtwork": 1,
                    "artworkTitle": "The Collaborative Artwork",
                }
            ]
        }
    ]
}

Pasted below is a diagram of my table structure. The blue arrow represents an existing FK. The Orange arrow represents a nonexistant FK that would be a circular reference. Based on my current knowledge of how the .NET Core Web API JSON scaffolding is generated, in order to create a JSON sub-sub-node using the _context.<Object>.Include().ThenInclude() API, I would need to define the orange-arrow FK. But this would introduce a circular reference in the DB, and my attempt to create this FK resulted in an error.

This is my table structure, including FKs:

CREATE TABLE [dbo].[Artists](
    [ID_Artist] [int] NOT NULL,
    [Artist_Name] [nvarchar](255) NULL,
 CONSTRAINT [PK_Artists] PRIMARY KEY CLUSTERED
(
    [ID_Artist] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

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

CREATE TABLE [dbo].[Artworks](
    [ID_Artwork] [int] NOT NULL,
    [Artwork_Title] [nvarchar](255) NULL
 CONSTRAINT [PK_Artworks] PRIMARY KEY CLUSTERED
(
    [ID_Artwork] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

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

CREATE TABLE [dbo].[Index_Artworks](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ID_Artwork] [int] NOT NULL,
    [ID_Artist] [int] NOT NULL
 CONSTRAINT [PK_Index_Artworks] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Index_Artworks]  WITH CHECK ADD  CONSTRAINT [FK__Index_Art__ID_Ar__1C1305F7] FOREIGN KEY([ID_Artwork])
REFERENCES [dbo].[Artworks] ([ID_Artwork])
GO

ALTER TABLE [dbo].[Index_Artworks] CHECK CONSTRAINT [FK__Index_Art__ID_Ar__1C1305F7]
GO

ALTER TABLE [dbo].[Index_Artworks]  WITH CHECK ADD  CONSTRAINT [FK__Index_Art__ID_Ar__1D072A30] FOREIGN KEY([ID_Artist])
REFERENCES [dbo].[Artists] ([ID_Artist])
GO

ALTER TABLE [dbo].[Index_Artworks] CHECK CONSTRAINT [FK__Index_Art__ID_Ar__1D072A30]
GO

This is my Artist object in the Web API.

    public partial class Artists
    {
        public Artists()
        {
            IndexArtworks = new HashSet<IndexArtworks>();
        }

        public int Id { get; set; }
        public string ArtistName { get; set; }

        public virtual ICollection<IndexArtworks> IndexArtworks { get; set; }
    }

This is where I am issuing the HttpGet in the Web API. I have pointed out the invalid line below. I realize that this is because the Artist object does not have the orange FK.

        // GET: api/Artists/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Artists>> GetArtists(int id)
        {
            var artists = await _context.Artists
                .Include(i => i.IndexArtworks)
                    .ThenInclude(i => i.Artworks) // <----------- this is not valid.
                .Where(i => i.Id == id)
                .FirstOrDefaultAsync();

            if (artists == null)
            {
                return NotFound();
            }

            return artists;
        }

My question: What do I need to change in the the API request, the Artist object in the API, or the tables and their relationships in order to include the "artworks" sub-sub node in the JSON?

Edits -----------------------------------------

@Guru Stron:
Not sure if I understand your suggestion - please correct me if I'm wrong. The FK between Index_Artworks and Artworks points from Index_Artworks to Artworks. I would need to create an FK that points in the opposite direction, but the DB won't allow it (and it's a circular ref, so it's bad design).

In case your suggestion does not involve creating the orange-arrow FK, I made the following update to my IndexArtworks object in the API layer: I added a HashSet reference to Artworks and added the virtual ICollection<Artworks>. When I uncommented the .ThenInclude(i => i.Artworks) in my ArtistController and ran the API, it gave me the following error: SqlException: Invalid column name 'IndexArtworksId'. Invalid column name 'IndexArtworksId'. I don't know what this is about, because I searched the solution for IndexArtworksId and could not find it.

public partial class IndexArtworks
    {
        public IndexArtworks()
        {
            Artworks = new HashSet<Artworks>();
        }

        public int Id { get; set; }
        public int IdArtwork { get; set; }
        public int IdArtist { get; set; }
        public bool AVisibleYn { get; set; }
        public string AVisibleIdAdmin { get; set; }

        public virtual Artists IdArtistNavigation { get; set; }
        public virtual Artworks IdArtworkNavigation { get; set; }
        public virtual ICollection<Artworks> Artworks { get; set; }
    }

Body:
You don't need the orange relation to use ThenInclude. You already have FK from IndexArtworks to Artworks so this should be fine:

class IndexArtworks
{
    public int ID { get; set; }
    public int ID_Artist { get; set; }
    public int ID_Artwork { get; set; }
    [ForeignKey("ID_Artist")]
    public virtual Artists Artist { get; set; }
    [ForeignKey("ID_Artwork")]
    public virtual Artworks Artwork { get; set; }
}

And query:

 var artists = await _context.Artists
            .Include(i => i.IndexArtworks)
                .ThenInclude(i => i.Artwork)
            .Where(i => i.Id == id)
            .FirstOrDefaultAsync();

UPD

With your naming conventions this should look like:

public partial class IndexArtworks
{
    public int Id { get; set; }
    public int IdArtwork { get; set; }
    public int IdArtist { get; set; }
    public bool AVisibleYn { get; set; }
    public string AVisibleIdAdmin { get; set; }

    public virtual Artists IdArtistNavigation { get; set; }
    public virtual Artworks IdArtworkNavigation { get; set; }
}

And query:

 var artists = await _context.Artists
            .Include(i => i.IndexArtworks)
                .ThenInclude(i => i.IdArtworkNavigation)
            .Where(i => i.Id == id)
            .FirstOrDefaultAsync();


来源: stackexchange

问:
Rust need help refactoring excessive functions
(i should mention im pretty new to rust)

hi! im building a 2d particle simulation game using a Vec to hold structs with the info on each particle. right now i need to write out a separate function every time i want to check if an element is touching something with a certain property. basically it searches around the particle in a circle by calculating the index of that position then compares that structs property to the target property like so:

```<code>//check around particle for corrodable particles
pub fn check_touch_corrode(screen: &mut Vec<Particle>, x_pos: usize) -> usize {
    if screen[calc::ul(x_pos)].corrode {return calc::ul(x_pos)}     //if particle can corrode return particle
    if screen[calc::u(x_pos)].corrode {return calc::u(x_pos)}
    if screen[calc::ur(x_pos)].corrode {return calc::ur(x_pos)}
    if screen[calc::l(x_pos)].corrode {return calc::l(x_pos)}
    if screen[calc::r(x_pos)].corrode {return calc::r(x_pos)}
    if screen[calc::dl(x_pos)].corrode {return calc::dl(x_pos)}
    if screen[calc::d(x_pos)].corrode {return calc::d(x_pos)}
    if screen[calc::dr(x_pos)].corrode {return calc::dr(x_pos)}
    x_pos                                                           //else return own position
}

//check around particle for flammable particle
pub fn check_touch_flammable(screen: &mut Vec<Particle>, x_pos: usize) -> usize {
    if screen[calc::ul(x_pos)].flammable {return calc::ul(x_pos)}   //if particle flammable return particle
    if screen[calc::u(x_pos)].flammable {return calc::u(x_pos)}
    if screen[calc::ur(x_pos)].flammable {return calc::ur(x_pos)}
    if screen[calc::l(x_pos)].flammable {return calc::l(x_pos)}
    if screen[calc::r(x_pos)].flammable {return calc::r(x_pos)}
    if screen[calc::dl(x_pos)].flammable {return calc::dl(x_pos)}
    if screen[calc::d(x_pos)].flammable {return calc::d(x_pos)}
    if screen[calc::dr(x_pos)].flammable {return calc::dr(x_pos)}
    x_pos                                                           //else return own position
}
</code>```

this isnt really scalable considering im planning on having hundreds of elements with all kinds of different properties and interactions. im really wondering if there is any way to reduce this down to one function. ive been messing around with it on my own for a while now and havent been able to make any progress. the issue im running into is that the comparison needs to be calculated in the function and cant be passed in as far as i can tell. is there any way to fix this? like make it so i pass something that says which field of the struct i want to compare after it calculates that the structs index?

答:
I managed to find a solution!

```<code>pub fn check_touch(screen: &mut Vec<Particle>, x_pos: usize, criteria: impl Fn(Particle) -> bool,) -> usize {
    if criteria(screen[calc::ul(x_pos)]) {return calc::ul(x_pos)}
    //do this for every direction
}
</code>```

then call it like

```<code>check_touch(screen, x_pos, |p| p.corrode)
</code>```

credit to r/Erelde on reddit for giving me advice

ContentLicense: CC BY-SA 4.0

Body:
(i should mention im pretty new to rust)

hi! im building a 2d particle simulation game using a Vec to hold structs with the info on each particle. right now i need to write out a separate function every time i want to check if an element is touching something with a certain property. basically it searches around the particle in a circle by calculating the index of that position then compares that structs property to the target property like so:

//check around particle for corrodable particles
pub fn check_touch_corrode(screen: &mut Vec<Particle>, x_pos: usize) -> usize {
    if screen[calc::ul(x_pos)].corrode {return calc::ul(x_pos)}     //if particle can corrode return particle
    if screen[calc::u(x_pos)].corrode {return calc::u(x_pos)}
    if screen[calc::ur(x_pos)].corrode {return calc::ur(x_pos)}
    if screen[calc::l(x_pos)].corrode {return calc::l(x_pos)}
    if screen[calc::r(x_pos)].corrode {return calc::r(x_pos)}
    if screen[calc::dl(x_pos)].corrode {return calc::dl(x_pos)}
    if screen[calc::d(x_pos)].corrode {return calc::d(x_pos)}
    if screen[calc::dr(x_pos)].corrode {return calc::dr(x_pos)}
    x_pos                                                           //else return own position
}

//check around particle for flammable particle
pub fn check_touch_flammable(screen: &mut Vec<Particle>, x_pos: usize) -> usize {
    if screen[calc::ul(x_pos)].flammable {return calc::ul(x_pos)}   //if particle flammable return particle
    if screen[calc::u(x_pos)].flammable {return calc::u(x_pos)}
    if screen[calc::ur(x_pos)].flammable {return calc::ur(x_pos)}
    if screen[calc::l(x_pos)].flammable {return calc::l(x_pos)}
    if screen[calc::r(x_pos)].flammable {return calc::r(x_pos)}
    if screen[calc::dl(x_pos)].flammable {return calc::dl(x_pos)}
    if screen[calc::d(x_pos)].flammable {return calc::d(x_pos)}
    if screen[calc::dr(x_pos)].flammable {return calc::dr(x_pos)}
    x_pos                                                           //else return own position
}

this isnt really scalable considering im planning on having hundreds of elements with all kinds of different properties and interactions. im really wondering if there is any way to reduce this down to one function. ive been messing around with it on my own for a while now and havent been able to make any progress. the issue im running into is that the comparison needs to be calculated in the function and cant be passed in as far as i can tell. is there any way to fix this? like make it so i pass something that says which field of the struct i want to compare after it calculates that the structs index?

Body:
I managed to find a solution!

pub fn check_touch(screen: &mut Vec<Particle>, x_pos: usize, criteria: impl Fn(Particle) -> bool,) -> usize {
    if criteria(screen[calc::ul(x_pos)]) {return calc::ul(x_pos)}
    //do this for every direction
}

then call it like

check_touch(screen, x_pos, |p| p.corrode)

credit to r/Erelde on reddit for giving me advice


问:
What does CG_INLINE do?
I was poking around the definitions for things like CGPoint for hints on how to create my own functions but I don't know the purpose of CG_INLINE. What is happening behind the scenes here?

```<code>CG_INLINE CGPoint
CGPointMake(CGFloat x, CGFloat y)
{
  CGPoint p; p.x = x; p.y = y; return p;
}

CG_INLINE CGSize
CGSizeMake(CGFloat width, CGFloat height)
{
  CGSize size; size.width = width; size.height = height; return size;
}
</code>```

答:
CG_INLINE is a macro that is used to mark a method as an inline function. The exact syntax is (was ?) compiler dependent, and through preprocessor checks the correct one is chosen for your compiler.

For current GCCs, it should resolve to static inline.

The point of a function marked with inline is that the compiler may insert the equivalent of that function's body where the function was called, instead of making a (slightly more costly) function call. So if you have:

```<code>inline int foo(int a, int b)
{
   return a + b;
}

void bar(int a, int b)
{
   NSLog(@"%d", foo(a, b));
}
</code>```

The compile then is allowed to internally transform it to:

```<code>void bar(int a, int b)
{
   NSLog(@"%d", a + b);
}
</code>```

This saves a function call which on some architectures might be costly and might be very noticeable for example when you're calling the function in a loop a few thousand times.

Note that it only means the compiler may do this transformation, it doesn't necessarily mean it does do it. Depends on compiler settings.

ContentLicense: CC BY-SA 3.0

Title: What does CG_INLINE do?

Body:
I was poking around the definitions for things like CGPoint for hints on how to create my own functions but I don't know the purpose of CG_INLINE. What is happening behind the scenes here?

CG_INLINE CGPoint
CGPointMake(CGFloat x, CGFloat y)
{
  CGPoint p; p.x = x; p.y = y; return p;
}

CG_INLINE CGSize
CGSizeMake(CGFloat width, CGFloat height)
{
  CGSize size; size.width = width; size.height = height; return size;
}

Body:
CG_INLINE is a macro that is used to mark a method as an inline function. The exact syntax is (was ?) compiler dependent, and through preprocessor checks the correct one is chosen for your compiler.

For current GCCs, it should resolve to static inline.

The point of a function marked with inline is that the compiler may insert the equivalent of that function's body where the function was called, instead of making a (slightly more costly) function call. So if you have:

inline int foo(int a, int b)
{
   return a + b;
}

void bar(int a, int b)
{
   NSLog(@"%d", foo(a, b));
}

The compile then is allowed to internally transform it to:

void bar(int a, int b)
{
   NSLog(@"%d", a + b);
}

This saves a function call which on some architectures might be costly and might be very noticeable for example when you're calling the function in a loop a few thousand times.

Note that it only means the compiler may do this transformation, it doesn't necessarily mean it does do it. Depends on compiler settings.


问:
Mongo querying if array contains value
I have such document tructure:

I need to find all documents where 'full' key is equal to '20200518_cbmoAXY.jpeg'

The best query I ended up with is:

```<code>db.getCollection('Advert').find({ $where: "this.images && this.images.length && (this.images[0].full == '20200518_cbmoAXY.jpeg')" })
</code>```

But it finds nothing although record is present.

答:
This is how I solved:</p>

```<code> db.getCollection('Advert').find({ 'images.0.full' : '20200518_cbmoAXY.jpeg'})
</code>```

Title: Mongo querying if array contains value

Body:
I have such document tructure:

I need to find all documents where 'full' key is equal to '20200518_cbmoAXY.jpeg'

The best query I ended up with is:

db.getCollection('Advert').find({ $where: "this.images && this.images.length && (this.images[0].full == '20200518_cbmoAXY.jpeg')" })

But it finds nothing although record is present.

Body:
This is how I solved:

 db.getCollection('Advert').find({ 'images.0.full' : '20200518_cbmoAXY.jpeg'})


问:
Use NumPy cleverly to speed up this loop
This is quite a theoretical question. It is about the for loop at the end of the code attached.

I have three compatible arrays, Z, Wt_1 and Wt_2.

I used the vectorized columns to speed up the loop, ie I code with columns as though they were scalars, and the whole process works.
But this loop still takes forever (2min+). Here, N = 5000 and a column is 100000 long.

Is there a syntax that speeds this up ?

```<code>M=100000

N=5000
t0=0.132
T=0.22
dt=T / N

Z0=8
Y0=7

ssqZ=0.04
ssqY=0.01
sigma_Z=np.sqrt(ssqZ)
sigma_Y=np.sqrt(ssqY)
rho=- 0.4

print("Genreating the Brownian Motions...")
Wt_1=rd.randn(M//2,N)
# shape is (50 000,5 000)
Wt_1=np.vstack((Wt_1,-Wt_1))
#print(np.shape(Wt_1))
Wt_2=rd.randn(M//2,N)
Wt_2=np.vstack((Wt_2,-Wt_2))
print("BM generated!\n")

Z=np.zeros((M,N+1))
# shape is (100 000, 5 001)
Y=np.zeros((M,N+1))
#in SciPy indexing starts from 0 :
Z[:,0]=Z0
Y[:,0]=Y0

for i in range(1,N+1) :
    Z[:,i]=Z[:,i-1] - 0.5*(sigma_Z**2)*dt + sigma_Z*np.sqrt(dt)*Wt_1[:,i-1]

    Y[:,i]=Y[:,i-1] + sigma_Y*np.sqrt(dt)* (rho*Wt_1[:,i-1] + np.sqrt(1 - rho**2)*Wt_2[:,i-1])
</code>```

I should add that the same routine in Matlab takes 19s, whereas this Python one takes 137s, which is counter intuitive to me

答:
You won't get any real speed improvements unless the loop is eliminated. Naturally, if we take a closer look, we can formulate the two equations in a different way. I'll demonstrate in brief with the first one, Z:

```<code>Z(i) = Z(i-1) - C + D*Wt_1(i-1), where C and D are constants.
Z(1) = Z(0) - C + D*Wt_1(0)
Z(2) = Z(1) - C + D*Wt_1(1) = Z(0) - 2*C + D*(Wt_1(0)+Wt_1(1))
i.e. Z(i) = Z(0) -i*C + D*Sum(Wt_1(0..i-1))
</code>```

As you can see, the term Z(0) is actually a constant and is present in all columns; we can simply set it during initialization. The only actual recurrence is in Wt_1. In the Y equation, similarly, the recurrence is dependent on Wt_1 and Wt_2.

And we have our loophole here: this repetition of the Ws is effectively a column-wise growing or cumulative sum, allowing us to discard the for loop and use np.cumsum instead. We can also broadcast and add in the constant C in Z's equation by multiplying it with np.arange(N+1).

```<code>Z = np.ones((M,N+1))*Z0
Y = np.ones((M,N+1))*Y0
W1 = np.cumsum(Wt_1,axis=1)
W2 = np.cumsum(Wt_2,axis=1)

# Calculate Z
Z -= (0.5*(sigma_Z**2)*dt)*np.arange(N+1)
Z[:,1:] = Z[:,1:] + W1*sigma_Z*np.sqrt(dt)

# Calculate Y
Y[:,1:] = Y[:,1:] + sigma_Y*np.sqrt(dt)*(rho*W1 + np.sqrt(1 - rho**2)*W2)
</code>```

Body:
This is quite a theoretical question. It is about the for loop at the end of the code attached.

I have three compatible arrays, Z, Wt_1 and Wt_2.

I used the vectorized columns to speed up the loop, ie I code with columns as though they were scalars, and the whole process works.
But this loop still takes forever (2min+). Here, N = 5000 and a column is 100000 long.

Is there a syntax that speeds this up ?

M=100000

N=5000
t0=0.132
T=0.22
dt=T / N

Z0=8
Y0=7

ssqZ=0.04
ssqY=0.01
sigma_Z=np.sqrt(ssqZ)
sigma_Y=np.sqrt(ssqY)
rho=- 0.4

print("Genreating the Brownian Motions...")
Wt_1=rd.randn(M//2,N)
# shape is (50 000,5 000)
Wt_1=np.vstack((Wt_1,-Wt_1))
#print(np.shape(Wt_1))
Wt_2=rd.randn(M//2,N)
Wt_2=np.vstack((Wt_2,-Wt_2))
print("BM generated!\n")

Z=np.zeros((M,N+1))
# shape is (100 000, 5 001)
Y=np.zeros((M,N+1))
#in SciPy indexing starts from 0 :
Z[:,0]=Z0
Y[:,0]=Y0

for i in range(1,N+1) :
    Z[:,i]=Z[:,i-1] - 0.5*(sigma_Z**2)*dt + sigma_Z*np.sqrt(dt)*Wt_1[:,i-1]

    Y[:,i]=Y[:,i-1] + sigma_Y*np.sqrt(dt)* (rho*Wt_1[:,i-1] + np.sqrt(1 - rho**2)*Wt_2[:,i-1])

I should add that the same routine in Matlab takes 19s, whereas this Python one takes 137s, which is counter intuitive to me

Body:
You won't get any real speed improvements unless the loop is eliminated. Naturally, if we take a closer look, we can formulate the two equations in a different way. I'll demonstrate in brief with the first one, Z:

Z(i) = Z(i-1) - C + D*Wt_1(i-1), where C and D are constants.
Z(1) = Z(0) - C + D*Wt_1(0)
Z(2) = Z(1) - C + D*Wt_1(1) = Z(0) - 2*C + D*(Wt_1(0)+Wt_1(1))
i.e. Z(i) = Z(0) -i*C + D*Sum(Wt_1(0..i-1))

As you can see, the term Z(0) is actually a constant and is present in all columns; we can simply set it during initialization. The only actual recurrence is in Wt_1. In the Y equation, similarly, the recurrence is dependent on Wt_1 and Wt_2.

And we have our loophole here: this repetition of the Ws is effectively a column-wise growing or cumulative sum, allowing us to discard the for loop and use np.cumsum instead. We can also broadcast and add in the constant C in Z's equation by multiplying it with np.arange(N+1).

Z = np.ones((M,N+1))*Z0
Y = np.ones((M,N+1))*Y0
W1 = np.cumsum(Wt_1,axis=1)
W2 = np.cumsum(Wt_2,axis=1)

# Calculate Z
Z -= (0.5*(sigma_Z**2)*dt)*np.arange(N+1)
Z[:,1:] = Z[:,1:] + W1*sigma_Z*np.sqrt(dt)

# Calculate Y
Y[:,1:] = Y[:,1:] + sigma_Y*np.sqrt(dt)*(rho*W1 + np.sqrt(1 - rho**2)*W2)


问:
JavaFX does not exist using Java 9 and Intellij Idea
I am using Intellij Idea to compile a project that uses Maven dependencies and Intellij keeps telling me that my project has 50 something errors because JavaFX does not exist.

Intellij is not highlighting all the javafx dependencies in my code as errors, it is just that once I press the run and compile the program says that everything in JavaFX does not exists.

I tried to redownload the latest JDK (Java 9.0.1) and that did not fix it. I went into the Default Project Structure and Project Structure to make sure it was using the correct jdk and that did not fix the issue. All the jdks I am using seem to list the javafx packages as included in the project.

This is also only an issue for a particular project that I am working on with a friend. We may have to move over all our code into a new project, however I am not sure if that will fix anything.

Any suggestions?

答:
In Java9+ some modules are not included in JRE/JDK. The solution is to add thore libraries explicitly.

For maven pom file for Java9 I used

```<code><!-- https://mvnrepository.com/artifact/org.openjfx/javafx-controls -->
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>11</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-fxml -->
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-fxml</artifactId>
    <version>11</version>
</dependency>
</code>```

Than I can use desired libray for including of TextField.

```<code>import javafx.scene.control.TextField;
</code>```

Body:
In Java9+ some modules are not included in JRE/JDK. The solution is to add thore libraries explicitly.

For maven pom file for Java9 I used

<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-controls -->
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>11</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.openjfx/javafx-fxml -->
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-fxml</artifactId>
    <version>11</version>
</dependency>

Than I can use desired libray for including of TextField.

import javafx.scene.control.TextField;


问:
Css3 evaluatable expressions?
Are there any techniques that allow for expressions in css3 statements?

Frequently it is helpful to do such things as width: 35%+20px or similar. Right now the only solutions I have to these circumstances are to either redesign the page or to use javascript to dynamically set the css.

答:
unfortunately CSS3 calc() is not quite ready yet ;)

Quote from the specs:

```<code>section {
  float: left;
  margin: 1em; border: solid 1px;
  width: calc(100%/3 - 2*1em - 2*1px);
}

p {
  margin: calc(1rem - 2px) calc(1rem - 1px);
  border: solid transparent; border-width: 2px 1px;
}

p:hover { border-color: yellow; }
</code>```

while it's scary that evaluation expressions may be allowed in CSS (it's not a programming language) it's exciting that something as simple as "take-away" might be used.. but then again there is the "box-sizing" property, so perhaps it's not necessary - to do otherwise is perhaps losing the KISS principle?

Title: Css3 evaluatable expressions?

Body:
unfortunately CSS3 calc() is not quite ready yet ;)

Quote from the specs:

section {
  float: left;
  margin: 1em; border: solid 1px;
  width: calc(100%/3 - 2*1em - 2*1px);
}

p {
  margin: calc(1rem - 2px) calc(1rem - 1px);
  border: solid transparent; border-width: 2px 1px;
}

p:hover { border-color: yellow; }

while it's scary that evaluation expressions may be allowed in CSS (it's not a programming language) it's exciting that something as simple as "take-away" might be used.. but then again there is the "box-sizing" property, so perhaps it's not necessary - to do otherwise is perhaps losing the KISS principle?


问:
How to ignore same values on ChartJs?
I have weird problem to solve.When repeated values exist on data array of chartjs,I want to ignore them(not removing).Because if I remove them or set null,then they will be seem not exaclty I want.Here below what I want to achieve

```<code>data: [500, 500,    2424,   2424,   4111, 4111, 80, 5555,   5555, 6811]
</code>```

When next value is duplicated,then somehow it should be between next and previous value.I couldnt figure that out and didn't know where to start.

Here codepen: https://codepen.io/Cicek96/pen/OJyevXb

var ctx = document.getElementById("myChart").getContext('2d');

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Tokyo", "Mumbai", "Mexico City", "Shanghai", "Sao Paulo", "New York", "Karachi","Buenos Aires", "Delhi","Moscow"],
        datasets: [{
            label: 'Series 1', // Name the series
            data: [500, 500, 2424, 2424, 4111, 4111, 80, 5555, 5555, 6811], // Specify the data values array
            fill: false,
            borderColor: '#2196f3', // Add custom color border (Line)
            backgroundColor: '#2196f3', // Add custom color background (Points and Fill)
            borderWidth: 1 // Specify bar border width
        }]},
    options: {
      responsive: true, // Instruct chart js to respond nicely.
      maintainAspectRatio: false, // Add to prevent default behaviour of full-width/height
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<canvas id="myChart"></canvas></code>```

答:
null dupes and use spanGaps: true to make it draw over dupes

var ctx = document.getElementById("myChart").getContext('2d');

const nullDupes = data => data.map((x, i) => data[i - 1] === x ? null : x);

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["Tokyo", "Mumbai", "Mexico City", "Shanghai", "Sao Paulo", "New York", "Karachi", "Buenos Aires", "Delhi", "Moscow"],
    datasets: [{
      spanGaps: true,
      label: 'Series 1', // Name the series
      data: nullDupes([500, 500, 2424, 2424, 4111, 4111, 80, 5555, 5555, 6811]), // Specify the data values array
      fill: false,
      borderColor: '#2196f3', // Add custom color border (Line)
      backgroundColor: '#2196f3', // Add custom color background (Points and Fill)
      borderWidth: 1 // Specify bar border width
    }]
  },
  options: {
    responsive: true, // Instruct chart js to respond nicely.
    maintainAspectRatio: false, // Add to prevent default behaviour of full-width/height
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<canvas id="myChart"></canvas></code>```

Title: How to ignore same values on ChartJs?

Body:
I have weird problem to solve.When repeated values exist on data array of chartjs,I want to ignore them(not removing).Because if I remove them or set null,then they will be seem not exaclty I want.Here below what I want to achieve

data: [500, 500,    2424,   2424,   4111, 4111, 80, 5555,   5555, 6811]

When next value is duplicated,then somehow it should be between next and previous value.I couldnt figure that out and didn't know where to start.

Here codepen: https://codepen.io/Cicek96/pen/OJyevXb

var ctx = document.getElementById("myChart").getContext('2d');

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Tokyo", "Mumbai", "Mexico City", "Shanghai", "Sao Paulo", "New York", "Karachi","Buenos Aires", "Delhi","Moscow"],
        datasets: [{
            label: 'Series 1', // Name the series
            data: [500, 500, 2424, 2424, 4111, 4111, 80, 5555, 5555, 6811], // Specify the data values array
            fill: false,
            borderColor: '#2196f3', // Add custom color border (Line)
            backgroundColor: '#2196f3', // Add custom color background (Points and Fill)
            borderWidth: 1 // Specify bar border width
        }]},
    options: {
      responsive: true, // Instruct chart js to respond nicely.
      maintainAspectRatio: false, // Add to prevent default behaviour of full-width/height
    }
});

<canvas id="myChart"></canvas>

Body:
null dupes and use spanGaps: true to make it draw over dupes

var ctx = document.getElementById("myChart").getContext('2d');

const nullDupes = data => data.map((x, i) => data[i - 1] === x ? null : x);

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["Tokyo", "Mumbai", "Mexico City", "Shanghai", "Sao Paulo", "New York", "Karachi", "Buenos Aires", "Delhi", "Moscow"],
    datasets: [{
      spanGaps: true,
      label: 'Series 1', // Name the series
      data: nullDupes([500, 500, 2424, 2424, 4111, 4111, 80, 5555, 5555, 6811]), // Specify the data values array
      fill: false,
      borderColor: '#2196f3', // Add custom color border (Line)
      backgroundColor: '#2196f3', // Add custom color background (Points and Fill)
      borderWidth: 1 // Specify bar border width
    }]
  },
  options: {
    responsive: true, // Instruct chart js to respond nicely.
    maintainAspectRatio: false, // Add to prevent default behaviour of full-width/height
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<canvas id="myChart"></canvas>


问:
How To Write An Inner Join With WP Query
I have a ACF relationship field for a custom post type, properties. Moreover, the content of these properties can either be in English or Spanish. When I use a ACF relationship field to associate properties to a user on the user edit page -- /wp/wp-admin/user-edit.php -- everything works as expected, and I can select from the relationship drop down the properties I want for this user.

My question is this: how can I write a query inside this filter such that only the English properties appear, regardless of the language of the page (English or Spanish) which is set by the WPML toggle? I know how to write such a query in SQL:

```<code>SELECT *
FROM wp_2_posts
INNER JOIN wp_2_icl_translations
ON wp_2_icl_translations.element_id = wp_2_posts.id
AND wp_2_icl_translations.language_code = 'en'
WHERE wp_2_posts.post_type = 'properties';
</code>```

But the filter requires that changes be made to $args which adhere to WP_Query. I do not know how to write the above INNER JOIN on wp_2_icl_translations to only show custom post types properties in English. Can someone please instruct me how so that I can get the acf filter to work the way I need it to?

答:
Ok so the way I was able to just show English properties on the user admin page was with this posts_request hook:

```<code>add_filter('posts_request', function($sql, $query) {
  $is_user_edit_page = (
    isset($_SERVER['HTTP_REFERER']) &&
    strpos($_SERVER['HTTP_REFERER'], 'user-edit') !== false
  );

  $is_property_sql  = (strpos($sql, 'property') !== false);

  if ($is_user_edit_page && $is_property_sql) {
    $sql = str_replace("'sp'", "'en'", $sql);
  }

  return $sql;
}, 10, 2);
</code>```

In this hook I make sure it only runs on the user-edit page and that the sql it's changing relates to the properties. If all those cases are true, then I just replace the Spanish language code with the English one. And as a result, the SQL used to query the properties is forced to only query for English ones.

Body:
I have a ACF relationship field for a custom post type, properties. Moreover, the content of these properties can either be in English or Spanish. When I use a ACF relationship field to associate properties to a user on the user edit page -- /wp/wp-admin/user-edit.php -- everything works as expected, and I can select from the relationship drop down the properties I want for this user.

My question is this: how can I write a query inside this filter such that only the English properties appear, regardless of the language of the page (English or Spanish) which is set by the WPML toggle? I know how to write such a query in SQL:

SELECT *
FROM wp_2_posts
INNER JOIN wp_2_icl_translations
ON wp_2_icl_translations.element_id = wp_2_posts.id
AND wp_2_icl_translations.language_code = 'en'
WHERE wp_2_posts.post_type = 'properties';

But the filter requires that changes be made to $args which adhere to WP_Query. I do not know how to write the above INNER JOIN on wp_2_icl_translations to only show custom post types properties in English. Can someone please instruct me how so that I can get the acf filter to work the way I need it to?

Body:
Ok so the way I was able to just show English properties on the user admin page was with this posts_request hook:

add_filter('posts_request', function($sql, $query) {
  $is_user_edit_page = (
    isset($_SERVER['HTTP_REFERER']) &&
    strpos($_SERVER['HTTP_REFERER'], 'user-edit') !== false
  );

  $is_property_sql  = (strpos($sql, 'property') !== false);

  if ($is_user_edit_page && $is_property_sql) {
    $sql = str_replace("'sp'", "'en'", $sql);
  }

  return $sql;
}, 10, 2);

In this hook I make sure it only runs on the user-edit page and that the sql it's changing relates to the properties. If all those cases are true, then I just replace the Spanish language code with the English one. And as a result, the SQL used to query the properties is forced to only query for English ones.


问:
Apache Ignite worker blocked when inserting large amount of records to the persistent storage
I'm looking at Apache Ignite to use as a fast database. Performance is very important, I need to build it as fast as possible with resources available.
First I copy all (450M) records from my original test database to Ignite caches through IgniteDataStreams using PK as a key. Database does not fit in memory so I have disk persistence enabled and eviction disabled. Data is inserted in parallel using 8 threads. I have only one but fairly powerful Windows PC doing all the work, no separate Ignite cluster. I'm not interested in cache recovery so WAL is disabled. Everything goes well until I hit around 310 million entries (2 hours of work). At this point Ignite starts to choke, inserts slow down and then stop with exceptions. Exception is triggered by systemWorkerBlockedTimeout setting set to 5 minutes. Extending this time does not help at all.
Based on heap dump I tried adding -DIGNITE_PAGES_LIST_DISABLE_ONHEAP_CACHING=true and it failed slightly later but still could not finish the job.
I read the performance guides and I tried tweaking other Ignite settings too but didn't see any impact.
How can if find which worker is being blocked and why?

Thank you

Tomasz Grygo

Java 1.8.0_231
Apache Ignite 2.8.1
Windows 10, 64G memory

```<code>2020-05-27 21:54:26,176 [Storage2 ] [ERROR] - DTR_0030 worker Storage2 had error: FATAL ERROR java.lang.IllegalStateException: Data streamer has been closed.
java.lang.IllegalStateException: Data streamer has been closed.
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.closedException(DataStreamerImpl.java:1095)
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.lock(DataStreamerImpl.java:446)
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.addDataInternal(DataStreamerImpl.java:646)
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.addDataInternal(DataStreamerImpl.java:631)
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.addData(DataStreamerImpl.java:753)
    at com.sc.extr.cache.PureIgniteDynamicRowStorage.putIfAbsent(PureIgniteDynamicRowStorage.java:83)
    at com.sc.extr.cache.PureIgniteDynamicRowStorage.addRowOnKey(PureIgniteDynamicRowStorage.java:160)
    at com.sc.extr.tree.MultiCacheTreeBuilder.addRootRowToCache(MultiCacheTreeBuilder.java:409)
    at com.sc.extr.tree.MultiCacheTreeBuilder.parentRev1to1(MultiCacheTreeBuilder.java:237)
    at com.sc.extr.tree.MultiCacheTreeBuilder.addRowToCache(MultiCacheTreeBuilder.java:333)
    at com.sc.extr.tree.MultiCacheTreeBuilder.parentRev(MultiCacheTreeBuilder.java:274)
    at com.sc.extr.tree.MultiCacheTreeBuilder.addRow(MultiCacheTreeBuilder.java:379)
    at com.sc.extr.tree.MultiCacheTreeBuilder.process(MultiCacheTreeBuilder.java:206)
    at com.sc.bi.workflow.WorkTransformer.processOne(WorkTransformer.java:84)
    at com.sc.bi.workflow.WorkTransformer.doWork(WorkTransformer.java:145)
    at com.sc.bi.workflow.WorkTransformer.processQueue(WorkTransformer.java:210)
    at com.sc.bi.workflow.WorkTransformer.run(WorkTransformer.java:169)
Caused by: class org.apache.ignite.IgniteCheckedException: Data streamer has been cancelled: DataStreamerImpl [bufLdrSzPerThread=4096, rcvr=org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl$IsolatedUpdater@381b03ed, ioPlcRslvr=null, cacheName=PERSON.PTINTN, bufSize=512, parallelOps=0, timeout=-1, autoFlushFreq=0, bufMappings=ConcurrentHashMap {03e74462-12ec-4140-b9fb-a975572ac3bb=Buffer [node=TcpDiscoveryNode [id=03e74462-12ec-4140-b9fb-a975572ac3bb, consistentId=b01eb38b-7728-4e43-a697-0bc52f872e44, addrs=ArrayList [127.0.0.1, 172.27.179.112], sockAddrs=HashSet [SOFTBI-DEV.sc.com/172.27.179.112:47500, /127.0.0.1:47500], discPort=47500, order=1, intOrder=1, lastExchangeTime=1590614830815, loc=true, ver=2.8.1#20200521-sha1:86422096, isClient=false], isLocNode=true, idGen=0, sem=java.util.concurrent.Semaphore@2a869d9[Permits = 64], perNodeParallelOps=64, entriesCnt=2048, locFutsSize=0, reqsSize=0]}, cacheObjProc=GridProcessorAdapter [], cacheObjCtx=org.apache.ignite.internal.processors.cache.CacheObjectContext@2a5313b0, cancelled=true, cancellationReason=null, failCntr=0, activeFuts=GridConcurrentHashSet [GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=2102798044], GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=1195632760], GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=370791970], GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=420732031], GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=1453517070]], jobPda=null, depCls=null, fut=DataStreamerFuture [super=GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=1165180540]], publicFut=IgniteFuture [orig=DataStreamerFuture [super=GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=1165180540]]], disconnectErr=null, closed=true, lastFlushTime=1590629894701, skipStore=false, keepBinary=false, maxRemapCnt=32, remapSem=java.util.concurrent.Semaphore@6e6f060b[Permits = 2147483647], remapOwning=false]
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.closeEx(DataStreamerImpl.java:1347)
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.closeEx(DataStreamerImpl.java:1318)
    at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.onKernalStop(DataStreamProcessor.java:155)
    at org.apache.ignite.internal.IgniteKernal.stop0(IgniteKernal.java:2551)
    at org.apache.ignite.internal.IgniteKernal.stop(IgniteKernal.java:2499)
    at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.stop0(IgnitionEx.java:2650)
    at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.stop(IgnitionEx.java:2613)
    at org.apache.ignite.internal.IgnitionEx.stop(IgnitionEx.java:339)
    at org.apache.ignite.failure.StopNodeFailureHandler$1.run(StopNodeFailureHandler.java:36)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Ignite config

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="org.apache.ignite.configuration.IgniteConfiguration">
        <property name="gridLogger">
            <bean class="org.apache.ignite.logger.log4j2.Log4J2Logger">
                <constructor-arg type="java.lang.String" value="log4j2.xml"/>
            </bean>
        </property>

        <property name="communicationSpi">
            <bean class="org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi">
              <!-- Override local port. -->
              <property name="localPort" value="47400"/>
            </bean>
        </property>

        <!-- Configure internal thread pool. 64-->
        <property name="publicThreadPoolSize" value="16"/>

        <!-- Configure system thread pool. 32-->
        <property name="systemThreadPoolSize" value="8"/>

        <property name="systemWorkerBlockedTimeout" value="#{5 * 60 * 1000}"/>

        <property name="failureHandler">
            <bean class="org.apache.ignite.failure.StopNodeFailureHandler">

                <!-- uncomment to enable this handler to
                process critical workers' hung-ups -->
                <property name="ignoredFailureTypes">
                    <list>
                    </list>
                </property>

            </bean>
        </property>
        <!-- Set to true to enable distributed class loading for examples, default is false. -->
        <property name="peerClassLoadingEnabled" value="false"/>

        <property name="dataStorageConfiguration">
            <bean class="org.apache.ignite.configuration.DataStorageConfiguration">

                <!--
                     Sets a path to the root directory where data and indexes are
                     to be persisted. It's assumed the directory is on a separated SSD.
                -->
                <property name="storagePath" value="persistence"/>

                <!--
                     Sets a path to the directory where WAL is stored.
                     It's assumed the directory is on a separated HDD.
                -->
                <property name="walPath" value="wal"/>

                <!--
                    Sets a path to the directory where WAL archive is stored.
                    The directory is on the same HDD as the WAL.
                -->
                <property name="walArchivePath" value="wal/archive"/>

                <!-- Changing WAL Mode. -->
                <property name="walMode" value="NONE"/>

                <!-- Set the page size to 4 KB, default -->
                <!-- limit 1 KB - 16 KB -->
                <property name="pageSize" value="#{4 * 1024}"/>

                <!-- Enable write throttling. -->
                <property name="writeThrottlingEnabled" value="false"/>

                <property name="checkpointFrequency" value="500"/>
                <property name="lockWaitTime" value="2000"/>
                <property name="checkpointThreads" value="1"/>
                <property name="checkpointWriteOrder" value="RANDOM"/>

                <!--
                    Default memory region that grows endlessly. A cache is bound to this memory region
                    unless it sets another one in its CacheConfiguration.
                -->
                <property name="defaultDataRegionConfiguration">
                    <bean class="org.apache.ignite.configuration.DataRegionConfiguration">
                        <!--property name="name" value="Default_Region"/-->
                        <property name="name" value="default"/>
                        <!-- 100 MB memory region with disabled eviction -->
                        <property name="initialSize" value="#{100L * 1024 * 1024}"/>
                        <!-- maxSize 20 MB is too little -->
                        <!-- sum of all maxSize values has to be less than total memory of the system -->
                        <!-- limits size in memory, not on disk -->
                        <!-- default value 1.2GB -->
                        <property name="maxSize"     value="#{2L * 1024 * 1024 * 1024}"/>
                        <property name="persistenceEnabled" value="true"/>
                        <!-- Increasing the buffer size to 1 GB. -->
                        <property name="checkpointPageBufferSize" value="#{1L * 1024 * 1024 * 1024}"/>
                    </bean>
                </property>

                <!-- Defining several data regions for different memory regions -->
                <property name="dataRegionConfigurations">
                    <list>
                    </list>
                </property>
            </bean>
        </property>

        <property name="cacheConfiguration">
            <list>
                <!--bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <property name="dataRegionName" value="default"/>
                    <property name="name" value=".ShardDetectorStorage"/>
                    <property name="onheapCacheEnabled" value="true"/>
                </bean>
                <bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <property name="dataRegionName" value="default"/>
                    <property name="name" value=".ChildrenStore"/>
                    <property name="onheapCacheEnabled" value="true"/>
                </bean>
                <bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <property name="dataRegionName" value="default"/>
                    <property name="name" value=".ChildrenStore.listsize"/>
                    <property name="onheapCacheEnabled" value="true"/>
                </bean>
                <bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <property name="dataRegionName" value="default"/>
                    <property name="name" value=".RootStorage"/>
                    <property name="onheapCacheEnabled" value="true"/>
                </bean>
                <bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <property name="dataRegionName" value="default"/>
                    <property name="name" value=".QualifierStorage"/>
                    <property name="onheapCacheEnabled" value="true"/>
                </bean-->
            </list>
        </property>
    </bean>

</beans>
</code>```

Java settings

```<code>-Xms1024m -Xmx50g -Xss1024m
-Xverify:none
-server
-DIGNITE_QUIET=true
-XX:+UseG1GC
-XX:+DisableExplicitGC
-Djava.net.preferIPv4Stack=true
-XX:+AlwaysPreTouch
-XX:+ScavengeBeforeFullGC
-XX:+AggressiveOpts
</code>```

partial thread dump during slowdown

```<code>"db-checkpoint-thread-#54" #99 prio=5 os_prio=0 tid=0x0000000070344800 nid=0x2d54 runnable [0x0000001c5df3e000]
   java.lang.Thread.State: RUNNABLE
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl$Segment.removePageForReplacement(PageMemoryImpl.java:2398)
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl$Segment.access$900(PageMemoryImpl.java:2093)
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl.acquirePage(PageMemoryImpl.java:773)
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl.acquirePage(PageMemoryImpl.java:701)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.saveStoreMetadata(GridCacheOffheapManager.java:342)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.syncMetadata(GridCacheOffheapManager.java:268)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.syncMetadata(GridCacheOffheapManager.java:254)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.beforeCheckpointBegin(GridCacheOffheapManager.java:226)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager$Checkpointer.markCheckpointBegin(GridCacheDatabaseSharedManager.java:4125)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager$Checkpointer.doCheckpoint(GridCacheDatabaseSharedManager.java:3738)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager$Checkpointer.body(GridCacheDatabaseSharedManager.java:3623)
        at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:120)
        at java.lang.Thread.run(Thread.java:748)

   Locked ownable synchronizers:
        - <0x000000009b71a250> (a java.util.concurrent.locks.ReentrantReadWriteLock$NonfairSync)

</code>```

答:
Well, the checkpointing could be the issue here. Please, check the recommendations https://www.gridgain.com/docs/latest/perf-troubleshooting-guide/persistence-tuning
I'd suggest you enable the page throttling, though it's quite weird that the app had been working for 2 hours just fine.</p>

Body:
I'm looking at Apache Ignite to use as a fast database. Performance is very important, I need to build it as fast as possible with resources available.
First I copy all (450M) records from my original test database to Ignite caches through IgniteDataStreams using PK as a key. Database does not fit in memory so I have disk persistence enabled and eviction disabled. Data is inserted in parallel using 8 threads. I have only one but fairly powerful Windows PC doing all the work, no separate Ignite cluster. I'm not interested in cache recovery so WAL is disabled. Everything goes well until I hit around 310 million entries (2 hours of work). At this point Ignite starts to choke, inserts slow down and then stop with exceptions. Exception is triggered by systemWorkerBlockedTimeout setting set to 5 minutes. Extending this time does not help at all.
Based on heap dump I tried adding -DIGNITE_PAGES_LIST_DISABLE_ONHEAP_CACHING=true and it failed slightly later but still could not finish the job.
I read the performance guides and I tried tweaking other Ignite settings too but didn't see any impact.
How can if find which worker is being blocked and why?

Thank you

Tomasz Grygo

Java 1.8.0_231
Apache Ignite 2.8.1
Windows 10, 64G memory

2020-05-27 21:54:26,176 [Storage2 ] [ERROR] - DTR_0030 worker Storage2 had error: FATAL ERROR java.lang.IllegalStateException: Data streamer has been closed.
java.lang.IllegalStateException: Data streamer has been closed.
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.closedException(DataStreamerImpl.java:1095)
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.lock(DataStreamerImpl.java:446)
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.addDataInternal(DataStreamerImpl.java:646)
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.addDataInternal(DataStreamerImpl.java:631)
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.addData(DataStreamerImpl.java:753)
    at com.sc.extr.cache.PureIgniteDynamicRowStorage.putIfAbsent(PureIgniteDynamicRowStorage.java:83)
    at com.sc.extr.cache.PureIgniteDynamicRowStorage.addRowOnKey(PureIgniteDynamicRowStorage.java:160)
    at com.sc.extr.tree.MultiCacheTreeBuilder.addRootRowToCache(MultiCacheTreeBuilder.java:409)
    at com.sc.extr.tree.MultiCacheTreeBuilder.parentRev1to1(MultiCacheTreeBuilder.java:237)
    at com.sc.extr.tree.MultiCacheTreeBuilder.addRowToCache(MultiCacheTreeBuilder.java:333)
    at com.sc.extr.tree.MultiCacheTreeBuilder.parentRev(MultiCacheTreeBuilder.java:274)
    at com.sc.extr.tree.MultiCacheTreeBuilder.addRow(MultiCacheTreeBuilder.java:379)
    at com.sc.extr.tree.MultiCacheTreeBuilder.process(MultiCacheTreeBuilder.java:206)
    at com.sc.bi.workflow.WorkTransformer.processOne(WorkTransformer.java:84)
    at com.sc.bi.workflow.WorkTransformer.doWork(WorkTransformer.java:145)
    at com.sc.bi.workflow.WorkTransformer.processQueue(WorkTransformer.java:210)
    at com.sc.bi.workflow.WorkTransformer.run(WorkTransformer.java:169)
Caused by: class org.apache.ignite.IgniteCheckedException: Data streamer has been cancelled: DataStreamerImpl [bufLdrSzPerThread=4096, rcvr=org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl$IsolatedUpdater@381b03ed, ioPlcRslvr=null, cacheName=PERSON.PTINTN, bufSize=512, parallelOps=0, timeout=-1, autoFlushFreq=0, bufMappings=ConcurrentHashMap {03e74462-12ec-4140-b9fb-a975572ac3bb=Buffer [node=TcpDiscoveryNode [id=03e74462-12ec-4140-b9fb-a975572ac3bb, consistentId=b01eb38b-7728-4e43-a697-0bc52f872e44, addrs=ArrayList [127.0.0.1, 172.27.179.112], sockAddrs=HashSet [SOFTBI-DEV.sc.com/172.27.179.112:47500, /127.0.0.1:47500], discPort=47500, order=1, intOrder=1, lastExchangeTime=1590614830815, loc=true, ver=2.8.1#20200521-sha1:86422096, isClient=false], isLocNode=true, idGen=0, sem=java.util.concurrent.Semaphore@2a869d9[Permits = 64], perNodeParallelOps=64, entriesCnt=2048, locFutsSize=0, reqsSize=0]}, cacheObjProc=GridProcessorAdapter [], cacheObjCtx=org.apache.ignite.internal.processors.cache.CacheObjectContext@2a5313b0, cancelled=true, cancellationReason=null, failCntr=0, activeFuts=GridConcurrentHashSet [GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=2102798044], GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=1195632760], GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=370791970], GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=420732031], GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=1453517070]], jobPda=null, depCls=null, fut=DataStreamerFuture [super=GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=1165180540]], publicFut=IgniteFuture [orig=DataStreamerFuture [super=GridFutureAdapter [ignoreInterrupts=false, state=INIT, res=null, hash=1165180540]]], disconnectErr=null, closed=true, lastFlushTime=1590629894701, skipStore=false, keepBinary=false, maxRemapCnt=32, remapSem=java.util.concurrent.Semaphore@6e6f060b[Permits = 2147483647], remapOwning=false]
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.closeEx(DataStreamerImpl.java:1347)
    at org.apache.ignite.internal.processors.datastreamer.DataStreamerImpl.closeEx(DataStreamerImpl.java:1318)
    at org.apache.ignite.internal.processors.datastreamer.DataStreamProcessor.onKernalStop(DataStreamProcessor.java:155)
    at org.apache.ignite.internal.IgniteKernal.stop0(IgniteKernal.java:2551)
    at org.apache.ignite.internal.IgniteKernal.stop(IgniteKernal.java:2499)
    at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.stop0(IgnitionEx.java:2650)
    at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.stop(IgnitionEx.java:2613)
    at org.apache.ignite.internal.IgnitionEx.stop(IgnitionEx.java:339)
    at org.apache.ignite.failure.StopNodeFailureHandler$1.run(StopNodeFailureHandler.java:36)
    at java.lang.Thread.run(Thread.java:748)

Ignite config

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="org.apache.ignite.configuration.IgniteConfiguration">
        <property name="gridLogger">
            <bean class="org.apache.ignite.logger.log4j2.Log4J2Logger">
                <constructor-arg type="java.lang.String" value="log4j2.xml"/>
            </bean>
        </property>

        <property name="communicationSpi">
            <bean class="org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi">

              <property name="localPort" value="47400"/>
            </bean>
        </property>

        <property name="publicThreadPoolSize" value="16"/>

        <property name="systemThreadPoolSize" value="8"/>

        <property name="systemWorkerBlockedTimeout" value="#{5 * 60 * 1000}"/>

        <property name="failureHandler">
            <bean class="org.apache.ignite.failure.StopNodeFailureHandler">

                <property name="ignoredFailureTypes">
                    <list>
                    </list>
                </property>

            </bean>
        </property>

        <property name="peerClassLoadingEnabled" value="false"/>

        <property name="dataStorageConfiguration">
            <bean class="org.apache.ignite.configuration.DataStorageConfiguration">

                <property name="storagePath" value="persistence"/>

                <property name="walPath" value="wal"/>

                <property name="walArchivePath" value="wal/archive"/>

                <property name="walMode" value="NONE"/>

                <property name="pageSize" value="#{4 * 1024}"/>

                <property name="writeThrottlingEnabled" value="false"/>

                <property name="checkpointFrequency" value="500"/>
                <property name="lockWaitTime" value="2000"/>
                <property name="checkpointThreads" value="1"/>
                <property name="checkpointWriteOrder" value="RANDOM"/>

                <property name="defaultDataRegionConfiguration">
                    <bean class="org.apache.ignite.configuration.DataRegionConfiguration">

                        <property name="name" value="default"/>

                        <property name="initialSize" value="#{100L * 1024 * 1024}"/>

                        <property name="maxSize"     value="#{2L * 1024 * 1024 * 1024}"/>
                        <property name="persistenceEnabled" value="true"/>

                        <property name="checkpointPageBufferSize" value="#{1L * 1024 * 1024 * 1024}"/>
                    </bean>
                </property>

                <property name="dataRegionConfigurations">
                    <list>
                    </list>
                </property>
            </bean>
        </property>

        <property name="cacheConfiguration">
            <list>

            </list>
        </property>
    </bean>

</beans>

Java settings

-Xms1024m -Xmx50g -Xss1024m
-Xverify:none
-server
-DIGNITE_QUIET=true
-XX:+UseG1GC
-XX:+DisableExplicitGC
-Djava.net.preferIPv4Stack=true
-XX:+AlwaysPreTouch
-XX:+ScavengeBeforeFullGC
-XX:+AggressiveOpts

partial thread dump during slowdown

"db-checkpoint-thread-#54" #99 prio=5 os_prio=0 tid=0x0000000070344800 nid=0x2d54 runnable [0x0000001c5df3e000]
   java.lang.Thread.State: RUNNABLE
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl$Segment.removePageForReplacement(PageMemoryImpl.java:2398)
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl$Segment.access$900(PageMemoryImpl.java:2093)
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl.acquirePage(PageMemoryImpl.java:773)
        at org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryImpl.acquirePage(PageMemoryImpl.java:701)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.saveStoreMetadata(GridCacheOffheapManager.java:342)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.syncMetadata(GridCacheOffheapManager.java:268)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.syncMetadata(GridCacheOffheapManager.java:254)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheOffheapManager.beforeCheckpointBegin(GridCacheOffheapManager.java:226)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager$Checkpointer.markCheckpointBegin(GridCacheDatabaseSharedManager.java:4125)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager$Checkpointer.doCheckpoint(GridCacheDatabaseSharedManager.java:3738)
        at org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager$Checkpointer.body(GridCacheDatabaseSharedManager.java:3623)
        at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:120)
        at java.lang.Thread.run(Thread.java:748)

   Locked ownable synchronizers:
        - <0x000000009b71a250> (a java.util.concurrent.locks.ReentrantReadWriteLock$NonfairSync)


问:
I'm passing an std::string to a boost function that takes a const reference to that type, but the value is mutated
I'm passing an std::string to a function imported from boost-program-options dll. The function takes one parameter and it's a const reference to a string. However, the value that the function receives is different from what I pass. Here's the minimal code

```<code>#include "boost/program_options.hpp"

int main()
{
    std::string s = "This is a string";
    auto res = boost::program_options::to_internal(s);
}
</code>```

And here's the function

```<code>BOOST_PROGRAM_OPTIONS_DECL std::string to_internal(const std::string& s)
{
    return s;
}
</code>```

The value of the parameter "s" is supposed to be "this is a string" when the function above is called, but the value is always something different. When I say something different I mean a long random string. So long that the basic_string constructor throws an exception.

My only guess is that it has something to do with how the function is called and how the parameters are passed since this function is imported from an external dll.

I followed the macro BOOST_PROGRAM_OPTIONS_DECL definition and it's just __declspec(dllimport)

More info:

standard is C++14

Toolset used is Visual studio 2019 v142

Boost library version is 1.73.0 and installed using vcpkg

答:
To anyone who's stuck in the same situation (Making a call to a function imported from a DLL and receiving garbage values for the arguments instead of what you're actually passing)
It's probably because of unmatching configurations used for building your project and the DLL.
In my case, I installed some boost libraries using Vcpkg. I was using the release builds while building my project in debug configuration. Turned out Vcpkg makes a different set of builds to be used in debug configuration. I switched to using those and now it works.</p>

Body:
I'm passing an std::string to a function imported from boost-program-options dll. The function takes one parameter and it's a const reference to a string. However, the value that the function receives is different from what I pass. Here's the minimal code

#include "boost/program_options.hpp"

int main()
{
    std::string s = "This is a string";
    auto res = boost::program_options::to_internal(s);
}

And here's the function

BOOST_PROGRAM_OPTIONS_DECL std::string to_internal(const std::string& s)
{
    return s;
}

The value of the parameter "s" is supposed to be "this is a string" when the function above is called, but the value is always something different. When I say something different I mean a long random string. So long that the basic_string constructor throws an exception.

My only guess is that it has something to do with how the function is called and how the parameters are passed since this function is imported from an external dll.

I followed the macro BOOST_PROGRAM_OPTIONS_DECL definition and it's just __declspec(dllimport)

More info:

standard is C++14

Toolset used is Visual studio 2019 v142

Boost library version is 1.73.0 and installed using vcpkg


问:
Chrome 83: Cannot upload file
I've update Chrome on version 83, and some of my forms that use an "Ajax upload" component (more info below) aren't working. I've read the issues of the new version (https://developers.google.com/web/updates/2020/05/nic83) but I can't find anything related on forms, iframes, files, ajax or posts.

I'll try to post a sample on fiddler, but I want to know if somebody knows anything about it.

By other way, on other forms I've a multifile, drag&drop uploader (dropzone.js) and it's working fine, but it isn't easy to convert and I need a fast solution.

A dummy sample (I don't have any sandbox to test upload): https://jsfiddle.net/drvespa/7ue8k94r/3/

On Chrome 83 (I've tried on Canary 85 version too): it throws no error cause the submit of the form isn't catched by AjaxUpload component. The callback is being called before the submit is done, and the response is empty.

On Firefox: it throws an error cause AjaxUpload component is trying to deserialize 404 of the dummy upload page.

I post the library on https://filebin.net/8sgsmq7sh14m0qen:

```<code>/**
* Ajax upload
* Project page - http://valums.com/ajax-upload/
* Copyright (c) 2008 Andris Valums, http://valums.com
* Licensed under the MIT license (http://valums.com/mit-license/)
* Version 3.6 (26.06.2009)
*/
</code>```

答:
We were using this old plugin:

http://jquery.malsup.com/form/#options-object

There's an option there you might be using if you were supporting ie8 at some point in the past 10 years...

```<code>{
    url: '/branded/image_upload',
    type: 'POST',
    iframe: false
}
</code>```

We also had a <textarea></textarea> wrapper hack in the response.

This code was passed down through a lot of iterations lol.

Title: Chrome 83: Cannot upload file

Body:
I've update Chrome on version 83, and some of my forms that use an "Ajax upload" component (more info below) aren't working. I've read the issues of the new version (https://developers.google.com/web/updates/2020/05/nic83) but I can't find anything related on forms, iframes, files, ajax or posts.

I'll try to post a sample on fiddler, but I want to know if somebody knows anything about it.

By other way, on other forms I've a multifile, drag&drop uploader (dropzone.js) and it's working fine, but it isn't easy to convert and I need a fast solution.

A dummy sample (I don't have any sandbox to test upload): https://jsfiddle.net/drvespa/7ue8k94r/3/

On Chrome 83 (I've tried on Canary 85 version too): it throws no error cause the submit of the form isn't catched by AjaxUpload component. The callback is being called before the submit is done, and the response is empty.

On Firefox: it throws an error cause AjaxUpload component is trying to deserialize 404 of the dummy upload page.

I post the library on https://filebin.net/8sgsmq7sh14m0qen:

/**
* Ajax upload
* Project page - http://valums.com/ajax-upload/
* Copyright (c) 2008 Andris Valums, http://valums.com
* Licensed under the MIT license (http://valums.com/mit-license/)
* Version 3.6 (26.06.2009)
*/

Body:
We were using this old plugin:

http://jquery.malsup.com/form/#options-object

There's an option there you might be using if you were supporting ie8 at some point in the past 10 years...

{
    url: '/branded/image_upload',
    type: 'POST',
    iframe: false
}

We also had a <textarea></textarea> wrapper hack in the response.

This code was passed down through a lot of iterations lol.


问:
Shouldn't this fail without the use of locking? Simple producer consumer
I have a queue, a list with producer threads and a list with consumer threads.

My code looks like this

```<code>    public class Runner
{
    List<Thread> Producers;
    List<Thread> Consumers;
    Queue<int> queue;
    Random random;

    public Runner()
    {
        Producers = new List<Thread>();
        Consumers = new List<Thread>();

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Produce);
            Producers.Add(thread);
        }

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Consume);
            Consumers.Add(thread);
        }

        queue = new Queue<int>();
        random = new Random();

        Producers.ForEach(( thread ) => { thread.Start(); });
        Consumers.ForEach(( thread ) => { thread.Start(); });
    }

    protected void Produce()
    {
        while (true)
        {
                int number = random.Next(0, 99);
                queue.Enqueue(number);
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Produce: " + number);
        }
    }

    protected void Consume()
    {
        while (true)
        {
                if (queue.Any())
                {
                    int number = queue.Dequeue();
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Consume: " + number);
                }
                else
                {
                    Console.WriteLine("No items to consume");
                }
        }
    }
}
</code>```

Shouldn't this fail miserable cause of the missing use of the lock keyword?
It failed once because it tried to dequeue when the queue was empty, using the lock keyword will fix that right?

If the lock keyword is not needed for the above code, when is it needed then?

Thank you in advance! =)

答:
By running your code I received InvalidOperationException - "Collection was modified after the enumerator was instantiated." It means that you modify data while using several threads.

You can use the lock every time you Enqueue or Dequeue - because you modify the queue from several threads. A far better option is to use ConcurentQueues as it is thread safe and lock-free concurrent collection. It also provides better performance.

Body:
I have a queue, a list with producer threads and a list with consumer threads.

My code looks like this

    public class Runner
{
    List<Thread> Producers;
    List<Thread> Consumers;
    Queue<int> queue;
    Random random;

    public Runner()
    {
        Producers = new List<Thread>();
        Consumers = new List<Thread>();

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Produce);
            Producers.Add(thread);
        }

        for (int i = 0; i < 2; i++)
        {
            Thread thread = new Thread(Consume);
            Consumers.Add(thread);
        }

        queue = new Queue<int>();
        random = new Random();

        Producers.ForEach(( thread ) => { thread.Start(); });
        Consumers.ForEach(( thread ) => { thread.Start(); });
    }

    protected void Produce()
    {
        while (true)
        {
                int number = random.Next(0, 99);
                queue.Enqueue(number);
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Produce: " + number);
        }
    }

    protected void Consume()
    {
        while (true)
        {
                if (queue.Any())
                {
                    int number = queue.Dequeue();
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " Consume: " + number);
                }
                else
                {
                    Console.WriteLine("No items to consume");
                }
        }
    }
}

Shouldn't this fail miserable cause of the missing use of the lock keyword?
It failed once because it tried to dequeue when the queue was empty, using the lock keyword will fix that right?

If the lock keyword is not needed for the above code, when is it needed then?

Thank you in advance! =)


问:
CSS width/height issue
I am facing a problem with image height. I want to make that image 100% height without hard coding. But i can't do that. Every time some margin goes bottom to the image. I have changed the image width, height, font size but nothing works.

Here is an example of the image not filling the height:

* {
  margin: 0;
  padding: 0;
  outline: none;
  box-sizing: border-box;
}
html {
  font-size:16px;
}
body {
  font-family: Raleway, "Times New Roman", Times, serif;
  background-color: #f6f6f6;
  line-height: 1.5rem;
  width: 100%;
  color: #424242;
}

.flexbox {
  display: flex;
  justify-content: space-between;
}

.img-responsive {max-width:100%;max-height:100%;}
.card {
  background-color: #ffffff;
  border: 2px solid red;
  margin: 1.5rem 0rem 0rem;
  width: 75%;
}

.post-card-body {
  padding: 1.5rem;
}

.post-card-heading {
  margin: 0 0 0.75rem;
}

.btn-section {
  margin-top: 1rem;
}
.continue-btn {
  background-color: #ffb69b;
  border-color: #ffb69b;
}

.btn {
  font-size: 0.75rem;
  text-transform: uppercase;
  color: #ffffff;
  padding: 0.75rem 1.25rem;
  border: 0.0625rem solid #e9e9ea;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexbox card">
  <div class="post-card-img">
    <img src="http://via.placeholder.com/300x300/DDaDaa/FFFFFF" alt="" class="img-responsive" />
  </div>
  <div class="post-card-body">
    <div class="post-card-heading">
      <h3>Lorem ipsum dolor sit amet.</h3>
      <h6>By Admin Ahsan September 11, 2015</h6>
      <hr />
    </div>
    <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum
      atque sed in, fugiat natus laboriosam
    </p>
    <div class="btn-section">
      <button class="btn continue-btn">Continue Reading</button>
    </div>
  </div>
</div></code>```

codepen link: click here
Screenshot: click here

答:
Two possible solutions:

```<code>.post-card-img img {
  display: block;
}
</code>```

or

```<code>.post-card-img {
  line-height: 0;
}
</code>```

Title: CSS width/height issue

Body:
I am facing a problem with image height. I want to make that image 100% height without hard coding. But i can't do that. Every time some margin goes bottom to the image. I have changed the image width, height, font size but nothing works.

Here is an example of the image not filling the height:

* {
  margin: 0;
  padding: 0;
  outline: none;
  box-sizing: border-box;
}
html {
  font-size:16px;
}
body {
  font-family: Raleway, "Times New Roman", Times, serif;
  background-color: #f6f6f6;
  line-height: 1.5rem;
  width: 100%;
  color: #424242;
}

.flexbox {
  display: flex;
  justify-content: space-between;
}

.img-responsive {max-width:100%;max-height:100%;}
.card {
  background-color: #ffffff;
  border: 2px solid red;
  margin: 1.5rem 0rem 0rem;
  width: 75%;
}

.post-card-body {
  padding: 1.5rem;
}

.post-card-heading {
  margin: 0 0 0.75rem;
}

.btn-section {
  margin-top: 1rem;
}
.continue-btn {
  background-color: #ffb69b;
  border-color: #ffb69b;
}

.btn {
  font-size: 0.75rem;
  text-transform: uppercase;
  color: #ffffff;
  padding: 0.75rem 1.25rem;
  border: 0.0625rem solid #e9e9ea;
}

Lorem ipsum dolor sit amet.

By Admin Ahsan September 11, 2015

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum
      atque sed in, fugiat natus laboriosam

      <button class="btn continue-btn">Continue Reading</button>

codepen link: click here
Screenshot: click here

Body:
Two possible solutions:

.post-card-img img {
  display: block;
}

or

.post-card-img {
  line-height: 0;
}


问:
How do you convert variable names to a string in Dart?
Very new to Flutter and Dart, so pardon me for the ill-phrased question.

This is a generic code that I have:

```<code>// Constructor class
class ctr {
  String i;
  ctr(String a){
    this.a = a;
}

// New variables based on contsructor
var ctrA = ctr('a');
var ctrB = ctr('b');
var ctrC = ctr('c');

// Storing the variables based on constructor in an array
List ctrList = [ctrA, ctrB, ctrC]

void main() {
  String match = 'ctrB';
  for (var i = 0; i<ctrList.length; i++) {
    if(match == ctrList.toString() {
      print('The string of your match is ${ctrList[i].a}');
    } else {
      print('Error!);
    }
  }
}
</code>```

The current output is Error!.
Instead, what I'm looking for is a.

As you can see, I'm trying to iterate the variable match over the array that stores the variables based on an aforementioned constructor, and if it matches, print out the value in the constructor that it has matched to. runtimeType can only get me the name of the origin Class (which will be ctr).

I tried to convert the variable name by using toString() but that didn't work either. What I need is a method to convert these variable names to a string and get a match, but I'm not sure what I can do.

Thanks in advance for the help!

答:
This is how you should declare a list of custom object.</p>

```<code>List<ctr> ctrList= [ ctrA , ctrB , ctrC ];

void main() {
String match = 'ctrB';
for (var index = 0; i<ctrList.length; i++) {
if(match == ctrList[index].i {
  print('The string of your match is ${ctrList[i].a}');
} else {
  print('Error!);
}}
</code>```

Body:
Very new to Flutter and Dart, so pardon me for the ill-phrased question.

This is a generic code that I have:

// Constructor class
class ctr {
  String i;
  ctr(String a){
    this.a = a;
}

// New variables based on contsructor
var ctrA = ctr('a');
var ctrB = ctr('b');
var ctrC = ctr('c');

// Storing the variables based on constructor in an array
List ctrList = [ctrA, ctrB, ctrC]

void main() {
  String match = 'ctrB';
  for (var i = 0; i<ctrList.length; i++) {
    if(match == ctrList.toString() {
      print('The string of your match is ${ctrList[i].a}');
    } else {
      print('Error!);
    }
  }
}

The current output is Error!.
Instead, what I'm looking for is a.

As you can see, I'm trying to iterate the variable match over the array that stores the variables based on an aforementioned constructor, and if it matches, print out the value in the constructor that it has matched to. runtimeType can only get me the name of the origin Class (which will be ctr).

I tried to convert the variable name by using toString() but that didn't work either. What I need is a method to convert these variable names to a string and get a match, but I'm not sure what I can do.

Thanks in advance for the help!

Body:
This is how you should declare a list of custom object.

List<ctr> ctrList= [ ctrA , ctrB , ctrC ];

void main() {
String match = 'ctrB';
for (var index = 0; i<ctrList.length; i++) {
if(match == ctrList[index].i {
  print('The string of your match is ${ctrList[i].a}');
} else {
  print('Error!);
}}


问:
Insert a variable in-between ' ' in a shell osascript command?
I am using a MacOS osascript command in a shell script and I try to run the following command:

```<code>APPNAME=$@

if pgrep -x "$APPNAME" > /dev/null # checking if app is open
then
  echo "Closing..."
  osascript -e 'quit app $APPNAME'

else
  echo "*** The app is not open"
fi
</code>```

Ideally, the command would be osascript -e 'quit app "Calendar"' as an example of a working solution. However, I can't seem to insert a variable in-between ' ' quotation marks.

What would be a workaround?

答:
Try:

```<code>osascript -e 'quit app '"$APPNAME"
</code>```

Or, if osascript requires additional double quotes, try:

```<code>osascript -e 'quit app "'"$APPNAME"'"'
</code>```

Body:
I am using a MacOS osascript command in a shell script and I try to run the following command:

APPNAME=$@

if pgrep -x "$APPNAME" > /dev/null # checking if app is open
then
  echo "Closing..."
  osascript -e 'quit app $APPNAME'

else
  echo "*** The app is not open"
fi

Ideally, the command would be osascript -e 'quit app "Calendar"' as an example of a working solution. However, I can't seem to insert a variable in-between ' ' quotation marks.

What would be a workaround?

Body:
Try:

osascript -e 'quit app '"$APPNAME"

Or, if osascript requires additional double quotes, try:

osascript -e 'quit app "'"$APPNAME"'"'


问:
My website is not showing on iphones?it is showing question marks with such a weird stuff?
Hello everyone my website is not showing on iphones its working fine on android devices but when i open it on iphones it is showing some unique content like this could anyone help plz:

See the Screenshot of the error

答:
Without seeing your code or knowing what you built it with, it's a little hard to tell, but looks like an issue with the character type setting.
Make sure you have a character type set:

Ex:

Content-Type: text/html; charset=utf-8


问:
How to build a SSDT project with different Target Platform in CI or from msbuild
With a SSDT project in VS 2019 there is a Target Platform which specifies the target database version for the bacpac when doing a build:

For local development this is correct, but in the continuous delivery setup we want to target Azure Database which is a different option.  Attempting to publish a bacpac file built for SQL Server 2017 results in the error
A project which specifies SQL Server 2017 as the target platform cannot be published to Microsoft Azure SQL Database v12.

This happens because, I think, in the bacpac model.xml file there is the line

```<code><DataSchemaModel FileFormatVersion="1.2" SchemaVersion="2.9" DspName="Microsoft.Data.Tools.Schema.Sql.Sql140DatabaseSchemaProvider" CollationLcid="1033" CollationCaseSensitive="False" xmlns="http://schemas.microsoft.com/sqlserver/dac/Serialization/2012/02">
</code>```

where the DspName is refering to SQL Server 2017.

Is there an option to pass to msbuild that will cause it to build a bacpac for a different, Azure SQL Database, target?

I've tried to use a publish profile and specify /p:SqlPublishProfilePath="Ci.publish.xml" when ci.publish.xml has been created from an Azure database, but that does not affect the creation of the bacpac.  Indeed the ci.publish.xml file only contains a db name and connection string, nothing about the version anyway.

答:
As often happens, typing the question makes you think, and in the sqlproj file you will see for SQL Server 2017:

```<code>   <DSP>Microsoft.Data.Tools.Schema.Sql.Sql140DatabaseSchemaProvider</DSP>
</code>```

and for Azure SQL Database:

```<code>   <DSP>Microsoft.Data.Tools.Schema.Sql.SqlAzureV12DatabaseSchemaProvider</DSP>
</code>```

so passing the option to msbuild

```<code>msbuild /t:Build Db.sln /p:Configuration=Release /p:Platform="Any cpu" /p:DSP="Microsoft.Data.Tools.Schema.Sql.SqlAzureV12DatabaseSchemaProvider"
</code>```

Does the trick.

Body:
With a SSDT project in VS 2019 there is a Target Platform which specifies the target database version for the bacpac when doing a build:

For local development this is correct, but in the continuous delivery setup we want to target Azure Database which is a different option.  Attempting to publish a bacpac file built for SQL Server 2017 results in the error
A project which specifies SQL Server 2017 as the target platform cannot be published to Microsoft Azure SQL Database v12.

This happens because, I think, in the bacpac model.xml file there is the line

<DataSchemaModel FileFormatVersion="1.2" SchemaVersion="2.9" DspName="Microsoft.Data.Tools.Schema.Sql.Sql140DatabaseSchemaProvider" CollationLcid="1033" CollationCaseSensitive="False" xmlns="http://schemas.microsoft.com/sqlserver/dac/Serialization/2012/02">

where the DspName is refering to SQL Server 2017.

Is there an option to pass to msbuild that will cause it to build a bacpac for a different, Azure SQL Database, target?

I've tried to use a publish profile and specify /p:SqlPublishProfilePath="Ci.publish.xml" when ci.publish.xml has been created from an Azure database, but that does not affect the creation of the bacpac.  Indeed the ci.publish.xml file only contains a db name and connection string, nothing about the version anyway.

Body:
As often happens, typing the question makes you think, and in the sqlproj file you will see for SQL Server 2017:

   <DSP>Microsoft.Data.Tools.Schema.Sql.Sql140DatabaseSchemaProvider</DSP>

and for Azure SQL Database:

   <DSP>Microsoft.Data.Tools.Schema.Sql.SqlAzureV12DatabaseSchemaProvider</DSP>

so passing the option to msbuild

msbuild /t:Build Db.sln /p:Configuration=Release /p:Platform="Any cpu" /p:DSP="Microsoft.Data.Tools.Schema.Sql.SqlAzureV12DatabaseSchemaProvider"

Does the trick.


问:
2 Classes and Filed in 1 Section
I have 2 different fields in different classes, which are displayed on the site in one section.

Only one of them is used at a time.

I am currently using this code:

```<code><div class = "class2">
<? php the_sub_field ('filed2'); ?>
</div>
<div class = "class1">
<? php the_sub_field ('filed1'); ?>
</div>
</code>```

Each has a different class, but both options are available. I want to make a condition.

If filed2 is used then class 2

And if filed1 is used then class 1

Right now the style of both is conflicting, and it doesn't fit.
How to define this condition?

答:
You can make as follows :</p>

```<code>    <? php
    if($field=='field1')
      $class="class1";
    else if($field=='field2')
      $class="class2";

    // here give $field a value

     $field= 'field1'
?>

    <div class = " <? php echo $class ?> ">
    <? php the_sub_field ('$field'); ?>
    </div>
</code>```

Title: 2 Classes and Filed in 1 Section

Body:
I have 2 different fields in different classes, which are displayed on the site in one section.

Only one of them is used at a time.

I am currently using this code:

<? php the_sub_field ('filed2'); ?>

<? php the_sub_field ('filed1'); ?>

Each has a different class, but both options are available. I want to make a condition.

If filed2 is used then class 2

And if filed1 is used then class 1

Right now the style of both is conflicting, and it doesn't fit.
How to define this condition?

Body:
You can make as follows :

    <? php
    if($field=='field1')
      $class="class1";
    else if($field=='field2')
      $class="class2";

    // here give $field a value

     $field= 'field1'
?>

    <div class = " <? php echo $class ?> ">
    <? php the_sub_field ('$field'); ?>
    </div>