问:
On successful login, this.props.history.push does not take to new page as ProtectedRoute is not successful
After I receive a 200 status code, I try to go to the dashboard page. However, it does not work as intended. I am using React Context and ProtectedRoute. When I get the successful response, I call the login() function and it makes isAuthenticated as true but still does not take me to the dashboard Page.

PS: I checked and saw that in my protected route, it goes to the second part and gets redirected to "/" and hence I am on the same page. Do not know why that is happening

Signin

```<code>import { AuthContext } from './AuthContext'

async handleSubmit(event) {

        //I send the request before this

            const status = await res.status
            const json = await res.json();
            if(status === 200) {
                const {login} = this.context;
                login();
                this.props.history.push('/dashBoard')
                console.log('done')
            } else {
                console.log('not done')
            }
        } catch (error) {
            console.log('Error', error)
        }
    }
static contextType = AuthContext;

render() {
return (
<Container className="formlogin">
                <div>
                    <Form className = "signinform backg-sheet1" onSubmit={this.handleSubmit}>
                        <div>
                            <h3 style = {{color: 'white', textAlign: 'center'}}> SIGN IN </h3>
                            <Form.Group controlId = "formBasicUsername">
                                <Form.Label style = {{color: 'white'}}>Username</Form.Label>
                                <Form.Control required name = "username" type = "text" placeholder = "Enter username" onChange = {this.handleChange}/>
                            </Form.Group>

                            <Form.Group controlId = "formBasicPassword">
                                <Form.Label style = {{color: 'white'}}>Password</Form.Label>
                                <Form.Control required name = "password" type = "password" placeholder = "Enter password" onChange = {this.handleChange}/>
                            </Form.Group>

                            <div style={{textAlign: 'center'}}>
                                <Button variant="warning" type="submit">
                                    Submit
                                </Button>
                            </div>
                        </div>
                    </Form>
                </div>
            </Container>
        );
    }
}

export default withRouter(SignIn);
</code>```

App.js

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
  return (
    <div>
      <Router>
          <AuthProvider>
            <NavigationBar />
            <Switch>
              <Route exact path = '/'
                component = {LandingPage}
              />
              <Route exact path = '/register'
                component = {Register}
              />
              <ProtectedRoute exact path = '/dashBoard'
                component = {dashBoard}
              />
            </Switch>
          </AuthProvider>
      </Router>
    </div>
  );
}
}

export default App;
</code>```

AuthProvider

```<code>import React, { Component} from 'react';

export const AuthContext = React.createContext();

class AuthProvider extends Component {
    state = {
        isAuthenticated: false
    }

    constructor() {
        super()
        this.login = this.login.bind(this)
        this.logout = this.logout.bind(this)
    }

    login() {
        setTimeout(() => this.setState({ isAuthenticated: true }), 1000)
    }

    logout() {
        this.setState({ isAuthenticated: false })
    }

    render() {
        console.log(this.state.isAuthenticated)
        return(
            <AuthContext.Provider value={{isAuthenticated: this.state.isAuthenticated, login: this.login, logout: this.logout}}>
            {this.props.children}
            </AuthContext.Provider>
        )
    }
}

const AuthConsumer = AuthContext.Consumer

export { AuthProvider, AuthConsumer }
</code>```

ProtectedRoute

```<code>import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { AuthConsumer } from './AuthContext'

const ProtectedRoute = ({component: Component, ...rest}) => (
        <AuthConsumer>
            {({ isAuthenticated }) => (
                <Route

                    render={(props) =>
                        isAuthenticated?<Component {...props} /> : <Redirect to="/" />
                    }
                    {...rest}
                />
            )}
        </AuthConsumer>
)

export default ProtectedRoute
</code>```

LandingPage

```<code>import React from 'react';
import SignIn from './SignIn'
import NavigationBar from './NavigationBar'
import {Row} from 'react-bootstrap';
import './Styles.css'

class LandingPage extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                    <div className = "backg">
                        <div className = "backg-sheet">
                            <SignIn />
                        </div>
                    </div>
            </div>
        )
    }

}

export default LandingPage
</code>```

答:
You need to implement withRouter component in order for you have access with this.props.hostory... variable just like this below.</p>

```<code>import { withRouter } from 'react-router';

export default withRouter(Login);
</code>```

Body:
After I receive a 200 status code, I try to go to the dashboard page. However, it does not work as intended. I am using React Context and ProtectedRoute. When I get the successful response, I call the login() function and it makes isAuthenticated as true but still does not take me to the dashboard Page.

PS: I checked and saw that in my protected route, it goes to the second part and gets redirected to "/" and hence I am on the same page. Do not know why that is happening

Signin

import { AuthContext } from './AuthContext'

async handleSubmit(event) {

        //I send the request before this

            const status = await res.status
            const json = await res.json();
            if(status === 200) {
                const {login} = this.context;
                login();
                this.props.history.push('/dashBoard')
                console.log('done')
            } else {
                console.log('not done')
            }
        } catch (error) {
            console.log('Error', error)
        }
    }
static contextType = AuthContext;

render() {
return (
<Container className="formlogin">

                    <Form className = "signinform backg-sheet1" onSubmit={this.handleSubmit}>

 SIGN IN

                            <Form.Group controlId = "formBasicUsername">
                                <Form.Label style = {{color: 'white'}}>Username</Form.Label>
                                <Form.Control required name = "username" type = "text" placeholder = "Enter username" onChange = {this.handleChange}/>
                            </Form.Group>

                            <Form.Group controlId = "formBasicPassword">
                                <Form.Label style = {{color: 'white'}}>Password</Form.Label>
                                <Form.Control required name = "password" type = "password" placeholder = "Enter password" onChange = {this.handleChange}/>
                            </Form.Group>

                                <Button variant="warning" type="submit">
                                    Submit
                                </Button>

                    </Form>

            </Container>
        );
    }
}

export default withRouter(SignIn);

App.js

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
  return (

      <Router>
          <AuthProvider>
            <NavigationBar />
            <Switch>
              <Route exact path = '/'
                component = {LandingPage}
              />
              <Route exact path = '/register'
                component = {Register}
              />
              <ProtectedRoute exact path = '/dashBoard'
                component = {dashBoard}
              />
            </Switch>
          </AuthProvider>
      </Router>

  );
}
}

export default App;

AuthProvider

import React, { Component} from 'react';

export const AuthContext = React.createContext();

class AuthProvider extends Component {
    state = {
        isAuthenticated: false
    }

    constructor() {
        super()
        this.login = this.login.bind(this)
        this.logout = this.logout.bind(this)
    }

    login() {
        setTimeout(() => this.setState({ isAuthenticated: true }), 1000)
    }

    logout() {
        this.setState({ isAuthenticated: false })
    }

    render() {
        console.log(this.state.isAuthenticated)
        return(
            <AuthContext.Provider value={{isAuthenticated: this.state.isAuthenticated, login: this.login, logout: this.logout}}>
            {this.props.children}
            </AuthContext.Provider>
        )
    }
}

const AuthConsumer = AuthContext.Consumer

export { AuthProvider, AuthConsumer }

ProtectedRoute

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { AuthConsumer } from './AuthContext'

const ProtectedRoute = ({component: Component, ...rest}) => (
        <AuthConsumer>
            {({ isAuthenticated }) => (
                <Route

                    render={(props) =>
                        isAuthenticated?<Component {...props} /> : <Redirect to="/" />
                    }
                    {...rest}
                />
            )}
        </AuthConsumer>
)

export default ProtectedRoute

LandingPage

import React from 'react';
import SignIn from './SignIn'
import NavigationBar from './NavigationBar'
import {Row} from 'react-bootstrap';
import './Styles.css'

class LandingPage extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (

                            <SignIn />

        )
    }

}

export default LandingPage

Body:
You need to implement withRouter component in order for you have access with this.props.hostory... variable just like this below.

import { withRouter } from 'react-router';

export default withRouter(Login);


来源: stackexchange

问:
pandas plot mixing bars and lines
I have the results from two groupby operations, the first one, m_y_count, in this multiindex format (first column years and second column months):

```<code>2007    12    39
2008    1     3
        2     120
2009    6     1000
2010    1     86575
        2     726212
        3     2987954
        4     3598215
        6     160597
</code>```

and the other one, y_count, only has years:

```<code>2007    69
2008    3792
2009    5
2010    791
</code>```

My question is: How do I plot them in the same figure, with different (log) y-axes, and m_y_count with bars while y_count with a line with marker?

My attempt:

```<code>ax = y_count.plot(kind="bar", color='blue', log = True)
ax2 = ax.twinx()
m_y_count.plot(kind="bar", color='red', alpha = 0.5, ax = ax2)
</code>```

This produces the bars for both pandas Series, but when I try to change to kind="line" in the first line, no line appears.

Any hint on how to proceed? Thanks!

答:
Edit:

I forgot you wanted one as bars.

Also, if you don't want to mess with all this datetime stuff, you can just plot the years as integers on the x-axis (with months being 1/12 fractions).  But I find that using datetime is pretty smart once you get everything as a time object.

I am not so familiar with plotting stuff straight out of pandas, but you can pretty easily do this in matplotlib.  I couldn't quite copy your data in, though: to follow the example below you would have to convert your multi-index to a single datetimeindex, which I think would not be too hard.

```<code>import datetime as dt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

#making fake data
dates1 = pd.date_range('12-01-2007','06-01-2010',periods=9)
data1 = np.random.randint(0,3598215,9)
df1 = pd.DataFrame(data1,index=dates1,columns=['Values'])
dates2 = pd.date_range('01-01-2006',periods=4,freq='1Y') #i don't get why but this starts at the end of 2006, near 2007
df2 = pd.DataFrame([69,3000,5,791],index=dates2,columns=['Values'])

#plotting
fig, ax = plt.subplots()
ax.bar(df2.index,df2['Values'],width=dt.timedelta(days=200),color='red',label='df2')
ax.set_yscale('log')
ax.set_ylabel('DF2 values',color='red')

ax2 = ax.twinx()
ax2.plot(df1.index,df1['Values'],color='blue',label='df1')
ax2.set_yscale('log',)
ax2.set_ylabel('DF1 values',color='blue')

years = mdates.YearLocator() #locate years for the ticks
ax.xaxis.set_major_locator(years) #format the ticks to just show years
xfmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_formatter(xfmt)

