问:
How to fetch data and make a route with the same endpoint React
I have an endpoint from where I retrieve data,it is /community.

My react app use 3001 port but the node server where is the /community endpoint use 3000 port,the problem is that when I'm trying to route to localhost:3001/community to display a component,it gives me the JSON data from the server,but I need to display the component,could you help me to identify and fix the problem please?

setupProxy.js

```<code>const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
  app.use(
    createProxyMiddleware('/subscribe', {
      target: 'http://localhost:3000',
      changeOrigin: true,
      headers: {
        Connection: "keep-alive"
      }
    })
  );
  app.use(
    createProxyMiddleware('/unsubscribe', {
      target: 'http://localhost:3000',
      changeOrigin: true,
      headers: {
        Connection: "keep-alive"
      }
    })
  );
  app.use(
    createProxyMiddleware('/community', {
      target: 'http://localhost:3000',
      changeOrigin: true,
      headers: {
        Connection: "keep-alive"
      }
    })
  );
}
</code>```

App.js

```<code>import './App.css';
// import JoinUsSection from './components/JoinUsSection';
// import BigCommunitySection from './components/BigCommunitySection';
import { Provider } from 'react-redux';
import { store, persistor } from './store';
import { PersistGate } from 'redux-persist/integration/react'
import { fetchUsers } from './asyncActions/users';
import {Routes,Route} from 'react-router-dom'
import Main from './pages/Main'
import Community from'./pages/Community'

store.dispatch(fetchUsers())

function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <Routes>

        {/* <main id='app-container'>
          <BigCommunitySection />
          <JoinUsSection />
        </main> */}

       <Route path="/" element={<Main/>}/>
<Route path="/community" element={<Community/>}/>
        </Routes>
      </PersistGate>
    </Provider>
  );
}

export default App;
</code>```

Community.js

```<code>import BigCommunitySection from '../components/BigCommunitySection';

const Community = () =>{
    return(
    <BigCommunitySection/>
    )
}

export default Community
</code>```

And users.js where I fetch data:

```<code>import axios from "axios"
import { addUsers } from "../store/usersReducer"

export const fetchUsers = () => {
  return dispatch => {
    axios
      .get('/community')
      .then(response => {
        dispatch(addUsers(response.data))
      })
      .catch(error => {
        console.log(error)
      })
  }
}
</code>```

答:
A common pattern is to prefix all your proxied URLs with /api or similar.

For example

module.exports = function (app) {
  app.use("/api", createProxyMiddleware({
      target: 'http://localhost:3000',
      pathRewrite: {
        "^/api": "" // remove the /api prefix
      },
      changeOrigin: true,
      headers: {
        Connection: "keep-alive"
      }
    })
  )
}
```
<p>This will proxy any request starting with <code>/api</code> to your Node server endpoints, removing the <code>/api</code> prefix, ie</p>
<ul>
<li><code>/api/subscribe   => http://localhost:3000/subscribe </code></li>
<li><code>/api/unsubscribe => http://localhost:3000/unsubscribe</code></li>
<li><code>/api/community   => http://localhost:3000/community</code></li>
</ul>
<p>Then make your requests to <code>/api</code>-prefixed URLs</p>
<pre class="lang-js prettyprint-override"><code>axios.get("/api/community")
</code>```

You can make this even easier by configuring an Axios instance with the appropriate baseURL

const api = axios.create({
  baseURL: "/api"
})

api.post("/subscribe")
api.post("/unsubscribe")
api.get("/community")
```

Body:
I have an endpoint from where I retrieve data,it is /community.

My react app use 3001 port but the node server where is the /community endpoint use 3000 port,the problem is that when I'm trying to route to localhost:3001/community to display a component,it gives me the JSON data from the server,but I need to display the component,could you help me to identify and fix the problem please?

setupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
  app.use(
    createProxyMiddleware('/subscribe', {
      target: 'http://localhost:3000',
      changeOrigin: true,
      headers: {
        Connection: "keep-alive"
      }
    })
  );
  app.use(
    createProxyMiddleware('/unsubscribe', {
      target: 'http://localhost:3000',
      changeOrigin: true,
      headers: {
        Connection: "keep-alive"
      }
    })
  );
  app.use(
    createProxyMiddleware('/community', {
      target: 'http://localhost:3000',
      changeOrigin: true,
      headers: {
        Connection: "keep-alive"
      }
    })
  );
}

App.js

import './App.css';
// import JoinUsSection from './components/JoinUsSection';
// import BigCommunitySection from './components/BigCommunitySection';
import { Provider } from 'react-redux';
import { store, persistor } from './store';
import { PersistGate } from 'redux-persist/integration/react'
import { fetchUsers } from './asyncActions/users';
import {Routes,Route} from 'react-router-dom'
import Main from './pages/Main'
import Community from'./pages/Community'

store.dispatch(fetchUsers())

function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <Routes>

        {/*
          <BigCommunitySection />
          <JoinUsSection />
         */}

       <Route path="/" element={}/>
<Route path="/community" element={<Community/>}/>
        </Routes>
      </PersistGate>
    </Provider>
  );
}

export default App;

Community.js

import BigCommunitySection from '../components/BigCommunitySection';

const Community = () =>{
    return(
    <BigCommunitySection/>
    )
}

export default Community

And users.js where I fetch data:

import axios from "axios"
import { addUsers } from "../store/usersReducer"

export const fetchUsers = () => {
  return dispatch => {
    axios
      .get('/community')
      .then(response => {
        dispatch(addUsers(response.data))
      })
      .catch(error => {
        console.log(error)
      })
  }
}

Body:
A common pattern is to prefix all your proxied URLs with /api or similar.

For example

module.exports = function (app) {
  app.use("/api", createProxyMiddleware({
      target: 'http://localhost:3000',
      pathRewrite: {
        "^/api": "" // remove the /api prefix
      },
      changeOrigin: true,
      headers: {
        Connection: "keep-alive"
      }
    })
  )
}

This will proxy any request starting with /api to your Node server endpoints, removing the /api prefix, ie

/api/subscribe   => http://localhost:3000/subscribe

/api/unsubscribe => http://localhost:3000/unsubscribe

/api/community   => http://localhost:3000/community

Then make your requests to /api-prefixed URLs

axios.get("/api/community")

You can make this even easier by configuring an Axios instance with the appropriate baseURL

const api = axios.create({
  baseURL: "/api"
})

api.post("/subscribe")
api.post("/unsubscribe")
api.get("/community")


来源: stackexchange

问:
adding a specific value in column data frame containing number and character
I'm facing some data manipulation difficulties.

This is part of my data frame:

```<code>
df <- structure(list(Residue = c("R-A-40", "R-A-350", "R-B-468", "R-C-490",
"R-A-610"), Energy = c(-3.45, -1.89, -0.25, -2.67, -1.98), Model = c("DELTA",
"DELTA", "DELTA", "DELTA", "DELTA")), class = "data.frame", row.names = c(NA,
-5L))

> df
  Residue Energy Model
1  R-A-40  -3.45 DELTA
2 R-A-350  -1.89 DELTA
3 R-B-468  -0.25 DELTA
4 R-C-490  -2.67 DELTA
5 R-A-610  -1.98 DELTA

</code>```

I would like to add (sum) +4 in all numbers in column "Residue". The output would be like this:

```<code>> df_new
  Residue Energy Model
1  R-A-44  -3.45 DELTA
2 R-A-354  -1.89 DELTA
3 R-B-472  -0.25 DELTA
4 R-C-494  -2.67 DELTA
5 R-A-614  -1.98 DELTA
</code>```

I have no idea how to do this since it mixes number and characters.

I appreciate any help

Thanks in advance

答:
Here's a way using tidyverse tools. This presumes that the Residue variable always has the same format as what you provided.</p>
```<code>library(dplyr)
library(stringr)

df |>
  mutate(Residue_val = str_extract(Residue, "\\d.*$"),
         Residue_val = as.numeric(Residue_val) + 4,
         Residue = paste0(str_remove_all(Residue, "\\d"), Residue_val)) |>
  select(-Residue_val)

  Residue Energy Model
1  R-A-44  -3.45 DELTA
2 R-A-354  -1.89 DELTA
3 R-B-472  -0.25 DELTA
4 R-C-494  -2.67 DELTA
5 R-A-614  -1.98 DELTA
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm facing some data manipulation difficulties.

This is part of my data frame:

df <- structure(list(Residue = c("R-A-40", "R-A-350", "R-B-468", "R-C-490",
"R-A-610"), Energy = c(-3.45, -1.89, -0.25, -2.67, -1.98), Model = c("DELTA",
"DELTA", "DELTA", "DELTA", "DELTA")), class = "data.frame", row.names = c(NA,
-5L))

> df
  Residue Energy Model
1  R-A-40  -3.45 DELTA
2 R-A-350  -1.89 DELTA
3 R-B-468  -0.25 DELTA
4 R-C-490  -2.67 DELTA
5 R-A-610  -1.98 DELTA

I would like to add (sum) +4 in all numbers in column "Residue". The output would be like this:

> df_new
  Residue Energy Model
1  R-A-44  -3.45 DELTA
2 R-A-354  -1.89 DELTA
3 R-B-472  -0.25 DELTA
4 R-C-494  -2.67 DELTA
5 R-A-614  -1.98 DELTA

I have no idea how to do this since it mixes number and characters.

I appreciate any help

Thanks in advance

Body:
Here's a way using tidyverse tools. This presumes that the Residue variable always has the same format as what you provided.

library(dplyr)
library(stringr)

df |>
  mutate(Residue_val = str_extract(Residue, "\\d.*$"),
         Residue_val = as.numeric(Residue_val) + 4,
         Residue = paste0(str_remove_all(Residue, "\\d"), Residue_val)) |>
  select(-Residue_val)

  Residue Energy Model
1  R-A-44  -3.45 DELTA
2 R-A-354  -1.89 DELTA
3 R-B-472  -0.25 DELTA
4 R-C-494  -2.67 DELTA
5 R-A-614  -1.98 DELTA


