答:
It seems to me that you want to update table after joining like below

```<code>; WITH CTE AS
(
   SELECT *, RN = ROW_NUMBER() OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND)
   FROM   DAILYDATA
)
Update your_table
SET -- your_table.columns = CTE.columns
From your_table
Inner join CTE on your_condition_join_here
</code>```

Read the following post to have a better understanding

SQL Update after Joining Two Tables

Updated

You should use multiple CTE in a query like below

```<code>; WITH CTE AS
(
SELECT *, RN = ROW_NUMBER() OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND)
FROM DAILYDATA
), CTE2 AS
(
SELECT NIP, NAME, DEPARTMENT, MIN(CTE.DATEATTEND) AS Min_DATEATTEND, MAX(CTE.DATEATTEND) AS Max_DATEATTEND
From CTE
GROUP BY NIP, NAME, DEPARTMENT
)
Update DAILYDATAWH
SET DAILYDATAWH.NIP = CTE2.NIP ,
DAILYDATAWH.NAME = CTE2.NAME,
DAILYDATAWH.DEPARTMENT = CTE2.DEPARTMENT,
DAILYDATAWH.STATUSIN = CTE2.Min_DATEATTEND,
DAILYDATAWH.STATUSOUT = CTE2.Max_DATEATTEND
From DAILYDATA
Inner join CTE2 on DAILYDATA.NIP = CTE2.NIP
</code>```

Title: Update records in table from CTE results

Body:
It seems to me that you want to update table after joining like below

; WITH CTE AS
(
   SELECT *, RN = ROW_NUMBER() OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND)
   FROM   DAILYDATA
)
Update your_table
SET -- your_table.columns = CTE.columns
From your_table
Inner join CTE on your_condition_join_here

Read the following post to have a better understanding

SQL Update after Joining Two Tables

Updated

You should use multiple CTE in a query like below

; WITH CTE AS
(
SELECT *, RN = ROW_NUMBER() OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND)
FROM DAILYDATA
), CTE2 AS
(
SELECT NIP, NAME, DEPARTMENT, MIN(CTE.DATEATTEND) AS Min_DATEATTEND, MAX(CTE.DATEATTEND) AS Max_DATEATTEND
From CTE
GROUP BY NIP, NAME, DEPARTMENT
)
Update DAILYDATAWH
SET DAILYDATAWH.NIP = CTE2.NIP ,
DAILYDATAWH.NAME = CTE2.NAME,
DAILYDATAWH.DEPARTMENT = CTE2.DEPARTMENT,
DAILYDATAWH.STATUSIN = CTE2.Min_DATEATTEND,
DAILYDATAWH.STATUSOUT = CTE2.Max_DATEATTEND
From DAILYDATA
Inner join CTE2 on DAILYDATA.NIP = CTE2.NIP


来源: stackexchange

问:
How can I figure out why my mini-max tic-tac-toe AI does not work?
I am trying to make a minimax tic-tac-toe game because I am a novice at Python and I am trying to figure out how a simple AI-mini-max game works. The AI for some reason still goes in order in which the spot turns up on the list for the board.

Ex: if the top right spot was first in the "b" list, it picks it first. It looks like it is calculating the scores, but I do not think it is utilizing them for some reason. I want it to not go in order of what the spaces in the board. I can't figure out a way to replace the code that places the "O".

import random
import math

three = [0, 0, 0]
game = True
turnai = False
result = ""
b = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
x = "X"
o = "O"
#Spots on the board Ex: ur = upper right, mm = middle middle, lm = lower middle
ur = b[2]
um = b[1]
ul = b[0]
ml = b[3]
mm = b[4]
mr = b[5]
ll = b[6]
lm = b[7]
lr = b[8]
cw = " "

AI = ""
player = ""

#Board setup
def board(ul, um, ur, ml, mm, mr, ll, lm, lr):
    print("|" + " " + ul + " " + "|" + " " + um + " " + "|" + " " + ur + " " + "|")
    print("|" + " " + ml + " " + "|" + " " + mm + " " + "|" + " " + mr + " " + "|")
    print("|" + " " + ll + " " + "|" + " " + lm + " " + "|" + " " + lr + " " + "|")

board(ul, um, ur, ml, mm, mr, ll, lm, lr)
print("This is the game of tic-tac-toe")
print("You will be playing against an AI")
print("Type where you want to place your letter Ex: ur = upper right, mm = middle middle, and ll = lower right")

first = "P"
player = "X"
AI = "O"

#Checks if someone has won
def checkwinner():
    ur = b[2]
    um = b[1]
    ul = b[0]
    ml = b[3]
    mm = b[4]
    mr = b[5]
    ll = b[6]
    lm = b[7]
    lr = b[8]
    row1 = [ul, ml, ll]
    row2 = [um, mm, lm]
    row3 = [ur, mr, lr]
    column1 = [ul, um, ur]
    column2 = [ml, mm, mr]
    column3 = [ll, lm, lr]
    diagonal1 = [ul, mm, lr]
    diagonal2 = [ur, mm, ll]
    if row1 == ["X", "X", "X"] or row2 == ["X", "X", "X"] or row3 == ["X", "X", "X"] or column1 == ["X", "X",
                                                                                "X"] or column2 == [
        "X", "X", "X"] or column3 == ["X", "X", "X"] or diagonal1 == ["X", "X", "X"] or diagonal2 == ["X", "X",
                                                                                "X"]:
        if player == x:
            print("You win! (X)")
            return "X"
        if player != x:
            print("You lose!")
            return "O"
    if row1 == ["O", "O", "O"] or row2 == ["O", "O", "O"] or row3 == ["O", "O", "O"] or column1 == ["O", "O",
                                                                                "O"] or column2 == [
        "O", "O", "O"] or column3 == ["O", "O", "O"] or diagonal1 == ["O", "O", "O"] or diagonal2 == ["O", "O",
                                                                                "O"]:
        if player == o:
            print("You win! (O)")
            return "X"
        if player != o:
            print("You lose")
            return "O"
    if b[0] != " " and b[1] != " " and b[2] != " " and b[3] != " " and b[4] != " " and b[5] != " " and b[
        6] != " " and b[7] != " " and b[8] != " ":
        print("TIE!")
        winner = True
        return "0"
    return "null"
#Minimax Algorithm
def minimax(b, depth, isMaximizing):
            result = checkwinner()
            if result != "null":
                score = scores[result] + score
                return score

            if (isMaximizing):
                bestScore = -math.inf
                j = 0
                for str in b:
                    if str == " ":
                        b[j] = AI
                        score = minimax(b, depth + 1, False) + score
                        b[j] = " "
                        bestScore = max(score, bestScore)
                    j += 1
                return bestScore

            else:
                bestScore = math.inf
                k = 0
                for str in b:
                    if str == " ":
                        b[k] = player
                        score = minimax(b, depth + 1, True) + score
                        b[k] = " "
                        bestScore = min(score, bestScore)
                    k += 1
                return bestScore

#Game Start loop
if (first == "P"):
    while (game == True):
        i = 0
        scores = {
            'O': 1,
            'X': -1,
            '0': 0
        }
#AI turn
        bestScore = -math.inf
        turnai = False
        i = 0
        for str in b:
            if str == " ":
                b[i] = AI
                score = minimax(b, 0, True)
                b[i] = " "
                print(score)
                if score > bestScore and turnai == False:
                    bestScore = score
                    b[i] = AI
                    turnai = True
            i += 1
        turnai = False
        print("")
        # b = [ul, um, ur, ml, mm, mr, ll, lm, lr]
        ur = b[2]
        um = b[1]
        ul = b[0]
        ml = b[3]
        mm = b[4]
        mr = b[5]
        ll = b[6]
        lm = b[7]
        lr = b[8]
#Prints Board
        board(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8])
        cw = checkwinner()
#Checks if game ended
        if cw == "X" or cw == "O" or cw == "0":
            game = False
            break
#Player turn
        print("Where do you want to place your letter?")
        turn = input(": ")
        if turn == "ur" and ur == " ":
            b[2] = player
            uru = True
        if turn == "um" and um == " ":
            b[1] = player
            umu = True
        if turn == "ul" and ul == " ":
            b[0] = player
            ulu = True
        if turn == "mr" and mr == " ":
            b[5] = player
            mru = True
        if turn == "mm" and mm == " ":
            b[4] = player
            mmu = True
        if turn == "ml" and ml == " ":
            b[3] = player
            mlu = True
        if turn == "lr" and lr == " ":
            b[8] = player
            lru = True
        if turn == "lm" and lm == " ":
            b[7] = player
            lmu = True
        if turn == "ll" and ll == " ":
            b[6] = player
            llu = True
#Prints Board
        board(b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8])
        sw = checkwinner()
#Checks if game needs to be ended
        if cw == "X" or cw == "O" or cw == "0":
            game = False
            break

```

答:
As a general style rule try to keep your line lengths < 100 characters.

You shouldn't use str as a variable name as it is a builtin.

You can use enumerate to get the index and the value from a list as you iterate.

scores should be defined in minimax because that's the only place it is used.

AI is taking the first spot available because of this section of code:

```<code>bestScore = -math.inf
turnai = False
i = 0
for str in b:
    if str == " ":
        b[i] = AI
        score = minimax(b, 0, True)
        b[i] = " "
        print(score)
        if score > bestScore and turnai == False: # Allways true first loop
            bestScore = score
            b[i] = AI
            turnai = True                         # ^ Never true in later loops
