问:
Request not made after ngx translate language change
I am trying to fix a bug that I think is caused by ngx translate. Changing language from default to English for the first time doesn't cause any issues, the loader works fine, but after changing the language for the second time request is not made which causes the interceptor not to fire, where I call the loader service method and tell the loader to stop. Any help is appreciated.

app.component.ts

```<code>export class AppComponent {
  title = 'app';

  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private progressBarService: ProgressBarService,
    private prevRoute: PreviousRouteService,
    private locationStrategy: LocationStrategy,
    private translate: TranslateService) {
    translate.addLangs(['en', 'ka']);

    this.activatedRoute.queryParams
      .subscribe(p => {
        const { lang } = p;
        if (!this.checkLang(lang) && lang.match(/en|ka|EN|KA/)) {
          let oldLang = this.translate.currentLang
          if (!oldLang) {
            this.translate.use(lang.toLowerCase());
            sessionStorage.setItem('lang', lang.toLowerCase());
          } else {
            const qParams = { ...p };
            qParams['lang'] = oldLang;
            this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: { ...qParams }, replaceUrl: true })
              .catch(err => console.log(err))
          }
        } else {
          this.translate.setDefaultLang('ka');
          sessionStorage.setItem('lang', 'ka');
        }
      })

    this.router.events
      .subscribe(event => {
        if (event instanceof NavigationStart) {
          if (event.url.includes('result')) {
            history.pushState(null, null, location.href);

            this.locationStrategy.onPopState((l: LocationChangeEvent) => {
              history.pushState(null, null, location.href);
            });
          }

          if (this.prevRoute.prevPath == undefined) {
            this.prevRoute.previousRoutePath.next(event.url);
          }
          this.progressBarService.progressBarProcess(false);
        }
      })
  }

  private checkLang(lang) {
    return lang === undefined || lang === "undefined" || lang === null || lang.length <= 0;
  }
}
</code>```

loader.component.html

```<code><div class="progress-bar-container">
      <div class="progress-bar" [ngClass]="{'in-progress': !show, 'fill': show}"></div>
</div>

</code>```

loader.component.ts

```<code>export class ProgressBarComponent {

  show = true;

  constructor(private progressBarService: ProgressBarService) {

    this.progressBarService.progressBarSub()

      .subscribe(status => {

        this.show = status;

      })

  }

}
</code>```

header.component.ts where I have dropdown flags for changing languages on click. here after change language method is called I tried to log result of activatedroute.subscribe and after each call subscribe method returns result increased by one compared to previous call. I have no idea what causes that as well.

```<code>this.translate.onDefaultLangChange
      .subscribe(defaultLang => {
        this.currentLang = defaultLang.lang;
        this.languageFlags = this.filterFlags();
      })

    this.translate.onLangChange
      .subscribe(lang => {
        this.currentLang = lang.lang;
        this.languageFlags = this.filterFlags();
      })
  }

  showPopOver() {
    setTimeout(() => {
      this.popoverVisible = !this.popoverVisible;
    }, 0)
  }

  toggleLanguageDropdown() {
    this.languageDropdown = !this.languageDropdown;
  }

  changeLanguage(lang: string) {
    this.languageDropdown = false;
    this.translate.use(lang)
      .subscribe(() => {
        this.languageFlags = this.langs;
        this.currentLang = this.translate.currentLang
        this.languageFlags = this.filterFlags();
        window.sessionStorage.setItem('lang', lang);
        this.activatedRoute.queryParams
          .subscribe(r => {
            this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: { lang: lang, status: r['status'] }, replaceUrl: true })
              .catch(err => console.log(err))
          });
      })
  }

  private filterFlags(): string[] {
    return this.languageFlags.filter(el => el !== this.currentLang)
  }

</code>```

interceptor

```<code>  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    this.progressBarService.progressBarProcess(false);

    const token = window.sessionStorage.getItem('auth_token');

    const lang = window.sessionStorage.getItem('lang') ?? 'ka';

    const newReq = token

      ? req.clone({ headers: req.headers.set("Authorization", `Bearer ${token}`).set("Accept-Language", lang) })

      : req.clone({ headers: req.headers.set("Accept-Language", lang) });

    return next.handle(newReq)

      .pipe(

        catchError((error) => {

          if (error.status === 301) {

            window.location.reload();

          }

          return throwError(error);

        }),

        finalize(() => {

          this.progressBarService.progressBarProcess(true);

        }));

  }

</code>```

Body:
I am trying to fix a bug that I think is caused by ngx translate. Changing language from default to English for the first time doesn't cause any issues, the loader works fine, but after changing the language for the second time request is not made which causes the interceptor not to fire, where I call the loader service method and tell the loader to stop. Any help is appreciated.

app.component.ts

export class AppComponent {
  title = 'app';

  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private progressBarService: ProgressBarService,
    private prevRoute: PreviousRouteService,
    private locationStrategy: LocationStrategy,
    private translate: TranslateService) {
    translate.addLangs(['en', 'ka']);

    this.activatedRoute.queryParams
      .subscribe(p => {
        const { lang } = p;
        if (!this.checkLang(lang) && lang.match(/en|ka|EN|KA/)) {
          let oldLang = this.translate.currentLang
          if (!oldLang) {
            this.translate.use(lang.toLowerCase());
            sessionStorage.setItem('lang', lang.toLowerCase());
          } else {
            const qParams = { ...p };
            qParams['lang'] = oldLang;
            this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: { ...qParams }, replaceUrl: true })
              .catch(err => console.log(err))
          }
        } else {
          this.translate.setDefaultLang('ka');
          sessionStorage.setItem('lang', 'ka');
        }
      })

    this.router.events
      .subscribe(event => {
        if (event instanceof NavigationStart) {
          if (event.url.includes('result')) {
            history.pushState(null, null, location.href);

            this.locationStrategy.onPopState((l: LocationChangeEvent) => {
              history.pushState(null, null, location.href);
            });
          }

          if (this.prevRoute.prevPath == undefined) {
            this.prevRoute.previousRoutePath.next(event.url);
          }
          this.progressBarService.progressBarProcess(false);
        }
      })
  }

  private checkLang(lang) {
    return lang === undefined || lang === "undefined" || lang === null || lang.length <= 0;
  }
}

loader.component.html

loader.component.ts

export class ProgressBarComponent {

  show = true;

  constructor(private progressBarService: ProgressBarService) {

    this.progressBarService.progressBarSub()

      .subscribe(status => {

        this.show = status;

      })

  }

}

header.component.ts where I have dropdown flags for changing languages on click. here after change language method is called I tried to log result of activatedroute.subscribe and after each call subscribe method returns result increased by one compared to previous call. I have no idea what causes that as well.

this.translate.onDefaultLangChange
      .subscribe(defaultLang => {
        this.currentLang = defaultLang.lang;
        this.languageFlags = this.filterFlags();
      })

    this.translate.onLangChange
      .subscribe(lang => {
        this.currentLang = lang.lang;
        this.languageFlags = this.filterFlags();
      })
  }

  showPopOver() {
    setTimeout(() => {
      this.popoverVisible = !this.popoverVisible;
    }, 0)
  }

  toggleLanguageDropdown() {
    this.languageDropdown = !this.languageDropdown;
  }

  changeLanguage(lang: string) {
    this.languageDropdown = false;
    this.translate.use(lang)
      .subscribe(() => {
        this.languageFlags = this.langs;
        this.currentLang = this.translate.currentLang
        this.languageFlags = this.filterFlags();
        window.sessionStorage.setItem('lang', lang);
        this.activatedRoute.queryParams
          .subscribe(r => {
            this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: { lang: lang, status: r['status'] }, replaceUrl: true })
              .catch(err => console.log(err))
          });
      })
  }

  private filterFlags(): string[] {
    return this.languageFlags.filter(el => el !== this.currentLang)
  }

interceptor

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    this.progressBarService.progressBarProcess(false);

    const token = window.sessionStorage.getItem('auth_token');

    const lang = window.sessionStorage.getItem('lang') ?? 'ka';

    const newReq = token

      ? req.clone({ headers: req.headers.set("Authorization", `Bearer ${token}`).set("Accept-Language", lang) })

      : req.clone({ headers: req.headers.set("Accept-Language", lang) });

    return next.handle(newReq)

      .pipe(

        catchError((error) => {

          if (error.status === 301) {

            window.location.reload();

          }

          return throwError(error);

        }),

        finalize(() => {

          this.progressBarService.progressBarProcess(true);

        }));

  }


来源: stackexchange

问:
I am new in Apex and need help to display an image in pl/sql dynamic content
I am new in Apex and need help to display an image in pl/sql dynamic content
I think this code is perfect but I am confuse to understand about the highlighted arguments. What is this and where we can declare this item?

I am new in Apex and need help to display an image in pl/sql dynamic content
I think this code is perfect but I am confuse to understand about the highlighted arguments. What is this and where we can declare this item?

ContentLicense: CC BY-SA 4.0


问:
JsonWebTokenError: jwt malformed if I use an instance of Axios in React
In this scenario I do not get in backend that token is null( jwt malformed).
And works perfectly fine.

```<code>console.log(localStorage.getItem("token")) // ey.....
   const res = await axios.get(`${process.env.REACT_APP_API_URL}/admin/categories`, {
          headers: {
            token: `${localStorage.getItem("token")}`,
          },
        })
</code>```

In this scenario, I do get that JWT is malformed.

index.tsx

```<code>    import axios_auth from "../../../utils/axios/admin"
console.log(localStorage.getItem("token")) // ey.....
    const res = await axios_auth.get(`/admin/categories`)
</code>```

admin.ts

```<code>import axios from "axios";
export default axios.create({
  baseURL: `${process.env.REACT_APP_API_URL}`,
  headers: {
    token: `${localStorage.getItem("token")}`,
  },
});
</code>```

Body:
In this scenario I do not get in backend that token is null( jwt malformed).
And works perfectly fine.

console.log(localStorage.getItem("token")) // ey.....
   const res = await axios.get(`${process.env.REACT_APP_API_URL}/admin/categories`, {
          headers: {
            token: `${localStorage.getItem("token")}`,
          },
        })

In this scenario, I do get that JWT is malformed.

index.tsx

    import axios_auth from "../../../utils/axios/admin"
console.log(localStorage.getItem("token")) // ey.....
    const res = await axios_auth.get(`/admin/categories`)

admin.ts

import axios from "axios";
export default axios.create({
  baseURL: `${process.env.REACT_APP_API_URL}`,
  headers: {
    token: `${localStorage.getItem("token")}`,
  },
});


