问:
Adding an equal amount of space between different sized elements with justify-content: space between
[![enter image description here][1]][1]
I have a table that requires flex due to it needing support for mobile use. I currently use flex justify-content: space-between; to give the three elements equal space; however since the data in the "rows" are uneven due to font, the center elements get shoved around. Is there a way to lock the center column in place?

As you can see the center column is slightly shoved, so is there a way to lock it in place?

CSS:'

```<code>        .UsageOverview__detailsRecord {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: $space-xxxs $space-xs;

          .UsageOverview__detailsRecordName {
            font-weight: $font-weight-bold;
          }

          .UsageOverview__detailsRecordValue {
            font-weight: 400;
            text-align: right;
          }

          .UsageOverview__detailsPriceValue {
            font-weight: 400;
            text-align: center;
          }
</code>```

HTML:

```<code> <div repeat.for="record of usage.currentPeriod" class="UsageOverview__detailsRecord">
                      <span class="UsageOverview__detailsDateValue">
                        <template if.bind="dateRange === 'year'">
                          ${record.fromTime | date:'MMMM'}
                        </template>
                        <template if.bind="dateRange === 'month'">
                          ${record.fromTime | date:'DD.'}
                        </template>
                        <template if.bind="dateRange === 'day'">
                          ${record.fromTime | date:'HH:00'}
                        </template>
                      </span>
                      <span class="UsageOverview__detailsDataValue">
                        ${getTablePriceValue(record) & signal:'force-refresh-signal'}
                      </span>
                      <span class="UsageOverview__detailsRecordValue">
                        ${getTableDataValue(record) & signal:'force-refresh-signal'}
                      </span> ```

  [1]: https://i.stack.imgur.com/D8Fl8.jpg
```

答: I would personally look at the space-evenly value instead of space-between. But not sure if this breaks your CSS or something.

Body:
[![enter image description here][1]][1]
I have a table that requires flex due to it needing support for mobile use. I currently use flex justify-content: space-between; to give the three elements equal space; however since the data in the "rows" are uneven due to font, the center elements get shoved around. Is there a way to lock the center column in place?

As you can see the center column is slightly shoved, so is there a way to lock it in place?

CSS:'

        .UsageOverview__detailsRecord {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: $space-xxxs $space-xs;

          .UsageOverview__detailsRecordName {
            font-weight: $font-weight-bold;
          }

          .UsageOverview__detailsRecordValue {
            font-weight: 400;
            text-align: right;
          }

          .UsageOverview__detailsPriceValue {
            font-weight: 400;
            text-align: center;
          }

HTML:

                        <template if.bind="dateRange === 'year'">
                          ${record.fromTime | date:'MMMM'}
                        </template>
                        <template if.bind="dateRange === 'month'">
                          ${record.fromTime | date:'DD.'}
                        </template>
                        <template if.bind="dateRange === 'day'">
                          ${record.fromTime | date:'HH:00'}
                        </template>

                        ${getTablePriceValue(record) & signal:'force-refresh-signal'}

                        ${getTableDataValue(record) & signal:'force-refresh-signal'}
                       ```

  [1]: https://i.stack.imgur.com/D8Fl8.jpg


来源: stackexchange

问:
grid component in materia ui
I have this code and I get this error:

```<code>No overload matches this call.
  Overload 1 of 2, '(props: { component: ElementType<any>; } & SystemProps<Theme> & { children?: ReactNode; classes?: Partial<GridClasses>; ... 14 more ...; zeroMinWidth?: boolean; } & CommonProps & Omit<...>): Element', gave the following error.
    Property 'component' is missing in type '{ children: Element; item: true; lg: 4; mmd: number; md: 3; ssm: number; sm: 4; key: string; }' but required in type '{ component: ElementType<any>; }'.
  Overload 2 of 2, '(props: DefaultComponentProps<GridTypeMap<{}, "div">>): Element', gave the following error.
    Type '{ children: Element; item: true; lg: 4; mmd: number; md: 3; ssm: number; sm: 4; key: string; }' is not assignable to type 'IntrinsicAttributes & SystemProps<Theme> & { children?: ReactNode; classes?: Partial<GridClasses>; ... 14 more ...; zeroMinWidth?: boolean; } & CommonProps & Omit<...>'.
      Property 'mmd' does not exist on type 'IntrinsicAttributes & SystemProps<Theme> & { children?: ReactNode; classes?: Partial<GridClasses>; ... 14 more ...; zeroMinWidth?: boolean; } & CommonProps & Omit<...>'.ts(2769)
OverridableComponent.d.ts(17, 7): 'component' is declared here.
</code>```

<Grid
    item
    lg={4}
    mmd={4}
    md={3}
    ssm={6}
    sm={4}
    key={`col${item.id}`}
>
```

Why does this error happen?

答: I found why this happen. Because I use mmd in grid its not recognized</p>

ContentLicense: CC BY-SA 4.0

Title: grid component in materia ui

Body:
I have this code and I get this error:

No overload matches this call.
  Overload 1 of 2, '(props: { component: ElementType<any>; } & SystemProps<Theme> & { children?: ReactNode; classes?: Partial<GridClasses>; ... 14 more ...; zeroMinWidth?: boolean; } & CommonProps & Omit<...>): Element', gave the following error.
    Property 'component' is missing in type '{ children: Element; item: true; lg: 4; mmd: number; md: 3; ssm: number; sm: 4; key: string; }' but required in type '{ component: ElementType<any>; }'.
  Overload 2 of 2, '(props: DefaultComponentProps<GridTypeMap<{}, "div">>): Element', gave the following error.
    Type '{ children: Element; item: true; lg: 4; mmd: number; md: 3; ssm: number; sm: 4; key: string; }' is not assignable to type 'IntrinsicAttributes & SystemProps<Theme> & { children?: ReactNode; classes?: Partial<GridClasses>; ... 14 more ...; zeroMinWidth?: boolean; } & CommonProps & Omit<...>'.
      Property 'mmd' does not exist on type 'IntrinsicAttributes & SystemProps<Theme> & { children?: ReactNode; classes?: Partial<GridClasses>; ... 14 more ...; zeroMinWidth?: boolean; } & CommonProps & Omit<...>'.ts(2769)
OverridableComponent.d.ts(17, 7): 'component' is declared here.

<Grid
    item
    lg={4}
    mmd={4}
    md={3}
    ssm={6}
    sm={4}
    key={`col${item.id}`}
>

Why does this error happen?


问:
Swiperjs. How can I pass custom props to SwiperSlide and get it onSlideChange function?
I am in a different situation. I am using Swiper.js for my React app. I need to change app theme color on slide changes and it have to be dynamic. That's I need to pass some props to SwiperSlide and get this props on slide change. How can I handle that ?

    <Swiper
      id="pathway-slider"
      slidesPerView={1}
      onSlideChange={(swiper) => {
        console.log("Slide index changed to: ", swiper);
      }}
    >
      <SwiperSlide>
          Slide 1
      </SwiperSlide>

      <SwiperSlide>
          Slide 2
      </SwiperSlide>
    </Swiper>```

When I console.log(swiper) it gives me huge object where I can access activeSlideIndex or etc. But how can I pass custom data to that ?

答:
A solution for people trying to use material UI and swiperis to wrapper the swiper component in amaterial styled componentand then pass your props through thesx={{}}for some reason this doesn't throw atypescript flag`

Import styled

```<code>import { styled } from "@mui/system";

</code>```

Wrapper Swiper in styled

```<code>const StyledSwiper = styled(Swiper)(({ theme }: any) => ({
  padding: "20px 0 70px 0",
}));
</code>```

Add Custom Swipper to your page or component

```<code><StyledSwiper
        ...some_default_PROPS
        sx={{
          "& .swiper-slide": {
            transition: "all 3s ease",
            transform: isHomePage ? "scale(0.8)" : "initial",
          },
          "& .swiper-slide-active": {
            transform: isHomePage ? "scale(1.1)" : "initial",
          },
          "& .swiper-pagination": {
            bottom: "0",
          },
        }}
      >  {data?.length > 0 &&
          data.map(((node,index)) => (
            <SwiperSlide key={node?.id}>
              <div> Slide {index}</div>
            </SwiperSlide>
          ))}
      </StyledSwiper>
</code>```

Body:
I am in a different situation. I am using Swiper.js for my React app. I need to change app theme color on slide changes and it have to be dynamic. That's I need to pass some props to SwiperSlide and get this props on slide change. How can I handle that ?

    <Swiper
      id="pathway-slider"
      slidesPerView={1}
      onSlideChange={(swiper) => {
        console.log("Slide index changed to: ", swiper);
      }}
    >
      <SwiperSlide>
          Slide 1
      </SwiperSlide>

      <SwiperSlide>
          Slide 2
      </SwiperSlide>
    </Swiper>

When I console.log(swiper) it gives me huge object where I can access activeSlideIndex or etc. But how can I pass custom data to that ?

Body:
A solution for people trying to use material UI and swiperis to wrapper the swiper component in amaterial styled componentand then pass your props through thesx={{}}for some reason this doesn't throw atypescript flag`

Import styled

import { styled } from "@mui/system";

Wrapper Swiper in styled

const StyledSwiper = styled(Swiper)(({ theme }: any) => ({
  padding: "20px 0 70px 0",
}));

Add Custom Swipper to your page or component

<StyledSwiper
        ...some_default_PROPS
        sx={{
          "& .swiper-slide": {
            transition: "all 3s ease",
            transform: isHomePage ? "scale(0.8)" : "initial",
          },
          "& .swiper-slide-active": {
            transform: isHomePage ? "scale(1.1)" : "initial",
          },
          "& .swiper-pagination": {
            bottom: "0",
          },
        }}
      >  {data?.length > 0 &&
          data.map(((node,index)) => (
            <SwiperSlide key={node?.id}>
              <div> Slide {index}</div>
            </SwiperSlide>
          ))}
      </StyledSwiper>


问:
round() mode ROUND_HALF_DOWN with PHP 5.2.17
I need to simulate ROUND_HALF_DOWN mode in PHP 5.2.17 - I cannot upgrade the server's PHP version. Any ideas how to achieve this?

The basic idea is that 1.895 becomes 1.89, not 1.90 like it usually does with round().

EDIT:
This function seems to do the trick:

```<code>function nav_round($v, $prec = 2) {
    // Seems to fix a bug with the ceil function
    $v = explode('.',$v);
    $v = implode('.',$v);
    // The actual calculation
    $v = $v * pow(10,$prec) - 0.5;
    $a = ceil($v) * pow(10,-$prec);
    return number_format( $a, 2, '.', '' );
}
</code>```

