答:
Would this work? I'm using time.time() which returns the number of seconds since the epoch.

```<code>import random
import time

listnum = int(input("What size list would you like? "))
randomlist = random.sample(range(0, 5000), listnum)
print(randomlist)
sort_i = input("Would you like to sort your list Y or N? ")

if sort_i == "Y":
    search_i = input("Bubble sort or Insertion sort? ")
    st = time.time() # Start time in seconds
    if search_i == "Bubble sort":
        for i in range(len(randomlist) - 1, 0, -1):
            for j in range(i):
                if randomlist[j] > randomlist[j + 1]:
                    randomlist[j], randomlist[j + 1] = randomlist[j + 1], randomlist[j]

    if search_i == "Insertion sort":
        for i in range(1, len(randomlist)):
            key = randomlist[i]
            j = i - 1
            while j >= 0 and key < randomlist[j]:
                randomlist[j + 1] = randomlist[j]
                j -= 1
            randomlist[j + 1] = key
    et = time.time() # End time in seconds
    print(randomlist)
    print(f"Time taken to sort in seconds: {et - st}")
elif sort_i == "N":

    lin_search_num = int(input("What number would you like to linear search? "))
    st = time.time()
    for s in range(len(randomlist)):
        if randomlist[s] == lin_search_num:
            print("Your number is at index " + str(s + 1))
            print(f"Took {time.time() - st} seconds.")
</code>```

Title: Time sorting in python

Body:
Would this work? I'm using time.time() which returns the number of seconds since the epoch.

import random
import time

listnum = int(input("What size list would you like? "))
randomlist = random.sample(range(0, 5000), listnum)
print(randomlist)
sort_i = input("Would you like to sort your list Y or N? ")

if sort_i == "Y":
    search_i = input("Bubble sort or Insertion sort? ")
    st = time.time() # Start time in seconds
    if search_i == "Bubble sort":
        for i in range(len(randomlist) - 1, 0, -1):
            for j in range(i):
                if randomlist[j] > randomlist[j + 1]:
                    randomlist[j], randomlist[j + 1] = randomlist[j + 1], randomlist[j]

    if search_i == "Insertion sort":
        for i in range(1, len(randomlist)):
            key = randomlist[i]
            j = i - 1
            while j >= 0 and key < randomlist[j]:
                randomlist[j + 1] = randomlist[j]
                j -= 1
            randomlist[j + 1] = key
    et = time.time() # End time in seconds
    print(randomlist)
    print(f"Time taken to sort in seconds: {et - st}")
elif sort_i == "N":

    lin_search_num = int(input("What number would you like to linear search? "))
    st = time.time()
    for s in range(len(randomlist)):
        if randomlist[s] == lin_search_num:
            print("Your number is at index " + str(s + 1))
            print(f"Took {time.time() - st} seconds.")


来源: stackexchange

问:
Pandas not appending values to data frame
I have a file called balance.csv. It contains user data such as their discord ID number, their account balance, and the amount of stocks that they own. I'm trying to create a simple command using discord.py that lets them know their account balance. If they don't have an account, it initializes one for them. However, the values aren't being appended to the CSV file when the code tries to initialize the account. I am not sure where the problem is and why it is occurring. I'm using pandas and discord.py.</p>
```<code>balance_data = pd.read_csv('balance.csv')

def init_account(id):
    global balance_data
    balance_data = balance_data.append({"user_id":id, "account_balance":100, "stocks":0}, ignore_index=True)

@client.command(name='bal')
async def balance(ctx):
    if ctx.author.id not in balance_data["user_id"].values:
        await ctx.send("Creating Account...")
        init_account(ctx.author.id)
        await ctx.send("Account created.")
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")
    else:
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")
</code>```

答: The dataframe and the CSV file are two separate things.  Just because you read the dataframe from a file doesn't mean that modifying the dataframe will modify the file.  It does not create any kind of persistent "sync" between the dataframe and the file.  If you want to change the file, you need to use .to_csv to write back out to the file.

ContentLicense: CC BY-SA 4.0

Body:
I have a file called balance.csv. It contains user data such as their discord ID number, their account balance, and the amount of stocks that they own. I'm trying to create a simple command using discord.py that lets them know their account balance. If they don't have an account, it initializes one for them. However, the values aren't being appended to the CSV file when the code tries to initialize the account. I am not sure where the problem is and why it is occurring. I'm using pandas and discord.py.

balance_data = pd.read_csv('balance.csv')

def init_account(id):
    global balance_data
    balance_data = balance_data.append({"user_id":id, "account_balance":100, "stocks":0}, ignore_index=True)

@client.command(name='bal')
async def balance(ctx):
    if ctx.author.id not in balance_data["user_id"].values:
        await ctx.send("Creating Account...")
        init_account(ctx.author.id)
        await ctx.send("Account created.")
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")
    else:
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")


问:
TypeError: Cannot read properties of undefined (reading 'total')
I've been working on a React project along with fetching Data from rapidAPI.
But whenever I rum my project I've been getting this error again and again.

```<code>TypeError: Cannot read properties of undefined (reading 'total')
Homepage
src/components/Homepage.jsx:23
  20 | <>
  21 |   <Title level={2} className="heading">Global Crypto Stats</Title>
  22 |   <Row gutter={[32, 32]}>
> 23 |     <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
     | ^  24 |     <Col span={12}><Statistic title="Total Exchanges" value={millify(globalStats.totalExchanges)} /></Col>
  25 |     <Col span={12}><Statistic title="Total Market Cap:" value={`$${millify(globalStats.totalMarketCap)}`} /></Col>
  26 |     <Col span={12}><Statistic title="Total 24h Volume" value={`$${millify(globalStats.total24hVolume)}`} /></Col>
</code>```

Here are the files that I've been looking in to debug.

App.js

```<code>import React from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import { Layout, Typography, Space } from 'antd';

import { Exchanges, Homepage, News, Cryptocurrencies, CryptoDetails, Navbar } from './components';
import './App.css';

const App = () => (
  <div className="app">
    <div className="navbar">
      <Navbar />
    </div>
    <div className="main">
      <Layout>
        <div className="routes">
          <Switch>
            <Route exact path="/">
              <Homepage />
            </Route>
            <Route exact path="/exchanges">
              <Exchanges />
            </Route>
            <Route exact path="/cryptocurrencies">
              <Cryptocurrencies />
            </Route>
            <Route exact path="/crypto/:coinId">
              <CryptoDetails />
            </Route>
            <Route exact path="/news">
              <News />
            </Route>
          </Switch>
        </div>
      </Layout>
      <div className="footer">
        <Typography.Title level={5} style={{ color: 'white', textAlign: 'center' }}>Copyright © 2021
          <Link to="/">
            Cryptoverse Inc.
          </Link> <br />
          All Rights Reserved.
        </Typography.Title>
        <Space>
          <Link to="/">Home</Link>
          <Link to="/exchanges">Exchanges</Link>
          <Link to="/news">News</Link>
        </Space>
      </div>
    </div>
  </div>
);

export default App;
</code>```

Homepage.jsx

```<code>import React from 'react';
import millify from 'millify';
import { Typography, Row, Col, Statistic } from 'antd';
import { Link } from 'react-router-dom';

import { useGetCryptosQuery } from '../services/cryptoApi';
import Cryptocurrencies from './Cryptocurrencies';
import News from './News';
import Loader from './Loader';

const { Title } = Typography;

const Homepage = () => {
  const { data, isFetching } = useGetCryptosQuery(10);
  const globalStats = data?.data?.stats;

  if (isFetching) return <Loader />;

  return (
    <>
      <Title level={2} className="heading">Global Crypto Stats</Title>
      <Row gutter={[32, 32]}>
        <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
        <Col span={12}><Statistic title="Total Exchanges" value={millify(globalStats.totalExchanges)} /></Col>
        <Col span={12}><Statistic title="Total Market Cap:" value={`$${millify(globalStats.totalMarketCap)}`} /></Col>
        <Col span={12}><Statistic title="Total 24h Volume" value={`$${millify(globalStats.total24hVolume)}`} /></Col>
        <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
        <Col span={12}><Statistic title="Total Markets" value={millify(globalStats.totalMarkets)} /></Col>
      </Row>
      <div className="home-heading-container">
        <Title level={2} className="home-title">Top 10 Cryptos In The World</Title>
        <Title level={3} className="show-more"><Link to="/cryptocurrencies">Show more</Link></Title>
      </div>
      <Cryptocurrencies simplified />
      <div className="home-heading-container">
        <Title level={2} className="home-title">Latest Crypto News</Title>
        <Title level={3}><Link to="/news">Show more</Link></Title>
      </div>
      <News simplified />
    </>
  );
};

export default Homepage;
</code>```

services/cryptoApi.js

```<code>import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const cryptoApiHeaders = {
    'x-rapidapi-host': 'coinranking1.p.rapidapi.com',
    'x-rapidapi-key': '268c978691mshf443e1a9132dfdep1f3fe3jsn953b6183c440',
};

const baseUrl = 'https://coinranking1.p.rapidapi.com';

const createRequest = (url) => ({ url, headers: cryptoApiHeaders });

export const cryptoApi = createApi({
    reducerPath: 'cryptoApi',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
      getCryptos: builder.query({
        query: (count) => createRequest(`/coins/?limit=${count}`),
      }),
      getExchanges: builder.query({
        query: () => createRequest('/exchanges'),
      }),
      getCryptoDetails: builder.query({
        query: (coinId) => createRequest(`/coin/${coinId}`),
      }),
      getCryptoHistory: builder.query({
        query: ({ coinId, timeperiod }) => createRequest(`coin/${coinId}/history/${timeperiod}`),
      }),
    }),
  });

export const {
    useGetCryptosQuery,
    useGetCryptoDetailsQuery,
    useGetCryptoHistoryQuery,
    useGetExchangesQuery,
} = cryptoApi;
</code>```

I've tried a lot but the situation continues.
Any help would be highly appreciated.
Thank You in advance.

答:
Looks like in the Homepage.jsx when you call globalStats - it's undefined.

You can either check if the object exists, using the question mark:

```<code><Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats?.total} />
</code>```

or you can add a check outside of the fragment, to display the content only if  globalStats exists:

```<code>return globalStats ? (<><Title>Global Crypto Stats</Title><>the rest...</></>) : null;
</code>```

