问:
How can I downgrade Homebrew to an older version?
Currently I have the latest version 2.2.17, I want to downgrade to version 2.2.12.

Brew does not have a downgrade option, just an upgrade. Is the process to uninstall brew and re-install it again?

答:
If you used the normal installation way via the install script:

```<code>/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
</code>```

Then take a look at the brew install script (it has its own repo).

It downloads the actual Homebrew repo to /usr/local/Homebrew.

```<code>...
HOMEBREW_PREFIX="/usr/local"
HOMEBREW_REPOSITORY="/usr/local/Homebrew"
...

BREW_REPO="https://github.com/Homebrew/brew"
...

ohai "Downloading and installing Homebrew..."
(
  cd "${HOMEBREW_REPOSITORY}" >/dev/null || return

  # "git remote add" will fail if the remote is defined in the global config
  execute "git" "config" "remote.origin.url" "${BREW_REPO}"
  execute "git" "config" "remote.origin.fetch" "+refs/heads/*:refs/remotes/origin/*"
  ...

  execute "ln" "-sf" "${HOMEBREW_REPOSITORY}/bin/brew" "${HOMEBREW_PREFIX}/bin/brew"
  ...
}
...
</code>```
```<code>==> This script will install:
/usr/local/bin/brew
/usr/local/share/doc/homebrew
/usr/local/share/man/man1/brew.1
/usr/local/share/zsh/site-functions/_brew
/usr/local/etc/bash_completion.d/brew
/usr/local/Homebrew
...
</code>```

The script installs the latest copy of the Homebrew repo. So the answer to "Is the process to uninstall brew and re-install it again?" would be a "NO". Instead, install it first normally, and then after, go over to /usr/local/Homebrew and checkout the version you want.

```<code>~$ cd /usr/local/Homebrew

Homebrew$ brew --version
Homebrew 2.3.0
Homebrew/homebrew-core (git revision d41d92; last commit 2020-05-29)

Homebrew$ git fetch --tags
Homebrew$ git checkout 2.2.12
Note: switching to '2.2.12'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at 2ae26808a Merge pull request #7301 from Bo98/cmake-sdkroot

Homebrew$ brew --version
Homebrew 2.2.12

Homebrew$ cd /usr/local/bin
bin$ ./brew --version
Homebrew 2.2.12
Homebrew/homebrew-core (git revision d41d92; last commit 2020-05-29)
</code>```

I recommend doing a brew doctor after just to make sure everything's still OK.

Then, unfortunately, Homebrew always auto-updates itself every time you install something. So it will always update the repo at /usr/local/Homebrew up again to the latest version. You can disable that by exporting HOMEBREW_NO_AUTO_UPDATE as mentioned here https://github.com/Homebrew/brew/issues/1670.

```<code>~$ export HOMEBREW_NO_AUTO_UPDATE=1
~$ brew install python@3.8
</code>```

You'll need to create an alias or auto-export that env var to your bash_profile (or whatever is the equivalent for the terminal you use), so that it takes effect every time you use brew.

Body:
If you used the normal installation way via the install script:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

Then take a look at the brew install script (it has its own repo).

It downloads the actual Homebrew repo to /usr/local/Homebrew.

...
HOMEBREW_PREFIX="/usr/local"
HOMEBREW_REPOSITORY="/usr/local/Homebrew"
...

BREW_REPO="https://github.com/Homebrew/brew"
...

ohai "Downloading and installing Homebrew..."
(
  cd "${HOMEBREW_REPOSITORY}" >/dev/null || return

  # "git remote add" will fail if the remote is defined in the global config
  execute "git" "config" "remote.origin.url" "${BREW_REPO}"
  execute "git" "config" "remote.origin.fetch" "+refs/heads/*:refs/remotes/origin/*"
  ...

  execute "ln" "-sf" "${HOMEBREW_REPOSITORY}/bin/brew" "${HOMEBREW_PREFIX}/bin/brew"
  ...
}
...

==> This script will install:
/usr/local/bin/brew
/usr/local/share/doc/homebrew
/usr/local/share/man/man1/brew.1
/usr/local/share/zsh/site-functions/_brew
/usr/local/etc/bash_completion.d/brew
/usr/local/Homebrew
...

The script installs the latest copy of the Homebrew repo. So the answer to "Is the process to uninstall brew and re-install it again?" would be a "NO". Instead, install it first normally, and then after, go over to /usr/local/Homebrew and checkout the version you want.

~$ cd /usr/local/Homebrew

Homebrew$ brew --version
Homebrew 2.3.0
Homebrew/homebrew-core (git revision d41d92; last commit 2020-05-29)

Homebrew$ git fetch --tags
Homebrew$ git checkout 2.2.12
Note: switching to '2.2.12'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at 2ae26808a Merge pull request #7301 from Bo98/cmake-sdkroot

Homebrew$ brew --version
Homebrew 2.2.12

Homebrew$ cd /usr/local/bin
bin$ ./brew --version
Homebrew 2.2.12
Homebrew/homebrew-core (git revision d41d92; last commit 2020-05-29)

I recommend doing a brew doctor after just to make sure everything's still OK.

Then, unfortunately, Homebrew always auto-updates itself every time you install something. So it will always update the repo at /usr/local/Homebrew up again to the latest version. You can disable that by exporting HOMEBREW_NO_AUTO_UPDATE as mentioned here https://github.com/Homebrew/brew/issues/1670.

~$ export HOMEBREW_NO_AUTO_UPDATE=1
~$ brew install python@3.8

You'll need to create an alias or auto-export that env var to your bash_profile (or whatever is the equivalent for the terminal you use), so that it takes effect every time you use brew.


来源: stackexchange

问:
vue-router params undefined on create()
I'm grabbing a param from my vue-router and I get this error when trying to store the params data into my components data

```<code>Error in created hook: "TypeError: Cannot read property 'params' of undefined"
</code>```

here is where I am sending the data from ('Home') component

```<code><template>
  <div class="container">

      <div v-for="art in articles" :key="art.title">
          <img alt="an image">
          <h4>{{art.title}}</h4>
          <button @click="shareData()"></button>
      </div>

  </div>
</template>

<script>
//const fb = require('../../fireconfig.js')

export default {
  name: 'Home',
  data:function() {
    return{
       articles: [
         {
           title: 'eee',
           body: 'oooo',
           img: 'dd'
        },
         {
           title: 'eesecone',
           body: 'secondddd',
           img: 'dwwd'
        }
      ]
    }
  },
  props: {
    post: Object
  },
  created(){
    console.log('db post will go here later')
    /*
    let ref = fb.db.collection('articles')
    ref.get()
  .then(snapshot => {
    if (snapshot.empty) {
      console.log('No matching documents.');
      return;
    }
    snapshot.forEach(doc => {
      console.log(doc.id, '=>', doc.data());
      this.articles.push(doc.data())
    });
  })
  .catch(err => {
    console.log('Error getting documents', err);
  });
  */
  },
  methods:{
    shareData(){
      this.$router.push({name: 'Article', params: {data: this.articles} })
    }
  }
}
</script>

</code>```

here is the component receiving the data and storing it ('Article'), they are in the same directory

```<code><template>
  <div class="container">
      <h3>THIS IS THE PAGE FOR A SINGLE ARTICLE</h3>
  <div v-for="art in articleData" :key="art.title">
      <img alt="an image">
          <h4>{{art.title}}</h4>
          <div>{{art.body}}</div>
</div>

  </div>
</template>

<script>
export default {
  name: 'Article',
    data:function(){
        return{
        articleData:[]
        }
},
    created(){
        this.articleData = this.$routes.params.data  //----------error happens here-------------
    }
}
</script>

</code>```

here is my router setup in main.js :)

```<code>import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';
import Article from './components/Article.vue'
import Home from './components/Home.vue'
import Search from './components/Search.vue'
Vue.use(VueRouter)
const routes = [
  {
    path: '/Article',
    name: 'Article',
    component: Article,
  },
  {
    path: '/',
    name: 'Home',
    component: Home,

  },
  {
    path: '/Search', component: Search,
    props: true
  }
];
const router = new VueRouter({
  routes
})

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

</code>```

答:
You're adding a s to $route it should be :

```<code>this.$route.params.data
</code>```

this refers to the current route not all $routes or the $router

ContentLicense: CC BY-SA 4.0

Title: vue-router params undefined on create()

Body:
I'm grabbing a param from my vue-router and I get this error when trying to store the params data into my components data

Error in created hook: "TypeError: Cannot read property 'params' of undefined"

here is where I am sending the data from ('Home') component

<template>

{{art.title}}

          <button @click="shareData()"></button>

</template>

here is the component receiving the data and storing it ('Article'), they are in the same directory

<template>

THIS IS THE PAGE FOR A SINGLE ARTICLE

{{art.title}}

{{art.body}}

</template>

here is my router setup in main.js :)

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';
import Article from './components/Article.vue'
import Home from './components/Home.vue'
import Search from './components/Search.vue'
Vue.use(VueRouter)
const routes = [
  {
    path: '/Article',
    name: 'Article',
    component: Article,
  },
  {
    path: '/',
    name: 'Home',
    component: Home,

  },
  {
    path: '/Search', component: Search,
    props: true
  }
];
const router = new VueRouter({
  routes
})

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

Body:
You're adding a s to $route it should be :

this.$route.params.data

this refers to the current route not all $routes or the $router


问:
How to format date correctly in LUA script - 05292020
I'm having some difficulty formatting the date in this LUA script. I want it to output the current date in the following format - 05292020. However, I can't get the year to format correctly, so my output is 052920. I've been searching extensively to find a solution but I'm really stuck on this one. Anyone able to point me in the right direction? Thank you in advance!

```<code>function OnEvent(event, arg, family)
  if event == "G_PRESSED" and arg == 1 then

    -- Take the first 8 characters only (1,8)
    local date = string.sub(GetDate(), 1, 8)
    for i = 1, #date do
      local ch = date:sub(i,i)
      if ch == "-" then
        PressAndReleaseKey("minus")
      elseif ch == "," then
        PressAndReleaseKey("comma")
      elseif ch == "." then
        PressAndReleaseKey("period")
      elseif ch == "/" then
      --  PressAndReleaseKey("slash")
      elseif ch == " " then
        PressAndReleaseKey("spacebar")
      elseif ch == ":" then
        PressKey("lshift")
        Sleep(10)
        PressAndReleaseKey("semicolon")
        ReleaseKey("lshift")
      elseif ch == ch:lower() then
        PressAndReleaseKey(ch)
      else
        PressKey("lshift")
        Sleep(10)
        PressAndReleaseKey(ch:lower())
        ReleaseKey("lshift")
      end
    end

  end
end
</code>```