答:
You can take off 0.5^p where p is the precision and then use ceiling:

<?php

function round_half_down($v, $prec) {
  $v = $v * pow(10,$prec) - 0.5;
  return ceil($v) * pow(10,-$prec);
}

print round_half_down(9.5,0) . "\n";
print round_half_down(9.05,0) . "\n";
print round_half_down(9.051,0) . "\n";
print round_half_down(9.05,1) . "\n";
print round_half_down(9.051,1) . "\n";
print round_half_down(9.055,2) . "\n";
print round_half_down(1.896,2) . "\n";

?>
```

<p>yields:</p>

<pre class="lang-none prettyprint-override"><code>$ php test.php
9
9
9
9
9.1
9.05
1.9
</code>```

You'll note that for any number x <= p <= x.5, we get ceiling(p - 0.5) = x, and for all x+1 => p > x.5, we get ceiling(p - 0.5) = x+1. This should be exactly what you want.

ContentLicense: CC BY-SA 3.0

Body:
I need to simulate ROUND_HALF_DOWN mode in PHP 5.2.17 - I cannot upgrade the server's PHP version. Any ideas how to achieve this?

The basic idea is that 1.895 becomes 1.89, not 1.90 like it usually does with round().

EDIT:
This function seems to do the trick:

function nav_round($v, $prec = 2) {
    // Seems to fix a bug with the ceil function
    $v = explode('.',$v);
    $v = implode('.',$v);
    // The actual calculation
    $v = $v * pow(10,$prec) - 0.5;
    $a = ceil($v) * pow(10,-$prec);
    return number_format( $a, 2, '.', '' );
}

Body:
You can take off 0.5^p where p is the precision and then use ceiling:

<?php

function round_half_down($v, $prec) {
  $v = $v * pow(10,$prec) - 0.5;
  return ceil($v) * pow(10,-$prec);
}

print round_half_down(9.5,0) . "\n";
print round_half_down(9.05,0) . "\n";
print round_half_down(9.051,0) . "\n";
print round_half_down(9.05,1) . "\n";
print round_half_down(9.051,1) . "\n";
print round_half_down(9.055,2) . "\n";
print round_half_down(1.896,2) . "\n";

?>

yields:

$ php test.php
9
9
9
9
9.1
9.05
1.9

You'll note that for any number x <= p <= x.5, we get ceiling(p - 0.5) = x, and for all x+1 => p > x.5, we get ceiling(p - 0.5) = x+1. This should be exactly what you want.


问:
Group by - Excel Power Query multiple rows into one
I have data I loaded to Power Query  - each Employee has mulitple rows and its looks like this:

empNum reason 1 reason 2 reason 3

3453    1         null    null

3453    null      1       null

3453    null      null    1

How can I transform the data to look like this?

empNum reason 1 reason 2 reason 3

3453    1        1        1

答:
In powerquery you can try

click select first column

right click ... unpivot other columns

click select attribute column, transform ... pivot column, use Values as values column, advanced options, dont aggregate
```<code>let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"empNum"}, "Attribute", "Value"),
#"Pivoted Column" = Table.Pivot(#"Unpivoted Other Columns", List.Distinct(#"Unpivoted Other Columns"[Attribute]), "Attribute", "Value")
in #"Pivoted Column"
</code>```

Body:
In powerquery you can try

click select first column

right click ... unpivot other columns

click select attribute column, transform ... pivot column, use Values as values column, advanced options, dont aggregate

let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"empNum"}, "Attribute", "Value"),
#"Pivoted Column" = Table.Pivot(#"Unpivoted Other Columns", List.Distinct(#"Unpivoted Other Columns"[Attribute]), "Attribute", "Value")
in #"Pivoted Column"


问:
Error and blank page on Vue JS when creating a json file in assets
I went through a very strange issue.
I have a vue project created with vue ui.
I'm editing my code in visual studio.

i want to prototype and work with fake data before connecting my API.
So i had the idea to create a json file in my assets folder to host my moock datas and import them to work on the UI.

but when i creating a Json file in my assets folder, and vue ui re render the project i have the following error.

```<code>app.js:1178 Uncaught Error: Cannot find module './assets/moockupdata.json'
at webpackMissingModule (app.js:1178:45)
at Object../src/assets/moockupdata.json (app.js:1178:145)
at __webpack_require__ (app.js:854:30)
at fn (app.js:151:20)
at webpackContext (eval at ./src sync recursive [A-Za-z0-9-_,\s]+\.json$/ (app.js:1087:1), <anonymous>:11:9)
at eval (i18n.js?9225:13:1)
at Array.forEach (<anonymous>)
at loadLocaleMessages (i18n.js?9225:9:1)
at eval (i18n.js?9225:22:1)
at Module../src/i18n.js (app.js:1191:1)
webpackMissingModule @ app.js:1178
./src/assets/moockupdata.json @ app.js:1178
__webpack_require__ @ app.js:854
fn @ app.js:151
webpackContext @ ?400a:11
eval @ i18n.js?9225:13
loadLocaleMessages @ i18n.js?9225:9
eval @ i18n.js?9225:22
./src/i18n.js @ app.js:1191
__webpack_require__ @ app.js:854
fn @ app.js:151
eval @ main.js:16
./src/main.js @ app.js:1225
__webpack_require__ @ app.js:854
fn @ app.js:151
1 @ app.js:1345
__webpack_require__ @ app.js:854
checkDeferredModules @ app.js:46
(anonymous) @ app.js:994
(anonymous) @ app.js:997
</code>```

i must confess i'm quiet stuck and confused with this issues.
I would appriciate some help

Thanks a lot

答:
I finally find a turnaround.
Instead of behing stubborn and try at any cost to create a JSON file.

I went for a "mydata.js" file

with the inner structure

```<code>const data = {
  Mykey1: 'Myvalue1',
  HasKey1: true,
  otherdata: 'yes'
}

export default data
</code>```

and import it from my Vue file with

```<code><script>
import AwsConfig from '@/config/mydata.js.js'
export default {
...
</code>```

Body:
I went through a very strange issue.
I have a vue project created with vue ui.
I'm editing my code in visual studio.

i want to prototype and work with fake data before connecting my API.
So i had the idea to create a json file in my assets folder to host my moock datas and import them to work on the UI.

but when i creating a Json file in my assets folder, and vue ui re render the project i have the following error.

app.js:1178 Uncaught Error: Cannot find module './assets/moockupdata.json'
at webpackMissingModule (app.js:1178:45)
at Object../src/assets/moockupdata.json (app.js:1178:145)
at __webpack_require__ (app.js:854:30)
at fn (app.js:151:20)
at webpackContext (eval at ./src sync recursive [A-Za-z0-9-_,\s]+\.json$/ (app.js:1087:1), <anonymous>:11:9)
at eval (i18n.js?9225:13:1)
at Array.forEach (<anonymous>)
at loadLocaleMessages (i18n.js?9225:9:1)
at eval (i18n.js?9225:22:1)
at Module../src/i18n.js (app.js:1191:1)
webpackMissingModule @ app.js:1178
./src/assets/moockupdata.json @ app.js:1178
__webpack_require__ @ app.js:854
fn @ app.js:151
webpackContext @ ?400a:11
eval @ i18n.js?9225:13
loadLocaleMessages @ i18n.js?9225:9
eval @ i18n.js?9225:22
./src/i18n.js @ app.js:1191
__webpack_require__ @ app.js:854
fn @ app.js:151
eval @ main.js:16
./src/main.js @ app.js:1225
__webpack_require__ @ app.js:854
fn @ app.js:151
1 @ app.js:1345
__webpack_require__ @ app.js:854
checkDeferredModules @ app.js:46
(anonymous) @ app.js:994
(anonymous) @ app.js:997

i must confess i'm quiet stuck and confused with this issues.
I would appriciate some help

Thanks a lot

Body:
I finally find a turnaround.
Instead of behing stubborn and try at any cost to create a JSON file.

I went for a "mydata.js" file

with the inner structure

const data = {
  Mykey1: 'Myvalue1',
  HasKey1: true,
  otherdata: 'yes'
}

export default data

and import it from my Vue file with

