问:
Access redux-form values through mapStateToProps
How can I access the field values in a parent component of a redux-form component?

I'm not sure if it's caused by typescript, but before I started using typescript, I was able to access the form values through mapStateToProps just like how I have it currently. I've been trying to figure out what was different to my previous implementation but the only difference would be the versions of the npm dependencies and the addition of typescript.

LoginPage.tsx

import LoginForm from 'components/Forms/LoginForm'
import Layout from 'components/Layout'
import { StatusCodes } from 'lib/enums/statusCodes'
import { storeAuthToken } from 'lib/helpers/auth'
import { NextPage } from 'next'
import Router from 'next/router'
import React from 'react'
import { connect, DispatchProp } from 'react-redux'
import { FormInstance } from 'redux-form'

interface IProps {
  login: FormInstance<IFormData, IFormProps>
}

interface IState {
  errorMessage?: string,
  processing: boolean
}

interface IRootState {
  form: IProps
}

export interface IFormData {
  username?: string,
  password?: string
}

export interface IFormProps {
  contactId?: string,
  errorMessage?: string,
  fieldValues: Partial<IFormData>,
  processing: boolean
}

class LoginPage extends React.Component<NextPage & DispatchProp & IProps, IState> {
  state = {
    errorMessage: undefined,
    processing: false
  }

  setErrorMessage = (message: string) => {
    this.setState({
      errorMessage: message,
      processing: false
    })
  }

  handleSubmit = async (values: IFormData) => {
    if (values && values.username && values.password) {
      this.setState({
        errorMessage: undefined,
        processing: true
      })

      try {
        const { dispatch } = this.props

        await storeAuthToken(dispatch, values.username, values.password)
        Router.push('/')
      } catch (error) {
        if (error === StatusCodes.BAD_REQUEST) {
          this.setErrorMessage("Sorry, you have entered incorrect details. Please try again.")
        } else {
          this.setErrorMessage("Sorry, there was an issue trying to log you in")
        }
      }
    }
  }

  render() {
    const { login } = this.props
    const { processing } = this.state

    return (
      <Layout title="Login">

          <LoginForm processing={processing} onSubmit={this.handleSubmit} fieldValues={login.values} />

      </Layout>
    )
  }
}

const mapStateToProps = ({ form: { login } }: IRootState) => ({ login })

export default connect(mapStateToProps)(LoginPage)```
</div>
</div>
</p>

<p><strong>LoginForm.tsx</strong></p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import Link from 'next/link'
import React from 'react'
import { Field, InjectedFormProps, reduxForm } from 'redux-form'
import FormButton from 'components/Forms/FormButton'
import Input from 'components/Fields/Input'
import { validateRequired } from 'lib/helpers/validators'
import { IFormProps, IFormData } from 'pages/login'

class LoginForm extends React.Component<IFormProps & InjectedFormProps<IFormData, IFormProps>> {
  render() {
    const { contactId, errorMessage, fieldValues, handleSubmit, processing } = this.props

    return (
      <form id="login" onSubmit={handleSubmit} >
        <h1>Sign in</h1>
        <fieldset>
          <div className="fields">
            {
              !contactId
                ? <Field name="username" type="text" component={Input} label="Username" validate={validateRequired} />
                : <Field name="username" type="email" component={Input} label="Email" validate={validateRequired} />
            }
          </div>
          <div className="fields">
            <Field name="password" type="password" component={Input} label="Password" validate={validateRequired} />
          </div>
        </fieldset>
        { errorMessage && <p className="error-message">{errorMessage}</p> }
        <div className="form-bottom">
          <Link href="/"/*{`/forgot-password${fields.email ? `?email=${encodeURIComponent(fields.email)}` : ''}`}*/>
            Forgotten your password?
          </Link>
          <FormButton loading={processing}>
            Login
          </FormButton>
        </div>
      </form>
    )
  }
}

export default reduxForm<{}, IFormProps>({ form: 'login' })(LoginForm)</code>```

Here is my redux store file incase if that is coded incorrectly

import { createWrapper, HYDRATE, MakeStore } from 'next-redux-wrapper'
import { AnyAction, applyMiddleware, combineReducers, createStore, Reducer } from 'redux'
import { reducer as formReducer } from 'redux-form'
import thunkMiddleware, { ThunkMiddleware } from 'redux-thunk'
import authReducer, { AuthState } from './auth/reducer'
import contactReducer, { ContactState } from './contact/reducer'
import initialState from './initialState'

export interface State {
  auth: AuthState
  contact: ContactState
}

const bindMiddleware = (middleware: [ThunkMiddleware]) => {
  if (process.env.NODE_ENV !== 'production') {
    const { composeWithDevTools } = require('redux-devtools-extension')
    return composeWithDevTools(applyMiddleware(...middleware))
  }

  return applyMiddleware(...middleware)
}

const combinedReducer = combineReducers({
  auth: authReducer,
  contact: contactReducer,
  form: formReducer
})

const reducer: Reducer = (state: State, action: AnyAction) => {
  if (action.type === HYDRATE) {
    const nextState: Reducer = {
      ...state,
      ...action.payload
    }

    return nextState
  } else {
    return combinedReducer
  }
}

const makeStore: MakeStore<State> = () => createStore(reducer, initialState, bindMiddleware([thunkMiddleware]))

export const wrapper = createWrapper<State>(makeStore/*, { debug: true }*/)```

答:
It seems like I missed out a key in the IApplicationState interface and as mentioned by @cbr, the parameters state and action needed to be passed to combinedReducer even though it doesn't directly take any.

Additionally it didn't like when the nextState constant had the type Reducer, so I have changed that to CombinedState<State> as well

The changed code looks like this

import { createWrapper, HYDRATE, MakeStore } from 'next-redux-wrapper'
import { AnyAction, applyMiddleware, combineReducers, createStore, Reducer } from 'redux'
import { reducer as formReducer } from 'redux-form'
import thunkMiddleware, { ThunkMiddleware } from 'redux-thunk'
import authReducer, { AuthState } from './auth/reducer'
import contactReducer, { ContactState } from './contact/reducer'
import initialState from './initialState'

export interface State {
  auth: AuthState
  contact: ContactState,
  form: FormStateMap
}

const bindMiddleware = (middleware: [ThunkMiddleware]) => {
  if (process.env.NODE_ENV !== 'production') {
    const { composeWithDevTools } = require('redux-devtools-extension')
    return composeWithDevTools(applyMiddleware(...middleware))
  }

  return applyMiddleware(...middleware)
}

const combinedReducer = combineReducers({
  auth: authReducer,
  contact: contactReducer,
  form: formReducer
})

const reducer: Reducer = (state: State, action: AnyAction) => {
  if (action.type === HYDRATE) {
    const nextState: CombinedState<State> = {
      ...state,
      ...action.payload
    }

    return nextState
  } else {
    return combinedReducer(state, action)
  }
}

const makeStore: MakeStore<State> = () => createStore(reducer, initialState, bindMiddleware([thunkMiddleware]))

export const wrapper = createWrapper<State>(makeStore)```

Body:
How can I access the field values in a parent component of a redux-form component?

I'm not sure if it's caused by typescript, but before I started using typescript, I was able to access the form values through mapStateToProps just like how I have it currently. I've been trying to figure out what was different to my previous implementation but the only difference would be the versions of the npm dependencies and the addition of typescript.

LoginPage.tsx

import LoginForm from 'components/Forms/LoginForm'
import Layout from 'components/Layout'
import { StatusCodes } from 'lib/enums/statusCodes'
import { storeAuthToken } from 'lib/helpers/auth'
import { NextPage } from 'next'
import Router from 'next/router'
import React from 'react'
import { connect, DispatchProp } from 'react-redux'
import { FormInstance } from 'redux-form'

interface IProps {
  login: FormInstance<IFormData, IFormProps>
}

interface IState {
  errorMessage?: string,
  processing: boolean
}

interface IRootState {
  form: IProps
}

export interface IFormData {
  username?: string,
  password?: string
}

export interface IFormProps {
  contactId?: string,
  errorMessage?: string,
  fieldValues: Partial<IFormData>,
  processing: boolean
}

class LoginPage extends React.Component<NextPage & DispatchProp & IProps, IState> {
  state = {
    errorMessage: undefined,
    processing: false
  }

  setErrorMessage = (message: string) => {
    this.setState({
      errorMessage: message,
      processing: false
    })
  }

  handleSubmit = async (values: IFormData) => {
    if (values && values.username && values.password) {
      this.setState({
        errorMessage: undefined,
        processing: true
      })

      try {
        const { dispatch } = this.props

        await storeAuthToken(dispatch, values.username, values.password)
        Router.push('/')
      } catch (error) {
        if (error === StatusCodes.BAD_REQUEST) {
          this.setErrorMessage("Sorry, you have entered incorrect details. Please try again.")
        } else {
          this.setErrorMessage("Sorry, there was an issue trying to log you in")
        }
      }
    }
  }