答:
For my needs I do it this way:

```<code>-- CURRENT DATE AND TIME
local myyear = os.date("*t").year
local mymonth = os.date("*t").month; if mymonth < 10 then mymonth = "0"..mymonth end
local myday = os.date("*t").day; if myday < 10 then myday = "0"..myday end
local myhour = os.date("*t").hour; if myhour < 10 then myhour = "0"..myhour end
local mymin = os.date("*t").min; if mymin < 10 then mymin = "0"..mymin end
local mysec = os.date("*t").sec; if mysec < 10 then mysec = "0"..mysec end
local mytime = myyear..mymonth..myday.."_"..myhour..mymin..mysec
print(mytime)
</code>```

Hope this is not too complicated and can be of help?

PS: I am using gideros engine which uses lua.

Body:
I'm having some difficulty formatting the date in this LUA script. I want it to output the current date in the following format - 05292020. However, I can't get the year to format correctly, so my output is 052920. I've been searching extensively to find a solution but I'm really stuck on this one. Anyone able to point me in the right direction? Thank you in advance!

function OnEvent(event, arg, family)
  if event == "G_PRESSED" and arg == 1 then

    -- Take the first 8 characters only (1,8)
    local date = string.sub(GetDate(), 1, 8)
    for i = 1, #date do
      local ch = date:sub(i,i)
      if ch == "-" then
        PressAndReleaseKey("minus")
      elseif ch == "," then
        PressAndReleaseKey("comma")
      elseif ch == "." then
        PressAndReleaseKey("period")
      elseif ch == "/" then
      --  PressAndReleaseKey("slash")
      elseif ch == " " then
        PressAndReleaseKey("spacebar")
      elseif ch == ":" then
        PressKey("lshift")
        Sleep(10)
        PressAndReleaseKey("semicolon")
        ReleaseKey("lshift")
      elseif ch == ch:lower() then
        PressAndReleaseKey(ch)
      else
        PressKey("lshift")
        Sleep(10)
        PressAndReleaseKey(ch:lower())
        ReleaseKey("lshift")
      end
    end

  end
end

Body:
For my needs I do it this way:

-- CURRENT DATE AND TIME
local myyear = os.date("*t").year
local mymonth = os.date("*t").month; if mymonth < 10 then mymonth = "0"..mymonth end
local myday = os.date("*t").day; if myday < 10 then myday = "0"..myday end
local myhour = os.date("*t").hour; if myhour < 10 then myhour = "0"..myhour end
local mymin = os.date("*t").min; if mymin < 10 then mymin = "0"..mymin end
local mysec = os.date("*t").sec; if mysec < 10 then mysec = "0"..mysec end
local mytime = myyear..mymonth..myday.."_"..myhour..mymin..mysec
print(mytime)

Hope this is not too complicated and can be of help?

PS: I am using gideros engine which uses lua.


问:
Get index of last occurence of matched string?
I want to get the index of the last occurrence of a character in a string which is part of a match string. What's the most efficient way to do this?

Something like match(/[\.,;]/g) but I want the index in the original string of the last element of the returned array, the way that match(/[\.,;]/) gives the index of the first match.

E.g., if string is Hello, this is a test. foo I want the index of the last period/comma/semicolon.

The best solution I've come up with is reversing the string and finding first match:

```<code>text.length - text.split('').reverse().join('').match(/[\.,;]/).index - 1
</code>```

答:
let text = 'Hello, this is a test. foo';
let lastChar = [...text.matchAll(/[\.,;]/g)].pop().index
console.log(lastChar)```

Body:
I want to get the index of the last occurrence of a character in a string which is part of a match string. What's the most efficient way to do this?

Something like match(/[\.,;]/g) but I want the index in the original string of the last element of the returned array, the way that match(/[\.,;]/) gives the index of the first match.

E.g., if string is Hello, this is a test. foo I want the index of the last period/comma/semicolon.

The best solution I've come up with is reversing the string and finding first match:

text.length - text.split('').reverse().join('').match(/[\.,;]/).index - 1


问:
Obj C: Grouping strings into NSMutableDictionary
I have an NSArray that contains a bunch of strings.  Each string lists a parent and child type, such as:

```<code>Tool: Saw
Fruit: Apple
Fruit: Orange
Tree: Maple
Fruit: Banana
Tree: Oak
Tool: Hammer
Tree: Cedar
</code>```

My final structure that I need to put them into is (sorted parents and children):

```<code>Fruit:
  - Apple
  - Banana
  - Orange
Tool:
  - Hammer
  - Saw
Tree:
  - Cedar
  - Maple
  - Oak
</code>```

I would like to know how to group these under their parent type, sorting by that parent type and sorting the children. I assume the best thing to use would be an NSMutableDictionary to make them into keys and objects.

Here is what I tested so far but does not turn out how I want:

```<code>// Add to tree
if ([tree objectForKey:pathParent]) {
    NSMutableArray *temp = (NSMutableArray *)[tree objectForKey:pathParent];
    [temp addObject:name];
    [tree removeObjectForKey:pathParent];
    [tree setObject:temp forKey:pathParent];

} else {
    [tree setObject:[NSMutableArray arrayWithObject:name] forKey:pathParent];
}//end
</code>```

How would I do this?

答:
This is what I got working inside my for loop:</p>

```<code>if (pathParent != nil) {
    if ([tree objectForKey:pathParent]) {
        [[tree objectForKey:pathParent] addObject:name];
    } else {
        [tree setObject:[NSMutableArray arrayWithObject:name] forKey:pathParent];
    }//end
}//end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an NSArray that contains a bunch of strings.  Each string lists a parent and child type, such as:

Tool: Saw
Fruit: Apple
Fruit: Orange
Tree: Maple
Fruit: Banana
Tree: Oak
Tool: Hammer
Tree: Cedar

My final structure that I need to put them into is (sorted parents and children):

Fruit:
  - Apple
  - Banana
  - Orange
Tool:
  - Hammer
  - Saw
Tree:
  - Cedar
  - Maple
  - Oak

I would like to know how to group these under their parent type, sorting by that parent type and sorting the children. I assume the best thing to use would be an NSMutableDictionary to make them into keys and objects.

Here is what I tested so far but does not turn out how I want:

// Add to tree
if ([tree objectForKey:pathParent]) {
    NSMutableArray *temp = (NSMutableArray *)[tree objectForKey:pathParent];
    [temp addObject:name];
    [tree removeObjectForKey:pathParent];
    [tree setObject:temp forKey:pathParent];

} else {
    [tree setObject:[NSMutableArray arrayWithObject:name] forKey:pathParent];
}//end

How would I do this?

Body:
This is what I got working inside my for loop:

if (pathParent != nil) {
    if ([tree objectForKey:pathParent]) {
        [[tree objectForKey:pathParent] addObject:name];
    } else {
        [tree setObject:[NSMutableArray arrayWithObject:name] forKey:pathParent];
    }//end
}//end


问:
Calculuate the differences between averages in a paired data in R
I have a data frame as below:</p>
```<code>df <- data.frame(Staff = c("Jack", "Ruth", "Michael", "Ruth", "Jack", "Jack", "Ruth", "Michael"),
                 Client = c("Julie", "Julie", "Julie", "Julie", "Julie", "Candice", "Candice", "Candice"),
                 Assessment = c(1, 2, 2, 1, 7, 4, 1, 1),
                 Staff_avg_by_client = c(4, 1.5, 2, 1.5, 4, 4, 1, 1))
</code>```

答:
Here's an approach with data.table (since that's what you asked for):

We can use by = seq(1,nrow(df)) to work on every row.

Then for each row, we can subset df by that row's Staff and Client using the .SD special symbol. So for row 1, .SD[,Staff] evaluates to "Jack" and .SD[,Client] evaluates to "Julie".

```<code>library(data.table)
setDT(df)
df[, Diff := Staff_avg_by_client -
     df[Staff != .SD[,Staff] & Client == .SD[,Client], mean(Assessment)],
   by = seq(1,nrow(df))][]
   Month   Staff  Client Assessment Staff_avg_by_client      Diff
1:     1    Jack   Julie          1                 4.0  2.333333
2:     1    Ruth   Julie          2                 1.5 -1.833333
3:     1 Michael   Julie          2                 2.0 -0.750000
4:     1    Ruth   Julie          1                 1.5 -1.833333
5:     1    Jack   Julie          7                 4.0  2.333333
6:     1    Jack Candice          4                 4.0  3.000000
7:     1    Ruth Candice          1                 1.0 -1.500000
8:     1 Michael Candice          1                 1.0 -1.500000
</code>```

The final [] is just to print the data.table after assigning by reference.

Body:
I have a data frame as below:

df <- data.frame(Staff = c("Jack", "Ruth", "Michael", "Ruth", "Jack", "Jack", "Ruth", "Michael"),
                 Client = c("Julie", "Julie", "Julie", "Julie", "Julie", "Candice", "Candice", "Candice"),
                 Assessment = c(1, 2, 2, 1, 7, 4, 1, 1),
                 Staff_avg_by_client = c(4, 1.5, 2, 1.5, 4, 4, 1, 1))

Body:
Here's an approach with data.table (since that's what you asked for):

We can use by = seq(1,nrow(df)) to work on every row.

Then for each row, we can subset df by that row's Staff and Client using the .SD special symbol. So for row 1, .SD[,Staff] evaluates to "Jack" and .SD[,Client] evaluates to "Julie".

library(data.table)
setDT(df)
df[, Diff := Staff_avg_by_client -
     df[Staff != .SD[,Staff] & Client == .SD[,Client], mean(Assessment)],
   by = seq(1,nrow(df))][]
   Month   Staff  Client Assessment Staff_avg_by_client      Diff
1:     1    Jack   Julie          1                 4.0  2.333333
2:     1    Ruth   Julie          2                 1.5 -1.833333
3:     1 Michael   Julie          2                 2.0 -0.750000
4:     1    Ruth   Julie          1                 1.5 -1.833333
5:     1    Jack   Julie          7                 4.0  2.333333
6:     1    Jack Candice          4                 4.0  3.000000
7:     1    Ruth Candice          1                 1.0 -1.500000
8:     1 Michael Candice          1                 1.0 -1.500000