ax.legend(loc=0)
ax2.legend(loc=2)
</code>```

I can elaborate if you can't port this to your case.

ContentLicense: CC BY-SA 4.0

Title: pandas plot mixing bars and lines

Body:
I have the results from two groupby operations, the first one, m_y_count, in this multiindex format (first column years and second column months):

2007    12    39
2008    1     3
        2     120
2009    6     1000
2010    1     86575
        2     726212
        3     2987954
        4     3598215
        6     160597

and the other one, y_count, only has years:

2007    69
2008    3792
2009    5
2010    791

My question is: How do I plot them in the same figure, with different (log) y-axes, and m_y_count with bars while y_count with a line with marker?

My attempt:

ax = y_count.plot(kind="bar", color='blue', log = True)
ax2 = ax.twinx()
m_y_count.plot(kind="bar", color='red', alpha = 0.5, ax = ax2)

This produces the bars for both pandas Series, but when I try to change to kind="line" in the first line, no line appears.

Any hint on how to proceed? Thanks!

Body:
Edit:

I forgot you wanted one as bars.

Also, if you don't want to mess with all this datetime stuff, you can just plot the years as integers on the x-axis (with months being 1/12 fractions).  But I find that using datetime is pretty smart once you get everything as a time object.

I am not so familiar with plotting stuff straight out of pandas, but you can pretty easily do this in matplotlib.  I couldn't quite copy your data in, though: to follow the example below you would have to convert your multi-index to a single datetimeindex, which I think would not be too hard.

import datetime as dt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

#making fake data
dates1 = pd.date_range('12-01-2007','06-01-2010',periods=9)
data1 = np.random.randint(0,3598215,9)
df1 = pd.DataFrame(data1,index=dates1,columns=['Values'])
dates2 = pd.date_range('01-01-2006',periods=4,freq='1Y') #i don't get why but this starts at the end of 2006, near 2007
df2 = pd.DataFrame([69,3000,5,791],index=dates2,columns=['Values'])

#plotting
fig, ax = plt.subplots()
ax.bar(df2.index,df2['Values'],width=dt.timedelta(days=200),color='red',label='df2')
ax.set_yscale('log')
ax.set_ylabel('DF2 values',color='red')

ax2 = ax.twinx()
ax2.plot(df1.index,df1['Values'],color='blue',label='df1')
ax2.set_yscale('log',)
ax2.set_ylabel('DF1 values',color='blue')

years = mdates.YearLocator() #locate years for the ticks
ax.xaxis.set_major_locator(years) #format the ticks to just show years
xfmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_formatter(xfmt)

ax.legend(loc=0)
ax2.legend(loc=2)

I can elaborate if you can't port this to your case.


问:
How to use functions in Javascript to bulid an interactive text?
I'm trying to build an interactive text with Javascript. I can do it by using a new function each element I create, but if I do that I'll have too many functions.

Could somebody tell me what is wrong with the following code and what I should do so it works?
Thanks in advance.

<!DOCTYPE html>

Name:

        <button id="peter" onclick="includeName1(peter)">Peter</button>
        <button id="paul" onclick="includeName1(paul)">Paul</button>

Wife's name

        <button id="mary" onclick="includeName2(mary)">Mary</button>
        <button id="emma" onclick="includeName2(emma)">Emma</button>

How long have you been married?

        <input id="years" type="number" oninput="includeTime()">

My name is . I'm married to . We've been married for  years.

```

答:
For the record...
this code should be more readable on this way:

const inTexts = document.getElementById('interractiv-texts')
  ,   outText = document.getElementById('Out-Text')
  ,   tVals   = {  man: '', wife: '', years: '' }
  ;
const setText = e =>
  {
  if (!e.target.matches('[data-part]')) return
  tVals[e.target.dataset.part] = e.target.value
  outText.textContent = `My name is ${tVals.man}, I'm married to ${tVals.wife}. We've been married for ${tVals.years} years.`
  }
inTexts.oninput = setText
inTexts.onclick = setText```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="interractiv-texts">
  <p>Name:</p>
  <select data-part="man">
    <option value="Peter">Peter</option>
    <option value="Paul">Paul</option>
    <option value="John">John</option>
  </select>

  <p>Wife's name</p>
  <button value="Mary" data-part="wife">Mary</button>
  <button value="Emma" data-part="wife">Emma</button>
  <p>How long have you been married?</p>
  <input data-part="years" type="number" >
</div>

  <p id="Out-Text"></p></code>```

Body:
For the record...
this code should be more readable on this way:

const inTexts = document.getElementById('interractiv-texts')
  ,   outText = document.getElementById('Out-Text')
  ,   tVals   = {  man: '', wife: '', years: '' }
  ;
const setText = e =>
  {
  if (!e.target.matches('[data-part]')) return
  tVals[e.target.dataset.part] = e.target.value
  outText.textContent = `My name is ${tVals.man}, I'm married to ${tVals.wife}. We've been married for ${tVals.years} years.`
  }
inTexts.oninput = setText
inTexts.onclick = setText

<div id="interractiv-texts">
  <p>Name:</p>
  <select data-part="man">
    <option value="Peter">Peter</option>
    <option value="Paul">Paul</option>
    <option value="John">John</option>
  </select>

  <p>Wife's name</p>
  <button value="Mary" data-part="wife">Mary</button>
  <button value="Emma" data-part="wife">Emma</button>
  <p>How long have you been married?</p>
  <input data-part="years" type="number" >
</div>

  <p id="Out-Text"></p>


问:
Plotting sorted data
I would need to plot accounts through time, by sorting opening account.

I have the following two columns, one for the Accounts and one for OpenTime (it is datetime):

```<code>Account Name          OpenTime
ABC                 2002/05/20
BAB                 2012/07/24
CMN                 2012/07/24
GKS                 2001/12/05
EIR                 2018/04/21
</code>```

I would like to see on the chart Account Names in the following order:

```<code>GKS    ABC     BAB,CMN      EIR
</code>```

How can I get this result?

答:
```<code>import matplotlib.pyplot as plt
plt.plot( da['Account Name'],da['OpenTime'], 'o-', linewidth=2)
</code>```

does this answers plotting part?

Title: Plotting sorted data

Body:
I would need to plot accounts through time, by sorting opening account.

I have the following two columns, one for the Accounts and one for OpenTime (it is datetime):

Account Name          OpenTime
ABC                 2002/05/20
BAB                 2012/07/24
CMN                 2012/07/24
GKS                 2001/12/05
EIR                 2018/04/21

I would like to see on the chart Account Names in the following order:

GKS    ABC     BAB,CMN      EIR

How can I get this result?

Body:
import matplotlib.pyplot as plt
plt.plot( da['Account Name'],da['OpenTime'], 'o-', linewidth=2)

does this answers plotting part?


问:
Scaling and listing deployments via Kubernetes HTTP API?
I'm trying to scale up/down some deployments over HTTP and also list the deployments on my cluster. I'm able to list pods, but can't figure out the deployments piece.

http://localhost:8080/api/v1/namespaces/default/deployments

```<code>{
    "kind": "Status",
    "apiVersion": "v1",
    "metadata": {},
    "status": "Failure",
    "message": "the server could not find the requested resource",
    "reason": "NotFound",
    "details": {},
    "code": 404
}
</code>```

答:
Deployments are in the apps/v1 namespace, and you need to include apps in the URL.  The API documentation for the "list deployments" endpoint gives the URL as

```<code>GET /apis/apps/v1/namespaces/{namespace}/deployments
</code>```

You can use the normal read-modify-write sequence to change the replicas: field in a deployment spec to scale it.

There is also a dedicated endpoint to scale deployments, though it's slightly underdocumented.  Manage replicas count for deployment using Kubernetes API
 suggests reading and patching the scale resource, or there is an example with a minimal JSON payload.

Body:
I'm trying to scale up/down some deployments over HTTP and also list the deployments on my cluster. I'm able to list pods, but can't figure out the deployments piece.

http://localhost:8080/api/v1/namespaces/default/deployments

{
    "kind": "Status",
    "apiVersion": "v1",
    "metadata": {},
    "status": "Failure",
    "message": "the server could not find the requested resource",
    "reason": "NotFound",
    "details": {},
    "code": 404
}

Body:
Deployments are in the apps/v1 namespace, and you need to include apps in the URL.  The API documentation for the "list deployments" endpoint gives the URL as

GET /apis/apps/v1/namespaces/{namespace}/deployments

You can use the normal read-modify-write sequence to change the replicas: field in a deployment spec to scale it.

There is also a dedicated endpoint to scale deployments, though it's slightly underdocumented.  Manage replicas count for deployment using Kubernetes API
 suggests reading and patching the scale resource, or there is an example with a minimal JSON payload.


问:
The storage engine MEMORY doesn't support FULLTEXT indexes
I'm in the process of changing a small web application I work on from using LIKE to MATCH for string queries, but I'm having an issue with a specific query that I need to get working (not the full query, but for the sake of brevity I've removed everything extra):

```<code>SET @n=0;
SET @pubdate='';
SELECT a.idArticle, CONCAT(a.date, '_', LPAD(a.n, 3, '0')) as alt_id, a.source, a.title, a.datetime
FROM (SELECT idArticle,title,datetime,source, @n:=CASE WHEN @pubdate = date(datetime) THEN @n + 1 ELSE 1 END AS n, @pubdate:=date(datetime) as date FROM article ORDER BY date, idArticle) a
WHERE (MATCH(title) AGAINST ('query') )
ORDER BY a.idArticle DESC
</code>```

This query allows me to generate an ID for an article in the format of "YYYY-MM-DD_n", where the date is the article's publication date and n is the Nth article entered into the database with that date (so the 22nd article published on May 20, 2020 would be 2020-05-20_022).

Upon running the query, I get the error:

```<code>#1214 - The storage engine MEMORY doesn't support FULLTEXT indexes
</code>```

Similar questions asked here tell people to change InnoDB to MyISAM because InnoDB used to not support fulltext searching. I'm running MariaDB 10.3.16 via XAMPP and it must be recent enough to where that doesn't apply, as a query like this works, and according to SHOW TABLE STATUS FROM database, all my tables run on InnoDB:

```<code>SELECT * from article WHERE MATCH(title) AGAINST ("query")
</code>```

So, it seems to be the fancy incrementing subquery but I don't know why this causes a problem. What's going wrong, and what can I do to fix it?

答:
Since MEMORY tables are lost on restart, all indexes on such tables are lost.  FULLTEXT is non-trivial to rebuild.  What's wrong with simply creating an InnoDB table instead of a MEMORY table?

Beware of @ variables; they may not act the way you expect, especially when using subqueries.

Body:
I'm in the process of changing a small web application I work on from using LIKE to MATCH for string queries, but I'm having an issue with a specific query that I need to get working (not the full query, but for the sake of brevity I've removed everything extra):

SET @n=0;
SET @pubdate='';
SELECT a.idArticle, CONCAT(a.date, '_', LPAD(a.n, 3, '0')) as alt_id, a.source, a.title, a.datetime
FROM (SELECT idArticle,title,datetime,source, @n:=CASE WHEN @pubdate = date(datetime) THEN @n + 1 ELSE 1 END AS n, @pubdate:=date(datetime) as date FROM article ORDER BY date, idArticle) a
WHERE (MATCH(title) AGAINST ('query') )
ORDER BY a.idArticle DESC

This query allows me to generate an ID for an article in the format of "YYYY-MM-DD_n", where the date is the article's publication date and n is the Nth article entered into the database with that date (so the 22nd article published on May 20, 2020 would be 2020-05-20_022).

Upon running the query, I get the error:

#1214 - The storage engine MEMORY doesn't support FULLTEXT indexes

Similar questions asked here tell people to change InnoDB to MyISAM because InnoDB used to not support fulltext searching. I'm running MariaDB 10.3.16 via XAMPP and it must be recent enough to where that doesn't apply, as a query like this works, and according to SHOW TABLE STATUS FROM database, all my tables run on InnoDB:

SELECT * from article WHERE MATCH(title) AGAINST ("query")

So, it seems to be the fancy incrementing subquery but I don't know why this causes a problem. What's going wrong, and what can I do to fix it?


问:
Empty EditText value displayed in AlertDialog
I am new in Android development and I got a problem. I have 2 EditText fields of login and password and 1 Button. When I click on the Button, I am getting AlertDialog with message "Logged in as " but I need it to be "Logged in as *value entered into "login" EditText".
The EditText value is always empty. It's just a simple implementation, but it doesn't work.
What am I doing wrong here?

Here is the code:

```<code>public class FirstFragment extends Fragment {
    EditText loginText;
    EditText passwText;
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        View view2 = inflater.inflate(R.layout.fragment_first, null, false);

        loginText = (EditText)view2.findViewById(R.id.loginText);
        passwText = (EditText)view2.findViewById(R.id.passText);
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick( View view) {
                handleLoginDialog();
            }
        });
    }

    private void handleLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //View view2 = getLayoutInflater().inflate(R.layout.fragment_first, null, false);

        String st = loginText.getText().toString();

        if (loginText != null && passwText != null){
            builder.setMessage("Logged in as " + st);
        }
        else
            builder.setMessage("Login or password was not entered!" );
        builder.show();
    }
}
</code>```

答: The safe side would be to send the loginText as string parameter in handleLoginDialog method and check there if the string is empty.

Body:
I am new in Android development and I got a problem. I have 2 EditText fields of login and password and 1 Button. When I click on the Button, I am getting AlertDialog with message "Logged in as " but I need it to be "Logged in as *value entered into "login" EditText".
The EditText value is always empty. It's just a simple implementation, but it doesn't work.
What am I doing wrong here?

Here is the code:

public class FirstFragment extends Fragment {
    EditText loginText;
    EditText passwText;
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        View view2 = inflater.inflate(R.layout.fragment_first, null, false);

        loginText = (EditText)view2.findViewById(R.id.loginText);
        passwText = (EditText)view2.findViewById(R.id.passText);
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick( View view) {
                handleLoginDialog();
            }
        });
    }

    private void handleLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //View view2 = getLayoutInflater().inflate(R.layout.fragment_first, null, false);

        String st = loginText.getText().toString();

        if (loginText != null && passwText != null){
            builder.setMessage("Logged in as " + st);
        }
        else
            builder.setMessage("Login or password was not entered!" );
        builder.show();
    }
}