问:
Reading a list of strings into pandas dataframe results in error
I want to read a text file into a pandas dataframe. In the file are several tables, each separated by an empty line. I would like to have those tables separated, so I split the text file into chunks each containing a table. Using StringIO I can read in a single chunk using pandas read_csv(). However, looping through the list of chunks that I have results in the following error: 'EmptyDataError: No columns to parse from file'

Creating the chunks from the text file

```<code>with open(txt_full_paths[0], 'r') as file:
    chunks = file.read().split('\n\n')
</code>```

Using StringIO to read single string into dataframe with read_csv(). This works as expected

```<code>df = pd.read_csv(StringIO(chunks[0]), sep='\t').transpose()
</code>```

However, when I try:

```<code>dfs=[]
for chunk in chunks:
    df = pd.read_csv(StringIO(chunk), sep='\t').transpose()
    dfs.append(df)
</code>```

I am getting the following error message:

```<code>EmptyDataError                            Traceback (most recent call last)
/Users/lefebre/Allostericsiteprediction_backup/pocket_pred_clust_backup.ipynb Cell 24 in <cell line: 2>()
      1 dfs=[]
      2 for chunk in chunks:
----> 3     df = pd.read_csv(StringIO(chunk), sep='\t').transpose()
      4     dfs.append(df)

File ~/miniconda3/envs/allostericsiteprediction/lib/python3.10/site-packages/pandas/util/_decorators.py:311, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
    305 if len(args) > num_allow_args:
    306     warnings.warn(
    307         msg.format(arguments=arguments),
    308         FutureWarning,
    309         stacklevel=stacklevel,
    310     )
--> 311 return func(*args, **kwargs)

File ~/miniconda3/envs/allostericsiteprediction/lib/python3.10/site-packages/pandas/io/parsers/readers.py:680, in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, error_bad_lines, warn_bad_lines, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options)
    665 kwds_defaults = _refine_defaults_read(
    666     dialect,
    667     delimiter,
   (...)
    676     defaults={"delimiter": ","},
    677 )
    678 kwds.update(kwds_defaults)
...
     79 # error: Cannot determine type of 'names'

File ~/miniconda3/envs/allostericsiteprediction/lib/python3.10/site-packages/pandas/_libs/parsers.pyx:551, in pandas._libs.parsers.TextReader.__cinit__()

EmptyDataError: No columns to parse from file
</code>```

Anyone knows how to solve this issue? Any help is appreciated!

Body:
I want to read a text file into a pandas dataframe. In the file are several tables, each separated by an empty line. I would like to have those tables separated, so I split the text file into chunks each containing a table. Using StringIO I can read in a single chunk using pandas read_csv(). However, looping through the list of chunks that I have results in the following error: 'EmptyDataError: No columns to parse from file'

Creating the chunks from the text file

with open(txt_full_paths[0], 'r') as file:
    chunks = file.read().split('\n\n')

Using StringIO to read single string into dataframe with read_csv(). This works as expected

df = pd.read_csv(StringIO(chunks[0]), sep='\t').transpose()

However, when I try:

dfs=[]
for chunk in chunks:
    df = pd.read_csv(StringIO(chunk), sep='\t').transpose()
    dfs.append(df)

I am getting the following error message:

EmptyDataError                            Traceback (most recent call last)
/Users/lefebre/Allostericsiteprediction_backup/pocket_pred_clust_backup.ipynb Cell 24 in <cell line: 2>()
      1 dfs=[]
      2 for chunk in chunks:
----> 3     df = pd.read_csv(StringIO(chunk), sep='\t').transpose()
      4     dfs.append(df)

File ~/miniconda3/envs/allostericsiteprediction/lib/python3.10/site-packages/pandas/util/_decorators.py:311, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
    305 if len(args) > num_allow_args:
    306     warnings.warn(
    307         msg.format(arguments=arguments),
    308         FutureWarning,
    309         stacklevel=stacklevel,
    310     )
--> 311 return func(*args, **kwargs)

File ~/miniconda3/envs/allostericsiteprediction/lib/python3.10/site-packages/pandas/io/parsers/readers.py:680, in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, error_bad_lines, warn_bad_lines, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options)
    665 kwds_defaults = _refine_defaults_read(
    666     dialect,
    667     delimiter,
   (...)
    676     defaults={"delimiter": ","},
    677 )
    678 kwds.update(kwds_defaults)
...
     79 # error: Cannot determine type of 'names'

File ~/miniconda3/envs/allostericsiteprediction/lib/python3.10/site-packages/pandas/_libs/parsers.pyx:551, in pandas._libs.parsers.TextReader.__cinit__()

EmptyDataError: No columns to parse from file

Anyone knows how to solve this issue? Any help is appreciated!


问:
CORS error while requesting file using signed URL (AWS)
I have applied Cloudfront function to decode application token for restrict user wise access content. so I have sending Authorization token on each header for security.

```<code>let signedUrl = cloudfrontSigner.getSignedUrl({
    url: fileUrl,
    dateLessThan: new Date(Date.now() + 1000 * 60 * 60),
    privateKey: awsPrivateKey,
    keyPairId: keyPairId,
  });
</code>```

I am able to access file content in Postman with pass header token but could't access using Angular request and showing a CORS error. I allowed CORS from bucket setting using below code still getting an error.

```<code>[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "PUT",
            "POST",
            "DELETE",
            "HEAD"
        ],
        "AllowedOrigins": [
            "http://*",
            "https://*"
        ],
        "ExposeHeaders": [
            "Access-Control-Allow-Origin",
            "ETag"
        ],
        "MaxAgeSeconds": 3000
    }
]
</code>```

Angular code:

```<code>public downloadFile(downloadLink: string) {
      return this.http.get(downloadLink)
        .map((response) => {
           const blob = new Blob([response], { type: 'text/csv'})
           window.open(window.URL.createObjectURL(blob))
      });
}
</code>```

Body:
I have applied Cloudfront function to decode application token for restrict user wise access content. so I have sending Authorization token on each header for security.

let signedUrl = cloudfrontSigner.getSignedUrl({
    url: fileUrl,
    dateLessThan: new Date(Date.now() + 1000 * 60 * 60),
    privateKey: awsPrivateKey,
    keyPairId: keyPairId,
  });

I am able to access file content in Postman with pass header token but could't access using Angular request and showing a CORS error. I allowed CORS from bucket setting using below code still getting an error.

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "PUT",
            "POST",
            "DELETE",
            "HEAD"
        ],
        "AllowedOrigins": [
            "http://*",
            "https://*"
        ],
        "ExposeHeaders": [
            "Access-Control-Allow-Origin",
            "ETag"
        ],
        "MaxAgeSeconds": 3000
    }
]

Angular code:

public downloadFile(downloadLink: string) {
      return this.http.get(downloadLink)
        .map((response) => {
           const blob = new Blob([response], { type: 'text/csv'})
           window.open(window.URL.createObjectURL(blob))
      });
}


问:
C# - Multiple selection of items in an Excel's Slicer
Given a list of SlicerItems in a Slicer on a Pivot Table of Excel, using Microsoft.Office.Interop. In Excel, I have to select all the items starting with a specified string.

My code till now is:

```<code>public static void SelectItemsStartingWith(string slicerName, string prefix)
{
      Slicer slicer = Pivot.Slicers[slicerName];
      Book.Application.EnableEvents = false;
      IEnumerable<SlicerItem> slicers = slicer.SlicerCache.SlicerItems.Cast<SlicerItem>();
      foreach (SlicerItem item in slicers)
      {
        if (item.Value.StartsWith(prefix))
        {
          item.Selected = true;
        }
        else if (item.Selected == true)
        {
          item.Selected = false;
        }
      }
}
</code>```

The problem with my code is that anytime I change the item.Selected property of each item it updates every time the pivot, instead of doing it preferably at the end of the foreach, this causes the app to take hours to cycle a list of few tens of items.

Is there any smarter and more efficient way to do so?

Body:
Given a list of SlicerItems in a Slicer on a Pivot Table of Excel, using Microsoft.Office.Interop. In Excel, I have to select all the items starting with a specified string.

My code till now is:

public static void SelectItemsStartingWith(string slicerName, string prefix)
{
      Slicer slicer = Pivot.Slicers[slicerName];
      Book.Application.EnableEvents = false;
      IEnumerable<SlicerItem> slicers = slicer.SlicerCache.SlicerItems.Cast<SlicerItem>();
      foreach (SlicerItem item in slicers)
      {
        if (item.Value.StartsWith(prefix))
        {
          item.Selected = true;
        }
        else if (item.Selected == true)
        {
          item.Selected = false;
        }
      }
}

The problem with my code is that anytime I change the item.Selected property of each item it updates every time the pivot, instead of doing it preferably at the end of the foreach, this causes the app to take hours to cycle a list of few tens of items.

Is there any smarter and more efficient way to do so?


问:
Typescript type transforming object fields to same type but as array
I'm trying to write a some functionality that will properly type transforming an object so each value that isn't an array gets transformed into an array.

For example:

```<code>// what I start with
type Foo = {
  id?: string | string[]
  name?: string
}

// what I want to end up with
type FooArr = {
  id: string[]
  name: string[]
}
</code>```

I haven't quite got it yet, but what I have so far is:

```<code>type ObjectArrayFields<T> = {
    [P in keyof T]: T[P] extends Array<infer U> ? U : Array<T[P]>
}
export function objectItemsToArrayItems<T extends object>(obj: T): ObjectArrayFields<T> {
    const transformed: ObjectArrayFields<T> = {}
    Object.entries(obj).forEach(([strKey, value]) => {
        const key = strKey as keyof T
        if (Array.isArray(value)) {
            transformed[key] = value
        } else {
            transformed[key] = [value]
        }
    })
    return transformed
}
</code>```

Any help is appreciated, thanks!

Body:
I'm trying to write a some functionality that will properly type transforming an object so each value that isn't an array gets transformed into an array.

For example:

// what I start with
type Foo = {
  id?: string | string[]
  name?: string
}

// what I want to end up with
type FooArr = {
  id: string[]
  name: string[]
}

I haven't quite got it yet, but what I have so far is:

type ObjectArrayFields<T> = {
    [P in keyof T]: T[P] extends Array<infer U> ? U : Array<T[P]>
}
export function objectItemsToArrayItems<T extends object>(obj: T): ObjectArrayFields<T> {
    const transformed: ObjectArrayFields<T> = {}
    Object.entries(obj).forEach(([strKey, value]) => {
        const key = strKey as keyof T
        if (Array.isArray(value)) {
            transformed[key] = value
        } else {
            transformed[key] = [value]
        }
    })
    return transformed
}

Any help is appreciated, thanks!


问:
Carrusel with React
I imported React-bootstrap Carousel but it is not been showed as the docuemntation... I

