问:
How do I update the values of these Int refs (Haskell)?
I have some variables like so:

```<code>let y0 = read (input!!0) :: Int
let h = read (input!!1) :: Int
y <- newIORef y0
minY <- newIORef 0
maxY <- newIORef (h - 1)
</code>```

And later I have

```<code>y_old <- readIORef y

if (some_string!!0 == 'U') then
    maxY = (y_old - 1)       --I don't think this is working
else if (some_string!!0 == 'D') then
    minY = (y_old + 1)       --I don't think this is working
</code>```

I am basically reading the references into some local ints and then trying to update the references based on criteria.

I also tried modifyIORef maxY (y_old - 1) but this doesn't work either. The compiler is only telling me "parse error" or "syntax error" which is not helpful.

My full code:

```<code>import System.IO
import Control.Monad
import Data.IORef
import Text.Printf

main :: IO ()
main = do
    hSetBuffering stdout NoBuffering -- DO NOT REMOVE

    -- Auto-generated code below aims at helping you parse
    -- the standard input according to the problem statement.

    input_line <- getLine
    let input = words input_line
    let w = read (input!!0) :: Int -- width of the building.
    let h = read (input!!1) :: Int -- height of the building.
    input_line <- getLine
    let n = read input_line :: Int -- maximum number of turns before game over.
    input_line <- getLine
    let input = words input_line
    let x0 = read (input!!0) :: Int
    let y0 = read (input!!1) :: Int
    x <- newIORef x0
    y <- newIORef y0
    minX <- newIORef 0
    maxX <- newIORef (w - 1)
    minY <- newIORef 0
    maxY <- newIORef (h - 1)
    loop x0 y0 w h x y minX maxX minY maxY

loop :: Int -> Int -> Int -> Int -> IORef Int -> IORef Int -> IORef Int -> IORef Int-> IORef Int -> IORef Int -> IO ()
loop x0 y0 w h x y minX maxX minY maxY = do
    input_line <- getLine
    let bombdir = input_line :: String -- the direction of the bombs from batman's current location (U, UR, R, DR, D, DL, L or UL)

    x_old <- readIORef x
    y_old <- readIORef y

    if (bombdir!!0 == 'U') then
        writeIORef maxY (y_old - 1)
    if (bombdir!!0 == 'D') then
        writeIORef minY (y_old + 1)

    if (bombdir!!(bombdir.length-1) == 'L') then
        writeIORef maxX (x_old - 1)
    if (bombdir!!(bombdir.length-1) == 'R') then
        writeIORef minX (x_old + 1)

    x = (minX + maxX) / 2
    y = (minY + maxY) / 2

    x_out <- readIORef x
    y_out <- readIORef y

    printf "%d %d" x_out y_out
    loop x0 y0 w h x y minX maxX minY maxY
</code>```

答:
First a bit of good style:

```<code>    ...
    input_line <- getLine
    let input = words input_line
    let w = read (input!!0) :: Int -- width of the building.
    let h = read (input!!1) :: Int -- height of the building.
</code>```

This works, but it's awkward. You build up a list and give it a name, only to access individual elements, parse them one-by-one and give them new names. Why not just

```<code>    input_line <- getLine
    let [w,h] = map read (words input_line) :: [Int]
</code>```

In fact, you don't even need input_line, nor the signatures (provided you later use w and h, so their types are unambiguous). I.e., the following also does the trick:

```<code>    [w,h] <- map read . words <$> getLine
</code>```

Likewise,

```<code>    [x₀,y₀] <- map read . words <$> getLine
</code>```

The real problem with your code in loop is that you try to use if as a procedural control-flow statement. Haskell doesn't have control flow, it only has expressions. Hence Haskell's if is actually very different from the if statement in imperative languages, it's more like the ? : operator. One thing you could do is complete these conditionals to

```<code>    if (bombdir!!0 == 'U')
     then writeIORef maxY (y_old - 1)
     else pure ()
</code>```

...pure () being the no-op in a pseudo-imperative (monadic) do block. But there's a standard combinator for this particular construct, when. It's actually just a library function, but behaves almost exactly like if in imperative languages. With that, you could make it

```<code>    when (bombdir!!0 == 'U') $ writeIORef maxY (y_old - 1)
</code>```

But I wouldn't recommend it. You're again do awkward list-element accessing. A much nicer way of deciding what to do depending on values of list-elements is directly pattern-matching them with a case expression:

```<code>loop :: Int -> Int -> Int -> Int
 -> IORef Int -> IORef Int -> IORef Int -> IORef Int-> IORef Int -> IORef Int -> IO ()
loop x₀ y₀ w h x y minX maxX minY maxY = do

    bombdir <- getLine  -- no need to first name it `input_line`

    x_old <- readIORef x
    y_old <- readIORef y

    case bomdir of
      ('U':_) -> writeIORef maxY (y_old - 1)
      ('D':_) -> writeIORef minY (y_old + 1)
      _       -> pure ()

    case reverse bombdir of
      ('L':_) -> writeIORef maxX (x_old - 1)
      ('R':_) -> writeIORef minX (x_old + 1)
      _       -> pure ()
</code>```

Then, you attempt to do arithmetic directly on IORefs, instead of on pure values. This is generally eschewed; what you'd actually need to write is

```<code>    writeIORef x =<< do
        xmin <- readIORef minX
        xmax <- readIORef maxX
        pure $ (xmin + xmax) / 2
</code>```

I think we agree that this looks horrible, but it works. A more concise way of writing it would be

```<code>    writeIORef x =<< (/2) <$> ((+) <$> readIORef minX <*> readIORef maxX)
</code>```

As I already commented, you fortunately don't need those ugly IORefs at all. Just make “new versions” of your variables to pass in the recursive call:

```<code>loop :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int-> Int -> Int -> IO ()
loop x₀ y₀ w h x y minX maxX minY maxY = do
    bombdir <- input_line

    let (maxY',minY') = case bombdir of
          ('U':_) -> (y - 1, minY )
          ('D':_) -> (maxY , y + 1)
        (maxX',minX') = case reverse bombdir of
          ('L':_) -> (x - 1, minX )
          ('R':_) -> (maxX , x + 1)

        x' = (minX' + maxX') / 2
        y' = (minY' + maxY') / 2

    printf "%d %d" x' y'
    loop x₀ y₀ w h x' y' minX' maxX' minY' maxY'
</code>```

Body:
I have some variables like so:

let y0 = read (input!!0) :: Int
let h = read (input!!1) :: Int
y <- newIORef y0
minY <- newIORef 0
maxY <- newIORef (h - 1)

And later I have

y_old <- readIORef y

if (some_string!!0 == 'U') then
    maxY = (y_old - 1)       --I don't think this is working
else if (some_string!!0 == 'D') then
    minY = (y_old + 1)       --I don't think this is working

I am basically reading the references into some local ints and then trying to update the references based on criteria.

I also tried modifyIORef maxY (y_old - 1) but this doesn't work either. The compiler is only telling me "parse error" or "syntax error" which is not helpful.

My full code:

import System.IO
import Control.Monad
import Data.IORef
import Text.Printf

main :: IO ()
main = do
    hSetBuffering stdout NoBuffering -- DO NOT REMOVE

    -- Auto-generated code below aims at helping you parse
    -- the standard input according to the problem statement.

    input_line <- getLine
    let input = words input_line
    let w = read (input!!0) :: Int -- width of the building.
    let h = read (input!!1) :: Int -- height of the building.
    input_line <- getLine
    let n = read input_line :: Int -- maximum number of turns before game over.
    input_line <- getLine
    let input = words input_line
    let x0 = read (input!!0) :: Int
    let y0 = read (input!!1) :: Int
    x <- newIORef x0
    y <- newIORef y0
    minX <- newIORef 0
    maxX <- newIORef (w - 1)
    minY <- newIORef 0
    maxY <- newIORef (h - 1)
    loop x0 y0 w h x y minX maxX minY maxY

loop :: Int -> Int -> Int -> Int -> IORef Int -> IORef Int -> IORef Int -> IORef Int-> IORef Int -> IORef Int -> IO ()
loop x0 y0 w h x y minX maxX minY maxY = do
    input_line <- getLine
    let bombdir = input_line :: String -- the direction of the bombs from batman's current location (U, UR, R, DR, D, DL, L or UL)

    x_old <- readIORef x
    y_old <- readIORef y

    if (bombdir!!0 == 'U') then
        writeIORef maxY (y_old - 1)
    if (bombdir!!0 == 'D') then
        writeIORef minY (y_old + 1)

    if (bombdir!!(bombdir.length-1) == 'L') then
        writeIORef maxX (x_old - 1)
    if (bombdir!!(bombdir.length-1) == 'R') then
        writeIORef minX (x_old + 1)

    x = (minX + maxX) / 2
    y = (minY + maxY) / 2

    x_out <- readIORef x
    y_out <- readIORef y

    printf "%d %d" x_out y_out
    loop x0 y0 w h x y minX maxX minY maxY

Body:
First a bit of good style:

    ...
    input_line <- getLine
    let input = words input_line
    let w = read (input!!0) :: Int -- width of the building.
    let h = read (input!!1) :: Int -- height of the building.

This works, but it's awkward. You build up a list and give it a name, only to access individual elements, parse them one-by-one and give them new names. Why not just

    input_line <- getLine
    let [w,h] = map read (words input_line) :: [Int]

In fact, you don't even need input_line, nor the signatures (provided you later use w and h, so their types are unambiguous). I.e., the following also does the trick:

    [w,h] <- map read . words <$> getLine

Likewise,

    [x₀,y₀] <- map read . words <$> getLine

The real problem with your code in loop is that you try to use if as a procedural control-flow statement. Haskell doesn't have control flow, it only has expressions. Hence Haskell's if is actually very different from the if statement in imperative languages, it's more like the ? : operator. One thing you could do is complete these conditionals to

    if (bombdir!!0 == 'U')
     then writeIORef maxY (y_old - 1)
     else pure ()

...pure () being the no-op in a pseudo-imperative (monadic) do block. But there's a standard combinator for this particular construct, when. It's actually just a library function, but behaves almost exactly like if in imperative languages. With that, you could make it

    when (bombdir!!0 == 'U') $ writeIORef maxY (y_old - 1)

But I wouldn't recommend it. You're again do awkward list-element accessing. A much nicer way of deciding what to do depending on values of list-elements is directly pattern-matching them with a case expression:

loop :: Int -> Int -> Int -> Int
 -> IORef Int -> IORef Int -> IORef Int -> IORef Int-> IORef Int -> IORef Int -> IO ()
loop x₀ y₀ w h x y minX maxX minY maxY = do

    bombdir <- getLine  -- no need to first name it `input_line`

    x_old <- readIORef x
    y_old <- readIORef y

    case bomdir of
      ('U':_) -> writeIORef maxY (y_old - 1)
      ('D':_) -> writeIORef minY (y_old + 1)
      _       -> pure ()

    case reverse bombdir of
      ('L':_) -> writeIORef maxX (x_old - 1)
      ('R':_) -> writeIORef minX (x_old + 1)
      _       -> pure ()

