问:
how to handle time for different components in pygame
I'm making a pygame game where a person can purchase bombs from a shop. The player can also drop as many bombs as he buys. I need a way to make each bomb disappear after 3 seconds of it being dropped. In the following code I am just able to drop the bombs however I have tried various methods and failed.  </p>

```<code>import pygame
import random

pygame.font.init()

width = 900
height = 600

screen = pygame.display.set_mode([width, height])

walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
             pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'),
             pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]

walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
            pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'),
            pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]

char = pygame.image.load('standing.png')
bomb_pic = pygame.transform.scale(pygame.image.load('bomb.png'), (20,20))
bomb_explosion = pygame.transform.scale(pygame.image.load('explosion1.png'), (40,40))
# char_rect = char.get_rect()

enemy_Left = [pygame.image.load('L1E.png'), pygame.image.load('L2E.png'), pygame.image.load('L3E.png'),
            pygame.image.load('L4E.png'), pygame.image.load('L5E.png'), pygame.image.load('L6E.png'),
            pygame.image.load('L7E.png'), pygame.image.load('L8E.png'), pygame.image.load('L9E.png')]

x = 50
y = 50
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
down = False
up = False
walkCount = 0

enemy_vel = 2
enemy_list = []

shop = pygame.transform.scale(pygame.image.load("shop.png"), (60, 60))

clock = pygame.time.Clock()
FPS = 60

font = pygame.font.Font('freesansbold.ttf', 32)
items_font = pygame.font.Font('freesansbold.ttf', 16)

bombs =[]
bag = {'bomb': 0}
print(bag["bomb"])

class Button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self, win, outline=None):

        # Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)

        pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)

        if self.text != '':
            font = pygame.font.SysFont('comicsans', 20)
            text = font.render(self.text, 1, (0, 0, 0))
            win.blit(text, (
                self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))

def shop_run():
    shop_bomb = Button((0, 200, 0), 820, 150, 60, 20, text="Bomb_b")
    bright_green = (0, 255, 0)
    green = (0, 200, 0)
    shop_bomb.draw(screen)

def redrawGameWindow():
    global walkCount
    global font
    global bag
    global items_font
    global enemy_list
    screen.fill([166, 166, 166])
    for five_enemies in range(6):
        random_enemy_location_y = random.randrange(100, 400)
        random_enemy_location_x = random.randrange(800, 840)
        enemy_list.append([random_enemy_location_x, random_enemy_location_y])

    for enemies in range(6):
        screen.blit(enemy_Left[enemies], enemy_list[enemies])
        enemy_list[enemies][0] -= 0.3

    pygame.draw.rect(screen, (0, 0, 0), (800, 0, 100, 600))
    if x + char.get_width() < 60 and y + char.get_height() < 60:
        shop_run()

    screen.blit(shop, (0, 0))
    screen.blit(font.render("Menu", True, (255,255,255)),(805, 10))
    screen.blit(items_font.render("Bombs: "+ str(bag["bomb"]), True, (255, 255, 255)), (805, 550))
    # screen.blit(bomb_explosion, (450, 300))
    if walkCount + 1 >= 27:
        walkCount = 0

    if left:
        screen.blit(walkLeft[walkCount // 3], (x, y))
        walkCount += 1

    elif right:
        screen.blit(walkRight[walkCount // 3], (x, y))
        walkCount += 1

    elif down:
        screen.blit(char, (x, y))
        walkcount = 0

    elif up:
        screen.blit(char, (x, y))
        walkcount = 0

    else:
        screen.blit(char, (x, y))
        walkCount = 0

    for pos in bombs:
        screen.blit(bomb_pic, pos)

    pygame.display.update()

def main():
    run = True
    # shopper()
    pygame.display.set_caption("bomb-mania")

    global x
    global y
    global width
    global height
    global vel

    global isJump
    global jumpCount

    global left
    global right
    global down
    global up

    global walkCount

    global bomb_pic

    global font
    while run:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if x + char.get_width() < 60 and y + char.get_height() < 60:
                buy = pygame.key.get_pressed()
                if buy[pygame.K_b]:
                    bag["bomb"] += 1
                    print(bag["bomb"])

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and bag["bomb"] >= 1:
                    bombs.append(((x + (char.get_width()/2)),( y + (char.get_height() - 20))))
                    bag["bomb"] -= 1

        redrawGameWindow()

        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT] and x > vel - 15:
            x -= vel
            left = True
            right = False
            down = False
            up = False

        elif keys[pygame.K_RIGHT] and x < 800 - vel - width:
            x += vel
            left = False
            right = True
            down = False
            up = False

        elif keys[pygame.K_DOWN] and y < 600 - height:
            y += vel
            left = False
            right = False
            down = True
            up = False

        elif keys[pygame.K_UP] and y > vel - 15:
            y -= vel
            left = False
            right = False
            down = False
            up = True

        else:
            left = False
            right = False
            down = False
            up = False
            walkCount = 0

        clock.tick(FPS)
        pygame.display.flip()

main()
</code>```

答:
Use pygame.time.get_ticks() to get the current time in milliseconds. Compute the time when the bomb has to disappear.
Store the time to the list bombs. The list bombs has to contain a tuple of position and time.

If the time is elapsed, then remove the bomb from the list:

def redrawGameWindow():
    current_time = pygame.time.get_ticks()
    # [...]

    for i in reversed(range(len(bombs))):
        pos, end_time = bombs[i]
        if current_time > end_time
            bombs.pop(i)
        else:
            screen.blit(bomb_pic, pos)
```

<pre class="lang-py prettyprint-override"><code>def main():
    # [...]

    while run:

        current_time = pygame.time.get_ticks()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            # [...]

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and bag["bomb"] >= 1:
                    pos = x + char.get_width()/2, y + char.get_height() - 20
                    end_time = current_time + 3000 # 3000 milliseconds = 3 seconds
                    bombs.append((pos, end_time))
                    bag["bomb"] -= 1

        redrawGameWindow()
</code>```

Body:
I'm making a pygame game where a person can purchase bombs from a shop. The player can also drop as many bombs as he buys. I need a way to make each bomb disappear after 3 seconds of it being dropped. In the following code I am just able to drop the bombs however I have tried various methods and failed.

import pygame
import random

pygame.font.init()

width = 900
height = 600

screen = pygame.display.set_mode([width, height])

walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
             pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'),
             pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]

walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
            pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'),
            pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]

char = pygame.image.load('standing.png')
bomb_pic = pygame.transform.scale(pygame.image.load('bomb.png'), (20,20))
bomb_explosion = pygame.transform.scale(pygame.image.load('explosion1.png'), (40,40))
# char_rect = char.get_rect()

enemy_Left = [pygame.image.load('L1E.png'), pygame.image.load('L2E.png'), pygame.image.load('L3E.png'),
            pygame.image.load('L4E.png'), pygame.image.load('L5E.png'), pygame.image.load('L6E.png'),
            pygame.image.load('L7E.png'), pygame.image.load('L8E.png'), pygame.image.load('L9E.png')]

x = 50
y = 50
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
down = False
up = False
walkCount = 0

enemy_vel = 2
enemy_list = []

shop = pygame.transform.scale(pygame.image.load("shop.png"), (60, 60))

clock = pygame.time.Clock()
FPS = 60

font = pygame.font.Font('freesansbold.ttf', 32)
items_font = pygame.font.Font('freesansbold.ttf', 16)

bombs =[]
bag = {'bomb': 0}
print(bag["bomb"])

class Button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self, win, outline=None):

        # Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)

        pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)

        if self.text != '':
            font = pygame.font.SysFont('comicsans', 20)
            text = font.render(self.text, 1, (0, 0, 0))
            win.blit(text, (
                self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))

def shop_run():
    shop_bomb = Button((0, 200, 0), 820, 150, 60, 20, text="Bomb_b")
    bright_green = (0, 255, 0)
    green = (0, 200, 0)
    shop_bomb.draw(screen)