</code>```

Which ironically only occurs when turnai == false

You don't actually need your turnai boolean in game loop because you explicitly code both the ai and user turns.

You don't need to check if a boolean == True just say while game:

You don't need to break if your control bool is set to false.

If the user enters invalid input they lose their turn.

you have sw = checkwinner() then you examine the value of cw

I could fix this for you but I think I've given you enough to work with here and I will tell you that your concept is sound(ish) so if you just keep with it a little further you should get some satisfactory results...

The major logical flaw here is that you never actually count how many wins a given choice leaves... Your minimax function just returns 1 every time.

ContentLicense: CC BY-SA 4.0

Body:
As a general style rule try to keep your line lengths < 100 characters.

You shouldn't use str as a variable name as it is a builtin.

You can use enumerate to get the index and the value from a list as you iterate.

scores should be defined in minimax because that's the only place it is used.

AI is taking the first spot available because of this section of code:

bestScore = -math.inf
turnai = False
i = 0
for str in b:
    if str == " ":
        b[i] = AI
        score = minimax(b, 0, True)
        b[i] = " "
        print(score)
        if score > bestScore and turnai == False: # Allways true first loop
            bestScore = score
            b[i] = AI
            turnai = True                         # ^ Never true in later loops

Which ironically only occurs when turnai == false

You don't actually need your turnai boolean in game loop because you explicitly code both the ai and user turns.

You don't need to check if a boolean == True just say while game:

You don't need to break if your control bool is set to false.

If the user enters invalid input they lose their turn.

you have sw = checkwinner() then you examine the value of cw

I could fix this for you but I think I've given you enough to work with here and I will tell you that your concept is sound(ish) so if you just keep with it a little further you should get some satisfactory results...

The major logical flaw here is that you never actually count how many wins a given choice leaves... Your minimax function just returns 1 every time.


问:
How to prevent Rest web-service Authentication with stolen Token
As we know Rest services are stateless, General strategies to authenticate is using a token based authentication.

In login service it takes credentials which returns a token.

This token might be set in client cookies, and all subsequent requests uses this token to be validated and process new request if token is valid.

Now my question is how one can validate the token ? If someone has stolen the token and tries to access rest services with stolen token by just editing cookies then how can it be identified and restricted ?

We can never know if the token is fetched by valid user and same user is trying to access subsequent request. but what are the possible ways to make it more hard, like to verify if the request has came from same source ?

One general suggestion is to set aging for token/cookies, but it still not helpful till the age of that token/cookies.

Any suggestions would be appreciated.

答:
To me, there was no way to prevent the access from being stolen JWT token except

setting a short timeout for the token

more secured at the HTTP request level by only allowing specific `User-Agent. See more

more secured at the HTTP request level by customizing the header key for the organization, e.g My-X-Auth = Bearer <token> instead of Authorization= Bearer <token>

more secured at the HTTP request level by restricting trusted urls/domains, e.g X-Content-Security-Policy. See more


问:
Ubuntu, cx_Freeze and multiprocessing.Manager() conflict in case "spawn" type processes

Env:

Ubuntu - 18.04

Python - 3.6.6

cx_Freeze - 6.1

Code:

Simple main_script.py file (example in repository - https://github.com/Yuriy-Leonov/cython_multiprocessing_issue )

```<code>import multiprocessing

if __name__ == '__main__':
    print("step-1")
    multiprocessing.set_start_method("spawn")
    print("step-2")
    multiprocessing.freeze_support()
    print("step-3")
    manager = multiprocessing.Manager()
    print("step-4")
    s_dict = manager.dict()
    print("finish")
</code>```

And setup.py (for cx_Freeze):

```<code>import cx_Freeze

executables = [cx_Freeze.Executable("main_script.py")]

cx_Freeze.setup(
    name="Example",
    options={
        "build_exe": {
            "replace_paths": [("*", "")]
        },
    },
    executables=executables
)
</code>```

Issue:

After building executable file via command python setup.py build I ran it and console log contained following:

```<code>step-1
step-2
step-3
step-1
step-2
step-3
step-1
step-2
step-3
...
</code>```

And infinite processes are spawned.

I understand that multiprocessing.Manager() should spawn "server" process. But can't get clue of current behaviorand and how to force it to create "shared dict"

Important:

multiprocessing.set_start_method("spawn") can't be changed and required due to main program behavior.

Question:

How to achive of creating manager.dict() in current configuration?

PS:

There is no issue if run with regular python <filename>(obvious)

答:
It's important to understand what set_start_method("spawn") does.

It does not make sense to run your script as a pre-compiled executable and expect set_start_method("spawn") to just work, because "spawn" here means "start my child processes by reinvoking the interpreter", but the "interpreter" is your pre-compiled program!

When you run your program, you get a fork bomb because the multiprocessing module tries to spawn the following processes:

$ ./main_script --multiprocessing-fork tracker_fd=6 pipe_handle=8
$ ./main_script -S -E -c 'from multiprocessing.semaphore_tracker import main;main(5)'
```

That's not going to work with your pre-compiled program. You will need to explicitly exec into the python interpreter or handle these cases if you want set_start_method("spawn") to work.

Body:
Env:

Ubuntu - 18.04

Python - 3.6.6

cx_Freeze - 6.1

Code:

Simple main_script.py file (example in repository - https://github.com/Yuriy-Leonov/cython_multiprocessing_issue )

import multiprocessing

if __name__ == '__main__':
    print("step-1")
    multiprocessing.set_start_method("spawn")
    print("step-2")
    multiprocessing.freeze_support()
    print("step-3")
    manager = multiprocessing.Manager()
    print("step-4")
    s_dict = manager.dict()
    print("finish")

And setup.py (for cx_Freeze):

import cx_Freeze

executables = [cx_Freeze.Executable("main_script.py")]

cx_Freeze.setup(
    name="Example",
    options={
        "build_exe": {
            "replace_paths": [("*", "")]
        },
    },
    executables=executables
)

Issue:

After building executable file via command python setup.py build I ran it and console log contained following:

step-1
step-2
step-3
step-1
step-2
step-3
step-1
step-2
step-3
...

And infinite processes are spawned.

I understand that multiprocessing.Manager() should spawn "server" process. But can't get clue of current behaviorand and how to force it to create "shared dict"

Important:

multiprocessing.set_start_method("spawn") can't be changed and required due to main program behavior.

Question:

How to achive of creating manager.dict() in current configuration?

PS:

There is no issue if run with regular python <filename>(obvious)

Body:
It's important to understand what set_start_method("spawn") does.

It does not make sense to run your script as a pre-compiled executable and expect set_start_method("spawn") to just work, because "spawn" here means "start my child processes by reinvoking the interpreter", but the "interpreter" is your pre-compiled program!

When you run your program, you get a fork bomb because the multiprocessing module tries to spawn the following processes:

$ ./main_script --multiprocessing-fork tracker_fd=6 pipe_handle=8
$ ./main_script -S -E -c 'from multiprocessing.semaphore_tracker import main;main(5)'

That's not going to work with your pre-compiled program. You will need to explicitly exec into the python interpreter or handle these cases if you want set_start_method("spawn") to work.


问:
Can I vertically scale an Amazon instance?
Is it possible? According to Amazon, Amazon EC2 Auto Scaling uses Horizontal scaling:

You can also use Amazon EC2 Auto Scaling for dynamic scaling of EC2 instances in order to automatically increase the number of Amazon EC2 instances during demand spikes to maintain performance and decrease capacity during lulls to reduce costs.

I found no reference to vertical scaling, by changing each instance specifications instead of adding or removing them.

答:
Amazon ECS enables you to control the usage of swap memory space on your Linux container instances at the container level. Using a per-container swap configuration, each container within a task definition can have swap enabled or disabled, and for those that have it enabled, the maximum amount of swap space used can be limited. For example, latency-critical containers can have swap disabled, whereas containers with high transient memory demands can have swap turned on to reduce the chances of out-of-memory errors when the container is under load.

Read more here, Managing Container Swap Space

The following is an example showing the JSON syntax:

additional configurable knob that allows us to configure a max swap size of 512 MB with an average aggressiveness (swappiness accepts an integer between 0 and 100).

```<code>{
    "family": "mywebsite",
    "networkMode": "awsvpc",
    "cpu": "256",
    "memory": "512",
    "requiresCompatibilities": ["EC2"],
    "containerDefinitions": [
        {
            "name": "mywebsite-nginx",
            "image": "nginx:latest",
            "essential": true,
            "cpu": 128,
            "memory": 256,
            "memoryReservation": 128,
            "linuxParameters": {
                "maxSwap": 512,
                "swappiness": 50
            }
        }
    ]
}
</code>```

Alternatively do read about AWS opsworks, https://docs.aws.amazon.com/opsworks/latest/userguide/workinglayers-ecscluster.html

Body:
Amazon ECS enables you to control the usage of swap memory space on your Linux container instances at the container level. Using a per-container swap configuration, each container within a task definition can have swap enabled or disabled, and for those that have it enabled, the maximum amount of swap space used can be limited. For example, latency-critical containers can have swap disabled, whereas containers with high transient memory demands can have swap turned on to reduce the chances of out-of-memory errors when the container is under load.

Read more here, Managing Container Swap Space

The following is an example showing the JSON syntax:

additional configurable knob that allows us to configure a max swap size of 512 MB with an average aggressiveness (swappiness accepts an integer between 0 and 100).

{
    "family": "mywebsite",
    "networkMode": "awsvpc",
    "cpu": "256",
    "memory": "512",
    "requiresCompatibilities": ["EC2"],
    "containerDefinitions": [
        {
            "name": "mywebsite-nginx",
            "image": "nginx:latest",
            "essential": true,
            "cpu": 128,
            "memory": 256,
            "memoryReservation": 128,
            "linuxParameters": {
                "maxSwap": 512,
                "swappiness": 50
            }
        }
    ]
}

Alternatively do read about AWS opsworks, https://docs.aws.amazon.com/opsworks/latest/userguide/workinglayers-ecscluster.html


问:
Laravel query join ManyToMany unique result
I have 3 tables : artists, albums and artist_albums.

I want get 1 result per album. For example, the album "What a Time to Be Alive" have 2 artists : "Drake" and "Future".
I would like a result in the following form :

```<code>id: 1,
name: "What a Time to Be Alive"
artists: [
    name: "Drake",
    name: "Future"
]
</code>```

Thanks for yous help

答:
To be more specific. Please set up a Many To Many relationship on the Album model.

```<code>class Album
{
    public function artists()
    {
        return $this->belongsToMany(Artist::class, 'artist_albums')
    }
}
</code>```

Then, from the controller action, you can say:

```<code>return Album::select('id', 'name')
           ->with('artists:name')
           ->get();
</code>```

Body:
I have 3 tables : artists, albums and artist_albums.

I want get 1 result per album. For example, the album "What a Time to Be Alive" have 2 artists : "Drake" and "Future".
I would like a result in the following form :

id: 1,
name: "What a Time to Be Alive"
artists: [
    name: "Drake",
    name: "Future"
]

Thanks for yous help

Body:
To be more specific. Please set up a Many To Many relationship on the Album model.

class Album
{
    public function artists()
    {
        return $this->belongsToMany(Artist::class, 'artist_albums')
    }
}

Then, from the controller action, you can say:

return Album::select('id', 'name')
           ->with('artists:name')
           ->get();


问:
MD5 Hash Conversion
The basis of what I am trying to understand is how the MD5 Hash function can convert a string of arbitrary length to such a small length, yet still represent the entire string.

I understand that it converts to a 128bit output which is composed of 16 Hexadecimal values, but from what I understand, a single Hex value in my mind would only represent one value. Ex: 0x41 in my mind with the ASCII table in relation to c++ would be 'A'.

Clearly my understanding in the MD5 function and how the output can hold the information is quite flawed, so I am looking for an explanation to understand how exactly those hexes can hold such a large string.

答:
They don't.

A hash doesn't "contain" or "represent" all of that information. They couldn't possibly.

They represent a digested version, a version with a whole load of information removed. Crucially, they do it in a way that's difficult to reverse, and in a way that produces a completely different hash when only a small change to the source data is made (this is deliberate: hashes are usually employed for quick error/change detection).

Yes, this means that multiple inputs hash to the same output. Collisions are something you have to consider when dealing with hashes.

You can read more about hashing on Wikipedia or in your security practices book.

I understand that it converts to a 128bit output which is composed of 16 Hexadecimal values, but from what I understand, a single Hex value in my mind would only represent one value. Ex: 0x41 in my mind with the ASCII table in relation to c++ would be 'A'.

Representing an MD5 hash using hex digits is just a convention. It doesn't mean that the individual bytes are intended to be interpreted using the ASCII table.

Title: MD5 Hash Conversion


问:
How can I make use of Error boundaries in functional React components?
I can make a class an error boundary in React by implementing componentDidCatch.

Is there a clean approach to making a functional component into an error boundary without converting it into a class?

Or is this a code smell?

答:
There is an implementation that can handle with non-existent functionalities for a functional component such as componentDidCatch and deriveStateFromError.

According to the author, it is based on React.memo().

The proposed solution is greatly inspired by the new React.memo() API.

import Catch from "./functional-error-boundary"

type Props = {
  children: React.ReactNode
}

const MyErrorBoundary = Catch(function MyErrorBoundary(props: Props, error?: Error) {
  if (error) {
    return (

An error has occured

{error.message}

    )
  } else {
    return <React.Fragment>{props.children}</React.Fragment>
  }
})
```

reference and API here

ContentLicense: CC BY-SA 3.0

Body:
There is an implementation that can handle with non-existent functionalities for a functional component such as componentDidCatch and deriveStateFromError.

According to the author, it is based on React.memo().

The proposed solution is greatly inspired by the new React.memo() API.

import Catch from "./functional-error-boundary"

type Props = {
  children: React.ReactNode
}

const MyErrorBoundary = Catch(function MyErrorBoundary(props: Props, error?: Error) {
  if (error) {
    return (
      <div className="error-screen">
        <h2>An error has occured</h2>
        <h4>{error.message}</h4>
      </div>
    )
  } else {
    return <React.Fragment>{props.children}</React.Fragment>
  }
})

reference and API here


答:
You're confusing a hash function with a compression algorithm.

A hash is typically a one-way operation, that is there's no way to "un-hash" something once it's hashed. That's fine as that's not what hashes are used for.

Hash functions are normally used to represent something of arbitrary length as a consistent length value. For example SHA2-256 represents an arbitrary amount of binary data as a 256-bit value. It's designed so that even a single bit change in the input causes the whole hash to change, making it difficult if not impossible to reverse the hashing process and "guess" the input.

This not to say hashes are without flaws. MD5, famously, is so weak that it's not hard to construct two binary strings that hash to the same value, generating a hash collision. A good hashing algorithm makes this unlikely, but no hashing algorithm can ever make it impossible.

Things hashes are used for:

Providing a "digest" of something in order to detect tampering, as in cryptographic signatures of things you download.

Distributing data "randomly" across a data structure to avoid clumping, as in a hash-table or dictionary.

Storing data that should not be easily reversible, like passwords. A good password hash is very hard to brute-force guess, but reasonably easy to test against a candidate password.

There's basically an infinite number of binary documents that could create a given MD5 hash. This is not true with lossless compression algorithms, as the compressed representation by design represents one and only one source document.

Title: MD5 Hash Conversion

Body:
The basis of what I am trying to understand is how the MD5 Hash function can convert a string of arbitrary length to such a small length, yet still represent the entire string.

I understand that it converts to a 128bit output which is composed of 16 Hexadecimal values, but from what I understand, a single Hex value in my mind would only represent one value. Ex: 0x41 in my mind with the ASCII table in relation to c++ would be 'A'.

Clearly my understanding in the MD5 function and how the output can hold the information is quite flawed, so I am looking for an explanation to understand how exactly those hexes can hold such a large string.


问:
Api Post always has user as null even though there is a logged in user
I am trying to have an api for my answers app.
When a post is created, the user is always set to null.
I am not sure of why that is.

How do I auto-add some fields to the saving object, like the authenticated user, user IP address?

Here is my serializer:

```<code>User = get_user_model()

class UserPublicSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            'username',
            'first_name',
            'last_name',
            'is_staff',
            'photo_url'
        ]
class AnswerCreateUpdateSerializer(ModelSerializer):
    user = UserPublicSerializer(read_only=True)
    class Meta:
        model = Answer
        fields = [
            'object_pk',
            'content_type',
            'answer',
            'user'
        ]
        read_only_fields = ['user']
</code>```

And the api create view:

```<code>class AnswerCreateAPIView(CreateAPIView):
    queryset = Answer.objects.all()
    serializer_class = AnswerCreateUpdateSerializer
</code>```

And the model is:

```<code>class AnswerAbstractModel(BaseAnswerAbstractModel):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'),
                             blank=True, null=True, related_name="%(class)s_answers",
                             on_delete=models.SET_NULL)
    answer = FroalaField()
    submit_date = models.DateTimeField(_('date/time submitted'), default=None, db_index=True)
    ip_address = models.GenericIPAddressField(_('IP address'), unpack_ipv4=True, blank=True, null=True)

class Answer(AnswerAbstractModel):
    class Meta(AnswerAbstractModel.Meta):
        db_table = "answers"
</code>```

I beg your pardon for my ignorance of the django world. I am trying hard to figure it out though.

That said, what should be the approach here?

答:
You have to override the perform_create() method of the AnswerCreateAPIView as below,

```<code>class AnswerCreateAPIView(CreateAPIView):
    queryset = Answer.objects.all()
    serializer_class = AnswerCreateUpdateSerializer

    <b>def perform_create(self, serializer):
        serializer.save(user=self.request.user)</b></code>```

Update-1

Why do you need to override?

Case-1

You set user as read_only_field in your AnswerCreateUpdateSerializer. By doing so DRF serialzier won't fetch any input data from JSON payload even if the data present in it

Case-2

If you unset the read_only property, DRF will ask you to provide a dict like object for the user since you have a Nested serializer configuration.

The DRF way

If you want to save the logged-in user to the DB in DRF, you should set the user field as read_only and override appropriate methods and fetch the logged-in user from request object.

Body:
I am trying to have an api for my answers app.
When a post is created, the user is always set to null.
I am not sure of why that is.

How do I auto-add some fields to the saving object, like the authenticated user, user IP address?

Here is my serializer:

User = get_user_model()

class UserPublicSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            'username',
            'first_name',
            'last_name',
            'is_staff',
            'photo_url'
        ]
