问:
Character string limit reached early using fread from data.table, CSV lines look fine
I'm reading a moderately big CSV with fread but it errors out with "R character strings are limited to 2^31-1 bytes". readLines works fine, however. Pinning down the faulty line (2965), I am not sure what's going on: doesn't seem longer than the next one, for example.

Any thoughts about what is going on and how to overcome this, preferably checking the CSV in advance to avoid an fread error?

library(data.table)
options(timeout=10000)

download.file("https://s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_2010-03.csv",
              destfile = "trip_data.csv", mode = "wb")

dt = fread("trip_data.csv")
#> Error in fread("trip_data.csv"): R character strings are limited to 2^31-1 bytes

lines = readLines("trip_data.csv")

dt2955 = fread("trip_data.csv", nrows = 2955)
#> Warning in fread("trip_data.csv", nrows = 2955): Previous fread() session was
#> not cleaned up properly. Cleaned up ok at the beginning of this fread() call.
dt2956 = fread("trip_data.csv", nrows = 2956)
#> Error in fread("trip_data.csv", nrows = 2956): R character strings are limited to 2^31-1 bytes
lines[2955]
#> [1] "CMT,2010-03-07 18:37:05,2010-03-07 18:41:51,1,1,-73.984211000000002,40.743720000000003,1,0,-73.974515999999994,40.748331,Cre,4.9000000000000004,0,0.5,1.0800000000000001,0,6.4800000000000004"
lines[2956]
#> [1] "CMT,2010-03-07 22:59:01,2010-03-07 23:01:04,1,0.59999999999999998,-73.992887999999994,40.703017000000003,1,0,-73.992887999999994,40.703017000000003,Cre,3.7000000000000002,0.5,0.5,2,0,6.7000000000000002"
```

Created on 2022-02-12 by the reprex package (v2.0.1)

答:
When trying to read part of the file (around 100k rows) I got:

```<code>Warning message:
In fread("trip_data.csv", skip = i * 500, nrows = 500) :
  Stopped early on line 2958. Expected 18 fields but found 19. Consider fill=TRUE and comment.char=. First discarded non-empty line: <<CMT,2010-03-07 03:46:42,2010-03-07 03:58:31,1,3.6000000000000001,-73.961027000000001,40.796674000000003,1,,,-73.937324000000004,40.839283000000002,Cas,10.9,0.5,0.5,0,0,11.9>>
>
</code>```

After removing it I was able to read at least 100 k rows

```<code>da = data.table(check.names = FALSE)

for (i in 0:200) {
  print(i*500)
  dt = fread("trip_data.csv", skip = i*500, nrows = 500, fill = TRUE)
  da <- rbind(da, dt, use.names = FALSE)
}

str(da)
Classes ‘data.table’ and 'data.frame':  101000 obs. of  18 variables:
 $ vendor_id         : chr  "" "CMT" "CMT" "CMT" ...
 $ pickup_datetime   : POSIXct, format: NA "2010-03-22 17:05:03" "2010-03-22 19:24:29" ...
 $ dropoff_datetime  : POSIXct, format: NA "2010-03-22 17:22:51" "2010-03-22 19:40:13" ...
 $ passenger_count   : int  NA 1 1 1 3 1 1 1 1 1 ...
[...]
</code>```

Any thoughts about what is going on and how to overcome this, preferably checking the CSV in advance to avoid an fread error?

Then you can read it line by line, checking length of the list, and binding it to data table.

Regards,
Grzegorz

Body:
I'm reading a moderately big CSV with fread but it errors out with "R character strings are limited to 2^31-1 bytes". readLines works fine, however. Pinning down the faulty line (2965), I am not sure what's going on: doesn't seem longer than the next one, for example.

Any thoughts about what is going on and how to overcome this, preferably checking the CSV in advance to avoid an fread error?

library(data.table)
options(timeout=10000)

download.file("https://s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_2010-03.csv",
              destfile = "trip_data.csv", mode = "wb")

dt = fread("trip_data.csv")
#> Error in fread("trip_data.csv"): R character strings are limited to 2^31-1 bytes

lines = readLines("trip_data.csv")

dt2955 = fread("trip_data.csv", nrows = 2955)
#> Warning in fread("trip_data.csv", nrows = 2955): Previous fread() session was
#> not cleaned up properly. Cleaned up ok at the beginning of this fread() call.
dt2956 = fread("trip_data.csv", nrows = 2956)
#> Error in fread("trip_data.csv", nrows = 2956): R character strings are limited to 2^31-1 bytes
lines[2955]
#> [1] "CMT,2010-03-07 18:37:05,2010-03-07 18:41:51,1,1,-73.984211000000002,40.743720000000003,1,0,-73.974515999999994,40.748331,Cre,4.9000000000000004,0,0.5,1.0800000000000001,0,6.4800000000000004"
lines[2956]
#> [1] "CMT,2010-03-07 22:59:01,2010-03-07 23:01:04,1,0.59999999999999998,-73.992887999999994,40.703017000000003,1,0,-73.992887999999994,40.703017000000003,Cre,3.7000000000000002,0.5,0.5,2,0,6.7000000000000002"

Created on 2022-02-12 by the reprex package (v2.0.1)

Body:
When trying to read part of the file (around 100k rows) I got:

Warning message:
In fread("trip_data.csv", skip = i * 500, nrows = 500) :
  Stopped early on line 2958. Expected 18 fields but found 19. Consider fill=TRUE and comment.char=. First discarded non-empty line: <<CMT,2010-03-07 03:46:42,2010-03-07 03:58:31,1,3.6000000000000001,-73.961027000000001,40.796674000000003,1,,,-73.937324000000004,40.839283000000002,Cas,10.9,0.5,0.5,0,0,11.9>>
>

After removing it I was able to read at least 100 k rows

da = data.table(check.names = FALSE)

for (i in 0:200) {
  print(i*500)
  dt = fread("trip_data.csv", skip = i*500, nrows = 500, fill = TRUE)
  da <- rbind(da, dt, use.names = FALSE)
}

str(da)
Classes ‘data.table’ and 'data.frame':  101000 obs. of  18 variables:
 $ vendor_id         : chr  "" "CMT" "CMT" "CMT" ...
 $ pickup_datetime   : POSIXct, format: NA "2010-03-22 17:05:03" "2010-03-22 19:24:29" ...
 $ dropoff_datetime  : POSIXct, format: NA "2010-03-22 17:22:51" "2010-03-22 19:40:13" ...
 $ passenger_count   : int  NA 1 1 1 3 1 1 1 1 1 ...
[...]

Any thoughts about what is going on and how to overcome this, preferably checking the CSV in advance to avoid an fread error?

Then you can read it line by line, checking length of the list, and binding it to data table.

Regards,
Grzegorz


来源: stackexchange

问:
How to stream binary data into a PostgreSQL BYTEA column using the Golang lib/pq API?
I'd like to insert some binary data into a BYTEA column,

How would I go about streaming the contents of somefile.tar.gz into a table with a BYTEA column?

Is it possible to stream to/from postgres from/to golang?

答:
If one would be willing to switch to github.com/jackc/pgx, Large Objects (PostgreSQL docs) can be streamed. The pgx.LargeObject type implements:

```<code>io.Writer
io.Reader
io.Seeker
io.Closer
</code>```

Large Objects are stored in a system table, there is no Large Object type which can be used in a column of a table. Large Objects are referenced by their object identifier. So a separate table needs to be maintained with file metadata and oid mapping.

Example program:

```<code>package main

import (
    "context"
    "io"
    "log"
    "os"
    "time"

    "github.com/jackc/pgx/v4"
)

const (
    // files table maps Large Object oid to file names
    createFileTable = `CREATE TABLE files (
        id oid primary key,
        name varchar,
        unique(name)
    );`
)

func main() {
    ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
    defer cancel()

    conn, err := pgx.Connect(ctx, "user=postgres host=/run/postgresql dbname=postgres")
    if err != nil {
        panic(err)
    }
    defer conn.Close(ctx)

    if _, err = conn.Exec(ctx, createFileTable); err != nil {
        panic(err)
    }

    written, err := storeFile(ctx, conn, "somefile.bin")
    log.Printf("storeFile written: %d", written)
    if err != nil {
        panic(err)
    }

    read, err := loadFile(ctx, conn, "somefile.bin")
    log.Printf("loadFile read: %d", read)
    if err != nil {
        panic(err)
    }
}

// storeFile as Large Object in the database.
// The resulting object identifier is stored along with the file name in the files table.
// The amount of written bytes and an erorr is returned, if one occured.
func storeFile(ctx context.Context, conn *pgx.Conn, name string) (written int64, err error) {
    file, err := os.Open(name)
    if err != nil {
        return 0, err
    }
    defer file.Close()

    // LargeObjects can only operate on an active TX
    tx, err := conn.Begin(ctx)
    if err != nil {
        return 0, err
    }
    defer tx.Rollback(ctx)

    lobs := tx.LargeObjects()

    // Create a new Large Object.
    // We pass 0, so the DB can pick an available oid for us.
    oid, err := lobs.Create(ctx, 0)
    if err != nil {
        return 0, err
    }

    // record the oid and filename in the files table
    _, err = tx.Exec(ctx, "INSERT INTO files (id, name) VALUES ($1, $2)", oid, name)
    if err != nil {
        return 0, err
    }

    // Open the new Object for writing.
    obj, err := lobs.Open(ctx, oid, pgx.LargeObjectModeWrite)
    if err != nil {
        return 0, err
    }

    // Copy the file stream to the Large Object stream
    written, err = io.Copy(obj, file)
    if err != nil {
        return written, err
    }

    err = tx.Commit(ctx)
    return written, err
}