```<code>import Carousel from 'react-bootstrap/Carousel';
</code>```
```<code> <div className='carru'>
                    <Carousel>
                        <Carousel.Item>
                            <img
                            className="d-block w-100"
                            src={img1}
                            alt="First slide"
                            />
                        </Carousel.Item>
                        <Carousel.Item>
                            <img
                            className="d-block w-100"
                            src={img2}
                            alt="Second slide"
                            />
                        </Carousel.Item>
                        <Carousel.Item>
                            <img
                            className="d-block w-100"
                            src={img3}
                            alt="Third slide"
                            />
                        </Carousel.Item>
                        </Carousel.Item>
                    </Carousel>
                </div>
        </div>

</code>```

I tried using other carousels but it happens the same...

This is how it is shown

How my problems looks

Title: Carrusel with React

Body:
I imported React-bootstrap Carousel but it is not been showed as the docuemntation... I

import Carousel from 'react-bootstrap/Carousel';

                    <Carousel>
                        <Carousel.Item>

                        </Carousel.Item>
                        <Carousel.Item>

                        </Carousel.Item>
                        <Carousel.Item>

                        </Carousel.Item>
                        </Carousel.Item>
                    </Carousel>

I tried using other carousels but it happens the same...

This is how it is shown

How my problems looks


问:
Dockerized VueJs + Nginx + Let's Encrypt
I am kind of stuck trying to solve a problem. I have a Dockerfile as per the guide, everything works fine.

Now I want to add an automatic SSL from let's encrypt so it always runs with https.

How would you go with solving this question? Here is my Dockerfile.

```<code>FROM node:14.17.0-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm cache verify
RUN npm install
COPY . .
RUN npm run build

FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
</code>```

After the image builds, I launch it with:

```<code>docker run -it -p 80:80 -d --rm --name app-container vuejs
</code>```

Thanks for the help :)

Body:
I am kind of stuck trying to solve a problem. I have a Dockerfile as per the guide, everything works fine.

Now I want to add an automatic SSL from let's encrypt so it always runs with https.

How would you go with solving this question? Here is my Dockerfile.

FROM node:14.17.0-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm cache verify
RUN npm install
COPY . .
RUN npm run build

FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

After the image builds, I launch it with:

docker run -it -p 80:80 -d --rm --name app-container vuejs

Thanks for the help :)


问:
Multi label image classification in tensorflow
i want to learn about multi label classifcation in tensorflow, so i programmed a simple example to understand how it works. Later i want to change this model a little bit, to use it on my real problem.

Basic Problem: I input a 8x8 rgb image with random colored pixels. 4 random pixels of the image are green. The labels are a 8x8 matrix with zeros, except the positions where green pixels are in the input image. So i just want the model to learn that if the pixel is green it should put in output matrix(at the corresponding place) and otherwise a zero. I reshaped the 8x8 label matrix to a 64x1 vector to train the network.

Code I use for input/label generation:

```<code>imagearray = []
label = []
for i in range(0,100000):
    p = np.zeros((8,8,3))
    l = np.zeros((8,8))
    b = 0
    for j in range(0,8):
        for k in range(0,8):
            p[j][k]=random.choice(colors)
    for m in range(0,4):
        r1 = random.randint(0,7)
        r2 = random.randint(0,7)
        p[r1][r2] = random.choice(green)
        l[r1][r2] = 1

    imagearray.append(p)
    label.append(l)
label = np.reshape(label,(100000,64,1))
label = tf.convert_to_tensor(label)
imagearray =tf.convert_to_tensor(imagearray)
print(np.shape(imagearray))
</code>```

It creates 100000 images which are 8x8 with random colors(except green) and than puts 4 random pixels in the image.

colors is a array with 5 different rgb colors

green is a array with 3 different rgb greens

all colors a normalized with 1/255

Code for my basic model:

```<code>model1 = tf.keras.Sequential([
    keras.layers.Flatten(input_shape=(8,8,3)),
    tf.keras.layers.Dense(1024, activation='relu'),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(256, activation='relu'),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(32, activation='relu'),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(64,activation='sigmoid')

])
model1.compile(optimizer='adam', loss = 'binary_crossentropy',metrics=['accuracy'])

model1.fit(imagearray,label,epochs = 4)
</code>```

Model Prediction are always values between 0 and 0.01. There is no difference at the places where it should be 1.

I tried feeding in more images and change the model shape, but it doesnt make a significant difference. Maybe i should use convolution, but i dont know if it is necessary for this problem.

Body:
i want to learn about multi label classifcation in tensorflow, so i programmed a simple example to understand how it works. Later i want to change this model a little bit, to use it on my real problem.

Basic Problem: I input a 8x8 rgb image with random colored pixels. 4 random pixels of the image are green. The labels are a 8x8 matrix with zeros, except the positions where green pixels are in the input image. So i just want the model to learn that if the pixel is green it should put in output matrix(at the corresponding place) and otherwise a zero. I reshaped the 8x8 label matrix to a 64x1 vector to train the network.

Code I use for input/label generation:

imagearray = []
label = []
for i in range(0,100000):
    p = np.zeros((8,8,3))
    l = np.zeros((8,8))
    b = 0
    for j in range(0,8):
        for k in range(0,8):
            p[j][k]=random.choice(colors)
    for m in range(0,4):
        r1 = random.randint(0,7)
        r2 = random.randint(0,7)
        p[r1][r2] = random.choice(green)
        l[r1][r2] = 1

    imagearray.append(p)
    label.append(l)
label = np.reshape(label,(100000,64,1))
label = tf.convert_to_tensor(label)
imagearray =tf.convert_to_tensor(imagearray)
print(np.shape(imagearray))

It creates 100000 images which are 8x8 with random colors(except green) and than puts 4 random pixels in the image.

colors is a array with 5 different rgb colors

green is a array with 3 different rgb greens

all colors a normalized with 1/255

Code for my basic model:

model1 = tf.keras.Sequential([
    keras.layers.Flatten(input_shape=(8,8,3)),
    tf.keras.layers.Dense(1024, activation='relu'),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(256, activation='relu'),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(32, activation='relu'),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(64,activation='sigmoid')

])
model1.compile(optimizer='adam', loss = 'binary_crossentropy',metrics=['accuracy'])

model1.fit(imagearray,label,epochs = 4)

Model Prediction are always values between 0 and 0.01. There is no difference at the places where it should be 1.

I tried feeding in more images and change the model shape, but it doesnt make a significant difference. Maybe i should use convolution, but i dont know if it is necessary for this problem.


问:
How do I use a cell reference in a filter?
I have an excel macro that I want to filter for rows that do not contain some specific text. The following code displays all rows that do not contain the text "lac" in column C.

```<code>ActiveSheet.Range("$C$1:$C$100000").AutoFilter Field:=1, Criteria1:= _
    "<>*lac*", Operator:=xlAnd
</code>```

However instead of filtering for "does not contain lac", I want it to filter for "does not contain the text in sheet 2, cell A3".

I have tried replacing "lac" with the cell reference or with a variable set to the cell value, and tried variations of removing quotes, substituting parenthesis, etc., but haven't stumbled upon the correct syntax.

What is the syntax for using a cell reference or a variable in place of "lac"?

Body:
I have an excel macro that I want to filter for rows that do not contain some specific text. The following code displays all rows that do not contain the text "lac" in column C.

ActiveSheet.Range("$C$1:$C$100000").AutoFilter Field:=1, Criteria1:= _
    "<>*lac*", Operator:=xlAnd

However instead of filtering for "does not contain lac", I want it to filter for "does not contain the text in sheet 2, cell A3".

I have tried replacing "lac" with the cell reference or with a variable set to the cell value, and tried variations of removing quotes, substituting parenthesis, etc., but haven't stumbled upon the correct syntax.

What is the syntax for using a cell reference or a variable in place of "lac"?


问:
I need to pass a Pandas Dataframe to a class and use the constructor to initialize class attributes using the data from the Dataframe
I am creating a class that has two constructors. One that can accept all attributes as input and one that accepts a Pandas Dataframe as input and then creates an object using the data from the dataframe as inputs for the first constructor. This code is shown below with some variable names changed.

```<code>class Platform:
    NAMES = ['Blah', 'Blah 2']

    def __init__(self, PlatformName, Mishaps, Hours, ProbBlah, ShelterFactor, ParachuteFactor, WingSpan, Buffer, Length):
        if PlatformName not in Platform.NAMES:
            raise ValueError(f'unknown PlatformName [{PlatformName}]')
        else:
            self.PlatformName = PlatformName
            self.Mishaps = Mishaps
            self.Hours = Hours
            self.ProbBlah = ProbBlah
            self.ShelterFactor = ShelterFactor
            self.ParachuteFactor = ParachuteFactor
            self.WingSpan = WingSpan
            self.Buffer = Buffer
            self.Length = Length

    def __init__(self, df):
        Platform(df.loc[0,'PlatformName'], df.loc[0,'Mishaps'],
        df.loc[0,'Hours'], df.loc[0,'ProbBlah'],
        df.loc[0,'ShelterFactor'], df.loc[0,'ParachuteFactor'],
        df.loc[0,'WingSpan'], df.loc[0,'Buffer'], df.loc[0,'Length'])`
</code>```

I am trying to set up some automated tests through PyTest and I am getting an error when testing this code.

```<code>TypeError: Platform.__init__() takes 2 positional arguments but 10 were given

Blah\Platform.py:21: TypeError
</code>```

The test code is as follows:

```<code>@pytest.fixture
def Blah_Dataframe():
    data = {'PlatformName':['Blah'], 'Mishaps':[20], 'Hours':[631403.9], 'ProbBlah':[1], 'ShelterFactor':[0.75], 'ParachuteFactor':[5], 'WingSpan':[56], 'Buffer':[1], 'Length':[28]}
    data = pd.DataFrame(data)
    return data

def test_platform_name_Blah(Blah_Dataframe):
    p = Platform(Blah_Dataframe)
</code>```

I'm thinking I maybe set up the constructor incorrectly, but I'm not really sure here. Any thoughts or recommendations are appreciated

Body:
I am creating a class that has two constructors. One that can accept all attributes as input and one that accepts a Pandas Dataframe as input and then creates an object using the data from the dataframe as inputs for the first constructor. This code is shown below with some variable names changed.

class Platform:
    NAMES = ['Blah', 'Blah 2']

    def __init__(self, PlatformName, Mishaps, Hours, ProbBlah, ShelterFactor, ParachuteFactor, WingSpan, Buffer, Length):
        if PlatformName not in Platform.NAMES:
            raise ValueError(f'unknown PlatformName [{PlatformName}]')
        else:
            self.PlatformName = PlatformName
            self.Mishaps = Mishaps
            self.Hours = Hours
            self.ProbBlah = ProbBlah
            self.ShelterFactor = ShelterFactor
            self.ParachuteFactor = ParachuteFactor
            self.WingSpan = WingSpan
            self.Buffer = Buffer
            self.Length = Length

    def __init__(self, df):
        Platform(df.loc[0,'PlatformName'], df.loc[0,'Mishaps'],
        df.loc[0,'Hours'], df.loc[0,'ProbBlah'],
        df.loc[0,'ShelterFactor'], df.loc[0,'ParachuteFactor'],
        df.loc[0,'WingSpan'], df.loc[0,'Buffer'], df.loc[0,'Length'])`