def redrawGameWindow():
    global walkCount
    global font
    global bag
    global items_font
    global enemy_list
    screen.fill([166, 166, 166])
    for five_enemies in range(6):
        random_enemy_location_y = random.randrange(100, 400)
        random_enemy_location_x = random.randrange(800, 840)
        enemy_list.append([random_enemy_location_x, random_enemy_location_y])

    for enemies in range(6):
        screen.blit(enemy_Left[enemies], enemy_list[enemies])
        enemy_list[enemies][0] -= 0.3

    pygame.draw.rect(screen, (0, 0, 0), (800, 0, 100, 600))
    if x + char.get_width() < 60 and y + char.get_height() < 60:
        shop_run()

    screen.blit(shop, (0, 0))
    screen.blit(font.render("Menu", True, (255,255,255)),(805, 10))
    screen.blit(items_font.render("Bombs: "+ str(bag["bomb"]), True, (255, 255, 255)), (805, 550))
    # screen.blit(bomb_explosion, (450, 300))
    if walkCount + 1 >= 27:
        walkCount = 0

    if left:
        screen.blit(walkLeft[walkCount // 3], (x, y))
        walkCount += 1

    elif right:
        screen.blit(walkRight[walkCount // 3], (x, y))
        walkCount += 1

    elif down:
        screen.blit(char, (x, y))
        walkcount = 0

    elif up:
        screen.blit(char, (x, y))
        walkcount = 0

    else:
        screen.blit(char, (x, y))
        walkCount = 0

    for pos in bombs:
        screen.blit(bomb_pic, pos)

    pygame.display.update()

def main():
    run = True
    # shopper()
    pygame.display.set_caption("bomb-mania")

    global x
    global y
    global width
    global height
    global vel

    global isJump
    global jumpCount

    global left
    global right
    global down
    global up

    global walkCount

    global bomb_pic

    global font
    while run:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if x + char.get_width() < 60 and y + char.get_height() < 60:
                buy = pygame.key.get_pressed()
                if buy[pygame.K_b]:
                    bag["bomb"] += 1
                    print(bag["bomb"])

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and bag["bomb"] >= 1:
                    bombs.append(((x + (char.get_width()/2)),( y + (char.get_height() - 20))))
                    bag["bomb"] -= 1

        redrawGameWindow()

        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT] and x > vel - 15:
            x -= vel
            left = True
            right = False
            down = False
            up = False

        elif keys[pygame.K_RIGHT] and x < 800 - vel - width:
            x += vel
            left = False
            right = True
            down = False
            up = False

        elif keys[pygame.K_DOWN] and y < 600 - height:
            y += vel
            left = False
            right = False
            down = True
            up = False

        elif keys[pygame.K_UP] and y > vel - 15:
            y -= vel
            left = False
            right = False
            down = False
            up = True

        else:
            left = False
            right = False
            down = False
            up = False
            walkCount = 0

        clock.tick(FPS)
        pygame.display.flip()

main()

Body:
Use pygame.time.get_ticks() to get the current time in milliseconds. Compute the time when the bomb has to disappear.
Store the time to the list bombs. The list bombs has to contain a tuple of position and time.

If the time is elapsed, then remove the bomb from the list:

def redrawGameWindow():
    current_time = pygame.time.get_ticks()
    # [...]

    for i in reversed(range(len(bombs))):
        pos, end_time = bombs[i]
        if current_time > end_time
            bombs.pop(i)
        else:
            screen.blit(bomb_pic, pos)

def main():
    # [...]

    while run:

        current_time = pygame.time.get_ticks()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            # [...]

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and bag["bomb"] >= 1:
                    pos = x + char.get_width()/2, y + char.get_height() - 20
                    end_time = current_time + 3000 # 3000 milliseconds = 3 seconds
                    bombs.append((pos, end_time))
                    bag["bomb"] -= 1

        redrawGameWindow()


来源: stackexchange

问:
Class constructor in C#
I am somewhat of a C# noob, and have been looking around in documentation but have been unable to understand how to create a constructor method for my class as I would in python.

Say I have a class named Vehicle, and when I create an instance of vehicle, I need to input the number of wheels and the number of axles the vehicles has. I want the constructor to divide the total wheels by the total axles to set the property wheelsPerAxle:

```<code>public class Vehicle
{
    public int numWheels;
    public int numAxles;
    public int wheelsPerAxle;

    public Vehicle()
    {
        wheelsPerAxle = Mathf.CeilToInt(numWheels/numAxles);
    }

}
</code>```

My code example is a little ridiculous but hopefully you get the idea that I want to call the method when the object is instantiated. How can I do this?

答:
You can pass the parameters you need in the constructor.

Also, it's usually more safe to mark those fields initilized during construction as readonly if you know they can't change for a specific instance. (And in this case they must be assigned a value in the constructor.

```<code>public class Vehicle
{
    public readonly int numWheels;
    public readonly int numAxles;
    public readonly int wheelsPerAxle;

    public Vehicle(int numWheels, int numAxles)
    {
        // let's do some validation here
        if (numWheels < 0)
        {
            throw new ArgumentOutOfRangeException(nameof(numWheels), "number of wheels must be non negative");
        }
        // And do something similar for number of axles

        //set the readonly fields, if you need them for another thing later
        this.numWheels = numWheels; // We must use "this" to refer to the fields to disambiguate between the field and the parameter because I chose to give them the same name.
        this.numAxles = numAxles;

        // I'll let you handle the case where "numAxles" is zero. Maybe you allow it ? (in this case you can use a conditional operator), or throw an exception during validation if you don't allow it.
        wheelsPerAxle = Mathf.CeilToInt(numWheels/numAxles);
    }

}
</code>```

Then you can instantiate like this, calling the constructor with the proper arguments as any method :

```<code>var car = new Vehicle(numWheels: 4, numAxles: 2); // Argument names are not mandatory, but good to avoid confusion while coding, since they are both int, you might invert them without noticing)
</code>```

Also, here I used fields, as you did, but you can set properties as well. And auto-properties if you want. To make them readonly, just give them a get;, instead of get; set;

ContentLicense: CC BY-SA 4.0

Title: Class constructor in C#

Body:
I am somewhat of a C# noob, and have been looking around in documentation but have been unable to understand how to create a constructor method for my class as I would in python.

Say I have a class named Vehicle, and when I create an instance of vehicle, I need to input the number of wheels and the number of axles the vehicles has. I want the constructor to divide the total wheels by the total axles to set the property wheelsPerAxle:

public class Vehicle
{
    public int numWheels;
    public int numAxles;
    public int wheelsPerAxle;

    public Vehicle()
    {
        wheelsPerAxle = Mathf.CeilToInt(numWheels/numAxles);
    }

}

My code example is a little ridiculous but hopefully you get the idea that I want to call the method when the object is instantiated. How can I do this?

Body:
You can pass the parameters you need in the constructor.

Also, it's usually more safe to mark those fields initilized during construction as readonly if you know they can't change for a specific instance. (And in this case they must be assigned a value in the constructor.

public class Vehicle
{
    public readonly int numWheels;
    public readonly int numAxles;
    public readonly int wheelsPerAxle;

    public Vehicle(int numWheels, int numAxles)
    {
        // let's do some validation here
        if (numWheels < 0)
        {
            throw new ArgumentOutOfRangeException(nameof(numWheels), "number of wheels must be non negative");
        }
        // And do something similar for number of axles

        //set the readonly fields, if you need them for another thing later
        this.numWheels = numWheels; // We must use "this" to refer to the fields to disambiguate between the field and the parameter because I chose to give them the same name.
        this.numAxles = numAxles;

        // I'll let you handle the case where "numAxles" is zero. Maybe you allow it ? (in this case you can use a conditional operator), or throw an exception during validation if you don't allow it.
        wheelsPerAxle = Mathf.CeilToInt(numWheels/numAxles);
    }

}

Then you can instantiate like this, calling the constructor with the proper arguments as any method :

var car = new Vehicle(numWheels: 4, numAxles: 2); // Argument names are not mandatory, but good to avoid confusion while coding, since they are both int, you might invert them without noticing)

Also, here I used fields, as you did, but you can set properties as well. And auto-properties if you want. To make them readonly, just give them a get;, instead of get; set;


问:
I am using recyclerview for loading images from Firebase
But the images are not loading and the app is crashing after a few seconds. Below is the complete coding of the project. I am new to android development and I thought I should start learning by doing a project. I am not understanding what is the problem in my coding.

RecyclerAdapter code

```<code>package com.example.wallpaper;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.List;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ImageVieHolder> {
    private Context mCtx;
    private List<Images> imagesList;

    public RecyclerAdapter(Context mCtx, List<Images> imagesList) {
        this.mCtx = mCtx;
        this.imagesList = imagesList;
    }

    @NonNull
    @Override
    public ImageVieHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
       View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.cards,parent,false);
       return new ImageVieHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ImageVieHolder holder, int position) {
        Images im=imagesList.get(position);
        Glide.with(mCtx).load(im.url).into(holder.imageView);
}

    @Override
    public int getItemCount() {
        return imagesList.size();
    }

    public class ImageVieHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        public ImageVieHolder(@NonNull View itemView) {
            super(itemView);
            imageView=itemView.findViewById(R.id.image_view);

        }
    }
}
</code>```

MainActivity.java code

```<code>package com.example.wallpaper;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<Images> imagesList;
    private RecyclerView recyclerView;
    private DatabaseReference db;
    private RecyclerAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=findViewById(R.id.recycler);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new GridLayoutManager(this,3));
        imagesList =new ArrayList<>();
        adapter=new RecyclerAdapter(this,imagesList);
        recyclerView.setAdapter(adapter);
        String category = "S10";
        db= FirebaseDatabase.getInstance().getReference("images").child(category);
        db.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot post:dataSnapshot.getChildren()){
                    Images im =post.getValue(Images.class);
                    imagesList.add(im);
                }

                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    }
</code>```

Images.java code

```<code>package com.example.wallpaper;

public class Images {
    String url;

    public Images(String url) {
        this.url = url;
    }
}
</code>```

答:
You are passing an empty list to the adapter, so its throwing exception while accessing an item from the empty list.

Please change your code as below:-

```<code>    db.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot post:dataSnapshot.getChildren()){
                Images im =post.getValue(Images.class);
                imagesList.add(im);
            }

             adapter=new RecyclerAdapter(this,imagesList);
             recyclerView.setAdapter(adapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
</code>```

Body:
But the images are not loading and the app is crashing after a few seconds. Below is the complete coding of the project. I am new to android development and I thought I should start learning by doing a project. I am not understanding what is the problem in my coding.

RecyclerAdapter code

package com.example.wallpaper;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.List;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ImageVieHolder> {
    private Context mCtx;
    private List<Images> imagesList;

    public RecyclerAdapter(Context mCtx, List<Images> imagesList) {
        this.mCtx = mCtx;
        this.imagesList = imagesList;
    }

    @NonNull
    @Override
    public ImageVieHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
       View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.cards,parent,false);
       return new ImageVieHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ImageVieHolder holder, int position) {
        Images im=imagesList.get(position);
        Glide.with(mCtx).load(im.url).into(holder.imageView);
}

    @Override
    public int getItemCount() {
        return imagesList.size();
    }

    public class ImageVieHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        public ImageVieHolder(@NonNull View itemView) {
            super(itemView);
            imageView=itemView.findViewById(R.id.image_view);

        }
    }
}

MainActivity.java code

package com.example.wallpaper;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<Images> imagesList;
    private RecyclerView recyclerView;
    private DatabaseReference db;
    private RecyclerAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=findViewById(R.id.recycler);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new GridLayoutManager(this,3));
        imagesList =new ArrayList<>();
        adapter=new RecyclerAdapter(this,imagesList);
        recyclerView.setAdapter(adapter);
        String category = "S10";
        db= FirebaseDatabase.getInstance().getReference("images").child(category);
        db.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot post:dataSnapshot.getChildren()){
                    Images im =post.getValue(Images.class);
                    imagesList.add(im);
                }

                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    }