// loadFile loads the file identified by name as Large Object
// and writes the contents to a local file by the same name.
// The amount of bytes read or an error is returned.
func loadFile(ctx context.Context, conn *pgx.Conn, name string) (read int64, err error) {
    tx, err := conn.Begin(ctx)
    if err != nil {
        return 0, err
    }
    defer tx.Rollback(ctx)

    var oid uint32
    err = conn.QueryRow(ctx, "SELECT id FROM files WHERE name = $1", name).Scan(&oid)
    if err != nil {
        return 0, err
    }

    file, err := os.Create(name)
    if err != nil {
        return 0, err
    }

    lobs := tx.LargeObjects()
    obj, err := lobs.Open(ctx, oid, pgx.LargeObjectModeRead)
    if err != nil {
        return 0, err
    }

    return io.Copy(file, obj)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If one would be willing to switch to github.com/jackc/pgx, Large Objects (PostgreSQL docs) can be streamed. The pgx.LargeObject type implements:

io.Writer
io.Reader
io.Seeker
io.Closer

Large Objects are stored in a system table, there is no Large Object type which can be used in a column of a table. Large Objects are referenced by their object identifier. So a separate table needs to be maintained with file metadata and oid mapping.

Example program:

package main

import (
    "context"
    "io"
    "log"
    "os"
    "time"

    "github.com/jackc/pgx/v4"
)

const (
    // files table maps Large Object oid to file names
    createFileTable = `CREATE TABLE files (
        id oid primary key,
        name varchar,
        unique(name)
    );`
)

func main() {
    ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
    defer cancel()

    conn, err := pgx.Connect(ctx, "user=postgres host=/run/postgresql dbname=postgres")
    if err != nil {
        panic(err)
    }
    defer conn.Close(ctx)

    if _, err = conn.Exec(ctx, createFileTable); err != nil {
        panic(err)
    }

    written, err := storeFile(ctx, conn, "somefile.bin")
    log.Printf("storeFile written: %d", written)
    if err != nil {
        panic(err)
    }

    read, err := loadFile(ctx, conn, "somefile.bin")
    log.Printf("loadFile read: %d", read)
    if err != nil {
        panic(err)
    }
}

// storeFile as Large Object in the database.
// The resulting object identifier is stored along with the file name in the files table.
// The amount of written bytes and an erorr is returned, if one occured.
func storeFile(ctx context.Context, conn *pgx.Conn, name string) (written int64, err error) {
    file, err := os.Open(name)
    if err != nil {
        return 0, err
    }
    defer file.Close()

    // LargeObjects can only operate on an active TX
    tx, err := conn.Begin(ctx)
    if err != nil {
        return 0, err
    }
    defer tx.Rollback(ctx)

    lobs := tx.LargeObjects()

    // Create a new Large Object.
    // We pass 0, so the DB can pick an available oid for us.
    oid, err := lobs.Create(ctx, 0)
    if err != nil {
        return 0, err
    }

    // record the oid and filename in the files table
    _, err = tx.Exec(ctx, "INSERT INTO files (id, name) VALUES ($1, $2)", oid, name)
    if err != nil {
        return 0, err
    }

    // Open the new Object for writing.
    obj, err := lobs.Open(ctx, oid, pgx.LargeObjectModeWrite)
    if err != nil {
        return 0, err
    }

    // Copy the file stream to the Large Object stream
    written, err = io.Copy(obj, file)
    if err != nil {
        return written, err
    }

    err = tx.Commit(ctx)
    return written, err
}

// loadFile loads the file identified by name as Large Object
// and writes the contents to a local file by the same name.
// The amount of bytes read or an error is returned.
func loadFile(ctx context.Context, conn *pgx.Conn, name string) (read int64, err error) {
    tx, err := conn.Begin(ctx)
    if err != nil {
        return 0, err
    }
    defer tx.Rollback(ctx)

    var oid uint32
    err = conn.QueryRow(ctx, "SELECT id FROM files WHERE name = $1", name).Scan(&oid)
    if err != nil {
        return 0, err
    }

    file, err := os.Create(name)
    if err != nil {
        return 0, err
    }

    lobs := tx.LargeObjects()
    obj, err := lobs.Open(ctx, oid, pgx.LargeObjectModeRead)
    if err != nil {
        return 0, err
    }

    return io.Copy(file, obj)
}


问:
LearnDash: How to authenticate api call?
I need to call learndash API from the wordpress
for example like this:

```<code>wp_remote_request ('https://mywpsite/wp-json/ldlms/v1/groups', $arg);
</code>```

LearnDash API is protected, so I'm getting 401 response:

```<code>{"code":"rest_forbidden","message":"Tut mir leid, aber Sie haben keine Berechtigung das zu tun.","data":{"status":401}}
</code>```

In the LearnDash API docs, there is no information how one can authenticate call
(Which auth header use, what kind of authentication, etc).

How can I authenticate the call to LearnDash ?

I'm not Wordpress expert, but may be there is a standard way to make such authenticated call to plugins' API?

P.S.: LearnDash is installed in same Wordpress installation I need to make a call from, I can't call functions directly, at least I didn't find required functions in LearnDash docs.

答:
you need to use a basic JWT auth, such as this one: https://cl.wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

Then, you need to include your authentication as a middleware, to retrieve the corresponding token and send it with your request to the Learndash endpoint.

In nextjs, I use this code:

```<code>export async function getCourseContent(id) {
  try {
    const token = await AuthJWT()
    const url = `https://yourserver.com/wp-json/ldlms/v2/sfwd-lessons?course=${id}`

    const courseSteps = await axios.get(url, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })

    return courseSteps.data
  } catch (error) {
    console.log(error, 'error')
  }
}

export async function AuthJWT() {
  try {

    const credentials = {
      username: process.env.EMAIL_ADMIN,
      password: process.env.PASSWORD_ADMIN
    }
    // console.log(credentials, 'credentials')
    const headers = {
      "Content-Type": "application/json"
    }

    const getToken = await axios.post('https://yourserver.com/wp-json/jwt-auth/v1/token',
      credentials,
      headers)
    // console.log(getToken.data.token, 'from authjwt')
    return getToken.data.token

  } catch (error) {
    return console.log('error', error)
  }

}
</code>```

Body:
I need to call learndash API from the wordpress
for example like this:

wp_remote_request ('https://mywpsite/wp-json/ldlms/v1/groups', $arg);

LearnDash API is protected, so I'm getting 401 response:

{"code":"rest_forbidden","message":"Tut mir leid, aber Sie haben keine Berechtigung das zu tun.","data":{"status":401}}

In the LearnDash API docs, there is no information how one can authenticate call
(Which auth header use, what kind of authentication, etc).

How can I authenticate the call to LearnDash ?

I'm not Wordpress expert, but may be there is a standard way to make such authenticated call to plugins' API?

P.S.: LearnDash is installed in same Wordpress installation I need to make a call from, I can't call functions directly, at least I didn't find required functions in LearnDash docs.

Body:
you need to use a basic JWT auth, such as this one: https://cl.wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

Then, you need to include your authentication as a middleware, to retrieve the corresponding token and send it with your request to the Learndash endpoint.

In nextjs, I use this code:

export async function getCourseContent(id) {
  try {
    const token = await AuthJWT()
    const url = `https://yourserver.com/wp-json/ldlms/v2/sfwd-lessons?course=${id}`

    const courseSteps = await axios.get(url, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })

    return courseSteps.data
  } catch (error) {
    console.log(error, 'error')
  }
}

export async function AuthJWT() {
  try {

    const credentials = {
      username: process.env.EMAIL_ADMIN,
      password: process.env.PASSWORD_ADMIN
    }
    // console.log(credentials, 'credentials')
    const headers = {
      "Content-Type": "application/json"
    }

    const getToken = await axios.post('https://yourserver.com/wp-json/jwt-auth/v1/token',
      credentials,
      headers)
    // console.log(getToken.data.token, 'from authjwt')
    return getToken.data.token

  } catch (error) {
    return console.log('error', error)
  }

}


问:
Connecting rows in Data Frame in python
I have Data Frame of 2 columns, I'm trying to combine each 3 rows into one row with "or" condition
between them.
I can't find smart and easy solution.

data frame:

dorks list  ofek rank
0                         allintext:"nike" acquisition          2
1                            allintext:"nike" acquired          2
2                                 allintext:"nike" buy          2
3                                allintext:"nike" sell          2
4                                allintext:"nike" sold          2
..                                                 ...        ...
481    insubject:"nike" divested source:prnewswire.com          4
482       insubject:"nike" divested source:reuters.com          4
483  insubject:"nike" divested source:seekingalpha.com          4
484     insubject:"nike" divested source:pitchbook.com          4
485     insubject:"nike" divested source:bloombarg.com          4
```

The desired result:

allintext:"nike" acquisition or allintext:"nike" acquired or allintext:"nike" buy
for each 3 rows.

答:
before I look for the smart way, I always use the dumb way. That is using iteration</p>
```<code>new_df = []
for index, row in df.iterrows():
    if something:
        dorks = dorks + row['dorks list']
    if index%3==0:
        new_df.append({'dorks list':dorks})
        dorks = ''
df_new = pd.DataFrame(new_df)
</code>```

Title: Connecting rows in Data Frame in python

Body:
I have Data Frame of 2 columns, I'm trying to combine each 3 rows into one row with "or" condition
between them.
I can't find smart and easy solution.

data frame:

dorks list  ofek rank
0                         allintext:"nike" acquisition          2
1                            allintext:"nike" acquired          2
2                                 allintext:"nike" buy          2
3                                allintext:"nike" sell          2
4                                allintext:"nike" sold          2
..                                                 ...        ...
481    insubject:"nike" divested source:prnewswire.com          4
482       insubject:"nike" divested source:reuters.com          4
483  insubject:"nike" divested source:seekingalpha.com          4
484     insubject:"nike" divested source:pitchbook.com          4
485     insubject:"nike" divested source:bloombarg.com          4

The desired result:

allintext:"nike" acquisition or allintext:"nike" acquired or allintext:"nike" buy
for each 3 rows.

Body:
before I look for the smart way, I always use the dumb way. That is using iteration

new_df = []
for index, row in df.iterrows():
    if something:
        dorks = dorks + row['dorks list']
    if index%3==0:
        new_df.append({'dorks list':dorks})
        dorks = ''
df_new = pd.DataFrame(new_df)


问:
How to make a next BuySignal only if the price goes 1% lower? I don't wanna buy almost at the same price over and over again. Pinescript
How to make a next BuySignal only if the price goes 1% lower? I don't wanna buy almost at the same price over and over again. Pinescript</p>
```<code>//@version=5