Then, you attempt to do arithmetic directly on IORefs, instead of on pure values. This is generally eschewed; what you'd actually need to write is

    writeIORef x =<< do
        xmin <- readIORef minX
        xmax <- readIORef maxX
        pure $ (xmin + xmax) / 2

I think we agree that this looks horrible, but it works. A more concise way of writing it would be

    writeIORef x =<< (/2) <$> ((+) <$> readIORef minX <*> readIORef maxX)

As I already commented, you fortunately don't need those ugly IORefs at all. Just make “new versions” of your variables to pass in the recursive call:

loop :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int-> Int -> Int -> IO ()
loop x₀ y₀ w h x y minX maxX minY maxY = do
    bombdir <- input_line

    let (maxY',minY') = case bombdir of
          ('U':_) -> (y - 1, minY )
          ('D':_) -> (maxY , y + 1)
        (maxX',minX') = case reverse bombdir of
          ('L':_) -> (x - 1, minX )
          ('R':_) -> (maxX , x + 1)

        x' = (minX' + maxX') / 2
        y' = (minY' + maxY') / 2

    printf "%d %d" x' y'
    loop x₀ y₀ w h x' y' minX' maxX' minY' maxY'


来源: stackexchange

问:
Cannot set desired time to my Gregorian calendar
The problem in the below code is that I am trying to set EVENING time to 6 P.M. please ignore the Calendar.evening values as it was for testing purpose.
here is my LOG file

D/Notification: MORN Tue Nov 14 16:00:00 GMT+05:30 2017 vs EVE Tue Nov 14 16:00:00 GMT+05:30 2017

MORN: Tue Nov 14 16:00:00 GMT+05:30 2017 vs Tue Nov 14 16:00:00 GMT+05:30 2017
    EVE: Tue Nov 14 16:00:00 GMT+05:30 2017 vs Tue Nov 14 16:00:00 GMT+05:30 2017

now the problem here is that both of the getTime() are returning CURRENT TIME.

I want the IF LOOP to execute at a 4 pm and 8 am, for this instance, my logic seems pretty legit! Please point me to the error

```<code>public class MyNotificationService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

static Calendar eve,morn;

@Override
public void onCreate() {
    super.onCreate();
    morn=Calendar.getInstance();
    morn.set(Calendar.HOUR_OF_DAY, 4);
    morn.set(Calendar.MINUTE, 0);
    morn.set(Calendar.SECOND, 0);
    morn.set(Calendar.AM_PM,1);

    eve=Calendar.getInstance();
    eve.set(Calendar.HOUR_OF_DAY, 6);
    eve.set(Calendar.MINUTE, 0);
    eve.set(Calendar.SECOND, 0);
    eve.set(Calendar.AM_PM,1);

    Log.d("Notification", "MORN "+morn.getTime().toString() +" vs EVE "+eve.getTime().toString());

}

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    setTimer();

    return Service.START_STICKY;
}

void setTimer(){

    Timer timer = new Timer ();
    TimerTask hourlyTask = new TimerTask () {

        @Override
        public void run () {
            Calendar now=Calendar.getInstance();
            now.set(Calendar.MINUTE,0);
            now.set(Calendar.SECOND,0);

            Log.d("Notification MORN", morn.getTime().toString() +" vs "+now.getTime().toString());
            if (now.compareTo(morn)==0||now.getTime().equals(morn.getTime())) {
                Log.d("Notification Func", eve.getTime().toString() + " MORNING exe");
                Handler mainHandler = new Handler(Looper.getMainLooper());
                Runnable myRunnable = new Runnable() {
                    @Override
                    public void run() {
                        if (isInternetOn(getApplicationContext())){
                            getCaseDetails();
                        }else {
                            setNotification("Internet not available","Please check your Cases");
                        }
                    }
                };
                mainHandler.post(myRunnable);
            }
            Log.d("Notification EVE", eve.getTime().toString() +" vs "+now.getTime().toString());
            if (now.compareTo(eve)==0||now.getTime().equals(eve.getTime())) {
                    Log.d("Notification Func", eve.getTime().toString() + " EVENING exe");
                Handler mainHandler = new Handler(Looper.getMainLooper());
                Runnable myRunnable = new Runnable() {
                    @Override
                    public void run() {
                        getCaseDetails();
                    }
                };
                mainHandler.post(myRunnable);
            }
        }
    };
//        timer.schedule (hourlyTask, 0L, 1000*60*60);
    timer.schedule (hourlyTask, 0L, 30*1000);
}

void getDetails() {
   }

@Override
public void onDestroy() {
    super.onDestroy();
    Toast.makeText(this, "Notification Service Stopped", Toast.LENGTH_LONG).show();
}

public void setNotification(String titleStr,String descStr) {

   setting alarm here.
}

}
</code>```

答:
Using AM/PM requires the use of Calendar.HOUR, not Calendar.HOUR_OF_DAY, which is ignored when setting AM/PM:

```<code>Calendar morn = Calendar.getInstance();
morn.set(Calendar.HOUR_OF_DAY, 4);
morn.set(Calendar.MINUTE, 0);
morn.set(Calendar.SECOND, 0);
morn.set(Calendar.AM_PM, Calendar.PM);

System.out.println(someDateFormat.format(morn.getTime()));
// current hour

morn = Calendar.getInstance();
morn.set(Calendar.HOUR, 4);
morn.set(Calendar.MINUTE, 0);
morn.set(Calendar.SECOND, 0);
morn.set(Calendar.AM_PM, Calendar.PM);

System.out.println(someDateFormat.format(morn.getTime()));
// correct hour
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The problem in the below code is that I am trying to set EVENING time to 6 P.M. please ignore the Calendar.evening values as it was for testing purpose.
here is my LOG file

D/Notification: MORN Tue Nov 14 16:00:00 GMT+05:30 2017 vs EVE Tue Nov 14 16:00:00 GMT+05:30 2017

MORN: Tue Nov 14 16:00:00 GMT+05:30 2017 vs Tue Nov 14 16:00:00 GMT+05:30 2017
    EVE: Tue Nov 14 16:00:00 GMT+05:30 2017 vs Tue Nov 14 16:00:00 GMT+05:30 2017

now the problem here is that both of the getTime() are returning CURRENT TIME.

I want the IF LOOP to execute at a 4 pm and 8 am, for this instance, my logic seems pretty legit! Please point me to the error

public class MyNotificationService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

static Calendar eve,morn;

@Override
public void onCreate() {
    super.onCreate();
    morn=Calendar.getInstance();
    morn.set(Calendar.HOUR_OF_DAY, 4);
    morn.set(Calendar.MINUTE, 0);
    morn.set(Calendar.SECOND, 0);
    morn.set(Calendar.AM_PM,1);

    eve=Calendar.getInstance();
    eve.set(Calendar.HOUR_OF_DAY, 6);
    eve.set(Calendar.MINUTE, 0);
    eve.set(Calendar.SECOND, 0);
    eve.set(Calendar.AM_PM,1);

    Log.d("Notification", "MORN "+morn.getTime().toString() +" vs EVE "+eve.getTime().toString());

}

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    setTimer();

    return Service.START_STICKY;
}

void setTimer(){

    Timer timer = new Timer ();
    TimerTask hourlyTask = new TimerTask () {

        @Override
        public void run () {
            Calendar now=Calendar.getInstance();
            now.set(Calendar.MINUTE,0);
            now.set(Calendar.SECOND,0);

            Log.d("Notification MORN", morn.getTime().toString() +" vs "+now.getTime().toString());
            if (now.compareTo(morn)==0||now.getTime().equals(morn.getTime())) {
                Log.d("Notification Func", eve.getTime().toString() + " MORNING exe");
                Handler mainHandler = new Handler(Looper.getMainLooper());
                Runnable myRunnable = new Runnable() {
                    @Override
                    public void run() {
                        if (isInternetOn(getApplicationContext())){
                            getCaseDetails();
                        }else {
                            setNotification("Internet not available","Please check your Cases");
                        }
                    }
                };
                mainHandler.post(myRunnable);
            }
            Log.d("Notification EVE", eve.getTime().toString() +" vs "+now.getTime().toString());
            if (now.compareTo(eve)==0||now.getTime().equals(eve.getTime())) {
                    Log.d("Notification Func", eve.getTime().toString() + " EVENING exe");
                Handler mainHandler = new Handler(Looper.getMainLooper());
                Runnable myRunnable = new Runnable() {
                    @Override
                    public void run() {
                        getCaseDetails();
                    }
                };
                mainHandler.post(myRunnable);
            }
        }
    };
//        timer.schedule (hourlyTask, 0L, 1000*60*60);
    timer.schedule (hourlyTask, 0L, 30*1000);
}

void getDetails() {
   }

@Override
public void onDestroy() {
    super.onDestroy();
    Toast.makeText(this, "Notification Service Stopped", Toast.LENGTH_LONG).show();
}

public void setNotification(String titleStr,String descStr) {

   setting alarm here.
}

}

Body:
Using AM/PM requires the use of Calendar.HOUR, not Calendar.HOUR_OF_DAY, which is ignored when setting AM/PM:

Calendar morn = Calendar.getInstance();
morn.set(Calendar.HOUR_OF_DAY, 4);
morn.set(Calendar.MINUTE, 0);
morn.set(Calendar.SECOND, 0);
morn.set(Calendar.AM_PM, Calendar.PM);

System.out.println(someDateFormat.format(morn.getTime()));
// current hour

morn = Calendar.getInstance();
morn.set(Calendar.HOUR, 4);
morn.set(Calendar.MINUTE, 0);
morn.set(Calendar.SECOND, 0);
morn.set(Calendar.AM_PM, Calendar.PM);

System.out.println(someDateFormat.format(morn.getTime()));
// correct hour


问:
gitlab-ci: Dynamic artifact names
I am running a gitlab-ci job that will fetch locally a file from a remote server, more or less as follows:

```<code>retrieve_docs:
    stage: fetch_docs
    image: debian:jessie
    script:
      - ssh $USERNAME@$SERVER /perform/some/work
      - INSTFILE=$(ssh $USERNAME@$SERVER bash -c 'find /root -iname "somepattern*" | tail -n 1 | xargs readlink -f')
      - echo "Will retrieve locally $INSTFILE"
      - scp $USERNAME@$SERVER:$INSTFILE .
      - BASEFILE=$(basename $INSTFILE)
      - mv $BASEFILE downloads/
    artifacts:
      name: $BASEFILE
      paths:
        - downloads/