  render() {
    const { login } = this.props
    const { processing } = this.state

    return (
      <Layout title="Login">

          <LoginForm processing={processing} onSubmit={this.handleSubmit} fieldValues={login.values} />

      </Layout>
    )
  }
}

const mapStateToProps = ({ form: { login } }: IRootState) => ({ login })

export default connect(mapStateToProps)(LoginPage)

LoginForm.tsx

import Link from 'next/link'
import React from 'react'
import { Field, InjectedFormProps, reduxForm } from 'redux-form'
import FormButton from 'components/Forms/FormButton'
import Input from 'components/Fields/Input'
import { validateRequired } from 'lib/helpers/validators'
import { IFormProps, IFormData } from 'pages/login'

class LoginForm extends React.Component<IFormProps & InjectedFormProps<IFormData, IFormProps>> {
  render() {
    const { contactId, errorMessage, fieldValues, handleSubmit, processing } = this.props

    return (
      <form id="login" onSubmit={handleSubmit} >

Sign in

        <fieldset>

            {
              !contactId
                ? <Field name="username" type="text" component={Input} label="Username" validate={validateRequired} />
                : <Field name="username" type="email" component={Input} label="Email" validate={validateRequired} />
            }

            <Field name="password" type="password" component={Input} label="Password" validate={validateRequired} />

        </fieldset>
        { errorMessage &&
{errorMessage}
 }

          <Link href="/"/*{`/forgot-password${fields.email ? `?email=${encodeURIComponent(fields.email)}` : ''}`}*/>
            Forgotten your password?
          </Link>
          <FormButton loading={processing}>
            Login
          </FormButton>

      </form>
    )
  }
}

export default reduxForm<{}, IFormProps>({ form: 'login' })(LoginForm)

Here is my redux store file incase if that is coded incorrectly

import { createWrapper, HYDRATE, MakeStore } from 'next-redux-wrapper'
import { AnyAction, applyMiddleware, combineReducers, createStore, Reducer } from 'redux'
import { reducer as formReducer } from 'redux-form'
import thunkMiddleware, { ThunkMiddleware } from 'redux-thunk'
import authReducer, { AuthState } from './auth/reducer'
import contactReducer, { ContactState } from './contact/reducer'
import initialState from './initialState'

export interface State {
  auth: AuthState
  contact: ContactState
}

const bindMiddleware = (middleware: [ThunkMiddleware]) => {
  if (process.env.NODE_ENV !== 'production') {
    const { composeWithDevTools } = require('redux-devtools-extension')
    return composeWithDevTools(applyMiddleware(...middleware))
  }

  return applyMiddleware(...middleware)
}

const combinedReducer = combineReducers({
  auth: authReducer,
  contact: contactReducer,
  form: formReducer
})

const reducer: Reducer = (state: State, action: AnyAction) => {
  if (action.type === HYDRATE) {
    const nextState: Reducer = {
      ...state,
      ...action.payload
    }

    return nextState
  } else {
    return combinedReducer
  }
}

const makeStore: MakeStore<State> = () => createStore(reducer, initialState, bindMiddleware([thunkMiddleware]))

export const wrapper = createWrapper<State>(makeStore/*, { debug: true }*/)


来源: stackexchange

问:
My Search Icon Disappears after Transition
I added a search icon with font awesome on my website that has a transition to the left but for some reason when I hover and the transition starts the font awesome icon disappears.
I'm having a hard time figuring this out because it works fine on my CodePen.

Please click on the link below to see the code in action on my website.

http://lonestarwebandgraphics.com/

答:
Another solution

Add following CSS

```<code> .#mybottomnav .items .item .search-box {
      min-width: 52px;
  }

  .#mybottomnav .items .item .search-box .search-btn {
      position: absolute;
      right: 10px;
      /*float: right;*/ //remove this css
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Another solution

Add following CSS

 .#mybottomnav .items .item .search-box {
      min-width: 52px;
  }

  .#mybottomnav .items .item .search-box .search-btn {
      position: absolute;
      right: 10px;
      /*float: right;*/ //remove this css
  }


问:
How do CSS triangles work?
There're plenty of different CSS shapes over at CSS Tricks - Shapes of CSS and I'm particularly puzzled with a triangle:

#triangle-up {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="triangle-up"></div></code>```

How and why does it work?

答:
I know this is an old one, but I'd like to add to this discussion that There are at least 5 different methods for creating a triangle using HTML & CSS alone.

Using borders

Using linear-gradient

Using conic-gradient

Using
transform and overflow

Using clip-path

I think that all have been covered here except for method 3, using the conic-gradient, so I will share it here:

.triangle{
        width: 40px;
        height: 40px;
        background: conic-gradient(at 50% 50%,transparent 135deg,green 0,green 225deg, transparent 0);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="triangle"></div></code>```

ContentLicense: CC BY-SA 3.0

Title: How do CSS triangles work?

Body:
There're plenty of different CSS shapes over at CSS Tricks - Shapes of CSS and I'm particularly puzzled with a triangle:

#triangle-up {
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 100px solid red;
}

How and why does it work?

Body:
I know this is an old one, but I'd like to add to this discussion that There are at least 5 different methods for creating a triangle using HTML & CSS alone.

Using borders

Using linear-gradient

Using conic-gradient

Using
transform and overflow

Using clip-path

I think that all have been covered here except for method 3, using the conic-gradient, so I will share it here:

.triangle{
        width: 40px;
        height: 40px;
        background: conic-gradient(at 50% 50%,transparent 135deg,green 0,green 225deg, transparent 0);
    }

<div class="triangle"></div>


问:
Spark PySpark output JSON with one column value as key
If I have a simple table in dataframe with schema:

```<code>a string, b string, c string
</code>```

for example:

```<code>a     b      c
cat   3-3    78-b
cat   3-3    89-0
cat   4-4    78-n
dog   4-4    89-b
</code>```

And so on.
I would want to partition this table by column a and save each partition as separate JSON.

Further I would want the each partition as a JSON file with value in column b as key. For example:

```<code>File cat.json:
     {
       "3-3": {"b": "3-3", "c": "78-b"},
       "3-3": {"b": "3-3", "c": "89-0"},
       "4-4": {"b": "4-4", "c": "78-n"}
     }
File dog.json:
     {
       "4-4": {"b": 4-4, "c": "89-b"}
     }
</code>```

Is there a way to do this in pyspark? Thanks

答:
Just add a row mapping logic for Dataframe and you should be good,
Please find the code explanation inline</p>

```<code>import org.apache.spark.sql.Row
import org.apache.spark.sql.functions._

object CatDog {

  def main(args: Array[String]): Unit = {

    val spark = Constant.getSparkSess

    import spark.implicits._

    val df = List(("cat",   "3-3"    ,"78-b"),
    ("cat"   ,"3-3",    "89-0"),
    ("cat"   ,"4-4"    ,"78-n"),
      ("dog"   ,"4-4",    "89-b")).toDF("a","b","c")

//    df.show()

    //Write your out as JSON
    df.select("a").distinct().map((a: Row) =>
      (a, df.filter(col("a") === a).map(row => parseDF(row)))
    ).foreachPartition((iterator) => {
      iterator.foreach(record => {
        val aVal = record._1.getString(0)
        record._2.write.json(s"src/main/resources/$aVal.json")
      })
    })
  }

  //Row mapping logic
  def parseDF(row: Row): Map[String, Map[String, String]] = {

    val b = row.getString(1)
    val c = row.getString(2)
    Map(b -> Map("b" -> b, "c" -> c))

  }

}

</code>```

Body:
If I have a simple table in dataframe with schema:

a string, b string, c string

for example:

a     b      c
cat   3-3    78-b
cat   3-3    89-0
cat   4-4    78-n
dog   4-4    89-b

And so on.
I would want to partition this table by column a and save each partition as separate JSON.

Further I would want the each partition as a JSON file with value in column b as key. For example:

File cat.json:
     {
       "3-3": {"b": "3-3", "c": "78-b"},
       "3-3": {"b": "3-3", "c": "89-0"},
       "4-4": {"b": "4-4", "c": "78-n"}
     }
File dog.json:
     {
       "4-4": {"b": 4-4, "c": "89-b"}
     }

Is there a way to do this in pyspark? Thanks

Body:
Just add a row mapping logic for Dataframe and you should be good,
Please find the code explanation inline

import org.apache.spark.sql.Row
import org.apache.spark.sql.functions._

object CatDog {

  def main(args: Array[String]): Unit = {

    val spark = Constant.getSparkSess

    import spark.implicits._

    val df = List(("cat",   "3-3"    ,"78-b"),
    ("cat"   ,"3-3",    "89-0"),
    ("cat"   ,"4-4"    ,"78-n"),
      ("dog"   ,"4-4",    "89-b")).toDF("a","b","c")

//    df.show()

    //Write your out as JSON
    df.select("a").distinct().map((a: Row) =>
      (a, df.filter(col("a") === a).map(row => parseDF(row)))
    ).foreachPartition((iterator) => {
      iterator.foreach(record => {
        val aVal = record._1.getString(0)
        record._2.write.json(s"src/main/resources/$aVal.json")
      })
    })
  }

  //Row mapping logic
  def parseDF(row: Row): Map[String, Map[String, String]] = {

    val b = row.getString(1)
    val c = row.getString(2)
    Map(b -> Map("b" -> b, "c" -> c))

  }

}


问:
How to enforce global uniqueness in a User table in CosmosDB
I need to create a User table that at minimum looks like this:

```<code>public class User
{
  public Guid Id {get; set;}
  public string Username {get; set;}
  public string EmailAddress {get; set;}
  public DateTime CreatedOn {get; set;}
}
</code>```

I'm currently writing all data to CosmosDB (SQL API). The problem is I need to add a unique index policy to Username and EmailAddress across all users. Since CosmosDB is designed with scaling out in mind, I'd need to partition this container. If I do so, I cannot enforce uniqueness across partitions.

Currently, my partition key is Id. If I change my partition key to Username or EmailAddress, I fear that changing these fields can potentially result in users being deleted (e.g. delete old username and insert new username would be two separate transactions if the usernames belong to different partitions, which means there is no atomicity.).

Is there a CosmosDB solution to this problem that I cannot think of? I can move this part to SQL Server, but I'll end up maintaining a large table over time. Also, since I'm using Azure Functions for server processing, shipping with EF DLLs makes the app size unnecessarily large.

答:
Make a synthetic partitionKey property and assign it a value, for example partitionKey:users_list. there you can keep all users id's and emails:

```<code>{
   id: guid,
   email: user@whatever.com,
   partitionKey: "users_list"
}
</code>```

make a stored procedure that registers new users and before saving a user it checks no other user exists with the same email address within "users_list" partition.

if your documents are 1kb (and i see no reason to be more) then your partition can hold up to 20 million users. if you need more, its easy to make this partition key granular but still being sure you keep all of your users in a very small number of partitions. like, 5 partitions give you 100 million users.
For example, you can have partitionKey granular by time, by world region, by starting letters, whatever you find suitable...

Body:
I need to create a User table that at minimum looks like this:

public class User
{
  public Guid Id {get; set;}
  public string Username {get; set;}
  public string EmailAddress {get; set;}
  public DateTime CreatedOn {get; set;}
}

I'm currently writing all data to CosmosDB (SQL API). The problem is I need to add a unique index policy to Username and EmailAddress across all users. Since CosmosDB is designed with scaling out in mind, I'd need to partition this container. If I do so, I cannot enforce uniqueness across partitions.

Currently, my partition key is Id. If I change my partition key to Username or EmailAddress, I fear that changing these fields can potentially result in users being deleted (e.g. delete old username and insert new username would be two separate transactions if the usernames belong to different partitions, which means there is no atomicity.).

Is there a CosmosDB solution to this problem that I cannot think of? I can move this part to SQL Server, but I'll end up maintaining a large table over time. Also, since I'm using Azure Functions for server processing, shipping with EF DLLs makes the app size unnecessarily large.

Body:
Make a synthetic partitionKey property and assign it a value, for example partitionKey:users_list. there you can keep all users id's and emails:

{
   id: guid,
   email: user@whatever.com,
   partitionKey: "users_list"
}

make a stored procedure that registers new users and before saving a user it checks no other user exists with the same email address within "users_list" partition.

if your documents are 1kb (and i see no reason to be more) then your partition can hold up to 20 million users. if you need more, its easy to make this partition key granular but still being sure you keep all of your users in a very small number of partitions. like, 5 partitions give you 100 million users.
For example, you can have partitionKey granular by time, by world region, by starting letters, whatever you find suitable...


问:
Exception when adding a record to an Access 2007 database in c#
I'm trying to add a record to an Access 2007 database using c# but I get an exception.

Here's my code, the database is called hms and the table is called login

```<code>DataSet ds = new DataSet();

System.Data.OleDb.OleDbConnection con;
DataRow dRow;
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" +  Application.StartupPath + "\\hms.mdb";
string sql = "select * from login";
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);

System.Data.OleDb.OleDbCommandBuilder cb;
cb = new System.Data.OleDb.OleDbCommandBuilder(da);

dRow = ds.Tables[1].NewRow(); //I get an error on this line

dRow[1] = "sakest";
ds.Tables["hms"].Rows.Add(dRow);
da.Fill(ds, "hms");
da.Update(ds, "hms");

MessageBox.Show("new enrtry ");
</code>```

答:
As far as I can tell, the issue with your code is that you create your DataSet (ds), but never fill it.

You need something similar to this:

```<code>using (OleDbConnection con = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\hms.mdb"))
{
    con.Open();
    string sql = "select * from login";
    using (OleDbDataAdapter da = new OleDbDataAdapter(sql, con))
    {
        DataSet ds = new DataSet();
        da.Fill(ds);

        DataRow dRow = ds.Tables[0].NewRow();
        dRow[1] = "sakest";
        ds.Tables["hms"].Rows.Add(dRow);
        da.Fill(ds, "hms");
        da.Update(ds, "hms");

        MessageBox.Show("new enrtry ");
    }
}
</code>```

Basically, the bit you're after is the da.Fill(ds) line, and the change from ds.Tables[1].NewRow() to ds.Tables[0].NewRow().

Note: I've re-jigged the code so as to show you how to wrap the OleDbConnection and OleDbDataAdapter in using's so as to ensure that they're cleaned up by the CLR properly.

Body:
I'm trying to add a record to an Access 2007 database using c# but I get an exception.

Here's my code, the database is called hms and the table is called login

DataSet ds = new DataSet();

System.Data.OleDb.OleDbConnection con;
DataRow dRow;
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" +  Application.StartupPath + "\\hms.mdb";
string sql = "select * from login";
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);

System.Data.OleDb.OleDbCommandBuilder cb;
cb = new System.Data.OleDb.OleDbCommandBuilder(da);

dRow = ds.Tables[1].NewRow(); //I get an error on this line

dRow[1] = "sakest";
ds.Tables["hms"].Rows.Add(dRow);
da.Fill(ds, "hms");
da.Update(ds, "hms");

MessageBox.Show("new enrtry ");

Body:
As far as I can tell, the issue with your code is that you create your DataSet (ds), but never fill it.

You need something similar to this:

using (OleDbConnection con = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\hms.mdb"))
{
    con.Open();
    string sql = "select * from login";
    using (OleDbDataAdapter da = new OleDbDataAdapter(sql, con))
    {
        DataSet ds = new DataSet();
        da.Fill(ds);

        DataRow dRow = ds.Tables[0].NewRow();
        dRow[1] = "sakest";
        ds.Tables["hms"].Rows.Add(dRow);
        da.Fill(ds, "hms");
        da.Update(ds, "hms");

        MessageBox.Show("new enrtry ");
    }
}

Basically, the bit you're after is the da.Fill(ds) line, and the change from ds.Tables[1].NewRow() to ds.Tables[0].NewRow().

Note: I've re-jigged the code so as to show you how to wrap the OleDbConnection and OleDbDataAdapter in using's so as to ensure that they're cleaned up by the CLR properly.


问:
Can 2 result sets be viewed from bigquery.client.query()?
I would like to run 2 Select parameters using the bigquery API.
for example, if I run the below query

```<code>SELECT 1;
SELECT 2;
</code>```

When I run this using the following python script I only obtain the result of 2nd query.

```<code>def runquery();
    bqclient = bigquery.client()
    query = """ SELECT 1;
                SELECT 2;"""
    query_job = bqclient.query(query)
    data = query_job.result()
    rows = list(data)
    print(rows)
</code>```

Result:

```<code>[Row((2,), {'f0_': 0})]
</code>```

But if I run the same query in bigquery query composer I would be able to view both the result.

How would I be able to get both the query results in Bigquery API resultset? Would I need to add a jobconfig to client.query() statement?

答:
Here's a quick example of walking a script.  In this example you parent job is of type script, which is composed of two child jobs that are both select statements.  Once the parent is complete, you can invoke list_jobs with a parent filter to find the child jobs and interrogate them for results.  Child jobs don't nest, so you only have to worry about one level of children below the parent job.

```<code>def multi_statement_script():

    from google.cloud import bigquery

    bqclient = bigquery.Client()
    query = """ SELECT 1;
                SELECT 2;
            """

    parent_query = bqclient.query(query)
    # wait for parent job to finish (which completes when all children are done)
    parent_query.result()

    print("parent job {}".format(parent_query.job_id))
    children = bqclient.list_jobs(parent_job=parent_query.job_id)

    # note the jobs are enumerated newest->oldest, so the reverse
    # ordering specified in the script
    for child in children:
        print("job {}".format(child.job_id))
        rows = list(child.result())
        print(rows)
</code>```

Body:
I would like to run 2 Select parameters using the bigquery API.
for example, if I run the below query

SELECT 1;
SELECT 2;

When I run this using the following python script I only obtain the result of 2nd query.

def runquery();
    bqclient = bigquery.client()
    query = """ SELECT 1;
                SELECT 2;"""
    query_job = bqclient.query(query)
    data = query_job.result()
    rows = list(data)
    print(rows)

Result:

[Row((2,), {'f0_': 0})]

But if I run the same query in bigquery query composer I would be able to view both the result.

How would I be able to get both the query results in Bigquery API resultset? Would I need to add a jobconfig to client.query() statement?

Body:
Here's a quick example of walking a script.  In this example you parent job is of type script, which is composed of two child jobs that are both select statements.  Once the parent is complete, you can invoke list_jobs with a parent filter to find the child jobs and interrogate them for results.  Child jobs don't nest, so you only have to worry about one level of children below the parent job.

def multi_statement_script():

    from google.cloud import bigquery

    bqclient = bigquery.Client()
    query = """ SELECT 1;
                SELECT 2;
            """

    parent_query = bqclient.query(query)
    # wait for parent job to finish (which completes when all children are done)
    parent_query.result()

    print("parent job {}".format(parent_query.job_id))
    children = bqclient.list_jobs(parent_job=parent_query.job_id)

    # note the jobs are enumerated newest->oldest, so the reverse
    # ordering specified in the script
    for child in children:
        print("job {}".format(child.job_id))
        rows = list(child.result())
        print(rows)


答:
here is the changes you can add to make it work, I add position: absolute along with left, top attributes, and for the search-box container added min-width to prevent the container from collapsing since there is no default with for the content inside:

```<code>#mybottomnav .items .item .search-box {
  position: absolute;
  top: 50%;
  right: 50%;
  transform: translate(0, -50%);
  background: #2f3640;
  height: 50px;
  border-radius: 50px;
  min-width: 50px;
  padding: 5px 10px 10px 10px;
}