indicator(title="Main Channel", overlay=true)
src = close
len = input(100)
mult = input(2)
a = ta.linreg(src, len, 0)
a1 = ta.linreg(src,len,1)
b = (a-a1)

MD(a,b,shift)=>
    md = math.pow(a-b*shift - close[shift], 2)

sum2 = 0.0
for shift = 0 to len-1
    sum2:=sum2+MD(a,b,shift)

ranges = math.sqrt(sum2/(len+1))*mult
top = a+ranges
bot = a-ranges
plot(top, color=color.red, linewidth=2, transp=0, title = "Upper Line")
plot(bot, color=color.green, linewidth=2, transp=0, title = "Lower Line")

//CROSSES///////////////////////////////////////////////////////////

sell=ta.crossover(high,top)

buy=ta.crossunder(low,bot)

//SHAPES/////////////////////////////////////////////////////////////////////////
plotshape(top and sell, style=shape.triangledown, location=location.abovebar, color =color.red, transp=0, size = size.small, title="Upper 6 Signal")
plotshape(bot and buy, style=shape.triangleup, location=location.belowbar, color =color.lime, transp=0, size = size.small, title="Lower 6 Signal")
</code>```

答:
you can use price filter as the following</p>
```<code>//@version=5

indicator(title="Main Channel", overlay=true)
src = close
len = input(100)
mult = input(2)
a = ta.linreg(src, len, 0)
a1 = ta.linreg(src,len,1)
b = (a-a1)

MD(a,b,shift)=>
    md = math.pow(a-b*shift - close[shift], 2)

sum2 = 0.0
for shift = 0 to len-1
    sum2:=sum2+MD(a,b,shift)

ranges = math.sqrt(sum2/(len+1))*mult
top = a+ranges
bot = a-ranges
plot(top, color=color.red, linewidth=2, transp=0, title = "Upper Line")
plot(bot, color=color.green, linewidth=2, transp=0, title = "Lower Line")

//CROSSES///////////////////////////////////////////////////////////

sell=ta.crossover(high,top)

buy=ta.crossunder(low,bot)

/////// anonimm support ///
k2=0
k2:= buy  ? 1 : sell ? -1 : 0

price= 0.0
price:= k2== 1 ? close :  k2== -1 ? close : price[1]

Dif = math.abs(price-close)
PriceCheckPer = input.float(title="Price Check (%)",    minval=0.00, step=0.01, defval=1.00) * 0.01

k3=0
k3:= (k2 ==1 or k2 == -1 ) and math.abs(price-price[1]) < price[1] * PriceCheckPer ? 0 :
     k2 ==1 and math.abs(price-price[1]) >= price[1] * PriceCheckPer ? 1 : k2 ==-1 and math.abs(price-price[1]) >= price[1] * PriceCheckPer ? -1 :0

////////

//SHAPES/////////////////////////////////////////////////////////////////////////
plotshape(top and k3==-1, style=shape.triangledown, location=location.abovebar, color =color.red, transp=0, size = size.small, title="Upper 6 Signal")
plotshape(bot and k3==1, style=shape.triangleup, location=location.belowbar, color =color.lime, transp=0, size = size.small, title="Lower 6 Signal")
</code>```

Body:
How to make a next BuySignal only if the price goes 1% lower? I don't wanna buy almost at the same price over and over again. Pinescript

//@version=5

indicator(title="Main Channel", overlay=true)
src = close
len = input(100)
mult = input(2)
a = ta.linreg(src, len, 0)
a1 = ta.linreg(src,len,1)
b = (a-a1)

MD(a,b,shift)=>
    md = math.pow(a-b*shift - close[shift], 2)

sum2 = 0.0
for shift = 0 to len-1
    sum2:=sum2+MD(a,b,shift)

ranges = math.sqrt(sum2/(len+1))*mult
top = a+ranges
bot = a-ranges
plot(top, color=color.red, linewidth=2, transp=0, title = "Upper Line")
plot(bot, color=color.green, linewidth=2, transp=0, title = "Lower Line")

//CROSSES///////////////////////////////////////////////////////////

sell=ta.crossover(high,top)

buy=ta.crossunder(low,bot)

//SHAPES/////////////////////////////////////////////////////////////////////////
plotshape(top and sell, style=shape.triangledown, location=location.abovebar, color =color.red, transp=0, size = size.small, title="Upper 6 Signal")
plotshape(bot and buy, style=shape.triangleup, location=location.belowbar, color =color.lime, transp=0, size = size.small, title="Lower 6 Signal")

Body:
you can use price filter as the following

//@version=5

indicator(title="Main Channel", overlay=true)
src = close
len = input(100)
mult = input(2)
a = ta.linreg(src, len, 0)
a1 = ta.linreg(src,len,1)
b = (a-a1)

MD(a,b,shift)=>
    md = math.pow(a-b*shift - close[shift], 2)

sum2 = 0.0
for shift = 0 to len-1
    sum2:=sum2+MD(a,b,shift)

ranges = math.sqrt(sum2/(len+1))*mult
top = a+ranges
bot = a-ranges
plot(top, color=color.red, linewidth=2, transp=0, title = "Upper Line")
plot(bot, color=color.green, linewidth=2, transp=0, title = "Lower Line")

//CROSSES///////////////////////////////////////////////////////////

sell=ta.crossover(high,top)

buy=ta.crossunder(low,bot)

/////// anonimm support ///
k2=0
k2:= buy  ? 1 : sell ? -1 : 0

price= 0.0
price:= k2== 1 ? close :  k2== -1 ? close : price[1]

Dif = math.abs(price-close)
PriceCheckPer = input.float(title="Price Check (%)",    minval=0.00, step=0.01, defval=1.00) * 0.01

k3=0
k3:= (k2 ==1 or k2 == -1 ) and math.abs(price-price[1]) < price[1] * PriceCheckPer ? 0 :
     k2 ==1 and math.abs(price-price[1]) >= price[1] * PriceCheckPer ? 1 : k2 ==-1 and math.abs(price-price[1]) >= price[1] * PriceCheckPer ? -1 :0

////////

//SHAPES/////////////////////////////////////////////////////////////////////////
plotshape(top and k3==-1, style=shape.triangledown, location=location.abovebar, color =color.red, transp=0, size = size.small, title="Upper 6 Signal")
plotshape(bot and k3==1, style=shape.triangleup, location=location.belowbar, color =color.lime, transp=0, size = size.small, title="Lower 6 Signal")


问:
Unity Wont Skip Splash Screen On Build
I made game using unity and its working in the editor.

But when I build it and play it on phone, it stucks on the splash screen.

How can I fix this? What I'm doing wrong?

Thanks.

答:
Probably you have 2 scenes, one for main menu and other one for the game scene.

But you forgot to add the main menu scene to build, so your unready game scene gives error about null references so its not being able to skip the splash screen.

Title: Unity Wont Skip Splash Screen On Build


问:
how to match a word with a list of tubles
i am trying to find a word in a list of tuples. I tried the following code

```<code> keywords_adera = [('athletes', 0.4235), ('scrimmages', 0.3895),('athlete', 0.379),('sport', 0.3714),('soccer', 0.3699)]
b_adera='athletes'
if b_adera in keywords_adera2:
    print('macrious4')
</code>```

the code does not give any output. Any suggestions are appreciated.

答:
You have to iterate over a list keywords_adera
Then you check if your searched word is in current tuple</p>
```<code>for t in lst:
    if word in t:
        print('found')
</code>```

Body:
i am trying to find a word in a list of tuples. I tried the following code

 keywords_adera = [('athletes', 0.4235), ('scrimmages', 0.3895),('athlete', 0.379),('sport', 0.3714),('soccer', 0.3699)]
b_adera='athletes'
if b_adera in keywords_adera2:
    print('macrious4')

the code does not give any output. Any suggestions are appreciated.

Body:
You have to iterate over a list keywords_adera
Then you check if your searched word is in current tuple

for t in lst:
    if word in t:
        print('found')


问:
REMOTE_USER not always set in basic authentication when changing to running PHP as a CGI module
My host provider just moved me to PHP 7.4 (at my request) and in the process changed PHP from running as an Apache module (now 2.4.52) to as CGI -- good from what I know.  My website uses Basic Authentication, and my code relies HEAVILY on $_SERVER['REMOTE_USER'] to get the username in tons of places.

In some cases at least (so far from what I've seen), that variable is NOT set, but instead $_SERVER['REDIRECT_REMOTE_USER'] is.  In other places, there might be other $_SERVER vars that are set instead, tho I haven't seen them yet (I reverted to the old configuration for the time being, since this broke the site).   [BTW, a lot of this code is over 20 years old now.]

So my question: is there any way to force $_SERVER['REMOTE_USER'] to always be set with the username without having to modify all those places in my code?  Especially if there are some config settings that I could use?  I did see what looks to be a nice function to get the username in
PHP get username from Basic Authorization
but I'm hoping to find a way to avoid changing all that old code.  Or any other ideas?

答:
Only the REDIRECT_REMOTE_USER gets set to the username

You could perhaps auto-include a short PHP script that sets REMOTE_USER (from REDIRECT_REMOTE_USER) before your main script runs.

For example, set the auto_prepend_file in your .user.ini file in the root

```<code>auto_prepend_file=/path/to/fix-http-authentication.php
</code>```

And then in your fix-http-authentication.php script, something like:

```<code><?php
if (empty($_SERVER['REMOTE_USER']) && isset($_SERVER['REDIRECT_REMOTE_USER'])) {
    $_SERVER['REMOTE_USER'] = $_SERVER['REDIRECT_REMOTE_USER'];
}
</code>```

Body:
Only the REDIRECT_REMOTE_USER gets set to the username

You could perhaps auto-include a short PHP script that sets REMOTE_USER (from REDIRECT_REMOTE_USER) before your main script runs.

For example, set the auto_prepend_file in your .user.ini file in the root

auto_prepend_file=/path/to/fix-http-authentication.php

And then in your fix-http-authentication.php script, something like:

<?php
if (empty($_SERVER['REMOTE_USER']) && isset($_SERVER['REDIRECT_REMOTE_USER'])) {
    $_SERVER['REMOTE_USER'] = $_SERVER['REDIRECT_REMOTE_USER'];
}


问:
How to return form the web(iOS) back to the app?
I am using an online builder for my app(ApperyDotIo, JQM framework). My application works fine with one exception. I have an in-app link to my website. The link in the iOS app, the link takes me to the page but since the iPhone doesn't have a "back" button I can't go back to the app. Looks like you have to close the app and then reopen it to get back into the app.

I tried to set the link to not open in the same window and vice versa.

Any easy work around?

Links and back buttons in Android apps work fine.

Thank you

答:
You can consider using the inAppBrowser: https://docs.appery.io/docs/cordova-jquerymobile-inappbrowser

It will allow you to open the website in the child window of the application (with the "close" button) or in the native browser, without opening the website as application page.


问:
How to pass updated values to my component
I am trying to implement a prevent double click and disable button and change text of button during click event.

```<code>    let btnText = "Initial";
    let btnDisabled = false;