</code>```

The above job definition however does not seem to work, as the BASEFILE variable is rendered as empty when providing the filename.

Is there a way to use dynamic artifact name(s)?

Is there a reason that this artifact is also never copied in my (empty/tracked) downloads folder?

The above process will actually fetch a .zip file locally. Is there a way (although I have set expiration of 1 week) to have each job delete old artifacts and keep only the latest artifact / zip file?

答:
For example if you use something like CI_JOB_ID CI_JOB_NAME you can have dynamic artifact names per JOB. You can have a combination of varibales defined in https://docs.gitlab.com/ee/ci/yaml/README.html#artifacts-name to get dynamic artifact names for your stage or job or pipeline.

Normally in a job, git lab compresses whatever specified in the path and upload it to the runner manager so that the next job can download the artifacts from the runner manager. If the job fails you cant upload any artifacts to other jobs. Do a find . and check wether the required dirs are there. You can use when option to continue the pipline no matter it fails or not. See https://docs.gitlab.com/ee/ci/yaml/README.html#artifacts-when

Yes you can expire the artifcat at your timers. See https://docs.gitlab.com/ee/ci/yaml/README.html#artifacts-expire_in

Title: gitlab-ci: Dynamic artifact names

Body:
I am running a gitlab-ci job that will fetch locally a file from a remote server, more or less as follows:

retrieve_docs:
    stage: fetch_docs
    image: debian:jessie
    script:
      - ssh $USERNAME@$SERVER /perform/some/work
      - INSTFILE=$(ssh $USERNAME@$SERVER bash -c 'find /root -iname "somepattern*" | tail -n 1 | xargs readlink -f')
      - echo "Will retrieve locally $INSTFILE"
      - scp $USERNAME@$SERVER:$INSTFILE .
      - BASEFILE=$(basename $INSTFILE)
      - mv $BASEFILE downloads/
    artifacts:
      name: $BASEFILE
      paths:
        - downloads/

The above job definition however does not seem to work, as the BASEFILE variable is rendered as empty when providing the filename.

Is there a way to use dynamic artifact name(s)?

Is there a reason that this artifact is also never copied in my (empty/tracked) downloads folder?

The above process will actually fetch a .zip file locally. Is there a way (although I have set expiration of 1 week) to have each job delete old artifacts and keep only the latest artifact / zip file?


问:
Rails - Using true and false
I have the following in my controller:

```<code>if params[:archive] == 'true'
  @archived_new_status = true
else
  @archived_new_status = false
end
</code>```

Then later in create.je.erb do:

```<code><% if !@archived_new_status.nil? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>
</code>```

That only works when @archived_new_status is true, when it's false that seems to not be getting set as false. When I do a Rails.logger.info on @archived_new_status for false it outputs nothing, if I inspect it, I get false.

Any thoughts?

答:
Do I understand correctly that somehow the variable @archived_new_status is not set? Although, the code you show always sets it to either true or false.

I would rewrite as follows:

```<code>@archived_new_status = if params[:archive] == 'true'
  true
else
  false
end
</code>```

The same as the code above, only somewhat simpler (and maybe clearer). Then you could write it even shorter:

```<code>@archived_new_status = params[:archive] == 'true'

</code>```

(actually this is completely identical to what you showed us).
In your view, you can then be sure that @archived_new_status is always set! From the code you showed us, there is no other way. It is either true or false. So your view becomes:

```<code>   xxx.myfuncthatNeedsTrueOrFalse(<%= @archived_new_status.to_s %>);
</code>```

(i presume you are calling some javascript function here, with a wanted parameter of either true or false. Are you sure that the value is converted correctly to a string?  --> i added .to_s for clarity)

From what you show us, nothing much could be wrong, so to wrap up:

can you make sure that @archived_new_status is set correctly, if not, show the complete code sample

in the view you are rendering, are you converting the value correctly to a string? can you explain what you are trying to do?

ContentLicense: CC BY-SA 2.5

Title: Rails - Using true and false

Body:
I have the following in my controller:

if params[:archive] == 'true'
  @archived_new_status = true
else
  @archived_new_status = false
end

Then later in create.je.erb do:

<% if !@archived_new_status.nil? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>

That only works when @archived_new_status is true, when it's false that seems to not be getting set as false. When I do a Rails.logger.info on @archived_new_status for false it outputs nothing, if I inspect it, I get false.

Any thoughts?

Body:
Do I understand correctly that somehow the variable @archived_new_status is not set? Although, the code you show always sets it to either true or false.

I would rewrite as follows:

@archived_new_status = if params[:archive] == 'true'
  true
else
  false
end

The same as the code above, only somewhat simpler (and maybe clearer). Then you could write it even shorter:

@archived_new_status = params[:archive] == 'true'

(actually this is completely identical to what you showed us).
In your view, you can then be sure that @archived_new_status is always set! From the code you showed us, there is no other way. It is either true or false. So your view becomes:

   xxx.myfuncthatNeedsTrueOrFalse(<%= @archived_new_status.to_s %>);

(i presume you are calling some javascript function here, with a wanted parameter of either true or false. Are you sure that the value is converted correctly to a string?  --> i added .to_s for clarity)

From what you show us, nothing much could be wrong, so to wrap up:

can you make sure that @archived_new_status is set correctly, if not, show the complete code sample

in the view you are rendering, are you converting the value correctly to a string? can you explain what you are trying to do?

ContentLicense: CC BY-SA 4.0


问:
Error when calling UDF using broadcasted objects in PySpark
I am trying to invoke a UDF that uses a broadcasted object in PySpark.

Here is a minimal example that reproduces the situation and error:

import pyspark.sql.functions as sf
from pyspark.sql.types import LongType

class SquareClass:
    def compute(self, n):
        return n ** 2

square = SquareClass()
square_sc = sc.broadcast(square)

def f(n):
    return square_sc.value.compute(n)

numbers = sc.parallelize([{'id': i} for i in range(10)]).toDF()
f_udf = sf.udf(f, LongType())

numbers.select(f_udf(numbers.id)).show(10)
```

<p>The stacktrace and error message that this snippet produces:</p>

<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last)
<ipython-input-75-6e38c014e4b2> in <module>()
     13 f_udf = sf.udf(f, LongType())
     14
---> 15 numbers.select(f_udf(numbers.id)).show(10)

/usr/hdp/current/spark-client/python/pyspark/sql/dataframe.py in show(self, n, truncate)
    255         +---+-----+
    256         """
--> 257         print(self._jdf.showString(n, truncate))
    258
    259     def __repr__(self):

/usr/local/lib/python3.5/dist-packages/py4j/java_gateway.py in __call__(self, *args)
   1131         answer = self.gateway_client.send_command(command)
   1132         return_value = get_return_value(
-> 1133             answer, self.gateway_client, self.target_id,

<snip>

An error occurred while calling o938.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 49.0 failed 1 times, most recent failure: Lost task 1.0 in stage 49.0 (TID 587, localhost): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
</code>```

答:
One thing you can do is, keep the class as separate module and add the module to sparkContext.</p>

```<code>class_module.py

class SquareClass:
    def compute(self, n):
        return n ** 2

pyspark-shell

    import pyspark.sql.functions as sf
    from pyspark.sql.types import LongType
    from class_module import SquareClass

    sc.addFile('class_module.py')

    square = SquareClass()
    square_sc = sc.broadcast(square)
    def f(n):
        return square_sc.value.compute(n)

    f_udf = sf.udf(f, LongType())
    numbers = sc.parallelize([{'id': i} for i in range(10)]).toDF()
    numbers.select(f_udf(numbers.id)).show(10)
    +-----+
    |f(id)|
    +-----+
    |    0|
    |    1|
    |    4|
    |    9|
    |   16|
    |   25|
    |   36|
    |   49|
    |   64|
    |   81|
    +-----+
</code>```

Body:
I am trying to invoke a UDF that uses a broadcasted object in PySpark.

Here is a minimal example that reproduces the situation and error:

import pyspark.sql.functions as sf
from pyspark.sql.types import LongType

class SquareClass:
    def compute(self, n):
        return n ** 2

square = SquareClass()
square_sc = sc.broadcast(square)

def f(n):
    return square_sc.value.compute(n)

numbers = sc.parallelize([{'id': i} for i in range(10)]).toDF()
f_udf = sf.udf(f, LongType())

numbers.select(f_udf(numbers.id)).show(10)

The stacktrace and error message that this snippet produces:

Traceback (most recent call last)
<ipython-input-75-6e38c014e4b2> in <module>()
     13 f_udf = sf.udf(f, LongType())
     14
---> 15 numbers.select(f_udf(numbers.id)).show(10)

/usr/hdp/current/spark-client/python/pyspark/sql/dataframe.py in show(self, n, truncate)
    255         +---+-----+
    256         """
--> 257         print(self._jdf.showString(n, truncate))
    258
    259     def __repr__(self):