问:
Cannot find the element on the page using Xpath in selenium
I need to obtain prices for the trips between every two stations in Metro North so I wrote the program to webscrape their website. But it does not work as it cannot find the prices on the page.

```<code>driver = webdriver.Chrome('/Users/miss_evgenia/Desktop/path/chromedriver')
driver.get("http://as0.mta.info/mnr/schedules/sched_form.cfm")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='Vorig_station']"))).click()
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='Vorig_station']"))))
select.select_by_visible_text('ANSONIA')
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='Vdest_station']"))))
select.select_by_visible_text('WATERBURY')
elem = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@value='fares']")))
elem.click()
time.sleep(3)
price1 =  driver.find_element_by_xpath('//*[@id="contentbox"]/div/table[1]/tbody/tr[2]/td[2]').text
price2 = driver.find_element_by_xpath('//*[@id="contentbox"]/div/table[1]/tbody/tr[2]/td[3]').text
print(price1)
print(price2)
</code>```

The prices are the red circles on the picture:

Please help me to obtain these two numbers.

答:
This should do it

```<code>On Board: (//td/a[contains(text(), 'One Way Intermediate')]/following::td)[1]
Station: (//td/a[contains(text(), 'One Way Intermediate')]/following::td)[2]
</code>```

All of the cells are too similar, you need to define a starting point and find the correct cell by relation.

Body:
I need to obtain prices for the trips between every two stations in Metro North so I wrote the program to webscrape their website. But it does not work as it cannot find the prices on the page.

driver = webdriver.Chrome('/Users/miss_evgenia/Desktop/path/chromedriver')
driver.get("http://as0.mta.info/mnr/schedules/sched_form.cfm")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='Vorig_station']"))).click()
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='Vorig_station']"))))
select.select_by_visible_text('ANSONIA')
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='Vdest_station']"))))
select.select_by_visible_text('WATERBURY')
elem = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@value='fares']")))
elem.click()
time.sleep(3)
price1 =  driver.find_element_by_xpath('//*[@id="contentbox"]/div/table[1]/tbody/tr[2]/td[2]').text
price2 = driver.find_element_by_xpath('//*[@id="contentbox"]/div/table[1]/tbody/tr[2]/td[3]').text
print(price1)
print(price2)

The prices are the red circles on the picture:

Please help me to obtain these two numbers.

Body:
This should do it