Images.java code

package com.example.wallpaper;

public class Images {
    String url;

    public Images(String url) {
        this.url = url;
    }
}

Body:
You are passing an empty list to the adapter, so its throwing exception while accessing an item from the empty list.

Please change your code as below:-

    db.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot post:dataSnapshot.getChildren()){
                Images im =post.getValue(Images.class);
                imagesList.add(im);
            }

             adapter=new RecyclerAdapter(this,imagesList);
             recyclerView.setAdapter(adapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });


问:
fill a div width 100% with same height dynamic width images
I m having images of same height but of varied width.

I was wondering if i can do something with css or js to fill the width of the container(parent div) with the images.

For an example I have made this page(link)

Now as one can see the last image in the second row if its placed in the first then easily the blank spaces can be saved.

Regards

答:
I don't think there will be any library available as per your requirement.
But look at this, I have created a function such as gridWidth() for you. Maybe this can help you.

$.fn.gridWidth = function() {
  var container = this,
    c_width = container.width(),
    imgs = $('img', container),
    obj = {},
    new_obj = [],
    tmp_tw = 0;

  $.each(imgs, (i, v) => obj[i] = {"e": v, "w": $(v).outerWidth(true) });
  while (Object.keys(obj).length) {
    f = 0;
    var tmp_obj = Object.assign({}, obj);
    $.each(tmp_obj, function(i, v) {
      if ((tmp_tw + v.w) <= c_width) {
        tmp_tw += v.w;
        new_obj.push(v.e);
        delete obj[i];
        delete tmp_obj[i];
        f = 1;
      }
      if (tmp_tw >= c_width) return tmp_tw = 0;
    });
    if (!f) tmp_tw = 0;
  }
  $.each(new_obj, (i, v) => { $(v).css('order', i) });
};