class AnswerCreateUpdateSerializer(ModelSerializer):
    user = UserPublicSerializer(read_only=True)
    class Meta:
        model = Answer
        fields = [
            'object_pk',
            'content_type',
            'answer',
            'user'
        ]
        read_only_fields = ['user']

And the api create view:

class AnswerCreateAPIView(CreateAPIView):
    queryset = Answer.objects.all()
    serializer_class = AnswerCreateUpdateSerializer

And the model is:

class AnswerAbstractModel(BaseAnswerAbstractModel):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'),
                             blank=True, null=True, related_name="%(class)s_answers",
                             on_delete=models.SET_NULL)
    answer = FroalaField()
    submit_date = models.DateTimeField(_('date/time submitted'), default=None, db_index=True)
    ip_address = models.GenericIPAddressField(_('IP address'), unpack_ipv4=True, blank=True, null=True)

class Answer(AnswerAbstractModel):
    class Meta(AnswerAbstractModel.Meta):
        db_table = "answers"

I beg your pardon for my ignorance of the django world. I am trying hard to figure it out though.

That said, what should be the approach here?

Body:
You have to override the perform_create() method of the AnswerCreateAPIView as below,

class AnswerCreateAPIView(CreateAPIView):
    queryset = Answer.objects.all()
    serializer_class = AnswerCreateUpdateSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

Update-1

Why do you need to override?

Case-1

You set user as read_only_field in your AnswerCreateUpdateSerializer. By doing so DRF serialzier won't fetch any input data from JSON payload even if the data present in it

Case-2

If you unset the read_only property, DRF will ask you to provide a dict like object for the user since you have a Nested serializer configuration.

The DRF way

If you want to save the logged-in user to the DB in DRF, you should set the user field as read_only and override appropriate methods and fetch the logged-in user from request object.


问:
Ubuntu-19.10 Qt Lib Anaconda-Navigator Error
Somewhat of a Ubuntu noob coming from windows, so i hope its an easy fix.

This is the error I get when I try to launch Anaconda:

Cannot mix incompatible Qt library (version 0x50905) with this library (version 0x50907)
Aborted (core dumped)

So my thought is that there is an environment variable that needs to be tweaked to point to a native version of qt that comes with conda. Any help would be great, i need line by line instructions if possible, still new.

Thanks

答: I was running a retro theme on my terminal that somehow interfered with the QT versions. </p>


问:
Using PHP to echo specific data from MySQL rows?
Here's an example of my MySQL table:

```<code>id, type, value
1, total_clicks, 15
2, total_revenue, 32.42
3, conversion_rate, 1.432
</code>```

I'm using this command to get all of those rows:

```<code>SELECT * FROM statistics
</code>```

How can I use PHP to echo the value column based upon what's in the type column?