Body:
I've been working on a React project along with fetching Data from rapidAPI.
But whenever I rum my project I've been getting this error again and again.

TypeError: Cannot read properties of undefined (reading 'total')
Homepage
src/components/Homepage.jsx:23
  20 | <>
  21 |   <Title level={2} className="heading">Global Crypto Stats</Title>
  22 |   <Row gutter={[32, 32]}>
> 23 |     <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
     | ^  24 |     <Col span={12}><Statistic title="Total Exchanges" value={millify(globalStats.totalExchanges)} /></Col>
  25 |     <Col span={12}><Statistic title="Total Market Cap:" value={`$${millify(globalStats.totalMarketCap)}`} /></Col>
  26 |     <Col span={12}><Statistic title="Total 24h Volume" value={`$${millify(globalStats.total24hVolume)}`} /></Col>

Here are the files that I've been looking in to debug.

App.js

import React from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import { Layout, Typography, Space } from 'antd';

import { Exchanges, Homepage, News, Cryptocurrencies, CryptoDetails, Navbar } from './components';
import './App.css';

const App = () => (

      <Navbar />

      <Layout>

          <Switch>
            <Route exact path="/">
              <Homepage />
            </Route>
            <Route exact path="/exchanges">
              <Exchanges />
            </Route>
            <Route exact path="/cryptocurrencies">
              <Cryptocurrencies />
            </Route>
            <Route exact path="/crypto/:coinId">
              <CryptoDetails />
            </Route>
            <Route exact path="/news">
              <News />
            </Route>
          </Switch>

      </Layout>

        <Typography.Title level={5} style={{ color: 'white', textAlign: 'center' }}>Copyright © 2021
          <Link to="/">
            Cryptoverse Inc.
          </Link>

          All Rights Reserved.
        </Typography.Title>
        <Space>
          <Link to="/">Home</Link>
          <Link to="/exchanges">Exchanges</Link>
          <Link to="/news">News</Link>
        </Space>

);

export default App;

Homepage.jsx

import React from 'react';
import millify from 'millify';
import { Typography, Row, Col, Statistic } from 'antd';
import { Link } from 'react-router-dom';

import { useGetCryptosQuery } from '../services/cryptoApi';
import Cryptocurrencies from './Cryptocurrencies';
import News from './News';
import Loader from './Loader';

const { Title } = Typography;

const Homepage = () => {
  const { data, isFetching } = useGetCryptosQuery(10);
  const globalStats = data?.data?.stats;

  if (isFetching) return <Loader />;

  return (
    <>
      <Title level={2} className="heading">Global Crypto Stats</Title>
      <Row gutter={[32, 32]}>
        <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
        <Col span={12}><Statistic title="Total Exchanges" value={millify(globalStats.totalExchanges)} /></Col>
        <Col span={12}><Statistic title="Total Market Cap:" value={`$${millify(globalStats.totalMarketCap)}`} /></Col>
        <Col span={12}><Statistic title="Total 24h Volume" value={`$${millify(globalStats.total24hVolume)}`} /></Col>
        <Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats.total} /></Col>
        <Col span={12}><Statistic title="Total Markets" value={millify(globalStats.totalMarkets)} /></Col>
      </Row>

        <Title level={2} className="home-title">Top 10 Cryptos In The World</Title>
        <Title level={3} className="show-more"><Link to="/cryptocurrencies">Show more</Link></Title>

      <Cryptocurrencies simplified />

        <Title level={2} className="home-title">Latest Crypto News</Title>
        <Title level={3}><Link to="/news">Show more</Link></Title>

      <News simplified />
    </>
  );
};

export default Homepage;

services/cryptoApi.js

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const cryptoApiHeaders = {
    'x-rapidapi-host': 'coinranking1.p.rapidapi.com',
    'x-rapidapi-key': '268c978691mshf443e1a9132dfdep1f3fe3jsn953b6183c440',
};

const baseUrl = 'https://coinranking1.p.rapidapi.com';

const createRequest = (url) => ({ url, headers: cryptoApiHeaders });

export const cryptoApi = createApi({
    reducerPath: 'cryptoApi',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
      getCryptos: builder.query({
        query: (count) => createRequest(`/coins/?limit=${count}`),
      }),
      getExchanges: builder.query({
        query: () => createRequest('/exchanges'),
      }),
      getCryptoDetails: builder.query({
        query: (coinId) => createRequest(`/coin/${coinId}`),
      }),
      getCryptoHistory: builder.query({
        query: ({ coinId, timeperiod }) => createRequest(`coin/${coinId}/history/${timeperiod}`),
      }),
    }),
  });

export const {
    useGetCryptosQuery,
    useGetCryptoDetailsQuery,
    useGetCryptoHistoryQuery,
    useGetExchangesQuery,
} = cryptoApi;

I've tried a lot but the situation continues.
Any help would be highly appreciated.
Thank You in advance.

Body:
Looks like in the Homepage.jsx when you call globalStats - it's undefined.

You can either check if the object exists, using the question mark:

<Col span={12}><Statistic title="Total Cryptocurrencies" value={globalStats?.total} />

or you can add a check outside of the fragment, to display the content only if  globalStats exists:

return globalStats ? (<><Title>Global Crypto Stats</Title><>the rest...</></>) : null;


问:
Can I selectively (force) inline a function?
In the book Clean Code (and a couple of others I have come across and read) it is suggested to keep the functions small and break them up if they become large. It also suggests that functions should do one thing and one thing only.

In Optimizing software in C++ Agner Fog states that he does not like the rule of breaking up a function just because it crosses a certain threshold of a number of lines. He states that this results in unnecessary jumps which degrade performance.

First off, I understand that it will not matter if the code I am working on is not in a tight loop and that the functions are heavy so that the time it takes to call them is dwarfed by the time the code in the function takes to execute. But let's assume that I am working with functions that are, most of the time, used by other objects/functions and are performing relatively trivial tasks. These functions follow the suggestions listed in the first paragraph (that is, perform one single function and are small/comprehensible). Then I start programming a performance critical function that utilizes these other functions in a tight loop and is essentially a frame function. Lastly, assume that in-lining them has a benefit for the performance critical function but no benefit whatsoever to any other function (yes, I have profiled this, albeit with a lot of copying and pasting which I want to avoid).

Immediately, one can say that tag the function inline and let the compiler choose. But what if I don't want all those functions to be in a `.inl file or exposed in the header? In my current situation, the performance critical functions and the other functions it uses are all in the same source file.

To sum it up, can I selectively (force) inline a function(s) for a single function so that the end code behaves like it is one big function instead of several calls to other functions.

答:
Compilers are actually really really good at generating optimized code.

I would suggest just organizing your code into logical groupings (using additional functions if that enhanced readability), marking them inline if appropriate, and letting the compiler decide what code to optimally generate.

ContentLicense: CC BY-SA 3.0


问:
Azure CLI - Azure Advisor Recommendation - does not have cost data for 'Microsoft.Compute/virtualMachines'
I was using az cli to get the Azure advisor recommendation data

```<code>az advisor recommendation list  --category cost  --subscription ************* -o json --query  "[?impactedField == 'Microsoft.Compute/virtualMachines'].{resource: impactedValue, cat: category, cpu:  extendedProperties.MaxCpuP95 , memory:  extendedProperties.MaxMemoryP95, saving:  extendedProperties.savingsAmount, Recommendation: shortDescription.solution }"
</code>```

While downloading pdf from portal it has "Potential savings/yr" . I found az cli is retuning  different output for "Reserve Instances Recommendation" but for VM's it does not have cost related information.

答:
You can use the below PowerShell cmdlet to pull the Potential savings of the virtual machine's in the subscription.</p>
```<code>Get-AzAdvisorRecommendation -Category Cost | Where-Object {$_.ImpactedField -eq "Microsoft.Compute/virtualMachines"} | Select-Object -ExpandProperty ExtendedProperties
</code>```

Body:
I was using az cli to get the Azure advisor recommendation data

az advisor recommendation list  --category cost  --subscription ************* -o json --query  "[?impactedField == 'Microsoft.Compute/virtualMachines'].{resource: impactedValue, cat: category, cpu:  extendedProperties.MaxCpuP95 , memory:  extendedProperties.MaxMemoryP95, saving:  extendedProperties.savingsAmount, Recommendation: shortDescription.solution }"

While downloading pdf from portal it has "Potential savings/yr" . I found az cli is retuning  different output for "Reserve Instances Recommendation" but for VM's it does not have cost related information.

Body:
You can use the below PowerShell cmdlet to pull the Potential savings of the virtual machine's in the subscription.

Get-AzAdvisorRecommendation -Category Cost | Where-Object {$_.ImpactedField -eq "Microsoft.Compute/virtualMachines"} | Select-Object -ExpandProperty ExtendedProperties


问:
Detection of reload button pressed in Java Script
How to detect whether the reload button is pressed and after that the the processes be held and after that reload. Like when reload is pressed or Ctrl + R then I want to save that it is reloaded in local storage.</p>

答:
To save localStorage in browser on reload/refresh of page.

Add Javascript code as below

```<code>window.onload = function () {
    alert(localStorage.variable) //comment this line to avoid alert box
    localStorage.setItem("variable", "set a variable value");
}
</code>```

Body:
To save localStorage in browser on reload/refresh of page.

Add Javascript code as below

window.onload = function () {
    alert(localStorage.variable) //comment this line to avoid alert box
    localStorage.setItem("variable", "set a variable value");
}


问:
calculate age from birthdate in java

Main.java:6: error: class BirthDate is public, should be declared in a file named BirthDate.java
public class BirthDate {
       ^
1 error

Process exited - Return Code: 1
```
<p>The code:</p>
<pre class="lang-java prettyprint-override"><code>package birthdate;

import java.time.*;
import java.util.Scanner;

public class BirthDate {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter your birth date (yyyy-mm-dd format only) ");
        String st = sc.nextLine();
        LocalDate Dob;
        Dob = LocalDate.parse(st);
        System.out.println("Age is :- "+calcAge(Dob));
    }

    static int calcAge(LocalDate Dob)
    {
        LocalDate currentDate = LocalDate.now();
        int age = Period.between(Dob,currentDate).getYears();
        return age;
    }
}
</code>```

答:
The error message tells you the problem.

Main.java:6: error: class BirthDate is public, should be declared in a file named BirthDate.java

Rename your file from Main.java to match the name of the class, BirthDate.java.

Title: calculate age from birthdate in java

Body:
Main.java:6: error: class BirthDate is public, should be declared in a file named BirthDate.java
public class BirthDate {
       ^
1 error

Process exited - Return Code: 1

The code:

package birthdate;

import java.time.*;
import java.util.Scanner;

public class BirthDate {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter your birth date (yyyy-mm-dd format only) ");
        String st = sc.nextLine();
        LocalDate Dob;
        Dob = LocalDate.parse(st);
        System.out.println("Age is :- "+calcAge(Dob));
    }