问:
How to change default Python version?
I have installed Python 3.2 in my Mac. After I run /Applications/Python 3.2/Update Shell Profile.command, it's confusing that when I type Python -V in Terminal it says that Python 2.6.1.

How can I change the default Python version?

答:
Starting with macOS Catalina the default shell is zsh. Therefore, all those ~/.bash_profile changes are not going to change the default when you open a new terminal since the new terminal is a zsh shell and not a bash shell.

You can confirm your terminal is a zsh shell by typing echo $SHELL and you should see a response of: zsh.

What should you do? You should use a solution that works for zsh shell and bash shell. Therefore, do the following:

enter: vi ~/.bash_profile

enter: alias python='python3'

close and save your bash_profile. Enter: :wq

Now open/create your zsh profile. Enter: vi ~/.zshrc

source your bash inside your zshrc. Enter: source ~/.bash_profile

Now python will be aliased to python3 in your zsh shells (and in bash if you switch the default) automatically.

Test:
python --version

Python 3.8.9

Title: How to change default Python version?


问:
How do I log off all currently logged on users?
I would like to create a GPO that includes a scheduled task, that should be run once every day. The scheduled task should get a list of all users currently logged on a specific workstation and log them off (just lock Windows would be prefered, but a regular log off seems easier to make)

First I tried to execute the following with the scheduled task:
"shutdown.exe /f /l" to log off users. But the command was being executed by the SYSTEM user, so all regular users was not being logged off.

2nd idea was then to create a Powershell Script and place on each workstation. The script should be able to extract all currently logged on users on the workstation and log off / lock screen for all users.

```<code>$Sessions = quser

# Parse the session IDs from the output
$SessionIds = ($Sessions -split ' +')[3]
$SessionIds

# Loop through each session ID and pass each to the logoff command
ForEach-Object ($SessionId in $SessionIds){
    logoff $SessionId
    }
</code>```

答:
Might as well turn this into a parser.</p>
```<code># q.ps1

$first = 1
quser 2>$null | ForEach-Object {
    if ($first -eq 1) {
        $userPos = $_.IndexOf("USERNAME")
        $sessionPos = $_.IndexOf("SESSIONNAME")
        $idPos = $_.IndexOf("ID") - 2   # ID is right justified
        $statePos = $_.IndexOf("STATE")
        $idlePos = $_.IndexOf("IDLE TIME")
        $logonPos = $_.IndexOf("LOGON TIME")
        $first = 0
    }
    else {
        $user = $_.substring($userPos,$sessionPos-$userPos).Trim()
        $session = $_.substring($sessionPos,$idPos-$sessionPos).Trim()
        $id = [int]$_.substring($idPos,$statePos-$idPos).Trim()
        $state = $_.substring($statePos,$idlePos-$statePos).Trim()
        $idle = $_.substring($idlePos,$logonPos-$idlePos).Trim()
        $logon = [datetime]$_.substring($logonPos,$_.length-$logonPos).Trim()
        [pscustomobject]@{User = $user; Session = $session; ID = $id;
            State = $state; Idle = $idle; Logon = $logon}
    }
}
</code>```
```<code>.\q | ft

User  Session  ID State  Idle Logon
----  -------  -- -----  ---- -----
admin console 111 Active none 2/6/2022 11:21:00 PM
</code>```
```<code>.\q | % { logoff $_.id }
</code>```

Body:
I would like to create a GPO that includes a scheduled task, that should be run once every day. The scheduled task should get a list of all users currently logged on a specific workstation and log them off (just lock Windows would be prefered, but a regular log off seems easier to make)

First I tried to execute the following with the scheduled task:
"shutdown.exe /f /l" to log off users. But the command was being executed by the SYSTEM user, so all regular users was not being logged off.

2nd idea was then to create a Powershell Script and place on each workstation. The script should be able to extract all currently logged on users on the workstation and log off / lock screen for all users.

$Sessions = quser

# Parse the session IDs from the output
$SessionIds = ($Sessions -split ' +')[3]
$SessionIds

# Loop through each session ID and pass each to the logoff command
ForEach-Object ($SessionId in $SessionIds){
    logoff $SessionId
    }

Body:
Might as well turn this into a parser.

# q.ps1

$first = 1
quser 2>$null | ForEach-Object {
    if ($first -eq 1) {
        $userPos = $_.IndexOf("USERNAME")
        $sessionPos = $_.IndexOf("SESSIONNAME")
        $idPos = $_.IndexOf("ID") - 2   # ID is right justified
        $statePos = $_.IndexOf("STATE")
        $idlePos = $_.IndexOf("IDLE TIME")
        $logonPos = $_.IndexOf("LOGON TIME")
        $first = 0
    }
    else {
        $user = $_.substring($userPos,$sessionPos-$userPos).Trim()
        $session = $_.substring($sessionPos,$idPos-$sessionPos).Trim()
        $id = [int]$_.substring($idPos,$statePos-$idPos).Trim()
        $state = $_.substring($statePos,$idlePos-$statePos).Trim()
        $idle = $_.substring($idlePos,$logonPos-$idlePos).Trim()
        $logon = [datetime]$_.substring($logonPos,$_.length-$logonPos).Trim()
        [pscustomobject]@{User = $user; Session = $session; ID = $id;
            State = $state; Idle = $idle; Logon = $logon}
    }
}

.\q | ft

User  Session  ID State  Idle Logon
----  -------  -- -----  ---- -----
admin console 111 Active none 2/6/2022 11:21:00 PM

.\q | % { logoff $_.id }


问:
How to use singlechildscroll view for Gridview.builder
I am using Singlechildscrollview on the top and column as first child. In Column i am using DefaultTabController and in Tabview i am using gridview.builder. Gridview builder can have any different number of products. How can give it  dynamic height as              TabBarView always needs fixed height

Code part:

```<code>  import 'package:flutter/material.dart';

class TestScreen extends StatefulWidget {
  const TestScreen({Key? key}) : super(key: key);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  var indexSelected = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomSheet: Container(
        padding: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 16.0),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
              padding:
                  const EdgeInsets.symmetric(horizontal: 25.0, vertical: 16.0),
              primary: Theme.of(context).primaryColor,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0))),
          onPressed: () {},
          child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        padding: const EdgeInsets.symmetric(
                            vertical: 2, horizontal: 8.0),
                        width: 24.0,
                        height: 24.0,
                        decoration: const BoxDecoration(
                          color: Colors.black,
                          shape: BoxShape.circle,
                        ),
                        child: Text('fasdfa',
                            textAlign: TextAlign.center,
                            style: Theme.of(context)
                                .textTheme
                                .button!
                                .copyWith(color: Colors.white))),
                    const SizedBox(width: 8.0),
                    Text('USD 1000',
                        textAlign: TextAlign.center,
                        style: Theme.of(context).textTheme.button)
                  ],
                ),
                Text('NEXT',
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.button)
              ]),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              Padding(
                /** header */
                padding: const EdgeInsets.only(top: 14, bottom: 10),
                child: Container(
                  height: 60,
                  padding: const EdgeInsets.symmetric(
                      horizontal: 15.0, vertical: 0.0),
                  width: MediaQuery.of(context).size.width * 1,
                  color: Colors.blue,
                ),
              ),
              Container(
                color: Colors.white,
                width: MediaQuery.of(context).size.width,
                child: Column(
                  children: [
                    const SizedBox(
                      width: 0,
                      height: 0,
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 4.0),
                      child: Column(
                        //_buildContent
                        children: [
                          Stack(
                            children: <Widget>[
                              Column(
                                children: <Widget>[
                                  Container(
                                    width:
                                        MediaQuery.of(context).size.width * 1,
                                    height: 200,
                                    color: Colors.yellow,
                                  ),
                                ],
                              ),
                              Positioned(
                                top: MediaQuery.of(context).size.height * 0.265,
                                right: 20,
                                child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                      shape: const CircleBorder(),
                                      primary: Colors.white),
                                  onPressed: () {},
                                  child: Container(
                                    color: Colors.blue,
                                    width: 10,
                                    height: MediaQuery.of(context).size.height *
                                        0.055,
                                  ),
                                ),
                              )
                            ],
                          ),
                          const Tabss(),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Tabss extends StatefulWidget {
  const Tabss({Key? key}) : super(key: key);

  @override
  _TabssState createState() => _TabssState();
}

class _TabssState extends State<Tabss> {
  var indexSelected = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 0.0),
      color: Colors.red,
      child: DefaultTabController(
        length: 1,
        child: Container(
          color: Colors.white,
          //primary: false,
          child: Column(
            children: [
              TabBar(
                onTap: (a) {
                  setState(() {});
                },
                labelStyle: Theme.of(context)
                    .textTheme
                    .button!
                    .copyWith(fontWeight: FontWeight.normal),
                unselectedLabelStyle: Theme.of(context)
                    .textTheme
                    .subtitle1!
                    .copyWith(fontSize: 14),
                isScrollable: true,
                labelPadding:
                    const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
                indicatorWeight: 4,
                indicatorColor: Colors.blue,
                indicatorSize: TabBarIndicatorSize.label,
                tabs: List.generate(
                  1,
                  (index) => const Text(
                    'TESTING',
                    style: TextStyle(
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
              Expanded(
                child: TabBarView(
                  children: List.generate(
                    1,
                    (index) {
                      return GridView.builder(
                          shrinkWrap: true,
                          // FOR FOOD AND DECO
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: 30,
                          gridDelegate:
                              const SliverGridDelegateWithFixedCrossAxisCount(
                                  childAspectRatio: 0.95,
                                  crossAxisSpacing: 15.0,
                                  mainAxisSpacing: 10.0,
                                  mainAxisExtent: 180,
                                  crossAxisCount: 2),
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              color: Colors.red,
                              alignment: Alignment.center,
                              child: Text(
                                index.toString(),
                              ),
                            );
                          });
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

答:
If you want to wrap TabBarView with an Expanded to give it a fixed height, since you have nested Columns, you should wrap all TabBarView parents that are in a Column with an Expanded.

In this way you can leave GridView.builder scrollable! so you won't need SingleChildScrollView! your code will be something like:

```<code>import 'package:flutter/material.dart';