#mybottomnav .items .item .search-box .search-btn {
  position: absolute;
  color: lightblue;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #2f3640;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  transition: 0.4s;
  right: 10px;
  top: 10px;
}
</code>```

NOTE: remove this CSS #mybottomnav .items .item .search-box:hover > .search-btn

Title: My Search Icon Disappears after Transition

Body:
I added a search icon with font awesome on my website that has a transition to the left but for some reason when I hover and the transition starts the font awesome icon disappears.
I'm having a hard time figuring this out because it works fine on my CodePen.

Please click on the link below to see the code in action on my website.

http://lonestarwebandgraphics.com/

Body:
here is the changes you can add to make it work, I add position: absolute along with left, top attributes, and for the search-box container added min-width to prevent the container from collapsing since there is no default with for the content inside:

#mybottomnav .items .item .search-box {
  position: absolute;
  top: 50%;
  right: 50%;
  transform: translate(0, -50%);
  background: #2f3640;
  height: 50px;
  border-radius: 50px;
  min-width: 50px;
  padding: 5px 10px 10px 10px;
}

#mybottomnav .items .item .search-box .search-btn {
  position: absolute;
  color: lightblue;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #2f3640;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  transition: 0.4s;
  right: 10px;
  top: 10px;
}

NOTE: remove this CSS #mybottomnav .items .item .search-box:hover > .search-btn


问:
unable to set value for json arraylist :object cannot be resolved or is not a field
I am unable to set value for JSON ArrayList object. I am getting error like an object cannot be resolved.

This is the code that I have written.

```<code>public class TestDataBuild {

    public static List<Addbook> addbook()
    {
    ReadJsonFile readJson=new ReadJsonFile();
    List<Addbook> addbook = readJson.getjsondata("src/test/resource/testdataresource/addplacerequest.json", Addbook.class);
    //System.out.println(addbook.getClass().getName());
    addbook.setName(addbook.name);
    addbook.setAuthor(addbook.author);
    addbook.setIsbn(addbook.isbn);
    addbook.setAisle(addbook.aisle);
    return addbook;
        }

    }