    static int calcAge(LocalDate Dob)
    {
        LocalDate currentDate = LocalDate.now();
        int age = Period.between(Dob,currentDate).getYears();
        return age;
    }
}


问:
Android save View position on orientation changed

Possible Duplicate:

  Android - disable landscape mode?

I can't save position of view when orientation changes.
I think it's because with orientation it also changes and I want that view stayed on the same position. For example of it was in the upper left corner of screen it stayed there and it doesn't matter what orientation of the device.
I'm using some kind of Absolute layout. Because I need to manage few screens at the same time.
So, i have x/y coordinate system. I think it's the main problem, but I can't solve it :(

I've attached images that you could see my problem.
As you can see first screen is portrait mode and View is located in upper-left corner, but when I changed to landscape mode position of view is also changed to upper-right corner.
And I need that position of view stayed always in left-upper corner.

http://imgur.com/qo19E&u2K0hl

http://imgur.com/qo19El&u2K0h

Sorry to bad screen. I'm still developing of an application and can't provide better screens :)

Ps: If you need some code, just say what part of code do you need.

答:
Duplicate of Android - disable landscape mode?

You can force the activity to run in a particular orientation.
Inside the AndroidManifest.xml use the attribute "android:screenOrientation"

See here for an example:
http://developer.android.com/guide/topics/manifest/activity-element.html


问:
Adding instrumentation (aka injecting into scripts) using chrome extensions
My goal is to inject instrumentation code into certain scripts of certain websites to then lately collect the data using chrome extension and upload it to a centralized DB.

The last time I tried this was around 2016 when I achieved this using "onbeforescriptexecute" in a user script I added to firefox using GreaseMonkey, back then chrome didn't support this at all. Now I've looked around here and the newest I found was around the same yeah mentioning "onbeforescriptexecute" is not supported in chrome and offering a workaround with a link to a GitHub page that no longer exists.

So are there any modern ways to intercept scripts loading into a web page in chrome extension content script? What I need is to catch each script before it loads, parse, inject instrumentation and then proceed to run it.

答:
From what I understand, you want to intercept every script and manipulate the contents of the script before it is being executed in the browser.

The short answer is No. You cannot intercept external scripts using Chrome Extension Content Scripts but you can intercept using webRequestAPI in Manifest V2 (Note - It's going away soon)

Your best bet is to write a Proxy application that intercepts the scripts and modifies the contents of the scripts as per the User or your business logic.

We have solved a similar problem at Requestly by offering a desktop app-based solution So you can launch a browser from the Requestly Desktop App and then create Modify Response Rule in the Desktop App which allows you to define a static response or change the existing response pragmatically.

Launching Apps

Modifying Response Pragmatically

Once you do this, your scripts will be intercepted and your code will run on top of the existing responses from the server.

You can build a similar application like this for your case. I am afraid this isn't possible with Chrome Extensions.


问:
how to create non-spa website only using react js?
I have a simple test project using react that shows users of fake API. The parent component is named App and it's my home page. There is a button named panel in the App component. I want it to go to Panel Component when I click it.

```<code>function App() {
const users = useSelector(state => state.users)
 const dispatch = useDispatch();
    const getUsers=()=>{
        // async action using redux-thunk
        return async function(dispatch){
            try{

            dispatch(GetUserRequest())
             const response= await axios.get("https://reqres.in/api/users?page=2")

             dispatch(GetUserSuccess(response.data.data))
            }
            catch(er){
                dispatch(GetUserFail(er))

            }
        }
    }
useEffect(()=>{

    dispatch(getUsers())
 }

  ,[])
  return (<>
 <Provider store={store}>
 <Routes>
<Route path="users" element={<Users Items={users}/>}/>
<Route path="/Panel" element={<Panel/>}/>
</Routes>

 <button className='btn btn-primary' onClick={()=>{
  navigate("/Panel")

}}>Panel</button>
<Users/>

</>
</code>```

It's simple, But I want the Panel component to be a separate page instead of being part of the home page! And I don't want to show other components (in my project User component)

So I tried a trick: using showPages state to determine which page should be shown:

```<code>function App() {
 const users = useSelector(state => state.users)
const[showPages,setShowPages]=useState("users")
  useEffect(()=>{

    setShowPages("users")
    dispatch(getUsers())
  }

  ,[])
 return (<>
<button className='btn btn-primary' onClick={()=>{
 setShowPages("panel")

}}>Panel</button>
 {showPages=="users" && ( <Users/> Items={users})}

     {showPages=="Panel" && <Panel/>}
 </>
</code>```

Now when  I click the Panel button, I can see Panel page as a separate page, But guess what: I missed back button of the browser! I also don't want to use html-based project and use react in it.

Is it possible to create non spa website using pure react? or I should create project without react and use react in it.

答:
Finally, I found a way. I created a new component named Home and I put User component and panel button in it. Rather than rendering home component in App component, I made Home component home page by routing:

```<code><Route path="/" element={<Home Items={users}/>}/>
</code>```

I also routed Panel component in App component

```<code><Route path="/Panel" element={<Panel/>}/>
</code>```

Now here is my App component:

```<code>function App() {
const users = useSelector(state => state.users)
 const dispatch = useDispatch();
    const getUsers=()=>{
        // async action using redux-thunk
        return async function(dispatch){
            try{

            dispatch(GetUserRequest())
             const response= await axios.get("https://reqres.in/api/users?page=2")

             dispatch(GetUserSuccess(response.data.data))
            }
            catch(er){
                dispatch(GetUserFail(er))

            }
        }
    }
useEffect(()=>{

    dispatch(getUsers())
 }

  ,[])
return(<>
<Routes>
<Route path="/" element={<Home Items={users}/>}/>
<Route path="/Panel" element={<Panel/>}/>
</Routes>
</>)
}
</code>```

And here is Home component:

```<code>const Home = (props) => {
  return ( <>
<button className='btn btn-primary' onClick={()=>{
  navigate("/Panel")

}}>Panel</button>
 <Users Items={props.Items}/>

</>
}
</code>```

Now when I click Panel button I see Panel component as a separate page (non-spa).
You can also use child route and outlet if you want to have semi spa site(
for example if you want to render some components in home page and render others as separate pages
)

Body:
I have a simple test project using react that shows users of fake API. The parent component is named App and it's my home page. There is a button named panel in the App component. I want it to go to Panel Component when I click it.

function App() {
const users = useSelector(state => state.users)
 const dispatch = useDispatch();
    const getUsers=()=>{
        // async action using redux-thunk
        return async function(dispatch){
            try{

            dispatch(GetUserRequest())
             const response= await axios.get("https://reqres.in/api/users?page=2")

             dispatch(GetUserSuccess(response.data.data))
            }
            catch(er){
                dispatch(GetUserFail(er))

            }
        }
    }
useEffect(()=>{

    dispatch(getUsers())
 }

  ,[])
  return (<>
 <Provider store={store}>
 <Routes>
<Route path="users" element={<Users Items={users}/>}/>
<Route path="/Panel" element={<Panel/>}/>
</Routes>

 <button className='btn btn-primary' onClick={()=>{
  navigate("/Panel")

}}>Panel</button>
<Users/>

</>

It's simple, But I want the Panel component to be a separate page instead of being part of the home page! And I don't want to show other components (in my project User component)

So I tried a trick: using showPages state to determine which page should be shown:

function App() {
 const users = useSelector(state => state.users)
const[showPages,setShowPages]=useState("users")
  useEffect(()=>{

    setShowPages("users")
    dispatch(getUsers())
  }

  ,[])
 return (<>
<button className='btn btn-primary' onClick={()=>{
 setShowPages("panel")

}}>Panel</button>
 {showPages=="users" && ( <Users/> Items={users})}

     {showPages=="Panel" && <Panel/>}
 </>

Now when  I click the Panel button, I can see Panel page as a separate page, But guess what: I missed back button of the browser! I also don't want to use html-based project and use react in it.

Is it possible to create non spa website using pure react? or I should create project without react and use react in it.

Body:
Finally, I found a way. I created a new component named Home and I put User component and panel button in it. Rather than rendering home component in App component, I made Home component home page by routing:

<Route path="/" element={<Home Items={users}/>}/>

I also routed Panel component in App component

<Route path="/Panel" element={<Panel/>}/>

Now here is my App component:

function App() {
const users = useSelector(state => state.users)
 const dispatch = useDispatch();
    const getUsers=()=>{
        // async action using redux-thunk
        return async function(dispatch){
            try{

            dispatch(GetUserRequest())
             const response= await axios.get("https://reqres.in/api/users?page=2")

             dispatch(GetUserSuccess(response.data.data))
            }
            catch(er){
                dispatch(GetUserFail(er))

            }
        }
    }
useEffect(()=>{

    dispatch(getUsers())
 }

  ,[])
return(<>
<Routes>
<Route path="/" element={<Home Items={users}/>}/>
<Route path="/Panel" element={<Panel/>}/>
</Routes>
</>)
}

And here is Home component:

const Home = (props) => {
  return ( <>
<button className='btn btn-primary' onClick={()=>{
  navigate("/Panel")

}}>Panel</button>
 <Users Items={props.Items}/>

</>
}

Now when I click Panel button I see Panel component as a separate page (non-spa).
You can also use child route and outlet if you want to have semi spa site(
for example if you want to render some components in home page and render others as separate pages
)


问:
Regex expression to match last numerical component, but exclude file extension
I'm stumped trying to figure out a regex expression. Given a file path, I need to match the last numerical component of the path ("frame" number in an image sequence), but also ignore any numerical component in the file extension.

For example, given path:

/path/to/file/abc123/GCAM5423.xmp

The following expression will correctly match 5423.

((?P<index>(?P<padding>0*)\d+)(?!.*(0*)\d+))

However, this expression fails if for example the file extension contains a number as follows:

/path/to/file/abc123/GCAM5423.cr2

In this case the expression will match the 2 in the file extension, when I still need it to match 5423. How can I modify the above expression to ignore file extensions that have a numerical component?

Using python flavor of regex. Thanks in advance!

Edit: Thanks all for your help! To clarify, I specifically need to modify the above expression to only capture the last group. I am passing this pattern to an external library so it needs to include the named groups and to only match the last number prior to the extension.

答:
Step1: Find substring before last dot.

```<code>(.*)\.
</code>```

Input: /path/to/file/abc123/GCAM5423.cr2

Output: /path/to/file/abc123/GCAM5423

Step2: Find the last numbers using your regex.

Input: /path/to/file/abc123/GCAM5423

Output: 5423

I don't know how to join these two regexs, but it also usefult for you. My hopes^_^

Body:
Step1: Find substring before last dot.

(.*)\.

Input: /path/to/file/abc123/GCAM5423.cr2

Output: /path/to/file/abc123/GCAM5423

Step2: Find the last numbers using your regex.

Input: /path/to/file/abc123/GCAM5423

Output: 5423

I don't know how to join these two regexs, but it also usefult for you. My hopes^_^


问:
Flutter: Need help displaying videos
I am trying to create a tik tok ui clone in flutter. I want to display videos from my assets but the videos are not being displayed when I run the code. Can someone look over my code and give any recommendations?</p>
```<code>import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

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

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

class _VideoTileState extends State<VideoTile> {
  late VideoPlayerController _videoController;
  late Future _intitializeVideoPlayer;

  @override
  void initState() {
    _videoController = VideoPlayerController.asset('assets/nft_vid1.mp4');
    _intitializeVideoPlayer = _videoController.initialize();
    _videoController.setLooping(true);
    _videoController.play();
    super.initState();
  }

  @override
  void dispose() {
    _videoController.dispose();
    super.dispose();
  }

  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue,
      child: FutureBuilder(
        future: _intitializeVideoPlayer,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return VideoPlayer(_videoController);
          } else {
            return Container(color: Colors.pink);
          }
        },
      ),
    );
  }
}
</code>```

答: My original code was working. Just had to close out my IDE and restart my simulator.</p>

Title: Flutter: Need help displaying videos

Body:
I am trying to create a tik tok ui clone in flutter. I want to display videos from my assets but the videos are not being displayed when I run the code. Can someone look over my code and give any recommendations?

import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

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

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

class _VideoTileState extends State<VideoTile> {
  late VideoPlayerController _videoController;
  late Future _intitializeVideoPlayer;

  @override
  void initState() {
    _videoController = VideoPlayerController.asset('assets/nft_vid1.mp4');
    _intitializeVideoPlayer = _videoController.initialize();
    _videoController.setLooping(true);
    _videoController.play();
    super.initState();
  }

  @override
  void dispose() {
    _videoController.dispose();
    super.dispose();
  }

  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue,
      child: FutureBuilder(
        future: _intitializeVideoPlayer,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return VideoPlayer(_videoController);
          } else {
            return Container(color: Colors.pink);
          }
        },
      ),
    );
  }
}


问:
collapse R package: rearraning or reposition columns in custom order
I'm using collapse R package want to reposition columns. In tidyverse or dplyr, this can be achieved by using everything() function. However everything() function is not working with fselect function from collapse. Any thoughts.

```<code>library(collapse)
library(tidyverse)

wlddev %>%
  qDT() %>%
  fselect(date, year, decade)

             date year decade
    1: 1961-01-01 1960   1960
    2: 1962-01-01 1961   1960
    3: 1963-01-01 1962   1960
    4: 1964-01-01 1963   1960
    5: 1965-01-01 1964   1960
   ---
13172: 2017-01-01 2016   2010
13173: 2018-01-01 2017   2010
13174: 2019-01-01 2018   2010
13175: 2020-01-01 2019   2010
13176: 2021-01-01 2020   2020

wlddev %>%
  qDT() %>%
  fselect(date, year, decade, everything())

Error in `peek_vars()`:
! `everything()` must be used within a *selecting* function.
i See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>.
Run `rlang::last_error()` to see where the error occurred.
</code>```

答:
setcolorder is the equivalent of everything() in Data Tables.

```<code>wlddev %>%
  qDT() %>%
  setcolorder(c("date", "year", "decade")) %>% eval()
</code>```

Body:
I'm using collapse R package want to reposition columns. In tidyverse or dplyr, this can be achieved by using everything() function. However everything() function is not working with fselect function from collapse. Any thoughts.

library(collapse)
library(tidyverse)

wlddev %>%
  qDT() %>%
  fselect(date, year, decade)

             date year decade
    1: 1961-01-01 1960   1960
    2: 1962-01-01 1961   1960
    3: 1963-01-01 1962   1960
    4: 1964-01-01 1963   1960
    5: 1965-01-01 1964   1960
   ---
13172: 2017-01-01 2016   2010
13173: 2018-01-01 2017   2010
13174: 2019-01-01 2018   2010
13175: 2020-01-01 2019   2010
13176: 2021-01-01 2020   2020

wlddev %>%
  qDT() %>%
  fselect(date, year, decade, everything())

Error in `peek_vars()`:
! `everything()` must be used within a *selecting* function.
i See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>.
Run `rlang::last_error()` to see where the error occurred.

Body:
setcolorder is the equivalent of everything() in Data Tables.

wlddev %>%
  qDT() %>%
  setcolorder(c("date", "year", "decade")) %>% eval()


问:
How to run LogRocket in expo go : Invariant Violation: Native module cannot be null
When run LogRocket in expo go has this error:</p>
```<code>Invariant Violation: Native module cannot be null.
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:104:6 in reportException
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:172:19 in handleException
at node_modules/react-native/Libraries/Core/setUpErrorHandling.js:24:6 in handleError
at node_modules/expo-error-recovery/build/ErrorRecovery.fx.js:12:21 in ErrorUtils.setGlobalHandler$argument_0
</code>```

答:
Based on this guide https://docs.expo.dev/bare/using-expo-client/#use-conditional-inline-requires-to-provide-fallbacks

create a file LogRocketInit.js

```<code>import Constants from 'expo-constants';
import { useEffect } from 'react';

export default function LogRocketInit() {
  useEffect(() => {
    if (Constants.appOwnership !== 'expo') {
      const LogRocket = require('@logrocket/react-native');
      LogRocket.init('****');
    }
  }, []);

  return null;
}
</code>```

then add it to App.js as normal

```<code>export default function App() {
  return (
       ...
       <LogRocketInit />
       ...
}
</code>```

in case you need to use it in another place, use this

```<code>   if (Constants.appOwnership !== 'expo') {
      const LogRocket = require('@logrocket/react-native');
      ....
   }
</code>```

Body:
When run LogRocket in expo go has this error:

Invariant Violation: Native module cannot be null.
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:104:6 in reportException
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:172:19 in handleException
at node_modules/react-native/Libraries/Core/setUpErrorHandling.js:24:6 in handleError
at node_modules/expo-error-recovery/build/ErrorRecovery.fx.js:12:21 in ErrorUtils.setGlobalHandler$argument_0

Body:
Based on this guide https://docs.expo.dev/bare/using-expo-client/#use-conditional-inline-requires-to-provide-fallbacks

create a file LogRocketInit.js

import Constants from 'expo-constants';
import { useEffect } from 'react';

export default function LogRocketInit() {
  useEffect(() => {
    if (Constants.appOwnership !== 'expo') {
      const LogRocket = require('@logrocket/react-native');
      LogRocket.init('****');
    }
  }, []);

  return null;
}

then add it to App.js as normal

export default function App() {
  return (
       ...
       <LogRocketInit />
       ...
}

in case you need to use it in another place, use this

   if (Constants.appOwnership !== 'expo') {
      const LogRocket = require('@logrocket/react-native');
      ....
   }


问:
How to Solve Flutter Expected a value of type 'List<dynamic>', but got one of type 'JsonMap'
Flutter Expected a value of type 'List', but got one of type '_jsonMap'

When i'm did this same with localhost it worked fine but when i do this same with hosting it give me this error.from api side is working api is sending the data.but something wrong.

```<code>//Future is n object representing a delayed computation.
Future<List<Homes>> downloadJSON() async {
  final jsonEndpoint = "https://homeshouse.000webhostapp.com/get.php";

  final response = await get(Uri.parse(jsonEndpoint));

  if (response.statusCode == 200) {
    List homelist = json.decode(response.body);
    return homelist.map((home) => new Homes.fromJson(home)).toList();
  } else
    throw Exception('We were not able to successfully download the json data.');
}
</code>```

please help i stucked here from last 2 days and i'm not getting this

答:
```<code> if (response.statusCode == 200) {
    final json = "[" + response.body + "]";
    List homelist = (jsonDecode(json) as List<dynamic>) ;
</code>```

this is works for me:-
enter link description here

Body:
Flutter Expected a value of type 'List', but got one of type '_jsonMap'

When i'm did this same with localhost it worked fine but when i do this same with hosting it give me this error.from api side is working api is sending the data.but something wrong.

//Future is n object representing a delayed computation.
Future<List<Homes>> downloadJSON() async {
  final jsonEndpoint = "https://homeshouse.000webhostapp.com/get.php";

  final response = await get(Uri.parse(jsonEndpoint));

  if (response.statusCode == 200) {
    List homelist = json.decode(response.body);
    return homelist.map((home) => new Homes.fromJson(home)).toList();
  } else
    throw Exception('We were not able to successfully download the json data.');
}

please help i stucked here from last 2 days and i'm not getting this

Body:
 if (response.statusCode == 200) {
    final json = "[" + response.body + "]";
    List homelist = (jsonDecode(json) as List<dynamic>) ;

this is works for me:-
enter link description here


问:
How to fix Laravel 8 - "SQLSTATE[HY000] [1049] Unknown database"
I'm trying to run the following command:

```<code>php artisan migrate
</code>```

When I do that, I get the following error:

```<code>Illuminate\Database\QueryException

  SQLSTATE[HY000] [1049] Unknown database 'verified_db' (SQL: select * from information_schema.tables where table_schema = verified_db and table_name = migrations and table_type = 'BASE TABLE')

  at C:\Users\richa\Desktop\back-office\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
    688▕         // If an exception occurs when attempting to run a query, we'll format the error
    689▕         // message to include the bindings with SQL, which will make this exception a
    690▕         // lot more helpful to the developer instead of just the database's errors.
    691▕         catch (Exception $e) {
  ➜ 692▕             throw new QueryException(
    693▕                 $query, $this->prepareBindings($bindings), $e
    694▕             );
    695▕         }
    696▕     }

  1   C:\Users\richa\Desktop\back-office\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDOException::("SQLSTATE[HY000] [1049] Unknown database 'verified_db'")

  2   C:\Users\richa\Desktop\back-office\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDO::__construct()
</code>```

I already configured the .env file with my database credentials. I hope someone can assist with this.

答:
in  MySQL Workbench
*create a new schema in the connected server
~set [Schema Name] =  [DB_DATABASE]='your name'
run command: php artisan migrate

in  phpMyAdmin
*create a Database
~set [Database Name] =  [DB_DATABASE]='your name'
run command: php artisan migrate

Body:
I'm trying to run the following command:

php artisan migrate

When I do that, I get the following error:

Illuminate\Database\QueryException

  SQLSTATE[HY000] [1049] Unknown database 'verified_db' (SQL: select * from information_schema.tables where table_schema = verified_db and table_name = migrations and table_type = 'BASE TABLE')

  at C:\Users\richa\Desktop\back-office\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
    688▕         // If an exception occurs when attempting to run a query, we'll format the error
    689▕         // message to include the bindings with SQL, which will make this exception a
    690▕         // lot more helpful to the developer instead of just the database's errors.
    691▕         catch (Exception $e) {
  ➜ 692▕             throw new QueryException(
    693▕                 $query, $this->prepareBindings($bindings), $e
    694▕             );
    695▕         }
    696▕     }

  1   C:\Users\richa\Desktop\back-office\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDOException::("SQLSTATE[HY000] [1049] Unknown database 'verified_db'")

  2   C:\Users\richa\Desktop\back-office\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDO::__construct()

I already configured the .env file with my database credentials. I hope someone can assist with this.


问:
How to create react app using yarn instead of npm?
The offical way to create react app is mentioned in react documentation

i think npx create-react-app project automatically detect yarn but in my case it doesn't and create react app using npm which i don't want.

Second option for me to use yarn create react-app for creating react app but it shows multiple warnings:

```<code>warning " > @testing-library/user-event@13.5.0" has unmet peer dependency "@testing-library/dom@>=7.21.4".
warning "react-scripts > tailwindcss@3.0.22" has unmet peer dependency "autoprefixer@^10.0.2".
warning "react-scripts > eslint-config-react-app > eslint-plugin-flowtype@8.0.3" has unmet peer dependency "@babel/plugin-syntax-flow@^7.14.5".
warning "react-scripts > eslint-config-react-app > eslint-plugin-flowtype@8.0.3" has unmet peer dependency "@babel/plugin-transform-react-jsx@^7.14.9".
warning "react-scripts > react-dev-utils > fork-ts-checker-webpack-plugin@6.5.0" has unmet peer dependency "typescript@>= 2.7".
warning "react-scripts > eslint-config-react-app > @typescript-eslint/eslint-plugin > tsutils@3.21.0" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
</code>```

so is there any better way to create react app with npx (that uses yarn)

答:
There is no need to use yarn for create-react-app as this npm package is not a local dev dependency. It's used to download a template of a React project and react-scripts package does all the "magic" stuff.

The reason why the official documentation suggests using npx is that it will delete the package after it's used to create a template. This mean when you want to create another react project, it will always use the latest version of create-react-app.

Body:
The offical way to create react app is mentioned in react documentation

i think npx create-react-app project automatically detect yarn but in my case it doesn't and create react app using npm which i don't want.

Second option for me to use yarn create react-app for creating react app but it shows multiple warnings:

warning " > @testing-library/user-event@13.5.0" has unmet peer dependency "@testing-library/dom@>=7.21.4".
warning "react-scripts > tailwindcss@3.0.22" has unmet peer dependency "autoprefixer@^10.0.2".
warning "react-scripts > eslint-config-react-app > eslint-plugin-flowtype@8.0.3" has unmet peer dependency "@babel/plugin-syntax-flow@^7.14.5".
warning "react-scripts > eslint-config-react-app > eslint-plugin-flowtype@8.0.3" has unmet peer dependency "@babel/plugin-transform-react-jsx@^7.14.9".
warning "react-scripts > react-dev-utils > fork-ts-checker-webpack-plugin@6.5.0" has unmet peer dependency "typescript@>= 2.7".
warning "react-scripts > eslint-config-react-app > @typescript-eslint/eslint-plugin > tsutils@3.21.0" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".

so is there any better way to create react app with npx (that uses yarn)


问:
How to remove all other python versions except for the one carried by the OS X
Before asking this question, I tried a lot of methods. I mainly focus on these posts.

How to find all python installations on mac os x and uninstall all but the native OS X installation

How to clean iPython environment so I can start over with Jupyter and Python 3.x?

I also tried

```<code>conda install anaconda-clean
anaconda-clean --yes
rm -rf ~/anaconda3
</code>```

brew  cleanup python3

But I still have a number of python versions left

```<code>GZs-MacBook-Pro:bin gz$ which python
/usr/bin/python
GZs-MacBook-Pro:bin gz$ which python3
/usr/bin/python3
GZs-MacBook-Pro:bin gz$ ls /System/Library/Frameworks/Python.framework/Versions
2.3 2.5 2.6 2.7 Current
GZs-MacBook-Pro:bin gz$ ls /Library/Frameworks/Python.framework/Versions
ls: /Library/Frameworks/Python.framework/Versions: No such file or directory
GZs-MacBook-Pro:bin gz$ ls -l /usr/bin/python*
lrwxr-xr-x  1 root  wheel     75  9 Oct 23:42 /usr/bin/python -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     82  9 Oct 23:42 /usr/bin/python-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
lrwxr-xr-x  1 root  wheel     75  9 Oct 23:42 /usr/bin/python2 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     75  9 Oct 23:42 /usr/bin/python2.7 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     82  9 Oct 23:42 /usr/bin/python2.7-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
-rwxr-xr-x  1 root  wheel  31456  5 Dec 04:32 /usr/bin/python3
</code>```

How can I remove the others python versions except for the original one on the OS X?

答:
For Windows.......

You have to follow 2 ways:-

Firstly, you can.....

Go to Control Panel and select Add or Remove Programs.

Assuming you have an older version X.Y installed, scroll through the
list of programs, and for each Python X.Y package that has been
installed, select it in the list and click Remove.

Note that most packages will be listed as Python X.Y package_name-
package_version, such as Python 2.5 numpy-1.0.4, but a few packages
such as wxPython, listed as wxPython 2.8.7.1 (unicode) for Python 2.5,
may not follow that convention, necessitating that you search the
entire program list for packages.

The directory C:\PythonXY\ will still exist, so it is recommended that
that directory be deleted to avoid confusion (make sure any code you
have in there is backed up before deleting the directory!!!)
Remove any shortcuts to Python X.Y or IPython that may still be under
the Start menu.

Secondly, you can....

Type "IDLE" on the Start menu.

Note that, please select the version you want to delete.

Right-click on the application it has found on your computer.

Select "Open file location".

In the Windows explorer, right-click on the IDLE shortcut.

Select "Properties"

At the beginning of the field "Target", you should see the location
of the "pythonw.exe" file.

"python.exe" should be right beside it.

You can uninstall these files or the whole folder.

Thank You.

Body:
Before asking this question, I tried a lot of methods. I mainly focus on these posts.

How to find all python installations on mac os x and uninstall all but the native OS X installation

How to clean iPython environment so I can start over with Jupyter and Python 3.x?

I also tried

conda install anaconda-clean
anaconda-clean --yes
rm -rf ~/anaconda3

brew  cleanup python3

But I still have a number of python versions left

GZs-MacBook-Pro:bin gz$ which python
/usr/bin/python
GZs-MacBook-Pro:bin gz$ which python3
/usr/bin/python3
GZs-MacBook-Pro:bin gz$ ls /System/Library/Frameworks/Python.framework/Versions
2.3 2.5 2.6 2.7 Current
GZs-MacBook-Pro:bin gz$ ls /Library/Frameworks/Python.framework/Versions
ls: /Library/Frameworks/Python.framework/Versions: No such file or directory
GZs-MacBook-Pro:bin gz$ ls -l /usr/bin/python*
lrwxr-xr-x  1 root  wheel     75  9 Oct 23:42 /usr/bin/python -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     82  9 Oct 23:42 /usr/bin/python-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
lrwxr-xr-x  1 root  wheel     75  9 Oct 23:42 /usr/bin/python2 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     75  9 Oct 23:42 /usr/bin/python2.7 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x  1 root  wheel     82  9 Oct 23:42 /usr/bin/python2.7-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
-rwxr-xr-x  1 root  wheel  31456  5 Dec 04:32 /usr/bin/python3

How can I remove the others python versions except for the original one on the OS X?


问:
How to convert mixed time formats with strings to military time?
I have a variable that needs to be converted to military time. This variable is very messy because it lacks consistency in the format.

Here is an example of what might be found in the variable.

```<code>x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 1525")
</code>```

So far I had some success in getting everything in a more consistent format with RegEx:

```<code>x <- str_extract(x, "[0-9]+.+[0-9]|[0-9][0-9][:][0-9][0-9]")
x <- str_remove(x, "[:]")
x <- str_remove(x, "[:][0-9][0-9]$")
</code>```

As you can see I get: "0.9305555555555547", "1520", "1000", "0.125", "1525"

The problem is the decimals need to be multiplied by 2400 to get back to military time but I also don't want to multiply integers (since those are already in military time).

x is essentially a variable in a dataframe.

I was thinking about using if/else logic but I don't know how to implement that.

To clarify, I want:

Input: "0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 15:25"

Output: "2233", "1520", "1000", "0300", "1525"

答:
We should extend the regex for AM/PM indicators so that the forces do not miss each other. Next, in subsets we handle decimal time, imperial time, 24h time, and return the result.

```<code>milt <- function(x) {
  u <- trimws(gsub('\\D*(\\d*\\W?[AP]?M?)\\D*', '\\1', x))
  u[grep('\\.', u)] <- sprintf('%04d', round(as.double(u[grep('\\.', u)])*2400))
  u[grep('[AP]M', u)] <- strftime(strptime(u[grep('[AP]M', u)], '%I:%M:%S %p'), '%H%M')
  u[grep(':', u)] <- gsub(':', '', u[grep(':', u)] )
  return(u)
}

milt(x)
# [1] "2233" "1520" "1000" "2200" "0300" "1525" "0000" "1020"
</code>```

Data:

```<code>x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found",
       "10:00:00 PM Found", "0.125", "Found 1525", "0000", "10:20")
</code>```

Body:
I have a variable that needs to be converted to military time. This variable is very messy because it lacks consistency in the format.

Here is an example of what might be found in the variable.

x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 1525")

So far I had some success in getting everything in a more consistent format with RegEx:

x <- str_extract(x, "[0-9]+.+[0-9]|[0-9][0-9][:][0-9][0-9]")
x <- str_remove(x, "[:]")
x <- str_remove(x, "[:][0-9][0-9]$")

As you can see I get: "0.9305555555555547", "1520", "1000", "0.125", "1525"

The problem is the decimals need to be multiplied by 2400 to get back to military time but I also don't want to multiply integers (since those are already in military time).

x is essentially a variable in a dataframe.

I was thinking about using if/else logic but I don't know how to implement that.

To clarify, I want:

Input: "0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 15:25"

Output: "2233", "1520", "1000", "0300", "1525"

Body:
We should extend the regex for AM/PM indicators so that the forces do not miss each other. Next, in subsets we handle decimal time, imperial time, 24h time, and return the result.

milt <- function(x) {
  u <- trimws(gsub('\\D*(\\d*\\W?[AP]?M?)\\D*', '\\1', x))
  u[grep('\\.', u)] <- sprintf('%04d', round(as.double(u[grep('\\.', u)])*2400))
  u[grep('[AP]M', u)] <- strftime(strptime(u[grep('[AP]M', u)], '%I:%M:%S %p'), '%H%M')
  u[grep(':', u)] <- gsub(':', '', u[grep(':', u)] )
  return(u)
}

milt(x)
# [1] "2233" "1520" "1000" "2200" "0300" "1525" "0000" "1020"

Data:

x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found",
       "10:00:00 PM Found", "0.125", "Found 1525", "0000", "10:20")


问:
Setting background color for  element (without height set to 100%) apply to the whole viewport
I found setting background color for entire  element  (without height set to 100%) result in the whole viewport was set to that color

This html

<!DOCTYPE html>

    1

    2

    3

```

will result like this

Obviously, the height of html element is less than the height of viewport, why the background color could extend to whole viewport?

答:
Because the spec says so:

The background of the root element becomes the background of the
canvas and covers the entire canvas, anchored (for
'background-position') at the same point as it would be if it was
painted only for the root element itself. The root element does not
paint this background again.

Title: Setting background color for <html> element (without height set to 100%) apply to the whole viewport

Body:
I found setting background color for entire  element  (without height set to 100%) result in the whole viewport was set to that color

This html

<!DOCTYPE html>

    1

    2

    3

will result like this

Obviously, the height of html element is less than the height of viewport, why the background color could extend to whole viewport?


问:
How Would You Parse This Object Representing an Annotated String To HTML? Stuck
This is the desired string rendered

Suppose you have an Array of Objects representing different attributes of the string:

```<code>[{
    "isBold": false,
    "isCode": true,
    "isItalic": false,
    "isStrikethrough": false,
    "range": [
        42,
        8
    ]
},
{
    "isBold": false,
    "isCode": false,
    "isItalic": true,
    "isStrikethrough": false,
    "range": [
        19,
        10
    ]
},
{
    "isBold": false,
    "isCode": false,
    "isItalic": false,
    "isStrikethrough": true,
    "range": [
        46,
        11
    ]
},
{
    "isBold": true,
    "isCode": false,
    "isItalic": false,
    "isStrikethrough": false,
    "range": [
        27,
        12
    ],
    "nested": [
        {
            "isBold": false,
            "isCode": true,
            "isItalic": false,
            "isStrikethrough": false,
            "range": [
                28,
                7
            ]
        }
    ]
},
{
    "highlightColor": "#fff100 #fff432",
    "isBold": false,
    "isCode": false,
    "isItalic": false,
    "isStrikethrough": false,
    "range": [
        1,
        15
    ]
},
{
    "isBold": false,
    "isCode": false,
    "isItalic": false,
    "isStrikethrough": false,
    "linkURL": "www.google.com",
    "range": [
        5,
        29
    ],
    "nested": [
        {
            "isBold": false,
            "isCode": false,
            "isItalic": true,
            "isStrikethrough": false,
            "range": [
                19,
                10
            ]
        }
    ]
}]
</code>```

Any suggestions on how you would go about rendering something like this?

The nested ranges and different attributes has me completely stuck... I tried going through the string char by char and collecting which attributes belong to each char – I'm close, but I'm not rendering links correctly and the code attributes get split up instead of wrapping their entire text:

Render of my attempt to parse

```<code>function renderTextAttributes(content, textAttributes)
  let attributes = []
  let currentAttributes, start, end
  for (let i = 0; i < content.length; i++) {
    if (i === content.length - 1) {
      attributes.push({
        attributes: currentAttributes,
        content:
          currentAttributes.length > 0
            ? `<span class="${currentAttributes.join(' ')}">${content.slice(
                Math.max(0, start)
              )}</span>`
            : content.slice(Math.max(0, start)),
        end,
        start
      })
    } else if (currentAttributes) {
      let charAttributes = []
      for (const attribute of textAttributes) {
        if (
          i >= attribute.range[0] &&
          i <= attribute.range[0] + attribute.range[1]
        ) {
          charAttributes = [
            ...new Set([...charAttributes, ...findAttributes(attribute)])
          ]
        }
      }
      if (
        JSON.stringify(charAttributes) === JSON.stringify(currentAttributes)
      ) {
        end = i
      } else {
        attributes.push({
          attributes: currentAttributes,
          content:
            currentAttributes.length > 0
              ? `<span class="${currentAttributes.join(
                  ' '
                )}">${content.substring(start, end)}</span>`
              : content.substring(start, end),
          end,
          start
        })
        currentAttributes = null
        i--
      }
    } else {
      currentAttributes = []
      start = i
      end = i + 1
      for (const attribute of textAttributes) {
        if (
          i >= attribute.range[0] &&
          i <= attribute.range[0] + attribute.range[1]
        ) {
          currentAttributes = [
            ...new Set([...currentAttributes, ...findAttributes(attribute)])
          ]
        }
      }
    }
  }

  let newContent = ''
  for (const attribute of attributes) {
    newContent += attribute.content
  }

  return newContent
}
</code>```

答:
I did something that may be what you are looking for.

**(update) Sometimes when inserting the tags with function replaceWithTags we get some closing tags (e.g.:  between  tag) in the middle of the string and that mess up the final HTML, the string result may be ok, but when printing it on the DOM because HTML doesn't throw errors, instead, it tries to add the missing/closing tags, so, to solve that, I'm adding a validation where it checks if we have a single closing tag and we add the current opening tag right after the found single closing tag, that way if we have for example:

for Strikethrough case:

```<code>'<del> be </code>rendere</del>'
</code>```

we will add a  tag after  like this:

```<code><del> be </code><del>rendere</del>
</code>```

as you can see it is still not a valid HTML code, but the browser will take care of it, adding the missing code:

Final HTML screenshot

let attributes = [
    {
        "isBold": false,
        "isCode": true,
        "isItalic": false,
        "isStrikethrough": false,
        "range": [
            42,
            8
        ]
    },
    {
        "isBold": false,
        "isCode": false,
        "isItalic": true,
        "isStrikethrough": false,
        "range": [
            19,
            10
        ]
    },
    {
        "isBold": false,
        "isCode": false,
        "isItalic": false,
        "isStrikethrough": true,
        "range": [
            46,
            11
        ]
    },
    {
        "isBold": true,
        "isCode": false,
        "isItalic": false,
        "isStrikethrough": false,
        "range": [
            27,
            12
        ],
        "nested": [
            {
                "isBold": false,
                "isCode": true,
                "isItalic": false,
                "isStrikethrough": false,
                "range": [
                    28,
                    7
                ]
            }
        ]
    },
    {
        "highlightColor": "#fff100 #fff432",
        "isBold": false,
        "isCode": false,
        "isItalic": false,
        "isStrikethrough": false,
        "range": [
            1,
            15
        ]
    },
    {
        "isBold": false,
        "isCode": false,
        "isItalic": false,
        "isStrikethrough": false,
        "linkURL": "www.google.com",
        "range": [
            5,
            29
        ],
        "nested": [
            {
                "isBold": false,
                "isCode": false,
                "isItalic": true,
                "isStrikethrough": false,
                "range": [
                    19,
                    10
                ]
            }
        ]
    }
];

const replaceWithTags = (content, ar, start, end, tag, attr) => {

    const startTag = `<${tag}${attr ? ' ' + attr : ''}>`;

    let str = content.join('');

    let match = str.match(/<\/.*?>/g);

    if (match && match.length === 1) {
        let idx = content.findIndex(x => x.match(/<\/.*?>/g))
        content[idx] = content[idx] + startTag;
    }

    ar[start] = startTag +  content.slice(0, 1);

    ar[end] = content.slice(content.length - 1, content.length) + `</${tag}>`;

    ar = [...ar.slice(0, start + 1),
          ...content.slice(1, content.length -  1),
          ...ar.slice(end, ar.length)];

    return ar;
}

const tags = {
    isCode: (content, ar, start, end) => {
        return replaceWithTags(content, ar, start, end, 'code');
    },
    isBold: (content, ar, start, end)=> {
        return replaceWithTags(content, ar, start, end, 'b');
    },
    isStrikethrough: (content, ar, start, end) => {
        return replaceWithTags(content, ar, start, end, 'del');
    },
    isItalic: (content, ar, start, end) => {
        return replaceWithTags(content, ar, start, end, 'span', 'style="font-style: italic;"');
    },
    linkURL: (content, ar, start, end, link) => {
        return replaceWithTags(content, ar, start, end, 'a', `href="${link}"`);
    },
    highlightColor: (content, ar, start, end, color) => {
        return replaceWithTags(content, ar, start, end, 'span', `style="background: ${color};"`);
    },
};

const renderTextAttributes = (content, textAttributes) => {
    let arr = content.split('');
    let checlAttrs = (attrs) => {
        for (let itm of attrs) {
            let start = itm.range[0];
            let end = itm.range[1];
            const slice = arr.slice(start, (start + (end)));

           for (let prop in itm) {

                if (typeof itm[prop] === 'boolean' && itm[prop]) {

                    arr = tags[prop](slice, arr, start, (start + (end - 1)));

                } else if (prop === 'linkURL') {

                    arr = tags[prop](slice, arr, start, (start + (end - 1)), itm[prop]);

                } else if (prop === 'highlightColor') {

                    arr = tags[prop](slice, arr, start, (start + (end - 1)), itm[prop].split(' ')[1]);

                } else if (prop === 'nested') {

                    arr = checlAttrs(itm[prop]);

                }
            }

        }
        return arr;
    }
    arr = checlAttrs(textAttributes);
    return arr.join('');
};

const text = 'String with different attributes and a link to be rendered.';
document.write(renderTextAttributes(text, attributes));
console.log(renderTextAttributes(text, attributes));```

Body:
This is the desired string rendered

Suppose you have an Array of Objects representing different attributes of the string:

[{
    "isBold": false,
    "isCode": true,
    "isItalic": false,
    "isStrikethrough": false,
    "range": [
        42,
        8
    ]
},
{
    "isBold": false,
    "isCode": false,
    "isItalic": true,
    "isStrikethrough": false,
    "range": [
        19,
        10
    ]
},
{
    "isBold": false,
    "isCode": false,
    "isItalic": false,
    "isStrikethrough": true,
    "range": [
        46,
        11
    ]
},
{
    "isBold": true,
    "isCode": false,
    "isItalic": false,
    "isStrikethrough": false,
    "range": [
        27,
        12
    ],
    "nested": [
        {
            "isBold": false,
            "isCode": true,
            "isItalic": false,
            "isStrikethrough": false,
            "range": [
                28,
                7
            ]
        }
    ]
},
{
    "highlightColor": "#fff100 #fff432",
    "isBold": false,
    "isCode": false,
    "isItalic": false,
    "isStrikethrough": false,
    "range": [
        1,
        15
    ]
},
{
    "isBold": false,
    "isCode": false,
    "isItalic": false,
    "isStrikethrough": false,
    "linkURL": "www.google.com",
    "range": [
        5,
        29
    ],
    "nested": [
        {
            "isBold": false,
            "isCode": false,
            "isItalic": true,
            "isStrikethrough": false,
            "range": [
                19,
                10
            ]
        }
    ]
}]

Any suggestions on how you would go about rendering something like this?

The nested ranges and different attributes has me completely stuck... I tried going through the string char by char and collecting which attributes belong to each char – I'm close, but I'm not rendering links correctly and the code attributes get split up instead of wrapping their entire text:

Render of my attempt to parse

function renderTextAttributes(content, textAttributes)
  let attributes = []
  let currentAttributes, start, end
  for (let i = 0; i < content.length; i++) {
    if (i === content.length - 1) {
      attributes.push({
        attributes: currentAttributes,
        content:
          currentAttributes.length > 0
            ? `${content.slice(
                Math.max(0, start)
              )}`
            : content.slice(Math.max(0, start)),
        end,
        start
      })
    } else if (currentAttributes) {
      let charAttributes = []
      for (const attribute of textAttributes) {
        if (
          i >= attribute.range[0] &&
          i <= attribute.range[0] + attribute.range[1]
        ) {
          charAttributes = [
            ...new Set([...charAttributes, ...findAttributes(attribute)])
          ]
        }
      }
      if (
        JSON.stringify(charAttributes) === JSON.stringify(currentAttributes)
      ) {
        end = i
      } else {
        attributes.push({
          attributes: currentAttributes,
          content:
            currentAttributes.length > 0
              ? `${content.substring(start, end)}`
              : content.substring(start, end),
          end,
          start
        })
        currentAttributes = null
        i--
      }
    } else {
      currentAttributes = []
      start = i
      end = i + 1
      for (const attribute of textAttributes) {
        if (
          i >= attribute.range[0] &&
          i <= attribute.range[0] + attribute.range[1]
        ) {
          currentAttributes = [
            ...new Set([...currentAttributes, ...findAttributes(attribute)])
          ]
        }
      }
    }
  }

  let newContent = ''
  for (const attribute of attributes) {
    newContent += attribute.content
  }

  return newContent
}

Body:
I did something that may be what you are looking for.

**(update) Sometimes when inserting the tags with function replaceWithTags we get some closing tags (e.g.: </code> between <del> tag) in the middle of the string and that mess up the final HTML, the string result may be ok, but when printing it on the DOM because HTML doesn't throw errors, instead, it tries to add the missing/closing tags, so, to solve that, I'm adding a validation where it checks if we have a single closing tag and we add the current opening tag right after the found single closing tag, that way if we have for example:

for Strikethrough case:

'<del> be </code>rendere</del>'

we will add a <del> tag after </code> like this:

<del> be </code><del>rendere</del>

as you can see it is still not a valid HTML code, but the browser will take care of it, adding the missing code:

Final HTML screenshot

let attributes = [
    {
        "isBold": false,
        "isCode": true,
        "isItalic": false,
        "isStrikethrough": false,
        "range": [
            42,
            8
        ]
    },
    {
        "isBold": false,
        "isCode": false,
        "isItalic": true,
        "isStrikethrough": false,
        "range": [
            19,
            10
        ]
    },
    {
        "isBold": false,
        "isCode": false,
        "isItalic": false,
        "isStrikethrough": true,
        "range": [
            46,
            11
        ]
    },
    {
        "isBold": true,
        "isCode": false,
        "isItalic": false,
        "isStrikethrough": false,
        "range": [
            27,
            12
        ],
        "nested": [
            {
                "isBold": false,
                "isCode": true,
                "isItalic": false,
                "isStrikethrough": false,
                "range": [
                    28,
                    7
                ]
            }
        ]
    },
    {
        "highlightColor": "#fff100 #fff432",
        "isBold": false,
        "isCode": false,
        "isItalic": false,
        "isStrikethrough": false,
        "range": [
            1,
            15
        ]
    },
    {
        "isBold": false,
        "isCode": false,
        "isItalic": false,
        "isStrikethrough": false,
        "linkURL": "www.google.com",
        "range": [
            5,
            29
        ],
        "nested": [
            {
                "isBold": false,
                "isCode": false,
                "isItalic": true,
                "isStrikethrough": false,
                "range": [
                    19,
                    10
                ]
            }
        ]
    }
];

const replaceWithTags = (content, ar, start, end, tag, attr) => {

    const startTag = `<${tag}${attr ? ' ' + attr : ''}>`;

    let str = content.join('');

    let match = str.match(/<\/.*?>/g);

    if (match && match.length === 1) {
        let idx = content.findIndex(x => x.match(/<\/.*?>/g))
        content[idx] = content[idx] + startTag;
    }

    ar[start] = startTag +  content.slice(0, 1);

    ar[end] = content.slice(content.length - 1, content.length) + `</${tag}>`;

    ar = [...ar.slice(0, start + 1),
          ...content.slice(1, content.length -  1),
          ...ar.slice(end, ar.length)];

    return ar;
}

const tags = {
    isCode: (content, ar, start, end) => {
        return replaceWithTags(content, ar, start, end, 'code');
    },
    isBold: (content, ar, start, end)=> {
        return replaceWithTags(content, ar, start, end, 'b');
    },
    isStrikethrough: (content, ar, start, end) => {
        return replaceWithTags(content, ar, start, end, 'del');
    },
    isItalic: (content, ar, start, end) => {
        return replaceWithTags(content, ar, start, end, 'span', 'style="font-style: italic;"');
    },
    linkURL: (content, ar, start, end, link) => {
        return replaceWithTags(content, ar, start, end, 'a', `href="${link}"`);
    },
    highlightColor: (content, ar, start, end, color) => {
        return replaceWithTags(content, ar, start, end, 'span', `style="background: ${color};"`);
    },
};

const renderTextAttributes = (content, textAttributes) => {
    let arr = content.split('');
    let checlAttrs = (attrs) => {
        for (let itm of attrs) {
            let start = itm.range[0];
            let end = itm.range[1];
            const slice = arr.slice(start, (start + (end)));

           for (let prop in itm) {

                if (typeof itm[prop] === 'boolean' && itm[prop]) {

                    arr = tags[prop](slice, arr, start, (start + (end - 1)));

                } else if (prop === 'linkURL') {

                    arr = tags[prop](slice, arr, start, (start + (end - 1)), itm[prop]);

                } else if (prop === 'highlightColor') {

                    arr = tags[prop](slice, arr, start, (start + (end - 1)), itm[prop].split(' ')[1]);

                } else if (prop === 'nested') {

                    arr = checlAttrs(itm[prop]);

                }
            }

        }
        return arr;
    }
    arr = checlAttrs(textAttributes);
    return arr.join('');
};

const text = 'String with different attributes and a link to be rendered.';
document.write(renderTextAttributes(text, attributes));
console.log(renderTextAttributes(text, attributes));


答:
I guess that's just the browser trying to match colours with the HTMLs background to better blend in. I think it might look weird especially back in the days where most stuff was sized via pixel values.

Extending a browser page wouldn't result in a rough cut of colour where it changes to white or something. But I would guess that's a browserspecific implementation but don't quote me on that.


问:
How to create image slider in flutter
I'm new to flutter and trying to learn some basic concepts. I want to add 3 background images to this same screen to slide automatically while all the text and buttons remaining the same. how can I do this using flutter. do I need to add 3 different pages to do this??  or can I do it in same file. appreciate your help on this.</p>
```<code>import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class GetStarted extends StatelessWidget {
  const GetStarted({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        //color: Colors.black,
        child: Stack(
          children: [
            Positioned.fill(
              child: Opacity(
                opacity: 0.4,
                child:
                Image.asset('assets/images/person1.png', fit: BoxFit.cover),
              ),
            ),
            Container(
              color: Color.fromRGBO(5, 65, 196, 0.19),
            ),

              Padding(
                padding: const EdgeInsets.only(left: 40,bottom: 230 ),
                child: Align(
                  alignment: Alignment.bottomLeft,
                    child: Text('Meet \nYour Doctor\nHere', style:TextStyle(
                      height: 1.2,
                      fontFamily: 'Dubai',
                      fontSize: 35,
                      color:Color(0xffFAFAFA),
                      fontWeight: FontWeight.w500,
                    ))),
              ),

            Padding(
              padding: const EdgeInsets.only(left: 30,top: 26),
              child: Align(
                  alignment: Alignment.topLeft,
                  child: Text('DOCTOR', style:TextStyle(
                    fontFamily: 'Dubai',
                    fontSize: 30,
                    color:Colors.white,
                    fontWeight: FontWeight.w500,
                  ))),
            ),

            Padding(
              padding: const EdgeInsets.only(bottom: 60),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child:  SizedBox(
                    width: 320,
                    height: 65,
                    child: ElevatedButton(
                        onPressed: () {
                        },
                        child: Text('Get Started',style:TextStyle(color:Colors.white,fontSize:25, fontWeight: FontWeight.normal),
                        ),
                        style:ButtonStyle(
                            backgroundColor: MaterialStateProperty.all<Color>(Color(0xff05ABA3)),
                            shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(50.0),
                              ),
                            )
                        )
                    ),
                  )
              ),
            ),

            Padding(
              padding: const EdgeInsets.only(bottom: 20),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(5.0),
                      color: Colors.white,
                    ),
                    height: 5,
                    width: 120,
                  )
                  )
            ),
          ],
        ),
      ),
    );
  }

}
</code>```

答:
I think you use this package: carousel_slider

Official link: https://pub.dev/packages/carousel_slider

Blog link: https://androidride.com/flutter-carousel-slider-example/

Thank You

Title: How to create image slider in flutter

Body:
I'm new to flutter and trying to learn some basic concepts. I want to add 3 background images to this same screen to slide automatically while all the text and buttons remaining the same. how can I do this using flutter. do I need to add 3 different pages to do this??  or can I do it in same file. appreciate your help on this.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class GetStarted extends StatelessWidget {
  const GetStarted({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        //color: Colors.black,
        child: Stack(
          children: [
            Positioned.fill(
              child: Opacity(
                opacity: 0.4,
                child:
                Image.asset('assets/images/person1.png', fit: BoxFit.cover),
              ),
            ),
            Container(
              color: Color.fromRGBO(5, 65, 196, 0.19),
            ),

              Padding(
                padding: const EdgeInsets.only(left: 40,bottom: 230 ),
                child: Align(
                  alignment: Alignment.bottomLeft,
                    child: Text('Meet \nYour Doctor\nHere', style:TextStyle(
                      height: 1.2,
                      fontFamily: 'Dubai',
                      fontSize: 35,
                      color:Color(0xffFAFAFA),
                      fontWeight: FontWeight.w500,
                    ))),
              ),

            Padding(
              padding: const EdgeInsets.only(left: 30,top: 26),
              child: Align(
                  alignment: Alignment.topLeft,
                  child: Text('DOCTOR', style:TextStyle(
                    fontFamily: 'Dubai',
                    fontSize: 30,
                    color:Colors.white,
                    fontWeight: FontWeight.w500,
                  ))),
            ),

            Padding(
              padding: const EdgeInsets.only(bottom: 60),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child:  SizedBox(
                    width: 320,
                    height: 65,
                    child: ElevatedButton(
                        onPressed: () {
                        },
                        child: Text('Get Started',style:TextStyle(color:Colors.white,fontSize:25, fontWeight: FontWeight.normal),
                        ),
                        style:ButtonStyle(
                            backgroundColor: MaterialStateProperty.all<Color>(Color(0xff05ABA3)),
                            shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(50.0),
                              ),
                            )
                        )
                    ),
                  )
              ),
            ),

            Padding(
              padding: const EdgeInsets.only(bottom: 20),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(5.0),
                      color: Colors.white,
                    ),
                    height: 5,
                    width: 120,
                  )
                  )
            ),
          ],
        ),
      ),
    );
  }

}