$(window).on('load', function(){
    $('.img_container').gridWidth();
});
$(window).resize(function(){
    $('.img_container').gridWidth();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.img_container {
  border: 2px black solid;
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  margin: 0 auto;
}

.img_container img {
  margin-bottom: 5px;
  margin-right: 5px;
}</code>```

```

ContentLicense: CC BY-SA 3.0

Body:
I don't think there will be any library available as per your requirement.
But look at this, I have created a function such as gridWidth() for you. Maybe this can help you.

$.fn.gridWidth = function() {
  var container = this,
    c_width = container.width(),
    imgs = $('img', container),
    obj = {},
    new_obj = [],
    tmp_tw = 0;

  $.each(imgs, (i, v) => obj[i] = {"e": v, "w": $(v).outerWidth(true) });
  while (Object.keys(obj).length) {
    f = 0;
    var tmp_obj = Object.assign({}, obj);
    $.each(tmp_obj, function(i, v) {
      if ((tmp_tw + v.w) <= c_width) {
        tmp_tw += v.w;
        new_obj.push(v.e);
        delete obj[i];
        delete tmp_obj[i];
        f = 1;
      }
      if (tmp_tw >= c_width) return tmp_tw = 0;
    });
    if (!f) tmp_tw = 0;
  }
  $.each(new_obj, (i, v) => { $(v).css('order', i) });
};

$(window).on('load', function(){
    $('.img_container').gridWidth();
});
$(window).resize(function(){
    $('.img_container').gridWidth();
});

.img_container {
  border: 2px black solid;
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  margin: 0 auto;
}

.img_container img {
  margin-bottom: 5px;
  margin-right: 5px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="img_container">
  <img src="https://dummyimage.com/100x150/000000/ffffff&text=1">
  <img src="https://dummyimage.com/150x150/0000FF/ffffff&text=2">
  <img src="https://dummyimage.com/200x150/EA00FF/ffffff&text=3">
  <img src="https://dummyimage.com/250x150/FF0000/ffffff&text=4">
  <img src="https://dummyimage.com/300x150/00D5FF/ffffff&text=5">
  <img src="https://dummyimage.com/350x150/26FF00/ffffff&text=6">
  <img src="https://dummyimage.com/300x150/FF8400/ffffff&text=7">
  <img src="https://dummyimage.com/250x150/000000/ffffff&text=8">
  <img src="https://dummyimage.com/200x150/0000FF/ffffff&text=9">
  <img src="https://dummyimage.com/150x150/EA00FF/ffffff&text=10">
  <img src="https://dummyimage.com/100x150/FF0000/ffffff&text=11">
  <img src="https://dummyimage.com/100x150/00D5FF/ffffff&text=12">
  <img src="https://dummyimage.com/150x150/26FF00/ffffff&text=13">
  <img src="https://dummyimage.com/200x150/FF8400/ffffff&text=14">
  <img src="https://dummyimage.com/250x150/000000/ffffff&text=15">
  <img src="https://dummyimage.com/300x150/0000FF/ffffff&text=16">
  <img src="https://dummyimage.com/350x150/EA00FF/ffffff&text=17">
  <img src="https://dummyimage.com/300x150/FF0000/ffffff&text=18">
  <img src="https://dummyimage.com/250x150/00D5FF/ffffff&text=19">
  <img src="https://dummyimage.com/200x150/26FF00/ffffff&text=20">
  <img src="https://dummyimage.com/150x150/FF8400/ffffff&text=21">
  <img src="https://dummyimage.com/100x150/000000/ffffff&text=22">
  <img src="https://dummyimage.com/100x150/0000FF/ffffff&text=23">
  <img src="https://dummyimage.com/150x150/EA00FF/ffffff&text=24">
  <img src="https://dummyimage.com/200x150/FF0000/ffffff&text=25">
  <img src="https://dummyimage.com/250x150/00D5FF/ffffff&text=26">
  <img src="https://dummyimage.com/300x150/26FF00/ffffff&text=27">
  <img src="https://dummyimage.com/350x150/FF8400/ffffff&text=28">
  <img src="https://dummyimage.com/300x150/000000/ffffff&text=29">
  <img src="https://dummyimage.com/250x150/0000FF/ffffff&text=30">
  <img src="https://dummyimage.com/200x150/EA00FF/ffffff&text=31">
  <img src="https://dummyimage.com/150x150/FF0000/ffffff&text=32">
  <img src="https://dummyimage.com/100x150/00D5FF/ffffff&text=33">
  <img src="https://dummyimage.com/100x150/26FF00/ffffff&text=34">
  <img src="https://dummyimage.com/100x150/FF8400/ffffff&text=35">
  <img src="https://dummyimage.com/150x150/000000/ffffff&text=36">
</div>


问:
Changing text color if text contains hashtag "#"
Basically I want to achieve a "hashtag" feature.
I'm having a hard time making a logic wherein if the text contains a "#" (eg. I love #flutter), the #flutter text will change its color to blue.

Can you give me a hint on what widget to use or is there a package for this?

I can't seem to find a similar problem.

答:
```<code>HashTagText
</code>```

https://pub.dev/packages/hashtagtext#-installing-tab-

I published this library. It will auto detect hash tags from string and make highlighted.

```<code>dependencies:
  hashtagtext: ^0.0.1
</code>```

EXAMPLE

```<code>HashTagText(text: "I will found and #highlight all #tag and #make it #clickable", onHashTagClick: (tag){
              print("You clicked on $tag");
            },)
</code>```

Body:
HashTagText

https://pub.dev/packages/hashtagtext#-installing-tab-

I published this library. It will auto detect hash tags from string and make highlighted.

dependencies:
  hashtagtext: ^0.0.1

EXAMPLE

HashTagText(text: "I will found and #highlight all #tag and #make it #clickable", onHashTagClick: (tag){
              print("You clicked on $tag");
            },)


问:
Trying to update prices from an API using AJAX/Flask
So I am trying to update prices on products, without having to refresh. I wat it to update live, but I don't understand. I have read a bunch of threads, but haven't figured it out.

Here is my python code:

```<code>@app.route('/bprices', methods=['GET'])
def bPrices():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=[can get you a key if needed]').json()

    products = [
        {
            "id": product["product_id"],
            "sell_price": product["sell_summary"][:1],
            "buy_price": product["buy_summary"][:1],
            "sell_volume": product["quick_status"]["sellVolume"],
            "buy_volume": product["quick_status"]["buyVolume"],
        }
        for product in f["products"].values()
    ]
    return jsonify(products=products)
</code>```

And here is my HTML + js:

```<code><table
    id="myTable"
    class="table table-striped table-bordered table-sm table-dark sortable"
    cellspacing="0"
  >
    <thead>
      <tr>
        <th aria-label="Product Name" data-balloon-pos="up">Product</th>
        <th aria-label="Product's buy price" data-balloon-pos="up">
          Buy Price
        </th>
        <th aria-label="Product's sell price" data-balloon-pos="up">
          Sell Price
        </th>
        <th aria-label="Product's buy volume" data-balloon-pos="up">
          Buy Volume
        </th>
        <th aria-label="Product's sell volume" data-balloon-pos="up">
          Sell Volume
        </th>
        <th>
          Margin
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td id="price"></td>
      </tr>
    </tbody>
  </table>
</div>
<script>
  $SCRIPT_ROOT = {{ request.script_root | tojson | safe }};
    (function () {
      $.getJSON(
        $SCRIPT_ROOT + "/_stuff", // Your AJAX route here
        function (data) {
          $("#price").text(data.products)
        }
      );
      setTimeout(arguments.callee, 10000);
    })();
</script>
</code>```

currently, it is only displaying a JSON file of the data I want to access, most likely because of the "jsonify".

答:
To show the JSON data in a table view, loop through the products in jquery and create the table records inside a tbody element. Then insert this tbody into the desired table.

Here I have shown an example of displaying live data without page refresh using AJAX and Flask.

app.py:

```<code>from random import randint
from flask import Flask, render_template, jsonify, request

app = Flask(__name__)

@app.route("/get_data", methods=["GET"])
def get_data():
    products = [
        {
            "name": "mobile",
            "quantity": 3217210,
            "price": randint(1,1000)
        },
        {
            "name": "laptop",
            "quantity": 343217210,
            "price": randint(1,1000)
        },
        {
            "name": "mouse",
            "quantity": 100,
            "price": randint(1,1000)
        }
    ]
    return jsonify(products=products)

@app.route("/", methods=["GET"])
def home():
    return render_template("products.html")
</code>```

products.html:

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="utf-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <title>Live Prices</title>
</head>
<body>
    <h3>Products</h3>
    <table border="1" id="products_table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Quantity</th>
                <th>Price</th>
            </tr>
        </thead>
    </table>
    <script type=text/javascript>
        $SCRIPT_ROOT = {{ request.script_root | tojson | safe }};
        (function () {
            $.getJSON($SCRIPT_ROOT + "/get_data",
            function(data) {
                var products = data.products;
                var table_body = document.createElement("tbody");
                $.each(products, function(index, product){
                    var product_name = product.name.toString();
                    var product_quantity = product.quantity;
                    var product_price = product.price;
                    var row = table_body.insertRow();
                    var name_cell = row.insertCell();
                    name_cell.appendChild(document.createTextNode(product_name));
                    var quantity_cell = row.insertCell();
                    quantity_cell.appendChild(document.createTextNode(product_quantity));
                    var price_cell = row.insertCell();
                    price_cell.appendChild(document.createTextNode(product_price));
                })
                $("#products_table tbody").remove();
                $("#products_table").append(table_body);
            }
            );
            setTimeout(arguments.callee, 5000);
        })();
    </script>
</body>
</html>
</code>```

Output:

Note:
- In get_data route, I have generated random price between 1 to 1000 for each products in each GET request.
- In setTimeout(arguments.callee, 5000); the 5000 indicates it will delay 5000 milliseconds(=5 seconds) between executions of the script.

Body:
So I am trying to update prices on products, without having to refresh. I wat it to update live, but I don't understand. I have read a bunch of threads, but haven't figured it out.

Here is my python code:

@app.route('/bprices', methods=['GET'])
def bPrices():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=[can get you a key if needed]').json()

    products = [
        {
            "id": product["product_id"],
            "sell_price": product["sell_summary"][:1],
            "buy_price": product["buy_summary"][:1],
            "sell_volume": product["quick_status"]["sellVolume"],
            "buy_volume": product["quick_status"]["buyVolume"],
        }
        for product in f["products"].values()
    ]
    return jsonify(products=products)

And here is my HTML + js:

        Product

          Buy Price

          Sell Price

          Buy Volume

          Sell Volume

          Margin

currently, it is only displaying a JSON file of the data I want to access, most likely because of the "jsonify".

Body:
To show the JSON data in a table view, loop through the products in jquery and create the table records inside a tbody element. Then insert this tbody into the desired table.

Here I have shown an example of displaying live data without page refresh using AJAX and Flask.

app.py:

from random import randint
from flask import Flask, render_template, jsonify, request

app = Flask(__name__)

@app.route("/get_data", methods=["GET"])
def get_data():
    products = [
        {
            "name": "mobile",
            "quantity": 3217210,
            "price": randint(1,1000)
        },
        {
            "name": "laptop",
            "quantity": 343217210,
            "price": randint(1,1000)
        },
        {
            "name": "mouse",
            "quantity": 100,
            "price": randint(1,1000)
        }
    ]
    return jsonify(products=products)

@app.route("/", methods=["GET"])
def home():
    return render_template("products.html")

products.html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="utf-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <title>Live Prices</title>
</head>
<body>
    <h3>Products</h3>
    <table border="1" id="products_table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Quantity</th>
                <th>Price</th>
            </tr>
        </thead>
    </table>
    <script type=text/javascript>
        $SCRIPT_ROOT = {{ request.script_root | tojson | safe }};
        (function () {
            $.getJSON($SCRIPT_ROOT + "/get_data",
            function(data) {
                var products = data.products;
                var table_body = document.createElement("tbody");
                $.each(products, function(index, product){
                    var product_name = product.name.toString();
                    var product_quantity = product.quantity;
                    var product_price = product.price;
                    var row = table_body.insertRow();
                    var name_cell = row.insertCell();
                    name_cell.appendChild(document.createTextNode(product_name));
                    var quantity_cell = row.insertCell();
                    quantity_cell.appendChild(document.createTextNode(product_quantity));
                    var price_cell = row.insertCell();
                    price_cell.appendChild(document.createTextNode(product_price));
                })
                $("#products_table tbody").remove();
                $("#products_table").append(table_body);
            }
            );
            setTimeout(arguments.callee, 5000);
        })();
    </script>
</body>
</html>

Output:

Note:
- In get_data route, I have generated random price between 1 to 1000 for each products in each GET request.
- In setTimeout(arguments.callee, 5000); the 5000 indicates it will delay 5000 milliseconds(=5 seconds) between executions of the script.


问:
Can I use/import my ARCore project (in Unity) to my Flutter project?
I wonder if anyone did this before or know how to. I've been surving the net for a while and got a lot of confusions about this.

Can someone make it straight for me?

Regards,
SlimmZ

答:
You can try with this dependancy for your project:
https://pub.dev/packages/flutter_unity_widget</p>


问:
Google Cloud VideoIntelligence - Is there a way to only call AnnotateVideo for a particular section of a video?
Currently I am using the AnnotateVideo function to analyse videos. Is there any way to analyse only a section of a video, such as providing start_time and end_time as an argument to the function ?</p>

```<code>gs_video_path ='gs://'+bucket_name+'/'+videodata.video.path+videodata.video.name
print(gs_video_path)

video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.OBJECT_TRACKING]
operation = video_client.annotate_video(gs_video_path, features=features)
</code>```

答:
You can analyse only the sections you're interested in by providing a VideoContext with a VideoSegment list. Here is an example with a single 21..42s segment:

```<code>from google.cloud import videointelligence
from google.cloud.videointelligence import enums, types

video_client = videointelligence.VideoIntelligenceServiceClient()

gs_video_path = f'gs://{bucket_name}/{videodata.video.path}{videodata.video.name}'
features = [enums.Feature.OBJECT_TRACKING]
segment = types.VideoSegment()
segment.start_time_offset.FromSeconds(21)
segment.end_time_offset.FromSeconds(42)
context = types.VideoContext(segments=[segment])

operation = video_client.annotate_video(
    gs_video_path,
    features=features,
    video_context=context)
</code>```

If you want more examples, I recently wrote this tutorial: https://codelabs.developers.google.com/codelabs/cloud-video-intelligence-python3

Body:
Currently I am using the AnnotateVideo function to analyse videos. Is there any way to analyse only a section of a video, such as providing start_time and end_time as an argument to the function ?

gs_video_path ='gs://'+bucket_name+'/'+videodata.video.path+videodata.video.name
print(gs_video_path)

video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.OBJECT_TRACKING]
operation = video_client.annotate_video(gs_video_path, features=features)

Body:
You can analyse only the sections you're interested in by providing a VideoContext with a VideoSegment list. Here is an example with a single 21..42s segment:

from google.cloud import videointelligence
from google.cloud.videointelligence import enums, types

video_client = videointelligence.VideoIntelligenceServiceClient()

gs_video_path = f'gs://{bucket_name}/{videodata.video.path}{videodata.video.name}'
features = [enums.Feature.OBJECT_TRACKING]
segment = types.VideoSegment()
segment.start_time_offset.FromSeconds(21)
segment.end_time_offset.FromSeconds(42)
context = types.VideoContext(segments=[segment])

operation = video_client.annotate_video(
    gs_video_path,
    features=features,
    video_context=context)

If you want more examples, I recently wrote this tutorial: https://codelabs.developers.google.com/codelabs/cloud-video-intelligence-python3


问:
NodeJS check if object property is not null
I'm working on nodejs and I want to check if my object property is not null when uses a filter :

propositions = propositions.filter((prop) => {
  return prop.issuer.city.equals(req.user.city._id);
});
```

<p><code>prop.issuer</code> may be null some time and I want to avoid this comparison when it's null! </p>

<p>I tried this but it's not worked :</p>

<pre class="lang-js prettyprint-override"><code>propositions = propositions.filter((prop) => {
  return prop.issuer?.city.equals(req.user.city._id);
});
</code>```

答:
The ?. syntax you used is next generation JS and not supported by all browsers (not sure if it supported in Node or not, but if it is, probably not supported in all versions of Node).

```<code>return prop.issuer?.city.equals(req.user.city._id)
</code>```

You can just use simple if statements to overcome this problem though (that is what happens behind the scenes in NextGen JS tools like Babel).

Below is an example:

```<code>propositions = propositions.filter(prop => {

          //this if will allow all items with props.issuer to pass through
          //could return false if you want to filter out anything without prop.issuer instead
          //Note null==undefined in JavaScript, don't need to check both
          if(prop.issuer==undefined){return true;}

          //below will only be made if prop.issuer is not null or undefined
          return prop.issuer.city.equals(req.user.city._id)
        })
</code>```

Body:
I'm working on nodejs and I want to check if my object property is not null when uses a filter :

propositions = propositions.filter((prop) => {
  return prop.issuer.city.equals(req.user.city._id);
});

prop.issuer may be null some time and I want to avoid this comparison when it's null!

I tried this but it's not worked :

propositions = propositions.filter((prop) => {
  return prop.issuer?.city.equals(req.user.city._id);
});

Body:
The ?. syntax you used is next generation JS and not supported by all browsers (not sure if it supported in Node or not, but if it is, probably not supported in all versions of Node).

return prop.issuer?.city.equals(req.user.city._id)

You can just use simple if statements to overcome this problem though (that is what happens behind the scenes in NextGen JS tools like Babel).

Below is an example:

propositions = propositions.filter(prop => {

          //this if will allow all items with props.issuer to pass through
          //could return false if you want to filter out anything without prop.issuer instead
          //Note null==undefined in JavaScript, don't need to check both
          if(prop.issuer==undefined){return true;}

          //below will only be made if prop.issuer is not null or undefined
          return prop.issuer.city.equals(req.user.city._id)
        })


问:
/// <reference types= "cypress" /> not enabling intellisense in VS code
I'm having a problem trying to get code completion for Cypress while I'm using JS. I've tried following every bit of documentation I could found, but I don't find these comprehensive enough.</p>

答:
I just added

```<code>  "compilerOptions": {
    "types": ["cypress"]
  }
</code>```

to the object in the tsconfig.json file that was in the root cypress directory. I then chose "Restart TS Server" from the Command Palette and that sorted things out for me.

Body:
I just added

  "compilerOptions": {
    "types": ["cypress"]
  }

to the object in the tsconfig.json file that was in the root cypress directory. I then chose "Restart TS Server" from the Command Palette and that sorted things out for me.


问:
Count played matchdays in html-table via simple html dom
I want to find the amount of days overall, the amount of days already played of a schedule .htm-file using simple html dom.

The .htm-file looks like this:

```<code><tr><th>November 1 2020</th></tr>
<tr><th>visitor</th><th>score</th><th>home</th><th>score</th></tr>
<tr><td><a href="Wizards.htm">Wizards</a></td><td>120</td><td><a href="Hawks.htm">Hawks</a></td>111<td></td></tr>
<tr><td><a href="Celtics.htm">Celtics</a></td><td>98</td><td><a href="Heat.htm">Heat</a></td><td>108</td></tr>

<tr><th>November 2 2020</th></tr>
<tr><th>visitor</th><th>score</th><th>home</th><th>score</th></tr>
<tr><td><a href="Nets.htm">Nets</a></td><td>95</td><td><a href="Cavaliers.htm">Cavaliers</a></td>98<td></td></tr>
<tr><td><a href="Knicks.htm">Knicks</a></td><td>110</td><td><a href="Hornets.htm">Hornets</a></td><td>100</td></tr>

<tr><th>November 3 2020</th></tr>
<tr><th>visitor</th><th>score</th><th>home</th><th>score</th></tr>
<tr><td><a href="Thunder.htm">Thunder</a></td><td></td><td><a href="Timberwolves.htm">Timberwolves</a></td><td></td></tr>
<tr><td><a href="Trailblazers.htm">Trailblazers</a></td><td></td><td><a href="Lakers.htm">Lakers
... and so on...
</code>```

Please note, that the amount of games could vary each day.
In the example above the overall amount would be = 3, played = 2, unplayed = 1.

Thus far I've come up with this:

```<code>$days = 0;
$days_played = 0;
$days_unplayed = $days - $days_played;

// find every row
foreach($table->find('tr') as $row) {

    // if row contains month then add a match-day
    if (strpos($row->find('th', 0)), 'November') OR
        strpos($row->find('th', 0)), 'December') OR
        strpos($row->find('th', 0)), 'January') OR
        strpos($row->find('th', 0)), 'February') OR
        strpos($row->find('th', 0)), 'March') OR
        strpos($row->find('th', 0)), 'April') OR
        strpos($row->find('th', 0)), 'May') !== false) {
            $days = $days + 1;
}
</code>```

I understand this isn't the most beautiful solution, but it works so far.

My problem is, that I don't know how to get the days, which contain played / scored games. The games itself I can find with this...

```<code>$row->find('td', 1)
</code>```

... since the second column of a row with tds always contains a score. But I need to count only one of them foreach matchday, otherwise I would come up with the amount of played games and not the match-days.

Since I'm stuck here, I would really appreciate an input. Thanks in advance.

答:
If you want to check for the month and the day, one option could be to use a DateTime using DateTime::createFromFormat and check for the month name and day name.

This page has an overview of the different formats

```<code>$months = ["November", "December"];
foreach($table->find('tr') as $row) {
    $res = $row->find('th', 0);
    if ($res && $counter%4 ===  0) {
        $dateTime = DateTime::createFromFormat("F d Y", $res->innertext());
        $month = $dateTime->format("F");
        $day = $dateTime->format("l");

        if (in_array($month, $months) && $day === "Sunday") { // I don't know the play day
            $days = $days + 1;
        }

    }
    $counter++;
}