const handlClick = () => {
    if (btnDisabled) return;
    console.log("handlClick")
    btnDisabled = true;
    btnText = "Pending...";
    somFunction();
    btnText = "Initial";
    btnDisabled = false;
  }

<Button
      {btnDisabled}
      text={btnText}
        btnClass="btn btn-primary"
        on:click={handlClick}
      />
</code>```

The updated values don't seem to pass down to the component

here is my Button component

```<code><script>
  import { createEventDispatcher } from "svelte";

  const dispatch = createEventDispatcher();

  function click() {
    dispatch("click");
  }

  export let text = "Pending";
  export let shrink = false;
  export let btnClass = "";
  export let btnDisabled = false;
</script>

<button
  disabled={btnDisabled} on:click={click} class={btnClass}>{text}</button>

<style>
  .button {
    border: 2px solid var(--theme_modal_button_border);
    border-radius: 0.5rem;
    padding-left: 25px;
    padding-right: 25px;
    font-size: smaller;

    font-weight: 700;
    background: var(--theme_modal_button_bg);
    color: var(--theme_button_color);
    padding-top: 12px;
    padding-bottom: 12px;
  }

  .button:before,
  .button:after {
    content: "";
    display: block;
    box-sizing: border-box;
    position: absolute;
    background: var(--theme_modal_button_bg);
  }

  .button:hover,
  .button:active {
    background: var(--theme_modal_button_bg_light);
    border: 2px solid var(--theme_modal_button_border_light);
  }

  .button:hover:before,
  .button:hover:after {
    height: 2px;
    background: var(--theme_modal_button_bg_light);
  }

  .button:focus {
    border-color: none;
    box-shadow: none;
    text-decoration: none;
    outline: none;
  }

  .button:active {
    transform: scale(0.9);
  }

  .button:hover,
  .button:focus,
  .button:active {
    outline: none;
  }
</style>
</code>```

答:
The problem is probably how you do not handle asynchrony:

    btnDisabled = true;
    btnText = "Pending...";
    somFunction();
    btnText = "Initial";
    btnDisabled = false;
```
<p><code>someFunction()</code> is probably not blocking<sup>1</sup>, so the state will immediately be reset in the following two lines. <code>someFunction</code> should return a <code>Promise</code> and then be awaited here.</p>
<pre class="lang-js prettyprint-override"><code>  const handlClick = async () => { // mark async to await
    console.log("handlClick")
    btnDisabled = true;
    btnText = "Pending...";
    await somFunction();
    btnText = "Initial";
    btnDisabled = false;
  }
</code>```

REPL example

1Even for blocking functions, of which there are not many, the execution flow needs to be broken, so the UI is given a chance to update: REPL

Body:
I am trying to implement a prevent double click and disable button and change text of button during click event.

    let btnText = "Initial";
    let btnDisabled = false;

const handlClick = () => {
    if (btnDisabled) return;
    console.log("handlClick")
    btnDisabled = true;
    btnText = "Pending...";
    somFunction();
    btnText = "Initial";
    btnDisabled = false;
  }

<Button
      {btnDisabled}
      text={btnText}
        btnClass="btn btn-primary"
        on:click={handlClick}
      />

The updated values don't seem to pass down to the component

here is my Button component

<button
  disabled={btnDisabled} on:click={click} class={btnClass}>{text}</button>

Body:
The problem is probably how you do not handle asynchrony:

    btnDisabled = true;
    btnText = "Pending...";
    somFunction();
    btnText = "Initial";
    btnDisabled = false;

someFunction() is probably not blocking1, so the state will immediately be reset in the following two lines. someFunction should return a Promise and then be awaited here.

  const handlClick = async () => { // mark async to await
    console.log("handlClick")
    btnDisabled = true;
    btnText = "Pending...";
    await somFunction();
    btnText = "Initial";
    btnDisabled = false;
  }

REPL example

1Even for blocking functions, of which there are not many, the execution flow needs to be broken, so the UI is given a chance to update: REPL


问:
assessing whether ec2 t3.nano instance can handle workload
I currently have an ec2 t2.micro instance and rds db.t3.micro instance on AWS, and in order to reduce costs I wish to transfer both the application (which is currently on the t2.micro ec2 instance) and database onto t3.nano or t3.micro instances. Thus my question is how do I analyse my current infrastructure in order to determine whether or not t3.nano/micro instances can handle the workload that my previous instances are handling? Do I look at the CPU percentage or something else? The CPU for my RDS is showing 4.75% at the moment - can I take this to mean my rds is using very little and thus could probably be shifted to something smaller?</p>

答:
Note that T2 and T3 are Burstable performance instances meaning that they are very powerful if used in bursts, but provide lower performance when usage is sustained.

So, if your system becomes popular and has a continual load, the app/database might suddenly drop in performance when the burst credits run out. This won't be obvious with normal monitoring, which would show everything performing very when there are only occasional bursts of traffic.

Reducing the instance size will also reduce memory, which could cause problems with your app/database.

If you just have a simple app & database requirement, you could consider using Amazon Lightsail, which can offer considerable savings since it includes a free bandwidth allowance.


问:
Why is my for-loop over a file not starting after using readlines()?
I'm trying to read info from a file and print it's information. Using a test program, I could get it working like this:

file = open("cooltextfile.txt", "r")
for line in file:
    if "BobRoss" in line:
        print(line)
```
<p>Using above method, it prints all lines containing "Bob Ross".</p>
<p>However, when I use it in my main program like this, it's not even printing the line if I tell it to print the whole line:</p>
<pre class="lang-py prettyprint-override"><code>number = 0
index = 0

textFile = open("cooltextfile.txt", "r")
lineInfo = textFile.readlines()

for line in textFile:
    index += 1

    print(line) # - An attempt to print the entire line

    if "BobRoss" in line:
        number += 1

        print(str(number) + ". " + line)
        print("Order: " + lineInfo[index])

textFile.close()
</code>```

Upon further inspection it would seem that the for-loop never starts. Any reason as to what could be causing the loop to not start?

答:
Think of reading a file like playing a tape.
You called textFile.readlines(), now you've reached the end of the tape.
Now you try to play it again (in a loop), but you're still at the end of the tape.
You need to rewind the tape before: textFile.seek(0)

Body:
I'm trying to read info from a file and print it's information. Using a test program, I could get it working like this:

file = open("cooltextfile.txt", "r")
for line in file:
    if "BobRoss" in line:
        print(line)

Using above method, it prints all lines containing "Bob Ross".

However, when I use it in my main program like this, it's not even printing the line if I tell it to print the whole line:

number = 0
index = 0

textFile = open("cooltextfile.txt", "r")
lineInfo = textFile.readlines()

for line in textFile:
    index += 1

    print(line) # - An attempt to print the entire line

    if "BobRoss" in line:
        number += 1

        print(str(number) + ". " + line)
        print("Order: " + lineInfo[index])

textFile.close()

Upon further inspection it would seem that the for-loop never starts. Any reason as to what could be causing the loop to not start?


问:
Check to see if elements in a list have an SRC from a variable and then run code - jQuery / Javascript
So I wish to check a variable called SRC against the source of images in a list from my HTML and if it returns true then run a certain function.

It seems that it is not currently running properly, please see the link for a live example.

http://jsbin.com/exigop/4/edit

答:
You should check the length property whenever you check for any element which is missing in your code.

```<code>if ($('ul li img[src=' + src + ']').length > 0) {
  //code here
}
</code>```

Also you had few other issues in the code like using src as attribute selector which will not work because it cantains / and it is not escaped.

I have fixed those issues and also improvised the code. Take a look

Working demo

ContentLicense: CC BY-SA 3.0

Body:
You should check the length property whenever you check for any element which is missing in your code.

if ($('ul li img[src=' + src + ']').length > 0) {
  //code here
}

Also you had few other issues in the code like using src as attribute selector which will not work because it cantains / and it is not escaped.

I have fixed those issues and also improvised the code. Take a look

Working demo


答:
The tuple is in list you need to match entier tuple with
Value for if statement to be true

```<code> keywords_adera = [('athletes', 0.4235), ('scrimmages', 0.3895),
 ('athlete', 0.379),('sport', 0.3714),('soccer', 0.3699)]
  b_adera=('athletes',0.4235)
  if b_adera in keywords_adera:
      print('macrious4')