问:
Screen reader cannot read text which dynamically add to button
When when I click "click me" button, I dynamically change button(class="b_button") text which is an inline div(class="b_button_label"),  the text I set as 'Search for "${inputText}"' (which with quotes) or 'Search for ${inputText}' (which without quotes).

The button(class="b_button") which has the aria-label, and the aria-label I dynamically  set as "Search for " + inputText.

I find that if I add quotes, the screen-reader can  read out “search for butterfly button”(which I set to aria-label), “search for butterfly” (which is the content of div inside button) sequentially ,when I keeping pressing down key on button(class="b_button") ,like this code:

let searchDescription = 'Search for "${inputText}"';//This text set to div

But when I delete quotes, the Narrator read out “button” (doesn’t read out aria-label), “search for butterfly” (which is the content of div inside button) sequentially, when I keeping pressing down key on button(class="b_button") ,like this code:

let searchDescription= `Search for ${inputText}`;//This text set to div

How should I understand this?  Is it a charset encoding issue or other issues?

Is it accidentally that I add quotes to solve my problem? Or the essential issue I cannot find out?

Thanks for your help.

By the way, I want to screen-reader readout “search for butterfly button”, “search for butterfly” sequentially when I keeping pressing down key on this button.

My code is below,

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
<head>
    <title>
        Create custom shape button
    </title>