var_dump($days);
</code>```

Output

```<code>1
</code>```

Body:
I want to find the amount of days overall, the amount of days already played of a schedule .htm-file using simple html dom.

The .htm-file looks like this:

November 1 2020

visitor	score	home	score

Wizards	120	Hawks	111

Celtics	98	Heat	108

November 2 2020

visitor	score	home	score

Nets	95	Cavaliers	98

Knicks	110	Hornets	100

November 3 2020

visitor	score	home	score

Thunder		Timberwolves

Trailblazers		Lakers
... and so on...

Please note, that the amount of games could vary each day.
In the example above the overall amount would be = 3, played = 2, unplayed = 1.

Thus far I've come up with this:

$days = 0;
$days_played = 0;
$days_unplayed = $days - $days_played;

// find every row
foreach($table->find('tr') as $row) {

    // if row contains month then add a match-day
    if (strpos($row->find('th', 0)), 'November') OR
        strpos($row->find('th', 0)), 'December') OR
        strpos($row->find('th', 0)), 'January') OR
        strpos($row->find('th', 0)), 'February') OR
        strpos($row->find('th', 0)), 'March') OR
        strpos($row->find('th', 0)), 'April') OR
        strpos($row->find('th', 0)), 'May') !== false) {
            $days = $days + 1;
}

I understand this isn't the most beautiful solution, but it works so far.

My problem is, that I don't know how to get the days, which contain played / scored games. The games itself I can find with this...

$row->find('td', 1)

... since the second column of a row with tds always contains a score. But I need to count only one of them foreach matchday, otherwise I would come up with the amount of played games and not the match-days.

Since I'm stuck here, I would really appreciate an input. Thanks in advance.

Body:
If you want to check for the month and the day, one option could be to use a DateTime using DateTime::createFromFormat and check for the month name and day name.

This page has an overview of the different formats

$months = ["November", "December"];
foreach($table->find('tr') as $row) {
    $res = $row->find('th', 0);
    if ($res && $counter%4 ===  0) {
        $dateTime = DateTime::createFromFormat("F d Y", $res->innertext());
        $month = $dateTime->format("F");
        $day = $dateTime->format("l");

        if (in_array($month, $months) && $day === "Sunday") { // I don't know the play day
            $days = $days + 1;
        }

    }
    $counter++;
}

var_dump($days);

Output

1


问:
how arguments are passed to __init__ in classes
Hello I am trying to understand __init__ in class in Python.I understood how classes work but i could not understand 1 thing
here is code:

```<code>class Computer:

    def __init__(self, name, cpu, ram, hdd, ssd):
        self.name = name
        self.cpu = cpu
        self.ram = ram
        self.hdd = hdd
        self.ssd = ssd
    def config(self):
        print("Configuration of computer is: ", self.name, self.cpu, self.ram, self.hdd, self.ssd )