I am trying to set up some automated tests through PyTest and I am getting an error when testing this code.

TypeError: Platform.__init__() takes 2 positional arguments but 10 were given

Blah\Platform.py:21: TypeError

The test code is as follows:

@pytest.fixture
def Blah_Dataframe():
    data = {'PlatformName':['Blah'], 'Mishaps':[20], 'Hours':[631403.9], 'ProbBlah':[1], 'ShelterFactor':[0.75], 'ParachuteFactor':[5], 'WingSpan':[56], 'Buffer':[1], 'Length':[28]}
    data = pd.DataFrame(data)
    return data

def test_platform_name_Blah(Blah_Dataframe):
    p = Platform(Blah_Dataframe)

I'm thinking I maybe set up the constructor incorrectly, but I'm not really sure here. Any thoughts or recommendations are appreciated


问:
MUI / Material-UI Autocomplete contains blue selection/outline box (for outlined input), which should not be there
As a test, I used a autocomplete (country select) from the official MUI.com autocomplete documentation.

https://mui.com/material-ui/react-autocomplete/

Here is also the code sandbox for the country select:

https://codesandbox.io/s/x1q340?file=/demo.tsx

The country select autocomplete should look like this:

MUI country select from official website

But when I am testing my code in a React/Inertia project of mine, it looks like that (with exactly the same code):

MUI country select in my project

The blue input box should not be there at all. All experiments to remove it somehow failed.

Both the sandbox and the project use the same latest MUI Version. Any idea where the box could come from?

I expected that, when I am using the same code, I should get the same result, but I did not.

So I tried to modify a theme and change the outline of any input content like this:

```<code>MuiOutlinedInput: {
    styleOverrides: {
        root: {
            "& .MuiOutlinedInput-notchedOutline": {
                borderColor: "gray"
            },
            "&:hover .MuiOutlinedInput-notchedOutline": {
                borderColor: "black"
            },
            "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
                borderColor: "green"
            },
        }
    }
},
</code>```

But the result was that the color of the outer border changed from blue to green, but not the inner one.

Try to fix

Body:
As a test, I used a autocomplete (country select) from the official MUI.com autocomplete documentation.

https://mui.com/material-ui/react-autocomplete/

Here is also the code sandbox for the country select:

https://codesandbox.io/s/x1q340?file=/demo.tsx

The country select autocomplete should look like this:

MUI country select from official website

But when I am testing my code in a React/Inertia project of mine, it looks like that (with exactly the same code):

MUI country select in my project

The blue input box should not be there at all. All experiments to remove it somehow failed.

Both the sandbox and the project use the same latest MUI Version. Any idea where the box could come from?

I expected that, when I am using the same code, I should get the same result, but I did not.

So I tried to modify a theme and change the outline of any input content like this:

MuiOutlinedInput: {
    styleOverrides: {
        root: {
            "& .MuiOutlinedInput-notchedOutline": {
                borderColor: "gray"
            },
            "&:hover .MuiOutlinedInput-notchedOutline": {
                borderColor: "black"
            },
            "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
                borderColor: "green"
            },
        }
    }
},

But the result was that the color of the outer border changed from blue to green, but not the inner one.

Try to fix


问:
Element nested in child moves on hover even when absolutely positioned relative to child's parent?
I'm trying to keep a nested element still and positioned absolute to its grandparent when the grandparent's hovered and the parent's moved. Is there a way to do that?

I've tried adding hover transitions to the element in opposite directions but it still moves.

Making the element a sibling of its parent so that the hierarchy is just 2 levels deep attains the visual effect but the structure needed for later is different. Hoping for a simple solution without needing to insert HTML or display none on elements.

https://codepen.io/y30b10/pen/WNKGKQz

.parent {
  position: relative;
  background-color: lightblue;
  width: 300px;
  height: 400px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-content: flex-start;
  gap: 20px;
  padding: 20px;
}

.child-1,
.child-2 {
}

.child-1 {
  flex: 1 1 20%;
  background-color: yellow;
}

.child-2 {
  flex: 1 1 80%;
  background-color: lightgreen;
  transition: transform 0.4s;
}

.child-2:hover {
  transform: translate(0, -10%);
}

h1 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child-1"></div>
  <div class="child-2">
    <h1 class="">Absolute positioned element</h1>
  </div>
</div></code>```

Body:
I'm trying to keep a nested element still and positioned absolute to its grandparent when the grandparent's hovered and the parent's moved. Is there a way to do that?

I've tried adding hover transitions to the element in opposite directions but it still moves.

Making the element a sibling of its parent so that the hierarchy is just 2 levels deep attains the visual effect but the structure needed for later is different. Hoping for a simple solution without needing to insert HTML or display none on elements.

https://codepen.io/y30b10/pen/WNKGKQz

.parent {
  position: relative;
  background-color: lightblue;
  width: 300px;
  height: 400px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-content: flex-start;
  gap: 20px;
  padding: 20px;
}

.child-1,
.child-2 {
}

.child-1 {
  flex: 1 1 20%;
  background-color: yellow;
}

.child-2 {
  flex: 1 1 80%;
  background-color: lightgreen;
  transition: transform 0.4s;
}

.child-2:hover {
  transform: translate(0, -10%);
}

h1 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

Absolute positioned element


问:
How to use the getAssignedPartition() in kafka spring? And what does it give us?
I'm trying to get the currently assigned partition in Kafka spring, and I found the getAssignedPartition() method, but I couldn't use it properly, how can I use this properly?

For more information: Can I get the information that which partition is going to receive the next message or what partition get the message last?

https://javadoc.io/static/org.springframework.kafka/spring-kafka/2.3.1.RELEASE/org/springframework/kafka/listener/MessageListenerContainer.html#getAssignedPartitions--


问:
Create multiple folders each with a file of the same name in terminal
Is it possible to do something like:

mkdir -p {folder1, folder2, folder3...}/

and then do something after the '/' like 'touch' to create an index.vue file in each folder simultaneously?


问:
New Data Series shifted left
I have indicator that alerts on condition. Just alerts.
Using just closes.
Sometimes I know for example that if the next (current) close will be up or down - alert will happen.
So, idea is next:
shift chart left for 1 bar, fill last empty with required value and calculate indicator from this new data series. As if it has been closed (current bar). Just to be ready fast.
I've tried to do it with array (filling it with close data until last, filling last with desired value). But I can't calculate indicator value from array data.
Are any decision exits to convert array to data series or may be dramatically other decision?

`

```<code>a = array.new_float(50)
for i = 1 to 49
    array. Set(a, i, close[i-1])
array. Set(a, 0, myValue)
</code>```

I've tried to fill array this way. But can't calculate

Title: New Data Series shifted left

Body:
I have indicator that alerts on condition. Just alerts.
Using just closes.
Sometimes I know for example that if the next (current) close will be up or down - alert will happen.
So, idea is next:
shift chart left for 1 bar, fill last empty with required value and calculate indicator from this new data series. As if it has been closed (current bar). Just to be ready fast.
I've tried to do it with array (filling it with close data until last, filling last with desired value). But I can't calculate indicator value from array data.
Are any decision exits to convert array to data series or may be dramatically other decision?

`

a = array.new_float(50)
for i = 1 to 49
    array. Set(a, i, close[i-1])
array. Set(a, 0, myValue)

I've tried to fill array this way. But can't calculate


问:
terraform ressource to provision an aws ressource group
i try to create a terraform resource that provision a terraform ressource group
the point is to create that include the ressources of some cloudformation stack.

i cannot figure out what is the proper way to do this

here is my current testing file :

```<code>provider "aws" {
}

terraform {
}

resource "aws_resourcegroups_group" "test" {
  name = "test"
  description = "test"
  resource_query {
    query = jsonencode(
      {
        ResourceTypeFilters = [ "AWS::AllSupported",]
        StackIdentifier     = "arn:aws:cloudformation:XXXXXX:XXXXXX:stack/endofarn"
      }
    )
    type = "CLOUDFORMATION_STACK_1_0"
  }
}
</code>```

all i get is :

```<code>terraform plan
╷
│ Error: expected resource_query.0.type to be one of [TAG_FILTERS_1_0], got CLOUDFORMATION_STACK_1_0
│
│   with aws_resourcegroups_group.test,
│   on main.tf line 18, in resource "aws_resourcegroups_group" "test":
│   18:     type = "CLOUDFORMATION_STACK_1_0"
│
╵
</code>```

does anyone know how to write this ?

Body:
i try to create a terraform resource that provision a terraform ressource group
the point is to create that include the ressources of some cloudformation stack.

i cannot figure out what is the proper way to do this

here is my current testing file :

provider "aws" {
}

terraform {
}

resource "aws_resourcegroups_group" "test" {
  name = "test"
  description = "test"
  resource_query {
    query = jsonencode(
      {
        ResourceTypeFilters = [ "AWS::AllSupported",]
        StackIdentifier     = "arn:aws:cloudformation:XXXXXX:XXXXXX:stack/endofarn"
      }
    )
    type = "CLOUDFORMATION_STACK_1_0"
  }
}

all i get is :

terraform plan
╷
│ Error: expected resource_query.0.type to be one of [TAG_FILTERS_1_0], got CLOUDFORMATION_STACK_1_0
│
│   with aws_resourcegroups_group.test,
│   on main.tf line 18, in resource "aws_resourcegroups_group" "test":
│   18:     type = "CLOUDFORMATION_STACK_1_0"
│
╵

does anyone know how to write this ?


问:
Monitor/sniff PCI I/O under Windows and Linux
A PCI device seems to have some sort of incompatibility with the process of I/O port range assignment on Linux, even if it works on Windows without any effort with a completely blank driver.

I would like to compare the I/O port range assignment process on Windows and Linux.

For that I need to monitor reads/writes to PCI I/O ports and memory. Primarily, I/O ports.

Unfortunately I don't own a hardware PCI sniffer, or anything that is capable of monitoring all PCI I/O lines at 33MHz.

Is there any way to monitor I/O in software for Windows and/or Linux?


问:
Backfill hive table with recent chnages in its structure
We pushed one hive table to prod in June22 with lets say below columns
A
B
C

In Nov22, we added few columns. Now table structure is like
A
B
C
D
E

Now I want to backfill the data from June. How can I do it ? Since partitions before Nov22 doesnt contain D and E col

Any help would be appreciated.


问:
c# how to measure used memory from referenced method
I've written a program that splits an XML into a lot of smaller XMLs and for performance reasons this program keeps all XML writers open at the same time and calls the relevant methods recursively. Also all this is nested in zip and xml readers and writers. When a lot of writers are open at the same time a stackoverflow exception happens and since these can't be caught I try to throw an exception in my code if too much memory is used. This works fine as a stand-alone application, but the used memory is reported incorrectly from the same method when used as a reference.

I wrote the following code that is called each recursion:

```<code>            var performance = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
            var available = performance.NextValue()/10;
            var memory = 0.0;

            using (Process proc = Process.GetCurrentProcess())
            {
                memory = proc.PrivateMemorySize64 / (1024 * 1024);
            }

            if(memory / available > maxMemoryUsageFactor)
            {
                throw new Exception("Memory usage is too high.");
            }