For example, how would I do something like this:

```<code>echo "We found that $total_clicks generated $total_revenue in revenue.";
</code>```

Normally I would have each of these as a column and use fetch_assoc to echo the value of each column, but for some reason the decided to break this data up into rows...

答:
One method uses aggregation:</p>

```<code>select replace(replace('We found that [total_clicks] generated [total_revenue] in revenue.',
                       '[total_clicks]',
                       max(case when type = 'total_clicks' then value end)
                      ), '[total_revenue],
                      max(case when type = 'total_revenue' then value end)
              )
from statistics;
</code>```

Body:
Here's an example of my MySQL table:

id, type, value
1, total_clicks, 15
2, total_revenue, 32.42
3, conversion_rate, 1.432

I'm using this command to get all of those rows:

SELECT * FROM statistics

How can I use PHP to echo the value column based upon what's in the type column?

For example, how would I do something like this:

echo "We found that $total_clicks generated $total_revenue in revenue.";

Normally I would have each of these as a column and use fetch_assoc to echo the value of each column, but for some reason the decided to break this data up into rows...

Body:
One method uses aggregation:

select replace(replace('We found that [total_clicks] generated [total_revenue] in revenue.',
                       '[total_clicks]',
                       max(case when type = 'total_clicks' then value end)
                      ), '[total_revenue],
                      max(case when type = 'total_revenue' then value end)
              )
from statistics;


问:
Nested While loop not working (C++ problem)
I am trying to output a triangle sort of figure based on the user entered number.
For example, if the user enters 3, the output should be:

1

12

123

but all I am getting is

1

2

3

what do I need to fix?

```<code>//File: digits.cpp
//Created by: Noah Bungart
//Created on: 02/16/2020

#include <iostream>
#include <cmath>
using namespace std;

int main(){

    int Rows;
    cout << "Enter number of rows: ";
    cin >> Rows;

    int i = 1;
    int j = 1;

    while (i <= Rows){
        while (j <= i){     //Should be iterating through j loop but isn't
            if (i < 10){
                cout << j;
            }
            if (i >= 10){
              cout << (j % 10);
            }
            j++;
        }
        cout << endl;
        i++;
    }
    return(0);
}
</code>```

答:
You just forgot to "reset" the j variable.

Just add a j = 1; just after the i++ (or before the second while loop).

Body:
I am trying to output a triangle sort of figure based on the user entered number.
For example, if the user enters 3, the output should be:

1

12

123

but all I am getting is

1

2

3

what do I need to fix?

//File: digits.cpp
//Created by: Noah Bungart
//Created on: 02/16/2020

#include <iostream>
#include <cmath>
using namespace std;

int main(){

    int Rows;
    cout << "Enter number of rows: ";
    cin >> Rows;

    int i = 1;
    int j = 1;

    while (i <= Rows){
        while (j <= i){     //Should be iterating through j loop but isn't
            if (i < 10){
                cout << j;
            }
            if (i >= 10){
              cout << (j % 10);
            }
            j++;
        }
        cout << endl;
        i++;
    }
    return(0);
}


问:
C and derived data types?
I know the fundamental data types in C - char, int, float etc. But What exactly are derived data types in C language?

答:
6.2.5.20 of the standard (well, a draft; hooray free :) covers derived types:

20 Any number of derived types can be constructed from the object, function, and
     incomplete types, as follows:

     -- An array type describes a contiguously allocated nonempty set of objects with a
         particular member object type, called the element type. Array types are
         characterized by their element type and by the number of elements in the array. An
         array type is said to be derived from its element type, and if its element type is T, the
         array type is sometimes called array of T. The construction of an array type from
         an element type is called array type derivation.

     -- A structure type describes a sequentially allocated nonempty set of member objects
         (and, in certain circumstances, an incomplete array), each of which has an optionally
         specified name and possibly distinct type.

     -- A union type describes an overlapping nonempty set of member objects, each of
         which has an optionally specified name and possibly distinct type.

     -- A function type describes a function with specified return type. A function type is
         characterized by its return type and the number and types of its parameters. A
         function type is said to be derived from its return type, and if its return type is T , the
         function type is sometimes called function returning T. The construction of a
         function type from a return type is called function type derivation.

     -- A pointer type may be derived from a function type, an object type, or an incomplete
         type, called the referenced type. A pointer type describes an object whose value
         provides a reference to an entity of the referenced type. A pointer type derived from
         the referenced type T is sometimes called pointer to T. The construction of a
         pointer type from a referenced type is called pointer type derivation.

These methods of constructing derived types can be applied recursively.

Title: C and derived data types?


答:
After struggling through various approach We found a solution explained below:

We store token (encrypted) in cookies  on login request and for each subsequent request this cookie gets validated.

The problem was if someone replace the token in cookie with another valid token, as cookies are maintained by client browser.

Solution :-> Though token values were encrypted, it was representing only one value, So if one replace whole encrypted value with another valid encrypted value it can be hacked.

So to solve this we have added another cookie which was combination of multiple values.

e.g.

Cookie 1 -> encrypted token

Cookie 2 -> An encrypted object containing information like username+ some other user context details+token

So in case of Cookie 1, it was easy to replace with another encrypted value as it was representing only one token though it was encrypted.

But in case of Cookie 2, it was containing object with multiple values, so only token value can not be modified, encrypted and set back in same cookie.

Before authentication We are doing decryption whole cookie 2, fetch token part from it and validate the token part of it against cookie 1.

That has solved our problem !!

Thanks all for your time and guidance.

Title: How to prevent Rest web-service Authentication with stolen Token

Body:
As we know Rest services are stateless, General strategies to authenticate is using a token based authentication.

In login service it takes credentials which returns a token.

This token might be set in client cookies, and all subsequent requests uses this token to be validated and process new request if token is valid.

Now my question is how one can validate the token ? If someone has stolen the token and tries to access rest services with stolen token by just editing cookies then how can it be identified and restricted ?

We can never know if the token is fetched by valid user and same user is trying to access subsequent request. but what are the possible ways to make it more hard, like to verify if the request has came from same source ?

One general suggestion is to set aging for token/cookies, but it still not helpful till the age of that token/cookies.

Any suggestions would be appreciated.


问:
How to label every nth row of a pandas dataframe by an incremental value
I have a simple problem (hopefully!). and i am overly complicating it. Maybe there is a one liner out there; I have a dataframe that contains lets say 10 rows and I want to label rows in such a way it looks like col B. Every 4th row has an different label.

```<code>Row B
1   1
2   1
3   1
4   1
5   2
6   2
7   2
8   2
9   3
10  3
</code>```

I tried iterating by dataframe position and ended up complicating it.

```<code>num =4
id=1
    def label_id(x,num,id):
        if x > num:
          id=id+1
          label=id
          num=num*id
        else:
            label = id
            id=id
        return label
    id=1
    for i in range(len(df)):
        df.iat[i,1] = df.apply(label_id(df.iat[i,0],num,id),axis=1)
</code>```

i get an error TypeError: ("'int' object is not callable", 'occurred at index 0'). I am sure i am overthinking this. Any help?

Body:
I have a simple problem (hopefully!). and i am overly complicating it. Maybe there is a one liner out there; I have a dataframe that contains lets say 10 rows and I want to label rows in such a way it looks like col B. Every 4th row has an different label.

Row B
1   1
2   1
3   1
4   1
5   2
6   2
7   2
8   2
9   3
10  3

I tried iterating by dataframe position and ended up complicating it.

num =4
id=1
    def label_id(x,num,id):
        if x > num:
          id=id+1
          label=id
          num=num*id
        else:
            label = id
            id=id
        return label
    id=1
    for i in range(len(df)):
        df.iat[i,1] = df.apply(label_id(df.iat[i,0],num,id),axis=1)

i get an error TypeError: ("'int' object is not callable", 'occurred at index 0'). I am sure i am overthinking this. Any help?

Body:
From numpy divmod

f['B']=np.divmod(np.arange(len(df)),4)[0]+1
df
   Row  B
0    1  1
1    2  1
2    3  1
3    4  1
4    5  2
5    6  2
6    7  2
7    8  2
8    9  3
9   10  3


问:
How to convert gulp watch script into gulp 4
I have upgraded my node version to v12 recently and i have an angular project which is running on gulp 3.8, by following some suggestions I have upgraded my gulp version to 4.0 and modified some scripts with gulp.series and parallel. but I'm getting problem in this below script. Can any once help me to convert the below watch file into gulp 4.0 script.</p>

```<code>
var gulp = require('gulp');

var paths = gulp.paths;

gulp.task('watch', ['inject'], function () {
  gulp.watch([
    paths.src + '/*.html',
    paths.src + '/{app,components}/**/*.less',
    paths.src + '/{app,components}/**/*.js',
    'bower.json'
  ], ['inject']);
});
</code>```

答:
```<code>gulp.task('watch', gulp.series('inject', function () {
  gulp.watch([
    paths.src + '/*.html',
    paths.src + '/{app,components}/**/*.less',
    paths.src + '/{app,components}/**/*.js',
    'bower.json'

   ], 'inject');  // this should work as well since you have only one task to run
  //   however in the future you may want to add another task as in the below.
  // ], gulp.series('inject', 'anotherTask`));

}));
</code>```

Tasks are not in arrays in v4, but in gulp.series or gulp.parallel.

Body:
I have upgraded my node version to v12 recently and i have an angular project which is running on gulp 3.8, by following some suggestions I have upgraded my gulp version to 4.0 and modified some scripts with gulp.series and parallel. but I'm getting problem in this below script. Can any once help me to convert the below watch file into gulp 4.0 script.

var gulp = require('gulp');

var paths = gulp.paths;

gulp.task('watch', ['inject'], function () {
  gulp.watch([
    paths.src + '/*.html',
    paths.src + '/{app,components}/**/*.less',
    paths.src + '/{app,components}/**/*.js',
    'bower.json'
  ], ['inject']);
});

Body:
gulp.task('watch', gulp.series('inject', function () {
  gulp.watch([
    paths.src + '/*.html',
    paths.src + '/{app,components}/**/*.less',
    paths.src + '/{app,components}/**/*.js',
    'bower.json'

   ], 'inject');  // this should work as well since you have only one task to run
  //   however in the future you may want to add another task as in the below.
  // ], gulp.series('inject', 'anotherTask`));

}));