</head>
<body>
    <p>
        <input name="name" class="b_input" id="b_input" value="butterfly"></input>
        <button class="b_create_text" onclick="Func()" width="100px">click me</button>
    </p>
    <button class="b_button">
        <div class="b_button_label">@("show me more information")</div>
    </button>
    <script>
        function Func() {
            let dir="ltr";
            let inputB = document.getElementById("b_input");
            let inputText = inputB.value;
            let searchDescription = 'Search for "${inputText}"';

            var sideBarLabelNodes = document.getElementsByClassName("b_button_label");
            if (sideBarLabelNodes.length == 1) {
                sideBarLabelNodes[0].textContent = searchDescription;
            }

            let el = document.getElementsByClassName('b_button');
            if(el.length == 1) {
                if(!!searchDescription) {
                    el[0].setAttribute("aria-label", "Search for " + inputText);
                }
            }
        }
    </script>
</body>
</html>
</code>```

When I view code by inspect in browser, When I click "click me" button.

```<code><button class="b_button" aria-label="Search for butterfly">
        <div class="b_button_label">Search for butterfly</div>
    </button>
</code>```

Is it that the screen-reader cannot readout aria-label when it's value is equal to button's content which dynamically set?

答:
Using single / double quotes will be string.
backtick will be eval() / Template literals

sample code :

```<code>    function test() {
        let t = 'text1';
        let n = 1;
        console.log( "#1", t );
        console.log( "#2", "${t}" );
        console.log( "#3", '${t}' );
        console.log( "#4", `${t}` );
        console.log( "#5", eval( {t} ) );
        console.log( "#6", eval( "{t}" ) );
        console.log( "#7", eval( "{n+1}" ) );
        console.log( "#8", eval( "console.log(98)" ) );
        console.log( "#9", `${console.log(99)}` );
    }
    test();

    /*
        #1 text1
        #2 ${t}
        #3 ${t}
        #4 text1
        #5
            Object { t: "text1" }
        #6 text1
        #7 2
        99 --> result by console.log(98)
        #8 undefined
        99 --> result by console.log(99)
        #9 undefined
    */
