问:
Pygame wall sprite collision
I am making a roguelike game, but I am beginner when it comes to coding. I already have my character moving, my wall and floor sprites, but there is some error in my code that allows the character to move through walls.

I used the block_path to choose between the floor and wall tile and I tried to use it then to recognize the wall but it didn't really work.

Next, you can see my code:

```<code>screenWidth = 800
screenHeight = 600
mapHeight = 30
mapWidth = 30
cellWidth = 32
cellHeight = 32

screen = pygame.display.set_mode((screenWidth, screenHeight))
walkRight = [pygame.image.load('model/r1.png'), pygame.image.load('model/r2.png'), pygame.image.load('model/r3.png'), pygame.image.load('model/r4.png'), pygame.image.load('model/r5.png'), pygame.image.load('model/r6.png')]
walkLeft = [pygame.image.load('model/l1.png'), pygame.image.load('model/l2.png'), pygame.image.load('model/l3.png'), pygame.image.load('model/l4.png'), pygame.image.load('model/l5.png'), pygame.image.load('model/l6.png')]
walkUp = [pygame.image.load('model/u1.png'), pygame.image.load('model/u2.png'), pygame.image.load('model/u3.png'), pygame.image.load('model/u4.png'), pygame.image.load('model/u5.png'), pygame.image.load('model/u6.png')]
Floor = pygame.image.load("map/floor.jpg")
wallRight = pygame.image.load("map/rightwall.png")
</code>```

`

```<code>class struc_Tile():
    def __init__(self,block_path):
        self.block_path = block_path`

class player(object):
    def __init__(self,x,y,width,height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.left = False
        self.right = False
        self.up = False
        self.down = False
        self.walkCount = 0

    def draw(self,screen):
        if self.walkCount + 1 >= 18:
            self.walkCount = 0

        elif self.left:
            screen.blit(walkLeft[self.walkCount//3], (self.x,self.y))
            self.walkCount += 1
        elif self.right:
            screen.blit(walkRight[self.walkCount//3], (self.x,self.y))
            self.walkCount += 1
        elif self.up:
            screen.blit(walkUp[self.walkCount//3], (self.x,self.y))
            self.walkCount += 1
        elif self.down:
            screen.blit(walkDown[self.walkCount//3], (self.x,self.y))
            self.walkCount += 1
        else:
            screen.blit(Standing[self.walkCount//3], (self.x,self.y))
            self.walkCount = 0

    def move(self,dx,dy):
        if gamemap[self.x + dx][self.y + dy].block_path == False:
            self.x += dx
            self.y += dy

def createmap():
    newmap = [[struc_Tile(False) for y in range(0,mapHeight)] for x in range (0,mapWidth) ]
    newmap[10][10].block_path = True
    newmap[10][15].block_path = True

    return newmap
        def drawmap(maptodraw):

    for x in range(0,mapWidth):
        for y in range(0,mapHeight):
            if maptodraw[x][y].block_path == True:
                screen.blit(wallRight, (x*cellWidth, y*cellHeight))
            else:
                screen.blit(Floor, (x*cellWidth, y*cellHeight)
def redrawgamewindow():
screen.blit(bg, (0, 0))
drawmap(gamemap)
character.draw(screen)
pygame.display.update()

pygame.init()
gamemap = createmap()
clock = pygame.time.Clock()
character = player(0, 0, 32,32)

run = True
while run:
clock.tick(18)

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

        run = False

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and character.x > character.vel:
    character.x -= character.vel
    character.left = True
    character.right = False
    character.up = False
    character.down = False
    character.standing = False

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

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

redrawgamewindow()
</code>```

答:
Changing your createmap() function to something like this will create a 5 pixel buffer on the boreder of your map. The reason I made it 5 pixels is because that's what your character movement is.

I would suggest putting in some actual character collision to test whether you're out of bounds regardless of speed though.

EDIT: I've included the full code since the changes I've made are easier to understand if I show them.

I've changed your image lists to a dict of list since they're easier to call that way. The grid you asked for is 30x30. Since you showed a 32x32 cell width I changed the map to 960 x 960.

I've extended your move method to check for collision to see if it can move before it does. I've also removed your redraw() function since it was easier to just move your redraw down. If you wish, you can add it back in but for this example, I removed it.

```<code>import pygame

# Based on the paths in your image
# This should work for your image paths
image = pygame.image.load('model/standing1.png')
Standing = pygame.transform.scale(image, (32, 32))
image = pygame.image.load('map/floor.jpg')
Floor = pygame.transform.scale(image, (32, 32))
image = pygame.image.load('map/rightwall.png')
wallRight = pygame.transform.scale(image, (32, 32))

walkLeft = []
walkRight = []
walkUp = []
walkDown = []

for i in range(1, 19):
    image = pygame.image.load('model/r' + str(i) + '.png')
    walkRight.append(pygame.transform.scale(image, (32, 32)))

    image = pygame.image.load('model/l' + str(i) + '.png')
    walkLeft.append(pygame.transform.scale(image, (32, 32)))

    image = pygame.image.load('model/u' + str(i) + '.png')
    walkUp.append(pygame.transform.scale(image, (32, 32)))

    image = pygame.image.load('model/d' + str(i) + '.png')
    walkDown.append(pygame.transform.scale(image, (32, 32)))

class struc_Tile():
    def __init__(self, block_path):
        self.block_path = block_path

class player(object):
    def __init__(self,x,y,width,height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.walkCount = 0

        # do something like this with your images
        # if you keep your lists in a dict you can avoid
        # all your boolean direction variables and
        # the lengthy if else statement
        self.images = {}
        self.images['walkleft'] = walkLeft[:]
        self.images['walkright'] = walkRight[:]
        self.images['walkup'] = walkUp[:]
        self.images['walkdown'] = walkDown[:]

    def draw(self, screen, direction):
        if self.walkCount + 1 >= 18:
            self.walkCount = 0

        # since standing is not in your dict check for that first
        if direction == 'standing':
            screen.blit(Standing, (self.x,self.y))
            self.walkCount = 0
        else:
            screen.blit(self.images[direction][self.walkCount], (self.x,self.y))
            self.walkCount += 1

    def can_move(self, dx, dy):
        # with the buffer created around the border of the map
        # you shouldn't have issues with
        # index out of bounds exceptions
        # EDIT: added better collision
        new_x = self.x + dx
        new_y = self.y + dy
        if gamemap[new_x][new_y].block_path == False:
            if gamemap[new_x + cellWidth][new_y].block_path == False:
                if gamemap[new_x][new_y + cellHeight].block_path == False:
                    if gamemap[new_x + cellWidth][new_y + cellHeight].block_path == False:
                        self.x += dx
                        self.y += dy
                        return True

def createmap():
    newmap = [[struc_Tile(False) for y in range(0, mapHeight)] for x in range (0,mapWidth)]

    # give our upper/left borders a cell width buffer
    # and our bottom/right borders a 2 cell width buffer
    # since blit uses the upper left corner this should account
    # for the sprite width
    # EDIT: Fixed this to accommodate the better collision
    for x in range(0, mapWidth):
        for y in range (0, mapHeight):
            if y < 32 or y + cellWidth >= mapHeight:
                newmap[x][y].block_path = True
            elif x < 32 or x + cellWidth >= mapWidth:
                newmap[x][y].block_path = True

    return newmap

def drawmap(maptodraw):
    # only blit at cellwidth and height intervals
    for x in range(0, mapWidth, cellWidth):
        for y in range(0, mapHeight, cellHeight):
            if maptodraw[x][y].block_path == True:
                screen.blit(wallRight, (x, y))
            else:
                screen.blit(Floor, (x, y))

# Added this function which lets you block or unblock a cell
# simply call like gamemap = block_element(5, 10, gamemap)
# this will block the 6th cell on the x axis and 11th on the y axis
# to unblock a cell call it with block=False
def block_element(x, y, maptoblock, block=True):
    x_cells = int(mapWidth / cellWidth)
    y_cells = int(mapHeight / cellHeight)

    start_x = int(x * cellWidth)
    start_y = int(y * cellHeight)

    end_x = start_x + cellWidth
    end_y = start_y + cellHeight

    print(start_x, end_x)

    if x >= 0 and x < x_cells:
        if y >= 0 and y < y_cells:
            for x in range(start_x, end_x):
                for y in range(start_y, end_y):
                    maptoblock[x][y].block_path = block

    return maptoblock

pygame.init()

mapHeight = 960
mapWidth = 960

cellWidth = 32
cellHeight = 32

screen = pygame.display.set_mode((mapWidth, mapHeight))

gamemap = createmap()
# blocking/unblocking example
gamemap = block_element(5, 10, gamemap)
gamemap = block_element(0, 8, gamemap, block=False)
gamemap = block_element(0, 9, gamemap, block=False)

clock = pygame.time.Clock()
character = player(64, 64, 32, 32)

run = True
while run:
    clock.tick(18)
    pygame.display.update()

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

            run = False
    # I just used fill since I didn't have a bg image handy
    screen.fill((0, 0, 0))
    drawmap(gamemap)

    # handle the keypresses
    # first check if the character can move that much
    # then draw the movement
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and character.can_move(0 - character.vel, 0):
        character.draw(screen, 'walkleft')
    elif keys[pygame.K_RIGHT] and character.can_move(character.vel, 0):
        character.draw(screen, 'walkright')
    elif keys[pygame.K_UP] and character.can_move(0, 0 - character.vel):
        character.draw(screen, 'walkup')
    elif keys[pygame.K_DOWN] and character.can_move(0, character.vel):
        character.draw(screen, 'walkdown')
    else:
        character.draw(screen, 'standing')

</code>```

Title: Pygame wall sprite collision

Body:
I am making a roguelike game, but I am beginner when it comes to coding. I already have my character moving, my wall and floor sprites, but there is some error in my code that allows the character to move through walls.

I used the block_path to choose between the floor and wall tile and I tried to use it then to recognize the wall but it didn't really work.