/usr/local/lib/python3.5/dist-packages/py4j/java_gateway.py in __call__(self, *args)
   1131         answer = self.gateway_client.send_command(command)
   1132         return_value = get_return_value(
-> 1133             answer, self.gateway_client, self.target_id,

<snip>

An error occurred while calling o938.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 49.0 failed 1 times, most recent failure: Lost task 1.0 in stage 49.0 (TID 587, localhost): org.apache.spark.api.python.PythonException: Traceback (most recent call last):

Body:
One thing you can do is, keep the class as separate module and add the module to sparkContext.

class_module.py

class SquareClass:
    def compute(self, n):
        return n ** 2

pyspark-shell

    import pyspark.sql.functions as sf
    from pyspark.sql.types import LongType
    from class_module import SquareClass

    sc.addFile('class_module.py')

    square = SquareClass()
    square_sc = sc.broadcast(square)
    def f(n):
        return square_sc.value.compute(n)

    f_udf = sf.udf(f, LongType())
    numbers = sc.parallelize([{'id': i} for i in range(10)]).toDF()
    numbers.select(f_udf(numbers.id)).show(10)
    +-----+
    |f(id)|
    +-----+
    |    0|
    |    1|
    |    4|
    |    9|
    |   16|
    |   25|
    |   36|
    |   49|
    |   64|
    |   81|
    +-----+


问:
Python Requests - Cannot import HTTPProxyAuth (AttributeError: 'module' object has no attribute 'HTTPPRoxyAuth')
At the top of my Python file, I have:

```<code>import requests
from requests.auth import HTTPPRoxyAuth
</code>```

The line auth = requests.auth.HTTPPRoxyAuth(username, password) spits out the error AttributeError: 'module' object has no attribute 'HTTPPRoxyAuth', which leads back to a ImportError: cannot import name HTTPPRoxyAuth at the import line.

I can look at C:\Python27\Lib\site-packages\requests\auth.py and see the HTTPProxyAuth class.

I can use from requests.auth import * and look at all the modules with

```<code>g = globals().copy()
for name, obj in g.iteritems():
        print name
</code>```

and see HTTPProxyAuth in the list, but I'm still receiving an AttributeError.

Can someone explain why it's not importing correctly? I'm using Python 2.7 and Requests 2.18.4

答:
The R in Proxy has to be lower case:</p>

```<code>import requests
from requests.auth import HTTPProxyAuth
</code>```

Body:
At the top of my Python file, I have:

import requests
from requests.auth import HTTPPRoxyAuth

The line auth = requests.auth.HTTPPRoxyAuth(username, password) spits out the error AttributeError: 'module' object has no attribute 'HTTPPRoxyAuth', which leads back to a ImportError: cannot import name HTTPPRoxyAuth at the import line.

I can look at C:\Python27\Lib\site-packages\requests\auth.py and see the HTTPProxyAuth class.

I can use from requests.auth import * and look at all the modules with

g = globals().copy()
for name, obj in g.iteritems():
        print name

and see HTTPProxyAuth in the list, but I'm still receiving an AttributeError.

Can someone explain why it's not importing correctly? I'm using Python 2.7 and Requests 2.18.4

Body:
The R in Proxy has to be lower case:

import requests
from requests.auth import HTTPProxyAuth


问:
Node.js and versions in long run
I make projects for customes in php+mysql+jquery and now learning node.js+npm angular..etc..
My question is, after very little of testing.. to build the project, needs many tools and plugins to complete. If version mismatch the build will fail and it takes 2-6 or more hours to update and resolve the issues.
If I donwload something new, like plugins, for my new project, they don't work. I HAVE to update node, npm, grunt, etc. to build new projects.

Let's say my first node.js customer calls me after 1,5 years and wants a small change to project. I say it's 1 hour of work, not so expensive.
But i have already updated all the tools and when building the project, it will fail. And takes me half day to update all and fix whole project if the plugins are not maintaided anymore and repos are gone.

How did we got to this point ? That making websites/webapps became so complicated ?

答:
You can just specify what version of each plugin you want to use.

Read https://docs.npmjs.com/files/package.json#dependencies

```<code>{ "dependencies" :
  { "foo" : "1.0.0 - 2.9999.9999"
  , "bar" : ">=1.0.2 <2.1.2"
  , "baz" : ">1.0.2 <=2.3.4"
  , "boo" : "2.0.1"
  , "qux" : "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0"
  , "asd" : "http://asdf.com/asdf.tar.gz"
  , "til" : "~1.2"
  , "elf" : "~1.2.3"
  , "two" : "2.x"
  , "thr" : "3.3.x"
  , "lat" : "latest"
  , "dyl" : "file:../dyl"
  }
}
</code>```

You don't HAVE to use the latest version.

Packages are stored in every individual project and not globally (unless you want to but why would you). So there is no "I already updated all the tools" .

These things have all been thought through so things will not break by new versions. If that was the case it would be unusable.

Title: Node.js and versions in long run

Body:
You can just specify what version of each plugin you want to use.

Read https://docs.npmjs.com/files/package.json#dependencies

{ "dependencies" :
  { "foo" : "1.0.0 - 2.9999.9999"
  , "bar" : ">=1.0.2 <2.1.2"
  , "baz" : ">1.0.2 <=2.3.4"
  , "boo" : "2.0.1"
  , "qux" : "<1.0.0 || >=2.3.1 <2.4.5 || >=2.5.2 <3.0.0"
  , "asd" : "http://asdf.com/asdf.tar.gz"
  , "til" : "~1.2"
  , "elf" : "~1.2.3"
  , "two" : "2.x"
  , "thr" : "3.3.x"
  , "lat" : "latest"
  , "dyl" : "file:../dyl"
  }
}

You don't HAVE to use the latest version.

Packages are stored in every individual project and not globally (unless you want to but why would you). So there is no "I already updated all the tools" .

These things have all been thought through so things will not break by new versions. If that was the case it would be unusable.


问:
SQL Delete conditionally between rows
I have a table with multiple rows for the same ID and I need to keep only one row with the following rules:

NUM = 'AM' prevail on other

If multiple NUM = 'AM' or none then the oldest date prevail

For example :

```<code>|_ID_|_NUM_|______DATE______|
| 99 | AM  |   2015-04-12   |
| 99 | QS  |   2012-05-31   |
| 99 | AM  |   2013-02-18   |
</code>```

I need to keep the last row.

```<code>|_ID_|_NUM_|______DATE______|
| 99 | QS  |   2013-05-31   |
| 99 | QS  |   2016-02-18   |
</code>```

I need to keep the first row.

I'm on a postgres database and I can't use Function or Procedure
Thank you for any help.

答:
distinct on. False orders before true.

```<code>select distinct on (id) *
from t
order by num <> 'AM', date
</code>```

Title: SQL Delete conditionally between rows

Body:
I have a table with multiple rows for the same ID and I need to keep only one row with the following rules:

NUM = 'AM' prevail on other

If multiple NUM = 'AM' or none then the oldest date prevail

For example :

|_ID_|_NUM_|______DATE______|
| 99 | AM  |   2015-04-12   |
| 99 | QS  |   2012-05-31   |
| 99 | AM  |   2013-02-18   |

I need to keep the last row.

|_ID_|_NUM_|______DATE______|
| 99 | QS  |   2013-05-31   |
| 99 | QS  |   2016-02-18   |

I need to keep the first row.

I'm on a postgres database and I can't use Function or Procedure
Thank you for any help.

Body:
distinct on. False orders before true.

select distinct on (id) *
from t
order by num <> 'AM', date


问:
Inialization makes pointer without a cast
I'm quite new in C programming and I've tried to read similar questions but I have not been able to solve my particular issue.

I have this small function which returns a pointer to g_Uart0RxBuf array:

```<code>uint8_t* R_UART0_getBuffer()
{
   uint8_t* pointer_to_buffer;
   pointer_to_buffer = &g_Uart0RxBuf[0];
   return pointer_to_buffer;
}
</code>```

In the calling function I'm doing this:

```<code>uint8_t* pointer;              //Define pointer variable
pointer = R_UART0_getBuffer(); //Should return a pointer to an uint8_t
</code>```

Honestly I don't understand why I need a cast in order to make this work. Isn't it possible to do it without casting?

Thanks a lot and my apologies for making such a noob question.

答:
No cast is necessary. The issue is down to one of:

You are calling R_UART0_getBuffer before the compiler has seen the declaration of the function, and your now lax C compiler is allowing implicit function definitions (which have been disallowed since C99 but some compilers have it switched on by default!)

The compile error actually refers to the statement pointer_to_buffer = &g_Uart0RxBuf[0]; depending on what the type is in that array.

Body:
I'm quite new in C programming and I've tried to read similar questions but I have not been able to solve my particular issue.

I have this small function which returns a pointer to g_Uart0RxBuf array:

uint8_t* R_UART0_getBuffer()
{
   uint8_t* pointer_to_buffer;
   pointer_to_buffer = &g_Uart0RxBuf[0];
   return pointer_to_buffer;
}

In the calling function I'm doing this:

uint8_t* pointer;              //Define pointer variable
pointer = R_UART0_getBuffer(); //Should return a pointer to an uint8_t

Honestly I don't understand why I need a cast in order to make this work. Isn't it possible to do it without casting?

Thanks a lot and my apologies for making such a noob question.


问:
Java Instant to Date - With Different Timezone
I am running my code in EST timezone.

Using Instant.now() in my code and it returns time in UTC.

But, I am trying to test a method which gets data from DB as Date not Instant and hence trying to convert this to Date using

```<code>Date.from(Instant.now())
</code>```

Since, I am running this in EST, this Date gives me time in EST.

Actual code,

```<code>    final Optional<Date> dbTime = dbService.getUpdatedTime();
    final Instant lastInstant = dbTime.orElseGet(() -> Date.from(Instant.now())).toInstant();
</code>```

Test Code,

```<code>final Date dbTime = Date.from(Instant.now().minusSeconds(36000));
when(dbService.getUpdatedTime().thenReturn(Optional.of(dbTime));
</code>```

Here, the dbTime gets converted to EST time. I can make that to return UTC time by setting TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

Is there any other better way? Is this ok to set TimeZone.setDefault(TimeZone.getTimeZone("UTC")); in the main Application class so that it will always be treated as UTC?

答:
First recommendation, since you can use the modern Java date and time API, use it as much as you can and minimize the use of the outdated Date class. Best will be if you can modify getUpdatedTime() to return an Optional<Instant> rather than an Optional<Date> (a modern JDBC driver can give you the datetime from your database as an Instant directly). Since an Instant prints in UTC, this should wipe away all of your issue and your question.

In this answer I am assuming that you either cannot do that or don’t want to do it just yet. You can still get close, though:

```<code>    final Optional<Instant> dbTime = dbService.getUpdatedTime().map(Date::toInstant);
    final Instant lastReconInstant = dbTime.orElseGet(Instant::now);
</code>```

Avoid TimeZone.setDefault(). Since the JVM only has one global time zone setting, this may unintentionally change the behaviour of other parts of your program or other programs running in the same JVM.

A detail, in your stub code I recommend to make it explicit that you subtract 10 hours. Two options are

```<code>    final Date dbTime = Date.from(Instant.now().minus(10, ChronoUnit.HOURS));

    final Date dbTime = Date.from(Instant.now().minus(Duration.ofHours(10)));
</code>```

All of this said, it still seems to me that you didn’t have a problem in the first place. A Date does not have a time zone in it. Its toString method just grabs the JVM’s default time zone and uses it for rendering the date and time. This has fooled many and is just one of the reasons to avoid that class when you can.

Body:
I am running my code in EST timezone.

Using Instant.now() in my code and it returns time in UTC.

But, I am trying to test a method which gets data from DB as Date not Instant and hence trying to convert this to Date using

Date.from(Instant.now())

Since, I am running this in EST, this Date gives me time in EST.

Actual code,

    final Optional<Date> dbTime = dbService.getUpdatedTime();
    final Instant lastInstant = dbTime.orElseGet(() -> Date.from(Instant.now())).toInstant();

Test Code,

final Date dbTime = Date.from(Instant.now().minusSeconds(36000));
when(dbService.getUpdatedTime().thenReturn(Optional.of(dbTime));

Here, the dbTime gets converted to EST time. I can make that to return UTC time by setting TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

Is there any other better way? Is this ok to set TimeZone.setDefault(TimeZone.getTimeZone("UTC")); in the main Application class so that it will always be treated as UTC?

Body:
First recommendation, since you can use the modern Java date and time API, use it as much as you can and minimize the use of the outdated Date class. Best will be if you can modify getUpdatedTime() to return an Optional<Instant> rather than an Optional<Date> (a modern JDBC driver can give you the datetime from your database as an Instant directly). Since an Instant prints in UTC, this should wipe away all of your issue and your question.

In this answer I am assuming that you either cannot do that or don’t want to do it just yet. You can still get close, though:

    final Optional<Instant> dbTime = dbService.getUpdatedTime().map(Date::toInstant);
    final Instant lastReconInstant = dbTime.orElseGet(Instant::now);

Avoid TimeZone.setDefault(). Since the JVM only has one global time zone setting, this may unintentionally change the behaviour of other parts of your program or other programs running in the same JVM.

A detail, in your stub code I recommend to make it explicit that you subtract 10 hours. Two options are

    final Date dbTime = Date.from(Instant.now().minus(10, ChronoUnit.HOURS));

    final Date dbTime = Date.from(Instant.now().minus(Duration.ofHours(10)));

All of this said, it still seems to me that you didn’t have a problem in the first place. A Date does not have a time zone in it. Its toString method just grabs the JVM’s default time zone and uses it for rendering the date and time. This has fooled many and is just one of the reasons to avoid that class when you can.


问:
Handle last iteration of asp.net repeater differently
Is it possible to detect or use a different template in the asp.net repeater for the last iteration in the repeater?

If not I could just use a for loop but I'm curious if it can be done.

答: If you know how many items you are expecting, you could use the e.Item.ItemIndex property to check if you are on the last item. Or, depending on what you are trying to do, you might be able to take advantage of the footer template.</p>


问:
Puppet Evaluation Error: Error while evaluating a Resource Statement, Could not find declared class
I'm trying to deploy an application called Bag-Of-Holding via Puppet using the instruction as posted on github - https://github.com/ribeiroit/boh-puppet

I run the command: sudo puppet apply /etc/puppet/manifests/site.pp
and I get the error below:

Error: Evaluation Error: Error while evaluating a Resource Statement, Could not find declared class boh at /etc/puppet/manifests/site.pp:2:2 on node lab1-hp-elitebook-8570p

It appears the puppet is having hard time finding the class boh which is already in the manifest folder

This is my directory tree:

```<code>/etc/puppet
├── code
├── manifests
└── modules
    └── boh-puppet
        ├── manifests
        └── templates
</code>```

my site.pp file is located in /etc/puppet/manifests
and it looks like this:

```<code>node 'lab1-hp-elitebook-8570p' {
  class { 'boh':
    python_version   => 3,
    environment      => 'dev',
    language         => 'en',
    debug            => 'True',
    create_superuser => 'true',
    pkg_checksum     => '86b0164f7fd6c5e4aa43c8f056f08cea'
  }
}
</code>```

And init.pp file has the class {boh } and that's located at:
/etc/puppet/modules/boh-puppet/manifests

Any ideas how to fix this?

答:
You are not calling the module name properly. This should work:

```<code>node 'lab1-hp-elitebook-8570p' {
        class { 'boh-puppet':
        python_version => 3,
        environment => 'dev',
        language => 'en',
        debug => 'True',
        create_superuser => 'true',
        pkg_checksum => '86b0164f7fd6c5e4aa43c8f056f08cea'
        }
}
</code>```

or the fqn this:

```<code>node 'lab1-hp-elitebook-8570p' {
        class { '::boh-puppet':
        python_version => 3,
        environment => 'dev',
        language => 'en',
        debug => 'True',
        create_superuser => 'true',
        pkg_checksum => '86b0164f7fd6c5e4aa43c8f056f08cea'
        }
}
</code>```

Body:
I'm trying to deploy an application called Bag-Of-Holding via Puppet using the instruction as posted on github - https://github.com/ribeiroit/boh-puppet

I run the command: sudo puppet apply /etc/puppet/manifests/site.pp
and I get the error below:

Error: Evaluation Error: Error while evaluating a Resource Statement, Could not find declared class boh at /etc/puppet/manifests/site.pp:2:2 on node lab1-hp-elitebook-8570p

It appears the puppet is having hard time finding the class boh which is already in the manifest folder

This is my directory tree:

/etc/puppet
├── code
├── manifests
└── modules
    └── boh-puppet
        ├── manifests
        └── templates

my site.pp file is located in /etc/puppet/manifests
and it looks like this:

node 'lab1-hp-elitebook-8570p' {
  class { 'boh':
    python_version   => 3,
    environment      => 'dev',
    language         => 'en',
    debug            => 'True',
    create_superuser => 'true',
    pkg_checksum     => '86b0164f7fd6c5e4aa43c8f056f08cea'
  }
}

And init.pp file has the class {boh } and that's located at:
/etc/puppet/modules/boh-puppet/manifests

Any ideas how to fix this?

Body:
You are not calling the module name properly. This should work:

node 'lab1-hp-elitebook-8570p' {
        class { 'boh-puppet':
        python_version => 3,
        environment => 'dev',
        language => 'en',
        debug => 'True',
        create_superuser => 'true',
        pkg_checksum => '86b0164f7fd6c5e4aa43c8f056f08cea'
        }
}

or the fqn this:

node 'lab1-hp-elitebook-8570p' {
        class { '::boh-puppet':
        python_version => 3,
        environment => 'dev',
        language => 'en',
        debug => 'True',
        create_superuser => 'true',
        pkg_checksum => '86b0164f7fd6c5e4aa43c8f056f08cea'
        }
}


问:
How can I add a button that toggles a drop down result in React?
I'm still learning a lot about React but I'm finding a toggle a lot difficult than I think it should be.

What I'm aiming to achieve is a link titled 'Add Me' that when clicked on shows a a new label that is title 'Added!' having also removed the original 'Add Me' link.

The current code below is what I have, of which I thought would work but it doesn't. I have read A LOT of questions & answers around this simple action, none of which has worked here. Any insight into what I'm doing wrong &/or how to correct it would be extremely helpful!

Thank you in advance!

JSX:

```<code>class App extends React.Component {

constructor(props) {
  super(props);
  this.state = {
    showComponent: false,
  };
  this.Search__toggle = this.Search__toggle.bind(this);
}

Search__toggle() {
  this.setState({
    showComponent: true,
  });
}

render() {
    return (
        <div className="FormField__control">
            <a onClick={this.Search__toggle}><i className="fa fa-plus" aria-hidden="true" />
                Add Me
            </a>
            {this.state.showComponent ? <div>Added!</div> : null }
        </div>
    );
}

export default App;
</code>```

答:
You can toggle the Added! lable by modifying Search__toggle() method as below

  Search__toggle() {
    let oldState = this.state
    this.setState({
      showComponent: !oldState.showComponent,
    });
  }```
</div>
</div>
</p>

<p>Further, if you want to hide the <strong>Add Me</strong> link modify the render() method as below</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>render() {
      return (
          <div className="FormField__control">
              {this.state.showComponent ?
                <div>Added!</div> :
                <i className="fa fa-plus" aria-hidden="true" />
                  Add Me

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

Body:
I'm still learning a lot about React but I'm finding a toggle a lot difficult than I think it should be.

What I'm aiming to achieve is a link titled 'Add Me' that when clicked on shows a a new label that is title 'Added!' having also removed the original 'Add Me' link.

The current code below is what I have, of which I thought would work but it doesn't. I have read A LOT of questions & answers around this simple action, none of which has worked here. Any insight into what I'm doing wrong &/or how to correct it would be extremely helpful!

Thank you in advance!

JSX:

class App extends React.Component {

constructor(props) {
  super(props);
  this.state = {
    showComponent: false,
  };
  this.Search__toggle = this.Search__toggle.bind(this);
}

Search__toggle() {
  this.setState({
    showComponent: true,
  });
}

render() {
    return (

                Add Me

            {this.state.showComponent ?
Added!
 : null }

    );
}

export default App;

Body:
You can toggle the Added! lable by modifying Search__toggle() method as below

  Search__toggle() {
    let oldState = this.state
    this.setState({
      showComponent: !oldState.showComponent,
    });
  }

Further, if you want to hide the Add Me link modify the render() method as below

render() {
      return (
          <div className="FormField__control">
              {this.state.showComponent ?
                <div>Added!</div> :
                <a onClick={this.Search__toggle}><i className="fa fa-plus" aria-hidden="true" />
                  Add Me
                </a>
              }
          </div>
      );
  }


问:
Multiple Concurrency access to DbContext in Webapi
I have a WebApi that that uses EFCore2.0 and 2 client trying to access to an action method at a same time ...
Everything is working fine with one client. But when 2 or more trying to access to a one particular action method at a same time, I got this error at Microsoft.EntityFrameworkCore :

A second operation started on this context before a previous operation
  completed. Any instance members are not guaranteed to be thread safe

I used DI and repository for WebApi. I defined Scope for IUnitOfWork,I defined Transient, but nothing is worked.

This is my startup :

....
services.AddSingleton(provider => Configuration);
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped<IUnitOfWork, ApplicationDbContext>();
            services.AddTransient<IRoleService, RoleService>();
            services.AddTransient<ISecurityService, SecurityService>();
            services.AddTransient<IDbInitializerService, DbInitializerService>();
            services.AddTransient<ITokenStoreService, TokenStoreService>();
            services.AddTransient<ITokenValidatorService, TokenValidatorService>();
            services.AddTransient<ICookieValidatorService, CookieValidatorService>();
            services.AddTransient<IRequestRepository, RequestRepository>();
            services.AddDbContextPool<ApplicationDbContext>(options =>
            {
                options.UseSqlServer(
                    Configuration["ConnectionStrings:ApplicationDbContextConnection"].ToString(),
                    serverDbContextOptionsBuilder =>
                    {
                        var minutes = (int)TimeSpan.FromMinutes(3).TotalSeconds;
                        serverDbContextOptionsBuilder.CommandTimeout(minutes);
                        serverDbContextOptionsBuilder.EnableRetryOnFailure();
                    });
            });
....
```

<p>This is my DbContext:</p>

<pre class="lang-cs prettyprint-override"><code>namespace Eela.Data
{

    public class
        ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {

        public ApplicationDbContext CreateDbContext(string[] args)
        {
            var services = new ServiceCollection();
            services.AddOptions();
            services.AddScoped<IHostingEnvironment, CustomHostingEnvironment>();
            services.AddSingleton<ILoggerFactory, LoggerFactory>();
            var serviceProvider = services.BuildServiceProvider();
            var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
            var logger = loggerFactory.CreateLogger<ConfigProvider>();
            var hostingEnvironment = serviceProvider.GetRequiredService<IHostingEnvironment>();
            Console.WriteLine($"Using `{hostingEnvironment.ContentRootPath}` as the ContentRootPath");
            var configuration = new ConfigurationBuilder()
                .SetBasePath(basePath: hostingEnvironment.ContentRootPath)
                .AddJsonFile(path: "appsettings.json", reloadOnChange: true, optional: false)
                .AddEncryptedProvider(hostingEnvironment: hostingEnvironment, logger: logger)
                .AddJsonFile(path: $"appsettings.{hostingEnvironment.EnvironmentName}.json", optional: true)
                .Build();
            var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
            var connectionString = configuration["ConnectionStrings:ApplicationDbContextConnection"];
            var useInMemoryDatabase = configuration[key: "UseInMemoryDatabase"].Equals(value: "true",
                comparisonType: StringComparison.OrdinalIgnoreCase);
            if (useInMemoryDatabase)
                builder.UseInMemoryDatabase("MyDatabase");
            else
            builder.UseSqlServer(connectionString);
            builder.ConfigureWarnings(warnings => warnings.Log(CoreEventId.IncludeIgnoredWarning));
            return new ApplicationDbContext(builder.Options);
        }
    }

    public class ApplicationDbContext : DbContext, IUnitOfWork
    {

        public ApplicationDbContext(DbContextOptions options) : base(options)
        { }
        protected override void OnModelCreating(ModelBuilder model)
        {
            base.OnModelCreating(model);

            model.Entity<Person>().Property(p => p.PersonId).ValueGeneratedOnAdd();
            model.Entity<Person>()
                .HasDiscriminator<int>(name: "Type")
                .HasValue<WorkerTaxi>(value: Convert.ToInt32(value: AccountType.TaxiWorker))
                .HasValue<User>(value: Convert.ToInt32(value: AccountType.User))
                .HasValue<Reseller>(value: Convert.ToInt32(value: AccountType.Reseller));

            model.Entity<Log>().Property(p => p.Id).ValueGeneratedOnAdd();
            model.Entity<Log>()
                .HasDiscriminator<int>(name: "Type")
                .HasValue<LogRequest>(value: Convert.ToInt32(value: LogLevel.Information))
                .HasValue<LogError>(value: Convert.ToInt32(value: LogLevel.Error));

            model.Entity<Request>().Property(p => p.RequestId).ValueGeneratedOnAdd();
            model.Entity<Request>()
                .HasDiscriminator<int>(name: "Type")
                .HasValue<RequestTaxi>(value: Convert.ToInt32(value: RequestType.TaxiRequester));

            model.Entity<ApplicationUsers>().Property(p => p.Id).ValueGeneratedOnAdd();
            model.Entity<Role>().Property(p => p.RoleId).ValueGeneratedOnAdd();
            model.Entity<Car>().Property(p => p.CarId).ValueGeneratedOnAdd();
            model.Entity<Address>().Property(p => p.AddressId).ValueGeneratedOnAdd();
            model.Entity<Organization>().Property(p => p.OrganizationId).ValueGeneratedOnAdd();
            model.Entity<Credit>().Property(p => p.CreditId).ValueGeneratedOnAdd();
            model.Entity<StablePrice>().Property(p => p.StablePriceId).ValueGeneratedOnAdd();
            model.Entity<Package>().Property(p => p.PackageId).ValueGeneratedOnAdd();
            model.Entity<Rating>().Property(p => p.RatingId).ValueGeneratedOnAdd();
            model.Entity<City>().Property(p => p.CityId).ValueGeneratedOnAdd();
            model.Entity<SpecialAddress>().Property(p => p.SpecialAddressId).ValueGeneratedOnAdd();
            model.Entity<UserToken>().Property(p => p.Id).ValueGeneratedOnAdd();
            model.Entity<PersonRequest>(entity =>
            {
                entity.HasKey(e => new {e.RequestId, e.PersonId})
                    .HasName(name: "PK_dbo.PersonRequest");

                entity.HasIndex(e => e.RequestId)
                    .HasName(name: "IX_RequestId");

                entity.HasIndex(e => e.PersonId)
                    .HasName(name: "IX_PersonId");
            });
            model.Entity<PackageReseller>(entity =>
            {
                entity.HasKey(e => new { e.PackageId, e.ResellerId })
                    .HasName(name: "PK_dbo.PackageReseller");

                entity.HasIndex(e => e.PackageId)
                    .HasName(name: "IX_PackageId");

                entity.HasIndex(e => e.ResellerId)
                    .HasName(name: "IX_ResellerId");
            });
            model.Entity<UserRole>(entity =>
            {
                entity.HasKey(e => new { e.ApplicationUserId, e.RoleId })
                    .HasName(name: "PK_dbo.UserRole");

                entity.HasIndex(e => e.ApplicationUserId)
                    .HasName(name: "IX_ApplicationUserId");

                entity.HasIndex(e => e.RoleId)
                    .HasName(name: "IX_RoleId");
            });
        }
        public virtual DbSet<ApplicationUsers> ApplicationUsers { get; set; }
        public virtual DbSet<Role> Role { get; set; }
        public virtual DbSet<UserRole> UserRole { get; set; }
        public virtual DbSet<UserToken> UserToken { get; set; }

        public virtual DbSet<Address> Address { get; set; }
        public virtual DbSet<Credit> Credit { get; set; }
        public virtual DbSet<Organization> Organization { get; set; }
        public virtual DbSet<City> City { get; set; }
        public virtual DbSet<StablePrice> StablePrice { get; set; }
        public virtual DbSet<PersonRequest> PersonRequest { get; set; }
        public virtual DbSet<Discount> Discount { get; set; }
        public virtual DbSet<Rating> Rating { get; set; }
        public virtual DbSet<SpecialAddress> SpecialAddress { get; set; }

        public void AddRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class
        {
            Set<TEntity>().AddRange(entities: entities);
        }

        public void RemoveRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class
        {
            Set<TEntity>().RemoveRange(entities: entities);
        }

        public void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class
        {
            Entry(entity: entity).State = EntityState.Modified; // Or use ---> this.Update(entity);
        }

        public void ExecuteSqlCommand(string query)
        {
            Database.ExecuteSqlCommand(sql: query);
        }

        public void ExecuteSqlCommand(string query, params object[] parameters)
        {
            Database.ExecuteSqlCommand(sql: query, parameters: parameters);
        }

        public int SaveAllChanges()
        {
            return SaveChanges();
        }

        public Task<int> SaveAllChangesAsync()
        {
            return SaveChangesAsync();
        }
    }
}
</code>```

This my IUnitOfWork:

namespace Eela.Data
{
    public interface IUnitOfWork : IDisposable
    {
        DbSet<TEntity> Set<TEntity>() where TEntity : class;

        void AddRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class;
        void RemoveRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class;

        EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
        void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class;

        void ExecuteSqlCommand(string query);
        void ExecuteSqlCommand(string query, params object[] parameters);

        int SaveAllChanges();
        Task<int> SaveAllChangesAsync();

        int SaveChanges(bool acceptAllChangesOnSuccess);
        int SaveChanges();
        Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken());
        Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken());
    }
}
```

<p>This is one of my repositories :</p>

<pre class="lang-cs prettyprint-override"><code>public class RequestRepository : IRequestRepository
   {
       private readonly IMapper _mapper;
       private readonly IUnitOfWork _unitOfWork;
       private readonly DbSet<Request> _request;
       private readonly DbSet<Person> _person;
       private readonly DbSet<PersonRequest> _personRequest;
       public RequestRepository(IMapper mapper, IUnitOfWork unitOfWork)
       {
           _mapper = mapper;
           _unitOfWork = unitOfWork;
           _request = _unitOfWork.Set<Request>();
           _person = _unitOfWork.Set<Person>();
           _personRequest = _unitOfWork.Set<PersonRequest>();
       }
     public async Task<DetailPageViewModel> GetRequestAsync(string requestId)
       {
           var request = await (from x in _request
               where x.RequestId == Guid.Parse(requestId)
               from y in x.PersonsRequests
               where y.Person is User
               select new DetailPageViewModel
               {
                   RequestId = x.RequestId.ToString(),
                   CustomerName = y.Person.LastName,
                   SourceAddress = ((RequestTaxi) x).SourceAddress,
                   DestinationAddress = ((RequestTaxi) x).DestinationAddress,
                   DestinationLat = x.DestinationLat,
                   DestinationLon = x.DestinationLon,
                   EstimateDistance = ((RequestTaxi) x).Distance.ToString(CultureInfo.InvariantCulture),
                   EstimateDriverPrice = x.Price.ToString(),
                   EstimatePassengerPrice = x.PaymentType == PaymentType.Cash ? x.Price.ToString() : "0",
                   SourceLat = ((RequestTaxi) x).SourceLat,
                   SourceLon = ((RequestTaxi) x).SourceLon
               }).FirstOrDefaultAsync();

           return
               _mapper.Map<DetailPageViewModel>(
                   source: request);
       }
       .....
</code>```

And finally, this is one of my controller :

public class DetailPageController:Controller
   {
       private readonly IPersonRequestRepository _personRequest;
       private readonly IRequestRepository _request;
       private readonly IApplicationUsersRepository _appUser;
       private readonly IStablePriceRepository _stablePrice;
       private readonly ILogRepository _log;
       private readonly ICreditRepository _credit;
       private readonly INotificationService _notification;
       private readonly IPasswordGenerator _charecterGenerator;

       public DetailPageController(IPersonRequestRepository personRequest,ICreditRepository credit,
           ILogRepository log,IStablePriceRepository stablePrice,IApplicationUsersRepository appUser,
           IRequestRepository request,INotificationService notification,IPasswordGenerator charecterGenerator)
       {
           _personRequest = personRequest;
           _credit = credit;
           _log = log;
           _stablePrice = stablePrice;
           _appUser = appUser;
           _request = request;
           _notification = notification;
           _charecterGenerator = charecterGenerator;
       }

       [HttpPost]
       [ActionName("GetRequest")]
       public async Task<ActionResult> GetRequest([FromBody]string model)
       {
           var requestId = model;
           return Json(data: await _request.GetRequestAsync(requestId));
       }
```

<p>RequestLoggingMiddleware.cs :</p>

<pre class="lang-cs prettyprint-override"><code>public class RequestLoggingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<RequestLoggingMiddleware> _logger;
        private readonly ILogRepository _logRepository;
        private readonly IConfigurationRoot _configuration;

        public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger,
            ILogRepository logRepository,IConfigurationRoot configuration)
        {
            _next = next;
            _logger = logger;
            _logRepository = logRepository;
            _configuration = configuration;
        }

        public async Task<OperationResult> Invoke(HttpContext context)
        {
            using (MemoryStream requestBodyStream = new MemoryStream())
            {
                using (MemoryStream responseBodyStream = new MemoryStream())
                {
                    Stream originalRequestBody = context.Request.Body;
                    context.Request.EnableRewind();
                    Stream originalResponseBody = context.Response.Body;

                    OperationResult op= new OperationResult();
                    try
                    {
                        await context.Request.Body.CopyToAsync(requestBodyStream);
                        requestBodyStream.Seek(0, SeekOrigin.Begin);

                        string requestBodyText = new StreamReader(requestBodyStream).ReadToEnd();

                        requestBodyStream.Seek(0, SeekOrigin.Begin);
                        context.Request.Body = requestBodyStream;

                        string responseBody = "";

                        context.Response.Body = responseBodyStream;
                        Stopwatch watch = Stopwatch.StartNew();
                        await _next(context);
                        watch.Stop();

                        responseBodyStream.Seek(0, SeekOrigin.Begin);
                        responseBody = new StreamReader(responseBodyStream).ReadToEnd();
                        var log = new LogRequestViewModel
                        {
                            Host= context.Request.Host.Host,
                            Path= context.Request.Path,
                            QueryString= context.Request.QueryString.ToString(),
                            ClientIp= context.Connection.RemoteIpAddress.MapToIPv4(),
                            Date= DateTime.Now.ToString(CultureInfo.InvariantCulture),
                            Duration= watch.ElapsedMilliseconds,
                            Method= context.Request.Method,
                            RequestContentLength= context.Request.ContentLength,
                            RequestContentType= context.Request.ContentType,
                            Application= GetType().Namespace,
                            User= context.User.Claims
                                .FirstOrDefault(x => x.Type == _configuration["UserIdType"])?.Value,
                            Headers= string.Join(",", context.Request.Headers.Select(he => he.Key + ":[" + he.Value + "]").ToList()),
                            RequestBodyText= requestBodyText,
                            ResponseBodyText = responseBody

                        };
                        var result = await _logRepository.SaveRequestLogAsync(log);
                        if (!result.Success)
                        {
                            op.Success = false;
                            op.AddMessage("Couldn't add request log to database");
                            _logger.LogError(message: result.MessageList.FirstOrDefault());
                            var ex = new Exception(message: result.MessageList.FirstOrDefault());
                            await _logRepository.SaveErrorLogAsync(exception: ex);
                        }
                        responseBodyStream.Seek(0, SeekOrigin.Begin);

                        await responseBodyStream.CopyToAsync(originalResponseBody);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(message: ex.Message);
                        await _logRepository.SaveErrorLogAsync(exception: ex);
                        byte[] data = System.Text.Encoding.UTF8.GetBytes("Unhandled Error occured, the error has been logged and the persons concerned are notified!! Please, try again in a while.");
                        originalResponseBody.Write(data, 0, data.Length);
                        op.Success = false;
                        op.AddMessage(ex.Message);
                    }
                    finally
                    {
                        context.Request.Body = originalRequestBody;
                        context.Response.Body = originalResponseBody;

                    }
                    const string logTemplate = @"
                        Client IP: {clientIP}
                        Request path: {requestPath}
                        Request content type: {requestContentType}
                        Request content length: {requestContentLength}
                        Start time: {startTime}
                        Duration: {duration}";
                    _logger.LogInformation(logTemplate,
                        context.Connection.RemoteIpAddress.ToString(),
                        context.Request.Path,
                        context.Request.ContentType,
                        context.Request.ContentLength,
                        DateTime.UtcNow,
                        Stopwatch.StartNew());
                    return op;

                }

            }
        }
    }
</code>```

and this is my stack trace :

at
  Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
  at
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.d__61.MoveNext()
  --- End of stack trace from previous location where exception was thrown --- at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.d__59.MoveNext()
  --- End of stack trace from previous location where exception was thrown --- at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at
  Microsoft.EntityFrameworkCore.DbContext.d__48.MoveNext()
  --- End of stack trace from previous location where exception was thrown --- at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at
  Eela.Service.LogRepository.d__7.MoveNext() in
  D:\Eela\Eela.Service\LogRepository.cs:line 41 --- End of stack trace
  from previous location where exception was thrown --- at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at
  Eela.Web.Models.RequestLoggingMiddleware.d__5.MoveNext() in
  D:\Eela\Eela.Web\Models\RequestLoggingMiddleware.cs:line 82

Update :

I have a Middleware at my startup.cs :

```<code>app.UseMiddleware<RequestLoggingMiddleware>();
</code>```

When I Comment it out, My code works without any problem.
I include RequestLoggingMiddleware.cs source in my question.

Where is the main problem ?

答:
My guess is that the middleware is instantiated just once. So, that means that a single instance of context is used to perform concurrent access to database.

There are two solutions. The first one is to have context fabric and create an instance of context each time Invoke method is called. The second one is to store log records in the middleware, in a collection. And save them to database on some condition(count of records reached some particular number or timeout has reached zero).

Depending on amount of log records, you might have performance issues. The second approach requires implementation of correct concurrent access to the collection. And in some circumstances you can lost some amount of log records.

Body:
I have a WebApi that that uses EFCore2.0 and 2 client trying to access to an action method at a same time ...
Everything is working fine with one client. But when 2 or more trying to access to a one particular action method at a same time, I got this error at Microsoft.EntityFrameworkCore :

A second operation started on this context before a previous operation
  completed. Any instance members are not guaranteed to be thread safe

I used DI and repository for WebApi. I defined Scope for IUnitOfWork,I defined Transient, but nothing is worked.

This is my startup :

....
services.AddSingleton(provider => Configuration);
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped<IUnitOfWork, ApplicationDbContext>();
            services.AddTransient<IRoleService, RoleService>();
            services.AddTransient<ISecurityService, SecurityService>();
            services.AddTransient<IDbInitializerService, DbInitializerService>();
            services.AddTransient<ITokenStoreService, TokenStoreService>();
            services.AddTransient<ITokenValidatorService, TokenValidatorService>();
            services.AddTransient<ICookieValidatorService, CookieValidatorService>();
            services.AddTransient<IRequestRepository, RequestRepository>();
            services.AddDbContextPool<ApplicationDbContext>(options =>
            {
                options.UseSqlServer(
                    Configuration["ConnectionStrings:ApplicationDbContextConnection"].ToString(),
                    serverDbContextOptionsBuilder =>
                    {
                        var minutes = (int)TimeSpan.FromMinutes(3).TotalSeconds;
                        serverDbContextOptionsBuilder.CommandTimeout(minutes);
                        serverDbContextOptionsBuilder.EnableRetryOnFailure();
                    });
            });
....

This is my DbContext:

namespace Eela.Data
{

    public class
        ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {

        public ApplicationDbContext CreateDbContext(string[] args)
        {
            var services = new ServiceCollection();
            services.AddOptions();
            services.AddScoped<IHostingEnvironment, CustomHostingEnvironment>();
            services.AddSingleton<ILoggerFactory, LoggerFactory>();
            var serviceProvider = services.BuildServiceProvider();
            var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
            var logger = loggerFactory.CreateLogger<ConfigProvider>();
            var hostingEnvironment = serviceProvider.GetRequiredService<IHostingEnvironment>();
            Console.WriteLine($"Using `{hostingEnvironment.ContentRootPath}` as the ContentRootPath");
            var configuration = new ConfigurationBuilder()
                .SetBasePath(basePath: hostingEnvironment.ContentRootPath)
                .AddJsonFile(path: "appsettings.json", reloadOnChange: true, optional: false)
                .AddEncryptedProvider(hostingEnvironment: hostingEnvironment, logger: logger)
                .AddJsonFile(path: $"appsettings.{hostingEnvironment.EnvironmentName}.json", optional: true)
                .Build();
            var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
            var connectionString = configuration["ConnectionStrings:ApplicationDbContextConnection"];
            var useInMemoryDatabase = configuration[key: "UseInMemoryDatabase"].Equals(value: "true",
                comparisonType: StringComparison.OrdinalIgnoreCase);
            if (useInMemoryDatabase)
                builder.UseInMemoryDatabase("MyDatabase");
            else
            builder.UseSqlServer(connectionString);
            builder.ConfigureWarnings(warnings => warnings.Log(CoreEventId.IncludeIgnoredWarning));
            return new ApplicationDbContext(builder.Options);
        }
    }

    public class ApplicationDbContext : DbContext, IUnitOfWork
    {

        public ApplicationDbContext(DbContextOptions options) : base(options)
        { }
        protected override void OnModelCreating(ModelBuilder model)
        {
            base.OnModelCreating(model);

            model.Entity<Person>().Property(p => p.PersonId).ValueGeneratedOnAdd();
            model.Entity<Person>()
                .HasDiscriminator<int>(name: "Type")
                .HasValue<WorkerTaxi>(value: Convert.ToInt32(value: AccountType.TaxiWorker))
                .HasValue<User>(value: Convert.ToInt32(value: AccountType.User))
                .HasValue<Reseller>(value: Convert.ToInt32(value: AccountType.Reseller));

            model.Entity<Log>().Property(p => p.Id).ValueGeneratedOnAdd();
            model.Entity<Log>()
                .HasDiscriminator<int>(name: "Type")
                .HasValue<LogRequest>(value: Convert.ToInt32(value: LogLevel.Information))
                .HasValue<LogError>(value: Convert.ToInt32(value: LogLevel.Error));

            model.Entity<Request>().Property(p => p.RequestId).ValueGeneratedOnAdd();
            model.Entity<Request>()
                .HasDiscriminator<int>(name: "Type")
                .HasValue<RequestTaxi>(value: Convert.ToInt32(value: RequestType.TaxiRequester));

            model.Entity<ApplicationUsers>().Property(p => p.Id).ValueGeneratedOnAdd();
            model.Entity<Role>().Property(p => p.RoleId).ValueGeneratedOnAdd();
            model.Entity<Car>().Property(p => p.CarId).ValueGeneratedOnAdd();
            model.Entity<Address>().Property(p => p.AddressId).ValueGeneratedOnAdd();
            model.Entity<Organization>().Property(p => p.OrganizationId).ValueGeneratedOnAdd();
            model.Entity<Credit>().Property(p => p.CreditId).ValueGeneratedOnAdd();
            model.Entity<StablePrice>().Property(p => p.StablePriceId).ValueGeneratedOnAdd();
            model.Entity<Package>().Property(p => p.PackageId).ValueGeneratedOnAdd();
            model.Entity<Rating>().Property(p => p.RatingId).ValueGeneratedOnAdd();
            model.Entity<City>().Property(p => p.CityId).ValueGeneratedOnAdd();
            model.Entity<SpecialAddress>().Property(p => p.SpecialAddressId).ValueGeneratedOnAdd();
            model.Entity<UserToken>().Property(p => p.Id).ValueGeneratedOnAdd();
            model.Entity<PersonRequest>(entity =>
            {
                entity.HasKey(e => new {e.RequestId, e.PersonId})
                    .HasName(name: "PK_dbo.PersonRequest");

                entity.HasIndex(e => e.RequestId)
                    .HasName(name: "IX_RequestId");

                entity.HasIndex(e => e.PersonId)
                    .HasName(name: "IX_PersonId");
            });
            model.Entity<PackageReseller>(entity =>
            {
                entity.HasKey(e => new { e.PackageId, e.ResellerId })
                    .HasName(name: "PK_dbo.PackageReseller");

                entity.HasIndex(e => e.PackageId)
                    .HasName(name: "IX_PackageId");

                entity.HasIndex(e => e.ResellerId)
                    .HasName(name: "IX_ResellerId");
            });
            model.Entity<UserRole>(entity =>
            {
                entity.HasKey(e => new { e.ApplicationUserId, e.RoleId })
                    .HasName(name: "PK_dbo.UserRole");

                entity.HasIndex(e => e.ApplicationUserId)
                    .HasName(name: "IX_ApplicationUserId");

                entity.HasIndex(e => e.RoleId)
                    .HasName(name: "IX_RoleId");
            });
        }
        public virtual DbSet<ApplicationUsers> ApplicationUsers { get; set; }
        public virtual DbSet<Role> Role { get; set; }
        public virtual DbSet<UserRole> UserRole { get; set; }
        public virtual DbSet<UserToken> UserToken { get; set; }

        public virtual DbSet<Address> Address { get; set; }
        public virtual DbSet<Credit> Credit { get; set; }
        public virtual DbSet<Organization> Organization { get; set; }
        public virtual DbSet<City> City { get; set; }
        public virtual DbSet<StablePrice> StablePrice { get; set; }
        public virtual DbSet<PersonRequest> PersonRequest { get; set; }
        public virtual DbSet<Discount> Discount { get; set; }
        public virtual DbSet<Rating> Rating { get; set; }
        public virtual DbSet<SpecialAddress> SpecialAddress { get; set; }

        public void AddRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class
        {
            Set<TEntity>().AddRange(entities: entities);
        }

        public void RemoveRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class
        {
            Set<TEntity>().RemoveRange(entities: entities);
        }

        public void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class
        {
            Entry(entity: entity).State = EntityState.Modified; // Or use ---> this.Update(entity);
        }

        public void ExecuteSqlCommand(string query)
        {
            Database.ExecuteSqlCommand(sql: query);
        }

        public void ExecuteSqlCommand(string query, params object[] parameters)
        {
            Database.ExecuteSqlCommand(sql: query, parameters: parameters);
        }

        public int SaveAllChanges()
        {
            return SaveChanges();
        }

        public Task<int> SaveAllChangesAsync()
        {
            return SaveChangesAsync();
        }
    }
}

This my IUnitOfWork:

namespace Eela.Data
{
    public interface IUnitOfWork : IDisposable
    {
        DbSet<TEntity> Set<TEntity>() where TEntity : class;

        void AddRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class;
        void RemoveRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class;

        EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
        void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class;

        void ExecuteSqlCommand(string query);
        void ExecuteSqlCommand(string query, params object[] parameters);

        int SaveAllChanges();
        Task<int> SaveAllChangesAsync();

        int SaveChanges(bool acceptAllChangesOnSuccess);
        int SaveChanges();
        Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken());
        Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken());
    }
}

This is one of my repositories :

public class RequestRepository : IRequestRepository
   {
       private readonly IMapper _mapper;
       private readonly IUnitOfWork _unitOfWork;
       private readonly DbSet<Request> _request;
       private readonly DbSet<Person> _person;
       private readonly DbSet<PersonRequest> _personRequest;
       public RequestRepository(IMapper mapper, IUnitOfWork unitOfWork)
       {
           _mapper = mapper;
           _unitOfWork = unitOfWork;
           _request = _unitOfWork.Set<Request>();
           _person = _unitOfWork.Set<Person>();
           _personRequest = _unitOfWork.Set<PersonRequest>();
       }
     public async Task<DetailPageViewModel> GetRequestAsync(string requestId)
       {
           var request = await (from x in _request
               where x.RequestId == Guid.Parse(requestId)
               from y in x.PersonsRequests
               where y.Person is User
               select new DetailPageViewModel
               {
                   RequestId = x.RequestId.ToString(),
                   CustomerName = y.Person.LastName,
                   SourceAddress = ((RequestTaxi) x).SourceAddress,
                   DestinationAddress = ((RequestTaxi) x).DestinationAddress,
                   DestinationLat = x.DestinationLat,
                   DestinationLon = x.DestinationLon,
                   EstimateDistance = ((RequestTaxi) x).Distance.ToString(CultureInfo.InvariantCulture),
                   EstimateDriverPrice = x.Price.ToString(),
                   EstimatePassengerPrice = x.PaymentType == PaymentType.Cash ? x.Price.ToString() : "0",
                   SourceLat = ((RequestTaxi) x).SourceLat,
                   SourceLon = ((RequestTaxi) x).SourceLon
               }).FirstOrDefaultAsync();

           return
               _mapper.Map<DetailPageViewModel>(
                   source: request);
       }
       .....

And finally, this is one of my controller :

public class DetailPageController:Controller
   {
       private readonly IPersonRequestRepository _personRequest;
       private readonly IRequestRepository _request;
       private readonly IApplicationUsersRepository _appUser;
       private readonly IStablePriceRepository _stablePrice;
       private readonly ILogRepository _log;
       private readonly ICreditRepository _credit;
       private readonly INotificationService _notification;
       private readonly IPasswordGenerator _charecterGenerator;

       public DetailPageController(IPersonRequestRepository personRequest,ICreditRepository credit,
           ILogRepository log,IStablePriceRepository stablePrice,IApplicationUsersRepository appUser,
           IRequestRepository request,INotificationService notification,IPasswordGenerator charecterGenerator)
       {
           _personRequest = personRequest;
           _credit = credit;
           _log = log;
           _stablePrice = stablePrice;
           _appUser = appUser;
           _request = request;
           _notification = notification;
           _charecterGenerator = charecterGenerator;
       }

       [HttpPost]
       [ActionName("GetRequest")]
       public async Task<ActionResult> GetRequest([FromBody]string model)
       {
           var requestId = model;
           return Json(data: await _request.GetRequestAsync(requestId));
       }

RequestLoggingMiddleware.cs :

public class RequestLoggingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<RequestLoggingMiddleware> _logger;
        private readonly ILogRepository _logRepository;
        private readonly IConfigurationRoot _configuration;

        public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger,
            ILogRepository logRepository,IConfigurationRoot configuration)
        {
            _next = next;
            _logger = logger;
            _logRepository = logRepository;
            _configuration = configuration;
        }

        public async Task<OperationResult> Invoke(HttpContext context)
        {
            using (MemoryStream requestBodyStream = new MemoryStream())
            {
                using (MemoryStream responseBodyStream = new MemoryStream())
                {
                    Stream originalRequestBody = context.Request.Body;
                    context.Request.EnableRewind();
                    Stream originalResponseBody = context.Response.Body;

                    OperationResult op= new OperationResult();
                    try
                    {
                        await context.Request.Body.CopyToAsync(requestBodyStream);
                        requestBodyStream.Seek(0, SeekOrigin.Begin);

                        string requestBodyText = new StreamReader(requestBodyStream).ReadToEnd();

                        requestBodyStream.Seek(0, SeekOrigin.Begin);
                        context.Request.Body = requestBodyStream;

                        string responseBody = "";

                        context.Response.Body = responseBodyStream;
                        Stopwatch watch = Stopwatch.StartNew();
                        await _next(context);
                        watch.Stop();

                        responseBodyStream.Seek(0, SeekOrigin.Begin);
                        responseBody = new StreamReader(responseBodyStream).ReadToEnd();
                        var log = new LogRequestViewModel
                        {
                            Host= context.Request.Host.Host,
                            Path= context.Request.Path,
                            QueryString= context.Request.QueryString.ToString(),
                            ClientIp= context.Connection.RemoteIpAddress.MapToIPv4(),
                            Date= DateTime.Now.ToString(CultureInfo.InvariantCulture),
                            Duration= watch.ElapsedMilliseconds,
                            Method= context.Request.Method,
                            RequestContentLength= context.Request.ContentLength,
                            RequestContentType= context.Request.ContentType,
                            Application= GetType().Namespace,
                            User= context.User.Claims
                                .FirstOrDefault(x => x.Type == _configuration["UserIdType"])?.Value,
                            Headers= string.Join(",", context.Request.Headers.Select(he => he.Key + ":[" + he.Value + "]").ToList()),
                            RequestBodyText= requestBodyText,
                            ResponseBodyText = responseBody

                        };
                        var result = await _logRepository.SaveRequestLogAsync(log);
                        if (!result.Success)
                        {
                            op.Success = false;
                            op.AddMessage("Couldn't add request log to database");
                            _logger.LogError(message: result.MessageList.FirstOrDefault());
                            var ex = new Exception(message: result.MessageList.FirstOrDefault());
                            await _logRepository.SaveErrorLogAsync(exception: ex);
                        }
                        responseBodyStream.Seek(0, SeekOrigin.Begin);

                        await responseBodyStream.CopyToAsync(originalResponseBody);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(message: ex.Message);
                        await _logRepository.SaveErrorLogAsync(exception: ex);
                        byte[] data = System.Text.Encoding.UTF8.GetBytes("Unhandled Error occured, the error has been logged and the persons concerned are notified!! Please, try again in a while.");
                        originalResponseBody.Write(data, 0, data.Length);
                        op.Success = false;
                        op.AddMessage(ex.Message);
                    }
                    finally
                    {
                        context.Request.Body = originalRequestBody;
                        context.Response.Body = originalResponseBody;

                    }
                    const string logTemplate = @"
                        Client IP: {clientIP}
                        Request path: {requestPath}
                        Request content type: {requestContentType}
                        Request content length: {requestContentLength}
                        Start time: {startTime}
                        Duration: {duration}";
                    _logger.LogInformation(logTemplate,
                        context.Connection.RemoteIpAddress.ToString(),
                        context.Request.Path,
                        context.Request.ContentType,
                        context.Request.ContentLength,
                        DateTime.UtcNow,
                        Stopwatch.StartNew());
                    return op;

                }

            }
        }
    }

and this is my stack trace :

at
  Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
  at
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.d__61.MoveNext()
  --- End of stack trace from previous location where exception was thrown --- at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.d__59.MoveNext()
  --- End of stack trace from previous location where exception was thrown --- at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at
  Microsoft.EntityFrameworkCore.DbContext.d__48.MoveNext()
  --- End of stack trace from previous location where exception was thrown --- at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at
  Eela.Service.LogRepository.d__7.MoveNext() in
  D:\Eela\Eela.Service\LogRepository.cs:line 41 --- End of stack trace
  from previous location where exception was thrown --- at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at
  Eela.Web.Models.RequestLoggingMiddleware.d__5.MoveNext() in
  D:\Eela\Eela.Web\Models\RequestLoggingMiddleware.cs:line 82

Update :

I have a Middleware at my startup.cs :

app.UseMiddleware<RequestLoggingMiddleware>();

When I Comment it out, My code works without any problem.
I include RequestLoggingMiddleware.cs source in my question.

Where is the main problem ?


问:
Not possible to Reload code in Android emulator (React Native)
I have modified build.gradle in the project, after the finishing modifying it, it's not possible to reload code in the Android emulator using R-R or using cmd+M. Any ideas how to fix it?

答:
I have found the solution: </p>

```<code>Clean project => Build => Edit Build Type => select Your Modules (app) => tab build Type => change Debugable to true
</code>```

<p>Sync and build again!
Now reloading using R-R working again! </p>

Body:
I have found the solution:

Clean project => Build => Edit Build Type => select Your Modules (app) => tab build Type => change Debugable to true

Sync and build again!
Now reloading using R-R working again!