On Board: (//td/a[contains(text(), 'One Way Intermediate')]/following::td)[1]
Station: (//td/a[contains(text(), 'One Way Intermediate')]/following::td)[2]

All of the cells are too similar, you need to define a starting point and find the correct cell by relation.


问:
Displaying UTF-8 Emoji in Java
Say I have the  (devil) emoji.

In 4-byte UTF-8, it's represented like so: \u00f0\u009f\u0098\u0088

However, in Java, it will only print correctly like so: \ud83d\ude08

How would I convert from the first to the second?

UPDATE 2

MNEMO's answer is much simpler, and answers my question, so it's probably better to go with his solution.

UPDATE

Thanks Basil Bourque for the write-up.  It was very interesting.

I found a good reference here: https://github.com/pRizz/Unicode-Converter/blob/master/conversionfunctions.js (particularly the convertUTF82Char() function).

For anyone wandering by here in the future, here's what that looks like in Java:

```<code>public static String fromCharCode(int n) {
    char c = (char)n;
    return Character.toString(c);
}

public static String decToChar(int n) {
    // converts a single string representing a decimal number to a character
    // note that no checking is performed to ensure that this is just a hex number, eg. no spaces etc
    // dec: string, the dec codepoint to be converted
    String result = "";
    if (n <= 0xFFFF) {
        result += fromCharCode(n);
    } else if (n <= 0x10FFFF) {
        n -= 0x10000;
        result += fromCharCode(0xD800 | (n >> 10)) + fromCharCode(0xDC00 | (n & 0x3FF));
    } else {
        result += "dec2char error: Code point out of range: " + decToHex(n);
    }

    return result;
}

public static String decToHex(int n) {
    return Integer.toHexString(n).toUpperCase();
}

public static String convertUTF8_toChar(String str) {
    // converts to characters a sequence of space-separated hex numbers representing bytes in utf8
    // str: string, the sequence to be converted
    var outputString = "";
    var counter = 0;
    var n = 0;

    // remove leading and trailing spaces
    str = str.replaceAll("/^\\s+/", "");
    str = str.replaceAll("/\\s+$/", "");
    if (str.length() == 0) {
        return "";
    }

    str = str.replaceAll("/\\s+/g", " ");

    var listArray = str.split(" ");
    for (var i = 0; i < listArray.length; i++) {
        int b = parseInt(listArray[i], 16); // alert('b:'+dec2hex(b));
        switch (counter) {
            case 0:
                if (0 <= b && b <= 0x7F) { // 0xxxxxxx
                    outputString += decToChar(b);
                } else if (0xC0 <= b && b <= 0xDF) { // 110xxxxx
                    counter = 1;
                    n = b & 0x1F;
                } else if (0xE0 <= b && b <= 0xEF) { // 1110xxxx
                    counter = 2;
                    n = b & 0xF;
                } else if (0xF0 <= b && b <= 0xF7) { // 11110xxx
                    counter = 3;
                    n = b & 0x7;
                } else {
                    outputString += "convertUTF82Char: error1 " + decToHex(b) + "! ";
                }
                break;
            case 1:
                if (b < 0x80 || b > 0xBF) {
                    outputString += "convertUTF82Char: error2 " + decToHex(b) + "! ";
                }
                counter--;
                outputString += decToChar((n << 6) | (b - 0x80));
                n = 0;
                break;
            case 2:
            case 3:
                if (b < 0x80 || b > 0xBF) {
                    outputString += "convertUTF82Char: error3 " + decToHex(b) + "! ";
                }
                n = (n << 6) | (b - 0x80);
                counter--;
                break;
        }
    }

    return outputString.replaceAll("/ $/", "");
}
</code>```

Pretty much a 1-for-1 copy, but it accomplishes my goal.

答:
well, this is quite unnecessary to add, but after you understand all character encoding system and Unicode concept, following code might work for you.</p>

```<code>byte[] a = { (byte)0xf0, (byte)0x9f, (byte)0x98, (byte)0x88 };
String s = new String(a,"UTF-8");
byte[] b = s.getBytes("UTF-16BE");
for ( byte c : b ) { System.out.printf("%02x ",c); }
</code>```

Title: Displaying UTF-8 Emoji in Java

Body:
Say I have the  (devil) emoji.

In 4-byte UTF-8, it's represented like so: \u00f0\u009f\u0098\u0088

However, in Java, it will only print correctly like so: \ud83d\ude08

How would I convert from the first to the second?

UPDATE 2

MNEMO's answer is much simpler, and answers my question, so it's probably better to go with his solution.

UPDATE

Thanks Basil Bourque for the write-up.  It was very interesting.

I found a good reference here: https://github.com/pRizz/Unicode-Converter/blob/master/conversionfunctions.js (particularly the convertUTF82Char() function).

For anyone wandering by here in the future, here's what that looks like in Java:

public static String fromCharCode(int n) {
    char c = (char)n;
    return Character.toString(c);
}

public static String decToChar(int n) {
    // converts a single string representing a decimal number to a character
    // note that no checking is performed to ensure that this is just a hex number, eg. no spaces etc
    // dec: string, the dec codepoint to be converted
    String result = "";
    if (n <= 0xFFFF) {
        result += fromCharCode(n);
    } else if (n <= 0x10FFFF) {
        n -= 0x10000;
        result += fromCharCode(0xD800 | (n >> 10)) + fromCharCode(0xDC00 | (n & 0x3FF));
    } else {
        result += "dec2char error: Code point out of range: " + decToHex(n);
    }

    return result;
}

public static String decToHex(int n) {
    return Integer.toHexString(n).toUpperCase();
}

public static String convertUTF8_toChar(String str) {
    // converts to characters a sequence of space-separated hex numbers representing bytes in utf8
    // str: string, the sequence to be converted
    var outputString = "";
    var counter = 0;
    var n = 0;

    // remove leading and trailing spaces
    str = str.replaceAll("/^\\s+/", "");
    str = str.replaceAll("/\\s+$/", "");
    if (str.length() == 0) {
        return "";
    }

    str = str.replaceAll("/\\s+/g", " ");

    var listArray = str.split(" ");
    for (var i = 0; i < listArray.length; i++) {
        int b = parseInt(listArray[i], 16); // alert('b:'+dec2hex(b));
        switch (counter) {
            case 0:
                if (0 <= b && b <= 0x7F) { // 0xxxxxxx
                    outputString += decToChar(b);
                } else if (0xC0 <= b && b <= 0xDF) { // 110xxxxx
                    counter = 1;
                    n = b & 0x1F;
                } else if (0xE0 <= b && b <= 0xEF) { // 1110xxxx
                    counter = 2;
                    n = b & 0xF;
                } else if (0xF0 <= b && b <= 0xF7) { // 11110xxx
                    counter = 3;
                    n = b & 0x7;
                } else {
                    outputString += "convertUTF82Char: error1 " + decToHex(b) + "! ";
                }
                break;
            case 1:
                if (b < 0x80 || b > 0xBF) {
                    outputString += "convertUTF82Char: error2 " + decToHex(b) + "! ";
                }
                counter--;
                outputString += decToChar((n << 6) | (b - 0x80));
                n = 0;
                break;
            case 2:
            case 3:
                if (b < 0x80 || b > 0xBF) {
                    outputString += "convertUTF82Char: error3 " + decToHex(b) + "! ";
                }
                n = (n << 6) | (b - 0x80);
                counter--;
                break;
        }
    }

    return outputString.replaceAll("/ $/", "");
}

Pretty much a 1-for-1 copy, but it accomplishes my goal.

Body:
well, this is quite unnecessary to add, but after you understand all character encoding system and Unicode concept, following code might work for you.

byte[] a = { (byte)0xf0, (byte)0x9f, (byte)0x98, (byte)0x88 };
String s = new String(a,"UTF-8");
byte[] b = s.getBytes("UTF-16BE");
for ( byte c : b ) { System.out.printf("%02x ",c); }


问:
How to cause soft references to be cleared in Java?
I have a cache which has soft references to the cached objects. I am trying to write a functional test for behavior of classes which use the cache specifically for what happens when the cached objects are cleared.

The problem is: I can't seem to reliably get the soft references to be cleared. Simply using up a bunch of memory doesn't do the trick: I get an OutOfMemory before any soft references are cleared.

Is there any way to get Java to more eagerly clear up the soft references?

Found here:

"It is guaranteed though that all
  SoftReferences will get cleared before
  OutOfMemoryError is thrown, so they
  theoretically can't cause an OOME."

So does this mean that the above scenario MUST mean I have a memory leak somewhere with some class holding a hard reference on my cached object?

答: If you have a cache which is a Map of SoftReferences and you want them cleared you can just clear() the map and they will all be cleaned up (including their references)</p>

OwnerDisplayName: Epaga

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Peter Lawrey


问:
How to format string from bash script? - Raspberry Pi
So, when you run uptime, you get the uptime of your pi, if you run uptime -p, you get up 32 minutes, how can I make it only output JUST the minutes i.e. 32?

答:
Like this:

```<code>uptime -p | cut -d' ' -f2-
</code>```

But if you have days/hours unlike your example, this snippet don't convert these in minutes. For this, consider:

```<code>uptime -p |
perl -ne '
    if (/^up (?<weeks>\d+) weeks, (?<hours>\d+) hours, (?<minutes>\d+) min/) {
        push @{ $data->{$_} }, $+{$_} for keys %+;
        print $data->{weeks}*168+$data->{hours}*60+$data->{minutes} . " mn\n";
    }
'
</code>```

Body:
Like this:

uptime -p | cut -d' ' -f2-

But if you have days/hours unlike your example, this snippet don't convert these in minutes. For this, consider:

uptime -p |
perl -ne '
    if (/^up (?<weeks>\d+) weeks, (?<hours>\d+) hours, (?<minutes>\d+) min/) {
        push @{ $data->{$_} }, $+{$_} for keys %+;
        print $data->{weeks}*168+$data->{hours}*60+$data->{minutes} . " mn\n";
    }
'


问:
How do you select a string value left of a specified section of a string, not including empty space?
Using vanilla javascript, how do you select the first string value left of a specified section of a string and not include the empty space?

For example, there is a string 1 hr 30 min

How do you get the 1 value left of hr and how do you get the 30 value left of min?

```<code>var string = "1 hr 30 min";
if (string.includes("hr")) {
    // get the 1 value
}
if (string.includes("min")) {
    // get the 30 value
}
</code>```

答:
It can be done this way, you will have good control on the way out.

If you can guarantee the input string in the function.

"use strict";
function zeroFill(str, width) {
    width -= str.toString().length;
    if (width > 0) {
        return new Array(width + (/\./.test(str) ? 2 : 1)).join('0') + str;
    }
    return str + ""; // always return a string
}
function getHoursOrMin(str, extract, returnType) {
    const _str = str.split(' ');
    let result = "";
    switch (extract) {
        case 'hr':
            const iHr = _str.indexOf('hr');
            result = _str[iHr - 1];
            break;
        case 'min':
            const iMin = _str.indexOf('min');
            result = _str[iMin - 1];
            break;
    }
    switch (returnType) {
        case 'number':
            return Number(result);
        case 'string':
            return result;
        case 'stringZeroFill':
            return zeroFill(result, 2);
    }
}
const str = "1 hr 30 min";
console.log(`${getHoursOrMin(str, 'hr', 'number')}:${getHoursOrMin(str, 'min', 'number')}`);
console.log(`${getHoursOrMin(str, 'hr', 'string')}:${getHoursOrMin(str, 'min', 'string')}`);
console.log(`${getHoursOrMin(str, 'hr', 'stringZeroFill')}:${getHoursOrMin(str, 'min', 'stringZeroFill')}`);
 ```

Body:
Using vanilla javascript, how do you select the first string value left of a specified section of a string and not include the empty space?

For example, there is a string 1 hr 30 min

How do you get the 1 value left of hr and how do you get the 30 value left of min?

var string = "1 hr 30 min";
if (string.includes("hr")) {
    // get the 1 value
}
if (string.includes("min")) {
    // get the 30 value
}


问:
How to disable screen snip in notification area?
I am developing a capture preventing software, but I can not prevent capturing by using screen snip in notification area (at Windows 10 1909).
I want to disable it.
How to disable screen snip in notification area programmatically?
Please help me.</p>

答:
You can make the screen snip invisible in the notification area by adding a new value to the registry.

Run regedit.exe and add a new value called Microsoft.QuickAction.ScreenClipping under HKEY_CURRENT_USER\Control Panel\Quick Actions\Control Center\Unpinned.

The value type is REG_BINARY and value data does not need to be set.

Then you can see that the screen snip has disappeared in the notification area.


问:
What's the best way to calculate the size of a directory in .NET?
I've written the following routine to manually traverse through a directory and calculate its size in C#/.NET:

```
<code>
protected static float CalculateFolderSize(string folder)
{
    float folderSize = 0.0f;
    try
    {
        //Checks if the path is valid or not
        if (!Directory.Exists(folder))
            return folderSize;
        else
        {
            try
            {
                foreach (string file in Directory.GetFiles(folder))
                {
                    if (File.Exists(file))
                    {
                        FileInfo finfo = new FileInfo(file);
                        folderSize += finfo.Length;
                    }
                }

                foreach (string dir in Directory.GetDirectories(folder))
                    folderSize += CalculateFolderSize(dir);
            }
            catch (NotSupportedException e)
            {
                Console.WriteLine("Unable to calculate folder size: {0}", e.Message);
            }
        }
    }
    catch (UnauthorizedAccessException e)
    {
        Console.WriteLine("Unable to calculate folder size: {0}", e.Message);
    }
    return folderSize;
}
</code>
```

I have an application which is running this routine repeatedly for a large number of folders.  I'm wondering if there's a more efficient way to calculate the size of a folder with .NET?  I didn't see anything specific in the framework.  Should I be using P/Invoke and a Win32 API?  What's the most efficient way of calculating the size of a folder in .NET?

答:
I try to change the sample (Alexandre Pepin and hao's Answer)

As is

```<code>    private long GetDirectorySize(string dirPath)
    {
        if (Directory.Exists(dirPath) == false)
        {
            return 0;
        }

        DirectoryInfo dirInfo = new DirectoryInfo(dirPath);

        long size = 0;

        // Add file sizes.
        FileInfo[] fis = dirInfo.GetFiles();
        foreach (FileInfo fi in fis)
        {
            size += fi.Length;
        }

        // Add subdirectory sizes.
        DirectoryInfo[] dis = dirInfo.GetDirectories();
        foreach (DirectoryInfo di in dis)
        {
            size += GetDirectorySize(di.FullName);
        }

        return size;
    }
</code>```

To be

```<code>    private long GetDirectorySize2(string dirPath)
    {
        if (Directory.Exists(dirPath) == false)
        {
            return 0;
        }

        DirectoryInfo dirInfo = new DirectoryInfo(dirPath);

        long size = 0;

        // Add file sizes.
        IEnumerable<FileInfo> fis = dirInfo.EnumerateFiles("*.*", SearchOption.AllDirectories);
        foreach (FileInfo fi in fis)
        {
            size += fi.Length;
        }

        return size;
    }
</code>```

finally you can check the result

```<code>        // ---------------------------------------------
        // size of directory
        using System.IO;

        string log1Path = @"D:\SampleDirPath1";
        string log2Path = @"D:\SampleDirPath2";
        string log1DirName = Path.GetDirectoryName(log1Path);
        string log2DirName = Path.GetDirectoryName(log2Path);
        long log1Size = GetDirectorySize(log1Path);
        long log2Size = GetDirectorySize(log2Path);
        long log1Size2 = GetDirectorySize2(log1Path);
        long log2Size2 = GetDirectorySize2(log2Path);

        Console.WriteLine($@"{log1DirName} Size: {SizeSuffix(log1Size)}, {SizeSuffix(log1Size2)}
        {log2DirName} Size: {SizeSuffix(log2Size)}, {SizeSuffix(log2Size2)}");
</code>```

and this is the SizeSuffix function

```<code>    private static readonly string[] SizeSuffixes =
               { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

    /// <summary>
    /// Size Display
    /// </summary>
    /// <param name="value">bytes 數值</param>
    /// <param name="decimalPlaces">小數位數</param>
    /// <returns></returns>
    public static string SizeSuffix(Int64 value, int decimalPlaces = 2)
    {
        if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
        if (value < 0) { return "-" + SizeSuffix(-value); }
        if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }

        // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
        int mag = (int)Math.Log(value, 1024);

        // 1L << (mag * 10) == 2 ^ (10 * mag)
        // [i.e. the number of bytes in the unit corresponding to mag]
        decimal adjustedSize = (decimal)value / (1L << (mag * 10));

        // make adjustment when the value is large enough that
        // it would round up to 1000 or more
        if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
        {
            mag += 1;
            adjustedSize /= 1024;
        }

        return string.Format("{0:n" + decimalPlaces + "} {1}",
            adjustedSize,
            SizeSuffixes[mag]);
    }
</code>```

OwnerDisplayName: Steve W

Body:
I've written the following routine to manually traverse through a directory and calculate its size in C#/.NET:

protected static float CalculateFolderSize(string folder)
{
    float folderSize = 0.0f;
    try
    {
        //Checks if the path is valid or not
        if (!Directory.Exists(folder))
            return folderSize;
        else
        {
            try
            {
                foreach (string file in Directory.GetFiles(folder))
                {
                    if (File.Exists(file))
                    {
                        FileInfo finfo = new FileInfo(file);
                        folderSize += finfo.Length;
                    }
                }

                foreach (string dir in Directory.GetDirectories(folder))
                    folderSize += CalculateFolderSize(dir);
            }
            catch (NotSupportedException e)
            {
                Console.WriteLine("Unable to calculate folder size: {0}", e.Message);
            }
        }
    }
    catch (UnauthorizedAccessException e)
    {
        Console.WriteLine("Unable to calculate folder size: {0}", e.Message);
    }
    return folderSize;
}

I have an application which is running this routine repeatedly for a large number of folders.  I'm wondering if there's a more efficient way to calculate the size of a folder with .NET?  I didn't see anything specific in the framework.  Should I be using P/Invoke and a Win32 API?  What's the most efficient way of calculating the size of a folder in .NET?

Body:
I try to change the sample (Alexandre Pepin and hao's Answer)

As is

    private long GetDirectorySize(string dirPath)
    {
        if (Directory.Exists(dirPath) == false)
        {
            return 0;
        }

        DirectoryInfo dirInfo = new DirectoryInfo(dirPath);

        long size = 0;

        // Add file sizes.
        FileInfo[] fis = dirInfo.GetFiles();
        foreach (FileInfo fi in fis)
        {
            size += fi.Length;
        }

        // Add subdirectory sizes.
        DirectoryInfo[] dis = dirInfo.GetDirectories();
        foreach (DirectoryInfo di in dis)
        {
            size += GetDirectorySize(di.FullName);
        }

        return size;
    }

To be

    private long GetDirectorySize2(string dirPath)
    {
        if (Directory.Exists(dirPath) == false)
        {
            return 0;
        }

        DirectoryInfo dirInfo = new DirectoryInfo(dirPath);

        long size = 0;

        // Add file sizes.
        IEnumerable<FileInfo> fis = dirInfo.EnumerateFiles("*.*", SearchOption.AllDirectories);
        foreach (FileInfo fi in fis)
        {
            size += fi.Length;
        }

        return size;
    }

finally you can check the result

        // ---------------------------------------------
        // size of directory
        using System.IO;

        string log1Path = @"D:\SampleDirPath1";
        string log2Path = @"D:\SampleDirPath2";
        string log1DirName = Path.GetDirectoryName(log1Path);
        string log2DirName = Path.GetDirectoryName(log2Path);
        long log1Size = GetDirectorySize(log1Path);
        long log2Size = GetDirectorySize(log2Path);
        long log1Size2 = GetDirectorySize2(log1Path);
        long log2Size2 = GetDirectorySize2(log2Path);

        Console.WriteLine($@"{log1DirName} Size: {SizeSuffix(log1Size)}, {SizeSuffix(log1Size2)}
        {log2DirName} Size: {SizeSuffix(log2Size)}, {SizeSuffix(log2Size2)}");

and this is the SizeSuffix function

    private static readonly string[] SizeSuffixes =
               { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

    /// <summary>
    /// Size Display
    /// </summary>
    /// <param name="value">bytes 數值</param>
    /// <param name="decimalPlaces">小數位數</param>
    /// <returns></returns>
    public static string SizeSuffix(Int64 value, int decimalPlaces = 2)
    {
        if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
        if (value < 0) { return "-" + SizeSuffix(-value); }
        if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }

        // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
        int mag = (int)Math.Log(value, 1024);

        // 1L << (mag * 10) == 2 ^ (10 * mag)
        // [i.e. the number of bytes in the unit corresponding to mag]
        decimal adjustedSize = (decimal)value / (1L << (mag * 10));

        // make adjustment when the value is large enough that
        // it would round up to 1000 or more
        if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
        {
            mag += 1;
            adjustedSize /= 1024;
        }

        return string.Format("{0:n" + decimalPlaces + "} {1}",
            adjustedSize,
            SizeSuffixes[mag]);
    }


问:
How to drop a class (table) in Back4app Dashboard
I'm new to parse and back4app. While I'm trying to delete a class (table) in the dashboard, I can't find any menu item that allows me to do it. Can anybody point me to the right direction?

Also related, is it possible to change a column's name after it is added, and is it possible to bulk update rows for certain fields, all within the dashboard?

答:
In order to delete the class, it must be empty, so you firstly need to delete all rows before deleting the class.

It's not possible to edit the column's name from the dashboard, so, what you may do is exporting the data and import your JSON file with the right name.

Another option that is not recommended if you're not sure about it, is updating the column's name through Mongo commands.

You'll need to update it in the collection (the class) and in the SCHEMAS too.

The connection string to help you with the mongo commands is available at Server Settings > Core Settings > Settings > MongoDB Database URI.


问:
Horizontal carousel for non-dynamic container widgets in flutter
I'm trying to build a horizontal carousel of container widgets - i.e. the user simply scrolls horizontally to view the 6 container widgets I have.

How can I implement this?

I have tried using SingleChildScrollView() - and placed in there a Row() widget, but that didn't do anything.. nothing scrolled.

```<code>Row(children: [
Container(child: Card(child: Text('Unit 1'))),
Container(child: Card(child: Text('Unit 2'))),
Container(child: Card(child: Text('Unit 3'))),
Container(child: Card(child: Text('Unit 4'))),
Container(child: Card(child: Text('Unit 5'))),
Container(child: Card(child: Text('Unit 6'))),

]),
</code>```

I'd like each container to be on the same row, and the end user able to scroll horizontally to view each item,

How would you implement this?

答:
You can copy paste run full code below

You can use package https://pub.dev/packages/flutter_mobile_carousel

You can use rowCount to define how many items need to show at the same time

code snippet

```<code> Carousel(rowCount: 4, children: [
              Container(child: Card(child: Text('Unit 1'))),
              Container(child: Card(child: Text('Unit 2'))),
              Container(child: Card(child: Text('Unit 3'))),
              Container(child: Card(child: Text('Unit 4'))),
              Container(child: Card(child: Text('Unit 5'))),
              Container(child: Card(child: Text('Unit 6'))),
            ]),
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';
import 'package:flutter_mobile_carousel/carousel.dart';
import 'package:flutter_mobile_carousel/carousel_arrow.dart';
import 'package:flutter_mobile_carousel/default_carousel_item.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Carousel(rowCount: 4, children: [
              Container(child: Card(child: Text('Unit 1'))),
              Container(child: Card(child: Text('Unit 2'))),
              Container(child: Card(child: Text('Unit 3'))),
              Container(child: Card(child: Text('Unit 4'))),
              Container(child: Card(child: Text('Unit 5'))),
              Container(child: Card(child: Text('Unit 6'))),
            ]),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Body:
I'm trying to build a horizontal carousel of container widgets - i.e. the user simply scrolls horizontally to view the 6 container widgets I have.

How can I implement this?

I have tried using SingleChildScrollView() - and placed in there a Row() widget, but that didn't do anything.. nothing scrolled.

Row(children: [
Container(child: Card(child: Text('Unit 1'))),
Container(child: Card(child: Text('Unit 2'))),
Container(child: Card(child: Text('Unit 3'))),
Container(child: Card(child: Text('Unit 4'))),
Container(child: Card(child: Text('Unit 5'))),
Container(child: Card(child: Text('Unit 6'))),

]),

I'd like each container to be on the same row, and the end user able to scroll horizontally to view each item,

How would you implement this?

Body:
You can copy paste run full code below

You can use package https://pub.dev/packages/flutter_mobile_carousel

You can use rowCount to define how many items need to show at the same time

code snippet

 Carousel(rowCount: 4, children: [
              Container(child: Card(child: Text('Unit 1'))),
              Container(child: Card(child: Text('Unit 2'))),
              Container(child: Card(child: Text('Unit 3'))),
              Container(child: Card(child: Text('Unit 4'))),
              Container(child: Card(child: Text('Unit 5'))),
              Container(child: Card(child: Text('Unit 6'))),
            ]),

working demo

full code

import 'package:flutter/material.dart';
import 'package:flutter_mobile_carousel/carousel.dart';
import 'package:flutter_mobile_carousel/carousel_arrow.dart';
import 'package:flutter_mobile_carousel/default_carousel_item.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Carousel(rowCount: 4, children: [
              Container(child: Card(child: Text('Unit 1'))),
              Container(child: Card(child: Text('Unit 2'))),
              Container(child: Card(child: Text('Unit 3'))),
              Container(child: Card(child: Text('Unit 4'))),
              Container(child: Card(child: Text('Unit 5'))),
              Container(child: Card(child: Text('Unit 6'))),
            ]),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