<script>
import AwsConfig from '@/config/mydata.js.js'
export default {
...


问:
How to unstage large number of files without deleting the content
I accidentally added a lot of temporary files using git add -A

I managed to unstage the files using the following commands and managed to remove the dirty index.

```<code>git ls-files -z | xargs -0 rm -f
git diff --name-only --diff-filter=D -z | xargs -0 git rm --cached
</code>```

The above commands are listed in the git help rm. But sadly, my files were also deleted on execution, even though I had given cache option. How can I clear the index without losing the content?

Also it would be helpful if someone can explain the way this pipe operation works.

答:
Use git reset HEAD to reset the index without removing files. (If you only want to reset a particular file in the index, you can use git reset HEAD -- /path/to/file to do so.)

The pipe operator, in a shell, takes the stdout of the process on the left and passes it as stdin to the process on the right. It's essentially the equivalent of:

```<code>$ proc1 > proc1.out
$ proc2 < proc1.out
$ rm proc1.out
</code>```

but instead it's $ proc1 | proc2, the second process can start getting data before the first is done outputting it, and there's no actual file involved.

Body:
I accidentally added a lot of temporary files using git add -A

I managed to unstage the files using the following commands and managed to remove the dirty index.

git ls-files -z | xargs -0 rm -f
git diff --name-only --diff-filter=D -z | xargs -0 git rm --cached

The above commands are listed in the git help rm. But sadly, my files were also deleted on execution, even though I had given cache option. How can I clear the index without losing the content?

Also it would be helpful if someone can explain the way this pipe operation works.

Body:
Use git reset HEAD to reset the index without removing files. (If you only want to reset a particular file in the index, you can use git reset HEAD -- /path/to/file to do so.)

The pipe operator, in a shell, takes the stdout of the process on the left and passes it as stdin to the process on the right. It's essentially the equivalent of:

$ proc1 > proc1.out
$ proc2 < proc1.out
$ rm proc1.out

but instead it's $ proc1 | proc2, the second process can start getting data before the first is done outputting it, and there's no actual file involved.


问:
Python Higher Order Function: New way to find Fibonacci Numbers
I am given a question to write a higher order function to find fibonacci numbers.
First, I am defined the combine function below:

```<code>def combine(f, op ,n):
    result = f(0)
    for i in range(n):
        result = op(result, f(i))
return result
</code>```

For example, new_fib(10) = 55

The function I'm supposed to define is thus to find the nth fibonacci number:

```<code>def new_fib(n):
    def f(x):
        ...
    def op(x, y):
        ...
    return combine(f, op, n+1)
</code>```

The idea I have to solve this question is simply to chuck the fibonacci sequence into the f(x) function, but I've been facing a lot of problems. Here's what I have now:

```<code>def new_fib(n):
    def op(x,y):
        return x+y
    def f(x):
        a,b = 0, 1
        fibs = ()
        for i in range(n+1):
            a, b = b, a+b
            fibs += (a,)
        return fibs[x]
    return combine(f, op, n+1)
</code>```

But that's wrong because it accumulates too fast. I can picture why in my head, but cannot figure a way out to get around it. Does anyone have any advice? It would be greatly appreciated! Thank you!

答:
The operation should just be a, b => b, a+b, and you iterate it.

Code could be:

```<code>def new_fib(n):
    def op(a, b):
        return b, a+b
    def combine(initial, op, n):
        a, b = initial
        for i in range(n):
            a, b = op(a, b)
        return b
    if n == 0:                # special processing for 0 and 1
        return 0
    if n == 1:
        return 1
    return combine((0,1), op, n - 1)
</code>```

It correctly gives 55 for new_fib(10)

Body:
I am given a question to write a higher order function to find fibonacci numbers.
First, I am defined the combine function below:

def combine(f, op ,n):
    result = f(0)
    for i in range(n):
        result = op(result, f(i))
return result

For example, new_fib(10) = 55

The function I'm supposed to define is thus to find the nth fibonacci number:

def new_fib(n):
    def f(x):
        ...
    def op(x, y):
        ...
    return combine(f, op, n+1)

The idea I have to solve this question is simply to chuck the fibonacci sequence into the f(x) function, but I've been facing a lot of problems. Here's what I have now:

def new_fib(n):
    def op(x,y):
        return x+y
    def f(x):
        a,b = 0, 1
        fibs = ()
        for i in range(n+1):
            a, b = b, a+b
            fibs += (a,)
        return fibs[x]
    return combine(f, op, n+1)

But that's wrong because it accumulates too fast. I can picture why in my head, but cannot figure a way out to get around it. Does anyone have any advice? It would be greatly appreciated! Thank you!

Body:
The operation should just be a, b => b, a+b, and you iterate it.

Code could be:

def new_fib(n):
    def op(a, b):
        return b, a+b
    def combine(initial, op, n):
        a, b = initial
        for i in range(n):
            a, b = op(a, b)
        return b
    if n == 0:                # special processing for 0 and 1
        return 0
    if n == 1:
        return 1
    return combine((0,1), op, n - 1)

It correctly gives 55 for new_fib(10)


问:
Scala Databricks: read a JSON file and return two DataFrame
I have the following code :

```<code>def reader (path:String):DataFrame={

val path =sc.textFile("/FileStore/tables/Data_exo2.json").reduce((a,b)=>s"$a$b")

val df = Seq((path)).toDF()

val schema_tran = new StructType()
.add("Devis", StringType, false)
.add("IdTransaction",LongType, false)
.add("Pays", StringType, false)
.add("Prix",DoubleType, false)
.add("TypeProduit", StringType, false)

val schema = new StructType().add("Transaction", ArrayType(schema_tran),true)

val df_66 = df.select(from_json($"value",schema)as "struct")
.select($"struct.*")
.withColumn("Transaction", explode(col("Transaction")))
.select($"Transaction.*")

val schema_devis = new StructType()

.add("Devis", StringType, false)
.add("Taux",DoubleType, false)

val schema_1 = new StructType()
.add("Devis", ArrayType(schema_devis),true)

val df_67 = df.select(from_json($"value",schema_1)as "struct")
.select($"struct.*")
.withColumn("Devis", explode(col("Devis")))
.select($"Devis.*")
 *****}
</code>```

So I have two dataframe df_66 and df_67.
Basicaly, I want to define a fonction to return those dataframe, one by one like this reader(path)(0)

答:
Is this what you are looking for ?

```<code>def reader(path: String): Map[Int, DataFrame] = {

    val df = spark.read.format("json").load(path)

    val schema_tran = new StructType()
    .add("Devis", StringType, false)
    .add("IdTransaction",LongType, false)
    .add("Pays", StringType, false)
    .add("Prix",DoubleType, false)
    .add("TypeProduit", StringType, false)

    val schema = new StructType().add("Transaction", ArrayType(schema_tran),true)

    val df_66 = df.select(from_json($"value",schema)as "struct")
    .select($"struct.*")
    .withColumn("Transaction", explode(col("Transaction")))
    .select($"Transaction.*")

    val schema_devis = new StructType()

    .add("Devis", StringType, false)
    .add("Taux",DoubleType, false)

    val schema_1 = new StructType()
    .add("Devis", ArrayType(schema_devis),true)

    val df_67 = df.select(from_json($"value",schema_1)as "struct")
    .select($"struct.*")
    .withColumn("Devis", explode(col("Devis")))
    .select($"Devis.*")

    Map(
        0 -> df_66,
        1 -> df_67
    )
}
</code>```

You can get the DataFrame back using

```<code>reader("some path")(0) // df_66
reader("some path")(1) // df_67

</code>```

Body:
I have the following code :

def reader (path:String):DataFrame={

val path =sc.textFile("/FileStore/tables/Data_exo2.json").reduce((a,b)=>s"$a$b")

val df = Seq((path)).toDF()

val schema_tran = new StructType()
.add("Devis", StringType, false)
.add("IdTransaction",LongType, false)
.add("Pays", StringType, false)
.add("Prix",DoubleType, false)
.add("TypeProduit", StringType, false)

val schema = new StructType().add("Transaction", ArrayType(schema_tran),true)

val df_66 = df.select(from_json($"value",schema)as "struct")
.select($"struct.*")
.withColumn("Transaction", explode(col("Transaction")))
.select($"Transaction.*")

val schema_devis = new StructType()

.add("Devis", StringType, false)
.add("Taux",DoubleType, false)

val schema_1 = new StructType()
.add("Devis", ArrayType(schema_devis),true)

val df_67 = df.select(from_json($"value",schema_1)as "struct")
.select($"struct.*")
.withColumn("Devis", explode(col("Devis")))
.select($"Devis.*")
 *****}

So I have two dataframe df_66 and df_67.
Basicaly, I want to define a fonction to return those dataframe, one by one like this reader(path)(0)

Body:
Is this what you are looking for ?

def reader(path: String): Map[Int, DataFrame] = {

    val df = spark.read.format("json").load(path)

    val schema_tran = new StructType()
    .add("Devis", StringType, false)
    .add("IdTransaction",LongType, false)
    .add("Pays", StringType, false)
    .add("Prix",DoubleType, false)
    .add("TypeProduit", StringType, false)

    val schema = new StructType().add("Transaction", ArrayType(schema_tran),true)

    val df_66 = df.select(from_json($"value",schema)as "struct")
    .select($"struct.*")
    .withColumn("Transaction", explode(col("Transaction")))
    .select($"Transaction.*")

    val schema_devis = new StructType()

    .add("Devis", StringType, false)
    .add("Taux",DoubleType, false)

    val schema_1 = new StructType()
    .add("Devis", ArrayType(schema_devis),true)

    val df_67 = df.select(from_json($"value",schema_1)as "struct")
    .select($"struct.*")
    .withColumn("Devis", explode(col("Devis")))
    .select($"Devis.*")

    Map(
        0 -> df_66,
        1 -> df_67
    )
}

You can get the DataFrame back using

reader("some path")(0) // df_66
reader("some path")(1) // df_67


问:
Getting dispatch_failed error in slack when using slash command
So I have been trying to make a very simple slash command since last 3 days that just triggers a lambda function using an api gateway. The lambda function is quite simple too. I am following the below tutorial to make this

https://medium.com/@farski/learn-aws-api-gateway-with-the-slack-police-ca8d636e9fc0

Before this I have tried many myself with a just hello work lambda function, but no matter what whenever I try to run the command in slack I always get this "dispatch_failed" error.

```<code>/appname failed with the error "dispatch_failed"
</code>```

As you can see this is se generic I dont know whats going wrong in this. Looks like slack is not even hitting the request url which I configured, i am not sure though. Anyone has ever faced this and knows how we can resolve this? Thanks

(The endpoint of api gateway works fine if I just use browser or postman)

P.S If you can suggest any tutorial that shows me how can I integrate slash command with api gateway and lambda, then please.

答: Use HTTP API you might have using REST API.

Body:
So I have been trying to make a very simple slash command since last 3 days that just triggers a lambda function using an api gateway. The lambda function is quite simple too. I am following the below tutorial to make this

https://medium.com/@farski/learn-aws-api-gateway-with-the-slack-police-ca8d636e9fc0

Before this I have tried many myself with a just hello work lambda function, but no matter what whenever I try to run the command in slack I always get this "dispatch_failed" error.

/appname failed with the error "dispatch_failed"

As you can see this is se generic I dont know whats going wrong in this. Looks like slack is not even hitting the request url which I configured, i am not sure though. Anyone has ever faced this and knows how we can resolve this? Thanks

(The endpoint of api gateway works fine if I just use browser or postman)

P.S If you can suggest any tutorial that shows me how can I integrate slash command with api gateway and lambda, then please.


问:
How to get the part of a file after the first line that matches a regular expression
I have a file with about 1000 lines. I want the part of my file after the line which matches my grep statement.

That is:

```<code>cat file | grep 'TERMINATE'     # It is found on line 534
</code>```

So, I want the file from line 535 to line 1000 for further processing.

How can I do that?

答:
sed is a much better tool for the job:

```<code>sed -n '/re/,$p' file
</code>```

where re is a regular expression.

Another option is grep's --after-context flag. You need to pass in a number to end at, using wc on the file should give the right value to stop at. Combine this with -n and your match expression.

Body:
I have a file with about 1000 lines. I want the part of my file after the line which matches my grep statement.

That is:

cat file | grep 'TERMINATE'     # It is found on line 534

So, I want the file from line 535 to line 1000 for further processing.

How can I do that?

Body:
sed is a much better tool for the job:

sed -n '/re/,$p' file

where re is a regular expression.

Another option is grep's --after-context flag. You need to pass in a number to end at, using wc on the file should give the right value to stop at. Combine this with -n and your match expression.


问:
Unable to access wso2 apim 4.0.0.0 publisher console in Openshift
We are trying to do a container based setup of WSO2 APIM 4.0.0.0 on Openshift and we have installed the apim on it and all the applications are Running and even URL is being connected to Host tried to do curl in terminal of apim-publisher, but unable to access url https://wso2apim-publisher-route-wso2-deploy.apps.cloud.admcoecloud.local/publisher, page is not opening it is being redirected to localhost. All routes are installed as well:
enter image description here

Need suggestion on how to access publishers, carbon and store in this scenario.

答:
You need to change the hostname as in [1]

```<code>[server]
hostname = "am.dev.wso2.com"
</code>```

[1] - https://apim.docs.wso2.com/en/latest/install-and-setup/setup/deployment-best-practices/changing-the-hostname/#changing-the-hostname

Body:
You need to change the hostname as in [1]

[server]
hostname = "am.dev.wso2.com"

[1] - https://apim.docs.wso2.com/en/latest/install-and-setup/setup/deployment-best-practices/changing-the-hostname/#changing-the-hostname


问:
Google Script subtract an entire column from the other
So I'm currently working on a meal planner that looks at my current inventory of ingredients and then looks through the recipes in the spreadsheet to determine what I do/don't need to make those recipes that week and then returns a shopping list. I want to add a button to update that inventory by adding the ingredients from the shopping list. I have the values set up in different columns, but I can't figure out the code to add the values respectively. I have never done any coding, so this is based off of what I found on Google. Here's the code I currently have:

```<code>function AddtoInventory() {

var ss = SpreadsheetApp.getActiveSheet();
  var num1 = ss.getRange('AA3:AA').getValue();
  var num2 = ss.getRange('E3:E').getValue();
  ss.getRange('E3:E').setValue(num1+num2);

}
</code>```

But this just adds the first set of values (AA3+E3) and changes the current inventory for every ingredient to that same value. I want it to add AA3+E3 and change the value of E3 to that sum and then AA4+E4 and change the value of E4 to that sum and so on if that makes sense.

答:
Use getValues() and setValues() instead of getValue() and setValue()

Use .map() for addition:

```<code>function AddtoInventory() {
  const ss = SpreadsheetApp.getActiveSheet(),
    lr = ss.getLastRow(),
    valuesAA = ss.getRange('AA3:AA' + lr).getValues(),
    rngE = ss.getRange('E3:E' + lr),
    valuesE = rngE.getValues(),
    add = (num1,num2) => num1 + num2;
  rngE.setValues(valuesE.map((row, idx) => [add(row[0],valuesAA[idx][0])]));
}
</code>```

Body:
So I'm currently working on a meal planner that looks at my current inventory of ingredients and then looks through the recipes in the spreadsheet to determine what I do/don't need to make those recipes that week and then returns a shopping list. I want to add a button to update that inventory by adding the ingredients from the shopping list. I have the values set up in different columns, but I can't figure out the code to add the values respectively. I have never done any coding, so this is based off of what I found on Google. Here's the code I currently have:

function AddtoInventory() {

var ss = SpreadsheetApp.getActiveSheet();
  var num1 = ss.getRange('AA3:AA').getValue();
  var num2 = ss.getRange('E3:E').getValue();
  ss.getRange('E3:E').setValue(num1+num2);

}

But this just adds the first set of values (AA3+E3) and changes the current inventory for every ingredient to that same value. I want it to add AA3+E3 and change the value of E3 to that sum and then AA4+E4 and change the value of E4 to that sum and so on if that makes sense.

Body:
Use getValues() and setValues() instead of getValue() and setValue()

Use .map() for addition:

function AddtoInventory() {
  const ss = SpreadsheetApp.getActiveSheet(),
    lr = ss.getLastRow(),
    valuesAA = ss.getRange('AA3:AA' + lr).getValues(),
    rngE = ss.getRange('E3:E' + lr),
    valuesE = rngE.getValues(),
    add = (num1,num2) => num1 + num2;
  rngE.setValues(valuesE.map((row, idx) => [add(row[0],valuesAA[idx][0])]));
}


问:
How to place a label on a single row/ on a single line
Two labels get separated by a line. I need to fix that(Look at First Name, Last Name)

```<code><section id="names">
    <B>First Name:</B><input type="text" name="Name" id="name">
    <B>Last Name:</B><input type="text" name="Surname" id="surname">
</section>
</code>```

I don't know if they will help but here I wrote some useless css for it

```<code>#names {
    display:flex;
    flex-direction: row;
    float: left;
}
</code>```

答:
you can use white-space: nowrap;

#names {
    display:flex;
    flex-direction: row;
    float: left;
}