Tasks are not in arrays in v4, but in gulp.series or gulp.parallel.


问:
How do you temporarily hide a table in React?
I need to display a different background when a modal shows up so I need to hide the table until the user submits the form in the modal. Any ideas? I can't find any show or hide attributes for a Table.

Table

```<code>import React, { Component } from 'react';
import Table from "react-bootstrap/Table";
import SampleQ from '../components/question.js';
import css from '../scss/style.scss';
import Layout from '../components/layout';

export default class extends Component {
    constructor(props) {
        super(props);

        this.state = {
            showBackground: false
        };

        this.showBackground = () => {
            this.setState({ showBackground: true });
        };

        this.hideBackground = () => {
            this.setState({ showBackground: false });
        }
    }

    static getInitialProps({query: {categories, questions, answers}}) {
        return {postCs: categories, allQs: questions, allAs: answers}
    }

    createTable = () => {
        let table = [];

        let cats = [];

        for (let i = 0; i < this.props.postCs.length; i++){
            cats.push(<th key = {i}>{this.props.postCs[i].title}</th>);
        }

        table.push(<thead> <tr> {cats} </tr> </thead>);

        let index = 0;
        // Outer loop to create parent
        for (let i = 1; i < 6; i++) {
            let children = [];

            //Inner loop to create children
            for (let j = 1; j < 7; j++) {
                children.push(
                    <td>
                        <div>
                            <SampleQ
                                amount={i}
                                question={this.props.allQs[(index)].title}
                                answer={this.props.allAs[(index)].title}
                                showBackdrop={this.showBackground}
                                hideBackdrop={this.hideBackground}
                            />
                        </div>
                    </td>);
                index++;
            }
            //Create the parent and add the children
            table.push(<tr>{children}</tr>)
        }

        return table
    };

    render() {
        return (
            <div>
                <Layout showBackground={this.state.showBackground} title="lllll" />
                <Table striped bordered hover variant = "dark" className={css.table} hide={true}>
                    {this.createTable()}
                </Table>
            </div>
        )
    }
}
</code>```

答:
You might want to use conditional rendering, e.g.</p>

```<code>render () {
  return (
    <Modal>
      {isFormSubmitted ? <Table /> : null}
    </Modal>
  )
}
</code>```

Body:
I need to display a different background when a modal shows up so I need to hide the table until the user submits the form in the modal. Any ideas? I can't find any show or hide attributes for a Table.

Table

import React, { Component } from 'react';
import Table from "react-bootstrap/Table";
import SampleQ from '../components/question.js';
import css from '../scss/style.scss';
import Layout from '../components/layout';

export default class extends Component {
    constructor(props) {
        super(props);

        this.state = {
            showBackground: false
        };

        this.showBackground = () => {
            this.setState({ showBackground: true });
        };

        this.hideBackground = () => {
            this.setState({ showBackground: false });
        }
    }

    static getInitialProps({query: {categories, questions, answers}}) {
        return {postCs: categories, allQs: questions, allAs: answers}
    }

    createTable = () => {
        let table = [];

        let cats = [];

        for (let i = 0; i < this.props.postCs.length; i++){
            cats.push({this.props.postCs[i].title}	);
        }

        table.push(

 {cats}

);

        let index = 0;
        // Outer loop to create parent
        for (let i = 1; i < 6; i++) {
            let children = [];

            //Inner loop to create children
            for (let j = 1; j < 7; j++) {
                children.push(

                            <SampleQ
                                amount={i}
                                question={this.props.allQs[(index)].title}
                                answer={this.props.allAs[(index)].title}
                                showBackdrop={this.showBackground}
                                hideBackdrop={this.hideBackground}
                            />

                    	);
                index++;
            }
            //Create the parent and add the children
            table.push(
{children}
)
        }

        return table
    };

    render() {
        return (

                <Layout showBackground={this.state.showBackground} title="lllll" />

                    {this.createTable()}

        )
    }
}

Body:
You might want to use conditional rendering, e.g.

render () {
  return (
    <Modal>
      {isFormSubmitted ? <Table /> : null}
    </Modal>
  )
}


问:
Implement Internal Interface in Tests
I have made internal classes and functions visible to my test project via:

```<code><ItemGroup>
  <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
    <_Parameter1>MyProject.Tests</_Parameter1>
  </AssemblyAttribute>
</ItemGroup>
</code>```

This works fine, but now I am trying to implement the following internal interface in my tests for mocking purposes:

```<code>internal interface IRepository
{
    void Function1();
}
</code>```

In my test code, I have implemented the above interface as follows:

```<code>internal class MockRepository : IRepository
{
    internal void Function1()
    {
        // Do something.
    }
}
</code>```

However, I am getting the following error:

'MockRepository' does not implement interface member 'IRepository.Function1()'. 'MockRepository.Function1()' cannot implement an interface member because it is not public. [MyProject.Tests]

It seems that InternalsVisibleToAttribute only applies to classes and functions.

Do I really have to make my internal interface public to let tests mock it, or is there a way to keep it internal?

I ask because I want to keep as many things accessible only to my project and its tests.

答:
I just figured it out. Turns out all I needed to do was make the implementation itself public.

The mock class itself can stay internal:

```<code>internal class MockRepository : IRepository
{
    public void Function1()
    {
        // Do something.
    }
}
</code>```

Title: Implement Internal Interface in Tests

Body:
I have made internal classes and functions visible to my test project via:

<ItemGroup>
  <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
    <_Parameter1>MyProject.Tests</_Parameter1>
  </AssemblyAttribute>
</ItemGroup>

This works fine, but now I am trying to implement the following internal interface in my tests for mocking purposes:

internal interface IRepository
{
    void Function1();
}

In my test code, I have implemented the above interface as follows:

internal class MockRepository : IRepository
{
    internal void Function1()
    {
        // Do something.
    }
}

However, I am getting the following error:

'MockRepository' does not implement interface member 'IRepository.Function1()'. 'MockRepository.Function1()' cannot implement an interface member because it is not public. [MyProject.Tests]

It seems that InternalsVisibleToAttribute only applies to classes and functions.

Do I really have to make my internal interface public to let tests mock it, or is there a way to keep it internal?

I ask because I want to keep as many things accessible only to my project and its tests.

Body:
I just figured it out. Turns out all I needed to do was make the implementation itself public.

The mock class itself can stay internal:

internal class MockRepository : IRepository
{
    public void Function1()
    {
        // Do something.
    }
}


答:
The hash does not contain the input.

You cannot reverse a hash function, provide the output (hash) to retrieve the input.

The corollary to this is that they are are many inputs that could result in the same hash; it's just very improbable that, for a given hash, someone could find any (other) input that generates it.

There's been news recently about the SHA1 hashing algorithm as clever folks are now able to determine inputs that will generate a given hash.

Title: MD5 Hash Conversion


问:
What is going on here: rspec stub(:new).with...?
I'm a little confused about what is going on with the scaffold controller specs that rspec generates.  It seemed to be making sense until I added authorization to my app and now I need to update my tests.

```<code>MyClass.stub(:new).with('these' => 'params') { mock_my_class(:save => true) }
</code>```

In my controller I merge a hash into params when creating a new record (it needs the current_user id to be valid).  MyClass.new(params[:my_class].merge(:user_id => current_user.id))

Test Fails

```<code>expected: ({"these"=>"params"})
got: ({"these"=>"params", "user_id"=>315})
</code>```

It makes sense that the test fails because the new method receives params it didn't expect. It expected to receive {'these' => 'params'} but it actually received {'these' => 'params', 'user_id' => 1234}

So my natural reaction is to adjust the test because the new method should receive {'these' => 'params', 'user_id' => 1234} and return the mock object.

So I add to the test as follows:

```<code>   MyClass.stub(:new).with({'these' => 'params', 'user_id' => @user.id}) { mock_my_class(:save => true) }
</code>```

Here is where I get thrown through a loop.  The output of the test is as follows:

```<code>expected: ({"these"=>"params", "user_id"=>298})
got: ({"these"=>"params"})
</code>```

It seems as if a successful test is magically evading me.  I'm sure there is a logical reason for these results, but I can't seem to figure them out.

Any help? :)

note:

The rspec site says the following:

```<code>Account.should_receive(:find).with("37").and_return(account)
</code>```

or

```<code>Account.stub!(:find).and_return(account)
</code>```

This is easy enough to follow it just seems odd the the scaffold generated would not contain these methods (unless I botched something which is possible (:  )

Passes

```<code>login_admin
describe "with valid params" do
  it "assigns a newly created forum_sub_topic as @forum_sub_topic" do
    ForumSubTopic.stub(:new) { mock_forum_sub_topic(:save => true) }
    ForumSubTopic.should_receive(:new).with({"these"=>"params", "user_id"=> @admin.id})  #PASS!
    post :create, :forum_sub_topic => {'these' => 'params'}
    assigns(:forum_sub_topic).should be(mock_forum_sub_topic) #PASS!
  end
end
</code>```

Fails

```<code>login_admin
describe "with valid params" do
  it "assigns a newly created forum_sub_topic as @forum_sub_topic" do
    ForumSubTopic.stub(:new).with({'these' => 'params', 'user_id' => @user.id}) { mock_forum_sub_topic(:save => true) }
    post :create, :forum_sub_topic => {'these' => 'params'}
    assigns(:forum_sub_topic).should be(mock_forum_sub_topic)
  end
end
</code>```

答:
"Never trust a junkie", as the saying goes. One could also say, "never trust a scaffold".

OK, that's being a little bit too harsh. The scaffold does its best to figure out which parameters will work for the models/controllers you are generating, but it doesn't know about nested resources (which is what I assume you are using), so it won't generate the user_id in the params hash. Add that:

```<code>post :create, :forum_sub_topic => {:user_id=>@user.id}
</code>```

The these_params key is generated as an example — remove it and add whatever parameters are needed for the controller to create a MyClass.

Regarding the with option: stub and should_receive will only stub out messages that meet the specified conditions, i.e. if you do:

```<code>MyClass.stub(:new) {mock_model(MyClass,:save=>true)}
</code>```

Then MyClass will respond to any new message with the mock. If, on the other hand, you do:

```<code>MyClass.stub(:new).with({:bogus=>37}) {mock_model(MyClass,:save=>true)}
</code>```

Then MyClass will only respond to new when it also receives {:bogus=>37} as an argument.

Body:
I'm a little confused about what is going on with the scaffold controller specs that rspec generates.  It seemed to be making sense until I added authorization to my app and now I need to update my tests.

MyClass.stub(:new).with('these' => 'params') { mock_my_class(:save => true) }

In my controller I merge a hash into params when creating a new record (it needs the current_user id to be valid).  MyClass.new(params[:my_class].merge(:user_id => current_user.id))

Test Fails

expected: ({"these"=>"params"})
got: ({"these"=>"params", "user_id"=>315})

It makes sense that the test fails because the new method receives params it didn't expect. It expected to receive {'these' => 'params'} but it actually received {'these' => 'params', 'user_id' => 1234}

So my natural reaction is to adjust the test because the new method should receive {'these' => 'params', 'user_id' => 1234} and return the mock object.

So I add to the test as follows:

   MyClass.stub(:new).with({'these' => 'params', 'user_id' => @user.id}) { mock_my_class(:save => true) }

Here is where I get thrown through a loop.  The output of the test is as follows:

expected: ({"these"=>"params", "user_id"=>298})
got: ({"these"=>"params"})

It seems as if a successful test is magically evading me.  I'm sure there is a logical reason for these results, but I can't seem to figure them out.

Any help? :)