</code>```

Body:
When when I click "click me" button, I dynamically change button(class="b_button") text which is an inline div(class="b_button_label"),  the text I set as 'Search for "${inputText}"' (which with quotes) or 'Search for ${inputText}' (which without quotes).

The button(class="b_button") which has the aria-label, and the aria-label I dynamically  set as "Search for " + inputText.

I find that if I add quotes, the screen-reader can  read out “search for butterfly button”(which I set to aria-label), “search for butterfly” (which is the content of div inside button) sequentially ,when I keeping pressing down key on button(class="b_button") ,like this code:

let searchDescription = 'Search for "${inputText}"';//This text set to div

But when I delete quotes, the Narrator read out “button” (doesn’t read out aria-label), “search for butterfly” (which is the content of div inside button) sequentially, when I keeping pressing down key on button(class="b_button") ,like this code:

let searchDescription= `Search for ${inputText}`;//This text set to div

How should I understand this?  Is it a charset encoding issue or other issues?

Is it accidentally that I add quotes to solve my problem? Or the essential issue I cannot find out?

Thanks for your help.

By the way, I want to screen-reader readout “search for butterfly button”, “search for butterfly” sequentially when I keeping pressing down key on this button.

My code is below,

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>
        Create custom shape button
    </title>

        <input name="name" class="b_input" id="b_input" value="butterfly"></input>
        <button class="b_create_text" onclick="Func()" width="100px">click me</button>

    <button class="b_button">

@("show me more information")

    </button>

When I view code by inspect in browser, When I click "click me" button.

<button class="b_button" aria-label="Search for butterfly">

Search for butterfly

    </button>

Is it that the screen-reader cannot readout aria-label when it's value is equal to button's content which dynamically set?

Body:
Using single / double quotes will be string.
backtick will be eval() / Template literals

sample code :

    function test() {
        let t = 'text1';
        let n = 1;
        console.log( "#1", t );
        console.log( "#2", "${t}" );
        console.log( "#3", '${t}' );
        console.log( "#4", `${t}` );
        console.log( "#5", eval( {t} ) );
        console.log( "#6", eval( "{t}" ) );
        console.log( "#7", eval( "{n+1}" ) );
        console.log( "#8", eval( "console.log(98)" ) );
        console.log( "#9", `${console.log(99)}` );
    }
    test();

    /*
        #1 text1
        #2 ${t}
        #3 ${t}
        #4 text1
        #5
            Object { t: "text1" }
        #6 text1
        #7 2
        99 --> result by console.log(98)
        #8 undefined
        99 --> result by console.log(99)
        #9 undefined
    */


问:
Run scheduled task inside Pod in Kubernetes
I have a small instance of influxdb running in my kubernetes cluster.

The data of that instance is stored in a persistent storage.

But I also want to run the backup command from influx at scheduled interval.

```<code>influxd backup -portable /backuppath
</code>```

What I do now is exec into the pod and run it manually.

Is there a way that I can do this automatically?

答: You can consider running a CronJob with bitnami kubectl which will execute the backup command. This is the same as exec into the pod and run except now you automate it with CronJob.

Body:
I have a small instance of influxdb running in my kubernetes cluster.

The data of that instance is stored in a persistent storage.

But I also want to run the backup command from influx at scheduled interval.

influxd backup -portable /backuppath

What I do now is exec into the pod and run it manually.

Is there a way that I can do this automatically?