问:
Pricing of Google App Engine Flexible env, a $500 lesson
I followed the Nodejs on App Engine Flexible env tutorial:
https://cloud.google.com/appengine/docs/flexible/nodejs/create-app

Having successfully deployed and tested the tutorial, I changed the code to experiment a little and successfully deployed it... and then left it running since this was a testing environment (not public).

A month later, I receive a bill from Google for over $370!

In the transaction details I see the following:

Oct 1 – 31, 2017 App Engine Flex Instance RAM: 5948.774 Gibibyte-hours
([MYPROJECT]) $42.24

Oct 1 – 31, 2017 App Engine Flex Instance Core Hours: 5948.774 Hours ([MYPROJECT]) $312.91

How did this testing environment with almost 0 requests require about 6,000 hours of resources? In the worst, I would have assume 720 hrs running fulltime for a month @ $0.05 per hour would cost me ~$40.
https://cloud.google.com/appengine/pricing

Can someone help shed light on this? I have not been able to find out why so many resources were needed?

Thanks for the help!

For more data, this is the traffic over the last month (basically 0):

And instance data

UPDATE:
Note that I did bring one modification to the package.json: I added nodemon as a dependency and added it as part of my "nmp start" script. Though I doubt this explains the 6000 hours of resources:

```<code>  "scripts": {
    "deploy": "gcloud app deploy",
    "start": "nodemon app.js",
    "dev": "nodemon app js",
    "lint": "samples lint",
    "pretest": "npm run lint",
    "system-test": "samples test app",
    "test": "npm run system-test",
    "e2e-test": "samples test deploy"
  },
</code>```

App.yaml (default-no change from tutorial)

```<code>runtime: nodejs
env: flex
</code>```

答:
for dev environments where I don't mind a little latency, I'm using the following settings:

```<code>instance_class: B1
basic_scaling:
  max_instances: 1
  idle_timeout: 1m
</code>```

And if you use your instance more than the free backend instance allowance try this:

```<code>instance_class: F1
automatic_scaling:
  max_instances: 1
</code>```

It the AppEngine dashboard, watch the Instances, take note of the start time, and watch to ensure that after the idle_timeout period has passed the Instance count drop to zero and you see the message "This version has no instances deployed".