label {
  white-space: nowrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="names">
    <!--use proper tags-->
    <label for="name">
       <b>First Name:</b>
    </label>
    <input type="text" name="Name" id="name">
    <label for="surname">
       <b>Last Name:</b>
    </label>
    <input type="text" name="Surname" id="surname">
</section></code>```

Body:
Two labels get separated by a line. I need to fix that(Look at First Name, Last Name)

    First Name:<input type="text" name="Name" id="name">
    Last Name:<input type="text" name="Surname" id="surname">

I don't know if they will help but here I wrote some useless css for it

#names {
    display:flex;
    flex-direction: row;
    float: left;
}

Body:
you can use white-space: nowrap;

#names {
    display:flex;
    flex-direction: row;
    float: left;
}

label {
  white-space: nowrap;
}

<section id="names">
    <!--use proper tags-->
    <label for="name">
       <b>First Name:</b>
    </label>
    <input type="text" name="Name" id="name">
    <label for="surname">
       <b>Last Name:</b>
    </label>
    <input type="text" name="Surname" id="surname">
</section>


问:
Is there a way to check if a certain port is open on server?
Just as you'd ping an IP of to a server to check if it is up, can we also check if, on that running server, a port is active/open?

this just comes from my head,but can you be more specific in your ping statement?

```<code> `ping 127.0.0.1:7004`
</code>```

I know this command is not allowed, but is there a way to check for this in Linux and Windows?

答:
As telnet is disabled by most corporate customers, i found that powershell command on windows machines for TCP quite useful:
New-Object System.Net.Sockets.TcpClient("server", port)

Body:
Just as you'd ping an IP of to a server to check if it is up, can we also check if, on that running server, a port is active/open?

this just comes from my head,but can you be more specific in your ping statement?

 `ping 127.0.0.1:7004`

I know this command is not allowed, but is there a way to check for this in Linux and Windows?


问:
cannot access viewBinding
Im now use viewBinding with kotlin.

here is my build.gradle

enable ViewBinding and has auto import ViewBinding dependency.

but Android Studio still show error like this

but I can build and run with no problem.

and if I add viewBinding in dependencies,then the error gone.

Does anyone know why?

UPDATE:

I know why. I'm use AndroidX,the IDE say can not access 'android.viewbinding.ViewBinding', but my dependencies is AndroidX, it is 'androidx.viewbinding.ViewBinding', package name changed.

SOLUTION:
add android.useAndroidX=true to project gradle.properties file.

global gradle.properties setting not work,don't know why.

答:
Facing same issue exact error yesterday. Solution work for me is

Step 1- Remove .Idea Folder

Step 2- Close android studio

Step 3- Reopen android studio with same project path (This will genarate new
.Idea folder)

and Error is gone

Making sure

android.useAndroidX=true.  inside gradle.properties file

inside app build.gradle

```<code> buildFeatures {
       viewBinding true
 }
</code>```

Always Use folder structure with samll case latter only class name is allowed to be Uppercase

If you are using any Copyright-Comment at top of xml or Layout tag without variable tag or we can say without any data then remove that and try to clean/rebuild project

Title: cannot access viewBinding

Body:
Facing same issue exact error yesterday. Solution work for me is

Step 1- Remove .Idea Folder

Step 2- Close android studio

Step 3- Reopen android studio with same project path (This will genarate new
.Idea folder)

and Error is gone

Making sure

android.useAndroidX=true.  inside gradle.properties file

inside app build.gradle

 buildFeatures {
       viewBinding true
 }

Always Use folder structure with samll case latter only class name is allowed to be Uppercase

If you are using any Copyright-Comment at top of xml or Layout tag without variable tag or we can say without any data then remove that and try to clean/rebuild project


问:
remove leading zeros (optional) from regex, with max length
I have a validation regex, that checks that the user sent a query param in this format-
an integer with max length of 10 - meaning it can be an integer between 0 and 10, and it can also contain leading zeros (any number of zeros at the beginning), but its optional.

Examples:

String
Result

12345
valid

000001234567890
valid

012345678900
not valid

12345678901
not valid

000000000012547
valid

this is my regex, but it doesn't seem to work

```<code>"^(0+)?|[0-9]{0,10}+$"
</code>```

^(0+)? - this is suppose to be the optional leading zeros at the beginning

[0-9]{0,10}+ - this is suppose to be the integer with the length validation

答:
You can use

^0*[1-9]\d{0,9}$
^0*[1-9][0-9]{0,9}$
```
<p>See the regex demo. <em>Details</em>:</p>
<ul>
<li><code>^</code> - start of string</li>
<li><code>0*</code> - zero or more leading zeros</li>
<li><code>[1-9]</code> - a non-zero digit</li>
<li><code>[0-9]{0,9}</code> - zero to nine digits</li>
<li><code>$</code> - end of string.</li>
</ul>
<p>If you allow an empty string, you can use</p>
<pre class="lang-none prettyprint-override"><code>^(?:0*[1-9][0-9]{0,9})?$
</code>```

where the pattern between anchors is optional.

Body:
I have a validation regex, that checks that the user sent a query param in this format-
an integer with max length of 10 - meaning it can be an integer between 0 and 10, and it can also contain leading zeros (any number of zeros at the beginning), but its optional.

Examples:

String
Result

12345
valid

000001234567890
valid

012345678900
not valid

12345678901
not valid

000000000012547
valid

this is my regex, but it doesn't seem to work

"^(0+)?|[0-9]{0,10}+$"

^(0+)? - this is suppose to be the optional leading zeros at the beginning

[0-9]{0,10}+ - this is suppose to be the integer with the length validation

Body:
You can use

^0*[1-9]\d{0,9}$
^0*[1-9][0-9]{0,9}$

See the regex demo. Details:

^ - start of string

0* - zero or more leading zeros

[1-9] - a non-zero digit

[0-9]{0,9} - zero to nine digits

$ - end of string.

If you allow an empty string, you can use

^(?:0*[1-9][0-9]{0,9})?$

where the pattern between anchors is optional.


问:
Unity Graphics White Screen Problem (Graphics Problem?)
My Unity Editor was showing a blank white screen when trying to start a project. Image here:

This is for the Karting Microgame. When it loads it only displays a blank screen. When clicking the play button there is sound but nothing showing on the screen. This issue also occurs for other Unity3D microgames. I suspect it is an error with the graphics setup or maybe a bug?

Technical details:

Dell G15 laptop

Ubuntu 20.04

Unity version 2020.3.21f1, installed via Unity Hub

NVIDIA Graphics Card (NVIDIA GeForce RTX 3060 GPU)

NVDIA Driver Version 470 (https://packages.ubuntu.com/focal/nvidia-driver-470)

I also have an Intel integrated graphics card on my machine. Tried switching to integrated graphics via the sudo prime-select intel command but it didn't work. Also tried installing Dell G15 graphics drivers from the Dell website but it seems like they only have Windows graphics drivers. Currently the screen is still blank.

Relevant links:

Unity forum discussion, have the exact same problem except for Ubuntu:
https://forum.unity.com/threads/uni...n-problem-might-know-the-real-problem.545441/

Dell graphics driver link, but seems to only have for Windows:
https://www.dell.com/support/home/en-us/product-support/product/g-series-15-5510-laptop/drivers

Tutorial on switching graphics cards. First tried updating my drivers via the ubuntu-drivers command from my existing 470 version to the recommended 510 version, but ran into an error saying my computer holds broken packages. Then tried switching to Intel integrated graphics card via the prime-select command but it caused my GUI to break (had to switch back to NVIDIA via the command line.)
https://www.linuxbabe.com/desktop-linux/switch-intel-nvidia-graphics-card-ubuntu

Any help would be appreciated.

答: Open windows in safe mode and try again also there might be other programs open that are causing the blank screen for example vpn could cause it</p>


问:
Simple Question: How to split date (08-17-2011) into month, day, year? PHP
I have a variable called $orderdate and it is set to a date format like this mm-dd-yyyy.

In PHP how would I split this variable into $month, $day, $year?

Thanks for your help.

答:
Use explode to split string

```<code>list($m,$d,$y)=explode('-',$date);
</code>```

Body:
Use explode to split string

list($m,$d,$y)=explode('-',$date);


问:
How to print a file from VsCode?
I want to send the file I'm currently editing to a printer, like I did in Notepad++ for example.
I havn't found any hint on a print command. Is it not possible ?</p>

答:
I have modified the https://marketplace.visualstudio.com/items?itemName=pdconsec.vscode-print. If you change the values that I have marked in the picture in the extension settings a browser tab opens with the you can then print this also works on the Ipad. It works also with the code-server Version inside a Docker Container.
I put the file on github https://github.com/chrishdx/vsc-print

enter image description here

Title: How to print a file from VsCode?


问:
Mandatory Validation for pathVariable not working
Currently we are adding mandatory validation for pathVariable - having customized message in response.

When @PathVariable is removed, then it is giving 404 error and not going into any of the exceptionHandler. Can you please help to resolve this issue?

```<code>@PostMapping(path = "{id}")
public ResponseEntity<String> migrate(@PathVariable(value = "id")
         @Size(min = 1, max = 64, message = INVALID_FIELD_LENGTH_DETAILS)
         String id) {
    ...
}
</code>```

Error response as below:

```<code>{
 "timestamp": "2022-02-08T15:26:58.649+00:00",
 "status": 404,
 "error": "Not Found",
 "message": "",
 "path": "/migrations"
}
</code>```

答:
javax.validation annotations are not supported yet: https://github.com/spring-projects/spring-framework/issues/11041

You can try several workarounds, e.g.:

```<code>@PostMapping(path = {"", "/{id}"})
public ResponseEntity<String> migrate(@PathVariable(value = "id", required = false)
                                                  Optional<String> id) {
    if (!id.isPresent() && id.get().length() > 64) {
        return new ResponseEntity<>("Validation error", HttpStatus.BAD_REQUEST);
    } else {
        return new ResponseEntity<>(id.orElse(""), HttpStatus.OK);
    }

}
</code>```

Body:
Currently we are adding mandatory validation for pathVariable - having customized message in response.

When @PathVariable is removed, then it is giving 404 error and not going into any of the exceptionHandler. Can you please help to resolve this issue?

@PostMapping(path = "{id}")
public ResponseEntity<String> migrate(@PathVariable(value = "id")
         @Size(min = 1, max = 64, message = INVALID_FIELD_LENGTH_DETAILS)
         String id) {
    ...
}

Error response as below:

{
 "timestamp": "2022-02-08T15:26:58.649+00:00",
 "status": 404,
 "error": "Not Found",
 "message": "",
 "path": "/migrations"
}

Body:
javax.validation annotations are not supported yet: https://github.com/spring-projects/spring-framework/issues/11041

You can try several workarounds, e.g.:

@PostMapping(path = {"", "/{id}"})
public ResponseEntity<String> migrate(@PathVariable(value = "id", required = false)
                                                  Optional<String> id) {
    if (!id.isPresent() && id.get().length() > 64) {
        return new ResponseEntity<>("Validation error", HttpStatus.BAD_REQUEST);
    } else {
        return new ResponseEntity<>(id.orElse(""), HttpStatus.OK);
    }

}


问:
How to run only a test suite with the connectedAndroidTest command
I am having problems with timeouts running my UI tests in circle ci since the command connectedAndroidTest is taking more than 10 minutes to run.

So I am trying to split them into test suits and run each suite at a time.

I found how to create suites for my android tests here: https://developer.android.com/reference/junit/framework/TestSuite.html

But I can't find how to run them with the connectedAndroidTest command.

答:
To add to @jonathanrz answer:

Run tests by class:

./gradlew app:connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.class= com.example.app.MyTestClass

Run tests by method:

./gradlew app:connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.class= com.example.app.MyTestClass#myTestMethod

Btw: You can add further arguments to your tests by adding:

-Pandroid.testInstrumentationRunnerArguments.foo="My\ Extra\ Info

Just note how you have to escape spaces here if they exist


问:
I can't get the id of the selected item via checkbox with IE
I'm having trouble retrieving the id of the selected objects via checkbox.

I have not put all the code because it is too long, I have only entered what is needed.

allart.Items.forEach(function (item) {
                    let child = document.createElement("tr");
                    child.innerHTML =
                        '' + item.id + '	' + item.title + '	' + item.date + '	<input type="checkbox" id="myCheck" data-item-id=+item.id+>	';
                    table.appendChild(child);```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="my-table" width="90%">
        <tr>
            <th>Id</th>
            <th>Title</th>
            <th>Date</th>
            <th>Selection</th>
        </tr>

    </table>

    <br><br>

        <input type="button" value="GetID" onclick="getId" /></code>```

function getId() {
            var cbs = document.querySelectorAll('#my-table input[type="checkbox"]:checked');
            console.log(cbs.length);
            const ids = Array.from(cbs).map(function (cb) { cb.getAttribute("data-item-id") });
            console.log(ids);
            for (let i = 0; i < ids.length; i++) {
                deleteRow(ids[i]);
            }
        }```

I can't get the ids variable.

ids return length 1 but data-item-id is undefined.

答:
Just change your const ids declaration to the following:

```<code>            ids = []
            cbs.forEach((checkedBox) => {
                ids.push(checkedBox.getAttribute("data-item-id"))
            })
</code>```

(Fiddle here: https://jsfiddle.net/3madc64u/1/)

Body:
I'm having trouble retrieving the id of the selected objects via checkbox.

I have not put all the code because it is too long, I have only entered what is needed.

allart.Items.forEach(function (item) {
                    let child = document.createElement("tr");
                    child.innerHTML =
                        '' + item.id + '	' + item.title + '	' + item.date + '	<input type="checkbox" id="myCheck" data-item-id=+item.id+>	';
                    table.appendChild(child);

            Id
            Title
            Date
            Selection

        <input type="button" value="GetID" onclick="getId" />

function getId() {
            var cbs = document.querySelectorAll('#my-table input[type="checkbox"]:checked');
            console.log(cbs.length);
            const ids = Array.from(cbs).map(function (cb) { cb.getAttribute("data-item-id") });
            console.log(ids);
            for (let i = 0; i < ids.length; i++) {
                deleteRow(ids[i]);
            }
        }

I can't get the ids variable.

ids return length 1 but data-item-id is undefined.

Body:
Just change your const ids declaration to the following:

            ids = []
            cbs.forEach((checkedBox) => {
                ids.push(checkedBox.getAttribute("data-item-id"))
            })

(Fiddle here: https://jsfiddle.net/3madc64u/1/)


问:
WEB API C# REPONSE HANGS (HttpWebResponse)http.GetResponse()
Am doing an WEB API .net 4.62 that /Token with username password and grant_type to get access token once its generated i woul like to get it value of access_token.This does not happen but when i take the same code to a windows form aplication I am able to get it what could be wrong. It hangs on    using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())</p>
```<code>try
            {
                string myParameters = "username=value1&password=value2&grant_type=password";
                string baseAddress = "http://localhost:50128/token";
                var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
                http.Accept = "application/x-www-form-urlencoded";
                http.ContentType = "application/x-www-form-urlencoded";
                http.Method = "POST";

                string parsedContent = myParameters;
                ASCIIEncoding encoding = new ASCIIEncoding();
                Byte[] bytes = encoding.GetBytes(parsedContent);
                Stream newStream = http.GetRequestStream();
                newStream.Write(bytes, 0, bytes.Length);
                newStream.Close();
                http.ServicePoint.Expect100Continue = false;
                http.ProtocolVersion = HttpVersion.Version11;
                http.Timeout = 2000;
               using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
                {
                    var stream = response.GetResponseStream();
                    var sr = new StreamReader(stream);
                    var content = sr.ReadToEnd();
                    JObject json = JObject.Parse(content);
                    var message = json.SelectToken("access_token").ToString();
                    Console.Write(message);
                }
            }

            catch (Exception ex)
            {
                //Handle the exceptions that could appear
            }
</code>```

答:
change the using block like this and also convert your function to "async".

using (HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync(http.BeginGetResponse, http.EndGetResponse, null).ConfigureAwait(false))

let me know if it works.

Body:
Am doing an WEB API .net 4.62 that /Token with username password and grant_type to get access token once its generated i woul like to get it value of access_token.This does not happen but when i take the same code to a windows form aplication I am able to get it what could be wrong. It hangs on    using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())

try
            {
                string myParameters = "username=value1&password=value2&grant_type=password";
                string baseAddress = "http://localhost:50128/token";
                var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
                http.Accept = "application/x-www-form-urlencoded";
                http.ContentType = "application/x-www-form-urlencoded";
                http.Method = "POST";

                string parsedContent = myParameters;
                ASCIIEncoding encoding = new ASCIIEncoding();
                Byte[] bytes = encoding.GetBytes(parsedContent);
                Stream newStream = http.GetRequestStream();
                newStream.Write(bytes, 0, bytes.Length);
                newStream.Close();
                http.ServicePoint.Expect100Continue = false;
                http.ProtocolVersion = HttpVersion.Version11;
                http.Timeout = 2000;
               using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
                {
                    var stream = response.GetResponseStream();
                    var sr = new StreamReader(stream);
                    var content = sr.ReadToEnd();
                    JObject json = JObject.Parse(content);
                    var message = json.SelectToken("access_token").ToString();
                    Console.Write(message);
                }
            }

            catch (Exception ex)
            {
                //Handle the exceptions that could appear
            }


问:
C# Application Multibyte vs. Unicode
I have a C# application which imports a 3rd Party DLL using DLL Import.

I keep getting Unable to find entry point error.     This is a screen shot of our log4Net

Log4Net Screen Shot

I used dependency walker to see the exact signature of the function and it appears to be correct:
Dependency Walker Screen Shot

This 3rd part DLL is written in C++.   The vendor keeps saying that the application settings in C# needs to look like this.
Vendor Screen Shot

I don't understand what this means for a C# application.    The vendor keeps telling me that I am building a Multi Byte Application.  I don't understand where is the multi byte settings for a C# application.

PS:  I am sorry I am unable to post code here because of the environment I work in.

答:
Check the declaration of the imported function. Probably it should be something like this:</p>
```<code>[DllImport("ITCtrl2005U.dll", EntryPoint = "SetParmFile",
  SetLastError = true,
  CharSet = CharSet.Ansi,
  ExactSpelling = true,
  BestFitMapping = true,
  CallingConvention = CallingConvention.Cdecl)]
static extern bool SetParmFile(string pathName);
</code>```

Title: C# Application Multibyte vs. Unicode

Body:
Check the declaration of the imported function. Probably it should be something like this:

[DllImport("ITCtrl2005U.dll", EntryPoint = "SetParmFile",
  SetLastError = true,
  CharSet = CharSet.Ansi,
  ExactSpelling = true,
  BestFitMapping = true,
  CallingConvention = CallingConvention.Cdecl)]
static extern bool SetParmFile(string pathName);


问:
Undefined type 'App\Http\Middleware\Auth'
i am new to laravel and i am trying to make an admin dashboard but in the adminmiddleware file i am having this error with both of my Auth</p>
```<code>Undefined type 'App\Http\Middleware\Auth'
</code>```
```<code>namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            if (Auth::user()->role_as == '1') {
                return $next($request);
            } else {
                return redirect('/home')->with('status', 'Access denied! as you are not an admin');
            }
        } else {
            return redirect('/home')->with('status', ' pleaselogin first');
        }
    }
}
</code>```

答:
either use the Auth facade from the global namespace: \Auth,

or (better) add its FQCN in your use declarations:
use Illuminate\Support\Facades\Auth;

Body:
i am new to laravel and i am trying to make an admin dashboard but in the adminmiddleware file i am having this error with both of my Auth

Undefined type 'App\Http\Middleware\Auth'

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            if (Auth::user()->role_as == '1') {
                return $next($request);
            } else {
                return redirect('/home')->with('status', 'Access denied! as you are not an admin');
            }
        } else {
            return redirect('/home')->with('status', ' pleaselogin first');
        }
    }
}