</code>```

This seems to do the trick when I run the program as a application. Typically on my workstation I will get a value of 328 MB for available memory (please note that I devide the MB as gotten from PerformanceCounter by 10, which makes it correpond with the debugger from Visual Studio, but is kinda odd). For maxMemoryUsageFactor I use 0.8, so that I can do a safe rollback of all the streams.

However, the code is intended to be used as a reference (.dll) in another application, and when I use it as such it seems be able to use roughly the same amount of memory, but only reports the memory used by the main application, not by the referenced method. At the point where it normally will report about 75% of memory usage, none of the metrics available in the process reports over 30%:

Initiating Chained writer 964 of 964 | current memory (MB): 58 of 300,9(19,2755072038829%) |  PagedMemorySize64:58 NonpagedSystemMemorySize64:0 VirtualMemorySize64:4709 WorkingSet64:69 PagedSystemMemorySize64:0 PeakPagedMemorySize64:58

I assume that this has something to do with either the accessibility of the memory used by the reference (since Visual studio also shows only about 60MB in it's performance chart now and in the stand alone version 328MB), or lag in memory reporting, but I have no idea how and why.

Body:
I've written a program that splits an XML into a lot of smaller XMLs and for performance reasons this program keeps all XML writers open at the same time and calls the relevant methods recursively. Also all this is nested in zip and xml readers and writers. When a lot of writers are open at the same time a stackoverflow exception happens and since these can't be caught I try to throw an exception in my code if too much memory is used. This works fine as a stand-alone application, but the used memory is reported incorrectly from the same method when used as a reference.

I wrote the following code that is called each recursion:

            var performance = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
            var available = performance.NextValue()/10;
            var memory = 0.0;

            using (Process proc = Process.GetCurrentProcess())
            {
                memory = proc.PrivateMemorySize64 / (1024 * 1024);
            }

            if(memory / available > maxMemoryUsageFactor)
            {
                throw new Exception("Memory usage is too high.");
            }

This seems to do the trick when I run the program as a application. Typically on my workstation I will get a value of 328 MB for available memory (please note that I devide the MB as gotten from PerformanceCounter by 10, which makes it correpond with the debugger from Visual Studio, but is kinda odd). For maxMemoryUsageFactor I use 0.8, so that I can do a safe rollback of all the streams.

However, the code is intended to be used as a reference (.dll) in another application, and when I use it as such it seems be able to use roughly the same amount of memory, but only reports the memory used by the main application, not by the referenced method. At the point where it normally will report about 75% of memory usage, none of the metrics available in the process reports over 30%:

Initiating Chained writer 964 of 964 | current memory (MB): 58 of 300,9(19,2755072038829%) |  PagedMemorySize64:58 NonpagedSystemMemorySize64:0 VirtualMemorySize64:4709 WorkingSet64:69 PagedSystemMemorySize64:0 PeakPagedMemorySize64:58

I assume that this has something to do with either the accessibility of the memory used by the reference (since Visual studio also shows only about 60MB in it's performance chart now and in the stand alone version 328MB), or lag in memory reporting, but I have no idea how and why.


问:
Prestashop Link to database cannot be established: SQLSTATE[28000] [1045]
error:Link to database cannot be established: SQLSTATE[28000] [1045] Access denied for user 'vandrein_admin'@'193.108.130.12' (using password: YES)
at line 136 in file classes/db/DbPDO.php

so my website is online and i got absolutely no idea why it just stopped working. It was working fine around 4 days ago and no one touched it. Please tell me how i can fix the problem. I really don't want to do the installation again......enter image description here

im open to suggestions


问:
Toggle multiple text input choices
I would like to have a user of a program be able to choose between multiple choices of options on the screen using cursor keys to toggle between choices and press return to make that choice.

For example:
Please Choose One or Two Players.

One Player

Two Players

I certainly am aware that I could simply assign a variable to inputs and maybe have the user type in a number 1 or 2 and get the result that way. Or they could type in the the whole word like "one player"or "two players". but i already know how to do that and that is not what i want.
It is of paramount importance that it involves selecting (toggling between) with cursor keys then press enter or return.
I don't want the user to have to type in the answer.
It would be kind of weird to ask a user to type in "One player" or type "two players" when the could be given choices to toggle between and besides, this is how a professionally written program would be written. not endless typing in unformatted fields. Giving user limited options sanitizes the input reducing errors and facilitates one handed operation of the program.
I don't believe pokes and peeks should be necessary nor do i believe that it would be necessary to use assembly language.
Yes I have googled this and the internet is flooded with "how to type on your c64"
i cannot find anything that doesn't deal with typing full answers beneath the ready prompt.
Not one single script on selecting objects or text on the screen except for assembly language like peek and poke.
These are ALL tutorials on variables. I know how to use variables. I need to select text on screen. and no, i am not trying to copy and paste. I successfully did this as a child but I don't remember how. But I DID NOT use assembly language.
Any help greatly appreciated.

Title: Toggle multiple text input choices


问:
"Sender action failed" When reacting to facebook message
I am using facebook api to react messages in messenger. This is the api POST request I am using

```<code>https://graph.facebook.com/v15.0/<PAGE-ID>/messages?recipient={id:<Pariticipant_ID>}&sender_action=react&payload={message_id:m_sVNX5t0U5gArMtgF2Dr26p5dVVsRueGmj101HP625pxXCZXRr6HtLeLonjV5eFKp44MXhELnNWrz50k6Upl8zg,reaction:love}&access_token=<ACCESS_TOKEN>
</code>```

After making the post request I am getting  "Sender action failed" as response.(Please find the complete response below)

```<code>{
    "error": {
        "message": "(#100) Sender action failed",
        "type": "OAuthException",
        "code": 100,
        "error_subcode": 2018048,
        "fbtrace_id": "AjwcP68lSlj9seauOxeV_Tl"
    }
}
</code>```

Am I doing something wrong here? Or is there any way to send reactions to messages?

Body:
I am using facebook api to react messages in messenger. This is the api POST request I am using

https://graph.facebook.com/v15.0/<PAGE-ID>/messages?recipient={id:<Pariticipant_ID>}&sender_action=react&payload={message_id:m_sVNX5t0U5gArMtgF2Dr26p5dVVsRueGmj101HP625pxXCZXRr6HtLeLonjV5eFKp44MXhELnNWrz50k6Upl8zg,reaction:love}&access_token=<ACCESS_TOKEN>

After making the post request I am getting  "Sender action failed" as response.(Please find the complete response below)

{
    "error": {
        "message": "(#100) Sender action failed",
        "type": "OAuthException",
        "code": 100,
        "error_subcode": 2018048,
        "fbtrace_id": "AjwcP68lSlj9seauOxeV_Tl"
    }
}

Am I doing something wrong here? Or is there any way to send reactions to messages?


问:
InternalError: Graph execution error in tensorflow code
This is my training images patch result :

training input images patch shape  :  (32, 224, 224, 3)
training input labels patch shape  :  (32, 7)
training labels: {'shoulder': 0, 'humerus': 1, 'finger': 2, 'elbow': 3, 'wrist': 4, 'forearm': 5, 'hand': 6}

and my model architecture is :

```<code>def Inception_block(input_layer, f1, f2_conv1, f2_conv3, f3_conv1, f3_conv5, f4):

    # Input:
    # - f1: number of filters of the 1x1 convolutional layer in the first path
    # - f2_conv1, f2_conv3 are number of filters corresponding to the 1x1 and 3x3 convolutional layers in the second path
    # - f3_conv1, f3_conv5 are the number of filters corresponding to the 1x1 and 5x5  convolutional layer in the third path
    # - f4: number of filters of the 1x1 convolutional layer in the fourth path

    # 1st path:
    path1 = Conv2D(filters=f1, kernel_size = (1,1), padding = 'same', activation = 'relu')(input_layer)

    # 2nd path
    path2 = Conv2D(filters = f2_conv1, kernel_size = (1,1), padding = 'same', activation = 'relu')(input_layer)
    path2 = Conv2D(filters = f2_conv3, kernel_size = (3,3), padding = 'same', activation = 'relu')(path2)

    # 3rd path
    path3 = Conv2D(filters = f3_conv1, kernel_size = (1,1), padding = 'same', activation = 'relu')(input_layer)
    path3 = Conv2D(filters = f3_conv5, kernel_size = (5,5), padding = 'same', activation = 'relu')(path3)

    # 4th path
    path4 = MaxPooling2D((3,3), strides= (1,1), padding = 'same')(input_layer)
    path4 = Conv2D(filters = f4, kernel_size = (1,1), padding = 'same', activation = 'relu')(path4)

    output_layer = concatenate([path1, path2, path3, path4], axis = -1)

    return output_layer

def layer_1(input_layer):

    '''composed of :
    > convolutional layer: filters = 64, kernel_size = (7,7), strides = 2
    > max-pooling layer: pool_size = (3,3), strides = 2'''

    X = Conv2D(filters = 64, kernel_size = (7,7), strides = 2, padding = 'valid', activation = 'relu')(input_layer)

    X = MaxPooling2D(pool_size = (3,3), strides = 2)(X)

    return X

def layer_2(X):

    '''composed of :
    > convolutional layer: filters = 64, strides = 1
    > convolutional layer: filters = 192, kernel_size = (3,3)
    > max-pooling layer: pool_size = (3,3), strides = 2'''

    X = Conv2D(filters = 64, kernel_size = (1,1), strides = 1, padding = 'same', activation = 'relu')(X)
    X = Conv2D(filters = 192, kernel_size = (3,3), padding = 'same', activation = 'relu')(X)

    X = MaxPooling2D(pool_size= (3,3), strides = 2)(X)

    return X