Next, you can see my code:

screenWidth = 800
screenHeight = 600
mapHeight = 30
mapWidth = 30
cellWidth = 32
cellHeight = 32

screen = pygame.display.set_mode((screenWidth, screenHeight))
walkRight = [pygame.image.load('model/r1.png'), pygame.image.load('model/r2.png'), pygame.image.load('model/r3.png'), pygame.image.load('model/r4.png'), pygame.image.load('model/r5.png'), pygame.image.load('model/r6.png')]
walkLeft = [pygame.image.load('model/l1.png'), pygame.image.load('model/l2.png'), pygame.image.load('model/l3.png'), pygame.image.load('model/l4.png'), pygame.image.load('model/l5.png'), pygame.image.load('model/l6.png')]
walkUp = [pygame.image.load('model/u1.png'), pygame.image.load('model/u2.png'), pygame.image.load('model/u3.png'), pygame.image.load('model/u4.png'), pygame.image.load('model/u5.png'), pygame.image.load('model/u6.png')]
Floor = pygame.image.load("map/floor.jpg")
wallRight = pygame.image.load("map/rightwall.png")

`

class struc_Tile():
    def __init__(self,block_path):
        self.block_path = block_path`

class player(object):
    def __init__(self,x,y,width,height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.left = False
        self.right = False
        self.up = False
        self.down = False
        self.walkCount = 0

    def draw(self,screen):
        if self.walkCount + 1 >= 18:
            self.walkCount = 0

        elif self.left:
            screen.blit(walkLeft[self.walkCount//3], (self.x,self.y))
            self.walkCount += 1
        elif self.right:
            screen.blit(walkRight[self.walkCount//3], (self.x,self.y))
            self.walkCount += 1
        elif self.up:
            screen.blit(walkUp[self.walkCount//3], (self.x,self.y))
            self.walkCount += 1
        elif self.down:
            screen.blit(walkDown[self.walkCount//3], (self.x,self.y))
            self.walkCount += 1
        else:
            screen.blit(Standing[self.walkCount//3], (self.x,self.y))
            self.walkCount = 0

    def move(self,dx,dy):
        if gamemap[self.x + dx][self.y + dy].block_path == False:
            self.x += dx
            self.y += dy

def createmap():
    newmap = [[struc_Tile(False) for y in range(0,mapHeight)] for x in range (0,mapWidth) ]
    newmap[10][10].block_path = True
    newmap[10][15].block_path = True

    return newmap
        def drawmap(maptodraw):

    for x in range(0,mapWidth):
        for y in range(0,mapHeight):
            if maptodraw[x][y].block_path == True:
                screen.blit(wallRight, (x*cellWidth, y*cellHeight))
            else:
                screen.blit(Floor, (x*cellWidth, y*cellHeight)
def redrawgamewindow():
screen.blit(bg, (0, 0))
drawmap(gamemap)
character.draw(screen)
pygame.display.update()

pygame.init()
gamemap = createmap()
clock = pygame.time.Clock()
character = player(0, 0, 32,32)

run = True
while run:
clock.tick(18)

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

        run = False

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and character.x > character.vel:
    character.x -= character.vel
    character.left = True
    character.right = False
    character.up = False
    character.down = False
    character.standing = False

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

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

redrawgamewindow()

Body:
Changing your createmap() function to something like this will create a 5 pixel buffer on the boreder of your map. The reason I made it 5 pixels is because that's what your character movement is.

I would suggest putting in some actual character collision to test whether you're out of bounds regardless of speed though.

EDIT: I've included the full code since the changes I've made are easier to understand if I show them.

I've changed your image lists to a dict of list since they're easier to call that way. The grid you asked for is 30x30. Since you showed a 32x32 cell width I changed the map to 960 x 960.

I've extended your move method to check for collision to see if it can move before it does. I've also removed your redraw() function since it was easier to just move your redraw down. If you wish, you can add it back in but for this example, I removed it.

import pygame

# Based on the paths in your image
# This should work for your image paths
image = pygame.image.load('model/standing1.png')
Standing = pygame.transform.scale(image, (32, 32))
image = pygame.image.load('map/floor.jpg')
Floor = pygame.transform.scale(image, (32, 32))
image = pygame.image.load('map/rightwall.png')
wallRight = pygame.transform.scale(image, (32, 32))

walkLeft = []
walkRight = []
walkUp = []
walkDown = []

for i in range(1, 19):
    image = pygame.image.load('model/r' + str(i) + '.png')
    walkRight.append(pygame.transform.scale(image, (32, 32)))

    image = pygame.image.load('model/l' + str(i) + '.png')
    walkLeft.append(pygame.transform.scale(image, (32, 32)))

    image = pygame.image.load('model/u' + str(i) + '.png')
    walkUp.append(pygame.transform.scale(image, (32, 32)))

    image = pygame.image.load('model/d' + str(i) + '.png')
    walkDown.append(pygame.transform.scale(image, (32, 32)))

class struc_Tile():
    def __init__(self, block_path):
        self.block_path = block_path

class player(object):
    def __init__(self,x,y,width,height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.walkCount = 0

        # do something like this with your images
        # if you keep your lists in a dict you can avoid
        # all your boolean direction variables and
        # the lengthy if else statement
        self.images = {}
        self.images['walkleft'] = walkLeft[:]
        self.images['walkright'] = walkRight[:]
        self.images['walkup'] = walkUp[:]
        self.images['walkdown'] = walkDown[:]

    def draw(self, screen, direction):
        if self.walkCount + 1 >= 18:
            self.walkCount = 0

        # since standing is not in your dict check for that first
        if direction == 'standing':
            screen.blit(Standing, (self.x,self.y))
            self.walkCount = 0
        else:
            screen.blit(self.images[direction][self.walkCount], (self.x,self.y))
            self.walkCount += 1

    def can_move(self, dx, dy):
        # with the buffer created around the border of the map
        # you shouldn't have issues with
        # index out of bounds exceptions
        # EDIT: added better collision
        new_x = self.x + dx
        new_y = self.y + dy
        if gamemap[new_x][new_y].block_path == False:
            if gamemap[new_x + cellWidth][new_y].block_path == False:
                if gamemap[new_x][new_y + cellHeight].block_path == False:
                    if gamemap[new_x + cellWidth][new_y + cellHeight].block_path == False:
                        self.x += dx
                        self.y += dy
                        return True

def createmap():
    newmap = [[struc_Tile(False) for y in range(0, mapHeight)] for x in range (0,mapWidth)]

    # give our upper/left borders a cell width buffer
    # and our bottom/right borders a 2 cell width buffer
    # since blit uses the upper left corner this should account
    # for the sprite width
    # EDIT: Fixed this to accommodate the better collision
    for x in range(0, mapWidth):
        for y in range (0, mapHeight):
            if y < 32 or y + cellWidth >= mapHeight:
                newmap[x][y].block_path = True
            elif x < 32 or x + cellWidth >= mapWidth:
                newmap[x][y].block_path = True

    return newmap

def drawmap(maptodraw):
    # only blit at cellwidth and height intervals
    for x in range(0, mapWidth, cellWidth):
        for y in range(0, mapHeight, cellHeight):
            if maptodraw[x][y].block_path == True:
                screen.blit(wallRight, (x, y))
            else:
                screen.blit(Floor, (x, y))

# Added this function which lets you block or unblock a cell
# simply call like gamemap = block_element(5, 10, gamemap)
# this will block the 6th cell on the x axis and 11th on the y axis
# to unblock a cell call it with block=False
def block_element(x, y, maptoblock, block=True):
    x_cells = int(mapWidth / cellWidth)
    y_cells = int(mapHeight / cellHeight)

    start_x = int(x * cellWidth)
    start_y = int(y * cellHeight)

    end_x = start_x + cellWidth
    end_y = start_y + cellHeight

    print(start_x, end_x)

    if x >= 0 and x < x_cells:
        if y >= 0 and y < y_cells:
            for x in range(start_x, end_x):
                for y in range(start_y, end_y):
                    maptoblock[x][y].block_path = block

    return maptoblock

pygame.init()

mapHeight = 960
mapWidth = 960

cellWidth = 32
cellHeight = 32

screen = pygame.display.set_mode((mapWidth, mapHeight))

gamemap = createmap()
# blocking/unblocking example
gamemap = block_element(5, 10, gamemap)
gamemap = block_element(0, 8, gamemap, block=False)
gamemap = block_element(0, 9, gamemap, block=False)

clock = pygame.time.Clock()
character = player(64, 64, 32, 32)

run = True
while run:
    clock.tick(18)
    pygame.display.update()

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

            run = False
    # I just used fill since I didn't have a bg image handy
    screen.fill((0, 0, 0))
    drawmap(gamemap)

    # handle the keypresses
    # first check if the character can move that much
    # then draw the movement
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and character.can_move(0 - character.vel, 0):
        character.draw(screen, 'walkleft')
    elif keys[pygame.K_RIGHT] and character.can_move(character.vel, 0):
        character.draw(screen, 'walkright')
    elif keys[pygame.K_UP] and character.can_move(0, 0 - character.vel):
        character.draw(screen, 'walkup')
    elif keys[pygame.K_DOWN] and character.can_move(0, character.vel):
        character.draw(screen, 'walkdown')
    else:
        character.draw(screen, 'standing')


来源: stackexchange

问:
Perform a lookup between C# Lists and return matched where value is minimum
I have two lists:

```<code>var qtys = new List<InventoryQuantity>()
{
    new InventoryQuantity() { WarehouseId = 1, QuantityInWarehouse = 0 },
    new InventoryQuantity() { WarehouseId = 2, QuantityInWarehouse = 452 },
    new InventoryQuantity() { WarehouseId = 3, QuantityInWarehouse = 184 },
    new InventoryQuantity() { WarehouseId = 4, QuantityInWarehouse = 328 },
    new InventoryQuantity() { WarehouseId = 5, QuantityInWarehouse = 0 },
};

var times = new List<WarehouseTransitTime>()
{
    new WarehouseTransitTime() { WarehouseId = 1, TransitDays = 1 },
    new WarehouseTransitTime() { WarehouseId = 2, TransitDays = 4 },
    new WarehouseTransitTime() { WarehouseId = 3, TransitDays = 2 },
    new WarehouseTransitTime() { WarehouseId = 4, TransitDays = 3 },
    new WarehouseTransitTime() { WarehouseId = 5, TransitDays = 5 },
};

class InventoryQuantity
{
    public int WarehouseId { get; set; }
    public int QuantityInWarehouse { get; set; }
}

class WarehouseTransitTime
{
    public int WarehouseId { get; set; }
    public int TransitDays { get; set; }
}
</code>```

I need to return the WarehouseId from qtys where the Quantity > 0 and the WarehouseId equals the minimum transit days WarehouseId in times.

I know I can do something like below but seems clunky and there must be an elegant solution.

```<code>    public int NearestWarehouse()
    {
        var withQty = qtys.Where(i => i.QuantityInWarehouse > 0);
        var orderedTransit = times.OrderBy(tt => tt.TransitDays).ToList();
        //loop and compare
    }
</code>```

Example data:

qtys

```<code>WarehouseId | Quantity
1           | 0
2           | 452
3           | 184
4           | 328
5           | 0
</code>```

times

```<code>WarehouseId | TransitTime
1           | 1
2           | 4
3           | 2
4           | 3
5           | 5
</code>```

Expected output would be 3, because warehouse 3 has inventory and the shortest transit time (2)

答:
You can do it like this..</p>

```<code>   var withQty = (from q in qtys
                       join t in times on q.WarehouseId equals t.WarehouseId
                       where q.QuantityInWarehouse > 0
                       select new { q.WarehouseId, t.TransitDays })
                       .OrderBy(item => item.TransitDays).FirstOrDefault();

   return withQty?.WarehouseId ?? 0;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two lists:

var qtys = new List<InventoryQuantity>()
{
    new InventoryQuantity() { WarehouseId = 1, QuantityInWarehouse = 0 },
    new InventoryQuantity() { WarehouseId = 2, QuantityInWarehouse = 452 },
    new InventoryQuantity() { WarehouseId = 3, QuantityInWarehouse = 184 },
    new InventoryQuantity() { WarehouseId = 4, QuantityInWarehouse = 328 },
    new InventoryQuantity() { WarehouseId = 5, QuantityInWarehouse = 0 },
};

var times = new List<WarehouseTransitTime>()
{
    new WarehouseTransitTime() { WarehouseId = 1, TransitDays = 1 },
    new WarehouseTransitTime() { WarehouseId = 2, TransitDays = 4 },
    new WarehouseTransitTime() { WarehouseId = 3, TransitDays = 2 },
    new WarehouseTransitTime() { WarehouseId = 4, TransitDays = 3 },
    new WarehouseTransitTime() { WarehouseId = 5, TransitDays = 5 },
};

class InventoryQuantity
{
    public int WarehouseId { get; set; }
    public int QuantityInWarehouse { get; set; }
}

class WarehouseTransitTime
{
    public int WarehouseId { get; set; }
    public int TransitDays { get; set; }
}

I need to return the WarehouseId from qtys where the Quantity > 0 and the WarehouseId equals the minimum transit days WarehouseId in times.

I know I can do something like below but seems clunky and there must be an elegant solution.

    public int NearestWarehouse()
    {
        var withQty = qtys.Where(i => i.QuantityInWarehouse > 0);
        var orderedTransit = times.OrderBy(tt => tt.TransitDays).ToList();
        //loop and compare
    }

Example data:

qtys

WarehouseId | Quantity
1           | 0
2           | 452
3           | 184
4           | 328
5           | 0

times

WarehouseId | TransitTime
1           | 1
2           | 4
3           | 2
4           | 3
5           | 5

Expected output would be 3, because warehouse 3 has inventory and the shortest transit time (2)

Body:
You can do it like this..

   var withQty = (from q in qtys
                       join t in times on q.WarehouseId equals t.WarehouseId
                       where q.QuantityInWarehouse > 0
                       select new { q.WarehouseId, t.TransitDays })
                       .OrderBy(item => item.TransitDays).FirstOrDefault();

   return withQty?.WarehouseId ?? 0;


问:
How can I reverse a single String in Java 8 using Lambda and Streams?
I have one string say "Aniruddh" and I want to reverse it using lambdas and streams in Java 8. How can I do it?

答:
Given a String of length S, reverse the whole string without reversing the individual words in it. Words are separated by dots.</p>

```<code>String str="abcd.efg.qwerty";

String reversed = Arrays.asList(str.split("\\.")).stream().map(m -> new
StringBuilder(m).reverse().toString()).collect(Collectors.joining("."));

System.out.println(reversed);
</code>```

Body:
Given a String of length S, reverse the whole string without reversing the individual words in it. Words are separated by dots.

String str="abcd.efg.qwerty";

String reversed = Arrays.asList(str.split("\\.")).stream().map(m -> new
StringBuilder(m).reverse().toString()).collect(Collectors.joining("."));

System.out.println(reversed);


问:
How to use 2 Labels in one Conditional tag in Blogger
```<code><b:if cond='data:blog.searchLabel == "Label"'>
<style type='text/css'>
.foa_bg {
  background-image: url(https://site.io/images/covers/image.jpg);
}
</style>
</b:if>
</code>```

I wold like to have in one line 2 or 5 labels.

答:
You can use in operator

```

Body:
You can use in operator

<b:if cond='data:blog.searchLabel in ["Label1","Label2","Label3"]'>
  <style type='text/css'>
    .foa_bg {
       background-image: url(https://site.io/images/covers/image.jpg);
    }
  </style>
</b:if>


问:
SweepGradient Android - How to set start angle for Gradient
I am having a hard time understanding how to use a SweepGradient to show my gradient color from a specific angle on Canvas.

For example: If I have an arc from 1 - 3pm, I would like to provide a Gradient as a Color. The Gradient should start from 2pm.

I have the following code which shows the Color without any gradient applied to it.

```<code> SweepGradient sweepGradient = new
                                SweepGradient(provideRectF().width() / 2, provideRectF().height() / 2,
                                arcColors, new float[]{
                                0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f
                        });

                        Matrix matrix = new Matrix();
                        matrix.postRotate(currentAngle, provideRectF().width() / 2, provideRectF().height() / 2);
                        sweepGradient.setLocalMatrix(matrix);
</code>```

How can I make my Color show the gradient from 2pm (in terms of angle) for the given arc?

答:
This answer is based on the excellent post on SweepGradient by Attila Tanyi.

To get a better understanding of SweepGradient, let's first paint the whole screen with a SweepGradient which is centered in the middle of the screen and shows sections corresponding to a clock face (please note that the area between 1pm and 2pm is a solid color since this is part of your setup):

The positions:

```<code>// positions for a clock face
// note: we need an opening position 0.0f as well as a closing position 1.0f, both of which belong to 3 pm
float[] positions = {0.0f,
            1/12f, 2/12f, 3/12f,
            4/12f, 5/12f, 6/12f,
            7/12f, 8/12f, 9/12f,
            10/12f, 11/12f, 1.0f};
</code>```

The colors:

```<code>int yellow = 0xFFFFFF88;
int blue = 0xFF0088FF;
int white = 0xFFFFFFFF;
int black = 0xFF000000;

// provide as many color values as there are positions
// we want to paint a "normal color" from 1pm to 2pm and then a gradient from 2pm to 3 pm
int[] colors = { black, // the first value is for 3 pm, the sweep starts here
        yellow, // 4
        white,  // 5
        black,  // 6
        white,  // 7
        yellow, // 8
        blue,   // 9
        black,  // 10
        white,  // 11
        black,  // 12
        blue,   // 1 constant color from 1pm to 2pm
        blue,   // 2
        white // the last value also is at 3 pm, the sweep ends here
};
</code>```

Initialising the Path and the Paint:

```<code>private Path circle = new Path();
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

// ...
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(30);
</code>```

I experimented with a custom View and configured the gradient in onLayout(). Since the post is about drawing an arc, I tried a full circle next:

```<code>@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    // use a square rectangle which does not touch the screen borders:
    float squareMaxWidth = Math.min(right - left, bottom - top) - 20;
    RectF circleRect = new RectF(left + 20, top + 20, left + squareMaxWidth, top + squareMaxWidth);
    // draw a full circle
    circle.addArc(circleRect, 180, 360);
    // calculate its center
    float centerH = (circleRect.right + circleRect.left)*0.5f;
    float centerV = (circleRect.bottom + circleRect.top)*0.5f;

    sweepGradient = new SweepGradient(centerH,centerV, colors, positions);
    paint.setShader(sweepGradient);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawPath(circle, paint);
}
</code>```

The result:

Next, let's just draw the border: change the Paint style

```<code>paint.setStyle(Paint.Style.STROKE);
</code>```

And finally, just draw an arc from 1 pm to 3 pm. Remember that the angle for 3 pm is zero and that one section on the clock face corresponds to 30 degrees. So in onLayout() we have

```<code>circle.addArc(circleRect, 300, 60);
</code>```

Another example: if you want to draw an arc from 4:15 pm to 4:45 pm with a gradient starting at 4:33 pm, you get the following picture (colored arc drawn over a full SweepGradient circle with alternating black and white at each "hour")

The colors:

```<code>int[] colors = {
        primaryColor,
        primaryColor,
        accentColor };
</code>```

To calculate the positions one needs to do a little math:

60 minutes = one hour ~ 1/12f

     3 minutes = one hour / 20 ~ 1/240f

      15 minutes = 5 * 3 minutes ~ 5 / 240f = 1 / 48f

      45 minutes = 3 * 15 minutes ~ 1 / 16f

      33 minutes = 11 * 3 minutes ~ 11 / 240f

```<code>float[] positions = {
        (1/12f + 1/48f),   // 4:15 pm
        (1/12f + 11/240f), // 4:33 pm
        (1/12f + 1/16f)    // 4:45 pm
     };
</code>```

Similarly, one can calculate the values for the start angle and sweep angle:

one hour ~ 30 degrees

   one minute ~ 0.5 degrees

```<code>// start at 4:15 pm:
float startAngle = (30 +  15*0.5f);
// sweep for 1/2 hour:
float sweepAngle = 15f;
circle.addArc(circleRect, startAngle, sweepAngle);
</code>```

Body:
I am having a hard time understanding how to use a SweepGradient to show my gradient color from a specific angle on Canvas.

For example: If I have an arc from 1 - 3pm, I would like to provide a Gradient as a Color. The Gradient should start from 2pm.

I have the following code which shows the Color without any gradient applied to it.

 SweepGradient sweepGradient = new
                                SweepGradient(provideRectF().width() / 2, provideRectF().height() / 2,
                                arcColors, new float[]{
                                0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f
                        });

                        Matrix matrix = new Matrix();
                        matrix.postRotate(currentAngle, provideRectF().width() / 2, provideRectF().height() / 2);
                        sweepGradient.setLocalMatrix(matrix);

How can I make my Color show the gradient from 2pm (in terms of angle) for the given arc?

Body:
This answer is based on the excellent post on SweepGradient by Attila Tanyi.

To get a better understanding of SweepGradient, let's first paint the whole screen with a SweepGradient which is centered in the middle of the screen and shows sections corresponding to a clock face (please note that the area between 1pm and 2pm is a solid color since this is part of your setup):

The positions:

// positions for a clock face
// note: we need an opening position 0.0f as well as a closing position 1.0f, both of which belong to 3 pm
float[] positions = {0.0f,
            1/12f, 2/12f, 3/12f,
            4/12f, 5/12f, 6/12f,
            7/12f, 8/12f, 9/12f,
            10/12f, 11/12f, 1.0f};

The colors:

int yellow = 0xFFFFFF88;
int blue = 0xFF0088FF;
int white = 0xFFFFFFFF;
int black = 0xFF000000;

// provide as many color values as there are positions
// we want to paint a "normal color" from 1pm to 2pm and then a gradient from 2pm to 3 pm
int[] colors = { black, // the first value is for 3 pm, the sweep starts here
        yellow, // 4
        white,  // 5
        black,  // 6
        white,  // 7
        yellow, // 8
        blue,   // 9
        black,  // 10
        white,  // 11
        black,  // 12
        blue,   // 1 constant color from 1pm to 2pm
        blue,   // 2
        white // the last value also is at 3 pm, the sweep ends here
};

Initialising the Path and the Paint:

private Path circle = new Path();
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

// ...
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(30);

I experimented with a custom View and configured the gradient in onLayout(). Since the post is about drawing an arc, I tried a full circle next:

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    // use a square rectangle which does not touch the screen borders:
    float squareMaxWidth = Math.min(right - left, bottom - top) - 20;
    RectF circleRect = new RectF(left + 20, top + 20, left + squareMaxWidth, top + squareMaxWidth);
    // draw a full circle
    circle.addArc(circleRect, 180, 360);
    // calculate its center
    float centerH = (circleRect.right + circleRect.left)*0.5f;
    float centerV = (circleRect.bottom + circleRect.top)*0.5f;

    sweepGradient = new SweepGradient(centerH,centerV, colors, positions);
    paint.setShader(sweepGradient);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawPath(circle, paint);
}

The result:

Next, let's just draw the border: change the Paint style

paint.setStyle(Paint.Style.STROKE);

And finally, just draw an arc from 1 pm to 3 pm. Remember that the angle for 3 pm is zero and that one section on the clock face corresponds to 30 degrees. So in onLayout() we have

circle.addArc(circleRect, 300, 60);

Another example: if you want to draw an arc from 4:15 pm to 4:45 pm with a gradient starting at 4:33 pm, you get the following picture (colored arc drawn over a full SweepGradient circle with alternating black and white at each "hour")

The colors:

int[] colors = {
        primaryColor,
        primaryColor,
        accentColor };

To calculate the positions one needs to do a little math:

60 minutes = one hour ~ 1/12f

     3 minutes = one hour / 20 ~ 1/240f

      15 minutes = 5 * 3 minutes ~ 5 / 240f = 1 / 48f

      45 minutes = 3 * 15 minutes ~ 1 / 16f

      33 minutes = 11 * 3 minutes ~ 11 / 240f

float[] positions = {
        (1/12f + 1/48f),   // 4:15 pm
        (1/12f + 11/240f), // 4:33 pm
        (1/12f + 1/16f)    // 4:45 pm
     };

Similarly, one can calculate the values for the start angle and sweep angle:

one hour ~ 30 degrees

   one minute ~ 0.5 degrees

// start at 4:15 pm:
float startAngle = (30 +  15*0.5f);
// sweep for 1/2 hour:
float sweepAngle = 15f;
circle.addArc(circleRect, startAngle, sweepAngle);


问:
terraform import google computer security policy Error reading SecurityPolic Error reading SecurityPolicy googleapi: Error 400: Invalid value
I am trying to import an existing security policy using

```<code>terraform import google_compute_security_policy.testpolicy lunar-11111/testsecuritypolicy
</code>```

I have this defined in my terraform file:

```<code>resource "google_compute_security_policy" "testpolicy" {
  name = "testsecuritypolicy"
}
</code>```

However, this is error I get:

```<code>google_compute_security_policy.testpolicy: Importing from ID "lunar-111111/testsecuritypolicy"...
google_compute_security_policy.testpolicy: Import complete!
  Imported google_compute_security_policy
google_compute_security_policy.testpolicy: Refreshing state... [id=lunar-111111/testsecuritypolicy]

Error: Error reading SecurityPolicy "lunar-111111/testsecuritypolicy":
googleapi: Error 400: Invalid value 'lunar-111111/testsecuritypolicy'.
Values must match the following regular expression:
'[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?|[1-9][0-9]{0,19}', invalidParameter
</code>```

I tried the other import formats listed in https://www.terraform.io/docs/providers/google/r/compute_security_policy.html with the same error.

I am able to create a new security policy using terraform.
Am I missing some configuration?  Any help would be appreciated.

The project name was changed in the above command and error result.

```<code>terraform -version
Terraform v0.12.2
+ provider.google v2.9.0
+ provider.random v2.1.2
</code>```

答:
You can follow GCP documentations on configuring cloud armor security policies and REST resources: securityPolicies.

To understand the error on regular expressions, I found this link that can explain details about the syntax and description.

Body:
I am trying to import an existing security policy using

terraform import google_compute_security_policy.testpolicy lunar-11111/testsecuritypolicy

I have this defined in my terraform file:

resource "google_compute_security_policy" "testpolicy" {
  name = "testsecuritypolicy"
}

However, this is error I get:

google_compute_security_policy.testpolicy: Importing from ID "lunar-111111/testsecuritypolicy"...
google_compute_security_policy.testpolicy: Import complete!
  Imported google_compute_security_policy
google_compute_security_policy.testpolicy: Refreshing state... [id=lunar-111111/testsecuritypolicy]

Error: Error reading SecurityPolicy "lunar-111111/testsecuritypolicy":
googleapi: Error 400: Invalid value 'lunar-111111/testsecuritypolicy'.
Values must match the following regular expression:
'[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?|[1-9][0-9]{0,19}', invalidParameter

I tried the other import formats listed in https://www.terraform.io/docs/providers/google/r/compute_security_policy.html with the same error.

I am able to create a new security policy using terraform.
Am I missing some configuration?  Any help would be appreciated.

The project name was changed in the above command and error result.

terraform -version
Terraform v0.12.2
+ provider.google v2.9.0
+ provider.random v2.1.2


问:
A same suid + system program, different outputs on different systems
I write a simple program named suid.c:

int main(int argc, char* argv[]) {
        system(argv[1]);
}
```

<p>Compile it with gcc then set suid permission (root user now):</p>

```# gcc suid.c -o suid
# chmod +s suid
```

I tried to run ./suid id with the www-data user on different virtual machines, but the output is different.

The output in kali 2019: id=33(www-data) gid=33(www-data) groups=33(www-data)

The output in ubuntu trusty(a old linux): uid=33(www-data) gid=33(www-data) euid=0(root) egid=0(root) groups=0(root),33(www-data)

Why is that? Has anything changed in Linux?

答:
It depends whether /bin/sh is bash or dash on your distribution. Bash always drops setuid/setgid privileges unless invoked with the option -p. Dash doesn't do anything special about privileges.

On Ubuntu, the system function invokes sh, which is /bin/sh, which is dash, which doesn't drop privileges. On Kali, the system function invokes sh, which is /bin/sh, which is bash, which drops privileges. It's a matter of which shell the distribution installs as sh, not of how recent the distribution is.

Bash's behavior can be a security countermeasure, but it isn't a very effective one. It's a second line of defense against misguided configurations or badly written programs that run with privileges that they shouldn't have, and allow untrusted input to functions such as system. However, such programs usually have other holes that allow the potential attacker to attack anyway, such as the ability to write to files.

Body:
I write a simple program named suid.c:

int main(int argc, char* argv[]) {
        system(argv[1]);
}

Compile it with gcc then set suid permission (root user now):

# gcc suid.c -o suid
# chmod +s suid

I tried to run ./suid id with the www-data user on different virtual machines, but the output is different.

The output in kali 2019: id=33(www-data) gid=33(www-data) groups=33(www-data)

The output in ubuntu trusty(a old linux): uid=33(www-data) gid=33(www-data) euid=0(root) egid=0(root) groups=0(root),33(www-data)

Why is that? Has anything changed in Linux?


问:
Should I use Static class for Database connectivity in C#.net?
I have a class which contain all the database connection activities. What i want to know is should i make this class as static then i can call anywhere without creating it.
but the application runs in different pcs in same network in same time.

OR ELSE

should i create a normal class that can be use in other classes by inheriting it?

答:
Do what you're best capable to deal
  with.

The decision of making the data-access classes as static or not has got nothing to do with the purpose of the class in this case (which is purely data-access). More important is the fact is it should co-align with the overall design of your project or system and for you and for team-members it should be easy to maintain. I would recommend to split the classes based on table-access and make them symmetric in terms of design. Having said this, some important concerns that you should be careful about your data-access classes are...

How are you going to deal with life-cycle of the database-connection(s) ?

How are you going to deal with concurrency and caching(if used) ?

ContentLicense: CC BY-SA 3.0


问:
How do you make a dynamic range function in excel with a dynamic start and end cell?
I have n export from a database of financial statement information. It only includes non zero rows. I am trying to use INDEX(MATCH) to copy the information and calculate key figures, KPI's etc. So far no problem.

The problem is the balance sheet contains multiple lines with the same text e.g. 'other receivables', so the basic INDEX(MATCH) will always take the first value. I can't solve it by counting the number of occurences either as if for example 'long term receivables' lacks 'other receivables' then that row is missing.

The solution I tried was using INDEX(MATCH) functions inside the INDEX(Match) 'array' section (first argument). It works fine if only the end point of the array is dynamic, but seizes to work when the starting value is dynamic as well. The idea is to isolate the 'other receivables' in e.g. short term receivables by searching an array starting from 'Short term receivables' and ending in 'Total short term receivables'.

To sum it up, the question is simple: How does one code an array with a dynamic start and end value?

答:
You can construct a dynamic range using either INDEX or OFFSET.

The Index syntax uses the range operator, which is a colon - so INDEX(.. start cell ..):INDEX(.. end cell ..)

The Offset syntax uses an anchor cell and then a calculated row offset to the starting point and  number of rows argument to get to the end point - so OFFSET($Anchor$Cell,row offset to start cell,0,number of rows to end, number of columns)

Use MATCH to find the start and end rows


问:
getting segmentation fault(core dump)after typing all the value in a vector in c++
i have made this code to print a string and int.

```<code> vector<int> nu;

for(int v;cin>>v;)
    nu.push_back(v);

vector<string> la;
for(string c;cin>>c;)
    la.push_back(c);
</code>```

the programme runs and starts taking value but as i put anything other than int to stop the

```<code>for(int v;cin>>v;)
</code>```

part i get segmentation fault.all variables are defined locally so i do not understand why i am getting this error.

EDIT: for printing i have created a function

```<code>void print(vector<string> a,vector<int> b)
{int y=0;
y= b.size();
for(int i=0;i<y;i++)
    {cout<<a[i]<<" "<<b[i]<<"\n";
     }

}
</code>```

答:
You can also try this if it suits:</p>

```<code>void print(vector<string> a,vector<int> b)
{int y=0;
y= b.size();

int x = a.size();

// min(x,y) is the minimum of x and y values
for(int i=0;i< min(x,y);i++)
    {cout<<a[i]<<" "<<b[i]<<"\n";
     }

}
</code>```

Body:
i have made this code to print a string and int.

 vector<int> nu;

for(int v;cin>>v;)
    nu.push_back(v);

vector<string> la;
for(string c;cin>>c;)
    la.push_back(c);

the programme runs and starts taking value but as i put anything other than int to stop the

for(int v;cin>>v;)

part i get segmentation fault.all variables are defined locally so i do not understand why i am getting this error.

EDIT: for printing i have created a function

void print(vector<string> a,vector<int> b)
{int y=0;
y= b.size();
for(int i=0;i<y;i++)
    {cout<<a[i]<<" "<<b[i]<<"\n";
     }

}

Body:
You can also try this if it suits:

void print(vector<string> a,vector<int> b)
{int y=0;
y= b.size();

int x = a.size();

// min(x,y) is the minimum of x and y values
for(int i=0;i< min(x,y);i++)
    {cout<<a[i]<<" "<<b[i]<<"\n";
     }

}


问:
Javascript & HTML - Passing dropdown index value as object property returns undefined
I'm brand new to this language and I've hit a road block. I've searched for a few hours about this specific problem but can't seem to figure out why my situation is so hard to fix. I'm sure I just need a set of eyes that knows what they're looking at.

I'm trying to pass the index of a dropdown select into my Code.gs function so that I can use it elsewhere to select a certain row of a data in a spreadsheet. I set up the object driverPicked and give it the property selected, and then hunt for the selected index property. As I'm really new to this, I'm having a hard time understanding the consequences of nesting properties like this and could use a clue as to how to solve the "TypeError: Cannot read property 'selected' of undefined (line 39, file "Code")" error I've been getting for hours now.

There are so many similar answers but I can't sort out exactly how they apply to me - so forgive me for that!

```<code>var url = "REDACTED";

function doGet(e){

//var x = document.getElementById("driver").selectedIndex;

var driverIndex = userClicked();
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Results_2019");
var listDrivers = ws.getRange(4,1,ws.getRange("A3").getDataRegion().getLastRow(),1).getValues();
var infoHeading = ws.getRange(3, 1, 1, 8).getValues();
var driverInfo = ws.getRange(driverIndex, 1, 1 ,8).getValues();

var tmp = HtmlService.createTemplateFromFile("page");
tmp.title = "GLTC Driver List";
//tmp.listDrivers = listDrivers.map(function(r){r[0];});
tmp.listDrivers = [].concat.apply([], listDrivers);
tmp.infoHeading = [].concat.apply([], infoHeading);
tmp.driverInfo = [].concat.apply([], driverInfo);
tmp.driverIndex = driverIndex;

return tmp.evaluate();

}

function include(filename){
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

function userClicked(driverPicked) {
  console.log(driverPicked);
  var driverName = driverPicked.value;
  return driverName;
}

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <!--Let browser know website is optimized for mobile-->
     <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <!--Import Google Icon Font-->
     <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <?!= include("page-css"); ?>
  </head>
  <body>

    <h1><?= title; ?></h1>

    <div class="input-field">
  <select id="driver">
    <option disabled selected>Choose Driver</option>
    <? for(var i=0;i<listDrivers.length;i++){ ?>
      <option class="selected">
        <?= listDrivers[i]; ?>
      </option>
      <? } ?>
  </select>
</div>

  <h5><?= infoHeading; ?></h5>

  <h5><?= driverInfo; ?></h5>

  <h5><?= driverIndex; ?></h5>

<script>

document.getElementById("driver").addEventListener("change", doStuff); // add onchange listener to the select element instead of options

function doStuff(event) {
  var driverPicked = {};

  driverPicked.driver = event.target.value;
  driverPicked.selected = event.target.options.selectedIndex;
  userClicked(driverPicked);
}

  </script>

    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <?!= include("page-js"); ?>

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

答:
A few issues with the code:

DOM elements' ids have to be unique, so when rendering options you either need to add index to id or use a class name instead.

Instead of click use change event for select elements.

You can access event object as an argument inside doStuff function instead of querying DOM elements manually.
I'm not sure why would you need to get an index, but in order to get driver's name you can do smth like this:

```<code><div class="input-field">
  <select id="driver">
    <option disabled selected>Choose Driver</option>
    <? for(var i=0;i<listDrivers.length;i++){ ?>
      <option class="selected"> // use class instead of id here
        <?= listDrivers[i]; ?>
      </option>
      <? } ?>
  </select>
</div>
</code>```

```<code>document.getElementById("driver").addEventListener("change", doStuff); // add onchange listener to the select element instead of options

function doStuff(event) {
  var driverPicked = {};

  driverPicked.driver = event.target.value;
  driverPicked.selected = event.target.options.selectedIndex;

  google.script.run.userClicked(driverPicked);
}

function userClicked(driverPicked) {

  var driverName = driverPicked.value;
  return driverName;
}
</code>```

Here's a runnable example with some mock select options:

document.getElementById("driver").addEventListener("change", doStuff); // add onchange listener to the select element instead of options

function doStuff(event) {
  var driverPicked = {};

  driverPicked.driver = event.target.value;
  driverPicked.selected = event.target.options.selectedIndex;
  userClicked(driverPicked);
}

function userClicked(driverPicked) {
  console.log(driverPicked);
  var driverName = driverPicked.value;
  return driverName;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="input-field">
  <select id="driver">
    <option disabled selected>Choose Driver</option>
      <option class="selected"> Driver 1</option>
      <option class="selected"> Driver 2</option>
  </select>
</div></code>```

Body:
I'm brand new to this language and I've hit a road block. I've searched for a few hours about this specific problem but can't seem to figure out why my situation is so hard to fix. I'm sure I just need a set of eyes that knows what they're looking at.

I'm trying to pass the index of a dropdown select into my Code.gs function so that I can use it elsewhere to select a certain row of a data in a spreadsheet. I set up the object driverPicked and give it the property selected, and then hunt for the selected index property. As I'm really new to this, I'm having a hard time understanding the consequences of nesting properties like this and could use a clue as to how to solve the "TypeError: Cannot read property 'selected' of undefined (line 39, file "Code")" error I've been getting for hours now.

There are so many similar answers but I can't sort out exactly how they apply to me - so forgive me for that!

var url = "REDACTED";

function doGet(e){

//var x = document.getElementById("driver").selectedIndex;

var driverIndex = userClicked();
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Results_2019");
var listDrivers = ws.getRange(4,1,ws.getRange("A3").getDataRegion().getLastRow(),1).getValues();
var infoHeading = ws.getRange(3, 1, 1, 8).getValues();
var driverInfo = ws.getRange(driverIndex, 1, 1 ,8).getValues();

var tmp = HtmlService.createTemplateFromFile("page");
tmp.title = "GLTC Driver List";
//tmp.listDrivers = listDrivers.map(function(r){r[0];});
tmp.listDrivers = [].concat.apply([], listDrivers);
tmp.infoHeading = [].concat.apply([], infoHeading);
tmp.driverInfo = [].concat.apply([], driverInfo);
tmp.driverIndex = driverIndex;

return tmp.evaluate();

}

function include(filename){
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

function userClicked(driverPicked) {
  console.log(driverPicked);
  var driverName = driverPicked.value;
  return driverName;
}

<!DOCTYPE html>

    <base target="_top">

     <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

     <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <?!= include("page-css"); ?>

<?= title; ?>

  <select id="driver">
    <option disabled selected>Choose Driver</option>
    <? for(var i=0;i<listDrivers.length;i++){ ?>
      <option class="selected">
        <?= listDrivers[i]; ?>
      </option>
      <? } ?>
  </select>

<?= infoHeading; ?>

<?= driverInfo; ?>

<?= driverIndex; ?>

    <?!= include("page-js"); ?>

Body:
A few issues with the code:

DOM elements' ids have to be unique, so when rendering options you either need to add index to id or use a class name instead.

Instead of click use change event for select elements.

You can access event object as an argument inside doStuff function instead of querying DOM elements manually.
I'm not sure why would you need to get an index, but in order to get driver's name you can do smth like this:

<div class="input-field">
  <select id="driver">
    <option disabled selected>Choose Driver</option>
    <? for(var i=0;i<listDrivers.length;i++){ ?>
      <option class="selected"> // use class instead of id here
        <?= listDrivers[i]; ?>
      </option>
      <? } ?>
  </select>
</div>

document.getElementById("driver").addEventListener("change", doStuff); // add onchange listener to the select element instead of options

function doStuff(event) {
  var driverPicked = {};

  driverPicked.driver = event.target.value;
  driverPicked.selected = event.target.options.selectedIndex;

  google.script.run.userClicked(driverPicked);
}

function userClicked(driverPicked) {

  var driverName = driverPicked.value;
  return driverName;
}

Here's a runnable example with some mock select options:

document.getElementById("driver").addEventListener("change", doStuff); // add onchange listener to the select element instead of options

function doStuff(event) {
  var driverPicked = {};

  driverPicked.driver = event.target.value;
  driverPicked.selected = event.target.options.selectedIndex;
  userClicked(driverPicked);
}

function userClicked(driverPicked) {
  console.log(driverPicked);
  var driverName = driverPicked.value;
  return driverName;
}

<div class="input-field">
  <select id="driver">
    <option disabled selected>Choose Driver</option>
      <option class="selected"> Driver 1</option>
      <option class="selected"> Driver 2</option>
  </select>
</div>


问:
Programmatically detect SQL Server Edition
I'm using C# with SMO and attempting to detect what edition of SQL Server (e.g., enterprise, standard) I'm connecting to.  I know how to get the version information, but that only tells me what version of SQL Server (e.g., SQL Server 2008 vs SQL Server 2005).

Does anyone know how to get the actual product edition (e.g., enterprise, standard)?

I need this information because some SQL Server features are only enterprise.  Thus, I could just try to call them and catch the exception, but I'd much prefer an upfront detection.

Thanks!

答:
I've always used @@Version (eg.  SELECT @@Version and manipluted the result in code), but this article looks pretty handy;
http://support.microsoft.com/kb/321185

The only issue with using SERVERPROPERTY, as per the link... is that this won't work with older version of SQL Server.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

OwnerDisplayName: GordonB

LastEditorDisplayName: GordonB


问:
Using a CASE inside an IN to give a possibility of multiple int's
I am trying to get a CASE statement working inside an IN statement where the first 2 conditions will result in 1 possible outcome, while the third will result in 2 possible outcomes. Which is why I'm using CASE. Here's the SQL that I have so far:

```<code>DECLARE @startDate date, @endDate date
DECLARE @AptTpye varchar(1)
SET @startDate = '2/17/2020'
SET @endDate = '2/18/2020'
-- 1 = Receiving : 2 = Shipping : 3 = Both
SET @AptTpye = 1

SELECT SAR.AppointmentID, SAR.LoadID, SAR2.DateValue [Check In], SAR3.EnteredOn [Scale In], SAR.LoadID + '*,', SAR.AppointmentType
FROM dbo.SAR_AppointmentMaster AS SAR
LEFT JOIN dbo.SAR_AppointmentTimes AS SAR2 ON SAR2.AppointmentID = SAR.AppointmentID AND SAR2.DateType = 'CHECKIN'
LEFT JOIN dbo.SAR_AppointmentWeights AS SAR3 ON SAR3.AppointmentID = SAR.AppointmentID AND SAR3.WeightType = 'SCALEIN'
WHERE SAR2.DateValue BETWEEN @startDate AND @endDate
    AND SAR.AppointmentType IN(CASE @AptTpye
                                    WHEN '1' THEN 1
                                    WHEN '2' THEN 2
                                    WHEN '3' THEN (1, 2)
                                END)
</code>```

Am I going about this wrong? Or is there a way to get this to work?

I have also tried this:

```<code>SELECT SAR.AppointmentID, SAR.LoadID, SAR2.DateValue [Check In], SAR3.EnteredOn [Scale In], SAR.LoadID + '*,', SAR.AppointmentType
FROM dbo.SAR_AppointmentMaster AS SAR
LEFT JOIN dbo.SAR_AppointmentTimes AS SAR2 ON SAR2.AppointmentID = SAR.AppointmentID AND SAR2.DateType = 'CHECKIN'
LEFT JOIN dbo.SAR_AppointmentWeights AS SAR3 ON SAR3.AppointmentID = SAR.AppointmentID AND SAR3.WeightType = 'SCALEIN'
WHERE SAR2.DateValue BETWEEN @startDate AND @endDate
    AND (CASE @AptTpye
                                    WHEN '1' THEN SAR.AppointmentType = 1
                                    WHEN '2' THEN SAR.AppointmentType = 2
                                    WHEN '3' THEN SAR.AppointmentType IN(1, 2)
                                END)
</code>```

Neither version works. The first version errors on the WHEN '3' THEN line and the second errors on the first WHEN.

答:
You seem to want this logic:

```<code>(SAR.AppointmentType = @AptType OR
 @AptType = 3 AND SAR.AppointmentType IN (1, 2)
)
</code>```

I see no reason for @AptType to be a string.

Note:  If you have only two appointment types, then this does the same thing:

```<code>(SAR.AppointmentType = @AptType OR
 @AptType = 3
)
</code>```

Body:
I am trying to get a CASE statement working inside an IN statement where the first 2 conditions will result in 1 possible outcome, while the third will result in 2 possible outcomes. Which is why I'm using CASE. Here's the SQL that I have so far:

DECLARE @startDate date, @endDate date
DECLARE @AptTpye varchar(1)
SET @startDate = '2/17/2020'
SET @endDate = '2/18/2020'
-- 1 = Receiving : 2 = Shipping : 3 = Both
SET @AptTpye = 1

SELECT SAR.AppointmentID, SAR.LoadID, SAR2.DateValue [Check In], SAR3.EnteredOn [Scale In], SAR.LoadID + '*,', SAR.AppointmentType
FROM dbo.SAR_AppointmentMaster AS SAR
LEFT JOIN dbo.SAR_AppointmentTimes AS SAR2 ON SAR2.AppointmentID = SAR.AppointmentID AND SAR2.DateType = 'CHECKIN'
LEFT JOIN dbo.SAR_AppointmentWeights AS SAR3 ON SAR3.AppointmentID = SAR.AppointmentID AND SAR3.WeightType = 'SCALEIN'
WHERE SAR2.DateValue BETWEEN @startDate AND @endDate
    AND SAR.AppointmentType IN(CASE @AptTpye
                                    WHEN '1' THEN 1
                                    WHEN '2' THEN 2
                                    WHEN '3' THEN (1, 2)
                                END)

Am I going about this wrong? Or is there a way to get this to work?

I have also tried this:

SELECT SAR.AppointmentID, SAR.LoadID, SAR2.DateValue [Check In], SAR3.EnteredOn [Scale In], SAR.LoadID + '*,', SAR.AppointmentType
FROM dbo.SAR_AppointmentMaster AS SAR
LEFT JOIN dbo.SAR_AppointmentTimes AS SAR2 ON SAR2.AppointmentID = SAR.AppointmentID AND SAR2.DateType = 'CHECKIN'
LEFT JOIN dbo.SAR_AppointmentWeights AS SAR3 ON SAR3.AppointmentID = SAR.AppointmentID AND SAR3.WeightType = 'SCALEIN'
WHERE SAR2.DateValue BETWEEN @startDate AND @endDate
    AND (CASE @AptTpye
                                    WHEN '1' THEN SAR.AppointmentType = 1
                                    WHEN '2' THEN SAR.AppointmentType = 2
                                    WHEN '3' THEN SAR.AppointmentType IN(1, 2)
                                END)

Neither version works. The first version errors on the WHEN '3' THEN line and the second errors on the first WHEN.

Body:
You seem to want this logic:

(SAR.AppointmentType = @AptType OR
 @AptType = 3 AND SAR.AppointmentType IN (1, 2)
)

I see no reason for @AptType to be a string.

Note:  If you have only two appointment types, then this does the same thing:

(SAR.AppointmentType = @AptType OR
 @AptType = 3
)


问:
Sonatype Nexus gives 401 for some unkown reason
We have to work with Nexus OSS version 3.20.1-01. We have a problem with it when we try to deploy or push an Maven2 artifact(jar) to Nexus. We used a account test123 with password test123. test123 has privlidges  nx-admin  in nexus.  If we try to login in the admin console we can do this without any problem.

But if we try to refer to a proxy server configured on Nexus with name  sligro-proxy  then for some reason its sends the 401.

We use Maven 3.5.4

But for some silly reason we can't use the proxy sligro-proxy  to maven central.  If we use Maven without Nexus by deleting the settings.xml file then this build goes fine.   ./mvn  package.

If I change something in the settings.xml file then I see the build is responding on that change.

We see the 401 in the request.log of Nexus like this:

```<code>192.168.178.123 - - [16/Feb/2020:19:46:50 +0100] "HEAD /nexus/repository/sligro-proxy/org/apache/maven/plugins/maven-resources-plugin/2.6/maven-resources-plugin-2.6.pom HTTP/1.1" 401 - 0 2 "Apache-Maven/3.5.4 (Java 1.8.0_112; Linux 3.10.0-957.27.2.el7.x86_64)" [qtp1998317514-191]
</code>```

And on the client we see this:
    [INFO] Finished at: 2020-02-16T19:46:50+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.6: Could not transfer artifact org.apache.maven.plugins:maven-resources-plugin:pom:2.6 from/to nexus (http://192.168.178.178:8081/nexus/repository/sligro-proxy): Not authorized , ReasonPhrase: Unauthorized. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginResolutionException

This is my settings.xml file:

```<code>    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>nexus-proxy</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>
    <distributionManagement>
        <repository>
            <id>sligro</id>
            <name>maven-releases</name>
            <url>http://192.168.178.178:8081/nexus/repository/maven-releases/</url>
        </repository>
        <snapshotRepository>
            <id>sligro</id>
            <name>maven-snapshots</name>
            <url>http://192.168.178.178:8081/nexus/repository/maven-snapshots/</url>
        </snapshotRepository>
    </distributionManagement>```

This is my settings.xml file:

    </project>This is my settings file:<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
    <proxies/>
    <servers>
        <server>
            <id>nexus-snapshots</id>
            <username>test123</username>
            <password>test123</password>
        </server>
        <server>
            <id>nexus-releases</id>
            <username>test123</username>
            <password>test123</password>
        </server>
        <server>
            <id>sligro</id>
            <username>test123</username>
            <password>test123</password>
        </server>
        <server>
            <id>sligro-proxy</id>
            <username>test123</username>
            <password>test123</password>
        </server>
        <server>
            <id>/192.168.178.178:8081</id>
            <username>test123</username>
            <password>test123</password>
        </server>
    </servers>
    <mirrors>
        <mirror>
            <id>nexus</id>
            <mirrorOf>*</mirrorOf>
            <url>http://192.168.178.178:8081/nexus/repository/sligro-proxy</url>
        </mirror>
    </mirrors>
    <profiles>
        <profile>
            <id>sligro</id>
            <repositories>
                <repository>
                    <id>central</id>
                    <url>http://central</url>
                    <releases>
                        <enabled>true</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </repository>
            </repositories>
            <pluginRepositories>
                <pluginRepository>
                    <id>central</id>
                    <url>http://central</url>
                    <releases>
                        <enabled>true</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </pluginRepository>
            </pluginRepositories>
            <properties>
                <nexus.url>http://192.168.178.178:8081/nexus/repository</nexus.url>
            </properties>
        </profile>
    </profiles>
    <activeProfiles>
        <activeProfile>sligro</activeProfile>
    </activeProfiles>
</settings>

Well I almost spend to 2 days this weekend to find out what the problem is and
changed tons of params but it gives always the 401. Help would be appriciated.
Thanks
```

答: I have found the solution. My mirror has the wrong ID. If I use the "sligro" ID instead of the "nexus" ID in the mirrors section then the Maven build to nexus runs fine.</p>

Body:
We have to work with Nexus OSS version 3.20.1-01. We have a problem with it when we try to deploy or push an Maven2 artifact(jar) to Nexus. We used a account test123 with password test123. test123 has privlidges  nx-admin  in nexus.  If we try to login in the admin console we can do this without any problem.

But if we try to refer to a proxy server configured on Nexus with name  sligro-proxy  then for some reason its sends the 401.

We use Maven 3.5.4

But for some silly reason we can't use the proxy sligro-proxy  to maven central.  If we use Maven without Nexus by deleting the settings.xml file then this build goes fine.   ./mvn  package.

If I change something in the settings.xml file then I see the build is responding on that change.

We see the 401 in the request.log of Nexus like this:

192.168.178.123 - - [16/Feb/2020:19:46:50 +0100] "HEAD /nexus/repository/sligro-proxy/org/apache/maven/plugins/maven-resources-plugin/2.6/maven-resources-plugin-2.6.pom HTTP/1.1" 401 - 0 2 "Apache-Maven/3.5.4 (Java 1.8.0_112; Linux 3.10.0-957.27.2.el7.x86_64)" [qtp1998317514-191]

And on the client we see this:
    [INFO] Finished at: 2020-02-16T19:46:50+01:00
[INFO] ------------------------------------------------------------------------
[ERROR] Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.6: Could not transfer artifact org.apache.maven.plugins:maven-resources-plugin:pom:2.6 from/to nexus (http://192.168.178.178:8081/nexus/repository/sligro-proxy): Not authorized , ReasonPhrase: Unauthorized. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginResolutionException

This is my settings.xml file:

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>nexus-proxy</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>
    <distributionManagement>
        <repository>
            <id>sligro</id>
            <name>maven-releases</name>
            <url>http://192.168.178.178:8081/nexus/repository/maven-releases/</url>
        </repository>
        <snapshotRepository>
            <id>sligro</id>
            <name>maven-snapshots</name>
            <url>http://192.168.178.178:8081/nexus/repository/maven-snapshots/</url>
        </snapshotRepository>
    </distributionManagement>```

This is my settings.xml file:

    </project>This is my settings file:<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
    <proxies/>
    <servers>
        <server>
            <id>nexus-snapshots</id>
            <username>test123</username>
            <password>test123</password>
        </server>
        <server>
            <id>nexus-releases</id>
            <username>test123</username>
            <password>test123</password>
        </server>
        <server>
            <id>sligro</id>
            <username>test123</username>
            <password>test123</password>
        </server>
        <server>
            <id>sligro-proxy</id>
            <username>test123</username>
            <password>test123</password>
        </server>
        <server>
            <id>/192.168.178.178:8081</id>
            <username>test123</username>
            <password>test123</password>
        </server>
    </servers>
    <mirrors>
        <mirror>
            <id>nexus</id>
            <mirrorOf>*</mirrorOf>
            <url>http://192.168.178.178:8081/nexus/repository/sligro-proxy</url>
        </mirror>
    </mirrors>
    <profiles>
        <profile>
            <id>sligro</id>
            <repositories>
                <repository>
                    <id>central</id>
                    <url>http://central</url>
                    <releases>
                        <enabled>true</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </repository>
            </repositories>
            <pluginRepositories>
                <pluginRepository>
                    <id>central</id>
                    <url>http://central</url>
                    <releases>
                        <enabled>true</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </pluginRepository>
            </pluginRepositories>
            <properties>
                <nexus.url>http://192.168.178.178:8081/nexus/repository</nexus.url>
            </properties>
        </profile>
    </profiles>
    <activeProfiles>
        <activeProfile>sligro</activeProfile>
    </activeProfiles>
</settings>

Well I almost spend to 2 days this weekend to find out what the problem is and
changed tons of params but it gives always the 401. Help would be appriciated.
Thanks


问:
How to get level(depth) number of two connected nodes in neo4j
I'm using neo4j as a graph database to store user's connections detail into this. here I want to show the level of one user with respect to another user in their connections like Linkedin. for example- first layer connection, second layer connection, third layer and above the third layer shows 3+. but I don't know how this happens using neo4j. i searched for this but couldn't find any solution for this. if anybody knows about this then please help me to implement this functionality.</p>

答:
To find the shortest "connection level" between 2 specific people, just get the shortest path and add 1:

```<code>MATCH path = shortestpath((p1:Person)-[*..]-(p2:Person))
WHERE p1.id = 1 AND p2.id = 2
RETURN LENGTH(path) + 1 AS level
</code>```

NOTE: You may want to put a reasonable upper bound on the variable-length relationship pattern (e.g., [*..6]) to avoid having the query taking too long or running out of memory in a large DB). You should probably ignore very distant connections anyway.

Body:
To find the shortest "connection level" between 2 specific people, just get the shortest path and add 1:

MATCH path = shortestpath((p1:Person)-[*..]-(p2:Person))
WHERE p1.id = 1 AND p2.id = 2
RETURN LENGTH(path) + 1 AS level

NOTE: You may want to put a reasonable upper bound on the variable-length relationship pattern (e.g., [*..6]) to avoid having the query taking too long or running out of memory in a large DB). You should probably ignore very distant connections anyway.


问:
Creating a generic PagedListAdapter using android paging library
My app has more than 4 lists of different data models.

I want to create a more generic  CommonAdapter that extends PagedListAdapter

Here is my current code

```<code>public abstract class CommonPagedListAdapter<T, VH extends RecyclerView.ViewHolder>
        extends PagedListAdapter<T, VH> {

    private Context mContext;
    private ArrayList<T> mArrayList;

    public abstract void onItemClick(T model, int position);
    public abstract int getLayoutResId();

    protected CommonPagedListAdapter(Context context, ArrayList<T> arrayList,
                                     @NonNull DiffUtil.ItemCallback<T> diffCallback) {
        super(diffCallback);
        this.mContext  = context;
        this.mArrayList = arrayList;
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //what should i return here?
        View view = LayoutInflater.from(mContext).inflate(getLayoutResId(),parent,false);
        return (VH) new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        //what should i do here?
//        holder
    }

    class ItemViewHolder extends RecyclerView.ViewHolder {

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}
</code>```

I'm using PagelListAdapter from the Android  Paging Library

I would like to know a few things:

- What should be set in the onCreateViewHolder as I'll be having different ViewHolders?

- What should be set in onBindViewHolder?

- Is this really the right way that makes the CommonPagedListAdapter extensible and maintainable?

答:
I had a similar issue where I tried to create a single adapter to use for multiple different list types. I ultimately came to the conclusion that it is best to use a separate adapter for each list type solely because it avoids having to make a very big "common" adapter class which goes against the "single-responsibility" principle. That way, each adapter is a lot smaller, more maintainable, and flexible.

However, if you really want to use a single adapter for similar items, the way I usually do it is by creating unique ViewHolders for each item type and then binding them accordingly in onBindViewHolder using a switch statement or something similar. In order to do this, you would need to override an additional method called getItemViewType in your adapter.

There's a really good guide that goes over how to create an adapter that can handle different view types on Codepath: https://guides.codepath.com/android/Heterogenous-Layouts-inside-RecyclerView

Body:
My app has more than 4 lists of different data models.

I want to create a more generic  CommonAdapter that extends PagedListAdapter

Here is my current code

public abstract class CommonPagedListAdapter<T, VH extends RecyclerView.ViewHolder>
        extends PagedListAdapter<T, VH> {

    private Context mContext;
    private ArrayList<T> mArrayList;

    public abstract void onItemClick(T model, int position);
    public abstract int getLayoutResId();

    protected CommonPagedListAdapter(Context context, ArrayList<T> arrayList,
                                     @NonNull DiffUtil.ItemCallback<T> diffCallback) {
        super(diffCallback);
        this.mContext  = context;
        this.mArrayList = arrayList;
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //what should i return here?
        View view = LayoutInflater.from(mContext).inflate(getLayoutResId(),parent,false);
        return (VH) new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        //what should i do here?
//        holder
    }

    class ItemViewHolder extends RecyclerView.ViewHolder {

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}

I'm using PagelListAdapter from the Android  Paging Library

I would like to know a few things:

- What should be set in the onCreateViewHolder as I'll be having different ViewHolders?

- What should be set in onBindViewHolder?

- Is this really the right way that makes the CommonPagedListAdapter extensible and maintainable?


问:
What is the best way to set font size for mobile, desktop, and print?
I'm making a website and want the font size to be readable on mobile, desktop, and also when printed.
I find the default font size on my desktop looks good on desktop, but is way too small in mobile (and often I notice default fonts are way too big when printed).
What's the best practice for setting a font size that is legible on mobile, desktop and print?</p>

答: Generally speaking you can accomplish this one of several ways. Two concepts that come to mind would be to have a stylesheet that is for web which would control your desktop, tablet and mobile styling. You can then have a separate stylesheet that targets print which is a less complicated stylesheet. You can also use media queries to target media type also. A reference for how to accomplish this can be reference by visiting https://www.w3schools.com/css/css3_mediaqueries.asp</p>


问:
Connecting to an online database server in Javafx
Hi guys am trying create a library management system but I want to host my database in an online server, I have gotten a free server and created my database, but now I don't really know how to connect to the online database, have search google but couldn't get any specific response..

The server am using is freemysqlhosting.com
I already have my username and password, so how do I connect to it from my application

答:
You may purchase or search for a free db hosting provider like

1. freemysqlhosting

Register to your preferred online hosting site then create a db and your tables.

Then you may connect to your DB from anywhere using a connection string. You can connect even from localhost.

how to connect

```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCExample {

    public static void main(String[] args) {

        // https://docs.oracle.com/javase/8/docs/api/java/sql/package-summary.html#package.description
        // auto java.sql.Driver discovery -- no longer need to load a java.sql.Driver class via Class.forName

        // register JDBC driver, optional since java 1.6
        /*try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }*/

        // auto close connection
        try (Connection conn = DriverManager.getConnection(
                "jdbc:mysql://127.0.0.1:3306/test", "root", "password")) {

            if (conn != null) {
                System.out.println("Connected to the database!");
            } else {
                System.out.println("Failed to make connection!");
            }

        } catch (SQLException e) {
            System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
</code>```

The hosting providers will provide you with the information that you would require for connection.

```<code>Server: xxxx
Db_Name: xxxx
Username: xxxx
Password: xxxx
Port number: 3306
</code>```

Once you get the details you can login to phpmyadmin online  phpmyadmin.co and create your tables

Body:
You may purchase or search for a free db hosting provider like

1. freemysqlhosting

Register to your preferred online hosting site then create a db and your tables.

Then you may connect to your DB from anywhere using a connection string. You can connect even from localhost.

how to connect

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCExample {

    public static void main(String[] args) {

        // https://docs.oracle.com/javase/8/docs/api/java/sql/package-summary.html#package.description
        // auto java.sql.Driver discovery -- no longer need to load a java.sql.Driver class via Class.forName

        // register JDBC driver, optional since java 1.6
        /*try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }*/

        // auto close connection
        try (Connection conn = DriverManager.getConnection(
                "jdbc:mysql://127.0.0.1:3306/test", "root", "password")) {

            if (conn != null) {
                System.out.println("Connected to the database!");
            } else {
                System.out.println("Failed to make connection!");
            }

        } catch (SQLException e) {
            System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

The hosting providers will provide you with the information that you would require for connection.

Server: xxxx
Db_Name: xxxx
Username: xxxx
Password: xxxx
Port number: 3306

Once you get the details you can login to phpmyadmin online  phpmyadmin.co and create your tables


问:
Coverity issue: noescape: Resource dataview is not closed or saved in Table.get
```<code>this.btnSaveChanges.Visible = false;
//Error: alloc_fn: A new resource is returned from allocation method Grp_des.
//Error: var_assign: Assigning: dtv = resource returned from this.dal.Grp_des(this.sParent).
DataView dtv = dal.Grp_des("ABC");
**//error:  noescape: Resource dtv is not closed or saved in Table.get.**
DataRow dtr = dtv.Table.Rows[0];
lblTransferFrom.Text = "Job Transferred from:  " + HttpUtility.HtmlEncode(dtr[0].ToString());
//Error: leaked_resource: Variable dtv going out of scope leaks the resource it refers to.
</code>```

What exactly both the error's pointing?
Can any one help me in this, Thank you in advance.

答:
I can explain what the messages mean, including noescape.

```<code>this.btnSaveChanges.Visible = false;
//Error: alloc_fn: A new resource is returned from allocation method Grp_des.
//Error: var_assign: Assigning: dtv = resource returned from this.dal.Grp_des(this.sParent).
DataView dtv = dal.Grp_des("ABC");
</code>```

The alloc_fn event means Coverity thinks that Grp_des allocates a resource that must be disposed.  Then var_assign says that resource is pointed to by the dtv variable.

```<code>**//error:  noescape: Resource dtv is not closed or saved in Table.get.**
DataRow dtr = dtv.Table.Rows[0];
</code>```

The noescape event is purely informative.  Coverity is saying that, although dtv was passed to Table.get, that method does not dispose of the resource, and also does not save it in a field.  Consequently, the resource is still allocated and still needs to be disposed.

This particular event is notoriously confusing.  The static analysis jargon term "escape" describes what happens when a value is saved to a field or a global.  "noescape" means that didn't happen.

```<code>lblTransferFrom.Text = "Job Transferred from:  " + HttpUtility.HtmlEncode(dtr[0].ToString());
//Error: leaked_resource: Variable dtv going out of scope leaks the resource it refers to.
</code>```

Finally, the leaked_resource event indicates that we have reached the end of this method and the resource still has not been either disposed or saved for later disposal.  This is usually bad because the resource will not be disposed until the garbage collector reclaims the associated memory object, which could be a long time from now, and something could starve for the resource in question in the meantime.

The straightforward fix would be to add dtv.Dispose(); at the end or to use a using statement to do disposal automatically and in an exception-safe way.  But, of course, without seeing the rest of the code, it's impossible to be sure that is the correct fix.

(Disclosure: I used to work for Coverity/Synopsys.)

Body:
this.btnSaveChanges.Visible = false;
//Error: alloc_fn: A new resource is returned from allocation method Grp_des.
//Error: var_assign: Assigning: dtv = resource returned from this.dal.Grp_des(this.sParent).
DataView dtv = dal.Grp_des("ABC");
**//error:  noescape: Resource dtv is not closed or saved in Table.get.**
DataRow dtr = dtv.Table.Rows[0];
lblTransferFrom.Text = "Job Transferred from:  " + HttpUtility.HtmlEncode(dtr[0].ToString());
//Error: leaked_resource: Variable dtv going out of scope leaks the resource it refers to.

What exactly both the error's pointing?
Can any one help me in this, Thank you in advance.

Body:
I can explain what the messages mean, including noescape.

this.btnSaveChanges.Visible = false;
//Error: alloc_fn: A new resource is returned from allocation method Grp_des.
//Error: var_assign: Assigning: dtv = resource returned from this.dal.Grp_des(this.sParent).
DataView dtv = dal.Grp_des("ABC");

The alloc_fn event means Coverity thinks that Grp_des allocates a resource that must be disposed.  Then var_assign says that resource is pointed to by the dtv variable.

**//error:  noescape: Resource dtv is not closed or saved in Table.get.**
DataRow dtr = dtv.Table.Rows[0];

The noescape event is purely informative.  Coverity is saying that, although dtv was passed to Table.get, that method does not dispose of the resource, and also does not save it in a field.  Consequently, the resource is still allocated and still needs to be disposed.

This particular event is notoriously confusing.  The static analysis jargon term "escape" describes what happens when a value is saved to a field or a global.  "noescape" means that didn't happen.

lblTransferFrom.Text = "Job Transferred from:  " + HttpUtility.HtmlEncode(dtr[0].ToString());
//Error: leaked_resource: Variable dtv going out of scope leaks the resource it refers to.

Finally, the leaked_resource event indicates that we have reached the end of this method and the resource still has not been either disposed or saved for later disposal.  This is usually bad because the resource will not be disposed until the garbage collector reclaims the associated memory object, which could be a long time from now, and something could starve for the resource in question in the meantime.

The straightforward fix would be to add dtv.Dispose(); at the end or to use a using statement to do disposal automatically and in an exception-safe way.  But, of course, without seeing the rest of the code, it's impossible to be sure that is the correct fix.

(Disclosure: I used to work for Coverity/Synopsys.)