问:
Burp Interception does not work for localhost in Chrome
I can't intercept requests made by Chrome version 73.0.3683.86 to my localhost site.

Local host site is running on IIS on http://127.0.0.3:80

Burp proxy lister is default one on 127.0.0.1:8080

Interception rules are default one as well

In my LAN settings, "Bypass proxy server for local addresses" is not enabled

When Interception is turned ON and I reload page in Chrome browser, no request is "caught" by Burp, my local site loads and only the external requests are intercepted, such as loading external scripts from CDN.

Also under "Proxy" > "HTTP History" there is only request to external sites, and all requests to http://127.0.0.3:80 are not recorded.

When I reload same page by Internet Explorer 11, initial GET request is intercepted by Burp, as expected. Also "Proxy" > "HTTP History" shows all the requests to local site http://127.0.0.3:80

What is the problem with the Chrome? Thanks!

答:
It helped me

I turned on this settings

Body:
It helped me

I turned on this settings


问:
Python: setting default side_effect with create_autospec on class instance
I am trying to use side_effect with unittest.mock.create_autospec on class to set default instance call behavior to raise NotImplementedError.

The problem I am facing is:

I do not want exception to be raise on class __init__.

I do not want to set explicitly all my methods side effect.

I want to use a pytest.fixture in order to make my mock reusable through various tests.