computer1 = Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB")
computer1.config()
</code>```

why and how arguments Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB") are passed to __init__(self, name, cpu, ram, hdd, ssd) automatically?why we are writing this arguments in class parentheses and not separately like this:

```<code> computer1.__init__("HP ", "i7 ", "16gb ", "1TB ", "256GB")
</code>```

how the code can understand  that arguments written in Computer's parentheses have to be passed to __init__ ?

答:
This is how python works.
Probably it was designed like that because some classes/structures are written in pure C.

For example.
When you want to implement custom class and implement for it len() function, so you could get length of it by calling len(instance_of_your_class). Then all what you have to do is implement method __len__() in your class.

On the other hand, you have class list in python. This class is implement in C, cause it has to be very fast. Then when you call len(instance_of_list) interpreted will call __len__, which will call equavilent function in C.

From this design comes lot of benefits. One example is method __getitem__. You implement so you could be able to get elements with instalce_of_class[2]. But it also give you ability to use in (if value in instance_of_class).

You can read about methods like that. In python jargon they are dunder methods.

Body:
Hello I am trying to understand __init__ in class in Python.I understood how classes work but i could not understand 1 thing
here is code:

class Computer:

    def __init__(self, name, cpu, ram, hdd, ssd):
        self.name = name
        self.cpu = cpu
        self.ram = ram
        self.hdd = hdd
        self.ssd = ssd
    def config(self):
        print("Configuration of computer is: ", self.name, self.cpu, self.ram, self.hdd, self.ssd )

computer1 = Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB")
computer1.config()

why and how arguments Computer("HP ", "i7 ", "16gb ", "1TB ", "256GB") are passed to __init__(self, name, cpu, ram, hdd, ssd) automatically?why we are writing this arguments in class parentheses and not separately like this:

 computer1.__init__("HP ", "i7 ", "16gb ", "1TB ", "256GB")

how the code can understand  that arguments written in Computer's parentheses have to be passed to __init__ ?


问:
Implement Quartz for Cron Scheduling with Spring Scheduler
```<code>@Component
public class QuartzConfig implements Job{