</code>```

Else you would need to iterate over list or specify which index in list

Title: how to match a word with a list of tubles

Body:
The tuple is in list you need to match entier tuple with
Value for if statement to be true

 keywords_adera = [('athletes', 0.4235), ('scrimmages', 0.3895),
 ('athlete', 0.379),('sport', 0.3714),('soccer', 0.3699)]
  b_adera=('athletes',0.4235)
  if b_adera in keywords_adera:
      print('macrious4')

Else you would need to iterate over list or specify which index in list


问:
Html Css how to make shadow on overlay
i want to make a shadow on overlay of div like the shadow in the photo

my code:

.nav-open {
    height: 350px;
    width: 100%;
    background-color: #ffffff;
    position: absolute;
    z-index: 1;
    border: 1px solid #aaaaaa;
    border-left: 0;
    border-right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav-open"></div></code>```

output:

答:
Use filter: brightness(50%). Everything in the div will be darkened.

Example with filter: brightness(50%):

Example with filter: brightness(150%):

Title: Html Css how to make shadow on overlay

Body:
i want to make a shadow on overlay of div like the shadow in the photo

my code:

.nav-open {
    height: 350px;
    width: 100%;
    background-color: #ffffff;
    position: absolute;
    z-index: 1;
    border: 1px solid #aaaaaa;
    border-left: 0;
    border-right: 0;
}

output:


问:
binascii.Error: Incorrect padding in python django
I am trying to save the base64 encoded image in the django rest framework. First of all, we make a code to insert the base64 encoded image into the imagefield and test it, and the following error appears.

binascii.Error: Incorrect padding

What I don't understand is that I've used the same code before and there was no such error. Can you help me? Here is my code.

serializers.py

```<code>from rest_framework import serializers
from .models import post, comment

class Base64ImageField (serializers.ImageField) :

    def to_internal_value (self, data) :
        from django.core.files.base import ContentFile
        import base64
        import six
        import uuid

        if isinstance(data, six.string_types):
            if 'data:' in data and ';base64,' in data :
                header, data = data.split(';base64,')

            try :
                decoded_file = base64.b64decode(data)
            except TypeError :
                self.fail('invalid_image')

            file_name = str(uuid.uuid4())[:12]
            file_extension = self.get_file_extension(file_name, decoded_file)
            complete_file_name = "%s.%s" % (file_name, file_extension, )
            data = ContentFile(decoded_file, name=complete_file_name)

        return super(Base64ImageField, self).to_internal_value(data)

    def get_file_extension (self, file_name, decoded_file) :
        import imghdr

        extension = imghdr.what(file_name, decoded_file)
        extension = "jpg" if extension == "jpeg" else extension

        return extension

class commentSerializer (serializers.ModelSerializer) :

    class Meta :
        model = comment
        fields = '__all__'

class postSerializer (serializers.ModelSerializer) :
    author = serializers.CharField(source='author.username', read_only=True)
    image1 = Base64ImageField(use_url=True)
    image2 = Base64ImageField(use_url=True)
    image3 = Base64ImageField(use_url=True)
    image4 = Base64ImageField(use_url=True)
    image5 = Base64ImageField(use_url=True)
    comment = commentSerializer(many=True, read_only=True)

    class Meta:
        model = post
        fields = ['pk', 'author', 'title', 'text', 'image1', 'image2', 'image3', 'image4', 'image5', 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'comment']
</code>```

答:
Run following command in shell

```<code>from django.contrib.sessions.models import Session
Session.objects.all().delete()
</code>```

More information at https://code.djangoproject.com/ticket/31592

Body:
I am trying to save the base64 encoded image in the django rest framework. First of all, we make a code to insert the base64 encoded image into the imagefield and test it, and the following error appears.

binascii.Error: Incorrect padding

What I don't understand is that I've used the same code before and there was no such error. Can you help me? Here is my code.

serializers.py

from rest_framework import serializers
from .models import post, comment

class Base64ImageField (serializers.ImageField) :

    def to_internal_value (self, data) :
        from django.core.files.base import ContentFile
        import base64
        import six
        import uuid

        if isinstance(data, six.string_types):
            if 'data:' in data and ';base64,' in data :
                header, data = data.split(';base64,')

            try :
                decoded_file = base64.b64decode(data)
            except TypeError :
                self.fail('invalid_image')

            file_name = str(uuid.uuid4())[:12]
            file_extension = self.get_file_extension(file_name, decoded_file)
            complete_file_name = "%s.%s" % (file_name, file_extension, )
            data = ContentFile(decoded_file, name=complete_file_name)

        return super(Base64ImageField, self).to_internal_value(data)

    def get_file_extension (self, file_name, decoded_file) :
        import imghdr

        extension = imghdr.what(file_name, decoded_file)
        extension = "jpg" if extension == "jpeg" else extension

        return extension

class commentSerializer (serializers.ModelSerializer) :

    class Meta :
        model = comment
        fields = '__all__'

class postSerializer (serializers.ModelSerializer) :
    author = serializers.CharField(source='author.username', read_only=True)
    image1 = Base64ImageField(use_url=True)
    image2 = Base64ImageField(use_url=True)
    image3 = Base64ImageField(use_url=True)
    image4 = Base64ImageField(use_url=True)
    image5 = Base64ImageField(use_url=True)
    comment = commentSerializer(many=True, read_only=True)

    class Meta:
        model = post
        fields = ['pk', 'author', 'title', 'text', 'image1', 'image2', 'image3', 'image4', 'image5', 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'comment']

Body:
Run following command in shell

from django.contrib.sessions.models import Session
Session.objects.all().delete()

More information at https://code.djangoproject.com/ticket/31592


问:
Scroll view does not scroll - Android Studio
I can't make a ScrollView properly scrolling.
I can scroll through the page but the scrollView itself not showing and it always cut off the content on the bottom.
The buttons portion is being cut off in portrait orientation, and not scrolling at all in the  landscape orientation.

Here is my XML code:

```<code><?xml version="1.0" encoding="utf-8"?>
 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
tools:context=".signUp.SignUpFragment">

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".signUp.SignUpFragment">

        <androidx.appcompat.widget.LinearLayoutCompat
            android:id="@+id/linearLayoutCompat"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_margin="20dp"
            android:layout_marginTop="10dp"
            android:orientation="vertical"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <ImageView
                android:id="@+id/signup_logo"
                android:layout_width="match_parent"
                android:layout_height="140dp"
                android:layout_marginTop="20dp"
                android:src="@drawable/logo"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/name"
                android:paddingTop="16dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/signup_name_show"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:maxLines="1" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/nick_name"
                android:paddingTop="16dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/signup_nickname_show"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:maxLines="1" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/email"
                android:paddingTop="16dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/signup_email_show"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:maxLines="1" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/password"
                android:paddingTop="16dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/signup_password_show"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textPassword"
                    android:maxLines="1" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/verifypassword"
                android:paddingTop="16dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/signup_verifypass_show"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textPassword"
                    android:maxLines="1" />

            </com.google.android.material.textfield.TextInputLayout>

        </androidx.appcompat.widget.LinearLayoutCompat>

        <TextView
            android:id="@+id/signup_profilepic_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="25dp"
            android:layout_marginTop="12dp"
            android:text="Profile picture"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/linearLayoutCompat" />

        <Button
            android:id="@+id/signup_cancel_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:backgroundTint="#7b9abe"
            android:text="Cancel"
            android:textSize="20sp"
            app:layout_constraintEnd_toStartOf="@+id/signup_save_btn"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/signup_camera_btn" />

        <Button
            android:id="@+id/signup_save_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="#7b9abe"
            android:text="Sign Up"
            android:textSize="20sp"
            app:layout_constraintBaseline_toBaselineOf="@+id/signup_cancel_btn"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toEndOf="@+id/signup_cancel_btn" />

        <ImageButton
            android:id="@+id/signup_camera_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="12dp"
            android:layout_marginTop="10dp"
            android:src="@android:drawable/ic_menu_camera"
            app:layout_constraintStart_toEndOf="@+id/signup_profilepic_tv"
            app:layout_constraintTop_toBottomOf="@+id/linearLayoutCompat" />

        <ImageButton
            android:id="@+id/signup_gallery_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:layout_marginTop="10dp"
            android:src="@android:drawable/ic_menu_gallery"
            app:layout_constraintStart_toEndOf="@+id/signup_camera_btn"
            app:layout_constraintTop_toBottomOf="@+id/linearLayoutCompat" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    </ScrollView>
</code>```

My device:

Thank you!!!

答:
end of code write
</scrollView> and remove ```fillViewport = “true”```</p>

Body:
I can't make a ScrollView properly scrolling.
I can scroll through the page but the scrollView itself not showing and it always cut off the content on the bottom.
The buttons portion is being cut off in portrait orientation, and not scrolling at all in the  landscape orientation.

Here is my XML code:

<?xml version="1.0" encoding="utf-8"?>
 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