class TestScreen extends StatefulWidget {
  const TestScreen({Key? key}) : super(key: key);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  var indexSelected = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomSheet: Container(
        padding: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 16.0),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
              padding:
                  const EdgeInsets.symmetric(horizontal: 25.0, vertical: 16.0),
              primary: Theme.of(context).primaryColor,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0))),
          onPressed: () {},
          child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        padding: const EdgeInsets.symmetric(
                            vertical: 2, horizontal: 8.0),
                        width: 24.0,
                        height: 24.0,
                        decoration: const BoxDecoration(
                          color: Colors.black,
                          shape: BoxShape.circle,
                        ),
                        child: Text('fasdfa',
                            textAlign: TextAlign.center,
                            style: Theme.of(context)
                                .textTheme
                                .button!
                                .copyWith(color: Colors.white))),
                    const SizedBox(width: 8.0),
                    Text('USD 1000',
                        textAlign: TextAlign.center,
                        style: Theme.of(context).textTheme.button)
                  ],
                ),
                Text('NEXT',
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.button)
              ]),
        ),
      ),
      body: SafeArea(
        child: Column(
          children: [
            Padding(
              /** header */
              padding: const EdgeInsets.only(top: 14, bottom: 10),
              child: Container(
                height: 60,
                padding:
                    const EdgeInsets.symmetric(horizontal: 15.0, vertical: 0.0),
                width: MediaQuery.of(context).size.width * 1,
                color: Colors.blue,
              ),
            ),
            Expanded(
              child: Container(
                color: Colors.white,
                width: MediaQuery.of(context).size.width,
                child: Padding(
                  padding: const EdgeInsets.only(top: 4.0),
                  child: Column(
                    //_buildContent
                    children: [
                      Stack(
                        children: <Widget>[
                          Column(
                            children: <Widget>[
                              Container(
                                width: MediaQuery.of(context).size.width * 1,
                                height: 200,
                                color: Colors.yellow,
                              ),
                            ],
                          ),
                          Positioned(
                            top: MediaQuery.of(context).size.height * 0.265,
                            right: 20,
                            child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                  shape: const CircleBorder(),
                                  primary: Colors.white),
                              onPressed: () {},
                              child: Container(
                                color: Colors.blue,
                                width: 10,
                                height:
                                    MediaQuery.of(context).size.height * 0.055,
                              ),
                            ),
                          )
                        ],
                      ),
                      const Expanded(child: Tabss()),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Tabss extends StatefulWidget {
  const Tabss({Key? key}) : super(key: key);

  @override
  _TabssState createState() => _TabssState();
}

class _TabssState extends State<Tabss> {
  var indexSelected = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 0.0),
      color: Colors.red,
      child: DefaultTabController(
        length: 3,
        child: Container(
          color: Colors.white,
          //primary: false,
          child: Column(
            children: [
              TabBar(
                onTap: (a) {
                  setState(() {});
                },
                labelStyle: Theme.of(context)
                    .textTheme
                    .button!
                    .copyWith(fontWeight: FontWeight.normal),
                unselectedLabelStyle: Theme.of(context)
                    .textTheme
                    .subtitle1!
                    .copyWith(fontSize: 14),
                isScrollable: true,
                labelPadding:
                    const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
                indicatorWeight: 4,
                indicatorColor: Colors.blue,
                indicatorSize: TabBarIndicatorSize.label,
                tabs: List.generate(
                  3,
                  (index) => const Text(
                    'TESTING',
                    style: TextStyle(
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
              Expanded(
                child: TabBarView(
                  children: List.generate(
                    3,
                    (index) {
                      return GridView.builder(
                        shrinkWrap: true,
                        // FOR FOOD AND DECO
                        itemCount: 30,
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                                childAspectRatio: 0.95,
                                crossAxisSpacing: 15.0,
                                mainAxisSpacing: 10.0,
                                mainAxisExtent: 180,
                                crossAxisCount: 2),
                        itemBuilder: (BuildContext context, int index) {
                          return Container(
                            color: Colors.red,
                            alignment: Alignment.center,
                            child: Text(
                              index.toString(),
                            ),
                          );
                        },
                      );
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

</code>```

Body:
I am using Singlechildscrollview on the top and column as first child. In Column i am using DefaultTabController and in Tabview i am using gridview.builder. Gridview builder can have any different number of products. How can give it  dynamic height as              TabBarView always needs fixed height

Code part:

  import 'package:flutter/material.dart';

class TestScreen extends StatefulWidget {
  const TestScreen({Key? key}) : super(key: key);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  var indexSelected = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomSheet: Container(
        padding: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 16.0),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
              padding:
                  const EdgeInsets.symmetric(horizontal: 25.0, vertical: 16.0),
              primary: Theme.of(context).primaryColor,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0))),
          onPressed: () {},
          child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        padding: const EdgeInsets.symmetric(
                            vertical: 2, horizontal: 8.0),
                        width: 24.0,
                        height: 24.0,
                        decoration: const BoxDecoration(
                          color: Colors.black,
                          shape: BoxShape.circle,
                        ),
                        child: Text('fasdfa',
                            textAlign: TextAlign.center,
                            style: Theme.of(context)
                                .textTheme
                                .button!
                                .copyWith(color: Colors.white))),
                    const SizedBox(width: 8.0),
                    Text('USD 1000',
                        textAlign: TextAlign.center,
                        style: Theme.of(context).textTheme.button)
                  ],
                ),
                Text('NEXT',
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.button)
              ]),
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              Padding(
                /** header */
                padding: const EdgeInsets.only(top: 14, bottom: 10),
                child: Container(
                  height: 60,
                  padding: const EdgeInsets.symmetric(
                      horizontal: 15.0, vertical: 0.0),
                  width: MediaQuery.of(context).size.width * 1,
                  color: Colors.blue,
                ),
              ),
              Container(
                color: Colors.white,
                width: MediaQuery.of(context).size.width,
                child: Column(
                  children: [
                    const SizedBox(
                      width: 0,
                      height: 0,
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 4.0),
                      child: Column(
                        //_buildContent
                        children: [
                          Stack(
                            children: <Widget>[
                              Column(
                                children: <Widget>[
                                  Container(
                                    width:
                                        MediaQuery.of(context).size.width * 1,
                                    height: 200,
                                    color: Colors.yellow,
                                  ),
                                ],
                              ),
                              Positioned(
                                top: MediaQuery.of(context).size.height * 0.265,
                                right: 20,
                                child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                      shape: const CircleBorder(),
                                      primary: Colors.white),
                                  onPressed: () {},
                                  child: Container(
                                    color: Colors.blue,
                                    width: 10,
                                    height: MediaQuery.of(context).size.height *
                                        0.055,
                                  ),
                                ),
                              )
                            ],
                          ),
                          const Tabss(),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class Tabss extends StatefulWidget {
  const Tabss({Key? key}) : super(key: key);

  @override
  _TabssState createState() => _TabssState();
}

class _TabssState extends State<Tabss> {
  var indexSelected = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 0.0),
      color: Colors.red,
      child: DefaultTabController(
        length: 1,
        child: Container(
          color: Colors.white,
          //primary: false,
          child: Column(
            children: [
              TabBar(
                onTap: (a) {
                  setState(() {});
                },
                labelStyle: Theme.of(context)
                    .textTheme
                    .button!
                    .copyWith(fontWeight: FontWeight.normal),
                unselectedLabelStyle: Theme.of(context)
                    .textTheme
                    .subtitle1!
                    .copyWith(fontSize: 14),
                isScrollable: true,
                labelPadding:
                    const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
                indicatorWeight: 4,
                indicatorColor: Colors.blue,
                indicatorSize: TabBarIndicatorSize.label,
                tabs: List.generate(
                  1,
                  (index) => const Text(
                    'TESTING',
                    style: TextStyle(
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
              Expanded(
                child: TabBarView(
                  children: List.generate(
                    1,
                    (index) {
                      return GridView.builder(
                          shrinkWrap: true,
                          // FOR FOOD AND DECO
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: 30,
                          gridDelegate:
                              const SliverGridDelegateWithFixedCrossAxisCount(
                                  childAspectRatio: 0.95,
                                  crossAxisSpacing: 15.0,
                                  mainAxisSpacing: 10.0,
                                  mainAxisExtent: 180,
                                  crossAxisCount: 2),
                          itemBuilder: (BuildContext context, int index) {
                            return Container(
                              color: Colors.red,
                              alignment: Alignment.center,
                              child: Text(
                                index.toString(),
                              ),
                            );
                          });
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Body:
If you want to wrap TabBarView with an Expanded to give it a fixed height, since you have nested Columns, you should wrap all TabBarView parents that are in a Column with an Expanded.

In this way you can leave GridView.builder scrollable! so you won't need SingleChildScrollView! your code will be something like:

import 'package:flutter/material.dart';

class TestScreen extends StatefulWidget {
  const TestScreen({Key? key}) : super(key: key);

  @override
  State<TestScreen> createState() => _TestScreenState();
}

class _TestScreenState extends State<TestScreen> {
  var indexSelected = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomSheet: Container(
        padding: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 16.0),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
              padding:
                  const EdgeInsets.symmetric(horizontal: 25.0, vertical: 16.0),
              primary: Theme.of(context).primaryColor,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0))),
          onPressed: () {},
          child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                        padding: const EdgeInsets.symmetric(
                            vertical: 2, horizontal: 8.0),
                        width: 24.0,
                        height: 24.0,
                        decoration: const BoxDecoration(
                          color: Colors.black,
                          shape: BoxShape.circle,
                        ),
                        child: Text('fasdfa',
                            textAlign: TextAlign.center,
                            style: Theme.of(context)
                                .textTheme
                                .button!
                                .copyWith(color: Colors.white))),
                    const SizedBox(width: 8.0),
                    Text('USD 1000',
                        textAlign: TextAlign.center,
                        style: Theme.of(context).textTheme.button)
                  ],
                ),
                Text('NEXT',
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.button)
              ]),
        ),
      ),
      body: SafeArea(
        child: Column(
          children: [
            Padding(
              /** header */
              padding: const EdgeInsets.only(top: 14, bottom: 10),
              child: Container(
                height: 60,
                padding:
                    const EdgeInsets.symmetric(horizontal: 15.0, vertical: 0.0),
                width: MediaQuery.of(context).size.width * 1,
                color: Colors.blue,
              ),
            ),
            Expanded(
              child: Container(
                color: Colors.white,
                width: MediaQuery.of(context).size.width,
                child: Padding(
                  padding: const EdgeInsets.only(top: 4.0),
                  child: Column(
                    //_buildContent
                    children: [
                      Stack(
                        children: <Widget>[
                          Column(
                            children: <Widget>[
                              Container(
                                width: MediaQuery.of(context).size.width * 1,
                                height: 200,
                                color: Colors.yellow,
                              ),
                            ],
                          ),
                          Positioned(
                            top: MediaQuery.of(context).size.height * 0.265,
                            right: 20,
                            child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                  shape: const CircleBorder(),
                                  primary: Colors.white),
                              onPressed: () {},
                              child: Container(
                                color: Colors.blue,
                                width: 10,
                                height:
                                    MediaQuery.of(context).size.height * 0.055,
                              ),
                            ),
                          )
                        ],
                      ),
                      const Expanded(child: Tabss()),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Tabss extends StatefulWidget {
  const Tabss({Key? key}) : super(key: key);

  @override
  _TabssState createState() => _TabssState();
}

class _TabssState extends State<Tabss> {
  var indexSelected = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 0.0),
      color: Colors.red,
      child: DefaultTabController(
        length: 3,
        child: Container(
          color: Colors.white,
          //primary: false,
          child: Column(
            children: [
              TabBar(
                onTap: (a) {
                  setState(() {});
                },
                labelStyle: Theme.of(context)
                    .textTheme
                    .button!
                    .copyWith(fontWeight: FontWeight.normal),
                unselectedLabelStyle: Theme.of(context)
                    .textTheme
                    .subtitle1!
                    .copyWith(fontSize: 14),
                isScrollable: true,
                labelPadding:
                    const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
                indicatorWeight: 4,
                indicatorColor: Colors.blue,
                indicatorSize: TabBarIndicatorSize.label,
                tabs: List.generate(
                  3,
                  (index) => const Text(
                    'TESTING',
                    style: TextStyle(
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
              Expanded(
                child: TabBarView(
                  children: List.generate(
                    3,
                    (index) {
                      return GridView.builder(
                        shrinkWrap: true,
                        // FOR FOOD AND DECO
                        itemCount: 30,
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                                childAspectRatio: 0.95,
                                crossAxisSpacing: 15.0,
                                mainAxisSpacing: 10.0,
                                mainAxisExtent: 180,
                                crossAxisCount: 2),
                        itemBuilder: (BuildContext context, int index) {
                          return Container(
                            color: Colors.red,
                            alignment: Alignment.center,
                            child: Text(
                              index.toString(),
                            ),
                          );
                        },
                      );
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


问:
VS Code Remote - Can't run 'code' command in WSL Ubuntu 18 or WSL 2 Ubuntu 20 - wrong path
I'm having an issue when I try to run the code command from Visual Studio Code in WSL Ubuntu. I get the following error:

```<code>$ code .

/mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: 63: /mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: /home/barry/.vscode/bin/899d46d82c4c95423fb7e10e68eba52050e30ba3/bin/remote-cli/code: not found
</code>```

When I run the following, it installs the VS Code Server and the command works as expected:

```<code>$ /mnt/c/Users/Name/AppData/Local/Programs/Microsoft\ VS\ Code/bin/code .
</code>```

When I run which -a code, I can see I have two paths related to this command and I believe the correct one is /mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code, but I don't know how to remove the first one or how it even related two paths to this command in the first place?

```<code>barry@RandomName:~$ which -a code
/mnt/c/Program Files/Microsoft VS Code/bin/code
/mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code
</code>```

Can anyone help please?

答:
Ran into the same problem 5 min ago and this post from thesteve0 worked for me:

https://github.com/microsoft/vscode-remote-release/issues/6294#issuecomment-1031974516

Quoting from the original post:

Open VS Code on Windows

Open Extensions and then search on WSL

It should say the extension needs to be reloaded - go ahead and reload it

Open WSL and type code

This should force another upgrade of code and this time it should launch.

Body:
I'm having an issue when I try to run the code command from Visual Studio Code in WSL Ubuntu. I get the following error:

$ code .

/mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: 63: /mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: /home/barry/.vscode/bin/899d46d82c4c95423fb7e10e68eba52050e30ba3/bin/remote-cli/code: not found

When I run the following, it installs the VS Code Server and the command works as expected:

$ /mnt/c/Users/Name/AppData/Local/Programs/Microsoft\ VS\ Code/bin/code .

When I run which -a code, I can see I have two paths related to this command and I believe the correct one is /mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code, but I don't know how to remove the first one or how it even related two paths to this command in the first place?

barry@RandomName:~$ which -a code
/mnt/c/Program Files/Microsoft VS Code/bin/code
/mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code

Can anyone help please?


问:
Long text (> 255 chars) truncated while importing and adding to existing table in MS Access 2013
I am trying to import an excel spreadsheet using the below VBA code. Before bringing it in I am also deleting the current contents of the table.

```<code>DoCmd.RunSQL ("DELETE * FROM REBATE_PROG")
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, "REBATE_PROG", filepath, True
</code>```

The rebate_prog table already has fields defined as long text (which is the old memo field, as per my understanding) which should be able to store > 255 chars.

Is there a reason why Access would be truncating the contents?

Some of the things that I have tried, without success:

Sorting the import file in descending on the length of the field which is truncating - for if excel looks at only a few top rows, it would import as Long text.

Tried to update the "Text Format" for the field under Design View in table properties to Rich text from Plain, but for some reason Access doesn't allow me to make the change.

Is there a way I can import the excel spreadsheet without access truncating the fields?

答:
There is a very simple and easy solution to this problem. For example, some rows for Column A in worksheet #1 contains short texts and some rows for the same column has long texts. Make a copy of worksheet #1 as worksheet #2.

On worksheet #1, delete long-text rows for column A and keep only short-text rows.

On worksheet #2, delete short-text rows for column A and keep only long-text rows.

Now use the transfer spreadsheet command for workheet 1 and then for woeksheet #2.

```<code>Call DoCmd.TransferSpreadsheet( _
    acImport, _
    acSpreadsheetTypeExcel12Xml, _
    strTableName, _
    strFullPathOfWorkbook, _
    True, _
    "WorkSheet_1!A1:Z1000)

Call DoCmd.TransferSpreadsheet( _
    acImport, _
    acSpreadsheetTypeExcel12Xml, _
    strTableName, _
    strFullPathOfWorkbook, _
    True, _
    "WorkSheet_2!A1:Z1000)
</code>```

I have tested this solution more than 100 times and it works perfectly. The trick is to divide columns with mixed short-text and long-text rows in two worksheets.
All other programmers have failed because majority of them ignored the fact that VBA cannot handle a mixed column with both short and long texts.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to import an excel spreadsheet using the below VBA code. Before bringing it in I am also deleting the current contents of the table.

DoCmd.RunSQL ("DELETE * FROM REBATE_PROG")
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, "REBATE_PROG", filepath, True

The rebate_prog table already has fields defined as long text (which is the old memo field, as per my understanding) which should be able to store > 255 chars.

Is there a reason why Access would be truncating the contents?

Some of the things that I have tried, without success:

Sorting the import file in descending on the length of the field which is truncating - for if excel looks at only a few top rows, it would import as Long text.

Tried to update the "Text Format" for the field under Design View in table properties to Rich text from Plain, but for some reason Access doesn't allow me to make the change.

Is there a way I can import the excel spreadsheet without access truncating the fields?

Body:
There is a very simple and easy solution to this problem. For example, some rows for Column A in worksheet #1 contains short texts and some rows for the same column has long texts. Make a copy of worksheet #1 as worksheet #2.

On worksheet #1, delete long-text rows for column A and keep only short-text rows.

On worksheet #2, delete short-text rows for column A and keep only long-text rows.

Now use the transfer spreadsheet command for workheet 1 and then for woeksheet #2.

Call DoCmd.TransferSpreadsheet( _
    acImport, _
    acSpreadsheetTypeExcel12Xml, _
    strTableName, _
    strFullPathOfWorkbook, _
    True, _
    "WorkSheet_1!A1:Z1000)

Call DoCmd.TransferSpreadsheet( _
    acImport, _
    acSpreadsheetTypeExcel12Xml, _
    strTableName, _
    strFullPathOfWorkbook, _
    True, _
    "WorkSheet_2!A1:Z1000)

I have tested this solution more than 100 times and it works perfectly. The trick is to divide columns with mixed short-text and long-text rows in two worksheets.
All other programmers have failed because majority of them ignored the fact that VBA cannot handle a mixed column with both short and long texts.


问:
With dvcs/git, is a single commit preferred over multiple, small, thematic commits?
This may not be a git specific question, but it comes up in the context of git. The idea may apply more broadly to other vcs's.

I am working on a small project in which I am currently the only developer. I'm getting used to using git, so I am wondering about best practices. As I implement new features/functions, I find that I work on multiple files, their examples, and documentation at once, such that my git status may report 15 files that have changed. But those files might relate to 3 different parts of the project.

Is it better to commit them in 3 separate parts, keeping the related files together, so that I could later go back and more easily find those commits. Or it is just as easy to commit them all at once with an appropriate message?

答:
Its preferable to make commits atomic. That is, a commit represents one logical change to the project in question, and can stand alone.

This allows

Easy code inspection

git bisect to work correctly


问:
ui-grid menu dropdown shows javascript code behind the buttons
Using Angular-UI-grid version 4.4.11 with Angular 1.8, And JQuery version is 3.6.0

But the dropdown in the grid menu header just show the Code behind the  tag

And the Generated HTML is as:

```<code><button type="button" class="ui-grid-menu-item ng-binding" ng-click="itemAction($event, title)" ng-show="itemShown()" ng-class="{ 'ui-grid-menu-item-active': active(), 'ui-grid-sr-only': (!focus && screenReaderOnly) }" aria-pressed="false" tabindex="0" ng-focus="focus=true" ng-blur="focus=false">
<i ng-class="icon" aria-hidden="true" class="ui-grid-icon-sort-alt-up"> </i>function(){return e.getSafeText("sort.ascending")}
</button>
</code>```

Why it's happening like this?

答:
Here's a suggestion for you how you might make this work, which is to:

place the function call in your view and

define the function itself in your controller as shown below

(You'll want to place your view and controller in two separate files.  I included everything in one file below just to display everything more clearly)

```<code><!DOCTYPE html>

<html ng-app="myApp">
  <head>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular.js"></script>
  </head>
  <body ng-controller="MyController">

    <button type="button"
            class="ui-grid-menu-item ng-binding"
            ng-click="itemAction($event, title)"
            ng-show="itemShown()"
            ng-class="{ 'ui-grid-menu-item-active': active(), 'ui-grid-sr-only': (!focus && screenReaderOnly) }"
            aria-pressed="false"
            tabindex="0"
            ng-focus="focus=true"
            ng-blur="focus=false">
            <i  ng-class="icon"
                aria-hidden="true"
                class="ui-grid-icon-sort-alt-up"> </i>
            {{ safeTextFunc() }}  <-----------------------
    </button>

    <script>
      angular.module('myApp', []).
        controller('MyController', ['$scope',function($scope) {
            $scope.safeTextFunc = function(){ <--------------------
                  return e.getSafeText("sort.ascending") <--------------------
            }

            // define e.getSafeText function here <--------------------
        }]
      );
    </script>
  </body>
</html>
</code>```

Body:
Using Angular-UI-grid version 4.4.11 with Angular 1.8, And JQuery version is 3.6.0

But the dropdown in the grid menu header just show the Code behind the  tag

And the Generated HTML is as:

<button type="button" class="ui-grid-menu-item ng-binding" ng-click="itemAction($event, title)" ng-show="itemShown()" ng-class="{ 'ui-grid-menu-item-active': active(), 'ui-grid-sr-only': (!focus && screenReaderOnly) }" aria-pressed="false" tabindex="0" ng-focus="focus=true" ng-blur="focus=false">
 function(){return e.getSafeText("sort.ascending")}
</button>

Why it's happening like this?

Body:
Here's a suggestion for you how you might make this work, which is to:

place the function call in your view and

define the function itself in your controller as shown below

(You'll want to place your view and controller in two separate files.  I included everything in one file below just to display everything more clearly)

<!DOCTYPE html>

<html ng-app="myApp">
  <head>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.11/angular.js"></script>
  </head>
  <body ng-controller="MyController">

    <button type="button"
            class="ui-grid-menu-item ng-binding"
            ng-click="itemAction($event, title)"
            ng-show="itemShown()"
            ng-class="{ 'ui-grid-menu-item-active': active(), 'ui-grid-sr-only': (!focus &amp;&amp; screenReaderOnly) }"
            aria-pressed="false"
            tabindex="0"
            ng-focus="focus=true"
            ng-blur="focus=false">
            <i  ng-class="icon"
                aria-hidden="true"
                class="ui-grid-icon-sort-alt-up">&nbsp;</i>
            {{ safeTextFunc() }}  <-----------------------
    </button>

    <script>
      angular.module('myApp', []).
        controller('MyController', ['$scope',function($scope) {
            $scope.safeTextFunc = function(){ <--------------------
                  return e.getSafeText("sort.ascending") <--------------------
            }

            // define e.getSafeText function here <--------------------
        }]
      );
    </script>
  </body>
</html>


问:
How to groupby a column and count the number of unique values in another column
I have the following dataframe. I need to groupby the ngram, and for each group, count how many unique documents are present in the DocID column.

For example, from the above

```<code>4-gram group - 4 as number of unique documents (doc64,doc383,doc76,doc370)
5-gram - 4
6-gram - 4
7-gram - 2
8-gram - 2
</code>```

I have an idea in bits. I can get the unique DocIDs as follows:

```<code>#Get all the docs of repeated summaries in one list as a list of lists.
rep = []
rep += temp['DocID'].str.split(",").tolist()

# Put all values in one list.
repSet = []
for i in range(len(rep)):
    repSet.extend(rep[i])

# Remove all duplicates and store in a list.
repSet = list(set(repSet))
</code>```

But I don't know how to merge this with groupby.

EDIT

I have added the output from the first answer provided. Thank you! But the total number of documents are only 461. So I believe the maximum value of the DocID can go up to only that much :( but for the trigram its above 461 :(

Help will be greatly appreciated. Thanks!

答:
Maybe something like this?</p>
```<code>df.assign(docid=df['docid'].str.split(',')).explode('docid').groupby('ngram')['docid'].nunique().reset_index()
</code>```

Body:
I have the following dataframe. I need to groupby the ngram, and for each group, count how many unique documents are present in the DocID column.

For example, from the above

4-gram group - 4 as number of unique documents (doc64,doc383,doc76,doc370)
5-gram - 4
6-gram - 4
7-gram - 2
8-gram - 2

I have an idea in bits. I can get the unique DocIDs as follows:

#Get all the docs of repeated summaries in one list as a list of lists.
rep = []
rep += temp['DocID'].str.split(",").tolist()

# Put all values in one list.
repSet = []
for i in range(len(rep)):
    repSet.extend(rep[i])

# Remove all duplicates and store in a list.
repSet = list(set(repSet))

But I don't know how to merge this with groupby.

EDIT

I have added the output from the first answer provided. Thank you! But the total number of documents are only 461. So I believe the maximum value of the DocID can go up to only that much :( but for the trigram its above 461 :(

Help will be greatly appreciated. Thanks!

Body:
Maybe something like this?

df.assign(docid=df['docid'].str.split(',')).explode('docid').groupby('ngram')['docid'].nunique().reset_index()


问:
Create a dynamic table on shiny app based on shiny widget and row selection of another datatable
I have the shiny app below which initially displays a checkBoxGroupButtons() and a table. The table has 5 rows (just example-normally more) if you click on a row then another table is displayed.

The checkbox group has 2 choices  Elective and Non-elective Long Stay. In this version I have included only calculation for Elective using data[,2] and data[,1] in lines 78-79 of my code. The respective calculations for Non-elective Long Stay will be data[,4] instead of data[2,] and data[3,] instead of data[1,].

The initial table is used to give the index or rows selected for the calculation.

So for example if I choose Elective and first row I should take a table based on 1st row and with 2 columns in total (only Elective as it is now),

If I choose then both Elective and Non-elective Long Stay another column will be added with the relative calculations.

IF I click on another row lets say row 3 it will be included in the calculations together with row 1 from earlier.

If nothing is chosen the no table is displayed.

To sum up the checkbox sets the service type displayed and the row selection the index of rows that wil be included in the means calculation.

```<code>library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(data.table)
library(dplyr)
library(DT)
library(devtools)

filtercost<-structure(list(Currency = c("A01A1", "A01AG", "A01C1", "A01CG",
                                        "A03"), `Currency Description` = c("Other Therapist, Adult, One to One",
                                                                           "Other Therapist, Adult, Group", "Other Therapist, Child, One to One",
                                                                           "Other Therapist, Child, Group", "Dietitian")), row.names = c(NA,
                                                                                -5L), class = c("tbl_df", "tbl", "data.frame"))

datacost<-structure(list(Elective_Activity = c(110, 134, 167, 241, 247),
                         `Elective_Unit Cost` = c(9329, 5105, 3354, 3116, 2429), `Non-elective Long Stay_Activity` = c(2957,
                                                                                1899, 2049, 2220, 3388), `Non-elective Long Stay_Unit Cost` = c(6877,
                                                                                5455, 3822, 3385, 2533)), row.names = c(NA, -5L), class = c("tbl_df",
                                                                                "tbl", "data.frame"))
header <- dashboardHeader(title = "National Schedule of NHS Costs")

sidebar <- dashboardSidebar(

)

body <- dashboardBody(fluidPage(
           checkboxGroupButtons(
                                     inputId = "somevalue2",
                                     label = "Choose service type:",
                                     choices = c("Elective","Non-elective Long Stay"),
                                     justified = F,
                                     status = "primary",
                                     checkIcon = list(
                                       yes = icon("ok",
                                                  lib = "glyphicon"),
                                       no = icon("remove",
                                                 lib = "glyphicon"))
                                   ),
                                   box(width = 12,DT::dataTableOutput('selectedrow_costs')),
                                   box(width = 12,DT::dataTableOutput('costs'), height = 150))

           )

ui <- dashboardPage(title = 'Search', header, sidebar, body)

server <- function(input, output, session) {

  output$costs <- DT::renderDataTable({

    dtable <- datatable(
      filtercost, selection = "multiple",rownames=FALSE
    )
    dep <- htmltools::htmlDependency("jqueryui", "1.12.1",
                                     "www/shared/jqueryui",
                                     script = "jquery-ui.min.js",
                                     package = "shiny")
    dtable$dependencies <- c(dtable$dependencies, list(dep))
    dtable
  })

  #output$value2 <- renderPrint({ input$somevalue2 })

  selectedrow_costsrows <- eventReactive(input$costs_rows_selected, {
    #req(input$costs_rows_selected)
    s <- input$costs_rows_selected
    data <- as.data.frame(datacost[s,])
    names(data) <- NULL
    data

    elective_mean<- weighted.mean(as.numeric(data[,2]),as.numeric(data[,1]),na.rm = F)
    elective_se<- sqrt(as.numeric(data[,1])*((as.numeric(data[,2])-elective_mean)^2)/sum(as.numeric(data[,1])))
    elective_CI_l<- elective_mean-1.96*elective_se
    elective_CI_h<- elective_mean+1.96*elective_se

    Service_type <- c("Elective")
    Weighted_mean <- round(c(elective_mean),0)
    Weighted_SR <-  round(c(elective_se),0)
    CI_Lower_95 <-  round(c(elective_CI_l),0)
    CI_Upeer_95 <-  round(c(elective_CI_h),0)

    costtable <- as.data.frame(rbind(Service_type,Weighted_mean,Weighted_SR,CI_Lower_95,CI_Upeer_95))
    costtable

  })

  output$selectedrow_costs <- DT::renderDataTable({
    df=selectedrow_costsrows()})

}
shinyApp(ui = ui, server = server)
</code>```

答:
Perhaps this will meet your needs.  Please note that you may need to modify the formula for elective_se and elective_se2.

```<code>server <- function(input, output, session) {

  output$costs <- DT::renderDataTable({

    dtable <- datatable(
      filtercost, selection = "multiple",rownames=FALSE
    )
    dep <- htmltools::htmlDependency("jqueryui", "1.12.1",
                                     "www/shared/jqueryui",
                                     script = "jquery-ui.min.js",
                                     package = "shiny")
    dtable$dependencies <- c(dtable$dependencies, list(dep))
    dtable
  })

  #output$value2 <- renderPrint({ input$somevalue2 })

  selectedrow_costsrows <- reactive({
    #req(input$costs_rows_selected)
    s <- input$costs_rows_selected
    data <- as.data.frame(datacost[s,])
    names(data) <- NULL
    data

    if (is.null(input$costs_rows_selected)) {costtable <- NULL
    }else {
      n <- length(input$costs_rows_selected)
      elective_mean<- weighted.mean(as.numeric(data[,2]),as.numeric(data[,1]),na.rm = F)
      elective_se  <- ifelse(n>1, sqrt(sum((as.numeric(data[,2])-elective_mean)^2)/(n*(n-1))), 0)
      elective_CI_l<- elective_mean-1.96*elective_se
      elective_CI_h<- elective_mean+1.96*elective_se

      Service_type <- c("Elective")
      Weighted_mean <- round(c(elective_mean),0)
      Weighted_SR <-  round(c(elective_se),0)
      CI_Lower_95 <-  round(c(elective_CI_l),0)
      CI_Upeer_95 <-  round(c(elective_CI_h),0)

      costtable1 <- as.data.frame(rbind(Service_type,Weighted_mean,Weighted_SR,CI_Lower_95,CI_Upeer_95))

      elective_mean2<- weighted.mean(as.numeric(data[,4]),as.numeric(data[,3]),na.rm = F)
      elective_se2  <- ifelse(n>1, sqrt(sum((as.numeric(data[,4])-elective_mean2)^2)/(n*(n-1))), 0)
      elective_CI_l2<- elective_mean2 - 1.96*elective_se2
      elective_CI_h2<- elective_mean2 + 1.96*elective_se2

      Service_type2 <- c("Non-elective Long Stay")
      Weighted_mean2 <- round(c(elective_mean2),0)
      Weighted_SR2 <-  round(c(elective_se2),0)
      CI_Lower_952 <-  round(c(elective_CI_l2),0)
      CI_Upeer_952 <-  round(c(elective_CI_h2),0)

      costtable2 <- as.data.frame(rbind(Service_type2,Weighted_mean2,Weighted_SR2,CI_Lower_952,CI_Upeer_952))
      colnames(costtable2) <- "V2"
      if (is.null(input$somevalue2)) {costtable <- NULL
      }else if (length(input$somevalue2)==2){
        costtable <- cbind(costtable1,costtable2)
      }else{
        if (input$somevalue2=="Elective"){
          costtable <- costtable1
        }else {
          costtable <- costtable2
        }
      }
    }

    costtable

  })

  output$selectedrow_costs <- DT::renderDataTable({
    df=selectedrow_costsrows()})

}
shinyApp(ui = ui, server = server)
</code>```

Body:
I have the shiny app below which initially displays a checkBoxGroupButtons() and a table. The table has 5 rows (just example-normally more) if you click on a row then another table is displayed.

The checkbox group has 2 choices  Elective and Non-elective Long Stay. In this version I have included only calculation for Elective using data[,2] and data[,1] in lines 78-79 of my code. The respective calculations for Non-elective Long Stay will be data[,4] instead of data[2,] and data[3,] instead of data[1,].

The initial table is used to give the index or rows selected for the calculation.

So for example if I choose Elective and first row I should take a table based on 1st row and with 2 columns in total (only Elective as it is now),

If I choose then both Elective and Non-elective Long Stay another column will be added with the relative calculations.

IF I click on another row lets say row 3 it will be included in the calculations together with row 1 from earlier.

If nothing is chosen the no table is displayed.

To sum up the checkbox sets the service type displayed and the row selection the index of rows that wil be included in the means calculation.

library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(data.table)
library(dplyr)
library(DT)
library(devtools)

filtercost<-structure(list(Currency = c("A01A1", "A01AG", "A01C1", "A01CG",
                                        "A03"), `Currency Description` = c("Other Therapist, Adult, One to One",
                                                                           "Other Therapist, Adult, Group", "Other Therapist, Child, One to One",
                                                                           "Other Therapist, Child, Group", "Dietitian")), row.names = c(NA,
                                                                                -5L), class = c("tbl_df", "tbl", "data.frame"))

datacost<-structure(list(Elective_Activity = c(110, 134, 167, 241, 247),
                         `Elective_Unit Cost` = c(9329, 5105, 3354, 3116, 2429), `Non-elective Long Stay_Activity` = c(2957,
                                                                                1899, 2049, 2220, 3388), `Non-elective Long Stay_Unit Cost` = c(6877,
                                                                                5455, 3822, 3385, 2533)), row.names = c(NA, -5L), class = c("tbl_df",
                                                                                "tbl", "data.frame"))
header <- dashboardHeader(title = "National Schedule of NHS Costs")

sidebar <- dashboardSidebar(

)

body <- dashboardBody(fluidPage(
           checkboxGroupButtons(
                                     inputId = "somevalue2",
                                     label = "Choose service type:",
                                     choices = c("Elective","Non-elective Long Stay"),
                                     justified = F,
                                     status = "primary",
                                     checkIcon = list(
                                       yes = icon("ok",
                                                  lib = "glyphicon"),
                                       no = icon("remove",
                                                 lib = "glyphicon"))
                                   ),
                                   box(width = 12,DT::dataTableOutput('selectedrow_costs')),
                                   box(width = 12,DT::dataTableOutput('costs'), height = 150))

           )

ui <- dashboardPage(title = 'Search', header, sidebar, body)

server <- function(input, output, session) {

  output$costs <- DT::renderDataTable({

    dtable <- datatable(
      filtercost, selection = "multiple",rownames=FALSE
    )
    dep <- htmltools::htmlDependency("jqueryui", "1.12.1",
                                     "www/shared/jqueryui",
                                     script = "jquery-ui.min.js",
                                     package = "shiny")
    dtable$dependencies <- c(dtable$dependencies, list(dep))
    dtable
  })

  #output$value2 <- renderPrint({ input$somevalue2 })

  selectedrow_costsrows <- eventReactive(input$costs_rows_selected, {
    #req(input$costs_rows_selected)
    s <- input$costs_rows_selected
    data <- as.data.frame(datacost[s,])
    names(data) <- NULL
    data

    elective_mean<- weighted.mean(as.numeric(data[,2]),as.numeric(data[,1]),na.rm = F)
    elective_se<- sqrt(as.numeric(data[,1])*((as.numeric(data[,2])-elective_mean)^2)/sum(as.numeric(data[,1])))
    elective_CI_l<- elective_mean-1.96*elective_se
    elective_CI_h<- elective_mean+1.96*elective_se

    Service_type <- c("Elective")
    Weighted_mean <- round(c(elective_mean),0)
    Weighted_SR <-  round(c(elective_se),0)
    CI_Lower_95 <-  round(c(elective_CI_l),0)
    CI_Upeer_95 <-  round(c(elective_CI_h),0)

    costtable <- as.data.frame(rbind(Service_type,Weighted_mean,Weighted_SR,CI_Lower_95,CI_Upeer_95))
    costtable

  })

  output$selectedrow_costs <- DT::renderDataTable({
    df=selectedrow_costsrows()})

}
shinyApp(ui = ui, server = server)

Body:
Perhaps this will meet your needs.  Please note that you may need to modify the formula for elective_se and elective_se2.

server <- function(input, output, session) {

  output$costs <- DT::renderDataTable({

    dtable <- datatable(
      filtercost, selection = "multiple",rownames=FALSE
    )
    dep <- htmltools::htmlDependency("jqueryui", "1.12.1",
                                     "www/shared/jqueryui",
                                     script = "jquery-ui.min.js",
                                     package = "shiny")
    dtable$dependencies <- c(dtable$dependencies, list(dep))
    dtable
  })

  #output$value2 <- renderPrint({ input$somevalue2 })

  selectedrow_costsrows <- reactive({
    #req(input$costs_rows_selected)
    s <- input$costs_rows_selected
    data <- as.data.frame(datacost[s,])
    names(data) <- NULL
    data

    if (is.null(input$costs_rows_selected)) {costtable <- NULL
    }else {
      n <- length(input$costs_rows_selected)
      elective_mean<- weighted.mean(as.numeric(data[,2]),as.numeric(data[,1]),na.rm = F)
      elective_se  <- ifelse(n>1, sqrt(sum((as.numeric(data[,2])-elective_mean)^2)/(n*(n-1))), 0)
      elective_CI_l<- elective_mean-1.96*elective_se
      elective_CI_h<- elective_mean+1.96*elective_se

      Service_type <- c("Elective")
      Weighted_mean <- round(c(elective_mean),0)
      Weighted_SR <-  round(c(elective_se),0)
      CI_Lower_95 <-  round(c(elective_CI_l),0)
      CI_Upeer_95 <-  round(c(elective_CI_h),0)

      costtable1 <- as.data.frame(rbind(Service_type,Weighted_mean,Weighted_SR,CI_Lower_95,CI_Upeer_95))

      elective_mean2<- weighted.mean(as.numeric(data[,4]),as.numeric(data[,3]),na.rm = F)
      elective_se2  <- ifelse(n>1, sqrt(sum((as.numeric(data[,4])-elective_mean2)^2)/(n*(n-1))), 0)
      elective_CI_l2<- elective_mean2 - 1.96*elective_se2
      elective_CI_h2<- elective_mean2 + 1.96*elective_se2

      Service_type2 <- c("Non-elective Long Stay")
      Weighted_mean2 <- round(c(elective_mean2),0)
      Weighted_SR2 <-  round(c(elective_se2),0)
      CI_Lower_952 <-  round(c(elective_CI_l2),0)
      CI_Upeer_952 <-  round(c(elective_CI_h2),0)

      costtable2 <- as.data.frame(rbind(Service_type2,Weighted_mean2,Weighted_SR2,CI_Lower_952,CI_Upeer_952))
      colnames(costtable2) <- "V2"
      if (is.null(input$somevalue2)) {costtable <- NULL
      }else if (length(input$somevalue2)==2){
        costtable <- cbind(costtable1,costtable2)
      }else{
        if (input$somevalue2=="Elective"){
          costtable <- costtable1
        }else {
          costtable <- costtable2
        }
      }
    }

    costtable

  })

  output$selectedrow_costs <- DT::renderDataTable({
    df=selectedrow_costsrows()})

}
shinyApp(ui = ui, server = server)


问:
SQL Error [91016] [22000]: Remote file 'stage_name/java_udf.jar' was not found
Created a jar file and use it as function. I created it with same user role for both function and snowflake stage. Uploaded the jar file to the stage using snowsql.

When I run the the following command in snowflake ui (browser), it works.

```<code>ls @~/stage_name
</code>```

However, when I use the service account with similar role that I have using DBeaver. It does not work. It comes up empty.

Same thing with the function, it works in the Snowflake UI, but not in DBeaver. Please note that both users have the same role. Also, added grant "all privileges" and "usage" (which be part of all) to the roles I want them to use. But again, it does not work. It shows error below

**> SQL Error [91016] [22000]: Remote file 'stage_name/java_udf.jar' was

not found. If you are running a copy command, please make sure files
are not deleted when they are being loaded or files are not being
loaded into two different tables concurrently with auto purge option.**

However, when I run the function in Snowflake UI using my user account, it works fine. Please note my user account has the same role as the service account. But it doesn't work on the service account. Any ideas?

Followed steps here in the documentation:
https://docs.snowflake.com/en/developer-guide/udf/java/udf-java-creating.html#label-udf-java-in-line-examples

答:
So I think I know the issue.

The stage could be shared using the same role. But the files uploaded in stage are not. They belong to the users who uploaded them. I just loaded exactly the same file a the same internal stage. And they did not overwrite each other:

Service Account:
name: xxxxxxx.jar
size: 389568
md5: be8b59593ae8c4b8baebaa8474bda0a7
last_modified: Tue, 8 Feb 2022 03:26:29 GMT

User account:
namne: xxxxxxx.jar
size: 389568
md5: 0c4d85a3a6581fa3007f0a4113570dbc
last_modified: Mon, 7 Feb 2022 17:03:58 GMT

Body:
Created a jar file and use it as function. I created it with same user role for both function and snowflake stage. Uploaded the jar file to the stage using snowsql.

When I run the the following command in snowflake ui (browser), it works.

ls @~/stage_name

However, when I use the service account with similar role that I have using DBeaver. It does not work. It comes up empty.

Same thing with the function, it works in the Snowflake UI, but not in DBeaver. Please note that both users have the same role. Also, added grant "all privileges" and "usage" (which be part of all) to the roles I want them to use. But again, it does not work. It shows error below

**> SQL Error [91016] [22000]: Remote file 'stage_name/java_udf.jar' was

not found. If you are running a copy command, please make sure files
are not deleted when they are being loaded or files are not being
loaded into two different tables concurrently with auto purge option.**

However, when I run the function in Snowflake UI using my user account, it works fine. Please note my user account has the same role as the service account. But it doesn't work on the service account. Any ideas?

Followed steps here in the documentation:
https://docs.snowflake.com/en/developer-guide/udf/java/udf-java-creating.html#label-udf-java-in-line-examples


问:
How can I read buffer data from the type script?(Solana)
How can I read buffer data from the type script?

I want to use the public key to get all the token lists I own.
I'm trying to get this, but an empty array of objects is being returned.

```<code>import {Connection, Keypair} from "@solana/web3.js";

const Solana = new Connection("https://api.testnet.solana.com/","confirmed")
const getInfo = async () => {
    const recentInfo = await Solana.getEpochInfo()
    const DEMO_FROM_SECRET_KEY = new Uint8Array([
       223, 119, 171,   5, 237, 138,  42, 140, 176, 163,  74,
      107,  25, 143,  90,  97, 250, 158, 203, 102, 238,  19,
       77, 228, 211, 238, 147, 149,  40,  50, 211, 155,  51,
      207,  14,  53,  86, 230, 164,  27,  14, 202,  78, 181,
      185, 250,  16,  52, 134, 242,  96,  16,  12,  67,   2,
      178, 106, 241, 156, 212,  11, 150, 114,  72])
    const keypair = Keypair.fromSecretKey(DEMO_FROM_SECRET_KEY)

    console.log("=============get account info==============")
    async function fetchaccountdata() {
        const accountinfo = await Solana.getParsedAccountInfo(keypair.publicKey,"max")
        const accountinfodata =  JSON.stringify(accountinfo)
        const accountinfodata2 = JSON.parse(accountinfodata)
        console.log(accountinfo)
        console.log("=============get account info==============")
        console.log(accountinfodata)
        console.log(accountinfodata2)
    }
    fetchaccountdata()
}
getInfo()
</code>```

Terminal is

```<code>accountinfodata = {"context":{"slot":94636033},"value":{"data":{"type":"Buffer","data":[]},"executable":false,"lamports":42784111360,"owner":{"_bn":"00"},"rentEpoch":231}}

accountinfodata2 = {
  context: { slot: 94636033 },
  value: {
    data: { type: 'Buffer', data: [] },
    executable: false,
    lamports: 42784111360,
    owner: { _bn: '00' },
    rentEpoch: 231
  }
}
</code>```

The data of accountinfo object is empty array.
How can I read the information?

答:
The buffer contains account info data in no particular format. Borsh has recently been established as a standard, though.

Example borsh serialization from SPL:
https://github.com/solana-labs/solana-program-library/blob/master/token/program/src/state.rs#L128

Example borsh deserialization for metaplex metadata: https://github.com/metaplex-foundation/metaplex-program-library/blob/master/token-metadata/program/src/instruction.rs#L77-L78

If you aren't trying to decode metaplex metadata, you should look elsewhere for the schema, but follow the same principles of the code. If you know the account isn't using borsh, then it's up to you to decode it.

Visit the solana tech discord for more information/help.
https://discord.com/channels/428295358100013066/517163444747894795/917412508418068510

Body:
How can I read buffer data from the type script?

I want to use the public key to get all the token lists I own.
I'm trying to get this, but an empty array of objects is being returned.

import {Connection, Keypair} from "@solana/web3.js";

const Solana = new Connection("https://api.testnet.solana.com/","confirmed")
const getInfo = async () => {
    const recentInfo = await Solana.getEpochInfo()
    const DEMO_FROM_SECRET_KEY = new Uint8Array([
       223, 119, 171,   5, 237, 138,  42, 140, 176, 163,  74,
      107,  25, 143,  90,  97, 250, 158, 203, 102, 238,  19,
       77, 228, 211, 238, 147, 149,  40,  50, 211, 155,  51,
      207,  14,  53,  86, 230, 164,  27,  14, 202,  78, 181,
      185, 250,  16,  52, 134, 242,  96,  16,  12,  67,   2,
      178, 106, 241, 156, 212,  11, 150, 114,  72])
    const keypair = Keypair.fromSecretKey(DEMO_FROM_SECRET_KEY)

    console.log("=============get account info==============")
    async function fetchaccountdata() {
        const accountinfo = await Solana.getParsedAccountInfo(keypair.publicKey,"max")
        const accountinfodata =  JSON.stringify(accountinfo)
        const accountinfodata2 = JSON.parse(accountinfodata)
        console.log(accountinfo)
        console.log("=============get account info==============")
        console.log(accountinfodata)
        console.log(accountinfodata2)
    }
    fetchaccountdata()
}
getInfo()

Terminal is

accountinfodata = {"context":{"slot":94636033},"value":{"data":{"type":"Buffer","data":[]},"executable":false,"lamports":42784111360,"owner":{"_bn":"00"},"rentEpoch":231}}

accountinfodata2 = {
  context: { slot: 94636033 },
  value: {
    data: { type: 'Buffer', data: [] },
    executable: false,
    lamports: 42784111360,
    owner: { _bn: '00' },
    rentEpoch: 231
  }
}

The data of accountinfo object is empty array.
How can I read the information?


问:
ImportXML extract table into Google Sheets
I'm trying to extract the whole following Warcraftlog table in a Google Sheets.
I just need the "names" with "count" and the "percentage numbers".

```<code>=IMPORTXML("URL"; "XPATH")
=IMPORTXML("https://classic.warcraftlogs.com/reports/P4CQdFTp21wADfKX/#boss=-3&difficulty=0&type=auras&ability=31035"; "//table[contains(@id,'main-table-0')]")
</code>```

But it doesn't work with //table[contains(@id,'main-table-0')] in the Xpath.
With //table/tr/td it will extract nearly everything on the warcraftlog website, except the table I want to extract.

Is there another option to extract them with XPath?

答:
You are after an html table so switch to IMPORTHTML

Data is pulled dynamically from another endpoint you can find in the network tab of the browser, so make your request to that

The last two webpage visible table columns are $ delimited in the retrieved table so you will need to split the entries e.g. using helper column in column D of sheet (if formula in A1) containing SPLIT

```<code>=IMPORTHTML("https://classic.warcraftlogs.com/reports/auras/P4CQdFTp21wADfKX/0/0/6175385/buffs/31035/0/0/0/0/source/0/-3.0.0/0/Any/Any/0", "table",1)
</code>```

Body:
I'm trying to extract the whole following Warcraftlog table in a Google Sheets.
I just need the "names" with "count" and the "percentage numbers".

=IMPORTXML("URL"; "XPATH")
=IMPORTXML("https://classic.warcraftlogs.com/reports/P4CQdFTp21wADfKX/#boss=-3&difficulty=0&type=auras&ability=31035"; "//table[contains(@id,'main-table-0')]")

But it doesn't work with //table[contains(@id,'main-table-0')] in the Xpath.
With //table/tr/td it will extract nearly everything on the warcraftlog website, except the table I want to extract.

Is there another option to extract them with XPath?

Body:
You are after an html table so switch to IMPORTHTML

Data is pulled dynamically from another endpoint you can find in the network tab of the browser, so make your request to that

The last two webpage visible table columns are $ delimited in the retrieved table so you will need to split the entries e.g. using helper column in column D of sheet (if formula in A1) containing SPLIT

=IMPORTHTML("https://classic.warcraftlogs.com/reports/auras/P4CQdFTp21wADfKX/0/0/6175385/buffs/31035/0/0/0/0/source/0/-3.0.0/0/Any/Any/0", "table",1)


问:
Code standard (not style) enforcer for Eclipse
Is there some coding standard enforcer for use with Eclipse (a plugin or something)? I know I can use "Window > Preferences > [Language] > Code Style" to suggest conventions, but these are not enforced.

In other words, I want Coding standard violations to be marked as "Errors" and Coding style violations as "Warnings".

Thanks and regards,
Karthick S.

答:
You got several options to do that :

PMD http://pmd.sourceforge.net/eclipse/

Eclipse Checkstyle http://checkstyle.sourceforge.net/

Findbugs http://findbugs.sourceforge.net/

You  can also integrate these plugins with your CI Server, for example Sonar For Hudson. Note that since 2011, Hudson has changed it's name to Jenkins. http://wiki.hudson-ci.org/display/HUDSON/Sonar+plugin


问:
Firebase Admin SDK with Cloud functions for cloud storage
I am trying to use the fire base admin SDK with cloud storage so I can upload images from the server side. For some reason when I type in admin.storage() my functions refuse to upload. I have everything set up well but for some reason that's the only thing that is not working.

答:
I was able to deploy your code on Firebase Cloud Functions by making some adjustments. If I'm not mistaken the error you encountered is:

```<code>Error: Error occurred while parsing your function triggers. Please ensure that admin.js only exports cloud functions.
</code>```

The error is saying that you can only export functions. You cannot export declarations such as const.

ES modules support only several syntax variations in order to be statically analyzed.
According to export documentation, the variations are:

```<code>// Exporting individual features
export let name1, name2, …, nameN; // also var, const
export let name1 = …, name2 = …, …, nameN; // also var, const
export function functionName(){...}
export class ClassName {...}

// Export list
export { name1, name2, …, nameN };

// Renaming exports
export { variable1 as name1, variable2 as name2, …, nameN };

// Exporting destructured assignments with renaming
export const { name1, name2: bar } = o;

// Default exports
export default expression;
export default function (…) { … } // also class, function*
export default function name1(…) { … } // also class, function*
export { name1 as default, … };

// Aggregating modules
export * from …; // does not set the default export
export * as name1 from …; // ECMAScript® 2O20
export { name1, name2, …, nameN } from …;
export { import1 as name1, import2 as name2, …, nameN } from …;
export { default, … } from …;
</code>```

export foo is not among them. It is not supported and cannot be used.

You can fix the error by removing firebase-admin on admin.js.

Create a new js file. For this instance, I used test.js. Refer to the below code:

```<code>const admin = require("firebase-admin");
admin.initializeApp();

module.exports = {
    admin
};
</code>```

On your admin.js:

```<code>const functions = require("firebase-functions");
const {admin} = require("./test");

const db = admin.firestore();
const firestore = admin.firestore;
const auth = admin.auth();
const storage = admin.storage().bucket();

module.exports = {
    db,
    firestore,
    auth,
    storage
};
</code>```

For uploading objects to Google Cloud Storage, add the target Bucket on the newly created js:

```<code>const admin = require("firebase-admin");
admin.initializeApp(
    {
        storageBucket: "bucket-name"
    }
);

module.exports = {
    admin
};
</code>```

Then on your admin.js, refer on below code:

```<code>const functions = require("firebase-functions");
const {admin} = require("./test");

const db = admin.firestore();
const firestore = admin.firestore;
const auth = admin.auth();
const storage = admin.storage().bucket();

// Uploads object to Google Cloud Storage
storage.upload(filePath, {
    destination: destFileName,
  }).then(data => {
    console.log('upload success');
}).catch(err => {
    console.log('error uploading to storage', err);
});

module.exports = {
    db,
    firestore,
    auth,
    storage
};
</code>```

You may also check Upload an object documentation for more information.

Body:
I was able to deploy your code on Firebase Cloud Functions by making some adjustments. If I'm not mistaken the error you encountered is:

Error: Error occurred while parsing your function triggers. Please ensure that admin.js only exports cloud functions.

The error is saying that you can only export functions. You cannot export declarations such as const.

ES modules support only several syntax variations in order to be statically analyzed.
According to export documentation, the variations are:

// Exporting individual features
export let name1, name2, …, nameN; // also var, const
export let name1 = …, name2 = …, …, nameN; // also var, const
export function functionName(){...}
export class ClassName {...}

// Export list
export { name1, name2, …, nameN };

// Renaming exports
export { variable1 as name1, variable2 as name2, …, nameN };

// Exporting destructured assignments with renaming
export const { name1, name2: bar } = o;

// Default exports
export default expression;
export default function (…) { … } // also class, function*
export default function name1(…) { … } // also class, function*
export { name1 as default, … };

// Aggregating modules
export * from …; // does not set the default export
export * as name1 from …; // ECMAScript® 2O20
export { name1, name2, …, nameN } from …;
export { import1 as name1, import2 as name2, …, nameN } from …;
export { default, … } from …;

export foo is not among them. It is not supported and cannot be used.

You can fix the error by removing firebase-admin on admin.js.

Create a new js file. For this instance, I used test.js. Refer to the below code:

const admin = require("firebase-admin");
admin.initializeApp();

module.exports = {
    admin
};

On your admin.js:

const functions = require("firebase-functions");
const {admin} = require("./test");

const db = admin.firestore();
const firestore = admin.firestore;
const auth = admin.auth();
const storage = admin.storage().bucket();

module.exports = {
    db,
    firestore,
    auth,
    storage
};

For uploading objects to Google Cloud Storage, add the target Bucket on the newly created js:

const admin = require("firebase-admin");
admin.initializeApp(
    {
        storageBucket: "bucket-name"
    }
);

module.exports = {
    admin
};

Then on your admin.js, refer on below code:

const functions = require("firebase-functions");
const {admin} = require("./test");

const db = admin.firestore();
const firestore = admin.firestore;
const auth = admin.auth();
const storage = admin.storage().bucket();

// Uploads object to Google Cloud Storage
storage.upload(filePath, {
    destination: destFileName,
  }).then(data => {
    console.log('upload success');
}).catch(err => {
    console.log('error uploading to storage', err);
});

module.exports = {
    db,
    firestore,
    auth,
    storage
};

You may also check Upload an object documentation for more information.


问:
Splitting a string and retaining the separator (without RegEx)
I have the following string foo:

```<code>foo = 'F9B2Z1F8B30Z4'
</code>```

Without using re, I'd like to split on 'F' and then add 'F' back to the resulting list.

My attempt is:

```<code>['F'+elem for elem in foo.split('F')]
</code>```

This gives us:

```<code>['F', 'F9B2Z1', 'F8B30Z4']
</code>```

But, I was expecting:

```<code>['F9B2Z1', 'F8B30Z4']
</code>```

Is it possible to modify the list comprehension to catch this case?  If not, is there another approach that I can use?

Thanks!

答:
Actually your problem might be more amenable to use re.findall:

foo = 'F9B2Z1F8B30Z4'
parts = re.findall(r'F[^\WF]*', foo)
print(parts)  # ['F9B2Z1', 'F8B30Z4']
```
<p>The regex pattern matches a leading <code>F</code> followed by zero or more word characters, which are not <code>F</code>.</p>
<p>To do this using non regex split, we can slightly modify your list comprehension to only retain non empty string elements from the split:</p>
<pre class="lang-py prettyprint-override"><code>parts = ['F' + elem for elem in foo.split('F') if elem != '']
print(parts)  # ['F9B2Z1', 'F8B30Z4']
</code>```

Body:
I have the following string foo:

foo = 'F9B2Z1F8B30Z4'

Without using re, I'd like to split on 'F' and then add 'F' back to the resulting list.

My attempt is:

['F'+elem for elem in foo.split('F')]

This gives us:

['F', 'F9B2Z1', 'F8B30Z4']

But, I was expecting:

['F9B2Z1', 'F8B30Z4']

Is it possible to modify the list comprehension to catch this case?  If not, is there another approach that I can use?

Thanks!

Body:
Actually your problem might be more amenable to use re.findall:

foo = 'F9B2Z1F8B30Z4'
parts = re.findall(r'F[^\WF]*', foo)
print(parts)  # ['F9B2Z1', 'F8B30Z4']

The regex pattern matches a leading F followed by zero or more word characters, which are not F.

To do this using non regex split, we can slightly modify your list comprehension to only retain non empty string elements from the split:

parts = ['F' + elem for elem in foo.split('F') if elem != '']
print(parts)  # ['F9B2Z1', 'F8B30Z4']