    @Autowired
    private JobService jobService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        System.out.println("Check Status");
        jobService.checkQueueStatus();
    }
</code>```

In quartz.properties file I have added this detail:

```<code># thread-pool
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount=2
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true

# job-store
# Enable this property for RAMJobStore
org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore
</code>```

How can I give the details about the job and trigger for Cron Scheduling?
Please help with the detailed flow.

答:
There are plenty of examples on the web showing you how to integrate Quartz and Spring. You may want to check one of our test web apps available on GitHub:

https://github.com/quartzdesk/quartzdesk-test-webapps/blob/master/quartzdesk-test-quartz-v2-4-x/quartzdesk-test-quartz-v2-4-x-logback/src/main/webapp/WEB-INF/spring/applicationContext.xml

Search for "quartzScheduler" to find the Quartz scheduler bean and then scroll down to see  jobDetails and triggers attributes.

Body:
@Component
public class QuartzConfig implements Job{

    @Autowired
    private JobService jobService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        System.out.println("Check Status");
        jobService.checkQueueStatus();
    }

In quartz.properties file I have added this detail:

# thread-pool
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount=2
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true

# job-store
# Enable this property for RAMJobStore
org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore

How can I give the details about the job and trigger for Cron Scheduling?
Please help with the detailed flow.