tools:context=".signUp.SignUpFragment">

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".signUp.SignUpFragment">

        <androidx.appcompat.widget.LinearLayoutCompat
            android:id="@+id/linearLayoutCompat"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_margin="20dp"
            android:layout_marginTop="10dp"
            android:orientation="vertical"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <ImageView
                android:id="@+id/signup_logo"
                android:layout_width="match_parent"
                android:layout_height="140dp"
                android:layout_marginTop="20dp"
                android:src="@drawable/logo"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/name"
                android:paddingTop="16dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/signup_name_show"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:maxLines="1" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/nick_name"
                android:paddingTop="16dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/signup_nickname_show"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:maxLines="1" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/email"
                android:paddingTop="16dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/signup_email_show"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:maxLines="1" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/password"
                android:paddingTop="16dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/signup_password_show"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textPassword"
                    android:maxLines="1" />
            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:hint="@string/verifypassword"
                android:paddingTop="16dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/signup_verifypass_show"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textPassword"
                    android:maxLines="1" />

            </com.google.android.material.textfield.TextInputLayout>

        </androidx.appcompat.widget.LinearLayoutCompat>

        <TextView
            android:id="@+id/signup_profilepic_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="25dp"
            android:layout_marginTop="12dp"
            android:text="Profile picture"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/linearLayoutCompat" />

        <Button
            android:id="@+id/signup_cancel_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:backgroundTint="#7b9abe"
            android:text="Cancel"
            android:textSize="20sp"
            app:layout_constraintEnd_toStartOf="@+id/signup_save_btn"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/signup_camera_btn" />

        <Button
            android:id="@+id/signup_save_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="#7b9abe"
            android:text="Sign Up"
            android:textSize="20sp"
            app:layout_constraintBaseline_toBaselineOf="@+id/signup_cancel_btn"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toEndOf="@+id/signup_cancel_btn" />

        <ImageButton
            android:id="@+id/signup_camera_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="12dp"
            android:layout_marginTop="10dp"
            android:src="@android:drawable/ic_menu_camera"
            app:layout_constraintStart_toEndOf="@+id/signup_profilepic_tv"
            app:layout_constraintTop_toBottomOf="@+id/linearLayoutCompat" />

        <ImageButton
            android:id="@+id/signup_gallery_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:layout_marginTop="10dp"
            android:src="@android:drawable/ic_menu_gallery"
            app:layout_constraintStart_toEndOf="@+id/signup_camera_btn"
            app:layout_constraintTop_toBottomOf="@+id/linearLayoutCompat" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    </ScrollView>

My device:

Thank you!!!

Body:
end of code write
</scrollView> and remove
fillViewport = “true”


问:
Failed flask heroku deployment
I am trying to host a Flask web application on Heroku, while I use these steps to get my web application hosted:

{git init
git add .
git commit -m "Initial commmit"

heroku create bukkit-list
git remote -v
git push heroku master}
```
<p>After I do all of this, I get absolutely no error in my terminal, but the flask application is still not working. The logs for Heroku are given below.</p>
<blockquote>
<p>2022-02-12T09:27:20.056100+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=bukkit-list.herokuapp.com request_id=cd77d2eb-110d-4943-bae1-18601c9f90b7 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https</p>
<p>2022-02-12T09:27:20.601039+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=bukkit-list.herokuapp.com request_id=5fe216d1-0f09-4777-8c6f-bee6b4b53f74 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https</p>
<p>2022-02-12T09:27:29.589547+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=bukkit-list.herokuapp.com request_id=169389de-b2ed-43a3-ae8e-1203558e9c86 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https</p>
<p>2022-02-12T09:27:47.095193+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=bukkit-list.herokuapp.com request_id=316fd6b2-9ffc-40ea-bee5-f0b3630a2948 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https</p>
<p>2022-02-12T09:27:48.317531+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=bukkit-list.herokuapp.com request_id=6416476f-2e45-4dd2-a2f9-85fdcccb5883 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https</p>
<p>2022-02-12T09:28:17.730376+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=bukkit-list.herokuapp.com request_id=3a7058d4-9796-4a62-8ec5-4be44728f638 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https</p>
<p>2022-02-12T09:28:18.395460+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=bukkit-list.herokuapp.com request_id=57d66c4d-8fe9-4801-8d9d-a65d9986b808 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https</p>
</blockquote>
<h3>My <em>app.py</em> code</h3>
```from flask import Flask, redirect, render_template, request
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tasks.db'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Task(db.Model):
   sno = db.Column(db.Integer, primary_key = True)
   title = db.Column(db.String(200), nullable=False)
   desc = db.Column(db.String(500), nullable=False)

   def __repr__(self) -> str:
       return f'{self.title} - {self.sno}'

# Routes
@app.route('/')
def home():
    return render_template('home.html')

# Task list area ==========================================
@app.route('/taskList')
def taskList():
    taskList = Task.query.all()
    return render_template('taskList.html', taskList=taskList)

@app.route('/delete/<int:sno>')
def delete(sno):
    task = Task.query.filter_by(sno=sno).first()
    db.session.delete(task)
    db.session.commit()
    return redirect('/taskList')

@app.route('/addTask')
def addTask():
    return redirect('/TaskEditor_Add')

# Add task area =============================================
@app.route('/TaskEditor_Add', methods=["GET", "POST"])
def TaskEditor_Add():
    state = "Add - Task"
    if request.method == "POST":
        title = request.form['title']
        desc = request.form['desc']
        if (title.isspace() or desc.isspace()):
            state = "Invalid Task"
        else:
            task = Task(title=title, desc=desc)
            db.session.add(task)
            db.session.commit()
            state = "Task added"
            return redirect("/taskList")

    return render_template('addTask.html', state=state)

# Update an existing todo area ================================
@app.route('/TaskEditor_Edit/<int:sno>', methods=["POST", "GET"])
def TaskEditor_Edit(sno):
    task = Task.query.filter_by(sno=sno).first()
    state="Edit Task"
    if request.method == "POST":
        title = request.form['title']
        desc = request.form['desc']
        if (title.isspace() or desc.isspace()):
            state = "Invalid Task"
        else:
           task.title = title
           task.desc = desc
           db.session.add(task)
           db.session.commit()
           return redirect('/taskList')

    return render_template('editTask.html', task=task, state=state)

if __name__ == "__main__":
    app.run(debug=True)    ```
</code>```

The procfile only has this single line of code which is down below:

web:gunicorn app:app
```

答:
I also deployed a website in Heroku with Flask and an SQL database a few days ago, and I got a similar error. First of all, in the Procfile add a space between the web: and the gunicorn like so:

web: gunicorn hello:app - this is how they write it in their documentation.

Second, make sure your requirement.txt file is updated and display the gunicorn in it.

Try changing the database to PostgreSQL. You can configure one in the resource tab:

And in your code you will need to change these lines:

```<code>import os
uri = os.getenv("DATABASE_URL")
if uri and uri.startswith("postgres://"):
    uri = uri.replace("postgres://", "postgresql://", 1)

app.config['SQLALCHEMY_DATABASE_URI'] = uri
</code>```

You can read about why you need to add those here.

Title: Failed flask heroku deployment

Body:
I am trying to host a Flask web application on Heroku, while I use these steps to get my web application hosted:

{git init
git add .
git commit -m "Initial commmit"

heroku create bukkit-list
git remote -v
git push heroku master}

After I do all of this, I get absolutely no error in my terminal, but the flask application is still not working. The logs for Heroku are given below.

2022-02-12T09:27:20.056100+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=bukkit-list.herokuapp.com request_id=cd77d2eb-110d-4943-bae1-18601c9f90b7 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https

2022-02-12T09:27:20.601039+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=bukkit-list.herokuapp.com request_id=5fe216d1-0f09-4777-8c6f-bee6b4b53f74 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https

2022-02-12T09:27:29.589547+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=bukkit-list.herokuapp.com request_id=169389de-b2ed-43a3-ae8e-1203558e9c86 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https

2022-02-12T09:27:47.095193+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=bukkit-list.herokuapp.com request_id=316fd6b2-9ffc-40ea-bee5-f0b3630a2948 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https

2022-02-12T09:27:48.317531+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=bukkit-list.herokuapp.com request_id=6416476f-2e45-4dd2-a2f9-85fdcccb5883 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https

2022-02-12T09:28:17.730376+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=bukkit-list.herokuapp.com request_id=3a7058d4-9796-4a62-8ec5-4be44728f638 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https

2022-02-12T09:28:18.395460+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=bukkit-list.herokuapp.com request_id=57d66c4d-8fe9-4801-8d9d-a65d9986b808 fwd="103.79.250.41" dyno= connect= service= status=503 bytes= protocol=https

My app.py code

from flask import Flask, redirect, render_template, request
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tasks.db'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Task(db.Model):
   sno = db.Column(db.Integer, primary_key = True)
   title = db.Column(db.String(200), nullable=False)
   desc = db.Column(db.String(500), nullable=False)

   def __repr__(self) -> str:
       return f'{self.title} - {self.sno}'

# Routes
@app.route('/')
def home():
    return render_template('home.html')

# Task list area ==========================================
@app.route('/taskList')
def taskList():
    taskList = Task.query.all()
    return render_template('taskList.html', taskList=taskList)

@app.route('/delete/<int:sno>')
def delete(sno):
    task = Task.query.filter_by(sno=sno).first()
    db.session.delete(task)
    db.session.commit()
    return redirect('/taskList')

@app.route('/addTask')
def addTask():
    return redirect('/TaskEditor_Add')

# Add task area =============================================
@app.route('/TaskEditor_Add', methods=["GET", "POST"])
def TaskEditor_Add():
    state = "Add - Task"
    if request.method == "POST":
        title = request.form['title']
        desc = request.form['desc']
        if (title.isspace() or desc.isspace()):
            state = "Invalid Task"
        else:
            task = Task(title=title, desc=desc)
            db.session.add(task)
            db.session.commit()
            state = "Task added"
            return redirect("/taskList")

    return render_template('addTask.html', state=state)

# Update an existing todo area ================================
@app.route('/TaskEditor_Edit/<int:sno>', methods=["POST", "GET"])
def TaskEditor_Edit(sno):
    task = Task.query.filter_by(sno=sno).first()
    state="Edit Task"
    if request.method == "POST":
        title = request.form['title']
        desc = request.form['desc']
        if (title.isspace() or desc.isspace()):
            state = "Invalid Task"
        else:
           task.title = title
           task.desc = desc
           db.session.add(task)
           db.session.commit()
           return redirect('/taskList')

    return render_template('editTask.html', task=task, state=state)

if __name__ == "__main__":
    app.run(debug=True)    ```

The procfile only has this single line of code which is down below:

web:gunicorn app:app

Body:
I also deployed a website in Heroku with Flask and an SQL database a few days ago, and I got a similar error. First of all, in the Procfile add a space between the web: and the gunicorn like so:

web: gunicorn hello:app - this is how they write it in their documentation.

Second, make sure your requirement.txt file is updated and display the gunicorn in it.

Try changing the database to PostgreSQL. You can configure one in the resource tab:

And in your code you will need to change these lines:

import os
uri = os.getenv("DATABASE_URL")
if uri and uri.startswith("postgres://"):
    uri = uri.replace("postgres://", "postgresql://", 1)

app.config['SQLALCHEMY_DATABASE_URI'] = uri

You can read about why you need to add those here.


问:
DiscordAPIError: Cannot send empty message
Im trying to make a discord bot for my fivem server. but when i try to send a message embed i get an error. Full error:
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (D:\DiscordBots\MoonRP\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (D:\DiscordBots\MoonRP\node_modules\discord.js\src\rest\RequestHandler.js:39:14) {
method: 'post',
path: '/channels/941736918104821820/messages',
code: 50006,
httpStatus: 400
}

The new full error:
DiscordAPIError: Invalid Form Body
embed.description: This field is required
embeds[0].description: This field is required
at RequestHandler.execute (D:\DiscordBots\MoonRP\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (D:\DiscordBots\MoonRP\node_modules\discord.js\src\rest\RequestHandler.js:39:14) {
method: 'post',
path: '/channels/941736918104821820/messages',
code: 50035,
httpStatus: 400
}

The index.js code is here:

```<code>const {MessageEmbed} = require('discord.js')
const fs = require('fs')
const fivereborn = require('fivereborn-query');
const bot = new Client({
    disableEveryone: true
})
const config = require('./config.json')
const prefix = config.prefix
const token = config.token
bot.commands = new Collection();
bot.aliases = new Collection();
bot.categories = fs.readdirSync("./commands/");
["command"].forEach(handler => {
    require(`./handlers/${handler}`)(bot);
});
bot.on('ready', () => {
    console.log(`${bot.user.username} ✅`)
})
bot.on('message', async message =>{
    if(message.author.bot) return;
    if(!message.content.startsWith(prefix)) return;
    if(!message.guild) return;
    if(!message.member) message.member = await message.guild.fetchMember(message);
    const args = message.content.slice(prefix.length).trim().split(/ +/g);
    const cmd = args.shift().toLowerCase();
    if(cmd.length == 0 ) return;
    let command = bot.commands.get(cmd)
    if(!command) command = bot.commands.get(bot.aliases.get(cmd));
    if(command) command.run(bot, message, args)
})

const ip = config.serverIp
const port = config.serverPort
const sName = config.serverName
var MoonRPEmbed = new MessageEmbed()

function activity(){ // Defines the function
    setTimeout(() => { // Starts a loop
        fivereborn.query(ip, port, (err, data) => { // Starts a function that allowes us to retrive data from our fivem server
            if (err) { // Checks for errors
                return console.log(err); // If a error is true then this will log that error and then stop it from going by
            } else { // If a error is not true then
              if(bot.user!= null)
                bot.user.setActivity(`${data.clients} / ${data.maxclients} i byen ${sName}`, { type: "WATCHING" }); // Serts the Status
            }
        });
        activity(); // Runs the function we defined at line 45
    }, 1000); // Waits 1 second
}
activity(); // Runs the function again

function status(){
    setTimeout(() => {
        fivereborn.query(ip, port, (err, data) => {
            if (!err) {
                console.log(data)
              bot.channels.fetch('941736918104821820').then(ch => {
                if (ch.isText())
                {
                  ch.bulkDelete(10);
                  }
              })
                .catch(console.error);

                 if (err) { // Checks for errors
                return console.log(err); // If a error is true then this will log that error and then stop it from going by
            } else { // If a error is not true then
              if(bot.user!= null)
                bot.user.setActivity(`${data.clients} / ${data.maxclients} i byen ${sName}`, { type: "WATCHING" }); // Serts the Status

              MoonRPEmbed = {
                color: 'ff0000',
                description: 'MoonRP Status',
                author: {
                name: 'MoonRP Status',
                },
                 fields: [
                {
                  name: 'Server Åben',
                  value: "```   ✅ ```",
                  inline: true,
                },
                {
                  name: 'Spillere inde',
                  value: "```"+data.clients+ " / "+ data.maxclients+"```",
                  inline: true,
                },
                {
                  name: 'Server IP',
                  value: "```cfx.re/join/ybrgv5```",
                  inline: false,
                }
              ],
            timestamp: Math.floor(new Date().getTime() / 1000),//new Date(),
              footer: {
                text: 'MoonRP Bot',
                icon_url: 'https://cdn.discordapp.com/attachments/703252325686575124/934779887112302652/Moonrp_logo-min.png'
              },
            };
            }

              bot.channels.fetch('941736918104821820')
                .then(channel => {
                  console.log(MoonRPEmbed);
                  channel.send({embed:[MoonRPEmbed]})
                    .then(console.log)
                    .catch(console.error);
                })
                .catch(console.error)
                //channel.send({ embeds: [MoonRPEmbed] });
            } else {
                return console.log(err)
            }
        });
        status();
    }, 60000); // Waits 10 mins
}
status()

bot.login(token)

</code>```

The discord.js version is: 12.5.3

答:
The problem is content: ''.
If you want to only send an embed, you need to do it like this:

.then(channel => { console.log(MoonRPEmbed); channel.send({embeds:[MoonRPEmbed]})
```

Don't include a content option at all.
By including it, but not actually putting anything inside, it tries to send a message with empty content and an embed, instead of a message with no content and an embed.

Body:
Im trying to make a discord bot for my fivem server. but when i try to send a message embed i get an error. Full error:
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (D:\DiscordBots\MoonRP\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (D:\DiscordBots\MoonRP\node_modules\discord.js\src\rest\RequestHandler.js:39:14) {
method: 'post',
path: '/channels/941736918104821820/messages',
code: 50006,
httpStatus: 400
}

The new full error:
DiscordAPIError: Invalid Form Body
embed.description: This field is required
embeds[0].description: This field is required
at RequestHandler.execute (D:\DiscordBots\MoonRP\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (D:\DiscordBots\MoonRP\node_modules\discord.js\src\rest\RequestHandler.js:39:14) {
method: 'post',
path: '/channels/941736918104821820/messages',
code: 50035,
httpStatus: 400
}

The index.js code is here:

const {MessageEmbed} = require('discord.js')
const fs = require('fs')
const fivereborn = require('fivereborn-query');
const bot = new Client({
    disableEveryone: true
})
const config = require('./config.json')
const prefix = config.prefix
const token = config.token
bot.commands = new Collection();
bot.aliases = new Collection();
bot.categories = fs.readdirSync("./commands/");
["command"].forEach(handler => {
    require(`./handlers/${handler}`)(bot);
});
bot.on('ready', () => {
    console.log(`${bot.user.username} ✅`)
})
bot.on('message', async message =>{
    if(message.author.bot) return;
    if(!message.content.startsWith(prefix)) return;
    if(!message.guild) return;
    if(!message.member) message.member = await message.guild.fetchMember(message);
    const args = message.content.slice(prefix.length).trim().split(/ +/g);
    const cmd = args.shift().toLowerCase();
    if(cmd.length == 0 ) return;
    let command = bot.commands.get(cmd)
    if(!command) command = bot.commands.get(bot.aliases.get(cmd));
    if(command) command.run(bot, message, args)
})

const ip = config.serverIp
const port = config.serverPort
const sName = config.serverName
var MoonRPEmbed = new MessageEmbed()

function activity(){ // Defines the function
    setTimeout(() => { // Starts a loop
        fivereborn.query(ip, port, (err, data) => { // Starts a function that allowes us to retrive data from our fivem server
            if (err) { // Checks for errors
                return console.log(err); // If a error is true then this will log that error and then stop it from going by
            } else { // If a error is not true then
              if(bot.user!= null)
                bot.user.setActivity(`${data.clients} / ${data.maxclients} i byen ${sName}`, { type: "WATCHING" }); // Serts the Status
            }
        });
        activity(); // Runs the function we defined at line 45
    }, 1000); // Waits 1 second
}
activity(); // Runs the function again

function status(){
    setTimeout(() => {
        fivereborn.query(ip, port, (err, data) => {
            if (!err) {
                console.log(data)
              bot.channels.fetch('941736918104821820').then(ch => {
                if (ch.isText())
                {
                  ch.bulkDelete(10);
                  }
              })
                .catch(console.error);

                 if (err) { // Checks for errors
                return console.log(err); // If a error is true then this will log that error and then stop it from going by
            } else { // If a error is not true then
              if(bot.user!= null)
                bot.user.setActivity(`${data.clients} / ${data.maxclients} i byen ${sName}`, { type: "WATCHING" }); // Serts the Status

              MoonRPEmbed = {
                color: 'ff0000',
                description: 'MoonRP Status',
                author: {
                name: 'MoonRP Status',
                },
                 fields: [
                {
                  name: 'Server Åben',
                  value: "```   ✅ ```",
                  inline: true,
                },
                {
                  name: 'Spillere inde',
                  value: "```"+data.clients+ " / "+ data.maxclients+"```",
                  inline: true,
                },
                {
                  name: 'Server IP',
                  value: "```cfx.re/join/ybrgv5```",
                  inline: false,
                }
              ],
            timestamp: Math.floor(new Date().getTime() / 1000),//new Date(),
              footer: {
                text: 'MoonRP Bot',
                icon_url: 'https://cdn.discordapp.com/attachments/703252325686575124/934779887112302652/Moonrp_logo-min.png'
              },
            };
            }

              bot.channels.fetch('941736918104821820')
                .then(channel => {
                  console.log(MoonRPEmbed);
                  channel.send({embed:[MoonRPEmbed]})
                    .then(console.log)
                    .catch(console.error);
                })
                .catch(console.error)
                //channel.send({ embeds: [MoonRPEmbed] });
            } else {
                return console.log(err)
            }
        });
        status();
    }, 60000); // Waits 10 mins
}
status()

bot.login(token)

The discord.js version is: 12.5.3

Body:
The problem is content: ''.
If you want to only send an embed, you need to do it like this:

.then(channel => { console.log(MoonRPEmbed); channel.send({embeds:[MoonRPEmbed]})

Don't include a content option at all.
By including it, but not actually putting anything inside, it tries to send a message with empty content and an embed, instead of a message with no content and an embed.


问:
Restricting personal accounts user login
I have to build a portal for my institute which will act as a job portal for the institute. Companies should be able to post their job/intern openings on the portal. For that to happen, one prime condition is that HRs should login only with their work profiles and thus their personal accounts(gmail,etc.) should be restricted. I have seen some similar questions where we had to whitelist a particular domain and restrict all others but this might not be feasible in this case, as whitelisting all the work domains doesn't seem practical. Is there a built-in solution for this?
My Tech Stack is:
NextJS for the frontend.
For the backend part, I am thinking of either NodeJS+mongoDB OR Sanity.io depending on a more feasible solution for the above problem statement...</p>

答:
Restrict yahoo/gmail and only allow their company's email or school's email (.edu). You can also have a dropdown of whitelisted school's email or company.

School or companies who wish to join your platform will have to be manually added once. Basically whitelisted list can perform registration in the future.


问:
Ensure StreamReader handles one message at a time
I am using the aioisotp library and sometimes messages are received close together. This means that aioisotp can, on occasion, provide 2 messages combined together.
For example,

```<code>03 7F 36 78 00 00 00 00
02 76 02 00 00 00 00 00
</code>```

I receive these 2 messages <2ms apart. aioisotp returns it as one combined message: 7f36787602

What I believe is happening:

StreamReader.feed_data() is receiving the first message (7F3678) and adds to the buffer.

It then flags for the read() to consume the data using _wakeup_waiter() which sets the result on the future()

Before the read() can be scheduled to consume the data, the second message (7602) is received; and StreamReader.feed_data() is called and the buffer is extended with the new data. So, the buffer now contains 7F36787602.

The read() now occurs and both pieces of data are received together.

There is nothing in the received data to tell me this is >1 message so I need to ensure the order of one feed_data() followed by read().

As a test, in StreamReader.feed_data() I changed self._buffer.extend(data) to self._buffer=bytearray(data)

Whilst this worked, it doesn't feel like the correct way of handling this. What would be the correct way to ensure read() only gets one message at a time?

答:
StreamReader expects streaming data, such as that coming from a TCP/IP socket or from a pipe. Such data has no concept of "messages", only a stream of bytes. Even if the peer sends bytes in individual bursts, those may be merged or split up by the sender's or the receiver's OS, or by the network equipment between them. No change to feed_data or other part of asyncio can fix that in the general case.

If you need to send individual messages over a TCP stream, you need to add explicit framing. For example, you can prefix the message with the message length, or you can insert a separator that cannot appear in the message between two messages. See this answer for an example of the former.

Body:
I am using the aioisotp library and sometimes messages are received close together. This means that aioisotp can, on occasion, provide 2 messages combined together.
For example,

03 7F 36 78 00 00 00 00
02 76 02 00 00 00 00 00

I receive these 2 messages <2ms apart. aioisotp returns it as one combined message: 7f36787602

What I believe is happening:

StreamReader.feed_data() is receiving the first message (7F3678) and adds to the buffer.

It then flags for the read() to consume the data using _wakeup_waiter() which sets the result on the future()

Before the read() can be scheduled to consume the data, the second message (7602) is received; and StreamReader.feed_data() is called and the buffer is extended with the new data. So, the buffer now contains 7F36787602.

The read() now occurs and both pieces of data are received together.

There is nothing in the received data to tell me this is >1 message so I need to ensure the order of one feed_data() followed by read().

As a test, in StreamReader.feed_data() I changed self._buffer.extend(data) to self._buffer=bytearray(data)

Whilst this worked, it doesn't feel like the correct way of handling this. What would be the correct way to ensure read() only gets one message at a time?


问:
REST URL structure advice
I'm trying to finalise on a restful url structure for the wishlist section of a site I'm working on. It's a pretty simple model, a user can have many wishlists and each wishlist can contain many products.

Currently I have the obvious CRUD URLs to manipulate the wishlist itself :

```<code>GET account/wishlists.json
GET account/wishlists/{id}.json
POST account/wishlists.json?name=My%20Wishlist
POST account/wishlists/{id}.json?name=My%20New%20Name
DELETE account/wishlists/{id}.json
</code>```

However, I don't think I know how to structure the URLs that would add/remove a product to a wishlist :(

Here are my current choices :

1) Have the product to add as part of the URL and use the HTTP verb to define my action

```<code>POST account/wishlist/{id}/product/{product_id}.json
DELETE account/wishlist/{id}/product/{product_id}.json
</code>```

or

2) Have the action as part of the URL and the product id as part of the payload

```<code>POST account/wishlist/{id}/add.json?product_id={product_id}
POST account/wishlist/{id}/remove.json?product_id={product_id}
</code>```

(1) is clean and, as far as I can tell it's pretty RESTful but doesn't allow things like adding multiple products easily etc.

I'm also a bit concerned about using the DELETE verb - I'm not deleting the product or the wishlist, I'm just removing one from the other.

(2) is more explicit but veers away from REST - I wouldn't be just referring to the resource in the url, I would be referring to an operation on that resource :(

Any advice on which of the above would be more correct would be very helpful! (If there's a third option that's better than mine, feel free to correct me!)

答:
(1) is the only valid approach for REST, using HTTP verbs for actions.

(2) encodes method names into the URI which is more like RPC and of course not RESTful.

Concerning your shortcomings about the first approach:

The DELETE verb is fine, because your resource is the item inside in the wishlist, not the item itself.

You can support batch requests. For instance, you might want to allow to POST a list of items to a wishlist resource resulting in mutliple adds.

PS: Prefer HTTP content negotiation (Accept and Content-Type headers) over representation formats encoded in the URI.

Title: REST URL structure advice

Body:
I'm trying to finalise on a restful url structure for the wishlist section of a site I'm working on. It's a pretty simple model, a user can have many wishlists and each wishlist can contain many products.

Currently I have the obvious CRUD URLs to manipulate the wishlist itself :

GET account/wishlists.json
GET account/wishlists/{id}.json
POST account/wishlists.json?name=My%20Wishlist
POST account/wishlists/{id}.json?name=My%20New%20Name
DELETE account/wishlists/{id}.json

However, I don't think I know how to structure the URLs that would add/remove a product to a wishlist :(

Here are my current choices :

1) Have the product to add as part of the URL and use the HTTP verb to define my action

POST account/wishlist/{id}/product/{product_id}.json
DELETE account/wishlist/{id}/product/{product_id}.json

or

2) Have the action as part of the URL and the product id as part of the payload

POST account/wishlist/{id}/add.json?product_id={product_id}
POST account/wishlist/{id}/remove.json?product_id={product_id}

(1) is clean and, as far as I can tell it's pretty RESTful but doesn't allow things like adding multiple products easily etc.

I'm also a bit concerned about using the DELETE verb - I'm not deleting the product or the wishlist, I'm just removing one from the other.

(2) is more explicit but veers away from REST - I wouldn't be just referring to the resource in the url, I would be referring to an operation on that resource :(

Any advice on which of the above would be more correct would be very helpful! (If there's a third option that's better than mine, feel free to correct me!)


问:
Autofit row height for specific range , then resize entire row height for each row ,as height of each cell after autofit on the cited range?
I need to Autofit row height only for specific range e.g ("B3:B8") But not autofit the entire row.

Autofit row height for specific range , then resize entire row height for each row ,depends on height of each cell after autofit on the cited range respectively.
On the below code , I did not use EntireRow but the code forcibly autofit entire row.

In advance, thanks for your help.

```<code>Sub AutoFit_Range()

    Dim rng As Range
     Set rng = ThisWorkbook.Sheets(1).Range("B3:B8")
         rng.Rows.AutoFit

End Sub
</code>```

答:
AutoFit (Entire) Rows of a Range

It will copy the range (including its column widths) to another worksheet, autofit the rows there and loop through the rows of the new range and use their heights to be set in the initial range.

Option Explicit

Sub AutoFit_Range()

    Const rgAddress As String = "B3:B8"

    Dim wb As Workbook: Set wb = ThisWorkbook

    Dim ash As Object: Set ash = ActiveSheet

    Dim dws As Worksheet: Set dws = wb.Worksheets(1)
    Dim drg As Range: Set drg = dws.Range(rgAddress)
    Dim rCount As Long: rCount = drg.Rows.Count

    Application.ScreenUpdating = False

    Dim sws As Worksheet
    Set sws = wb.Worksheets.Add(After:=wb.Sheets(wb.Sheets.Count))

    drg.Copy

    Dim srg As Range
    With sws.Range("A1")
        .PasteSpecial xlPasteColumnWidths
        .PasteSpecial xlPasteAll
        Set srg = .Resize(rCount)
    End With
    srg.EntireRow.AutoFit

    Dim r As Long
    For r = 1 To rCount
        drg.Rows(r).RowHeight = srg.Rows(r).RowHeight
    Next r

    Application.DisplayAlerts = False
    sws.Delete
    Application.DisplayAlerts = True

    ash.Activate

    Application.ScreenUpdating = True

End Sub
```

Body:
I need to Autofit row height only for specific range e.g ("B3:B8") But not autofit the entire row.

Autofit row height for specific range , then resize entire row height for each row ,depends on height of each cell after autofit on the cited range respectively.
On the below code , I did not use EntireRow but the code forcibly autofit entire row.

In advance, thanks for your help.

Sub AutoFit_Range()

    Dim rng As Range
     Set rng = ThisWorkbook.Sheets(1).Range("B3:B8")
         rng.Rows.AutoFit

End Sub