Here a code sample of what I am trying to achieve.

# module.py

class MyClass:
    def __init__(self, value):
        self.value = value

    def compute(self):
        return self.value

def foo():
    instance = MyClass(42)
    return instance.compute()
```
<pre class="lang-py prettyprint-override"><code># test_module.py

from unittest.mock import create_autospec
import module
import pytest

@pytest.fixture(autouse=True)
def my_class(monkeypatch):
    # Help me HERE to set side_effect, bellow tests will not work with this settings.
    spec_cls = create_autospec(module.MyClass, side_effect=NotImplementedError)

    monkeypatch.setattr(module, "MyClass", spec_cls)

    return spec_cls("<whatever>")

def test_foo():
    with pytest.raises(NotImplementedError):
        module.foo()

def test_bar(my_class):
    my_class.compute.return_value = 24
    assert module.foo() == 24
</code>```

答:
Not need to use autospec :

import unittest.mock as mocking

import pytest

import so71018132_module as module

@pytest.fixture(autouse=True)
def fake_my_class():
    with mocking.patch.object(module.MyClass, "compute") as compute_mock:
        compute_mock.side_effect = NotImplementedError  # default behaviour
        yield compute_mock

def test_foo():
    with pytest.raises(NotImplementedError):
        module.foo()

def test_bar(fake_my_class):
    fake_my_class.side_effect = [24]
    # or alternatively, clear the side_effect then set a return_value :
    # fake_my_class.side_effect = None
    # fake_my_class.return_value = 24
    assert module.foo() == 24
```

passes the 2 tests.

I completely changed the fixture to use unittest.mock.object.patch on the compute method of MyClass so just that is mocked, the rest of the class is used ordinarily.
Also, I had to slightly adjust the test_bar code to correctly alter the mock behavior.

Body:
I am trying to use side_effect with unittest.mock.create_autospec on class to set default instance call behavior to raise NotImplementedError.

The problem I am facing is:

I do not want exception to be raise on class __init__.

I do not want to set explicitly all my methods side effect.

I want to use a pytest.fixture in order to make my mock reusable through various tests.

Here a code sample of what I am trying to achieve.

# module.py

class MyClass:
    def __init__(self, value):
        self.value = value

    def compute(self):
        return self.value

def foo():
    instance = MyClass(42)
    return instance.compute()

# test_module.py

from unittest.mock import create_autospec
import module
import pytest

@pytest.fixture(autouse=True)
def my_class(monkeypatch):
    # Help me HERE to set side_effect, bellow tests will not work with this settings.
    spec_cls = create_autospec(module.MyClass, side_effect=NotImplementedError)

    monkeypatch.setattr(module, "MyClass", spec_cls)

    return spec_cls("<whatever>")

def test_foo():
    with pytest.raises(NotImplementedError):
        module.foo()

def test_bar(my_class):
    my_class.compute.return_value = 24
    assert module.foo() == 24

Body:
Not need to use autospec :

import unittest.mock as mocking

import pytest

import so71018132_module as module

@pytest.fixture(autouse=True)
def fake_my_class():
    with mocking.patch.object(module.MyClass, "compute") as compute_mock:
        compute_mock.side_effect = NotImplementedError  # default behaviour
        yield compute_mock

def test_foo():
    with pytest.raises(NotImplementedError):
        module.foo()

def test_bar(fake_my_class):
    fake_my_class.side_effect = [24]
    # or alternatively, clear the side_effect then set a return_value :
    # fake_my_class.side_effect = None
    # fake_my_class.return_value = 24
    assert module.foo() == 24

passes the 2 tests.

I completely changed the fixture to use unittest.mock.object.patch on the compute method of MyClass so just that is mocked, the rest of the class is used ordinarily.
Also, I had to slightly adjust the test_bar code to correctly alter the mock behavior.


问:
How to rename a folder and its contents at a time, according to the input, using cocoa?
I have a folder as 'rootfolder', There are some other subfolders as (rat, cat, hat) inside the 'rootfolder'. I want to rename the matching character. For example if user want to replace 't' with 'z'.Then the 'rootfolder' renamed in 'roozfolder' similarly subfolders will be as (raz, caz, haz)..

Thanks in advance..

答:
You need a recursive function to deal with all the subfolders of subfolders. Here's some pseudocode:

```<code>function recursive_rename(current_directory)
    for each item in current_directory
        if item is a directory
            for each subitem in item
                recursive_rename(subitem)
            rename(item)
</code>```

I'm assuming from your description that you only want to rename directories, right? Not normal items? If not, it would just be

```<code>function recursive_rename(current_directory)
    for each item in current_directory
        for each subitem in item
            recursive_rename(subitem)
        rename(item)
</code>```

Body:
You need a recursive function to deal with all the subfolders of subfolders. Here's some pseudocode:

function recursive_rename(current_directory)
    for each item in current_directory
        if item is a directory
            for each subitem in item
                recursive_rename(subitem)
            rename(item)

I'm assuming from your description that you only want to rename directories, right? Not normal items? If not, it would just be

function recursive_rename(current_directory)
    for each item in current_directory
        for each subitem in item
            recursive_rename(subitem)
        rename(item)


问:
Tone.js problems with changing Tone.Polysynth
In Tone.js I have made a class that creates a synth instance where .play() is called in a sequencer function, thereby playing a sound. In the class below there are absolutely no problems when this.synth in updateSynthType is a monophonic Tone.Synth, but the whole thing breaks when it is Tone.Polysynth and I receive the following error when trying to call updateSynthType.

```<code>Uncaught Error: Synth was already disposed
    at ti (Tone.js:1)
    at ra._scheduleEvent (Tone.js:21)
    at Object.callback (Tone.js:21)
    at Gi._timeoutLoop (Tone.js:21)
    at Gi.emit (Tone.js:7)