note:

The rspec site says the following:

Account.should_receive(:find).with("37").and_return(account)

or

Account.stub!(:find).and_return(account)

This is easy enough to follow it just seems odd the the scaffold generated would not contain these methods (unless I botched something which is possible (:  )

Passes

login_admin
describe "with valid params" do
  it "assigns a newly created forum_sub_topic as @forum_sub_topic" do
    ForumSubTopic.stub(:new) { mock_forum_sub_topic(:save => true) }
    ForumSubTopic.should_receive(:new).with({"these"=>"params", "user_id"=> @admin.id})  #PASS!
    post :create, :forum_sub_topic => {'these' => 'params'}
    assigns(:forum_sub_topic).should be(mock_forum_sub_topic) #PASS!
  end
end

Fails

login_admin
describe "with valid params" do
  it "assigns a newly created forum_sub_topic as @forum_sub_topic" do
    ForumSubTopic.stub(:new).with({'these' => 'params', 'user_id' => @user.id}) { mock_forum_sub_topic(:save => true) }
    post :create, :forum_sub_topic => {'these' => 'params'}
    assigns(:forum_sub_topic).should be(mock_forum_sub_topic)
  end
end

Body:
"Never trust a junkie", as the saying goes. One could also say, "never trust a scaffold".

OK, that's being a little bit too harsh. The scaffold does its best to figure out which parameters will work for the models/controllers you are generating, but it doesn't know about nested resources (which is what I assume you are using), so it won't generate the user_id in the params hash. Add that:

post :create, :forum_sub_topic => {:user_id=>@user.id}

The these_params key is generated as an example — remove it and add whatever parameters are needed for the controller to create a MyClass.

Regarding the with option: stub and should_receive will only stub out messages that meet the specified conditions, i.e. if you do:

MyClass.stub(:new) {mock_model(MyClass,:save=>true)}

Then MyClass will respond to any new message with the mock. If, on the other hand, you do:

MyClass.stub(:new).with({:bogus=>37}) {mock_model(MyClass,:save=>true)}

Then MyClass will only respond to new when it also receives {:bogus=>37} as an argument.


问:
How do I compare 2 different sized 2D arrays?
The first 2D array is

```<code>[[1, 10], [0, 4], [1, 1]]
</code>```

The second 2D array is

```<code>[[0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10]]
</code>```

How do I find if they have values overlapping in the 2nd column?

And after finding the overlap, how do I replace the element in the 2nd 2D array with the 1st 2D array?

For example:

[1, 10] from the 1st 2D array has the same 2nd column value as [0, 10] from the 2nd 2D array. Then, I replace [0, 10] with [1, 10].

答:
```<code>    int[][] first = {{1, 10}, {0, 4}, {1, 1}};
    int[][] second = {{0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {0, 6}, {0, 7}, {0, 8}, {0, 9}, {0, 10}};

    // first lets build a map for easy lookup of values
    // produces map {1=1, 4=0, 10=1}
    final Map<Integer, Integer> map = Stream.of(first)
            .collect(Collectors.toMap(key -> key[1], value -> value[0]));

    // then we can do simple loop
    for (int[] pair : second) {
        // and if it contains the key (second column)
        if (map.containsKey(pair[1])) {
            // then we can just replace the value
            pair[0] = map.get(pair[1]);
        }
    }
</code>```

Body:
The first 2D array is

[[1, 10], [0, 4], [1, 1]]

The second 2D array is

[[0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10]]

How do I find if they have values overlapping in the 2nd column?

And after finding the overlap, how do I replace the element in the 2nd 2D array with the 1st 2D array?

For example:

[1, 10] from the 1st 2D array has the same 2nd column value as [0, 10] from the 2nd 2D array. Then, I replace [0, 10] with [1, 10].


问:
Is it possible to create a slider for Conway's game of life if birth happens only when there are FOUR living neighbours?
I'm just playing around with Conway's game of life and I adjusted the settings so that birth only happens when there are 4 living neighbours. A cell will die when the living neighbours != 2.

After a lot of trying I still can't find a slider, is this probably just impossible?!

Thanks in advance!

答:
No, a Life-like cellular automaton where births require at least four live neighbors cannot have gliders.

To see why, take any isolated cluster of live cells on the lattice and draw a box around it.  Now observe that any cell outside the box has at most three neighboring cells that are inside the box.  This means that the cluster of cells inside the box can never move or expand outside the box.


问:
Time limit exceeds
There are N drivers participating in the Championship. They are all assigned points after each race, including the final one. The winner of the race is awarded N points, the runner-up gets N - 1 points, and so on until the last driver, who gets 1 point. Two drivers cannot finish a race in the same spot.

Write a program to calculate, based on the total number of points that each driver has earned before the final race, how many drivers still have a chance to have the largest total after the final race and thus win the Championship. If more than one driver has the same maximum point total, they are all awarded the World Champion title.

I am getting time limit exceeded for all test cases and My code is failing for one test case for 100 participants.
Test cases are:

test case-1:

3

10

9

8

output-3

test case-2:

5

15

14

12

14

15

output-4

Here is my code:

```<code>n=int(input())
b=[]
for i in range(n) :
    b.append(int(input()))
l=len(b)
c=l
sort(b)-->>> some sorting algo to sort in O(n*logn)
for i in range(len(b)) :
    x=b[i]
    x+=l
    for j in range(i+1,len(b)) :
        l-=1
        y=b[j]
        y+=l
        if y>x :
            c-=1
            break
print(c)``
</code>```

答:
You overcomplicate things, this can be easily solved in O(NlogN), assume results is the current results of the drivers and N is the number of the drivers. All you have to do is:

```<code>N = 5
results = [ 15, 14, 12, 14, 15 ]
# find who can achieve the highest result
max_points = max([a+b for a,b in enumerate(sorted(results, reverse=True))])
# now count how many drivers can get as much as "max_points"
has_potential = [ 1 for r in results if r+N-1 >= max_points ]
print len(has_potential)   # print the result
</code>```

output:

```<code>4
</code>```

Title: Time limit exceeds

Body:
There are N drivers participating in the Championship. They are all assigned points after each race, including the final one. The winner of the race is awarded N points, the runner-up gets N - 1 points, and so on until the last driver, who gets 1 point. Two drivers cannot finish a race in the same spot.

Write a program to calculate, based on the total number of points that each driver has earned before the final race, how many drivers still have a chance to have the largest total after the final race and thus win the Championship. If more than one driver has the same maximum point total, they are all awarded the World Champion title.

I am getting time limit exceeded for all test cases and My code is failing for one test case for 100 participants.
Test cases are:

test case-1:

3

10

9

8

output-3

test case-2:

5

15

14

12

14

15

output-4

Here is my code:

n=int(input())
b=[]
for i in range(n) :
    b.append(int(input()))
l=len(b)
c=l
sort(b)-->>> some sorting algo to sort in O(n*logn)
for i in range(len(b)) :
    x=b[i]
    x+=l
    for j in range(i+1,len(b)) :
        l-=1
        y=b[j]
        y+=l
        if y>x :
            c-=1
            break
print(c)``

Body:
You overcomplicate things, this can be easily solved in O(NlogN), assume results is the current results of the drivers and N is the number of the drivers. All you have to do is:

N = 5
results = [ 15, 14, 12, 14, 15 ]
# find who can achieve the highest result
max_points = max([a+b for a,b in enumerate(sorted(results, reverse=True))])
# now count how many drivers can get as much as "max_points"
has_potential = [ 1 for r in results if r+N-1 >= max_points ]
print len(has_potential)   # print the result

output:

4


问:
Is an index used when joining a dynamic table?
```<code>SELECT term, ...
  FROM tbl INNER JOIN
       (SELECT 'constant 1' AS term
         UNION
        SELECT 'constant x' AS term) AS T USING (term)
 WHERE ...
</code>```

There is an index on term column in tbl.

Suppose the union is thousands long, does performance suffer since the constants are specified out of thin air or is the index used because it exists in tbl?

答:
Let's see what EXPLAIN SELECT ...; says.  It will say which, if any index(es) are being used.

But that won't answer the "real" question -- How can the query be sped up.

For the table, as it stands, the optimal index on tbl is any index starting with term.

UNION is the same as UNION DISTINCT, which gathers the rows, then de-duplicates the result.  I suspect you do not need the de-dup?  Then change them to UNION ALL.

What version of MySQL?  In old versions, UNION always created a temp table.  In newer versions, the UNION ALL that you will have would probably qualify for skipping the temp table.  (But I am not sure about the "derived" table that you have.)  Again, the EXPLAIN would help determine that.  Even better would be EXPLAIN FORMAT=JSON SELECT ...  Please trim it if there are thousands of items.

There may be a better way!

```<code>SELECT term, ...
    FROM tbl INNER JOIN
    WHERE term IN('constant 1', 'constant x', ...)
      AND ...
</code>```

There may be more optimizations, but we need to see SHOW CREATE TABLE, and the rest of the query.  (Only a sampling of the constants will suffice, but the othere ellipses may hold useful secrets.)

Body:
SELECT term, ...
  FROM tbl INNER JOIN
       (SELECT 'constant 1' AS term
         UNION
        SELECT 'constant x' AS term) AS T USING (term)
 WHERE ...

There is an index on term column in tbl.

Suppose the union is thousands long, does performance suffer since the constants are specified out of thin air or is the index used because it exists in tbl?

Body:
Let's see what EXPLAIN SELECT ...; says.  It will say which, if any index(es) are being used.

But that won't answer the "real" question -- How can the query be sped up.

For the table, as it stands, the optimal index on tbl is any index starting with term.

UNION is the same as UNION DISTINCT, which gathers the rows, then de-duplicates the result.  I suspect you do not need the de-dup?  Then change them to UNION ALL.

What version of MySQL?  In old versions, UNION always created a temp table.  In newer versions, the UNION ALL that you will have would probably qualify for skipping the temp table.  (But I am not sure about the "derived" table that you have.)  Again, the EXPLAIN would help determine that.  Even better would be EXPLAIN FORMAT=JSON SELECT ...  Please trim it if there are thousands of items.

There may be a better way!

SELECT term, ...
    FROM tbl INNER JOIN
    WHERE term IN('constant 1', 'constant x', ...)
      AND ...

There may be more optimizations, but we need to see SHOW CREATE TABLE, and the rest of the query.  (Only a sampling of the constants will suffice, but the othere ellipses may hold useful secrets.)


答:
You have a couple of options to store the results from the query and then output them in PHP:

an associative array

```<code>    while ($row = $result->fetch_assoc()) {
        $data[$row['type']] = $row['value'];
    }
    echo "We found that {$data['total_clicks']} generated {$data['total_revenue']} in revenue.";
</code>```

variable variables

```<code>    while ($row = $result->fetch_assoc()) {
        ${$row['type']} = $row['value'];
    }
    echo "We found that $total_clicks generated $total_revenue in revenue.";
</code>```

Title: Using PHP to echo specific data from MySQL rows?

Body:
Here's an example of my MySQL table:

id, type, value
1, total_clicks, 15
2, total_revenue, 32.42
3, conversion_rate, 1.432

I'm using this command to get all of those rows:

SELECT * FROM statistics

How can I use PHP to echo the value column based upon what's in the type column?

For example, how would I do something like this:

echo "We found that $total_clicks generated $total_revenue in revenue.";

Normally I would have each of these as a column and use fetch_assoc to echo the value of each column, but for some reason the decided to break this data up into rows...

Body:
You have a couple of options to store the results from the query and then output them in PHP:

an associative array

    while ($row = $result->fetch_assoc()) {
        $data[$row['type']] = $row['value'];
    }
    echo "We found that {$data['total_clicks']} generated {$data['total_revenue']} in revenue.";

variable variables

    while ($row = $result->fetch_assoc()) {
        ${$row['type']} = $row['value'];
    }
    echo "We found that $total_clicks generated $total_revenue in revenue.";


问:
I am getting a 'Cannot set property 'variable' of undefined' in the following component
The component will render a list of values fetched from an API. I am getting the following component initialization issue:

```<code>Cannot set property 'hits' of undefined
</code>```

display-recipes.component.ts:

```<code>import { Component, OnInit, Input} from '@angular/core';
import { SearchRecipeService } from '../search-recipe.service';
import { RecipeGlobal } from '../pojos/RecipeGlobal';

@Component({
  selector: 'app-display-recipes',
  templateUrl: './display-recipes.component.html',
  styleUrls: ['./display-recipes.component.css']
})
export class DisplayRecipesComponent implements OnInit {

  @Input() calories: String;
  @Input() recipe: String;
  recipeResult: RecipeGlobal;
  constructor(private searchRecipeService: SearchRecipeService) { }

  ngOnInit() {
     this.recipeResult.hits = [];
  }

  ngOnChanges(){
    this.getRecipeInfo();
  }

  getRecipeInfo(){
     this.searchRecipeService.getRecipeInfo().
     subscribe(recipeResult => this.recipeResult = recipeResult);
  }

}
</code>```

display-recipes.component.html

```<code><p>display-recipes works!</p>
<div id='display_recipe'  *ngFor="let recipe of recipeResult.hits">
    {{recipe.label}}
</div>
</code>```

RecipeGlobal.ts

```<code>export class RecipeGlobal{
    q: String;
    hits: Recipe[];
}

export class Recipe{
    image: String;
    calories: String;
    label: String
}
</code>```

I am failing to understand how objects are initialized in typescript. If I declare a non primitive inside the object, do I have to initialize it?. If so, in this case how should I initialize the array?.

答:
You must start your variable on declaration. recipeResult: RecipeGlobal = {};. When you are starting the array in ngOnInit, the variable is undefined. so this.recipeResult.hits generates a null pointer.

For that you need to put all attributes as optionals:

```<code>export class RecipeGlobal{
    q?: String;
    hits?: Recipe[];
}
</code>```

Or you don't initialize the variable, then in your ngFor you must use safe navigation operator ?.

```<code><p>display-recipes works!</p>
<div id='display_recipe'  *ngFor="let recipe of recipeResult?.hits">
    {{recipe.label}}
</div>
</code>```

Body:
The component will render a list of values fetched from an API. I am getting the following component initialization issue:

Cannot set property 'hits' of undefined

display-recipes.component.ts:

import { Component, OnInit, Input} from '@angular/core';
import { SearchRecipeService } from '../search-recipe.service';
import { RecipeGlobal } from '../pojos/RecipeGlobal';

@Component({
  selector: 'app-display-recipes',
  templateUrl: './display-recipes.component.html',
  styleUrls: ['./display-recipes.component.css']
})
export class DisplayRecipesComponent implements OnInit {

  @Input() calories: String;
  @Input() recipe: String;
  recipeResult: RecipeGlobal;
  constructor(private searchRecipeService: SearchRecipeService) { }

  ngOnInit() {
     this.recipeResult.hits = [];
  }

  ngOnChanges(){
    this.getRecipeInfo();
  }

  getRecipeInfo(){
     this.searchRecipeService.getRecipeInfo().
     subscribe(recipeResult => this.recipeResult = recipeResult);
  }

}

display-recipes.component.html

display-recipes works!

    {{recipe.label}}

RecipeGlobal.ts

export class RecipeGlobal{
    q: String;
    hits: Recipe[];
}

export class Recipe{
    image: String;
    calories: String;
    label: String
}

I am failing to understand how objects are initialized in typescript. If I declare a non primitive inside the object, do I have to initialize it?. If so, in this case how should I initialize the array?.

Body:
You must start your variable on declaration. recipeResult: RecipeGlobal = {};. When you are starting the array in ngOnInit, the variable is undefined. so this.recipeResult.hits generates a null pointer.

For that you need to put all attributes as optionals:

export class RecipeGlobal{
    q?: String;
    hits?: Recipe[];
}

Or you don't initialize the variable, then in your ngFor you must use safe navigation operator ?.

<p>display-recipes works!</p>
<div id='display_recipe'  *ngFor="let recipe of recipeResult?.hits">
    {{recipe.label}}
</div>


问:
What is the alternative to rewritebase on IIS?
I have the following .htaccess file in my website - I'm having to relocate it to a windows IIS machine and having problems with using the URL-Rewrite module to import a rule and create a web.config file.

This is my .htaccess file

```<code># Rewrite URLs and direct to index.php

<IfModule mod_rewrite.c>
Options -Multiviews
RewriteEngine On
##
## If moving host, change the structure below to folder name of where public folder lives
##
RewriteBase /foldername/public
##
##
##
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule  ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>
</code>```

It fails on the RewriteBase but this I understand in the .htaccess file is crucial for my site to function.

Can anyone give me anyone pointers?

答:
It will convery to below url rewrite rule:</p>

```<code><rewrite>
  <rules>
    <rule name="Imported Rule 1" stopProcessing="true">
      <match url="^(.+)$" ignoreCase="false" />
      <conditions>
        <!--##-->
        <!--## If moving host, change the structure below to folder name of where public folder lives-->
        <!--##-->
        <!--##-->
        <!--##-->
        <!--##-->
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
      </conditions>
      <action type="Rewrite" url="/foldername/public/index.php?url={R:1}" appendQueryString="true" />
    </rule>
  </rules>
</rewrite>
</code>```

Body:
I have the following .htaccess file in my website - I'm having to relocate it to a windows IIS machine and having problems with using the URL-Rewrite module to import a rule and create a web.config file.

This is my .htaccess file

# Rewrite URLs and direct to index.php

<IfModule mod_rewrite.c>
Options -Multiviews
RewriteEngine On
##
## If moving host, change the structure below to folder name of where public folder lives
##
RewriteBase /foldername/public
##
##
##
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule  ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>

It fails on the RewriteBase but this I understand in the .htaccess file is crucial for my site to function.

Can anyone give me anyone pointers?

Body:
It will convery to below url rewrite rule:

<rewrite>
  <rules>
    <rule name="Imported Rule 1" stopProcessing="true">
      <match url="^(.+)$" ignoreCase="false" />
      <conditions>
        <!--##-->
        <!--## If moving host, change the structure below to folder name of where public folder lives-->
        <!--##-->
        <!--##-->
        <!--##-->
        <!--##-->
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
      </conditions>
      <action type="Rewrite" url="/foldername/public/index.php?url={R:1}" appendQueryString="true" />
    </rule>
  </rules>
</rewrite>


问:
FlowListView one separate label with FlowColumnCount = "1"
After using FlowListView I got the following result:

But the Emergency should be an other colour with an other click event and the size of FlowColumnCount = "1"

this is the following code:

```<code><?xml version="1.0" encoding="utf-8" ?>
</code>```

```<code>            <flv:FlowListView.FlowColumnTemplate>
                <DataTemplate>
                    <Frame BackgroundColor="Purple" Margin="5">
                        <Label HorizontalOptions="Fill"
                        VerticalOptions="Fill"
                        TextColor="White"
                        XAlign="Center"
                        YAlign="Center"
                        Text="{Binding Text}"/>
                    </Frame>
                </DataTemplate>
            </flv:FlowListView.FlowColumnTemplate>
        </flv:FlowListView>
    </StackLayout>
</ContentPage.Content>
</code>```

This is the MockDataStore:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DLToolkit.Forms.Controls;
using EscapeHaarlem.Models;

namespace EscapeHaarlem.Services
{
public class MockDataStore : IDataStore<Item>
{
    List<Item> items;

    public MockDataStore()
    {
        FlowListView.Init();
        items = new List<Item>();
        //this.items.Add(new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 1", Description = "This is an item description." });
        //this.items.Add(new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 2", Description = "This is an item description." });

        var mockItems = new List<Item>
        {
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 1", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 2", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 3", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 4", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 5", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 6", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 7", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 8", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 9", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 10", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 11", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 12", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 13", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 14", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Emergency", Description="This is an item description."},
        };

        foreach (var item in mockItems)
        {
            items.Add(item);
        }
    }

    public async Task<bool> AddItemAsync(Item item)
    {
        items.Add(item);

        return await Task.FromResult(true);
    }

    public async Task<bool> UpdateItemAsync(Item item)
    {
        var oldItem = items.Where((Item arg) => arg.Id == item.Id).FirstOrDefault();
        items.Remove(oldItem);
        items.Add(item);

        return await Task.FromResult(true);
    }

    public async Task<bool> DeleteItemAsync(string id)
    {
        var oldItem = items.Where((Item arg) => arg.Id == id).FirstOrDefault();
        items.Remove(oldItem);

        return await Task.FromResult(true);
    }

    public async Task<Item> GetItemAsync(string id)
    {
        return await Task.FromResult(items.FirstOrDefault(s => s.Id == id));
    }

    public async Task<IEnumerable<Item>> GetItemsAsync(bool forceRefresh = false)
    {
        return await Task.FromResult(items);
    }
}
</code>```

}

How could I achieve so that the emergency button has other color size and clickevent?

Thanks in advance

答:
Do you mean you want to let Emergency a separate column and have a separate click event, right ?

If yes,you may could display it with ListView.Footer,then you could defined its color,click event separately，like:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d"
         xmlns:flv="clr-namespace:DLToolkit.Forms.Controls;assembly=DLToolkit.Forms.Controls.FlowListView"
         x:Class="App18.FlowListPage">
<ContentPage.Content>
    <StackLayout>
        <flv:FlowListView FlowColumnCount="2"
            SeparatorVisibility="Default"
            HasUnevenRows="True"
            FlowItemTappedCommand="{Binding ItemTappedCommand}"
            FlowItemsSource="{Binding Items}">

            <flv:FlowListView.FlowColumnTemplate>
                <DataTemplate>
                    <Frame BackgroundColor="Purple"
            Margin="5">
                        <Label HorizontalOptions="Fill"
                VerticalOptions="Fill"
                TextColor="White"
                XAlign="Center"
                YAlign="Center"
                Text="{Binding Text}"/>
                    </Frame>
                </DataTemplate>
            </flv:FlowListView.FlowColumnTemplate>
            <flv:FlowListView.Footer>

                <StackLayout>
                    <Button Text="Emergency" BackgroundColor="Accent" Clicked="Button_Clicked"></Button>
                </StackLayout>

            </flv:FlowListView.Footer>
        </flv:FlowListView>
    </StackLayout>
</ContentPage.Content>
</code>```

Body:
After using FlowListView I got the following result:

But the Emergency should be an other colour with an other click event and the size of FlowColumnCount = "1"

this is the following code:

<?xml version="1.0" encoding="utf-8" ?>

            <flv:FlowListView.FlowColumnTemplate>
                <DataTemplate>
                    <Frame BackgroundColor="Purple" Margin="5">

                    </Frame>
                </DataTemplate>
            </flv:FlowListView.FlowColumnTemplate>
        </flv:FlowListView>
    </StackLayout>
</ContentPage.Content>

This is the MockDataStore:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DLToolkit.Forms.Controls;
using EscapeHaarlem.Models;

namespace EscapeHaarlem.Services
{
public class MockDataStore : IDataStore<Item>
{
    List<Item> items;

    public MockDataStore()
    {
        FlowListView.Init();
        items = new List<Item>();
        //this.items.Add(new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 1", Description = "This is an item description." });
        //this.items.Add(new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 2", Description = "This is an item description." });

        var mockItems = new List<Item>
        {
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 1", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 2", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 3", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 4", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 5", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 6", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 7", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 8", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 9", Description="This is an item description." },
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 10", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 11", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 12", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 13", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Hint 14", Description="This is an item description."},
            new Item { Id = Guid.NewGuid().ToString(), Text = "Emergency", Description="This is an item description."},
        };

        foreach (var item in mockItems)
        {
            items.Add(item);
        }
    }

    public async Task<bool> AddItemAsync(Item item)
    {
        items.Add(item);

        return await Task.FromResult(true);
    }

    public async Task<bool> UpdateItemAsync(Item item)
    {
        var oldItem = items.Where((Item arg) => arg.Id == item.Id).FirstOrDefault();
        items.Remove(oldItem);
        items.Add(item);

        return await Task.FromResult(true);
    }

    public async Task<bool> DeleteItemAsync(string id)
    {
        var oldItem = items.Where((Item arg) => arg.Id == id).FirstOrDefault();
        items.Remove(oldItem);

        return await Task.FromResult(true);
    }

    public async Task<Item> GetItemAsync(string id)
    {
        return await Task.FromResult(items.FirstOrDefault(s => s.Id == id));
    }

    public async Task<IEnumerable<Item>> GetItemsAsync(bool forceRefresh = false)
    {
        return await Task.FromResult(items);
    }
}

}

How could I achieve so that the emergency button has other color size and clickevent?

Thanks in advance

Body:
Do you mean you want to let Emergency a separate column and have a separate click event, right ?

If yes,you may could display it with ListView.Footer,then you could defined its color,click event separately，like:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d"
         xmlns:flv="clr-namespace:DLToolkit.Forms.Controls;assembly=DLToolkit.Forms.Controls.FlowListView"
         x:Class="App18.FlowListPage">
<ContentPage.Content>
    <StackLayout>
        <flv:FlowListView FlowColumnCount="2"
            SeparatorVisibility="Default"
            HasUnevenRows="True"
            FlowItemTappedCommand="{Binding ItemTappedCommand}"
            FlowItemsSource="{Binding Items}">

            <flv:FlowListView.FlowColumnTemplate>
                <DataTemplate>
                    <Frame BackgroundColor="Purple"
            Margin="5">
                        <Label HorizontalOptions="Fill"
                VerticalOptions="Fill"
                TextColor="White"
                XAlign="Center"
                YAlign="Center"
                Text="{Binding Text}"/>
                    </Frame>
                </DataTemplate>
            </flv:FlowListView.FlowColumnTemplate>
            <flv:FlowListView.Footer>

                <StackLayout>
                    <Button Text="Emergency" BackgroundColor="Accent" Clicked="Button_Clicked"></Button>
                </StackLayout>

            </flv:FlowListView.Footer>
        </flv:FlowListView>
    </StackLayout>
</ContentPage.Content>


问:
Why does Angular CLI 9.01 fails to create a bazel project?
Steps to Reproduce

remove Angular's global installation: npm uninstall -g angular-cli && npm cache clean --force

install Angular 9, globally: npm install -g @angular/cli@latest

intall bazel globally: npm i -g @angular/bazel

start an Angular 9 project using bazel:
$ ng new bazel-project --defaults --collection=@angular/bazel

Observed Behavior
Angular CLI fails to create the project: An unhandled exception occurred: Cannot find module '@angular-devkit/schematics'

Expected Behavior
The project is created

Additional Material

ng --version yields the following:

```<code>$ ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 9.0.1
Node: 13.8.0
OS: darwin x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.900.1
@angular-devkit/core         9.0.1
@angular-devkit/schematics   9.0.1
@schematics/angular          9.0.1
@schematics/update           0.900.1
rxjs                         6.5.3
</code>```

答:
I erease Node and Angular from my machine, and re-installed them from scratch. The, I followed these instructions to create a new ng project.

The option to use Bazel in a new application, by installing @angular/bazel globally:

```<code>npm install -g @angular/bazel
ng new my-project --collection=@angular/bazel
</code>```

Does not work, as per my steps above.

The option to opt-in an existing application:

```<code>ng new my-project --collection=@angular/bazel
npm install -g @angular/bazel
</code>```

works, without creating the WORKSPACE and BUILD files, which I expected would be created.

I'm closing this issue and will wait until the Angular folks fix this.

Body:
Steps to Reproduce

remove Angular's global installation: npm uninstall -g angular-cli && npm cache clean --force

install Angular 9, globally: npm install -g @angular/cli@latest

intall bazel globally: npm i -g @angular/bazel

start an Angular 9 project using bazel:
$ ng new bazel-project --defaults --collection=@angular/bazel

Observed Behavior
Angular CLI fails to create the project: An unhandled exception occurred: Cannot find module '@angular-devkit/schematics'

Expected Behavior
The project is created

Additional Material

ng --version yields the following:

$ ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 9.0.1
Node: 13.8.0
OS: darwin x64

Angular:
...
Ivy Workspace:

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.900.1
@angular-devkit/core         9.0.1
@angular-devkit/schematics   9.0.1
@schematics/angular          9.0.1
@schematics/update           0.900.1
rxjs                         6.5.3

Body:
I erease Node and Angular from my machine, and re-installed them from scratch. The, I followed these instructions to create a new ng project.

The option to use Bazel in a new application, by installing @angular/bazel globally:

npm install -g @angular/bazel
ng new my-project --collection=@angular/bazel

Does not work, as per my steps above.

The option to opt-in an existing application:

ng new my-project --collection=@angular/bazel
npm install -g @angular/bazel

works, without creating the WORKSPACE and BUILD files, which I expected would be created.

I'm closing this issue and will wait until the Angular folks fix this.


问:
forgotten key pair needed for bastion host to connect to rds
I am trying to set up a bastion host to connect to my rds in AWS, but I have forgotten the key pair that I need in order to configure it. Is there a way to retrieve it or make a new one so I can configure the bastion host? If so how would I go about it?</p>

答:
Replace with new one bastion. This is easiest way to resolve this issue.
If your bastion store important data, create new ebs from snapshot ebs volume old bastion then attach to newly bastion. </p>