The final [] is just to print the data.table after assigning by reference.


问:
Create a table using data from another's table column that is in JSON form
I'm using a Postgres server. Here's how my table looks

which means the column of the genres of each movie is in form:

```<code>[
    {'id': 18, 'name': 'Drama'},
    {'id': 36, 'name': 'History'},
    {'id': 10749, 'name': 'Romance'}
]
</code>```

As you can see the genres for each movie are in a VARCHAR variable and in JSON array.

What I want to do is unpack the contents of the JSON and create a new table named Genres, which is going to have every genre once with its unique id.

So for the upper example I want my new table to look like this:

```<code>id  | genre
18  | 'Drama'
36  | 'History'.
</code>```

How can I do that?

答:
You should definitly fix your schema, and store your JSON data as JSON[B]  datatype rather than as strings.

That said, one option is to force the conversion to json so we then can use Postsgres' powerful json functions to unnest the arrays and access the inner objects. As far as your data shows, you just need to turn the single quotes to double quotes to make the strings valid Postgres JSON, so this should work:

```<code>insert into genres(id, genre)
select distinct js ->> 'id', js ->> 'name'
from mytable t
cross join lateral jsonb_array_elements( (replace(genres, ''', '"'))::jsonb ) j(js)
</code>```

Body:
I'm using a Postgres server. Here's how my table looks

which means the column of the genres of each movie is in form:

[
    {'id': 18, 'name': 'Drama'},
    {'id': 36, 'name': 'History'},
    {'id': 10749, 'name': 'Romance'}
]

As you can see the genres for each movie are in a VARCHAR variable and in JSON array.

What I want to do is unpack the contents of the JSON and create a new table named Genres, which is going to have every genre once with its unique id.

So for the upper example I want my new table to look like this:

id  | genre
18  | 'Drama'
36  | 'History'.

How can I do that?

Body:
You should definitly fix your schema, and store your JSON data as JSON[B]  datatype rather than as strings.

That said, one option is to force the conversion to json so we then can use Postsgres' powerful json functions to unnest the arrays and access the inner objects. As far as your data shows, you just need to turn the single quotes to double quotes to make the strings valid Postgres JSON, so this should work:

insert into genres(id, genre)
select distinct js ->> 'id', js ->> 'name'
from mytable t
cross join lateral jsonb_array_elements( (replace(genres, ''', '"'))::jsonb ) j(js)


问:
Identify AWS IAM user that assumed an IAM role
I'm working on a system that receives new findings from Amazon GuardDuty. Most access in our organization is delegated to IAM roles instead of directly to users, so the findings usually result from the actions of assumed roles, and the actor identity of the GuardDuty finding looks something like this:

```<code>  "resource": {
    "accessKeyDetails": {
      "accessKeyId": "ASIALXUWSRBXSAQZECAY",
      "principalId": "AROACDRML13PHK3X7J1UL:129545928468",
      "userName": "my-permitted-role",
      "userType": "AssumedRole"
    },
    "resourceType": "AccessKey"
  },
</code>```

I know that the accessKeyId is created when a security principal performs the iam:AssumeRole action. But I can't tell who assumed the role in the first place! If it was an IAM user, I want to know the username. Is there a way to programmatically map temporary AWS STS keys (starts with ASIA...) back to an original user?

Ideally I'm looking for a method that runs in less than 30 seconds so I can use it as part of my security event pipeline to enrich GuardDuty findings with the missing information.

I've already looked at aws-cli and found aws cloudtrail lookup-events but it lacks the ability to narrow the query to a specific accessKeyId so it takes a loooong time to run. I've explored the CloudTrail console but it's only about as capable as aws-cli here. I tried saving my CloudTrail logs to S3 and running an Athena query, but that was pretty slow too.

This seems like it would be a common requirement. Is there something obvious that I'm missing?

答:
Actually, aws-cli can perform a lookup on the session! Just make sure to specify ResourceName as the attribute key in the lookup attributes.

$ aws cloudtrail lookup-events \
  --lookup-attributes 'AttributeKey=ResourceName,AttributeValue=ASIALXUWSRBXSAQZECAY' \
  --query 'Events[*].Username'

[
    "the.user@example.com"
]
```

Body:
I'm working on a system that receives new findings from Amazon GuardDuty. Most access in our organization is delegated to IAM roles instead of directly to users, so the findings usually result from the actions of assumed roles, and the actor identity of the GuardDuty finding looks something like this:

  "resource": {
    "accessKeyDetails": {
      "accessKeyId": "ASIALXUWSRBXSAQZECAY",
      "principalId": "AROACDRML13PHK3X7J1UL:129545928468",
      "userName": "my-permitted-role",
      "userType": "AssumedRole"
    },
    "resourceType": "AccessKey"
  },

I know that the accessKeyId is created when a security principal performs the iam:AssumeRole action. But I can't tell who assumed the role in the first place! If it was an IAM user, I want to know the username. Is there a way to programmatically map temporary AWS STS keys (starts with ASIA...) back to an original user?

Ideally I'm looking for a method that runs in less than 30 seconds so I can use it as part of my security event pipeline to enrich GuardDuty findings with the missing information.

I've already looked at aws-cli and found aws cloudtrail lookup-events but it lacks the ability to narrow the query to a specific accessKeyId so it takes a loooong time to run. I've explored the CloudTrail console but it's only about as capable as aws-cli here. I tried saving my CloudTrail logs to S3 and running an Athena query, but that was pretty slow too.

This seems like it would be a common requirement. Is there something obvious that I'm missing?


问:
Setting up a Discord oauth2 login on my website (with PHP?)
So I'm having troubles learning how to set up a login through discord on my site. I've been browsing for literally hours and haven't been able to find anything I understand...

At the moment, I have created the discord application, giving me a client ID and client secret, as well as a link back to my localhost:

https://discordapp.com/api/oauth2/authorize?client_id=550631359337594881&redirect_uri=http%3A%2F%2Flocalhost&response_type=code&scope=identify

At the moment I have it set up to redirect from a button to that URL, which then sends me to discord to accept. It then returns me to http://localhost?code=CODE_HERE

However, I don't know what I am supposed to do with this code. I am trying to set it up so that it will show the person's username with hashtag thing, and their profile picture.

I am currently using HTML, CSS, JS, and PHP on the site, but I think I might need to use something else, but I don't know how to set that up, or what it is I need. I am running my local server with XAMPP. I'd prefer if it is just PHP, but I'm open to other options.

Does anyone know how I can convert the code to a username + image?

Thanks in advance!

答:
Try this

Credits to: eslachance

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('max_execution_time', 300); //300 seconds = 5 minutes. In case if your CURL is slow and is loading too much (Can be IPv6 problem)

error_reporting(E_ALL);

define('OAUTH2_CLIENT_ID', '1234567890'); //Your client Id
define('OAUTH2_CLIENT_SECRET', 'verysecretclientcode'); //Your secret client code

$authorizeURL = 'https://discordapp.com/api/oauth2/authorize';
$tokenURL = 'https://discordapp.com/api/oauth2/token';
$apiURLBase = 'https://discordapp.com/api/users/@me';

session_start();

// Start the login process by sending the user to Discord's authorization page
if(get('action') == 'login') {

  $params = array(
    'client_id' => OAUTH2_CLIENT_ID,
    'redirect_uri' => 'https://yoursite.location/ifyouneedit',
    'response_type' => 'code',
    'scope' => 'identify guilds'
  );

  // Redirect the user to Discord's authorization page
  header('Location: https://discordapp.com/api/oauth2/authorize' . '?' . http_build_query($params));
  die();
}

// When Discord redirects the user back here, there will be a "code" and "state" parameter in the query string
if(get('code')) {

  // Exchange the auth code for a token
  $token = apiRequest($tokenURL, array(
    "grant_type" => "authorization_code",
    'client_id' => OAUTH2_CLIENT_ID,
    'client_secret' => OAUTH2_CLIENT_SECRET,
    'redirect_uri' => 'https://yoursite.location/ifyouneedit',
    'code' => get('code')
  ));
  $logout_token = $token->access_token;
  $_SESSION['access_token'] = $token->access_token;

  header('Location: ' . $_SERVER['PHP_SELF']);
}

if(session('access_token')) {
  $user = apiRequest($apiURLBase);

  echo '
Logged In
';
  echo '
Welcome, ' . $user->username . '
';
  echo '```';
    print_r($user);
  echo '```';

} else {
  echo '
Not logged in
';
  echo '
Log In
';
}

if(get('action') == 'logout') {
  // This must to logout you, but it didn't worked(

  $params = array(
    'access_token' => $logout_token
  );

  // Redirect the user to Discord's revoke page
  header('Location: https://discordapp.com/api/oauth2/token/revoke' . '?' . http_build_query($params));
  die();
}

function apiRequest($url, $post=FALSE, $headers=array()) {
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

  $response = curl_exec($ch);

  if($post)
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

  $headers[] = 'Accept: application/json';

  if(session('access_token'))
    $headers[] = 'Authorization: Bearer ' . session('access_token');

  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  $response = curl_exec($ch);
  return json_decode($response);
}

function get($key, $default=NULL) {
  return array_key_exists($key, $_GET) ? $_GET[$key] : $default;
}

function session($key, $default=NULL) {
  return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
}

?>
```

Body:
Try this

Credits to: eslachance

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('max_execution_time', 300); //300 seconds = 5 minutes. In case if your CURL is slow and is loading too much (Can be IPv6 problem)

error_reporting(E_ALL);

define('OAUTH2_CLIENT_ID', '1234567890'); //Your client Id
define('OAUTH2_CLIENT_SECRET', 'verysecretclientcode'); //Your secret client code

$authorizeURL = 'https://discordapp.com/api/oauth2/authorize';
$tokenURL = 'https://discordapp.com/api/oauth2/token';
$apiURLBase = 'https://discordapp.com/api/users/@me';

session_start();

// Start the login process by sending the user to Discord's authorization page
if(get('action') == 'login') {

  $params = array(
    'client_id' => OAUTH2_CLIENT_ID,
    'redirect_uri' => 'https://yoursite.location/ifyouneedit',
    'response_type' => 'code',
    'scope' => 'identify guilds'
  );

  // Redirect the user to Discord's authorization page
  header('Location: https://discordapp.com/api/oauth2/authorize' . '?' . http_build_query($params));
  die();
}

// When Discord redirects the user back here, there will be a "code" and "state" parameter in the query string
if(get('code')) {

  // Exchange the auth code for a token
  $token = apiRequest($tokenURL, array(
    "grant_type" => "authorization_code",
    'client_id' => OAUTH2_CLIENT_ID,
    'client_secret' => OAUTH2_CLIENT_SECRET,
    'redirect_uri' => 'https://yoursite.location/ifyouneedit',
    'code' => get('code')
  ));
  $logout_token = $token->access_token;
  $_SESSION['access_token'] = $token->access_token;

  header('Location: ' . $_SERVER['PHP_SELF']);
}

if(session('access_token')) {
  $user = apiRequest($apiURLBase);

  echo '<h3>Logged In</h3>';
  echo '<h4>Welcome, ' . $user->username . '</h4>';
  echo '<pre>';
    print_r($user);
  echo '</pre>';

} else {
  echo '<h3>Not logged in</h3>';
  echo '<p><a href="?action=login">Log In</a></p>';
}

if(get('action') == 'logout') {
  // This must to logout you, but it didn't worked(

  $params = array(
    'access_token' => $logout_token
  );

  // Redirect the user to Discord's revoke page
  header('Location: https://discordapp.com/api/oauth2/token/revoke' . '?' . http_build_query($params));
  die();
}

function apiRequest($url, $post=FALSE, $headers=array()) {
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

  $response = curl_exec($ch);

  if($post)
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

  $headers[] = 'Accept: application/json';

  if(session('access_token'))
    $headers[] = 'Authorization: Bearer ' . session('access_token');

  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  $response = curl_exec($ch);
  return json_decode($response);
}

function get($key, $default=NULL) {
  return array_key_exists($key, $_GET) ? $_GET[$key] : $default;
}

function session($key, $default=NULL) {
  return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
}

?>


问:
What are resources to build parts of a Web Application in Rust?
I want to learn Rust and am coming from a web application background. My past experience is React, React Native, Node.js, Java (Springboot), and Angular.

My question is can a server or a user interface be built on Rust? I imagine it's possible today. Where can I go to for learning how?

答:
Yeah you can build both a web server and a web application in rust. If you don’t know any rust, I would get started with the Rust Book which you can find on rust’s website.

If you want to build a web application, the crate, Yew, is the best in my opinion. It does state it’s not production ready but fine for personal projects. Coming from rust, it should feel similar ( but obviously different because rust and JavaScript are a lot different ). It even has a JSX like implementation.

There are plenty of web server crates you can use. The fastest being Actix-web. Other crates for web servers include Rocket, warp, & tower. All have documentation and tutorials if you google for their github repo.


问:
How to resolve "unable to find package java.lang in classpath or bootclasspath" in Dr Java?
I am new to Java. I am taking a University beginners Java course. I'm running my first hello world code and am getting an error message. I have installed the latest Dr. Java stable version and have installed Java SE 12 JDK.

I have uninstalled and reinstalled Dr. Java several times and still getting error message. I have also recompiled it to and still the error message is there.

```<code>public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World");
    }
}
</code>```

I expected the code output to say, "Hello World" under the interactions pane but it isn't and instead there is an error message that says, "Current document is out of sync with the Interactions Pane and should be recompiled!".

Also, under the console pane I receive the following message:

Compiler is using classPath = '[C:\Users\Admin,
  C:\Users\Admin\Downloads\drjava-beta-20190813-220051.jar]';
  bootClassPath = 'null' Fatal Error: Unable to find package java.lang
  in classpath or bootclasspath

答:
Realizing that the OP solved his problem by version of JDK, I ran across this question after experiencing the same symptoms he describes.  With that, it seems possibly appropriate to post a solution for the symptoms even though the problem ended up not being quite "identical" to the OP's situation:

I had the same problem with compilation not working.  In my case, I am using a Linux system that has both OpenJDK and a manually installed Oracle JDK (extracted from a tarball obtained from java.com), along with some other JRE environments in various places.  I "installed" the DrJava Version : drjava-20190813-220051 jar file and ran it from the command-line.  I then clicked [ Manual Download ] when it asked about installing updates (drjava-beta-2019-220051).

DrJava reported that my compiler was JDK 8.0_222.  Note, I don't know where that compiler came from.  As far as I know, I didn't have that version installed. My OpenJDK was:

```<code>$ /bin/java -version
openjdk version "1.8.0_252"
OpenJDK Runtime Environment (build 1.8.0_252-b09)
OpenJDK 64-Bit Server VM (build 25.252-b09, mixed mode)
</code>```

I typed in a simple "Hello World" program, and every attempt to compile produced:

```<code>Compiler Output:
  "Compilation completed."
</code>```

This is a bug, because in fact compilation apparently did not complete.

Clicking Run produced:

```<code>Interactions
  Welcome to DrJava.  Working directory is /home/krb/Projects/Software/java
  Current document is out of sync with the Interactions Pane and should be recompiled!
  >
</code>```

Restarting DrJava, saving, clicking Reset, etc., would not clear the problem.

In any event, at some point I noticed the Console tab was full of messages like:

```<code>Console
  Compiler is using classPath = '[/home/krb/Projects/Software/java, /home/apps/drjava/drjava-beta-20190813-220051.jar]';  bootClassPath = 'null'
  Fatal Error: Unable to find package java.lang in classpath or bootclasspath
</code>```

At this point, I tried various things, but I focused on pointing DrJava to an Oracle Java JDK I had installed a few days ago.  Everything I did was in Edit | Preferences ... | Resource Locations, though I beat around in there a while.  All of the settings were "blank" before I started.  Anyway, I eventually had some success after I'd set:

```<code>Web Browser
 /usr/lib64/firefox/firefox
Web Browser Command

Tools.jar Location
  /home/raid/apps/oracle/jdk-1.8.0_251/jre/lib/tools.jar
Display All Compiler Version [ ]
Extra Classpath
  /home/raid/apps/oracle/jdk1.8.0_251/jre/lib
  /home/raid/apps/oracle/jdk1.8.0_251/lib
</code>```

NOTE:  Your PATHs will NOT be the same as mine!  You need to use the
  actual paths on your system.  In my case I searched for "rt.jar" and
  "tools.jar" that were obviously in folders related to an installed
  JDK.

At this point I decided to try to figure out the minimum required to get it working.  After a lot of fiddling around, I found it is sufficient just to set Preferences | Resource Locations | Tools.jar Location, but with with one MAJOR caveat.  You must BROWSE to the file using that dialog.  YOU CANNOT JUST PASTE IN THE PATH!  If you just paste in the path, it can look like it is set correctly, but the compiler will continue to not work.  This was how I got the oracle jdk compiler to work.

Next, I set about to see if I could get OpenJDK to work.  I searched my entire system for another tools.jar that belonged to OpenJDK, and did not find one.  Then I realized I did not have the DEVEL OpenJDK package installed (on Mageia Linux 7).

```<code>java-1.8.0-openjdk-headless-1.8.0.252-1.b09.1.mga7
java-1.8.0-openjdk-1.8.0.252-1.b09.1.mga7
</code>```

I installed:

```<code>java-1.8.0-openjdk-devel-1.8.0.252-1.b09.1.mga7
</code>```

Now, even after resetting defaults, DrJava no longer says it is using JDK 8.0_222, but rather JDK 8.0-openjdk-1.8.0.252-1.b09.1.mga7.x86_64-OpenJDK, and everything works fine with NO customization to preferences!

I don't know where the heck JDK 8.0_222 came from.  There's nothing on my system with that version.  I rather suppose it is some internal thing in DrJava.  I think the takeaways are:

If DrJava says its using JDK 8.0_222, it probably is not going to work!

Make sure you actually have a tools.jar installed if your system might split up the OpenJDK installation.

Point Tools.jar Location to an existing tools.jar file where the JDK you are using is installed, and making sure to browse to it (not just paste in a path).

I know what I saw was with Linux and a .jar install of DrJava, and this might not be what you have, but perhaps the information will be helpful in offering you things to look at and try.

Body:
I am new to Java. I am taking a University beginners Java course. I'm running my first hello world code and am getting an error message. I have installed the latest Dr. Java stable version and have installed Java SE 12 JDK.

I have uninstalled and reinstalled Dr. Java several times and still getting error message. I have also recompiled it to and still the error message is there.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World");
    }
}

I expected the code output to say, "Hello World" under the interactions pane but it isn't and instead there is an error message that says, "Current document is out of sync with the Interactions Pane and should be recompiled!".

Also, under the console pane I receive the following message:

Compiler is using classPath = '[C:\Users\Admin,
  C:\Users\Admin\Downloads\drjava-beta-20190813-220051.jar]';
  bootClassPath = 'null' Fatal Error: Unable to find package java.lang
  in classpath or bootclasspath

Body:
Realizing that the OP solved his problem by version of JDK, I ran across this question after experiencing the same symptoms he describes.  With that, it seems possibly appropriate to post a solution for the symptoms even though the problem ended up not being quite "identical" to the OP's situation:

I had the same problem with compilation not working.  In my case, I am using a Linux system that has both OpenJDK and a manually installed Oracle JDK (extracted from a tarball obtained from java.com), along with some other JRE environments in various places.  I "installed" the DrJava Version : drjava-20190813-220051 jar file and ran it from the command-line.  I then clicked [ Manual Download ] when it asked about installing updates (drjava-beta-2019-220051).

DrJava reported that my compiler was JDK 8.0_222.  Note, I don't know where that compiler came from.  As far as I know, I didn't have that version installed. My OpenJDK was:

$ /bin/java -version
openjdk version "1.8.0_252"
OpenJDK Runtime Environment (build 1.8.0_252-b09)
OpenJDK 64-Bit Server VM (build 25.252-b09, mixed mode)

I typed in a simple "Hello World" program, and every attempt to compile produced:

Compiler Output:
  "Compilation completed."

This is a bug, because in fact compilation apparently did not complete.

Clicking Run produced:

Interactions
  Welcome to DrJava.  Working directory is /home/krb/Projects/Software/java
  Current document is out of sync with the Interactions Pane and should be recompiled!
  >

Restarting DrJava, saving, clicking Reset, etc., would not clear the problem.

In any event, at some point I noticed the Console tab was full of messages like:

Console
  Compiler is using classPath = '[/home/krb/Projects/Software/java, /home/apps/drjava/drjava-beta-20190813-220051.jar]';  bootClassPath = 'null'
  Fatal Error: Unable to find package java.lang in classpath or bootclasspath

At this point, I tried various things, but I focused on pointing DrJava to an Oracle Java JDK I had installed a few days ago.  Everything I did was in Edit | Preferences ... | Resource Locations, though I beat around in there a while.  All of the settings were "blank" before I started.  Anyway, I eventually had some success after I'd set:

Web Browser
 /usr/lib64/firefox/firefox
Web Browser Command

Tools.jar Location
  /home/raid/apps/oracle/jdk-1.8.0_251/jre/lib/tools.jar
Display All Compiler Version [ ]
Extra Classpath
  /home/raid/apps/oracle/jdk1.8.0_251/jre/lib
  /home/raid/apps/oracle/jdk1.8.0_251/lib

NOTE:  Your PATHs will NOT be the same as mine!  You need to use the
  actual paths on your system.  In my case I searched for "rt.jar" and
  "tools.jar" that were obviously in folders related to an installed
  JDK.

At this point I decided to try to figure out the minimum required to get it working.  After a lot of fiddling around, I found it is sufficient just to set Preferences | Resource Locations | Tools.jar Location, but with with one MAJOR caveat.  You must BROWSE to the file using that dialog.  YOU CANNOT JUST PASTE IN THE PATH!  If you just paste in the path, it can look like it is set correctly, but the compiler will continue to not work.  This was how I got the oracle jdk compiler to work.

Next, I set about to see if I could get OpenJDK to work.  I searched my entire system for another tools.jar that belonged to OpenJDK, and did not find one.  Then I realized I did not have the DEVEL OpenJDK package installed (on Mageia Linux 7).

java-1.8.0-openjdk-headless-1.8.0.252-1.b09.1.mga7
java-1.8.0-openjdk-1.8.0.252-1.b09.1.mga7

I installed:

java-1.8.0-openjdk-devel-1.8.0.252-1.b09.1.mga7

Now, even after resetting defaults, DrJava no longer says it is using JDK 8.0_222, but rather JDK 8.0-openjdk-1.8.0.252-1.b09.1.mga7.x86_64-OpenJDK, and everything works fine with NO customization to preferences!

I don't know where the heck JDK 8.0_222 came from.  There's nothing on my system with that version.  I rather suppose it is some internal thing in DrJava.  I think the takeaways are:

If DrJava says its using JDK 8.0_222, it probably is not going to work!

Make sure you actually have a tools.jar installed if your system might split up the OpenJDK installation.

Point Tools.jar Location to an existing tools.jar file where the JDK you are using is installed, and making sure to browse to it (not just paste in a path).

I know what I saw was with Linux and a .jar install of DrJava, and this might not be what you have, but perhaps the information will be helpful in offering you things to look at and try.


问:
Throttle HTTP request in Java Servlet
In a java servlet, how can I throttle http requests coming from users based on the client's IP address?  I do not want to serve more than X requests per second coming from a particular source IP address where X is configurable and having practical values in [0.1; 10] range (from 1 request in 10 sec to 10 requests per sec).</p>

答: As @EJP said, using a Filter with a HashMap that stores the last access time by IP address key.  10 requests a second would translate to 100ms between calls, minimum.  Sending a server busy error code back and killing the request will quickly close the resources used by the connection.  There are prebuilt solutions for Apache if that's an option for you. </p>

Title: Throttle HTTP request in Java Servlet


问:
How to undo javascript function
I have a function like so which toggles my dropdown menu.

```<code><div class="module widget-handle mobile-toggle right visible-sm visible-xs">
  <a id="mobile-nav" href="#">
    <div class="container1" onclick="myFunction(this)">
      <div class="bar1"></div>
      <div class="bar2"></div>
      <div class="bar3"></div>.
    </div>
  </a>
</div>
<script>
  function myFunction(x) {
    x.classList.toggle('change');
    document.body.style.overflow ='hidden'
  }
</script>
</code>```

The last part of it

```<code>document.body.style.overflow = 'hidden'
</code>```

Keeps the page from overflowing at the top when the dropdown menu is open. The problem is that when I click on my menu bars, whilst the overflow disappears, clicking on the bars again reveals the page but locks it due to the overflow being hidden.

I'd like to undo

```<code>document.body.style.overflow = 'hidden'
</code>```

When the menu is closed and the closest I've got to understanding it is the function doBack. Can I somehow add doBack to my existing function?

Mobile page here

It's a WordPress site and the javascript above toggles the dropdown by pressing on the bars. In order to extend the dropdown, I made the class collapse bigger, like so.

```<code>@media (max-width: 768px) {
  .collapse {
    position: absolute;
    height: 775px;
    background-color: white;
    z-index: 99999 !important;
    top: 75px;
    left: -50px;
    line-height: 10px;
  }
}
</code>```

HTML:

```<code><div class="module-group right">
  <div class="module left">
    <div class="collapse navbar-collapse navbar-ex1-collapse">
      <ul id="menu" class="menu">
        <li id="menu-item-15050" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-15050 dropdown">
          <a title="Contact" href="url">Contact
            <ul role="menu" class="dropdow n-menu">
            </ul>
          </a>
        </li>
      </ul>
    </div>
  </div>
</div>

</code>```

答:
You can eliminate the style attribute by using:</p>

```<code>document.body.style.overflow = null
</code>```

Title: How to undo javascript function

Body:
I have a function like so which toggles my dropdown menu.

.

The last part of it

document.body.style.overflow = 'hidden'

Keeps the page from overflowing at the top when the dropdown menu is open. The problem is that when I click on my menu bars, whilst the overflow disappears, clicking on the bars again reveals the page but locks it due to the overflow being hidden.

I'd like to undo

document.body.style.overflow = 'hidden'

When the menu is closed and the closest I've got to understanding it is the function doBack. Can I somehow add doBack to my existing function?

Mobile page here

It's a WordPress site and the javascript above toggles the dropdown by pressing on the bars. In order to extend the dropdown, I made the class collapse bigger, like so.

@media (max-width: 768px) {
  .collapse {
    position: absolute;
    height: 775px;
    background-color: white;
    z-index: 99999 !important;
    top: 75px;
    left: -50px;
    line-height: 10px;
  }
}

HTML:

          Contact

Body:
You can eliminate the style attribute by using:

document.body.style.overflow = null


问:
Vuex mapState returns object not array?
I want to loop over an array of objects using v-for. However my state returns an object containing an array of Objects:

```<code>{ "todos": [ { "id": "x", "description": "y" }, { "id": "a", "description": "b" } ] }
</code>```

which causes v-for not to work. If I use a getter instead it returns my array of objects like it's supposed to:

```<code>[ { "id": "x", "description": "y" }, { "id": "a", "description": "b" } ]
</code>```

is this normal behaviour?

using mapState:

```<code><template>
    <div class="content-center">
       {{todos}}
    </div>
</template>
....
import {mapActions, mapGetters, mapState} from 'vuex';

  export default {
        ....
        computed: mapState(['todos'])
    }
</code>```

using getter:

```<code><template>
    <div class="content-center">
       {{getTodos}}
    </div>
</template>
....
import {mapActions, mapGetters, mapState} from 'vuex';

 export default {
        ....
        computed: mapGetters(['getTodos'])
    }
</code>```

I also wanna add that i'm using modules, in case that changes anything about calling the mapState

vuex:

```<code>const state = {
    todos: []
};

const getters = {

    getTodos: state => state.todos

};

const actions = {
    loadTodos({commit}) {
        axios.get('/api/todos', {
        }).then(response => {
            commit('setTodos', response.data);
        }).catch(error => {
            console.error(error);
        })
    }
};

const mutations = {
    setTodos: (state, response) => {
        state.todos = response;
    }
};
</code>```

答:
According to the Vuex documentation, the mapState helper returns an object by default.

The reason why your getter returns an array instead of an object is that a getter must always be a function. In your case, the single line arrow function state => state.todos accesses the object and it then implicitly returns the state within the object.

Instead of passing a string array into the helper like mapState(['todos']), you can open it up to perform additional operations (i.e. to access the object) as shown in the docs:

```<code>computed: mapState({
        todos: state => state.todos
})
</code>```

Notice that you are basically accessing the state the same way the getter was... Only this time you're doing it within the component under the computed section.

Note: If you have nested modules, you might want to bind your namespaces as shown in the docs here.

Additionally, if you don't need to make use of multiple store state properties or getters, then you could just access that single todos property using the this.$store shortcut:

```<code>computed: {
    todos() {
      return this.$store.state.{module_filename}.todos
    }
}
</code>```

Hope that helps.

Title: Vuex mapState returns object not array?

Body:
I want to loop over an array of objects using v-for. However my state returns an object containing an array of Objects:

{ "todos": [ { "id": "x", "description": "y" }, { "id": "a", "description": "b" } ] }

which causes v-for not to work. If I use a getter instead it returns my array of objects like it's supposed to:

[ { "id": "x", "description": "y" }, { "id": "a", "description": "b" } ]

is this normal behaviour?

using mapState:

<template>

       {{todos}}

</template>
....
import {mapActions, mapGetters, mapState} from 'vuex';

  export default {
        ....
        computed: mapState(['todos'])
    }

using getter:

<template>

       {{getTodos}}

</template>
....
import {mapActions, mapGetters, mapState} from 'vuex';

 export default {
        ....
        computed: mapGetters(['getTodos'])
    }

I also wanna add that i'm using modules, in case that changes anything about calling the mapState

vuex:

const state = {
    todos: []
};

const getters = {

    getTodos: state => state.todos

};

const actions = {
    loadTodos({commit}) {
        axios.get('/api/todos', {
        }).then(response => {
            commit('setTodos', response.data);
        }).catch(error => {
            console.error(error);
        })
    }
};

const mutations = {
    setTodos: (state, response) => {
        state.todos = response;
    }
};

Body:
According to the Vuex documentation, the mapState helper returns an object by default.

The reason why your getter returns an array instead of an object is that a getter must always be a function. In your case, the single line arrow function state => state.todos accesses the object and it then implicitly returns the state within the object.

Instead of passing a string array into the helper like mapState(['todos']), you can open it up to perform additional operations (i.e. to access the object) as shown in the docs:

computed: mapState({
        todos: state => state.todos
})

Notice that you are basically accessing the state the same way the getter was... Only this time you're doing it within the component under the computed section.

Note: If you have nested modules, you might want to bind your namespaces as shown in the docs here.

Additionally, if you don't need to make use of multiple store state properties or getters, then you could just access that single todos property using the this.$store shortcut:

computed: {
    todos() {
      return this.$store.state.{module_filename}.todos
    }
}

Hope that helps.


问:
I try to make left side menu Collapse as accordion in angular but Not Work?
I work on angular 7 app I try to make left side menu accordion Expandable and Collapse but it does not work.

For main menu I display Main Reports Category as:

```<code><ul *ngFor="let rep of allReportCategories"  style="margin-top:2px;"  class="page-sidebar-menu" data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200">
<span><button class="accordion">{{rep.reportCategory}}</button></span>
</code>```

For display sub category reports I depend on CategoryID to join between category and sub Category:

```<code>*ngFor="let subrep of reportsubCategory"
<div *ngIf="subrep.reportCategoryID === rep.reportCategoryID" class="wrapper">
 <span class="sideNav nav navbar">{{subrep.reportName}}</span>
</code>```

CSS Accordion :

```<code>.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}
</code>```

I work on Stackbliz already have data and Show Main Category and Sub Category but the issue i can't solve Issue of accordion.

https://stackblitz.com/edit/create-1arrvm?file=app%2Fapp.component.html

Updated post
my bussiness logic for button

I need to pass main category to function getreportbycategory but i dont know

```<code>     this._displayreport.GetreportByCategoryId(this.reportid).subscribe((data: any[]) => {
            this.reportsubCategory = data;
          });
 toggleAccordian(event, index) {
      var element = event.target;
      element.classList.toggle("active");
     this._displayreport.GetreportByCategoryId(index);
  }
</code>```

also How to display them as accordion when open page .

can you show me code if possible for that

答:
add a 'collapse' field in your allreportcategories data at ngonInit, pass down collapse field into every child, set up ngClass for 'display: block'/'display: none' switch based on the collapse field you passed down, set up onclick to toggle the true/false of collapse field</p>

```<code>import { Component, OnInit } from '@angular/core';
import { DisplayreportService } from './displayreport.service';
import { HttpClient } from '@angular/common/http';
import { Router , ActivatedRoute} from '@angular/router';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  expanded = new Array(3).fill(false);
datalis:string;
allReportCategories:any[];
reportsubCategory:any[];
reportByCategoryId:any[];
allReportsubCategory:any[];
reportCategoryIdparam:string;
  constructor(public http: HttpClient, private _router: Router, private _displayreport: DisplayreportService) { }

  ngOnInit() {

      // this._displayreport.getallReportCategories().subscribe((data: any[]) => {
       // this.allReportCategories = data;

    //  });
this.allReportCategories=this._displayreport.getallReportCategories().map((e) => {
  e.collapse = false;
  return e
});

console.log(this.allReportCategories)

       //this._displayreport.GetreportByCategoryId(this.reportid)//.subscribe((data: any[]) => {
       // this.reportByCategoryId = data;

      //});
    //  this.reportid="3";
//this.reportByCategoryId=this._displayreport.GetreportByCategoryId////(this.reportid);

  this.reportByCategoryId = this._displayreport.GetreportByCategoryId("3");
  console.log("data by category id" + this.reportByCategoryId);
  this.reportsubCategory=this._displayreport.getallReportsubCategory();

  }
   toggleAccordian(event, index) {
      var element = event.target;
      console.log("element is" +JSON.stringify(index)  )
      console.log("element is" +JSON.stringify(element)  )
      this.allReportCategories[index].collapse = !this.allReportCategories[index].collapse
    //   element.classList.toggle("active");
    //   if(this.allReportCategories[index].isActive) {
    //    this.allReportCategories[index].isActive = false;
    //   } else {
    //     this.allReportCategories[index].isActive = true;
    //   }
    //  this._displayreport.GetreportByCategoryId(index);
    //  console.log(this._displayreport.GetreportByCategoryId(index))
  }

}
</code>```

```<code><div class="row" style="display: block;float: left;margin-left:10px; margin-top: 2px;">
    <div class="page-sidebar navbar-collapse collapse">
    <nav class="colsm12" id="">
            <ul *ngFor="let rep of allReportCategories;let i = index;"  style="margin-top:2px;" class="page-sidebar-menu" data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200">

                    <li class="active open">
                        <a  id="menu" >

                            <i class="rep.menuIcon"></i>
                            <span ><button class="accordion" (click)="toggleAccordian($event, i)">{{rep.reportCategory}}
                            </button></span>

                        </a>
                        <ul [ngStyle]="{'display':rep.collapse ? 'block' : 'none' }" *ngFor="let subrep of reportsubCategory"  style="display:block;" id="submenu" style="padding-left:7px;" hide="!rep.isActive">

                            <div *ngIf="subrep.reportCategoryID === rep.reportCategoryID" class="wrapper" >

                                <a href="/reportdetails?id={{subrep.reportID}}">

                                            <span class="sideNav nav navbar">{{subrep.reportName}}</span>

                                        </a>

                            </div>

                        </ul>

            </ul>
        </nav>
        </div>
    </div>
</code>```

Body:
I work on angular 7 app I try to make left side menu accordion Expandable and Collapse but it does not work.

For main menu I display Main Reports Category as:

<button class="accordion">{{rep.reportCategory}}</button>

For display sub category reports I depend on CategoryID to join between category and sub Category:

*ngFor="let subrep of reportsubCategory"

 {{subrep.reportName}}

CSS Accordion :

.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

I work on Stackbliz already have data and Show Main Category and Sub Category but the issue i can't solve Issue of accordion.

https://stackblitz.com/edit/create-1arrvm?file=app%2Fapp.component.html

Updated post
my bussiness logic for button

I need to pass main category to function getreportbycategory but i dont know

     this._displayreport.GetreportByCategoryId(this.reportid).subscribe((data: any[]) => {
            this.reportsubCategory = data;
          });
 toggleAccordian(event, index) {
      var element = event.target;
      element.classList.toggle("active");
     this._displayreport.GetreportByCategoryId(index);
  }

also How to display them as accordion when open page .

can you show me code if possible for that

Body:
add a 'collapse' field in your allreportcategories data at ngonInit, pass down collapse field into every child, set up ngClass for 'display: block'/'display: none' switch based on the collapse field you passed down, set up onclick to toggle the true/false of collapse field

import { Component, OnInit } from '@angular/core';
import { DisplayreportService } from './displayreport.service';
import { HttpClient } from '@angular/common/http';
import { Router , ActivatedRoute} from '@angular/router';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  expanded = new Array(3).fill(false);
datalis:string;
allReportCategories:any[];
reportsubCategory:any[];
reportByCategoryId:any[];
allReportsubCategory:any[];
reportCategoryIdparam:string;
  constructor(public http: HttpClient, private _router: Router, private _displayreport: DisplayreportService) { }

  ngOnInit() {

      // this._displayreport.getallReportCategories().subscribe((data: any[]) => {
       // this.allReportCategories = data;

    //  });
this.allReportCategories=this._displayreport.getallReportCategories().map((e) => {
  e.collapse = false;
  return e
});

console.log(this.allReportCategories)

       //this._displayreport.GetreportByCategoryId(this.reportid)//.subscribe((data: any[]) => {
       // this.reportByCategoryId = data;

      //});
    //  this.reportid="3";
//this.reportByCategoryId=this._displayreport.GetreportByCategoryId////(this.reportid);

  this.reportByCategoryId = this._displayreport.GetreportByCategoryId("3");
  console.log("data by category id" + this.reportByCategoryId);
  this.reportsubCategory=this._displayreport.getallReportsubCategory();

  }
   toggleAccordian(event, index) {
      var element = event.target;
      console.log("element is" +JSON.stringify(index)  )
      console.log("element is" +JSON.stringify(element)  )
      this.allReportCategories[index].collapse = !this.allReportCategories[index].collapse
    //   element.classList.toggle("active");
    //   if(this.allReportCategories[index].isActive) {
    //    this.allReportCategories[index].isActive = false;
    //   } else {
    //     this.allReportCategories[index].isActive = true;
    //   }
    //  this._displayreport.GetreportByCategoryId(index);
    //  console.log(this._displayreport.GetreportByCategoryId(index))
  }

}

<div class="row" style="display: block;float: left;margin-left:10px; margin-top: 2px;">
    <div class="page-sidebar navbar-collapse collapse">
    <nav class="colsm12" id="">
            <ul *ngFor="let rep of allReportCategories;let i = index;"  style="margin-top:2px;" class="page-sidebar-menu" data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200">

                    <li class="active open">
                        <a  id="menu" >

                            <i class="rep.menuIcon"></i>
                            <span ><button class="accordion" (click)="toggleAccordian($event, i)">{{rep.reportCategory}}
                            </button></span>

                        </a>
                        <ul [ngStyle]="{'display':rep.collapse ? 'block' : 'none' }" *ngFor="let subrep of reportsubCategory"  style="display:block;" id="submenu" style="padding-left:7px;" hide="!rep.isActive">

                            <div *ngIf="subrep.reportCategoryID === rep.reportCategoryID" class="wrapper" >

                                <a href="/reportdetails?id={{subrep.reportID}}">

                                            <span class="sideNav nav navbar">{{subrep.reportName}}</span>

                                        </a>

                            </div>

                        </ul>

            </ul>
        </nav>
        </div>
    </div>


问:
Global exception handling in Xamarin.Forms
Is there a way to handle exceptions at a global level in a Xamarin.Forms app?

Currently my app has a login page which has a button "Throw Exception" button bound to the "Exception_Clicked" method.

```<code>private void Exception_Clicked(object sender, EventArgs e)
{
        throw new Exception("ERROR MESSAGE");
}
</code>```

What I am trying to accomplish is for the app to manage the exception that the method throws without explicitly putting a try-catch in each method.

Currently I know that global exception handling can be handled in regular web and desktop apps with code like below

```<code>public static class ExceptionHandlerHelper
{
    public static void Register()
    {
        AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
        {
            Console.WriteLine(eventArgs.Exception.ToString());
            Logging.LogException(eventArgs.Exception, string.Empty);
        };
    }
}
</code>```

Is there a way to do this in the xamarin.forms, How it would work?

EDIT 1 - while the answer presented in Global Exception Handling in Xamarin Cross platform is very close it unfortunately does not stop the application from closing and only presents a log of where the exception happened. The exception handling that I am trying to implement must catch the exception as it happens and allow the app to continue normally

答:
I already had this doubt and looked for a similar solution. But, reading about it, I found that it is not good exception handling practice. The best I found and adapted to my needs is the SafelyExecute design pattern.

Like this:

>

```<code>public async Task<SafelyExecuteResult> SafelyExecute(Action method, string genericErrorMessage = null)
{
    try
    {
        method.Invoke();
        return new SafelyExecuteResult { Successful = true };
    }
    catch (HttpRequestException ex)
    {
        await PageDialogService.DisplayAlertAsync(AppResources.Error, AppResources.InternetConnectionRequired, AppResources.Ok);
        return new SafelyExecuteResult { Successful = false, raisedException = ex };
    }
    catch (Exception ex)
    {
        await PageDialogService.DisplayAlertAsync(AppResources.Error, genericErrorMessage ?? ex.Message, AppResources.Ok);
        return new SafelyExecuteResult { Successful = false, raisedException = ex };
    }
    //You can add more exception here
}
</code>```

And the called:

>

```<code>await SafelyExecute(() => { /*your code here*/ });
</code>```

>

```<code>public class SafelyExecuteResult
    {
        public Exception raisedException;
        public bool Successful;
    }
</code>```

Unfortunately you will need to use this method where you need to track exceptions.

Body:
Is there a way to handle exceptions at a global level in a Xamarin.Forms app?

Currently my app has a login page which has a button "Throw Exception" button bound to the "Exception_Clicked" method.

private void Exception_Clicked(object sender, EventArgs e)
{
        throw new Exception("ERROR MESSAGE");
}

What I am trying to accomplish is for the app to manage the exception that the method throws without explicitly putting a try-catch in each method.

Currently I know that global exception handling can be handled in regular web and desktop apps with code like below

public static class ExceptionHandlerHelper
{
    public static void Register()
    {
        AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
        {
            Console.WriteLine(eventArgs.Exception.ToString());
            Logging.LogException(eventArgs.Exception, string.Empty);
        };
    }
}

Is there a way to do this in the xamarin.forms, How it would work?

EDIT 1 - while the answer presented in Global Exception Handling in Xamarin Cross platform is very close it unfortunately does not stop the application from closing and only presents a log of where the exception happened. The exception handling that I am trying to implement must catch the exception as it happens and allow the app to continue normally

Body:
I already had this doubt and looked for a similar solution. But, reading about it, I found that it is not good exception handling practice. The best I found and adapted to my needs is the SafelyExecute design pattern.

Like this:

>

public async Task<SafelyExecuteResult> SafelyExecute(Action method, string genericErrorMessage = null)
{
    try
    {
        method.Invoke();
        return new SafelyExecuteResult { Successful = true };
    }
    catch (HttpRequestException ex)
    {
        await PageDialogService.DisplayAlertAsync(AppResources.Error, AppResources.InternetConnectionRequired, AppResources.Ok);
        return new SafelyExecuteResult { Successful = false, raisedException = ex };
    }
    catch (Exception ex)
    {
        await PageDialogService.DisplayAlertAsync(AppResources.Error, genericErrorMessage ?? ex.Message, AppResources.Ok);
        return new SafelyExecuteResult { Successful = false, raisedException = ex };
    }
    //You can add more exception here
}

And the called:

>

await SafelyExecute(() => { /*your code here*/ });

>

public class SafelyExecuteResult
    {
        public Exception raisedException;
        public bool Successful;
    }

Unfortunately you will need to use this method where you need to track exceptions.


问:
How to reformat date from 26-MAY-20 03.43.48.861000000 to 'yyyy-mm-dd hh:mm:ss'?
How would I convert '26-MAY-20 03.43.48.861000000' into 'yyyy-mm-dd hh:mm:ss' using datetime in Python ?

答:
So big picture, the goal is to create a date object out of the first string, and then format the date into the second string.

datetime.strptime will be your best friend here, along with datetime.strftime.

By referencing the library's format codes, we can put together a format of the first string.

from datetime import datetime

# I don't know why your datetime doesn't conform to the 1989 C standard but I'm just truncating it
may_26 = datetime.strptime('26-MAY-20 03.43.48.861000000'[:-3], "%d-%b-%y %H.%M.%S.%f")

output = datetime.strftime(may_26, "%Y-%m-%d %H:%M:%S")
```

I am making a few assumptions for you in the formatting, like assuming your datetime is on 24hr format, and stuff, so definitely check for yourself.

Body:
So big picture, the goal is to create a date object out of the first string, and then format the date into the second string.

datetime.strptime will be your best friend here, along with datetime.strftime.

By referencing the library's format codes, we can put together a format of the first string.

from datetime import datetime

# I don't know why your datetime doesn't conform to the 1989 C standard but I'm just truncating it
may_26 = datetime.strptime('26-MAY-20 03.43.48.861000000'[:-3], "%d-%b-%y %H.%M.%S.%f")

output = datetime.strftime(may_26, "%Y-%m-%d %H:%M:%S")

I am making a few assumptions for you in the formatting, like assuming your datetime is on 24hr format, and stuff, so definitely check for yourself.


问:
React Hook to find user
I am trying to use the React useState Hook for an online project. What I want to happen is, when I type the users name in the search box, It will find the users card on the browser. I am able to log the user to the console, but I am stuck on how to get it to render on screen. Tried so many ways and just not getting it.

console output

App.js

```<code>import React, { useState } from 'react';
import CardList from './CardList';
import {robots} from './robots';
import SearchBox from './SearchBox';

function App() {

  let [searchInput] = useState('');

  function onSearchChange(e) {

    searchInput = e.target.value;

    const filteredRobots = robots.filter(function(robot){
      return robot.name.toLowerCase().includes(searchInput.toLowerCase());
    });

    console.log(filteredRobots);

  }

  return (
    <div className='tc'>
      <h1>RoboFriends</h1>
      <SearchBox searchChange={onSearchChange} />
      <CardList id={robots.id} name={robots.name} email={robots.email}/>
    </div>
  );
}

export default App;
</code>```

CardList.js

```<code>import React from 'react';
import Card from './Card';
import {robots} from './robots';

function CardList(props) {
  return (
    <div>
    {
      robots.map(function(user) {
        return <Card key={user.id} id={user.id} name={user.name} email={user.email} />
      })
    };
  </div> )
}

export default CardList;
</code>```

Card.js

```<code>import React from 'react';
import 'tachyons';

function Card(props) {
  return (
    <div className='bg-light-green dib br3 pa3 ma2 grow shadow-5'>
      <img src={`https://robohash.org/${props.id}`} alt="Robot" />
      <h2>{props.name}</h2>
      <p>{props.email}</p>
    </div>
  );
}

export default Card;
</code>```

答:
React only re-render when you set a state to a new value.

Check the code below:

import React, { useState } from 'react';
import CardList from './CardList';
import {robots} from './robots';
import SearchBox from './SearchBox';

function App() {

  let [searchInput, setSeachInput] = useState('');

  function onSearchChange(e) {

    // set state here to re-render
    setSeachInput(e.target.value);
  }

  // use might want to use useMemo to improve this, I just want to make it simple now
   const filteredRobots = robots.filter(function(robot){
      return robot.name.toLowerCase().includes(searchInput.toLowerCase());
    });

    console.log(filteredRobots);

  return (

RoboFriends

      <SearchBox searchChange={onSearchChange} />
      {/* using filteredRobots herer*/}
      <CardList id={filteredRobots.id} name={filteredRobots.name} email={filteredRobots.email}/>

  );
}

export default App;```

Title: React Hook to find user

Body:
I am trying to use the React useState Hook for an online project. What I want to happen is, when I type the users name in the search box, It will find the users card on the browser. I am able to log the user to the console, but I am stuck on how to get it to render on screen. Tried so many ways and just not getting it.

console output

App.js

import React, { useState } from 'react';
import CardList from './CardList';
import {robots} from './robots';
import SearchBox from './SearchBox';

function App() {

  let [searchInput] = useState('');

  function onSearchChange(e) {

    searchInput = e.target.value;

    const filteredRobots = robots.filter(function(robot){
      return robot.name.toLowerCase().includes(searchInput.toLowerCase());
    });

    console.log(filteredRobots);

  }

  return (

RoboFriends

      <SearchBox searchChange={onSearchChange} />
      <CardList id={robots.id} name={robots.name} email={robots.email}/>

  );
}

export default App;

CardList.js

import React from 'react';
import Card from './Card';
import {robots} from './robots';

function CardList(props) {
  return (

    {
      robots.map(function(user) {
        return <Card key={user.id} id={user.id} name={user.name} email={user.email} />
      })
    };

 )
}

export default CardList;

Card.js

import React from 'react';
import 'tachyons';

function Card(props) {
  return (

      <img src={`https://robohash.org/${props.id}`} alt="Robot" />

{props.name}

{props.email}

  );
}

export default Card;

Body:
React only re-render when you set a state to a new value.

Check the code below:

import React, { useState } from 'react';
import CardList from './CardList';
import {robots} from './robots';
import SearchBox from './SearchBox';

function App() {

  let [searchInput, setSeachInput] = useState('');

  function onSearchChange(e) {

    // set state here to re-render
    setSeachInput(e.target.value);
  }

  // use might want to use useMemo to improve this, I just want to make it simple now
   const filteredRobots = robots.filter(function(robot){
      return robot.name.toLowerCase().includes(searchInput.toLowerCase());
    });

    console.log(filteredRobots);

  return (
    <div className='tc'>
      <h1>RoboFriends</h1>
      <SearchBox searchChange={onSearchChange} />
      {/* using filteredRobots herer*/}
      <CardList id={filteredRobots.id} name={filteredRobots.name} email={filteredRobots.email}/>
    </div>
  );
}

export default App;


答:
use shift

```<code>import numpy as np
df['2017 (Bi-monthly)'] = np.where(df['Mês'] > 1, df['2017'] + df['2017'].shift(1), '')
df['2018 (Bi-monthly)'] = np.where(df['Mês'] > 1, df['2018'] + df['2018'].shift(1), '')
df['2019 (Bi-monthly)'] = np.where(df['Mês'] > 1, df['2019'] + df['2019'].shift(1), '')
</code>```

You won't be able to calculate the first month of 2017, but you can calculate the first month of 2018 and 2019. To do that, try the below; admittedly, I couldn't confirm that the code below works as I couldn't test since you pasted an image. If you could copy and paste the actual data instead of an image, I could fix the below code if it doesn't work:

```<code>df.loc[df['Mês'] == 1, '2018 (Bi-monthly)'] = df.loc[df['Mês'] == 12]['2017'] + df.loc[df['Mês'] == 1]['2018']
df.loc[df['Mês'] == 1, '2019 (Bi-monthly)'] = df.loc[df['Mês'] == 12]['2018'] + df.loc[df['Mês'] == 1]['2019']
</code>```

Title: How to sum a inverval of rows in Pandas Series?

Body:
I have a pandas data frame, and I need to sum the bimonthly values for each City ('Municipio' Column).

Like in 'Acrelândia' on the first bimester in 2019, it should give the value 1.762.356,65.
I don't have any idea to do this efficiently. Someone can help me?

The DataFrame looks like this:

        Município   UF   Mês  ...       2017       2018       2019
0      Acrelândia   AC   1.0  ...  748780.61  740381.02  861747.15
1      Acrelândia   AC   2.0  ...  850714.86  880849.33  900609.50
2      Acrelândia   AC   3.0  ...  617978.20  642454.98  711703.16
3      Acrelândia   AC   4.0  ...  685174.68  661647.05  718405.94
4      Acrelândia   AC   5.0  ...  772153.06  783355.47  825357.96
...           ...  ...   ...  ...        ...        ...        ...
66824     Xambioá   TO   9.0  ...  440157.71  447923.66  522026.46
66825     Xambioá   TO  10.0  ...  478002.52  445073.83  564305.39
66826     Xambioá   TO  11.0  ...  473037.80  431933.80  633013.36
66827     Xambioá   TO  12.0  ...  568319.87  762546.79       0.00
66828         NaN  NaN   NaN  ...        NaN        NaN        NaN

[66829 rows x 16 columns]

Body:
use shift

import numpy as np
df['2017 (Bi-monthly)'] = np.where(df['Mês'] > 1, df['2017'] + df['2017'].shift(1), '')
df['2018 (Bi-monthly)'] = np.where(df['Mês'] > 1, df['2018'] + df['2018'].shift(1), '')
df['2019 (Bi-monthly)'] = np.where(df['Mês'] > 1, df['2019'] + df['2019'].shift(1), '')

You won't be able to calculate the first month of 2017, but you can calculate the first month of 2018 and 2019. To do that, try the below; admittedly, I couldn't confirm that the code below works as I couldn't test since you pasted an image. If you could copy and paste the actual data instead of an image, I could fix the below code if it doesn't work:

df.loc[df['Mês'] == 1, '2018 (Bi-monthly)'] = df.loc[df['Mês'] == 12]['2017'] + df.loc[df['Mês'] == 1]['2018']
df.loc[df['Mês'] == 1, '2019 (Bi-monthly)'] = df.loc[df['Mês'] == 12]['2018'] + df.loc[df['Mês'] == 1]['2019']


问:
Getting this error with the coordinates of the cursor using MouseClicked."The method getX() & getY() is undefined for the type MouseEvent"
Simple Addition subtraction application:

I checked for its solution and I found solutions regarding getX() but there were not related to MouseClicked!

I think its some type casting issue but I'm unable to resolve it and I verified all the imports and also even matched the code with the available online ones!

imports:

```<code>    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import javax.swing.JTextField;
    import com.sun.glass.events.MouseEvent;
</code>```

Main Class:

```<code>    public class Calcx {
        public static void main(String[] args) {
            Initialize o=new Initialize();

        }
    }
</code>```

called class:

```<code>    class Initialize extends JFrame implements ActionListener {
            JFrame frame;
            JTextField t1;
            JButton b1,b2;
            JTextField t2;
            JLabel l,l1;
            JPopupMenu p;
            JMenuItem i,j;
</code>```

Constructor:

```<code>                public Initialize() {
                    setTitle("CalcX");
                    setLayout(new FlowLayout());
                    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    l=new JLabel("CalcX");
                    t1=new JTextField(5);
                    t2=new JTextField(5);
                    b1=new JButton("ADD");
                    b2=new JButton("SUBTRACT");
                    b2.addActionListener(this);
                    l1=new JLabel();
                    b1.addActionListener(this);
                    p=new JPopupMenu("Edit");
                    i= new JMenuItem("cut");
                    j= new JMenuItem("copy");
                    add(p);
                    p.add(i);
                    p.add(j);
                    add(l);
                    add(t1);
                    add(t2);
                    add(b1);
                    add(b2);
                    pack();
                    setVisible(true);

Error while using mouseClicked:

                    addMouseListener(new MouseAdapter()
                    {
                    public void mouseClicked(MouseEvent a)
                    {
                         int x=a.getX();    *Error*
                        int y=a.getY();     *Error*
                    p.show(frame,x,y);
                    }
                    });
                }

    }
</code>```

答:
```<code>import com.sun.glass.events.MouseEvent;
</code>```

That is not the standard MouseEvent class used with the JDK.

You need to use:

```<code>import java.awt.event.MouseEvent;
</code>```

Body:
Simple Addition subtraction application:

I checked for its solution and I found solutions regarding getX() but there were not related to MouseClicked!

I think its some type casting issue but I'm unable to resolve it and I verified all the imports and also even matched the code with the available online ones!

imports:

    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import javax.swing.JTextField;
    import com.sun.glass.events.MouseEvent;

Main Class:

    public class Calcx {
        public static void main(String[] args) {
            Initialize o=new Initialize();

        }
    }

called class:

    class Initialize extends JFrame implements ActionListener {
            JFrame frame;
            JTextField t1;
            JButton b1,b2;
            JTextField t2;
            JLabel l,l1;
            JPopupMenu p;
            JMenuItem i,j;

Constructor:

                public Initialize() {
                    setTitle("CalcX");
                    setLayout(new FlowLayout());
                    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    l=new JLabel("CalcX");
                    t1=new JTextField(5);
                    t2=new JTextField(5);
                    b1=new JButton("ADD");
                    b2=new JButton("SUBTRACT");
                    b2.addActionListener(this);
                    l1=new JLabel();
                    b1.addActionListener(this);
                    p=new JPopupMenu("Edit");
                    i= new JMenuItem("cut");
                    j= new JMenuItem("copy");
                    add(p);
                    p.add(i);
                    p.add(j);
                    add(l);
                    add(t1);
                    add(t2);
                    add(b1);
                    add(b2);
                    pack();
                    setVisible(true);

Error while using mouseClicked:

                    addMouseListener(new MouseAdapter()
                    {
                    public void mouseClicked(MouseEvent a)
                    {
                         int x=a.getX();    *Error*
                        int y=a.getY();     *Error*
                    p.show(frame,x,y);
                    }
                    });
                }

    }

Body:
import com.sun.glass.events.MouseEvent;

That is not the standard MouseEvent class used with the JDK.

You need to use:

import java.awt.event.MouseEvent;


问:
Makefile variable value not available during ifeq
I have the following Makefile

```<code>SHELL=/bin/bash
.SHELLFLAGS=-O extglob -o errexit -o pipefail -o nounset -c

.PHONY: testing

define getFileContents
$(shell cat ./test.txt)
endef

TEST_STATIC=dummy

deploy:
    $(eval TEST=$(getFileContents))
    @echo "$(TEST)"
ifeq ($(TEST),dummy)
    @echo "$(TEST) is FAILED"
else
    @echo "$(TEST) is PASS"
endif
ifneq (,$(findstring dummy,$(TEST)))
    @echo "$(TEST) is FAILED"
else
    @echo "$(TEST) is PASS"
endif

ifeq ($(TEST_STATIC),dummy)
    @echo "$(TEST) is FAILED"
else
    @echo "$(TEST) is PASS"
endif
ifneq (,$(findstring dummy,$(TEST_STATIC)))
    @echo "$(TEST) is FAILED"
else
    @echo "$(TEST) is PASS"
endif
</code>```

No matter what value I put in ./test.txt, I always go into PASS in both the ifeq & the findstring conditions but the variable's values show up properly in the echo statements. So the value is not available during the evaluation of ifeq

However, the if-else behaves properly for the TEST_STATIC variable.

Any help would be appreciated. Thanks.

答:
ifeq is parsed while the makefile is read in.  Even if it looks like it's part of a recipe, it isn't.  You can tell that it isn't, because it isn't indented with a TAB character.  Anything not indented by TAB, is part of the makefile not part of the recipe, and is parsed when the makefile is read in, not when the rule is run.

So by the time your rule is running and it gets to your eval, all the ifeq statements have long been expanded and dealt with.

In general, it's virtually never a good idea to use eval inside a recipe.  It will almost never do what you're hoping for.

If you need to test some value inside a recipe then you have to write shell code to do it, not makefile code, and indent the shell code with a TAB so it's passed to the shell.

Body:
I have the following Makefile

SHELL=/bin/bash
.SHELLFLAGS=-O extglob -o errexit -o pipefail -o nounset -c

.PHONY: testing

define getFileContents
$(shell cat ./test.txt)
endef

TEST_STATIC=dummy

deploy:
    $(eval TEST=$(getFileContents))
    @echo "$(TEST)"
ifeq ($(TEST),dummy)
    @echo "$(TEST) is FAILED"
else
    @echo "$(TEST) is PASS"
endif
ifneq (,$(findstring dummy,$(TEST)))
    @echo "$(TEST) is FAILED"
else
    @echo "$(TEST) is PASS"
endif

ifeq ($(TEST_STATIC),dummy)
    @echo "$(TEST) is FAILED"
else
    @echo "$(TEST) is PASS"
endif
ifneq (,$(findstring dummy,$(TEST_STATIC)))
    @echo "$(TEST) is FAILED"
else
    @echo "$(TEST) is PASS"
endif

No matter what value I put in ./test.txt, I always go into PASS in both the ifeq & the findstring conditions but the variable's values show up properly in the echo statements. So the value is not available during the evaluation of ifeq

However, the if-else behaves properly for the TEST_STATIC variable.

Any help would be appreciated. Thanks.