Body:
I followed the Nodejs on App Engine Flexible env tutorial:
https://cloud.google.com/appengine/docs/flexible/nodejs/create-app

Having successfully deployed and tested the tutorial, I changed the code to experiment a little and successfully deployed it... and then left it running since this was a testing environment (not public).

A month later, I receive a bill from Google for over $370!

In the transaction details I see the following:

Oct 1 – 31, 2017 App Engine Flex Instance RAM: 5948.774 Gibibyte-hours
([MYPROJECT]) $42.24

Oct 1 – 31, 2017 App Engine Flex Instance Core Hours: 5948.774 Hours ([MYPROJECT]) $312.91

How did this testing environment with almost 0 requests require about 6,000 hours of resources? In the worst, I would have assume 720 hrs running fulltime for a month @ $0.05 per hour would cost me ~$40.
https://cloud.google.com/appengine/pricing

Can someone help shed light on this? I have not been able to find out why so many resources were needed?

Thanks for the help!

For more data, this is the traffic over the last month (basically 0):

And instance data

UPDATE:
Note that I did bring one modification to the package.json: I added nodemon as a dependency and added it as part of my "nmp start" script. Though I doubt this explains the 6000 hours of resources:

  "scripts": {
    "deploy": "gcloud app deploy",
    "start": "nodemon app.js",
    "dev": "nodemon app js",
    "lint": "samples lint",
    "pretest": "npm run lint",
    "system-test": "samples test app",
    "test": "npm run system-test",
    "e2e-test": "samples test deploy"
  },

App.yaml (default-no change from tutorial)

runtime: nodejs
env: flex

Body:
for dev environments where I don't mind a little latency, I'm using the following settings:

instance_class: B1
basic_scaling:
  max_instances: 1
  idle_timeout: 1m

And if you use your instance more than the free backend instance allowance try this:

instance_class: F1
automatic_scaling:
  max_instances: 1

It the AppEngine dashboard, watch the Instances, take note of the start time, and watch to ensure that after the idle_timeout period has passed the Instance count drop to zero and you see the message "This version has no instances deployed".


问:
How can I parse delimited list in string to rows?
This is my previous question: How can I merge two strings of comma-separated numbers in MySQL?

I tried to use delimited list with these reasons:

the data is more than 2000 rows.

I have just one day.

this is not production level

I need to parse the data with my hands.

I thought I don't have any choice. But I found this: SQL split values to multiple rows

So, I got some hopes from it. But it's quite difficult to apply it to my table.

Mine is different form. I have multiple columns and I'd like to avoid duplicate row.

I rather UPDATE and INSERT than SELECT because changing the formation of table will be easier to manage with this reason:Is storing a delimited list in a database column really that bad?

I need to find the non listed numbers. For example, if the time value is
1, 3, 8 then I need 2,4,5,6,7,9,10,11,12,13 (between 1 and 13)

My example table looks like this:

```<code>+-----+------+--------+------+-------+-----------+-------------+
| cid | sid  | type   | day  | time  | building  | room_number |
+-----+------+--------+------+-------+-----------+-------------+
|   1 |    1 | daytime   | mon   | 6,7,8 | sky    | 507         |
|   2 |    2 | daytime   | thu   | 2,3,4 | nuri    | 906         |
|   3 |    3 | daytime   | tue   | 6,7,8 | nuri    | 906         |
|   4 |    4 | daytime   | thu   | 6,7   | sky    | 1003        |
|   5 |    5 | daytime   | mon   | 2,3,4 | sky    | 507         |
|   6 |    6 | daytime   | wed   | 6,7,8 | belief    | 1003        |
|   7 |    7 | daytime   | mon   | 2,3,4 | belief    | 905         |
|   8 |    8 | daytime   | fri   | 6,7,8 | truth    | 905         |
|   9 |    9 | daytime   | tue   | 6,7,8 | truth    | 905         |
|  10 |   10 | daytime   | fri   | 2,3,4 | truth    | 905         |
|  11 |   11 | daytime   | wed   | 6,7,8 | truth    | 905         |
|  12 |   12 | daytime   | fri   | 2,3,4 | truth    | 1003        |
|  13 |   13 | daytime   | mon   | 6,7,8 | truth    | 905         |
|  14 |   14 | daytime   | tue   | 2,3,4 | truth    | 905         |
|  15 |   15 | daytime   | tue   | 6,7,8 | sky    | 208         |
|  16 |   16 | daytime   | tue   | 2,3,4 | sky    | 208         |
|  17 |   17 | daytime   | tue   | 2,3,4 | truth    | 1004        |
|  18 |   19 | daytime   | mon   | 2,3,4 | sky    | 208         |
|  19 |   20 | daytime   | thu   | 2,3,4 | truth    | 1003        |
|  20 |   21 | daytime   | wed   | 6,7,8 | sky    | 208         |
|  21 |   22 | night   | tue   | 4,5,6 | nuri    | 405         |
|  22 |   23 | night   | tue   | 1,2,3 | nuri    | 405         |
|  23 |   24 | night   | tue   | 1,2,3 | nuri    | 306         |
|  24 |   25 | night   | thu   | 1,2,3 | nuri    | 205         |
|  25 |   26 | night   | thu   | 4,5,6 | sky    | 306         |
|  26 |   27 | night   | wed   | 1,2,3 | nuri    | 306         |
|  27 |   28 | night   | wed   | 4,5,6 | sky    | 309         |
|  28 |   29 | night   | wed   | 4,5,6 | nuri    | 407         |
|  29 |   30 | night   | tue   | 4,5,6 | nuri    | 306         |
|  30 |   31 | night   | thu   | 1,2,3 | nuri    | 307         |
| 31 |    0 | always   |      |      | sky    | 201         |
| 32 |    0 | always   |      |      | sky    | 202         |
| 33 |    0 | always   |      |      | sky    | 203         |
| 34 |    0 | always   |      |      | sky    | 204         |
| 35 |    0 | always   |      |      | nuri    | 205         |
| 36 |    0 | always   |      |      | nuri    | 206         |
| 37 |    0 | always   |      |      | truth    | 207         |
| ... |    ... | ...   |      |      | ...    | ...         |
| 2000 |    0 | always   |      |      | belief    | 1101         |
+-----+------+--------+------+-------+-----------+-------------+
</code>```

507|sky building on monday: 2,3,4,6,7,8 are scheduled. So, 1,5,9,10,11,12,13 will be added.

906|nuri building has schedule on thu, tue. which is different day. So, they will not affect each other. So, 1,5,6,7,8,9,10,11,12,13 on thu & 1,2,3,4,5,9,10,11,12,13 on tue.

If there's duplicate row, it won't affect.

And my expectation of changed table is this:

```<code>
+-----+------+--------+------+-------+-----------+-------------+
| cid | sid  | type   | day  | time  | building  | room_number |
+-----+------+--------+------+-------+-----------+-------------+
|   1 |    1 | daytime   | mon   | 1 | sky    | 507         |
|   2 |    1 | daytime   | mon   | 5 | sky    | 507         |
|   3 |    1 | daytime   | mon   | 9 | sky    | 507         |
|   4 |    1 | daytime   | mon   | 10 | sky    | 507         |
|   5 |    1 | daytime   | mon   | 11 | sky    | 507         |
|   6 |    1 | daytime   | mon   | 12 | sky    | 507         |
|   7 |    1 | daytime   | mon   | 13 | sky    | 507         |
|   8 |    2 | daytime   | thu   | 1 | nuri    | 906         |
|   9 |    2 | daytime   | thu   | 5 | nuri    | 906         |
|   10 |    2 | daytime   | thu   | 6 | nuri    | 906         |
|   11 |    2 | daytime   | thu   | 7 | nuri    | 906         |
|   12 |    2 | daytime   | thu   | 8 | nuri    | 906         |
|   13 |    2 | daytime   | thu   | 9 | nuri    | 906         |
|   14 |    2 | daytime   | thu   | 10 | nuri    | 906         |
|   15 |    2 | daytime   | thu   | 11 | nuri    | 906         |
|   16 |    2 | daytime   | thu   | 12 | nuri    | 906         |
|   17 |    2 | daytime   | thu   | 13 | nuri    | 906         |
|   18 |    3 | daytime   | tue   | 1 | nuri    | 906         |
|   19 |    3 | daytime   | tue   | 2 | nuri    | 906         |
|   20 |    3 | daytime   | tue   | 3 | nuri    | 906         |
| ... |    ... | ...   |      |      | ...    | ...         |
| 302 |    0 | always   |      |      | nuri    | 206         |
| 303 |    0 | always   |      |      | truth    | 207         |
| ... |    ... | ...   |      |      | ...    | ...         |
| 4020 |    0 | always   |      |      | belief    | 1101         |
+-----+------+--------+------+-------+-----------+-------------+
</code>```

The reason why I do this is the origin data is the time schedule of classes. And I want to find empty time so that people can use the class room during the time there's any classes.

答:
Here is an approach using a recusive query to split the strings into rows. You can then use this resultset to identify the missing records: for this, you can cross join the original table with the list of times, and use an anti-left join to pull out missing records:

```<code>with recursive
    cte as (
        select cid, sid, type, day, room_number,
            substring(time, 1, locate(',', time) - 1) time,
            substring(concat(time, ','), locate(',', time) + 1) rest
        from mytable
        union all
        select cid, sid, type, day, room_number,
            substring(rest, 1, locate(',', rest) - 1),
            substring(rest, locate(',', rest) + 1)
        from cte
        where  locate(',', rest) > 0
    ),
    all_times as (
        select 1 time
        union all select time + 1 from all_times where time < 13
    )
select  t.cid, t.sid, t.type, t.day, at.time, t.building, t.room_number
from all_times at
cross join mytable t
left join cte c on c.cid = t.cid and c.time = at.time
where c.cid is null
order by t.cid, at.time
</code>```

Demo on DB Fiddle:

Sample data:

```
cid | sid | type    | day | time  | building | room_number
--: | --: | :------ | :-- | :---- | :------- | ----------:
  1 |   1 | daytime | mon | 6,7,8 | sky      |         507
  2 |   2 | daytime | thu | 2,3,4 | nuri     |         906
```

Query results:

```
cid | sid | type    | day | time | building | room_number
--: | --: | :------ | :-- | ---: | :------- | ----------:
  1 |   1 | daytime | mon |    1 | sky      |         507
  1 |   1 | daytime | mon |    2 | sky      |         507
  1 |   1 | daytime | mon |    3 | sky      |         507
  1 |   1 | daytime | mon |    4 | sky      |         507
  1 |   1 | daytime | mon |    5 | sky      |         507
  1 |   1 | daytime | mon |    9 | sky      |         507
  1 |   1 | daytime | mon |   10 | sky      |         507
  1 |   1 | daytime | mon |   11 | sky      |         507
  1 |   1 | daytime | mon |   12 | sky      |         507
  1 |   1 | daytime | mon |   13 | sky      |         507
  2 |   2 | daytime | thu |    1 | nuri     |         906
  2 |   2 | daytime | thu |    5 | nuri     |         906
  2 |   2 | daytime | thu |    6 | nuri     |         906
  2 |   2 | daytime | thu |    7 | nuri     |         906
  2 |   2 | daytime | thu |    8 | nuri     |         906
  2 |   2 | daytime | thu |    9 | nuri     |         906
  2 |   2 | daytime | thu |   10 | nuri     |         906
  2 |   2 | daytime | thu |   11 | nuri     |         906
  2 |   2 | daytime | thu |   12 | nuri     |         906
  2 |   2 | daytime | thu |   13 | nuri     |         906
```