def layer_3(X):

    '''composed of :
    > 1st Inception block
    > 2nd Inception block
    > max-pooling layer: pool_size = (3,3), strides = 2'''

    X = Inception_block(X, f1 = 64, f2_conv1 = 96, f2_conv3 = 128, f3_conv1 = 16, f3_conv5 = 32, f4 = 32)
    X = Inception_block(X, f1 = 128, f2_conv1 = 128, f2_conv3 = 192, f3_conv1 = 32, f3_conv5 = 96, f4 = 64)

    X = MaxPooling2D(pool_size= (3,3), strides = 2)(X)

    return X

def layer_4(X):

    '''composed of :
    > 3rd Inception block
    > Extra Network 1
    > 4th Inception block
    > 5th Inception block
    > 6th Inception block
    > Extra Network 2
    > 7th Inception block
    > max-pooling layer: pool_size = (3,3), strides = 2'''

    X = Inception_block(X, f1 = 192, f2_conv1 = 96, f2_conv3 = 208, f3_conv1 = 16, f3_conv5 = 48, f4 = 64)

    X1 = Extra_Network1(X)

    X = Inception_block(X, f1 = 160, f2_conv1 = 112, f2_conv3 = 224, f3_conv1 = 24, f3_conv5 = 64, f4 = 64)
    X = Inception_block(X, f1 = 128, f2_conv1 = 128, f2_conv3 = 256, f3_conv1 = 24, f3_conv5 = 64, f4 = 64)
    X = Inception_block(X, f1 = 112, f2_conv1 = 144, f2_conv3 = 288, f3_conv1 = 32, f3_conv5 = 64, f4 = 64)

    X2 = Extra_Network2(X)

    X = Inception_block(X, f1 = 256, f2_conv1 = 160, f2_conv3 = 320, f3_conv1 = 32, f3_conv5 = 128, f4 = 128)

    X = MaxPooling2D(pool_size = (3,3), strides = 2)(X)

    return X, X1, X2

def layer_5(X):

    '''composed of :
    > 8th Inception block
    > 9th Inception block
    > Global Average pooling layer
    > Dropoutlayer'''

    X = Inception_block(X, f1 = 256, f2_conv1 = 160, f2_conv3 = 320, f3_conv1 = 32, f3_conv5 = 128, f4 = 128)
    X = Inception_block(X, f1 = 384, f2_conv1 = 192, f2_conv3 = 384, f3_conv1 = 48, f3_conv5 = 128, f4 = 128)

    X = GlobalAveragePooling2D(name = 'GAPL')(X)

    X = Dropout(0.4)(X)

    return X

def Extra_Network1(X):

    X1 = AveragePooling2D(pool_size = (5,5), strides = 3)(X)
    X1 = Conv2D(filters = 128, kernel_size = (1,1), padding = 'same', activation = 'relu')(X1)
    X1 = Flatten()(X1)
    X1 = Dense(1024, activation = 'relu')(X1)
    X1 = Dropout(0.7)(X1)
    X1 = Dense(n_classes, activation = 'softmax', name = 'output_1')(X1)

    return X1

def Extra_Network2(X):

    X2 = AveragePooling2D(pool_size = (5,5), strides = 3)(X)
    X2 = Conv2D(filters = 128, kernel_size = (1,1), padding = 'same', activation = 'relu')(X2)
    X2 = Flatten()(X2)
    X2 = Dense(1024, activation = 'relu')(X2)
    X2 = Dropout(0.7)(X2)
    X2 = Dense(n_classes, activation = 'softmax', name = 'output_2')(X2)

    return X2

def _GoogleNet():

    # input layer
    input_layer = Input(shape = (224, 224, 3))

    #architecture broken into layers
    X = layer_1(input_layer)
    X = layer_2(X)
    X = layer_3(X)

    X, X1, X2 = layer_4(X)

    X = layer_5(X)

    # output layer
    X = Dense(n_classes, activation = 'softmax', name = 'output_3')(X)

    # model
    model = Model(inputs = input_layer,  outputs = [X, X1, X2], name = 'GoogLeNet')

    return model
</code>```

thats how i compiled my model :

```<code>def CompileModel(name, model):

    if name == 'GoogleNet':
        model.compile(optimizer = 'adam',
                      loss = categorical_crossentropy,
                      metrics={"output_1":"accuracy",
                               "output_2":"accuracy",
                               "output_3":"accuracy"})

    return model

def CompileModel(name, model):

    if name == 'GoogleNet':
        model.compile(optimizer = 'adam',
                      loss = categorical_crossentropy,
                      metrics={"output_1":"accuracy",
                               "output_2":"accuracy",
                               "output_3":"accuracy"})

    return model

def CompileModel(name, model):

    if name == 'GoogleNet':
        model.compile(optimizer = 'adam',
                      loss = categorical_crossentropy,
                      metrics={"output_1":"accuracy",
                               "output_2":"accuracy",
                               "output_3":"accuracy"})

    return model

def CompileModel(name, model):

    if name == 'GoogleNet':
        model.compile(optimizer = 'adam',
                      loss = categorical_crossentropy,
                      metrics={"output_1":"accuracy",
                               "output_2":"accuracy",
                               "output_3":"accuracy"})

    return model

compiled_model = BuildModel('GoogleNet')
model, history = FitModel('GoogleNet', compiled_model)
</code>```

and finally the error ii am getting is like this any solution on how to solve it :

```<code>Epoch 1/40

2023-01-04 22:37:40.595715: I tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:428] Loaded cuDNN version 8100
2023-01-04 22:37:41.117823: I tensorflow/tsl/platform/default/subprocess.cc:304] Start cannot spawn child process: No such file or directory
2023-01-04 22:37:41.118274: I tensorflow/tsl/platform/default/subprocess.cc:304] Start cannot spawn child process: No such file or directory
2023-01-04 22:37:41.118307: W tensorflow/compiler/xla/stream_executor/gpu/asm_compiler.cc:85] Couldn't get ptxas version string: INTERNAL: Couldn't invoke ptxas --version
2023-01-04 22:37:41.118676: I tensorflow/tsl/platform/default/subprocess.cc:304] Start cannot spawn child process: No such file or directory
2023-01-04 22:37:41.118766: W tensorflow/compiler/xla/stream_executor/gpu/redzone_allocator.cc:318] INTERNAL: Failed to launch ptxas
Relying on driver to perform ptx compilation.
Modify $PATH to customize ptxas location.
This message will be only logged once.
2023-01-04 22:37:43.785545: I tensorflow/compiler/xla/service/service.cc:173] XLA service 0x1d4de930 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
2023-01-04 22:37:43.785576: I tensorflow/compiler/xla/service/service.cc:181]   StreamExecutor device (0): NVIDIA GeForce GTX 1650, Compute Capability 7.5
2023-01-04 22:37:43.798640: I tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.cc:268] disabling MLIR crash reproducer, set env var `MLIR_CRASH_REPRODUCER_DIRECTORY` to enable.
2023-01-04 22:37:43.844140: W tensorflow/compiler/xla/service/gpu/nvptx_helper.cc:56] Can't find libdevice directory ${CUDA_DIR}/nvvm/libdevice. This may result in compilation or runtime failures, if the program we try to run uses routines from libdevice.
Searched for CUDA in the following directories:
  ./cuda_sdk_lib
  /usr/local/cuda-11.2
  /usr/local/cuda
  .

2023-01-04 22:37:48.488260: W tensorflow/core/framework/op_kernel.cc:1830] OP_REQUIRES failed at xla_ops.cc:446 : INTERNAL: libdevice not found at ./libdevice.10.bc

---------------------------------------------------------------------------
InternalError                             Traceback (most recent call last)
Cell In[31], line 2
      1 compiled_model = BuildModel('GoogleNet')
----> 2 model, history = FitModel('GoogleNet', compiled_model)

Cell In[29], line 12, in FitModel(name, model)
      7 callbacks_ = [
      8     tf.keras.callbacks.EarlyStopping(patience = 2)
      9 ]
     11 if name == 'GoogleNet':
---> 12     history = model.fit(train_image_generator,
     13                         epochs = EPOCHS,
     14                         callbacks = callbacks_,
     15                         validation_data = valid_image_generator,
     16                         steps_per_epoch = (int(len(train_image_generator.labels) / 80)),
     17                         validation_steps = (int(len(valid_image_generator.labels) / 80)))
     19     model.load_weights(name + '_Weights.h5')
     21 return history, model

File ~/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/utils/traceback_utils.py:70, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     67     filtered_tb = _process_traceback_frames(e.__traceback__)
     68     # To get the full stack trace, call:
     69     # `tf.debugging.disable_traceback_filtering()`
---> 70     raise e.with_traceback(filtered_tb) from None
     71 finally:
     72     del filtered_tb

File ~/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/tensorflow/python/eager/execute.py:52, in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     50 try:
     51   ctx.ensure_initialized()
---> 52   tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
     53                                       inputs, attrs, num_outputs)
     54 except core._NotOkStatusException as e:
     55   if name is not None:

InternalError: Graph execution error:

Detected at node 'StatefulPartitionedCall_115' defined at (most recent call last):
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/runpy.py", line 196, in _run_module_as_main
      return _run_code(code, main_globals, None,
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/runpy.py", line 86, in _run_code
      exec(code, run_globals)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel_launcher.py", line 17, in <module>
      app.launch_new_instance()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/traitlets/config/application.py", line 1041, in launch_instance
      app.start()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/kernelapp.py", line 711, in start
      self.io_loop.start()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/tornado/platform/asyncio.py", line 215, in start
      self.asyncio_loop.run_forever()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/asyncio/base_events.py", line 603, in run_forever
      self._run_once()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/asyncio/base_events.py", line 1899, in _run_once
      handle._run()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/asyncio/events.py", line 80, in _run
      self._context.run(self._callback, *self._args)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 510, in dispatch_queue
      await self.process_one()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 499, in process_one
      await dispatch(*args)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 406, in dispatch_shell
      await result
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 729, in execute_request
      reply_content = await reply_content
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/ipkernel.py", line 411, in do_execute
      res = shell.run_cell(
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/zmqshell.py", line 530, in run_cell
      return super().run_cell(*args, **kwargs)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 2940, in run_cell
      result = self._run_cell(
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 2995, in _run_cell
      return runner(coro)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/IPython/core/async_helpers.py", line 129, in _pseudo_sync_runner
      coro.send(None)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3194, in run_cell_async
      has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3373, in run_ast_nodes
      if await self.run_code(code, result, async_=asy):
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3433, in run_code
      exec(code_obj, self.user_global_ns, self.user_ns)
    File "/tmp/ipykernel_2575/1809520282.py", line 2, in <module>
      model, history = FitModel('GoogleNet', compiled_model)
    File "/tmp/ipykernel_2575/2245888179.py", line 12, in FitModel
      history = model.fit(train_image_generator,
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/utils/traceback_utils.py", line 65, in error_handler
      return fn(*args, **kwargs)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/engine/training.py", line 1650, in fit
      tmp_logs = self.train_function(iterator)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/engine/training.py", line 1249, in train_function
      return step_function(self, iterator)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/engine/training.py", line 1233, in step_function
      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/engine/training.py", line 1222, in run_step
      outputs = model.train_step(data)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/engine/training.py", line 1027, in train_step
      self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/optimizers/optimizer_experimental/optimizer.py", line 527, in minimize
      self.apply_gradients(grads_and_vars)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/optimizers/optimizer_experimental/optimizer.py", line 1140, in apply_gradients
      return super().apply_gradients(grads_and_vars, name=name)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/optimizers/optimizer_experimental/optimizer.py", line 634, in apply_gradients
      iteration = self._internal_apply_gradients(grads_and_vars)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/optimizers/optimizer_experimental/optimizer.py", line 1166, in _internal_apply_gradients
      return tf.__internal__.distribute.interim.maybe_merge_call(
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/optimizers/optimizer_experimental/optimizer.py", line 1216, in _distributed_apply_gradients_fn
      distribution.extended.update(
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/optimizers/optimizer_experimental/optimizer.py", line 1211, in apply_grad_to_update_var
      return self._update_step_xla(grad, var, id(self._var_key(var)))
Node: 'StatefulPartitionedCall_115'
libdevice not found at ./libdevice.10.bc
     [[{{node StatefulPartitionedCall_115}}]] [Op:__inference_train_function_24159]

</code>```

I have tried training with other models and also checked the input output shape of images but have not found any solution

Body:
This is my training images patch result :

training input images patch shape  :  (32, 224, 224, 3)
training input labels patch shape  :  (32, 7)
training labels: {'shoulder': 0, 'humerus': 1, 'finger': 2, 'elbow': 3, 'wrist': 4, 'forearm': 5, 'hand': 6}

and my model architecture is :

def Inception_block(input_layer, f1, f2_conv1, f2_conv3, f3_conv1, f3_conv5, f4):

    # Input:
    # - f1: number of filters of the 1x1 convolutional layer in the first path
    # - f2_conv1, f2_conv3 are number of filters corresponding to the 1x1 and 3x3 convolutional layers in the second path
    # - f3_conv1, f3_conv5 are the number of filters corresponding to the 1x1 and 5x5  convolutional layer in the third path
    # - f4: number of filters of the 1x1 convolutional layer in the fourth path

    # 1st path:
    path1 = Conv2D(filters=f1, kernel_size = (1,1), padding = 'same', activation = 'relu')(input_layer)

    # 2nd path
    path2 = Conv2D(filters = f2_conv1, kernel_size = (1,1), padding = 'same', activation = 'relu')(input_layer)
    path2 = Conv2D(filters = f2_conv3, kernel_size = (3,3), padding = 'same', activation = 'relu')(path2)

    # 3rd path
    path3 = Conv2D(filters = f3_conv1, kernel_size = (1,1), padding = 'same', activation = 'relu')(input_layer)
    path3 = Conv2D(filters = f3_conv5, kernel_size = (5,5), padding = 'same', activation = 'relu')(path3)

    # 4th path
    path4 = MaxPooling2D((3,3), strides= (1,1), padding = 'same')(input_layer)
    path4 = Conv2D(filters = f4, kernel_size = (1,1), padding = 'same', activation = 'relu')(path4)

    output_layer = concatenate([path1, path2, path3, path4], axis = -1)

    return output_layer

def layer_1(input_layer):

    '''composed of :
    > convolutional layer: filters = 64, kernel_size = (7,7), strides = 2
    > max-pooling layer: pool_size = (3,3), strides = 2'''

    X = Conv2D(filters = 64, kernel_size = (7,7), strides = 2, padding = 'valid', activation = 'relu')(input_layer)

    X = MaxPooling2D(pool_size = (3,3), strides = 2)(X)

    return X

def layer_2(X):

    '''composed of :
    > convolutional layer: filters = 64, strides = 1
    > convolutional layer: filters = 192, kernel_size = (3,3)
    > max-pooling layer: pool_size = (3,3), strides = 2'''

    X = Conv2D(filters = 64, kernel_size = (1,1), strides = 1, padding = 'same', activation = 'relu')(X)
    X = Conv2D(filters = 192, kernel_size = (3,3), padding = 'same', activation = 'relu')(X)

    X = MaxPooling2D(pool_size= (3,3), strides = 2)(X)

    return X

def layer_3(X):

    '''composed of :
    > 1st Inception block
    > 2nd Inception block
    > max-pooling layer: pool_size = (3,3), strides = 2'''

    X = Inception_block(X, f1 = 64, f2_conv1 = 96, f2_conv3 = 128, f3_conv1 = 16, f3_conv5 = 32, f4 = 32)
    X = Inception_block(X, f1 = 128, f2_conv1 = 128, f2_conv3 = 192, f3_conv1 = 32, f3_conv5 = 96, f4 = 64)

    X = MaxPooling2D(pool_size= (3,3), strides = 2)(X)

    return X

def layer_4(X):

    '''composed of :
    > 3rd Inception block
    > Extra Network 1
    > 4th Inception block
    > 5th Inception block
    > 6th Inception block
    > Extra Network 2
    > 7th Inception block
    > max-pooling layer: pool_size = (3,3), strides = 2'''

    X = Inception_block(X, f1 = 192, f2_conv1 = 96, f2_conv3 = 208, f3_conv1 = 16, f3_conv5 = 48, f4 = 64)

    X1 = Extra_Network1(X)

    X = Inception_block(X, f1 = 160, f2_conv1 = 112, f2_conv3 = 224, f3_conv1 = 24, f3_conv5 = 64, f4 = 64)
    X = Inception_block(X, f1 = 128, f2_conv1 = 128, f2_conv3 = 256, f3_conv1 = 24, f3_conv5 = 64, f4 = 64)
    X = Inception_block(X, f1 = 112, f2_conv1 = 144, f2_conv3 = 288, f3_conv1 = 32, f3_conv5 = 64, f4 = 64)

    X2 = Extra_Network2(X)

    X = Inception_block(X, f1 = 256, f2_conv1 = 160, f2_conv3 = 320, f3_conv1 = 32, f3_conv5 = 128, f4 = 128)

    X = MaxPooling2D(pool_size = (3,3), strides = 2)(X)

    return X, X1, X2

def layer_5(X):

    '''composed of :
    > 8th Inception block
    > 9th Inception block
    > Global Average pooling layer
    > Dropoutlayer'''

    X = Inception_block(X, f1 = 256, f2_conv1 = 160, f2_conv3 = 320, f3_conv1 = 32, f3_conv5 = 128, f4 = 128)
    X = Inception_block(X, f1 = 384, f2_conv1 = 192, f2_conv3 = 384, f3_conv1 = 48, f3_conv5 = 128, f4 = 128)

    X = GlobalAveragePooling2D(name = 'GAPL')(X)

    X = Dropout(0.4)(X)

    return X

def Extra_Network1(X):

    X1 = AveragePooling2D(pool_size = (5,5), strides = 3)(X)
    X1 = Conv2D(filters = 128, kernel_size = (1,1), padding = 'same', activation = 'relu')(X1)
    X1 = Flatten()(X1)
    X1 = Dense(1024, activation = 'relu')(X1)
    X1 = Dropout(0.7)(X1)
    X1 = Dense(n_classes, activation = 'softmax', name = 'output_1')(X1)

    return X1

def Extra_Network2(X):

    X2 = AveragePooling2D(pool_size = (5,5), strides = 3)(X)
    X2 = Conv2D(filters = 128, kernel_size = (1,1), padding = 'same', activation = 'relu')(X2)
    X2 = Flatten()(X2)
    X2 = Dense(1024, activation = 'relu')(X2)
    X2 = Dropout(0.7)(X2)
    X2 = Dense(n_classes, activation = 'softmax', name = 'output_2')(X2)

    return X2

def _GoogleNet():

    # input layer
    input_layer = Input(shape = (224, 224, 3))

    #architecture broken into layers
    X = layer_1(input_layer)
    X = layer_2(X)
    X = layer_3(X)

    X, X1, X2 = layer_4(X)

    X = layer_5(X)

    # output layer
    X = Dense(n_classes, activation = 'softmax', name = 'output_3')(X)

    # model
    model = Model(inputs = input_layer,  outputs = [X, X1, X2], name = 'GoogLeNet')

    return model

thats how i compiled my model :

def CompileModel(name, model):

    if name == 'GoogleNet':
        model.compile(optimizer = 'adam',
                      loss = categorical_crossentropy,
                      metrics={"output_1":"accuracy",
                               "output_2":"accuracy",
                               "output_3":"accuracy"})

    return model

def CompileModel(name, model):

    if name == 'GoogleNet':
        model.compile(optimizer = 'adam',
                      loss = categorical_crossentropy,
                      metrics={"output_1":"accuracy",
                               "output_2":"accuracy",
                               "output_3":"accuracy"})

    return model

def CompileModel(name, model):

    if name == 'GoogleNet':
        model.compile(optimizer = 'adam',
                      loss = categorical_crossentropy,
                      metrics={"output_1":"accuracy",
                               "output_2":"accuracy",
                               "output_3":"accuracy"})

    return model

def CompileModel(name, model):

    if name == 'GoogleNet':
        model.compile(optimizer = 'adam',
                      loss = categorical_crossentropy,
                      metrics={"output_1":"accuracy",
                               "output_2":"accuracy",
                               "output_3":"accuracy"})

    return model

compiled_model = BuildModel('GoogleNet')
model, history = FitModel('GoogleNet', compiled_model)

and finally the error ii am getting is like this any solution on how to solve it :

Epoch 1/40

2023-01-04 22:37:40.595715: I tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:428] Loaded cuDNN version 8100
2023-01-04 22:37:41.117823: I tensorflow/tsl/platform/default/subprocess.cc:304] Start cannot spawn child process: No such file or directory
2023-01-04 22:37:41.118274: I tensorflow/tsl/platform/default/subprocess.cc:304] Start cannot spawn child process: No such file or directory
2023-01-04 22:37:41.118307: W tensorflow/compiler/xla/stream_executor/gpu/asm_compiler.cc:85] Couldn't get ptxas version string: INTERNAL: Couldn't invoke ptxas --version
2023-01-04 22:37:41.118676: I tensorflow/tsl/platform/default/subprocess.cc:304] Start cannot spawn child process: No such file or directory
2023-01-04 22:37:41.118766: W tensorflow/compiler/xla/stream_executor/gpu/redzone_allocator.cc:318] INTERNAL: Failed to launch ptxas
Relying on driver to perform ptx compilation.
Modify $PATH to customize ptxas location.
This message will be only logged once.
2023-01-04 22:37:43.785545: I tensorflow/compiler/xla/service/service.cc:173] XLA service 0x1d4de930 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
2023-01-04 22:37:43.785576: I tensorflow/compiler/xla/service/service.cc:181]   StreamExecutor device (0): NVIDIA GeForce GTX 1650, Compute Capability 7.5
2023-01-04 22:37:43.798640: I tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.cc:268] disabling MLIR crash reproducer, set env var `MLIR_CRASH_REPRODUCER_DIRECTORY` to enable.
2023-01-04 22:37:43.844140: W tensorflow/compiler/xla/service/gpu/nvptx_helper.cc:56] Can't find libdevice directory ${CUDA_DIR}/nvvm/libdevice. This may result in compilation or runtime failures, if the program we try to run uses routines from libdevice.
Searched for CUDA in the following directories:
  ./cuda_sdk_lib
  /usr/local/cuda-11.2
  /usr/local/cuda
  .

2023-01-04 22:37:48.488260: W tensorflow/core/framework/op_kernel.cc:1830] OP_REQUIRES failed at xla_ops.cc:446 : INTERNAL: libdevice not found at ./libdevice.10.bc

---------------------------------------------------------------------------
InternalError                             Traceback (most recent call last)
Cell In[31], line 2
      1 compiled_model = BuildModel('GoogleNet')
----> 2 model, history = FitModel('GoogleNet', compiled_model)

Cell In[29], line 12, in FitModel(name, model)
      7 callbacks_ = [
      8     tf.keras.callbacks.EarlyStopping(patience = 2)
      9 ]
     11 if name == 'GoogleNet':
---> 12     history = model.fit(train_image_generator,
     13                         epochs = EPOCHS,
     14                         callbacks = callbacks_,
     15                         validation_data = valid_image_generator,
     16                         steps_per_epoch = (int(len(train_image_generator.labels) / 80)),
     17                         validation_steps = (int(len(valid_image_generator.labels) / 80)))
     19     model.load_weights(name + '_Weights.h5')
     21 return history, model

File ~/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/utils/traceback_utils.py:70, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     67     filtered_tb = _process_traceback_frames(e.__traceback__)
     68     # To get the full stack trace, call:
     69     # `tf.debugging.disable_traceback_filtering()`
---> 70     raise e.with_traceback(filtered_tb) from None
     71 finally:
     72     del filtered_tb

File ~/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/tensorflow/python/eager/execute.py:52, in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     50 try:
     51   ctx.ensure_initialized()
---> 52   tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
     53                                       inputs, attrs, num_outputs)
     54 except core._NotOkStatusException as e:
     55   if name is not None:

InternalError: Graph execution error:

Detected at node 'StatefulPartitionedCall_115' defined at (most recent call last):
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/runpy.py", line 196, in _run_module_as_main
      return _run_code(code, main_globals, None,
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/runpy.py", line 86, in _run_code
      exec(code, run_globals)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel_launcher.py", line 17, in <module>
      app.launch_new_instance()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/traitlets/config/application.py", line 1041, in launch_instance
      app.start()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/kernelapp.py", line 711, in start
      self.io_loop.start()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/tornado/platform/asyncio.py", line 215, in start
      self.asyncio_loop.run_forever()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/asyncio/base_events.py", line 603, in run_forever
      self._run_once()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/asyncio/base_events.py", line 1899, in _run_once
      handle._run()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/asyncio/events.py", line 80, in _run
      self._context.run(self._callback, *self._args)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 510, in dispatch_queue
      await self.process_one()
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 499, in process_one
      await dispatch(*args)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 406, in dispatch_shell
      await result
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 729, in execute_request
      reply_content = await reply_content
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/ipkernel.py", line 411, in do_execute
      res = shell.run_cell(
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/ipykernel/zmqshell.py", line 530, in run_cell
      return super().run_cell(*args, **kwargs)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 2940, in run_cell
      result = self._run_cell(
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 2995, in _run_cell
      return runner(coro)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/IPython/core/async_helpers.py", line 129, in _pseudo_sync_runner
      coro.send(None)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3194, in run_cell_async
      has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3373, in run_ast_nodes
      if await self.run_code(code, result, async_=asy):
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3433, in run_code
      exec(code_obj, self.user_global_ns, self.user_ns)
    File "/tmp/ipykernel_2575/1809520282.py", line 2, in <module>
      model, history = FitModel('GoogleNet', compiled_model)
    File "/tmp/ipykernel_2575/2245888179.py", line 12, in FitModel
      history = model.fit(train_image_generator,
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/utils/traceback_utils.py", line 65, in error_handler
      return fn(*args, **kwargs)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/engine/training.py", line 1650, in fit
      tmp_logs = self.train_function(iterator)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/engine/training.py", line 1249, in train_function
      return step_function(self, iterator)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/engine/training.py", line 1233, in step_function
      outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/engine/training.py", line 1222, in run_step
      outputs = model.train_step(data)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/engine/training.py", line 1027, in train_step
      self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/optimizers/optimizer_experimental/optimizer.py", line 527, in minimize
      self.apply_gradients(grads_and_vars)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/optimizers/optimizer_experimental/optimizer.py", line 1140, in apply_gradients
      return super().apply_gradients(grads_and_vars, name=name)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/optimizers/optimizer_experimental/optimizer.py", line 634, in apply_gradients
      iteration = self._internal_apply_gradients(grads_and_vars)
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/optimizers/optimizer_experimental/optimizer.py", line 1166, in _internal_apply_gradients
      return tf.__internal__.distribute.interim.maybe_merge_call(
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/optimizers/optimizer_experimental/optimizer.py", line 1216, in _distributed_apply_gradients_fn
      distribution.extended.update(
    File "/home/anish/miniconda3/envs/dlenv_conda/lib/python3.10/site-packages/keras/optimizers/optimizer_experimental/optimizer.py", line 1211, in apply_grad_to_update_var
      return self._update_step_xla(grad, var, id(self._var_key(var)))
Node: 'StatefulPartitionedCall_115'
libdevice not found at ./libdevice.10.bc
     [[{{node StatefulPartitionedCall_115}}]] [Op:__inference_train_function_24159]

I have tried training with other models and also checked the input output shape of images but have not found any solution


问:
/usr/bin/ld: cannot open output file files
*I'm executing the program in ubuntu *

```<code>#include <iostream>
#include <dirent.h>
#include <sys/types.h>

using namespace std;
void list_dir(const char *path) {

   struct dirent *entry;
   DIR *dir = opendir(path);

   if (dir == NULL) {
   cout << "Null \n";
      return;
   }
   while ((entry = readdir(dir)) != NULL) {
    cout << entry->d_name << endl;

   }
   closedir(dir);

}
int main() {
   list_dir("/home/bilalubuntu/Desktop");
}
</code>```

I was expecting it will show the files and folder of a given directory in main function, it shows error
/usr/bin/ld: cannot open output file files: Is a directory
collect2: error: ld returned 1 exit status

Body:
*I'm executing the program in ubuntu *

#include <iostream>
#include <dirent.h>
#include <sys/types.h>

using namespace std;
void list_dir(const char *path) {

   struct dirent *entry;
   DIR *dir = opendir(path);

   if (dir == NULL) {
   cout << "Null \n";
      return;
   }
   while ((entry = readdir(dir)) != NULL) {
    cout << entry->d_name << endl;

   }
   closedir(dir);

}
int main() {
   list_dir("/home/bilalubuntu/Desktop");
}

I was expecting it will show the files and folder of a given directory in main function, it shows error
/usr/bin/ld: cannot open output file files: Is a directory
collect2: error: ld returned 1 exit status


问:
How can I get raw byte offsets and bytes read from that offset using the HDF5 C API?
I want to get raw byte offsets and the number of bytes read from that offset using the HDF5 C API. A parallel to this is using lseek to get the location of the file pointer i.e. the byte offset from which to read and number of bytes read returned by the read system call. I need to do something similar but using the HDF5 C API.</p>


问:
any way to suppress semicolon between citations in footnotes?
Hoping this is the right place for this question--

I'm writing a document in Markdown with a bibliography exported from Zotero using Better BibTeX, and I'm citing a source via a footnote that in turn quotes another source, and the proper (law review article) format in the footnote is

<source1> (quoting <source2>).

In my Markdown text I have

[@Reed, p. 25; \(quoting @vol3, p. 408)]

This comes very close to rendering the neededed format in the footnote BUT includes an unwanted semicolon after the second source--so the format it's producing is:

<source1>; (quoting <source2>).

Is there a way to suppress that semicolon between citations in particular instances? Wouldn't want have it suppressed universally/still need the semicolon between cites in most instances, but need to suppress it any time one source cites or quotes another source (which requires a parenthetical indication starting with "quoting" or "citing").

Thanks!


问:
(Rust) Implementing a trait generically for another trait
I have two traits, TypeOne and TypeTwo describing different kinds of objects. Both implement Sized so they are not object-safe (I cannot implement for dyn TypeOne or dyn TypeTwo). I also have a third trait Hashable which I would like to implement for both TypeOne and TypeTwo.

```<code>pub trait Hashable {
    fn hash(&self) -> &str;
}

pub trait TypeOne { }

pub trait TypeTwo { }

impl<T: TypeOne> Hashable for T {
    fn hash(&self) -> &str {
        todo!();
    }
}

impl<T: TypeTwo> Hashable for T {
    fn hash(&self) -> &str {
        todo!();
    }
}
</code>```

The above code gives a conflicting implementations error, which I fully understand. If a struct were to implement both TypeOne and TypeTwo it would have two different (i.e. conflicting) implementations.

From my understanding after asking a related question, there is a way to circumvent this limitation when the traits are defined within the same crate (see @kmdreko's response). Does anyone know a way around this?

Body:
I have two traits, TypeOne and TypeTwo describing different kinds of objects. Both implement Sized so they are not object-safe (I cannot implement for dyn TypeOne or dyn TypeTwo). I also have a third trait Hashable which I would like to implement for both TypeOne and TypeTwo.

pub trait Hashable {
    fn hash(&self) -> &str;
}

pub trait TypeOne { }

pub trait TypeTwo { }

impl<T: TypeOne> Hashable for T {
    fn hash(&self) -> &str {
        todo!();
    }
}

impl<T: TypeTwo> Hashable for T {
    fn hash(&self) -> &str {
        todo!();
    }
}

The above code gives a conflicting implementations error, which I fully understand. If a struct were to implement both TypeOne and TypeTwo it would have two different (i.e. conflicting) implementations.

From my understanding after asking a related question, there is a way to circumvent this limitation when the traits are defined within the same crate (see @kmdreko's response). Does anyone know a way around this?