</code>```

I don't understand why this never happens with a regular Tone.Synth but when I try to change a Tone.PolySynth an error appears. I am trying to update the settings to change between the type of polysynth (e.g. Synth, AMSynth, MetalSyth etc). How can I stop this problem? Why does this class only work for a regular Tone.Synth? Is there a better way of updating the PolySynth type in this class?

Here is the class in question:

```<code>class PolyInstrument {
  constructor(){
    this.synth = null
    this.gain = new Tone.Gain()
    this.gain.toDestination()
  }

  play(note = null, beat, time = null){
    if (this.synth){
      if (note === null){
        time ? this.synth.triggerAttackRelease(beat, time) : this.synth.triggerAttackRelease(beat)
      } else {
        time ? this.synth.triggerAttackRelease(note, beat, time) : this.synth.triggerAttackRelease(note, beat)
      }
    } else {
      alert('error: no synth')
    }
  }

  get defaultSettings(){
    return {
      Synth: {
        oscillator: {
          type: 'triangle'
        },
        envelope: {
          attack: 0.005,
          decay: 0.1,
          sustain: 0.3,
          release: 1
        }
      },
      AMSynth: {
        harmonicity: 3 ,
        detune: 0 ,
        oscillator: {
          type: 'sine'
        },
        envelope: {
          attack: 0.01 ,
          decay: 0.01 ,
          sustain: 1 ,
          release: 0.5
        },
        modulation: {
          type: 'square'
        },
        modulationEnvelope: {
          attack: 0.5 ,
          decay: 0 ,
          sustain: 1 ,
          release: 0.5
        }
      }
    }
  }

  updateSynthType(synthType){
    if (this.synth){
      this.synth.disconnect(this.gain)
      this.synth.dispose()
    }
    let settings = this.defaultSettings[synthType] || {}
    this.synth = new Tone.PolySynth(Tone[synthType], settings)
    this.synth.connect(this.gain)
    this.play()
  }
}
</code>```

Thanks for reading.

答:
I was able to fix this by clearing out the context timeline before disposing:</p>
```<code>synth.context._timeouts.cancel(0);
synth.dispose();
</code>```

Body:
In Tone.js I have made a class that creates a synth instance where .play() is called in a sequencer function, thereby playing a sound. In the class below there are absolutely no problems when this.synth in updateSynthType is a monophonic Tone.Synth, but the whole thing breaks when it is Tone.Polysynth and I receive the following error when trying to call updateSynthType.

Uncaught Error: Synth was already disposed
    at ti (Tone.js:1)
    at ra._scheduleEvent (Tone.js:21)
    at Object.callback (Tone.js:21)
    at Gi._timeoutLoop (Tone.js:21)
    at Gi.emit (Tone.js:7)

I don't understand why this never happens with a regular Tone.Synth but when I try to change a Tone.PolySynth an error appears. I am trying to update the settings to change between the type of polysynth (e.g. Synth, AMSynth, MetalSyth etc). How can I stop this problem? Why does this class only work for a regular Tone.Synth? Is there a better way of updating the PolySynth type in this class?

Here is the class in question:

class PolyInstrument {
  constructor(){
    this.synth = null
    this.gain = new Tone.Gain()
    this.gain.toDestination()
  }

  play(note = null, beat, time = null){
    if (this.synth){
      if (note === null){
        time ? this.synth.triggerAttackRelease(beat, time) : this.synth.triggerAttackRelease(beat)
      } else {
        time ? this.synth.triggerAttackRelease(note, beat, time) : this.synth.triggerAttackRelease(note, beat)
      }
    } else {
      alert('error: no synth')
    }
  }

  get defaultSettings(){
    return {
      Synth: {
        oscillator: {
          type: 'triangle'
        },
        envelope: {
          attack: 0.005,
          decay: 0.1,
          sustain: 0.3,
          release: 1
        }
      },
      AMSynth: {
        harmonicity: 3 ,
        detune: 0 ,
        oscillator: {
          type: 'sine'
        },
        envelope: {
          attack: 0.01 ,
          decay: 0.01 ,
          sustain: 1 ,
          release: 0.5
        },
        modulation: {
          type: 'square'
        },
        modulationEnvelope: {
          attack: 0.5 ,
          decay: 0 ,
          sustain: 1 ,
          release: 0.5
        }
      }
    }
  }

  updateSynthType(synthType){
    if (this.synth){
      this.synth.disconnect(this.gain)
      this.synth.dispose()
    }
    let settings = this.defaultSettings[synthType] || {}
    this.synth = new Tone.PolySynth(Tone[synthType], settings)
    this.synth.connect(this.gain)
    this.play()
  }
}

Thanks for reading.

Body:
I was able to fix this by clearing out the context timeline before disposing:

synth.context._timeouts.cancel(0);
synth.dispose();


问:
Onclick function in js not working properly
onclick function to change an image once clicked but its giving me an error in Js saying unexpected else please I need an assistance Im a newbie in programming

function changeImage(){
    let a=document.getElementById("changeimg").src
        if (a==="img/save.png") {
            return a = "img/saveblack.png"
        }

}
 else{
    return a= "img/save.png"
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code></div>

                <div class="wrapper_center">
                    <img src="img/profilepix.jpg">
                </div>

                <div class="wrapper_bottom">
                    <div class="reaction_wrapper">
                        <img src="img/heart.png">
                        <img src="img/messagereaction.png">
                        <img src="img/message.png">
                        <img src="img/save.png" id="changeimg" onclick="changeImage()">
                    </div></code>```

答:
The curly bracket on line 7 should be moved to below the else statement. The way it currently is, you're closing the function, and then have an else clause not tied with an if.

Also, setting a to element.src will just copy the value of element.src to the variable a, so if you change a at all it won't change element.src at all. You can fix this by saving a as element so that you can modify the properties, since objects (not primitives) are copied by reference and not value.

function changeImage() {
  let a = document.getElementById("changeimg");

  if (a.src === "img/save.png") {
    return a.src "img/saveblack.png"
  } else {
    return a.src = "img/save.png"
  }
}```


问:
Importing files outside my App.js - React Native
I'm new to React Native and I'm currently trying to create a cookbook application with Expo. And I'm looking for a solution to shorten my importing in my App.js since they're all in the same folder. Here it looks like:

```<code>import Ampalaya from "./recipes/Ampalaya";
import AdobongSitaw from "./recipes/AdobongSitaw";
import BananaQue from "./recipes/BananaQue";
import Bibingka from "./recipes/Bibingka";
import BukoPie from "./recipes/BukoPie";
</code>```

And this is how I use these all I imported:

```<code><NavigationContainer>
        <StatusBar style="auto" />
        <Stack.Navigator>

          <Stack.Screen
            name="Ampalaya"
            component={Ampalaya}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="AdobongSitaw"
            component={AdobongSitaw}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="BananaQue"
            component={BananaQue}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="Bibingka"
            component={Bibingka}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="BukoPie"
            component={BukoPie}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>
</code>```

答:
As an option you can create index.js file in "Screens" folder, then in file make all exports like:

```<code>// index.js
export * from './Home'

// Home.js
import react from 'react'
import {View, Text} from 'react-native'

export const Home = () => {
  return (
   <View><Text> Home </Text></View>
  )
}

export default Home

// App.js
import {Home, Banana, etc} from './Screens'
</code>```

Or import like:

```<code>// Home.js
import { StyleSheet, Text, View } from 'react-native';
import React from 'react';

export const Home = () => {
  return (
    <View>
      <Text>Home</Text>
    </View>
  );
};

export default Home;

const styles = StyleSheet.create({});

//index.js
export * from './Home'
export * from './Banana'`

App.js:

import React from 'react';
import * as Screens from './screens'

const App = () => {
  return (
      <Screens.Home />
  );
};

export default App;
</code>```

Body:
I'm new to React Native and I'm currently trying to create a cookbook application with Expo. And I'm looking for a solution to shorten my importing in my App.js since they're all in the same folder. Here it looks like:

import Ampalaya from "./recipes/Ampalaya";
import AdobongSitaw from "./recipes/AdobongSitaw";
import BananaQue from "./recipes/BananaQue";
import Bibingka from "./recipes/Bibingka";
import BukoPie from "./recipes/BukoPie";

And this is how I use these all I imported:

<NavigationContainer>
        <StatusBar style="auto" />
        <Stack.Navigator>

          <Stack.Screen
            name="Ampalaya"
            component={Ampalaya}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="AdobongSitaw"
            component={AdobongSitaw}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="BananaQue"
            component={BananaQue}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="Bibingka"
            component={Bibingka}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
          <Stack.Screen
            name="BukoPie"
            component={BukoPie}
            options={{
              headerRight: (props) => <Logo {...props} />,
              headerTitle: "Back",
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>

Body:
As an option you can create index.js file in "Screens" folder, then in file make all exports like:

// index.js
export * from './Home'

// Home.js
import react from 'react'
import {View, Text} from 'react-native'

export const Home = () => {
  return (
   <View><Text> Home </Text></View>
  )
}

export default Home

// App.js
import {Home, Banana, etc} from './Screens'

Or import like:

// Home.js
import { StyleSheet, Text, View } from 'react-native';
import React from 'react';

export const Home = () => {
  return (
    <View>
      <Text>Home</Text>
    </View>
  );
};

export default Home;

const styles = StyleSheet.create({});

//index.js
export * from './Home'
export * from './Banana'`

App.js:

import React from 'react';
import * as Screens from './screens'

const App = () => {
  return (
      <Screens.Home />
  );
};

export default App;


问:
Shopify embedded admin app with App Bridge, hosted as static files
Is it possible to host the Shopify admin app's frontend part on a CDN/static-like on S3 bucket?

I want to use the NestJS framework for the API part and in a separate codebase (and under different domain) have frontend of the admin panel in React (React Admin). However, in the Shopify App Setup I can only provide a single app url.

If I provide frontend, it doesn't go through API and is missing quite some functionality (like checking authentication, installing, etc.).

If I provide API's base url, then I get an error that origins don't match when redirected to frontend.

Only solution I see is creating a proxy under NestJS after authentication, but then it doesn't make sense to host it under CDN anymore. Is there an alternative or we're stuck with what Shopify allows us to do? (I really do hope I'm wrong or missing something)

答:
Shopify App Setup asks for the homepage of your app.
The "API part" will need the authentication code that can be given by the frontend (or stored in configuration if it's a custom app).

So you should use the frontend page in the setup app and build the backend as you wish.

So the answer is yes, you can put your frontend on an S3 if you want. But you will need the authentication code that Shopify will pass you when you connect.


问:
split cell at special character if comma found after first word
hi i've got some budget data with names and titles that read "Last, First - Title" and other rows in same column position that read "anything really - ,asd;flkajsd". I'd like to split the column IF first word ends in a "," at the "-" position that follows it.

ive tried this:

```<code>C22$ITEM2 <- ifelse(grepl(",", C22$ITEM), C22$ITEM,  NA)
test <- str_split_fixed(C22$ITEM2, "-", 2)
C22 <- cbind(C22, test)
</code>```

but i'm getting other cells with commas elsewhere, need to limit to just "if first word ends in comma"

答:
We may use extract to do this - capture the regex pattern as two groups ((...)) where the first group would return word (\\w+) from the start (^) of the string followed by a ,, zero or more space (\\s*), another word (\\w+), then the - (preceding or succeeding zero or more space and the second capture group with the word (\\w+) before the end ($) of the string

```<code>library(tidyr)
library(dplyr)
extract(C22, ITEM, into = c("Name", "Title"),
      "^(\\w+,\\s*\\w+)\\s*-\\s*(\\w+)$") %>%
   mutate(Name = coalesce(Name, ITEM), .keep = 'unused')
</code>```

NOTE: The mutate is added in case the regex didn't match and return NA elements, we coalesce with the original column to return the value that corresponds to NA

Body:
hi i've got some budget data with names and titles that read "Last, First - Title" and other rows in same column position that read "anything really - ,asd;flkajsd". I'd like to split the column IF first word ends in a "," at the "-" position that follows it.

ive tried this:

C22$ITEM2 <- ifelse(grepl(",", C22$ITEM), C22$ITEM,  NA)
test <- str_split_fixed(C22$ITEM2, "-", 2)
C22 <- cbind(C22, test)

but i'm getting other cells with commas elsewhere, need to limit to just "if first word ends in comma"

Body:
We may use extract to do this - capture the regex pattern as two groups ((...)) where the first group would return word (\\w+) from the start (^) of the string followed by a ,, zero or more space (\\s*), another word (\\w+), then the - (preceding or succeeding zero or more space and the second capture group with the word (\\w+) before the end ($) of the string

library(tidyr)
library(dplyr)
extract(C22, ITEM, into = c("Name", "Title"),
      "^(\\w+,\\s*\\w+)\\s*-\\s*(\\w+)$") %>%
   mutate(Name = coalesce(Name, ITEM), .keep = 'unused')

NOTE: The mutate is added in case the regex didn't match and return NA elements, we coalesce with the original column to return the value that corresponds to NA


问:
SQL GROUP BY and HAVING but have results include column not included in GROUP BY to provide more detail?
Sample data:

Week
Client
Amount

1
A
20

1
B
20

2
A
20

2
B
10

3
C
40

I want a query where if the total for the week is 40 or more, include those rows in the result set, but ALSO include the Client.

So the results would look something like this:

Week
Client
Amount

1
A
20

1
B
20

3
C
40

I am prepared to do this via two queries and EXISTS, but I was checking to see if there was something more elegant. I've tried using a GROUP BY and HAVING but no such luck as I don't think I can use having on the aggregate but also show the client detail.

答:
You can do:</p>
```<code>select *
from (
  select *, sum(amount) over(partition by week) as sa
  from t
) x
where sa >= 40
</code>```

Body:
You can do:

select *
from (
  select *, sum(amount) over(partition by week) as sa
  from t
) x
where sa >= 40


问:
deploy telegram bot on heroku
I want to learn how to create telegram bot but I have trouble on deploying it on the cloud. I kept getting this error on Heroku log

```<code>2021-11-01T16:51:38.071120+00:00 heroku[router]: at=info method=POST path="/2xxxxxXXxx:AAAAAAAAxxxx-xxx" host=xxxx-Xxxx-xxxx.herokuapp.com request_id=ed02154c-af96-44b7-af50-0ad1d8891f8f fwd="91.108.6.83" dyno=web.1 connect=0ms service=1ms status=500 bytes=404 protocol=https

2021-11-01T16:51:38.076047+00:00 app[web.1]: TypeError: bot.processUpdate is not a function

2021-11-01T16:51:38.076210+00:00 app[web.1]:     at /app/index.js:18:6
</code>```

here is my index.js

```<code>// DEPENDENCIES
const express = require('express');
require('dotenv').config();

const bot = require('./bot');

const app = express();

const port = process.env.PORT || 5000;

app.use(express.json());

app.get('/', (req, res) => {
    res.status(200).json({ message: 'Hello from the Bot API.' });
});
// TELEGRAM WEBHOOK - https://core.telegram.org/bots/api#setwebhook
app.post(`/${process.env.TELEGRAM_TOKEN}`, (req, res) => {
    bot.processUpdate(req.body);
    res.status(200).json({ message: 'ok' });
});

app.listen(port, () => {
    console.log(`\n\nServer running on port ${port}.\n\n`);
});
</code>```

and here is my bot.js

```<code>//dependency
const TelegramBot = require('node-telegram-bot-api');
require('dotenv').config();
const axios = require('axios');
const fs = require('fs');

//bot token
const token = process.env.TELEGRAM_TOKEN;
//initialize bot
var bot;

// if production env, we use webhooks
// https://core.telegram.org/bots/api#setwebhook
// https://github.com/yagop/node-telegram-bot-api/blob/release/doc/api.md#TelegramBot+setWebHook
if (process.env.NODE_ENV === 'production') {
    bot = new TelegramBot(token);
    bot.setWebHook(process.env.HEROKU_URL + bot.token);
    console.log('**** BOT initiated ***** ');
} else {
    // otherwise, we use polling
    // differences between webhooks and polling:
    // https://core.telegram.org/bots/webhooks
    // https://stackoverflow.com/questions/40033150/telegram-bot-getupdates-vs-setwebhook
    bot = new TelegramBot(token, { polling: true });
}

console.log(`Bot started in the ${process.env.NODE_ENV} mode`);

bot.onText(/^\/say_hello (.+)$/, function (msg, match) {
    var name = match[1];
    bot.sendMessage(msg.chat.id, 'Hello ' + name + '!').then(function () {
        // reply sent!
    });
});

bot.onText(/^\/sum((\s+\d+)+)$/, function (msg, match) {
    var result = 0;
    match[1].trim().split(/\s+/).forEach(function (i) {
        result += (+i || 0);
    })
    bot.sendMessage(msg.chat.id, result).then(function () {
        // reply sent!
    });
});
</code>```

everything works flawlessly on local. I thought the problem was with the webhook URL at first, after spending hours I realized the log said something else. I'm using https://github.com/yagop/node-telegram-bot-api and the documentation definitely still have processUpdate written but I have no idea how to test it. Since deploying on local works maybe the problem is somewhere else that I have no idea about.

答:
You need to exports bot defined in bot.js adding to that module next line

```<code>module.exports = bot
</code>```

Title: deploy telegram bot on heroku

Body:
I want to learn how to create telegram bot but I have trouble on deploying it on the cloud. I kept getting this error on Heroku log

2021-11-01T16:51:38.071120+00:00 heroku[router]: at=info method=POST path="/2xxxxxXXxx:AAAAAAAAxxxx-xxx" host=xxxx-Xxxx-xxxx.herokuapp.com request_id=ed02154c-af96-44b7-af50-0ad1d8891f8f fwd="91.108.6.83" dyno=web.1 connect=0ms service=1ms status=500 bytes=404 protocol=https

2021-11-01T16:51:38.076047+00:00 app[web.1]: TypeError: bot.processUpdate is not a function

2021-11-01T16:51:38.076210+00:00 app[web.1]:     at /app/index.js:18:6

here is my index.js

// DEPENDENCIES
const express = require('express');
require('dotenv').config();

const bot = require('./bot');

const app = express();

const port = process.env.PORT || 5000;

app.use(express.json());

app.get('/', (req, res) => {
    res.status(200).json({ message: 'Hello from the Bot API.' });
});
// TELEGRAM WEBHOOK - https://core.telegram.org/bots/api#setwebhook
app.post(`/${process.env.TELEGRAM_TOKEN}`, (req, res) => {
    bot.processUpdate(req.body);
    res.status(200).json({ message: 'ok' });
});

app.listen(port, () => {
    console.log(`\n\nServer running on port ${port}.\n\n`);
});

and here is my bot.js

//dependency
const TelegramBot = require('node-telegram-bot-api');
require('dotenv').config();
const axios = require('axios');
const fs = require('fs');

//bot token
const token = process.env.TELEGRAM_TOKEN;
//initialize bot
var bot;

// if production env, we use webhooks
// https://core.telegram.org/bots/api#setwebhook
// https://github.com/yagop/node-telegram-bot-api/blob/release/doc/api.md#TelegramBot+setWebHook
if (process.env.NODE_ENV === 'production') {
    bot = new TelegramBot(token);
    bot.setWebHook(process.env.HEROKU_URL + bot.token);
    console.log('**** BOT initiated ***** ');
} else {
    // otherwise, we use polling
    // differences between webhooks and polling:
    // https://core.telegram.org/bots/webhooks
    // https://stackoverflow.com/questions/40033150/telegram-bot-getupdates-vs-setwebhook
    bot = new TelegramBot(token, { polling: true });
}

console.log(`Bot started in the ${process.env.NODE_ENV} mode`);

bot.onText(/^\/say_hello (.+)$/, function (msg, match) {
    var name = match[1];
    bot.sendMessage(msg.chat.id, 'Hello ' + name + '!').then(function () {
        // reply sent!
    });
});

bot.onText(/^\/sum((\s+\d+)+)$/, function (msg, match) {
    var result = 0;
    match[1].trim().split(/\s+/).forEach(function (i) {
        result += (+i || 0);
    })
    bot.sendMessage(msg.chat.id, result).then(function () {
        // reply sent!
    });
});

everything works flawlessly on local. I thought the problem was with the webhook URL at first, after spending hours I realized the log said something else. I'm using https://github.com/yagop/node-telegram-bot-api and the documentation definitely still have processUpdate written but I have no idea how to test it. Since deploying on local works maybe the problem is somewhere else that I have no idea about.

Body:
You need to exports bot defined in bot.js adding to that module next line

module.exports = bot