</code>```

POJO class that I have used is:

```<code>public class Addbook {

    public String name;
    public int  isbn;
    public String aisle;
    public String author;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getIsbn() {
        return isbn;
    }
    public void setIsbn(int isbn) {
        this.isbn = isbn;
    }
    public String getAisle() {
        return aisle;
    }
    public void setAisle(String aisle) {
        this.aisle = aisle;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Addbook [name="+ name + ",isbn="+ isbn +",aisle="+ aisle +",authur="+ author +"]";
    }
}
</code>```

The JSON file that I have is :

```<code>[
{"name": "The GoodDay", "isbn": 67086, "aisle": "GoodDay","author": "ggdf"},
{"name": "The BadDay", "isbn": 56897, "aisle": "BadDay", "author": "fdffd"}
]
</code>```

How should I resolve this error?

答:
You can use Google Gson . Try this :</p>

```<code>public static List<Addbook> getBookList() {
        List<Addbook> bookList = null;
        try {
            String path = "Your path here"; // I used "D:\\test.json"
            BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
            Gson gson = new Gson();
            bookList =  gson.fromJson(bufferedReader, List.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bookList;
    }
</code>```

```<code>        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>
</code>```

Body:
I am unable to set value for JSON ArrayList object. I am getting error like an object cannot be resolved.

This is the code that I have written.

public class TestDataBuild {

    public static List<Addbook> addbook()
    {
    ReadJsonFile readJson=new ReadJsonFile();
    List<Addbook> addbook = readJson.getjsondata("src/test/resource/testdataresource/addplacerequest.json", Addbook.class);
    //System.out.println(addbook.getClass().getName());
    addbook.setName(addbook.name);
    addbook.setAuthor(addbook.author);
    addbook.setIsbn(addbook.isbn);
    addbook.setAisle(addbook.aisle);
    return addbook;
        }

    }

POJO class that I have used is:

public class Addbook {

    public String name;
    public int  isbn;
    public String aisle;
    public String author;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getIsbn() {
        return isbn;
    }
    public void setIsbn(int isbn) {
        this.isbn = isbn;
    }
    public String getAisle() {
        return aisle;
    }
    public void setAisle(String aisle) {
        this.aisle = aisle;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Addbook [name="+ name + ",isbn="+ isbn +",aisle="+ aisle +",authur="+ author +"]";
    }
}

The JSON file that I have is :

[
{"name": "The GoodDay", "isbn": 67086, "aisle": "GoodDay","author": "ggdf"},
{"name": "The BadDay", "isbn": 56897, "aisle": "BadDay", "author": "fdffd"}
]

How should I resolve this error?

Body:
You can use Google Gson . Try this :

public static List<Addbook> getBookList() {
        List<Addbook> bookList = null;
        try {
            String path = "Your path here"; // I used "D:\\test.json"
            BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
            Gson gson = new Gson();
            bookList =  gson.fromJson(bufferedReader, List.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bookList;
    }

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>


问:
App.config for dll
We have an "engine" that loads dlls dynamically (whatever is located in a certain directory) and calls Workflow classes from them by way of reflection.

We now have some new Workflows that require access to a database, so I figured that I would put a config file in the dll directory.

But for some reason my Workflows just don't see the config file.

```<code><configuration>
  <appSettings>
      <add key="ConnectString" value="Data Source=officeserver;Database=mydatabase;User ID=officeuser;Password=officeuser;" />
  </appSettings>
</configuration>
</code>```

Given the above config file, the following code prints an empty string:

```<code>Console.WriteLine(ConfigurationManager.AppSettings["ConnectString"]);
</code>```

I think what I want is to just specify a config filename, but I'm having problems here.  I'm just not getting results.
Anyone have any pointers?

答:
Here is one way -
AppDomain.CurrentDomain.SetData ("APP_CONFIG_FILE", "path to config file");

Call in constructor.

ContentLicense: CC BY-SA 2.5

Title: App.config for dll

Body:
We have an "engine" that loads dlls dynamically (whatever is located in a certain directory) and calls Workflow classes from them by way of reflection.

We now have some new Workflows that require access to a database, so I figured that I would put a config file in the dll directory.

But for some reason my Workflows just don't see the config file.

<configuration>
  <appSettings>
      <add key="ConnectString" value="Data Source=officeserver;Database=mydatabase;User ID=officeuser;Password=officeuser;" />
  </appSettings>
</configuration>

Given the above config file, the following code prints an empty string:

Console.WriteLine(ConfigurationManager.AppSettings["ConnectString"]);

I think what I want is to just specify a config filename, but I'm having problems here.  I'm just not getting results.
Anyone have any pointers?

LastEditorDisplayName: Panos


问:
Getting NumberFormatException for Spring Boot rest API
I am working on the following API in Spring Boot:

```<code>/fetchStudents?prefix=<prefix>&fetchSize=<fetchSize>
</code>```

I am implementing the rest API as follows:

```<code>  @GetMapping("/fetchStudents")
   public ResponseEntity<List<Student> getStudents(@RequestParam String prefix,
                                                   @RequestParam(defaultValue="50") int fetchSize) {
   ....
  }
</code>```

While calling the API as: /fetchStudents?prefix='a'&fetchSize=50, I am getting NumberFormatException. I am not getting how to fix this issue.

答:
The issue might come from the a param that is surrounded by ` signs.

Since you send it in the URL it should be encoded to %60a%60

So it seems like Spring is not reading the first param correctly and that effects the second param of fetchSize

Try to eliminate parts of the query params to better identify the problem:

/fetchStudents?fetchSize=50

/fetchStudents?fetchSize=50&prefix='a'

/fetchStudents?fetchSize=50&prefix=%60a%60

Body:
I am working on the following API in Spring Boot:

/fetchStudents?prefix=<prefix>&fetchSize=<fetchSize>

I am implementing the rest API as follows:

  @GetMapping("/fetchStudents")
   public ResponseEntity<List<Student> getStudents(@RequestParam String prefix,
                                                   @RequestParam(defaultValue="50") int fetchSize) {
   ....
  }

While calling the API as: /fetchStudents?prefix='a'&fetchSize=50, I am getting NumberFormatException. I am not getting how to fix this issue.


问:
Update logged in user details in session
I am using PassportJS with ExpressJS.

I need to update the logged in user details. While I do update this in the DB, how do I update it in the session too so that request.user contains the updated user details?

That is, after updating the database, how do I update the session info on the user as well?

I tried directly assigning the updated details to request.user but it did not work.
I then tried request.session.passport.user - this worked but there is a delay of around 5 to 10 seconds before it gets updated in request.user too.

Is there a function that I need to call that updates the user information stored in the session? Or is there some other object that I can update where the change does not have a delay

答:
```<code>User.findById(req.user._id,function(err,doc){
        req.logIn(doc,function(err1){

                if(err1){ console.log("Error : "+err1) }
                              else{
                                    res.render("abc.ejs",{user:req.user});
                                    console.log('Item Removed Successfully!!!');
                              }

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

Here we are re-login the user

User => Mongoose Model

Body:
User.findById(req.user._id,function(err,doc){
        req.logIn(doc,function(err1){

                if(err1){ console.log("Error : "+err1) }
                              else{
                                    res.render("abc.ejs",{user:req.user});
                                    console.log('Item Removed Successfully!!!');
                              }

                        });
                  });

Here we are re-login the user

User => Mongoose Model


问:
KeyError: 'Tipos' During handling of the above exception, another exception occurred: Traceback (most recent call last):
Pandas is so difficult i have rechecked a million times and my Python file and csv are indeed in the same folder.</p>

```<code>import pandas as pd
import matplotlib.pyplot as plt

plt.subplot(131) #Numero de choques por estado al mes
estados = ['NL','COAH','EDOMEX','VER','TAMP']
choques = [12000, 7600, 9500, 3000, 5430]
plt.title ("Numero de choques por estado al mes")
plt.xlabel ('Estados')
plt.ylabel ('choques')
plt.bar(estados, choques, color = 'green')
plt.plot(estados, choques,"r:*")
plt.xticks (rotation=45, fontsize=6)
plt.subplot(132) #grafica tips de accidentes

Tipos = {'tipos' : ['choque','atropellamiento','volcamiento','otro'],
'numeros': [752, 230,365,155]}
df=pd.DataFrame(Tipos)
plt.scatter(df['tipos'], df['numeros'])
plt.xticks(rotation=45)
plt.ylabel ('Accidentes Numero de Accidentes en Nuevo Leon')
plt.xlabel ('Tipos')
plt.title ('Numero de Accidentes en Nuevo Leon')
plt.subplot(133)

tiposdevehiculos = pd.read_csv('tiposdevehiculos.csv')
df = pd.DataFrame (tiposdevehiculos)

plt.title('tipos de vehiculos y numero de accidentes')
plt.plot (df['Tipos'], df['Numero'],'r*:')
plt.xticks(rotation=35, fontsize=6)
plt.xlabel('Tipos')
plt.yticks(rotation=35, fontsize=6)
plt.ylabel('Numeros')
plt.legend(['Tipos','Numeros'])
plt.tight_layout()
plt.show()
</code>```

答:
After you created your DataFrame (df), add:

```<code>print(df.columns)
</code>```

and take a look at column names. Most probably your DataFrame has no
column named Tipos.

One possible cause of such error is that the title row in CSV file
contains spaces, e.g.:

```<code>id, Tipos, numeros,...
</code>```

For a human reading this file it is quite natural, but not for a computer.

In such case, your DataFrame has column name ' Tipos', with a leading
space, but does not have 'Tipos' column. It takes some experience to
know what to look for (among other just for such details).

Another correction is that instead of:

```<code>tiposdevehiculos = pd.read_csv('tiposdevehiculos.csv')
df = pd.DataFrame (tiposdevehiculos)
</code>```

write just:

```<code>df = pd.read_csv('tiposdevehiculos.csv')
</code>```

There is no sense to create one DataFrame (reading it from a CSV file)
and then create from it another DataFrame (df).

Yet another hint: Your first 2 pictures are created with no error.
So asking this question you should have included only the part concerning
the third picture, even without plt.subplot(133).
Just the code concerning this single picture.

And last important detail: Your stacktrace surely contains precise
indication which line of code raised this exception. You should have
included it as well.

Body:
Pandas is so difficult i have rechecked a million times and my Python file and csv are indeed in the same folder.

import pandas as pd
import matplotlib.pyplot as plt

plt.subplot(131) #Numero de choques por estado al mes
estados = ['NL','COAH','EDOMEX','VER','TAMP']
choques = [12000, 7600, 9500, 3000, 5430]
plt.title ("Numero de choques por estado al mes")
plt.xlabel ('Estados')
plt.ylabel ('choques')
plt.bar(estados, choques, color = 'green')
plt.plot(estados, choques,"r:*")
plt.xticks (rotation=45, fontsize=6)
plt.subplot(132) #grafica tips de accidentes

Tipos = {'tipos' : ['choque','atropellamiento','volcamiento','otro'],
'numeros': [752, 230,365,155]}
df=pd.DataFrame(Tipos)
plt.scatter(df['tipos'], df['numeros'])
plt.xticks(rotation=45)
plt.ylabel ('Accidentes Numero de Accidentes en Nuevo Leon')
plt.xlabel ('Tipos')
plt.title ('Numero de Accidentes en Nuevo Leon')
plt.subplot(133)

tiposdevehiculos = pd.read_csv('tiposdevehiculos.csv')
df = pd.DataFrame (tiposdevehiculos)

plt.title('tipos de vehiculos y numero de accidentes')
plt.plot (df['Tipos'], df['Numero'],'r*:')
plt.xticks(rotation=35, fontsize=6)
plt.xlabel('Tipos')
plt.yticks(rotation=35, fontsize=6)
plt.ylabel('Numeros')
plt.legend(['Tipos','Numeros'])
plt.tight_layout()
plt.show()

Body:
After you created your DataFrame (df), add:

print(df.columns)

and take a look at column names. Most probably your DataFrame has no
column named Tipos.

One possible cause of such error is that the title row in CSV file
contains spaces, e.g.:

id, Tipos, numeros,...

For a human reading this file it is quite natural, but not for a computer.

In such case, your DataFrame has column name ' Tipos', with a leading
space, but does not have 'Tipos' column. It takes some experience to
know what to look for (among other just for such details).

Another correction is that instead of:

tiposdevehiculos = pd.read_csv('tiposdevehiculos.csv')
df = pd.DataFrame (tiposdevehiculos)

write just:

df = pd.read_csv('tiposdevehiculos.csv')

There is no sense to create one DataFrame (reading it from a CSV file)
and then create from it another DataFrame (df).

Yet another hint: Your first 2 pictures are created with no error.
So asking this question you should have included only the part concerning
the third picture, even without plt.subplot(133).
Just the code concerning this single picture.

And last important detail: Your stacktrace surely contains precise
indication which line of code raised this exception. You should have
included it as well.


问:
Can't run node express on centos server
I am trying to run an express app that I installed using express --view pug urltracker. I also executed npm install to install all dependencies.

When I start it on my laptop localhost using DEBUG=urltracker:* && npm start
it perfectly starts on localhost:3000 and my app runs smoothly but when I install it on centos 7 server, the same gets stuck at [nodemon] starting `node ./bin/www and nothing happens afterwards.

I tried running it like this as well DEBUG=backend ./bin/www but it says -bash: ./bin/www: Permission denied OR sudo: ./bin/www: command not found

I can execute a normal file like node app.js and it works fine but when it comes to running it as server, it doesn't work.

Here's my package.json

```<code>{
  "name": "urltracker",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "nodemon ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.18.2",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "express": "~4.15.5",
    "morgan": "~1.9.0",
    "pug": "2.0.0-beta11",
    "serve-favicon": "~2.4.5",
    "puppeteer": "^1.6.2",
    "puppeteer-select": "^1.0.3"
  },
  "devDependencies": {
    "eslint-plugin-mocha": "^4.11.0",
    "file-system": "^2.2.2",
    "jest": "^21.2.1",
    "js-comments": "^0.5.4",
    "lodash": "^4.17.13"
  }
}

</code>```

I also tried it with running node supervisor using supervisor ./bin/www
but it says

```<code>Starting child process with 'node ./bin/www'
Watching directory '/home/admin/web/example.com/node/projects' for changes.
Press rs for restarting the process.
</code>```

I also tried changing the port to 3001 in ./bin/www like this - server.listen('3001', '0.0.0.0');

but nothing works. Help.

答:
Nodemon is not listed in your dependencies list in package.json and on the centos server nodemon is not present.

Please add the nodemon dependency in the package.json and then run npm i
or change the start script from "start": "nodemon ./bin/www" to "start": "node ./bin/www"

Title: Can't run node express on centos server

Body:
I am trying to run an express app that I installed using express --view pug urltracker. I also executed npm install to install all dependencies.

When I start it on my laptop localhost using DEBUG=urltracker:* && npm start
it perfectly starts on localhost:3000 and my app runs smoothly but when I install it on centos 7 server, the same gets stuck at [nodemon] starting `node ./bin/www and nothing happens afterwards.

I tried running it like this as well DEBUG=backend ./bin/www but it says -bash: ./bin/www: Permission denied OR sudo: ./bin/www: command not found

I can execute a normal file like node app.js and it works fine but when it comes to running it as server, it doesn't work.

Here's my package.json

{
  "name": "urltracker",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "nodemon ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.18.2",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "express": "~4.15.5",
    "morgan": "~1.9.0",
    "pug": "2.0.0-beta11",
    "serve-favicon": "~2.4.5",
    "puppeteer": "^1.6.2",
    "puppeteer-select": "^1.0.3"
  },
  "devDependencies": {
    "eslint-plugin-mocha": "^4.11.0",
    "file-system": "^2.2.2",
    "jest": "^21.2.1",
    "js-comments": "^0.5.4",
    "lodash": "^4.17.13"
  }
}

I also tried it with running node supervisor using supervisor ./bin/www
but it says

Starting child process with 'node ./bin/www'
Watching directory '/home/admin/web/example.com/node/projects' for changes.
Press rs for restarting the process.

I also tried changing the port to 3001 in ./bin/www like this - server.listen('3001', '0.0.0.0');

but nothing works. Help.


问:
Nginx on kubernetes not serving static content
I have Nginx Open Source on AKS service. Every thing was good but unable to serve static content like index.html or favicon.ico.

When I open http:// it is not serving the index.html by default[i get 404] and if I try to open any static content I get 404 error.

nginx configuration was passed as ConfigMap and below is the config file that talks about serving static content.

```<code>server {
listen 80;
server_name localhost;
root /opt/abc/html; #also tried root /opt/abc/html/

location / {
root /opt/abc/html; #also tried root /opt/abc/html/
index index.html;
try_files $uri $uri/ /index.html?$args;

...
...
..

proxy_pass http://tomcat;
}
}
</code>```

Setup:
Kubernetes on AKS
Nginx Open Source [no ingress]
configMaps to mount config.d
the static content (/opt/abc/html) was passed into pod with kubernetes cp command. [will this work?]

答:
ref: https://github.com/RammusXu/toolkit/tree/master/k8s/echoserver

Here's a example to mount nginx.conf from ConfigMap

And make sure you kubectl rollout restart deployment echoserver after update ConfigMap. Pod only clone ConfigMap when it created. It don't sync or auto-updated.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: echoserver
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      app: echoserver
  template:
    metadata:
      labels:
        app: echoserver
    spec:
      volumes:
      - name: config
        configMap:
          name: nginx-config

      containers:
      - name: echoserver
        # image: gcr.io/google_containers/echoserver:1.10
        image: openresty/openresty:1.15.8.2-1-alpine
        ports:
        - containerPort: 8080
          name: http

        # nginx.conf override
        volumeMounts:
        - name: config
          subPath: nginx.conf
          # mountPath: /etc/nginx/nginx.conf
          mountPath: /usr/local/openresty/nginx/conf/nginx.conf
          readOnly: true
---
apiVersion: v1
kind: Service
metadata:
  name: echoserver
  namespace: default
spec:
  type: NodePort
  ports:
  - port: 80
    targetPort: http
    protocol: TCP
    name: http
  selector:
    app: echoserver
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config
  namespace: default
data:
  nginx.conf: |-
    events {
      worker_connections 1024;
    }

    env HOSTNAME;
    env NODE_NAME;
    env POD_NAME;
    env POD_NAMESPACE;
    env POD_IP;

    http {
      default_type 'text/plain';
      # maximum allowed size of the client request body. By default this is 1m.
      # Request with bigger bodies nginx will return error code 413.
      # http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size
      client_max_body_size 10m;

      # https://blog.percy.io/tuning-nginx-behind-google-cloud-platform-http-s-load-balancer-305982ddb340
      keepalive_timeout         650;
      keepalive_requests        10000;

      # GZIP support
      gzip                      on;
      gzip_min_length           128;
      gzip_proxied              any;
      gzip_comp_level           6;

      gzip_types                text/css
                                text/plain
                                text/javascript
                                application/javascript
                                application/json
                                application/x-javascript
                                application/xml
                                application/xml+rss
                                application/xhtml+xml
                                application/x-font-ttf
                                application/x-font-opentype
                                application/vnd.ms-fontobject
                                image/svg+xml
                                image/x-icon
                                application/rss+xml
                                application/atom_xml
                                application/vnd.apple.mpegURL
                                application/x-mpegurl
                                vnd.apple.mpegURL
                                application/dash+xml;

      init_by_lua_block {
        local template = require("template")
        -- template syntax documented here:
        -- https://github.com/bungle/lua-resty-template/blob/master/README.md
        tmpl = template.compile([[

    Hostname: {{os.getenv("HOSTNAME") or "N/A"}}

    Pod Information:
    {% if os.getenv("POD_NAME") then %}
      node name:    {{os.getenv("NODE_NAME") or "N/A"}}
      pod name: {{os.getenv("POD_NAME") or "N/A"}}
      pod namespace:    {{os.getenv("POD_NAMESPACE") or "N/A"}}
      pod IP:   {{os.getenv("POD_IP") or "N/A"}}
    {% else %}
      -no pod information available-
    {% end %}

    Server values:
      server_version=nginx: {{ngx.var.nginx_version}} - lua: {{ngx.config.ngx_lua_version}}

    Request Information:
      client_address={{ngx.var.remote_addr}}
      method={{ngx.req.get_method()}}
      real path={{ngx.var.request_uri}}
      query={{ngx.var.query_string or ""}}
      request_version={{ngx.req.http_version()}}
      request_scheme={{ngx.var.scheme}}
      request_uri={{ngx.var.scheme.."://"..ngx.var.host..":"..ngx.var.server_port..ngx.var.request_uri}}

    Request Headers:
    {% for i, key in ipairs(keys) do %}
      {{key}}={{headers[key]}}
    {% end %}

    Request Body:
    {{ngx.var.request_body or " -no body in request-"}}
    ]])
      }

      server {
        # please check the benefits of reuseport https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1
        # basically instructs to create an individual listening socket for each worker process (using the SO_REUSEPORT
        # socket option), allowing a kernel to distribute incoming connections between worker processes.
        listen 8080 default_server reuseport;
        listen 8443 default_server ssl http2 reuseport;

        ssl_certificate /certs/certificate.crt;
        ssl_certificate_key /certs/privateKey.key;

        # Replace '_' with your hostname.
        server_name _;

        location / {
          lua_need_request_body on;
          content_by_lua_block {
            ngx.header["Server"] = "echoserver"

            local headers = ngx.req.get_headers()
            local keys = {}
            for key, val in pairs(headers) do
              table.insert(keys, key)
            end
            table.sort(keys)

            ngx.say(tmpl({os=os, ngx=ngx, keys=keys, headers=headers}))
          }
        }
      }
    }
```

Body:
I have Nginx Open Source on AKS service. Every thing was good but unable to serve static content like index.html or favicon.ico.

When I open http:// it is not serving the index.html by default[i get 404] and if I try to open any static content I get 404 error.

nginx configuration was passed as ConfigMap and below is the config file that talks about serving static content.

server {
listen 80;
server_name localhost;
root /opt/abc/html; #also tried root /opt/abc/html/

location / {
root /opt/abc/html; #also tried root /opt/abc/html/
index index.html;
try_files $uri $uri/ /index.html?$args;

...
...
..

proxy_pass http://tomcat;
}
}

Setup:
Kubernetes on AKS
Nginx Open Source [no ingress]
configMaps to mount config.d
the static content (/opt/abc/html) was passed into pod with kubernetes cp command. [will this work?]


问:
nodejs - certificate has expired
In my nodejs code, I request to a site using request library:

```<code>const httpReq = require("request")
function postJSON(uri, data, headers) {
  if (uri.slice(-1) != "/") {
    uri += "/"
  }

  console.log(`[postJSON] uri: ${uri}`)
  console.log(`[postJSON] body: ${JSON.stringify(data, null, 2)}`)
  console.log("[postJSON] headers", JSON.stringify(headers, null, 2))

  return new Promise((resolve, reject) => {
    httpReq(
      {
        method: "POST",
        uri: uri + Math.floor(Math.random() * 100000000).toString(),
        headers: headers,
        json: data
      }, function (err, resp, body) {
        console.log(`[postJSON] done with error: ${err} -> ${uri}`)

        if (err) {
          reject(err)
        }
        else {
          resolve(body)
        }
      }
    )
  })
}
</code>```

For ~30 recent hours, my NodeJS code has got this issue:

```<code>unhandledRejection at: Promise  Promise {
  <rejected> { Error: certificate has expired
    at TLSSocket.<anonymous> (_tls_wrap.js:1108:38)
    at emitNone (events.js:105:13)
    at TLSSocket.emit (events.js:207:7)
    at TLSSocket._finishInit (_tls_wrap.js:638:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:468:38) code: 'CERT_HAS_EXPIRED' } } reason:  { Error: certificate has expired
    at TLSSocket.<anonymous> (_tls_wrap.js:1108:38)
    at emitNone (events.js:105:13)
    at TLSSocket.emit (events.js:207:7)
    at TLSSocket._finishInit (_tls_wrap.js:638:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:468:38) code: 'CERT_HAS_EXPIRED' }
</code>```

I checked: Certificate of the endpoint (which is https://...) by opening Safari, accessing endpoint, and confirming the certificate expired data is ~Apr, 2021

I also tried to request the endpoint using curl and axios library from my server (the same location as my original nodejs code), the error is still thrown as above.
I tried to request from my local machine, using the same code. It works!

So, there could be some difference between requests from my server and those from my local machine.

What could possibly cause this issue? How should I fix this?

As a temporary solution, I add this: process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'

Thanks

答:
In https://support.sectigo.com/Com_KnowledgeDetailPage?Id=kA03l00000117LT it state modern browser will have the modern USERTRust root so that the outdated AddTrust External CA Root will not be used to verify.

So, for node code, I try to test different node version, hope that new node version will do something like new browser to update to the modern USERTRust root

The test code is quite simple

```<code>const axios = require('axios');

axios.get('https://some.site.use.addtrust.external.ca.root')
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error.message);
  })
</code>```

I tested all the 4 cases shown here:
http://testsites.test.certificatetest.com/

Result shows that for the first 3 cases, nodejs version affects nothing. However, for the 4th case, node 10+ seems can fix the issue.

Here is the result:

lts/carbon -> v8.17.0 (certificate has expired)

lts/dubnium -> v10.20.1 (ok)

lts/erbium -> v12.17.0 (ok)

I test it on my mac Catalina 10.15.5

It appears that use node version 10+ can solve this issue for Certificate issued from a CA signed by USERTrust RSA Certification Authority with a cross cert via server chain from AddTrust External CA Root.

Title: nodejs - certificate has expired

Body:
In my nodejs code, I request to a site using request library:

const httpReq = require("request")
function postJSON(uri, data, headers) {
  if (uri.slice(-1) != "/") {
    uri += "/"
  }

  console.log(`[postJSON] uri: ${uri}`)
  console.log(`[postJSON] body: ${JSON.stringify(data, null, 2)}`)
  console.log("[postJSON] headers", JSON.stringify(headers, null, 2))

  return new Promise((resolve, reject) => {
    httpReq(
      {
        method: "POST",
        uri: uri + Math.floor(Math.random() * 100000000).toString(),
        headers: headers,
        json: data
      }, function (err, resp, body) {
        console.log(`[postJSON] done with error: ${err} -> ${uri}`)

        if (err) {
          reject(err)
        }
        else {
          resolve(body)
        }
      }
    )
  })
}

For ~30 recent hours, my NodeJS code has got this issue:

unhandledRejection at: Promise  Promise {
  <rejected> { Error: certificate has expired
    at TLSSocket.<anonymous> (_tls_wrap.js:1108:38)
    at emitNone (events.js:105:13)
    at TLSSocket.emit (events.js:207:7)
    at TLSSocket._finishInit (_tls_wrap.js:638:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:468:38) code: 'CERT_HAS_EXPIRED' } } reason:  { Error: certificate has expired
    at TLSSocket.<anonymous> (_tls_wrap.js:1108:38)
    at emitNone (events.js:105:13)
    at TLSSocket.emit (events.js:207:7)
    at TLSSocket._finishInit (_tls_wrap.js:638:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:468:38) code: 'CERT_HAS_EXPIRED' }

I checked: Certificate of the endpoint (which is https://...) by opening Safari, accessing endpoint, and confirming the certificate expired data is ~Apr, 2021

I also tried to request the endpoint using curl and axios library from my server (the same location as my original nodejs code), the error is still thrown as above.
I tried to request from my local machine, using the same code. It works!

So, there could be some difference between requests from my server and those from my local machine.

What could possibly cause this issue? How should I fix this?

As a temporary solution, I add this: process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'

Thanks

Body:
In https://support.sectigo.com/Com_KnowledgeDetailPage?Id=kA03l00000117LT it state modern browser will have the modern USERTRust root so that the outdated AddTrust External CA Root will not be used to verify.

So, for node code, I try to test different node version, hope that new node version will do something like new browser to update to the modern USERTRust root

The test code is quite simple

const axios = require('axios');

axios.get('https://some.site.use.addtrust.external.ca.root')
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error.message);
  })

I tested all the 4 cases shown here:
http://testsites.test.certificatetest.com/

Result shows that for the first 3 cases, nodejs version affects nothing. However, for the 4th case, node 10+ seems can fix the issue.

Here is the result:

lts/carbon -> v8.17.0 (certificate has expired)

lts/dubnium -> v10.20.1 (ok)

lts/erbium -> v12.17.0 (ok)

I test it on my mac Catalina 10.15.5

It appears that use node version 10+ can solve this issue for Certificate issued from a CA signed by USERTrust RSA Certification Authority with a cross cert via server chain from AddTrust External CA Root.


问:
What is the purpose of using JSON.stringify()?
I'm using JSON.stringify in my react redux application. What's the purpose of JSON.stringify in the following context? Even without JSON.stringify it works, but yet I've been advised to use JSON.stringify.

```<code>if (JSON.stringify(earlyBird.eBird) !== JSON.stringify(prevProps.earlyBird.eBird)) {
</code>```

答:
It is used to turn javascript objects into their JSON string equivalent i.e.</p>

```<code>typeof(JSON.stringify(['Hello'])); //string
typeof(['Hello']); //object
</code>```

Body:
I'm using JSON.stringify in my react redux application. What's the purpose of JSON.stringify in the following context? Even without JSON.stringify it works, but yet I've been advised to use JSON.stringify.

if (JSON.stringify(earlyBird.eBird) !== JSON.stringify(prevProps.earlyBird.eBird)) {

Body:
It is used to turn javascript objects into their JSON string equivalent i.e.

typeof(JSON.stringify(['Hello'])); //string
typeof(['Hello']); //object


问:
Adding a JComponent on top of full-screen-graphics
I have a fullscreen program, which draws a lot of things for the game I am making. The canvas is the entire window, which it should be. Now I want to add a button, or textfield (JButton and JTextField etc...) to my window. However, when I add a button, or anything else, they go begind the canvas.

Do you have any idea how to get the button to show up ON the canvas, so I can click it?

Edit:
Drawing code:

```<code>public synchronized void draw(Graphics2D g) {
        if (!welcome)
            g.drawImage(background,0,0,null);

        if (welcome) {
            g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
        }
        else if (gettingName) {
            setFont (new Font("Verdana", Font.ITALIC, 40));

            g.draw3DRect(center.x -325, center.y -50, 650, 100, true);
            g.drawString("Please enter your name", center.x -250, center.y -120);
            g.drawString(name, center.x -315, center.y);
        }
        if (game) {
            for (Player p: player) {
                int x = center.x;
                int y = center.y;

                switch (p.getID()) {
                case 1:
                    x -= name.length()*10;
                    y *= 1.4;
                    break;
                case 2:
                    x -= name.length()*10;
                    y /= 1.4;
                    break;
                case 3:
                    x *= 1.4;
                    x -= name.length()*10;
                    break;
                case 4:
                    x *= 0.6;
                    x -= name.length()*10;
                    break;
                default:
                    System.out.println("Error 2");
                }
                g.drawString(p.getName(),x,y);
            }
            for (int x = 0; x<13; x++) {
                g.drawImage(diamonds[x].getImage(), (int) diamonds[x].getX(), (int) diamonds[x].getY(), null);
                g.drawImage(clubs[x].getImage(), (int) clubs[x].getX(), (int) clubs[x].getY(), null);
                g.drawImage(hearts[x].getImage(), (int) hearts[x].getX(), (int) hearts[x].getY(), null);
                g.drawImage(spades[x].getImage(), (int) spades[x].getX(), (int) spades[x].getY(), null);
            }
            g.drawImage(put.getImage(), (int) put.getX(), (int) put.getY(), null);
        }

        if (won) {
            g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
        }
        else if (lost) {
            g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
        }
    }
</code>```

Edit2:
My frame is a JFrame.

答:
It is difficult to tell much from the code snippet (please consider posting an SSCCE in future), but:

Don't code AWT in this millennium.

Don't mix Swing with AWT (at least until Java 7)

Don't load images within the draw() method (which is presumably called from the paintComponent() method).

Note that custom painting in Swing can be done in a JComponent or JPanel and that if the class is the latter, it can have a layout with other components added.

Body:
I have a fullscreen program, which draws a lot of things for the game I am making. The canvas is the entire window, which it should be. Now I want to add a button, or textfield (JButton and JTextField etc...) to my window. However, when I add a button, or anything else, they go begind the canvas.

Do you have any idea how to get the button to show up ON the canvas, so I can click it?

Edit:
Drawing code:

public synchronized void draw(Graphics2D g) {
        if (!welcome)
            g.drawImage(background,0,0,null);

        if (welcome) {
            g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
        }
        else if (gettingName) {
            setFont (new Font("Verdana", Font.ITALIC, 40));

            g.draw3DRect(center.x -325, center.y -50, 650, 100, true);
            g.drawString("Please enter your name", center.x -250, center.y -120);
            g.drawString(name, center.x -315, center.y);
        }
        if (game) {
            for (Player p: player) {
                int x = center.x;
                int y = center.y;

                switch (p.getID()) {
                case 1:
                    x -= name.length()*10;
                    y *= 1.4;
                    break;
                case 2:
                    x -= name.length()*10;
                    y /= 1.4;
                    break;
                case 3:
                    x *= 1.4;
                    x -= name.length()*10;
                    break;
                case 4:
                    x *= 0.6;
                    x -= name.length()*10;
                    break;
                default:
                    System.out.println("Error 2");
                }
                g.drawString(p.getName(),x,y);
            }
            for (int x = 0; x<13; x++) {
                g.drawImage(diamonds[x].getImage(), (int) diamonds[x].getX(), (int) diamonds[x].getY(), null);
                g.drawImage(clubs[x].getImage(), (int) clubs[x].getX(), (int) clubs[x].getY(), null);
                g.drawImage(hearts[x].getImage(), (int) hearts[x].getX(), (int) hearts[x].getY(), null);
                g.drawImage(spades[x].getImage(), (int) spades[x].getX(), (int) spades[x].getY(), null);
            }
            g.drawImage(put.getImage(), (int) put.getX(), (int) put.getY(), null);
        }

        if (won) {
            g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
        }
        else if (lost) {
            g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
        }
    }

Edit2:
My frame is a JFrame.


问:
Delete row containing #N/A
I am trying to delete rows from a table where a value within that row is #N/A

Sub remove_na()

Dim ws As Worksheet

Dim r As Variant
Dim i As Variant

Set ws = ThisWorkbook.ActiveSheet

r = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

For Each i In Range("A1:A" & r)
    If i = "#N/A" Then i.EntireRow.Delete
Next

End Sub
```
<p>I get a Type Mismatch error on the IF statement. I tried using WHILE loops as well as FOR. The same issue occurred.</p>
<p>An example of the data being processed is columns of data (a few hundred records):</p>
<pre class="lang-none prettyprint-override"><code>#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
456699.512  6523052.64
456699.512  6523052.64
456699.512  6523052.64
456699.512  6523052.64
456699.512  6523052.64
</code>```

答:
You can use the IsError() function to evaluate if the cell contains the #N/A error within your If...Then statement.

Like so:

```<code>If IsError(i.Value) Then
    i.EntireRow.Delete
End If
</code>```

Note: Not tested due to lack of excel on this workstation.

Title: Delete row containing #N/A

Body:
I am trying to delete rows from a table where a value within that row is #N/A

Sub remove_na()

Dim ws As Worksheet

Dim r As Variant
Dim i As Variant

Set ws = ThisWorkbook.ActiveSheet

r = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

For Each i In Range("A1:A" & r)
    If i = "#N/A" Then i.EntireRow.Delete
Next

End Sub

I get a Type Mismatch error on the IF statement. I tried using WHILE loops as well as FOR. The same issue occurred.

An example of the data being processed is columns of data (a few hundred records):

#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
#N/A        #N/A
456699.512  6523052.64
456699.512  6523052.64
456699.512  6523052.64
456699.512  6523052.64
456699.512  6523052.64

Body:
You can use the IsError() function to evaluate if the cell contains the #N/A error within your If...Then statement.

Like so:

If IsError(i.Value) Then
    i.EntireRow.Delete
End If

Note: Not tested due to lack of excel on this workstation.


问:
SCSS loading error while building React application
I am trying to build a React application using Webpack. I get this error, connected with main SCSS file:

```<code>ERROR in ./resources/scss/style.scss (./node_modules/css-loader/dist/cjs.js??ref--6-2!./node_modules/sass-loader/dist/cjs.js!./resources/scss/style.scss)
Module build failed (from ./node_modules/css-loader/dist/cjs.js):
ValidationError: Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema.     - options has an unknown property 'minimize'. These properties are valid:
object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }
at validate (C:\Users\User\Documents\Projects\App\client\node_modules\schema-utils\dist\validate.js:96:11)
at Object.loader (C:\Users\User\Documents\Projects\App\client\node_modules\css-loader\dist\index.js:36:28)
</code>```

I can't understant, what's wrong. There are the fragments of my package.json and style.scss:

package.json

```<code>  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode production",
    "start": "webpack-dev-server --mode development --open"
  },
  "devDependencies": {
    "babel": "^6.23.0",
    "node-sass": "^4.14.1",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.2.1",
    "webpack": "^4.43.0",
  }
</code>```

style.scss

```<code>@import "~bootstrap/scss/bootstrap";

body, html {
  height: 100%;
  background-color: rgba(0,0,0,.018);
  color: rgba(0,0,0,.75);
}
</code>```

答: I thought that the problem was in dependencies, but I fixed it by deleting option minimize: true in webpack.config.js.

Body:
I am trying to build a React application using Webpack. I get this error, connected with main SCSS file:

ERROR in ./resources/scss/style.scss (./node_modules/css-loader/dist/cjs.js??ref--6-2!./node_modules/sass-loader/dist/cjs.js!./resources/scss/style.scss)
Module build failed (from ./node_modules/css-loader/dist/cjs.js):
ValidationError: Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema.     - options has an unknown property 'minimize'. These properties are valid:
object { url?, import?, modules?, sourceMap?, importLoaders?, localsConvention?, onlyLocals?, esModule? }
at validate (C:\Users\User\Documents\Projects\App\client\node_modules\schema-utils\dist\validate.js:96:11)
at Object.loader (C:\Users\User\Documents\Projects\App\client\node_modules\css-loader\dist\index.js:36:28)

I can't understant, what's wrong. There are the fragments of my package.json and style.scss:

package.json

  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode production",
    "start": "webpack-dev-server --mode development --open"
  },
  "devDependencies": {
    "babel": "^6.23.0",
    "node-sass": "^4.14.1",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.2.1",
    "webpack": "^4.43.0",
  }

style.scss

@import "~bootstrap/scss/bootstrap";

body, html {
  height: 100%;
  background-color: rgba(0,0,0,.018);
  color: rgba(0,0,0,.75);
}