You can easily turn this to an insert query by just preceding it with with an insert instruction, like:

```<code>insert into sometable(cid, sid, type, day, time, building, room_number)
with recursive ...
select ...
from ...
where ...
</code>```

Actually, since the list of values in the csv list is pre-defined, this can very well be done without recursion. You can join the list of days with the table and use find_in_set() to identify the gaps. The upside is that it would work on versions of MySQL / MariaDB that do not support recusive queries:

```<code>select  t.cid, t.sid, t.type, t.day, at.time, t.building, t.room_number
from (
    select 1 time union all select 2 time union all select 3
    union all select 4 union all select 5 union all select 6
    union all select 7 union all select 8 union all select 9
    union all select 10 union all select 11 union all select 12 union all select 13
) at
cross join (
    select distinct cid, sid, type, day, building, room_number
    from mytable
) t
left join mytable t1 on t1.cid = t.cid and find_in_set(at.time, t1.time)
where t1.cid is null
order by t.cid, at.time
</code>```

Demo

Body:
This is my previous question: How can I merge two strings of comma-separated numbers in MySQL?

I tried to use delimited list with these reasons:

the data is more than 2000 rows.

I have just one day.

this is not production level

I need to parse the data with my hands.

I thought I don't have any choice. But I found this: SQL split values to multiple rows

So, I got some hopes from it. But it's quite difficult to apply it to my table.

Mine is different form. I have multiple columns and I'd like to avoid duplicate row.

I rather UPDATE and INSERT than SELECT because changing the formation of table will be easier to manage with this reason:Is storing a delimited list in a database column really that bad?

I need to find the non listed numbers. For example, if the time value is
1, 3, 8 then I need 2,4,5,6,7,9,10,11,12,13 (between 1 and 13)

My example table looks like this:

+-----+------+--------+------+-------+-----------+-------------+
| cid | sid  | type   | day  | time  | building  | room_number |
+-----+------+--------+------+-------+-----------+-------------+
|   1 |    1 | daytime   | mon   | 6,7,8 | sky    | 507         |
|   2 |    2 | daytime   | thu   | 2,3,4 | nuri    | 906         |
|   3 |    3 | daytime   | tue   | 6,7,8 | nuri    | 906         |
|   4 |    4 | daytime   | thu   | 6,7   | sky    | 1003        |
|   5 |    5 | daytime   | mon   | 2,3,4 | sky    | 507         |
|   6 |    6 | daytime   | wed   | 6,7,8 | belief    | 1003        |
|   7 |    7 | daytime   | mon   | 2,3,4 | belief    | 905         |
|   8 |    8 | daytime   | fri   | 6,7,8 | truth    | 905         |
|   9 |    9 | daytime   | tue   | 6,7,8 | truth    | 905         |
|  10 |   10 | daytime   | fri   | 2,3,4 | truth    | 905         |
|  11 |   11 | daytime   | wed   | 6,7,8 | truth    | 905         |
|  12 |   12 | daytime   | fri   | 2,3,4 | truth    | 1003        |
|  13 |   13 | daytime   | mon   | 6,7,8 | truth    | 905         |
|  14 |   14 | daytime   | tue   | 2,3,4 | truth    | 905         |
|  15 |   15 | daytime   | tue   | 6,7,8 | sky    | 208         |
|  16 |   16 | daytime   | tue   | 2,3,4 | sky    | 208         |
|  17 |   17 | daytime   | tue   | 2,3,4 | truth    | 1004        |
|  18 |   19 | daytime   | mon   | 2,3,4 | sky    | 208         |
|  19 |   20 | daytime   | thu   | 2,3,4 | truth    | 1003        |
|  20 |   21 | daytime   | wed   | 6,7,8 | sky    | 208         |
|  21 |   22 | night   | tue   | 4,5,6 | nuri    | 405         |
|  22 |   23 | night   | tue   | 1,2,3 | nuri    | 405         |
|  23 |   24 | night   | tue   | 1,2,3 | nuri    | 306         |
|  24 |   25 | night   | thu   | 1,2,3 | nuri    | 205         |
|  25 |   26 | night   | thu   | 4,5,6 | sky    | 306         |
|  26 |   27 | night   | wed   | 1,2,3 | nuri    | 306         |
|  27 |   28 | night   | wed   | 4,5,6 | sky    | 309         |
|  28 |   29 | night   | wed   | 4,5,6 | nuri    | 407         |
|  29 |   30 | night   | tue   | 4,5,6 | nuri    | 306         |
|  30 |   31 | night   | thu   | 1,2,3 | nuri    | 307         |
| 31 |    0 | always   |      |      | sky    | 201         |
| 32 |    0 | always   |      |      | sky    | 202         |
| 33 |    0 | always   |      |      | sky    | 203         |
| 34 |    0 | always   |      |      | sky    | 204         |
| 35 |    0 | always   |      |      | nuri    | 205         |
| 36 |    0 | always   |      |      | nuri    | 206         |
| 37 |    0 | always   |      |      | truth    | 207         |
| ... |    ... | ...   |      |      | ...    | ...         |
| 2000 |    0 | always   |      |      | belief    | 1101         |
+-----+------+--------+------+-------+-----------+-------------+

507|sky building on monday: 2,3,4,6,7,8 are scheduled. So, 1,5,9,10,11,12,13 will be added.

906|nuri building has schedule on thu, tue. which is different day. So, they will not affect each other. So, 1,5,6,7,8,9,10,11,12,13 on thu & 1,2,3,4,5,9,10,11,12,13 on tue.

If there's duplicate row, it won't affect.

And my expectation of changed table is this:

+-----+------+--------+------+-------+-----------+-------------+
| cid | sid  | type   | day  | time  | building  | room_number |
+-----+------+--------+------+-------+-----------+-------------+
|   1 |    1 | daytime   | mon   | 1 | sky    | 507         |
|   2 |    1 | daytime   | mon   | 5 | sky    | 507         |
|   3 |    1 | daytime   | mon   | 9 | sky    | 507         |
|   4 |    1 | daytime   | mon   | 10 | sky    | 507         |
|   5 |    1 | daytime   | mon   | 11 | sky    | 507         |
|   6 |    1 | daytime   | mon   | 12 | sky    | 507         |
|   7 |    1 | daytime   | mon   | 13 | sky    | 507         |
|   8 |    2 | daytime   | thu   | 1 | nuri    | 906         |
|   9 |    2 | daytime   | thu   | 5 | nuri    | 906         |
|   10 |    2 | daytime   | thu   | 6 | nuri    | 906         |
|   11 |    2 | daytime   | thu   | 7 | nuri    | 906         |
|   12 |    2 | daytime   | thu   | 8 | nuri    | 906         |
|   13 |    2 | daytime   | thu   | 9 | nuri    | 906         |
|   14 |    2 | daytime   | thu   | 10 | nuri    | 906         |
|   15 |    2 | daytime   | thu   | 11 | nuri    | 906         |
|   16 |    2 | daytime   | thu   | 12 | nuri    | 906         |
|   17 |    2 | daytime   | thu   | 13 | nuri    | 906         |
|   18 |    3 | daytime   | tue   | 1 | nuri    | 906         |
|   19 |    3 | daytime   | tue   | 2 | nuri    | 906         |
|   20 |    3 | daytime   | tue   | 3 | nuri    | 906         |
| ... |    ... | ...   |      |      | ...    | ...         |
| 302 |    0 | always   |      |      | nuri    | 206         |
| 303 |    0 | always   |      |      | truth    | 207         |
| ... |    ... | ...   |      |      | ...    | ...         |
| 4020 |    0 | always   |      |      | belief    | 1101         |
+-----+------+--------+------+-------+-----------+-------------+

The reason why I do this is the origin data is the time schedule of classes. And I want to find empty time so that people can use the class room during the time there's any classes.

Body:
Here is an approach using a recusive query to split the strings into rows. You can then use this resultset to identify the missing records: for this, you can cross join the original table with the list of times, and use an anti-left join to pull out missing records:

with recursive
    cte as (
        select cid, sid, type, day, room_number,
            substring(time, 1, locate(',', time) - 1) time,
            substring(concat(time, ','), locate(',', time) + 1) rest
        from mytable
        union all
        select cid, sid, type, day, room_number,
            substring(rest, 1, locate(',', rest) - 1),
            substring(rest, locate(',', rest) + 1)
        from cte
        where  locate(',', rest) > 0
    ),
    all_times as (
        select 1 time
        union all select time + 1 from all_times where time < 13
    )
select  t.cid, t.sid, t.type, t.day, at.time, t.building, t.room_number
from all_times at
cross join mytable t
left join cte c on c.cid = t.cid and c.time = at.time
where c.cid is null
order by t.cid, at.time

Demo on DB Fiddle:

Sample data:

cid | sid | type    | day | time  | building | room_number
--: | --: | :------ | :-- | :---- | :------- | ----------:
  1 |   1 | daytime | mon | 6,7,8 | sky      |         507
  2 |   2 | daytime | thu | 2,3,4 | nuri     |         906

Query results:

cid | sid | type    | day | time | building | room_number
--: | --: | :------ | :-- | ---: | :------- | ----------:
  1 |   1 | daytime | mon |    1 | sky      |         507
  1 |   1 | daytime | mon |    2 | sky      |         507
  1 |   1 | daytime | mon |    3 | sky      |         507
  1 |   1 | daytime | mon |    4 | sky      |         507
  1 |   1 | daytime | mon |    5 | sky      |         507
  1 |   1 | daytime | mon |    9 | sky      |         507
  1 |   1 | daytime | mon |   10 | sky      |         507
  1 |   1 | daytime | mon |   11 | sky      |         507
  1 |   1 | daytime | mon |   12 | sky      |         507
  1 |   1 | daytime | mon |   13 | sky      |         507
  2 |   2 | daytime | thu |    1 | nuri     |         906
  2 |   2 | daytime | thu |    5 | nuri     |         906
  2 |   2 | daytime | thu |    6 | nuri     |         906
  2 |   2 | daytime | thu |    7 | nuri     |         906
  2 |   2 | daytime | thu |    8 | nuri     |         906
  2 |   2 | daytime | thu |    9 | nuri     |         906
  2 |   2 | daytime | thu |   10 | nuri     |         906
  2 |   2 | daytime | thu |   11 | nuri     |         906
  2 |   2 | daytime | thu |   12 | nuri     |         906
  2 |   2 | daytime | thu |   13 | nuri     |         906

You can easily turn this to an insert query by just preceding it with with an insert instruction, like:

insert into sometable(cid, sid, type, day, time, building, room_number)
with recursive ...
select ...
from ...
where ...

Actually, since the list of values in the csv list is pre-defined, this can very well be done without recursion. You can join the list of days with the table and use find_in_set() to identify the gaps. The upside is that it would work on versions of MySQL / MariaDB that do not support recusive queries:

select  t.cid, t.sid, t.type, t.day, at.time, t.building, t.room_number
from (
    select 1 time union all select 2 time union all select 3
    union all select 4 union all select 5 union all select 6
    union all select 7 union all select 8 union all select 9
    union all select 10 union all select 11 union all select 12 union all select 13
) at
cross join (
    select distinct cid, sid, type, day, building, room_number
    from mytable
) t
left join mytable t1 on t1.cid = t.cid and find_in_set(at.time, t1.time)
where t1.cid is null
order by t.cid, at.time

Demo


问:
OpenGL 3D text rendering
Short of writing my own text rendering engine, is there any way I can import external fonts to use with glutstrokecharacter to render 3D text in OpenGL. (Just for clairty, this needs to be done using the JOGL API).

答: glutStrokeCharacter uses built-in fonts. If you want to use custom font you need to use TextRenderer. Check this question for more options.

ContentLicense: CC BY-SA 3.0

Title: OpenGL 3D text rendering


问:
File Descriptors to asyncio transport/protocol
Ok, so, I have a Base Protocol and specializations for Streams and Subprocess. I am also trying to rig it up for inherited file descriptors (namely, stdio). This is useful for proxying over ssh, systemd socket activation, etc.

To be clear, I need to get asyncio to wire up a reader file descriptor and writer file descriptor to a Transport and construct a Protocol from it.

Unfortunately, there doesn't seem to be anything for that? I can ask it to watch descriptors or get stream objects for them, but I can't seem to wire them up to a transport/protocol pair.

答:
I ended up writing a proxy transport/protocol object: It can act as the protocol for the reader/writer transports, and act as a transport for the actual protocol, shuffling data  between all three.

https://github.com/minecraft-podman/urp/blob/8ed78d12c8abfa7ef067892dda25149d023b03fc/urp/common.py#L286-L364


问:
How to configure cloud.google.com/go/logging to look like logs written to stdout?
I'm writing a Google Cloud Function in Go. I can write log messages simply by writing to stdout. The logs produced includes info about the function, its runtime, trace info, etc. Super nice, however, I want to add some structured data to my logs which means stdout is not flexible enough. So I'm trying to use "cloud.google.com/go/logging". I set it up like so:

```<code>// Set up like this
logClient, err = logging.NewClient(ctx, "my-project-id")
if err != nil {
    return
}
logger := logClient.Logger("my-function-name")

// And log like this
logger.Log(logging.Entry{
    Payload:  "Hello World!",
    Severity: logging.Info,
})
</code>```

However, the logs I see the Cloud Console are missing all of that nice info that is automatically attached to the stdout logs.

To get some of it back, I can add this option when setting up the logger:

```<code>logging.CommonResource(&monitoredres.MonitoredResource{
    Type: fmt.Sprintf("projects/%s/logs/cloudfunctions.googleapis.com%scloud-functions", os.Getenv("GCP_PROJECT"), "%2F"),
    Labels: map[string]string{
        "function_name": os.Getenv("FUNCTION_NAME"),
        "project_id":    os.Getenv("GCP_PROJECT"),
        "region":        os.Getenv("FUNCTION_REGION"),
    },
})
</code>```

This allows me to see the logs when I click the "see logs" button in the cloud function list in the Cloud Console. However, it's missing the function execution id and trace id.

Am I missing something obvious here or is it just ridiculously complicated to set up decent logging for Google Cloud services? Any help appreciated.

答:
The trick was to simply write a json string to stdout.

```<code>fmt.Println(`{"field_name": "Hello World!"}`)
</code>```

The schema for the logs can be found here.

e.g. set the severity like so:

```<code>fmt.Println(`{"field_name": "Hello World!", "severity": "DEBUG"}`)
</code>```

Body:
I'm writing a Google Cloud Function in Go. I can write log messages simply by writing to stdout. The logs produced includes info about the function, its runtime, trace info, etc. Super nice, however, I want to add some structured data to my logs which means stdout is not flexible enough. So I'm trying to use "cloud.google.com/go/logging". I set it up like so:

// Set up like this
logClient, err = logging.NewClient(ctx, "my-project-id")
if err != nil {
    return
}
logger := logClient.Logger("my-function-name")

// And log like this
logger.Log(logging.Entry{
    Payload:  "Hello World!",
    Severity: logging.Info,
})

However, the logs I see the Cloud Console are missing all of that nice info that is automatically attached to the stdout logs.

To get some of it back, I can add this option when setting up the logger:

logging.CommonResource(&monitoredres.MonitoredResource{
    Type: fmt.Sprintf("projects/%s/logs/cloudfunctions.googleapis.com%scloud-functions", os.Getenv("GCP_PROJECT"), "%2F"),
    Labels: map[string]string{
        "function_name": os.Getenv("FUNCTION_NAME"),
        "project_id":    os.Getenv("GCP_PROJECT"),
        "region":        os.Getenv("FUNCTION_REGION"),
    },
})

This allows me to see the logs when I click the "see logs" button in the cloud function list in the Cloud Console. However, it's missing the function execution id and trace id.

Am I missing something obvious here or is it just ridiculously complicated to set up decent logging for Google Cloud services? Any help appreciated.

Body:
The trick was to simply write a json string to stdout.

fmt.Println(`{"field_name": "Hello World!"}`)

The schema for the logs can be found here.

e.g. set the severity like so:

fmt.Println(`{"field_name": "Hello World!", "severity": "DEBUG"}`)


问:
Split a python string by particular identifications
I am trying to split a python string when a particular character appears.

For example:

```<code>mystring="I want to eat an apple. \n 12345 \n 12 34 56"
</code>```

The output I want is a string with

```<code>[["I want to eat an apple"], [12345], [12, 34, 56]]
</code>```

答:
```<code>mystring = "I want to eat an apple. \n 12345 \n 12 34 56"
# split and strip the lines in case they all dont have the format ' \n '
split_list = [line.strip() for line in mystring.split('\n')] # use [line.strip] to make each element a list...
print(split_list)
</code>```

Output:

```<code>['I want to eat an apple.', '12345', '12 34 56']
</code>```

Body:
I am trying to split a python string when a particular character appears.

For example:

mystring="I want to eat an apple. \n 12345 \n 12 34 56"

The output I want is a string with

[["I want to eat an apple"], [12345], [12, 34, 56]]

Body:
mystring = "I want to eat an apple. \n 12345 \n 12 34 56"
# split and strip the lines in case they all dont have the format ' \n '
split_list = [line.strip() for line in mystring.split('\n')] # use [line.strip] to make each element a list...
print(split_list)

Output:

['I want to eat an apple.', '12345', '12 34 56']


问:
Extract the first object from a JSON array
input:

```<code>[
  {
    "name": "John",
    "title": "Hello"
  }
]
</code>```

output:

```<code>{"name": "John","title": "Hello"}
</code>```

答:
For the sake of illustration, the following assumes a bash or bash-like shell:</p>

```<code>$ jq -c first <<< '[ { "name": "John", "title": "Hello" } ]'
{"name":"John","title":"Hello"}
</code>```

Body:
input:

[
  {
    "name": "John",
    "title": "Hello"
  }
]

output:

{"name": "John","title": "Hello"}

Body:
For the sake of illustration, the following assumes a bash or bash-like shell:

$ jq -c first <<< '[ { "name": "John", "title": "Hello" } ]'
{"name":"John","title":"Hello"}


问:
How do I read from the terminal in Python?
I just want to use os.system("dir") and also be able to save the text outputted to a variable.  I tried using sys.stdout.read() but running sys.stdout.readable() returns False.  Do you know how I can read from the terminal?

答:
You can use the subprocess.check_output method

Example

import subprocess as sp

stdout = sp.check_output("dir")
print(stdout)
```


问:
Python Pandas DF append to same row
Trying to print some stockprices to Pandas Df, and having a hard time to make the stock name get in the same line as the price.

This is my complete code, what am i missing?

```<code>import yfinance as yf
from pandas_datareader import data
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame()
tickers = ['ALZR11']
df['Ticker'] = ['']
for ticker in tickers:
    print(ticker)
    df = df.append(pd.DataFrame({'Ticker': ticker}, index=[0]), ignore_index=True)
    ticker = ticker+".SA"
    data = yf.download(tickers=ticker, period="1d", interval="1d")
    df = df.append(data, ignore_index=True)
    #df.loc[ticker, 'New Column Title'] = ticker
    print(df)
</code>```

Result:

```<code>     Ticker  Open  High  Low        Close    Adj Close  Volume
0             NaN   NaN  NaN          NaN          NaN     NaN
1    ALZR11   NaN   NaN  NaN          NaN          NaN     NaN
2       NaN   0.0   0.0  0.0   116.500000   116.500000     0.0
</code>```

Expected:

```<code>     Ticker  Open  High  Low        Close    Adj Close  Volume
0    ALZR11   0.0   0.0  0.0   116.500000   116.500000     0.0
</code>```

答:
Let us try , this will make the ticker become the index </p>

```<code>for ticker in tickers:
    print(ticker)
    ticker = ticker+".SA"
    data = yf.download(tickers=ticker, period="1d", interval="1d")
    data.index=[ticker]
    df = df.append(data)
    #df.loc[ticker, 'New Column Title'] = ticker
    print(df)
</code>```

Title: Python Pandas DF append to same row

Body:
Trying to print some stockprices to Pandas Df, and having a hard time to make the stock name get in the same line as the price.

This is my complete code, what am i missing?

import yfinance as yf
from pandas_datareader import data
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame()
tickers = ['ALZR11']
df['Ticker'] = ['']
for ticker in tickers:
    print(ticker)
    df = df.append(pd.DataFrame({'Ticker': ticker}, index=[0]), ignore_index=True)
    ticker = ticker+".SA"
    data = yf.download(tickers=ticker, period="1d", interval="1d")
    df = df.append(data, ignore_index=True)
    #df.loc[ticker, 'New Column Title'] = ticker
    print(df)

Result:

     Ticker  Open  High  Low        Close    Adj Close  Volume
0             NaN   NaN  NaN          NaN          NaN     NaN
1    ALZR11   NaN   NaN  NaN          NaN          NaN     NaN
2       NaN   0.0   0.0  0.0   116.500000   116.500000     0.0

Expected:

     Ticker  Open  High  Low        Close    Adj Close  Volume
0    ALZR11   0.0   0.0  0.0   116.500000   116.500000     0.0

Body:
Let us try , this will make the ticker become the index

for ticker in tickers:
    print(ticker)
    ticker = ticker+".SA"
    data = yf.download(tickers=ticker, period="1d", interval="1d")
    data.index=[ticker]
    df = df.append(data)
    #df.loc[ticker, 'New Column Title'] = ticker
    print(df)