问:
importing ERROR: importing 'simtk.openmm' is deprecated. import 'openmm' instead
I am running a program 'MSMBuilder', it works well on the last week but suddenly an error came out, saying 'importing 'simtk.openmm' is deprecated. import 'openmm' instead'.
But there is no command such as 'import simtk.openmm' in my code.
Where this error came from?

Here is my code..

```<code>from msmbuilder.io import gather_metadata, save_meta, NumberedRunsParser

##Construct and save the dataframe
parser= NumberedRunsParser(
      traj_fmt="trajectory-{run}.xtc",
      top_fn="top.pdb",
      step_ps=50,
)
meta = gather_metadata("trajs/*.xtc", parser)
save_meta(meta)
</code>```

Body:
I am running a program 'MSMBuilder', it works well on the last week but suddenly an error came out, saying 'importing 'simtk.openmm' is deprecated. import 'openmm' instead'.
But there is no command such as 'import simtk.openmm' in my code.
Where this error came from?

Here is my code..

from msmbuilder.io import gather_metadata, save_meta, NumberedRunsParser

##Construct and save the dataframe
parser= NumberedRunsParser(
      traj_fmt="trajectory-{run}.xtc",
      top_fn="top.pdb",
      step_ps=50,
)
meta = gather_metadata("trajs/*.xtc", parser)
save_meta(meta)


来源: stackexchange

问:
How to integrate adminjs with pino-http?

I would like to log every request made into adminjs along with the account Id or admin user Id of the person who executed the request.

How can I hook into adminjs and log HTTP requests made by pino-http

This is what my authenticated router looks like

```<code>const adminbroRouter = AdminBroExpress.buildAuthenticatedRouter(
  adminBro,
  {
    authenticate: async (email, password) => {
      try {
        const account = await AuthService.getByEmail(email);
        if (!account) {
          return false;
        }
        const { password: accountPassword } =
          await AuthService.getPasswordByEmail(email);
        if (!(await isHashEqual(accountPassword, password))) {
          return false;
        }
        if (!AuthService.isAdmin(account as any)) {
          return false;
        }
        return account;
      } catch (error) {
        return false;
      }
    },
    cookiePassword: ADMINJS_COOKIE_PASSWORD,
    cookieName: ADMINJS_COOKIE_NAME,
    maxRetries: {
      count: ADMINJS_MAX_RETRIES_COUNT,
      duration: ADMINJS_MAX_RETRIES_DURATION,
    },
  },
  null,
  sessionOptions,
);
</code>```

I am facing an issue with the customProps method in pino-http currently which is where I can get the accountId of the logged in user

```<code>customProps: (req, res) => {
  const accountId = req.user ? req.user.id : null;
  return {
    accountId,
  };
},
</code>```

How do I get the admin user id in the above function or distinguish between when I am logged in as non-admin vs admin?

I am using passport-local with express-session

After reading through their docs, this is the closest thing I could find which is @adminjs/logger library

However it is not what I expected, any suggestions?

ContentLicense: CC BY-SA 4.0

Body:
I would like to log every request made into adminjs along with the account Id or admin user Id of the person who executed the request.

How can I hook into adminjs and log HTTP requests made by pino-http

This is what my authenticated router looks like

const adminbroRouter = AdminBroExpress.buildAuthenticatedRouter(
  adminBro,
  {
    authenticate: async (email, password) => {
      try {
        const account = await AuthService.getByEmail(email);
        if (!account) {
          return false;
        }
        const { password: accountPassword } =
          await AuthService.getPasswordByEmail(email);
        if (!(await isHashEqual(accountPassword, password))) {
          return false;
        }
        if (!AuthService.isAdmin(account as any)) {
          return false;
        }
        return account;
      } catch (error) {
        return false;
      }
    },
    cookiePassword: ADMINJS_COOKIE_PASSWORD,
    cookieName: ADMINJS_COOKIE_NAME,
    maxRetries: {
      count: ADMINJS_MAX_RETRIES_COUNT,
      duration: ADMINJS_MAX_RETRIES_DURATION,
    },
  },
  null,
  sessionOptions,
);

I am facing an issue with the customProps method in pino-http currently which is where I can get the accountId of the logged in user

customProps: (req, res) => {
  const accountId = req.user ? req.user.id : null;
  return {
    accountId,
  };
},

How do I get the admin user id in the above function or distinguish between when I am logged in as non-admin vs admin?

I am using passport-local with express-session

After reading through their docs, this is the closest thing I could find which is @adminjs/logger library

However it is not what I expected, any suggestions?


问:
COleClientItem::CreateFromFile() is strange on Windows11 but is OK on Windows10
I got a strange result when executed the next code:

```<code>BOOL ret = pOleClientItem->CreateFromFile("a-bitmap-file.bmp");
</code>```

On Windows11 but it is OK on Windows10 (pOleClientItem is a pointer to COleClientItem instance object).

The return code is TRUE, but that object's surface is not correctly drawn (on Windows11).

I tried the following,

I tried .png file instead .bmp file, and got a same result.
I tried CreateFromClipboard(), and got a same result.
a-bitmap-file.bmp is full-path.
a-bitmap-file.bmp is set security policy as full-control.

Body:
I got a strange result when executed the next code:

BOOL ret = pOleClientItem->CreateFromFile("a-bitmap-file.bmp");

On Windows11 but it is OK on Windows10 (pOleClientItem is a pointer to COleClientItem instance object).

The return code is TRUE, but that object's surface is not correctly drawn (on Windows11).

I tried the following,

I tried .png file instead .bmp file, and got a same result.
I tried CreateFromClipboard(), and got a same result.
a-bitmap-file.bmp is full-path.
a-bitmap-file.bmp is set security policy as full-control.


问:
RedBaron analog in javascript?
I need to read a python file from javascript. I used in another project RedBaron which was quite helpful since I can easily access different node types and their value. Since I cannot use this library in Javascript since RedBaron is  a python library I wanted to ask you all if you know a library that is similar to RedBaron.

Thanks in advance!

I tried using a line by line reader in Javascript but it is not sufficient for my needs. As I explained earlier I want to access different node types their values or operators.

Title: RedBaron analog in javascript?


问:
How to fix class not found error exception in freetts 1.2.2 VoiceManager in Maven on Windows
I am new to freetts and I want to convert text to speech, but I am getting class not found exception.

My source code

package com.sewonet;

import com.sun.speech.freetts.VoiceManager;
import com.sun.speech.freetts.Voice;

public class App {
    public static void main(String[] args) throws Exception{
        VoiceManager voiceManager = VoiceManager.getInstance();
        Voice voice = VoiceManager.getVoice("kelvin16");
        voice.speak("I love java");
    }

}
```
<p>Code compilation does not generate any error but generate the below error at runtime.</p>
<pre class="lang-none prettyprint-override"><code>Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/speech/freetts/VoiceManager
        at com.sewonet.App.main(App.java:7)
Caused by: java.lang.ClassNotFoundException: com.sun.speech.freetts.VoiceManager
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        ... 1 more
</code>```

Body:
I am new to freetts and I want to convert text to speech, but I am getting class not found exception.

My source code

package com.sewonet;

import com.sun.speech.freetts.VoiceManager;
import com.sun.speech.freetts.Voice;

public class App {
    public static void main(String[] args) throws Exception{
        VoiceManager voiceManager = VoiceManager.getInstance();
        Voice voice = VoiceManager.getVoice("kelvin16");
        voice.speak("I love java");
    }

}

Code compilation does not generate any error but generate the below error at runtime.

Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/speech/freetts/VoiceManager
        at com.sewonet.App.main(App.java:7)
Caused by: java.lang.ClassNotFoundException: com.sun.speech.freetts.VoiceManager
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        ... 1 more


问:
How do I change the terminal's path style in Mac OS
I have searched on Google but I couldn’t find the exact solution.

Please take a look at the picture and let me know how to change the path's background color as you can see.

I know how to change the font or the background but I meant that exactly background of the path in terminal.


问:
FullCalendar Won't Show

$(document).ready(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    var booking = @json($events);

    $('#calendar').fullCalendar({
        header: {
            left: 'prev, next today',
            center: 'title',
            right: 'month, agendaWeek, agendaDay',
        },
    });
});
```
<p>Whenever I implement the code above, the full calendar doesn't show but when I comment out <code>var booking = @json($events);</code>, the full calendar appears.</p>
<p>I tried the code below and it still didn't work:</p>
<pre class="lang-js prettyprint-override"><code>$(document).ready(function () {
    var events = JSON.parse('@json($events)');

    console.log(events)

    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next,today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        }
    })
});
</code>```

Any help is greatly appreciated.

Title: FullCalendar Won't Show

Body:
$(document).ready(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    var booking = @json($events);

    $('#calendar').fullCalendar({
        header: {
            left: 'prev, next today',
            center: 'title',
            right: 'month, agendaWeek, agendaDay',
        },
    });
});

Whenever I implement the code above, the full calendar doesn't show but when I comment out var booking = @json($events);, the full calendar appears.

I tried the code below and it still didn't work:

$(document).ready(function () {
    var events = JSON.parse('@json($events)');

    console.log(events)

    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next,today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        }
    })
});

Any help is greatly appreciated.


问:
Can you access the shadow dom from a script inside the shadow dom?
Can you access the shadow dom from within a script inside the shadow dom?

Here's a dumb example of the kind of code I might want. Not sure I'm a fan of Chrome's extension for declarative shadow Dom but it's useful for the example.

Open shadow Dom might be the simplest option but it's still annoying.

```<code><div>
<template shadowroot="closed">
<script type="module" src="menu.mjs"></script>

<div id="summary">
  <slot name="menu"></slot>
  <button id="menu-button">Open</button>
</div>
<div id="details">
<slot></slot>
</div>
</template>

<h2 slot="menu">Menu</h2>

<a>Home</a>
<a>Search</a>

</div>
</code>```

Body:
Can you access the shadow dom from within a script inside the shadow dom?

Here's a dumb example of the kind of code I might want. Not sure I'm a fan of Chrome's extension for declarative shadow Dom but it's useful for the example.

Open shadow Dom might be the simplest option but it's still annoying.

<template shadowroot="closed">

  <slot name="menu"></slot>
  <button id="menu-button">Open</button>

<slot></slot>

</template>

Menu

Home
Search


问:
PineScript Help - Backtesting Strategy "No Data", uknown error in logic
Backtesting Strategy "No Data" on any timeframe, uknown error in logic. Visually with the indicators there should be positions taken.

The issue occurred when I changed timeframe on RSI and SMA from chart to 720 (12HR) with the request.security function. Searched in here and in the pinescript docs and cant figure out the error.

Any help would be appreciated!

Script:

```<code>strategy('RSI Crossover Strategy', shorttitle='RSI Cross', default_qty_type=strategy.percent_of_equity, default_qty_value=5, initial_capital=1000, calc_on_every_tick=true)
// inputs
rsiLength = input(title='RSI Length', defval=14)
smaLength = input(title='SMA Length', defval=21)
// data/series
rsi = request.security(syminfo.ticker, "720", ta.rsi(close, rsiLength))
sma = request.security(syminfo.ticker,"720", ta.sma(rsi, smaLength))
ma = request.security(syminfo.ticker, "1D", ta.sma(close, 200))
// plot
plotColor = rsi > sma ? color.green : color.red
rsiPlot = plot(rsi, color=color.new(plotColor, 0), title='RSI')
smaPlot = plot(sma, color=color.new(color.white, 0), title='SMA')
fillColor = rsi > sma ? color.lime : color.red
fill(rsiPlot, smaPlot, color=color.new(fillColor, 75))
oversoldLine = hline(30, title='Oversold level')
overboughtLine = hline(70, title='Overbought level')
// strategy
buy = ta.crossover(rsi, sma) and rsi<44
sell = ta.crossunder(rsi, sma) and rsi>50 and close<ma
TPL = ta.crossunder(rsi, sma) and rsi>55
TPS = ta.crossover(rsi, sma) and rsi<45

if ((ta.crossover(rsi, sma)) and (rsi<44))
    strategy.entry("Long", strategy.long, comment="Long")

if ((ta.crossunder(rsi, sma)) and (rsi>55))
    strategy.close("Long", comment="Close Long")

if ((ta.crossunder(rsi, sma)) and (rsi>50) and (close<ma))
    strategy.entry("Short",strategy.short, comment="Short")

if ((ta.crossover(rsi, sma)) and (rsi<45))
    strategy.close("Short", comment="Close Short")
</code>```

Intent is to backtest a strategy with position entries and exits occuring when RSI and RSI SMA crossover and cross under on 12HR, executing on the 1HR close. 200D MA is to screen for short entry. I.e. no shorts if close is above 200D MA.

Body:
Backtesting Strategy "No Data" on any timeframe, uknown error in logic. Visually with the indicators there should be positions taken.

The issue occurred when I changed timeframe on RSI and SMA from chart to 720 (12HR) with the request.security function. Searched in here and in the pinescript docs and cant figure out the error.

Any help would be appreciated!

Script:

strategy('RSI Crossover Strategy', shorttitle='RSI Cross', default_qty_type=strategy.percent_of_equity, default_qty_value=5, initial_capital=1000, calc_on_every_tick=true)
// inputs
rsiLength = input(title='RSI Length', defval=14)
smaLength = input(title='SMA Length', defval=21)
// data/series
rsi = request.security(syminfo.ticker, "720", ta.rsi(close, rsiLength))
sma = request.security(syminfo.ticker,"720", ta.sma(rsi, smaLength))
ma = request.security(syminfo.ticker, "1D", ta.sma(close, 200))
// plot
plotColor = rsi > sma ? color.green : color.red
rsiPlot = plot(rsi, color=color.new(plotColor, 0), title='RSI')
smaPlot = plot(sma, color=color.new(color.white, 0), title='SMA')
fillColor = rsi > sma ? color.lime : color.red
fill(rsiPlot, smaPlot, color=color.new(fillColor, 75))
oversoldLine = hline(30, title='Oversold level')
overboughtLine = hline(70, title='Overbought level')
// strategy
buy = ta.crossover(rsi, sma) and rsi<44
sell = ta.crossunder(rsi, sma) and rsi>50 and close<ma
TPL = ta.crossunder(rsi, sma) and rsi>55
TPS = ta.crossover(rsi, sma) and rsi<45

if ((ta.crossover(rsi, sma)) and (rsi<44))
    strategy.entry("Long", strategy.long, comment="Long")

if ((ta.crossunder(rsi, sma)) and (rsi>55))
    strategy.close("Long", comment="Close Long")

if ((ta.crossunder(rsi, sma)) and (rsi>50) and (close<ma))
    strategy.entry("Short",strategy.short, comment="Short")

if ((ta.crossover(rsi, sma)) and (rsi<45))
    strategy.close("Short", comment="Close Short")

Intent is to backtest a strategy with position entries and exits occuring when RSI and RSI SMA crossover and cross under on 12HR, executing on the 1HR close. 200D MA is to screen for short entry. I.e. no shorts if close is above 200D MA.


问:
How do I shorten a number?
How would I go about shortening a number like 1,000 into 1k, 1,000,000 into 1m, and so on in Python 3.X?

I have been experimenting with this line of code:

print("{:,}".format(1000)) # returns 1,000
```

I get errors when I place anything besides a comma there.

Title: How do I shorten a number?

Body:
How would I go about shortening a number like 1,000 into 1k, 1,000,000 into 1m, and so on in Python 3.X?

I have been experimenting with this line of code:

print("{:,}".format(1000)) # returns 1,000

I get errors when I place anything besides a comma there.


问:
Getting rid of white space after transform
I'm trying to translate an element such that it always stays on the screen, but it seems that it's leaving some whitespace on the bottom. I can't use position absolute as I want high performance on the animation. I have tried making the width and height 0 and changing the transform-origin property, but nothing has worked so far. Here is my website and the relevant code.

JSX:

```<code>  useEffect(() => {
    const onScroll = () => {
      let test = document.getElementsByClassName('scrollToTop')[0];
      test.style.transform =
        'translate(calc(100vw - 36px - 10px),' +
        (window.scrollY -
          document.body.scrollHeight +
          window.innerHeight -
          10) +
        'px)';
      console.log(test.style.transform);
    };
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
</code>```

CSS:

```<code>.scrollToTop {
  /* opacity: 0; */
  transform: translate(0, 0);
  visibility: none;
  background: var(--blue);
  transition: opacity 0.5s ease-in-out;
  display: inline-block;
}
</code>```

Body:
I'm trying to translate an element such that it always stays on the screen, but it seems that it's leaving some whitespace on the bottom. I can't use position absolute as I want high performance on the animation. I have tried making the width and height 0 and changing the transform-origin property, but nothing has worked so far. Here is my website and the relevant code.

JSX:

  useEffect(() => {
    const onScroll = () => {
      let test = document.getElementsByClassName('scrollToTop')[0];
      test.style.transform =
        'translate(calc(100vw - 36px - 10px),' +
        (window.scrollY -
          document.body.scrollHeight +
          window.innerHeight -
          10) +
        'px)';
      console.log(test.style.transform);
    };
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

CSS:

.scrollToTop {
  /* opacity: 0; */
  transform: translate(0, 0);
  visibility: none;
  background: var(--blue);
  transition: opacity 0.5s ease-in-out;
  display: inline-block;
}


问:
I want to concat element-wise two numpy integer arrays
A = [[1 2], [ 3 4]] (order is 2x2)

B = [[5 6], [ 7 8]] (order is 2x2)

C = [[1 5 2 6], [3 7 4 8]] (order is 2x4)

Above is a specific example. Generally, I have two integer matrices of 120x6 and after concatenation, I need a 120x12 single matrix but it should be element-wise as in the above example.

I tried concat and hstack functions but couldn't get the desired result.


问:
how to unwind generic arrays in typescript
I'm trying to implement MongoDB style array "unwinds" in typescript.
I want to implement a generic function that returns the correct answer with well defined types.

I provided an example problem with the expected result below.

I don't understand the syntax to

determine the type of the unwound items returned from an input generic type

omit the key that contains the nested array

describe('unwindByKey', () => {
// please help #1
  type UnwindItemType = <T, key = key of T> Omit<T, key>

// please help #2
  function unwindByKey<T extends {}, K = keyof T, U>(items: T[], key: K): U[] {
    return items.reduce((accum, item) => {
      const {[key]: keyItems, ...itemRest} = item
      const unwoundItems: UnwindItemType<T, key> = keyItems.map(keyItem => ({
        ...itemRest
        [key]: keyItem,
      })
      return [...accum, ...unwoundItems]
    }, [])
  }

// example problem
  interface DataItem {
    a: number
    b: number[]
  }

  type UnwoundDataItem = UnwindItemType<DataItem, 'b'>

// should make this
  // interface UnwoundDataItem {
  //   a: number
  //   b: number
  // }

  const data: DataItem[] = [
    {a: 0, b: [0, 1, 2]},
    {a: 1, b: [3, 4, 5]},
  ]

  const expectedData: UnwoundDataItem[] = [
    {a: 0, b: 0},
    {a: 0, b: 1},
    {a: 0, b: 2},
    {a: 1, b: 3},
    {a: 1, b: 4},
    {a: 1, b: 5},
  ]

  test('it works', () => {
    const result = unwindByKey(data, 'b')
    expect(result.length).toBe(expectedData.length)
  })

})
```


问:
How to make encryption faster in c using AES128 CBC faster using OPENSSL
The code works fine it's just I want it faster but am unsure how to. here is what the code does: This code encrypts the contents of a specified directory and all its subdirectories recursively. The encrypt_file function is used to encrypt each file in the directory and its subdirectories. The encrypt_directory function reads each entry in the directory using readdir and checks if it is a regular file or a directory. If it is a regular file, it encrypts the file using the encrypt_file function and appends ".enc" to the filename. If it is a directory, it calls itself recursively to process the subdirectory.

The encryption itself is done using the AES algorithm in CBC mode, with a randomly generated key and IV (initialization vector). The key and IV are written to the beginning of the encrypted file, followed by the encrypted contents of the file. The EVP_EncryptUpdate function is used to encrypt the file in blocks, and EVP_EncryptFinal_ex is used to finalize the encryption and write the final block of ciphertext to the output file.

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "dirent.h"
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/aes.h>

#define AES_BLOCK_SIZE 16

int encrypt_file(const char* in_filename, const char* out_filename)
{
    EVP_CIPHER_CTX* ctx;
    int len;
    int ciphertext_len;
    FILE* in_file, * out_file;
    unsigned char key[AES_BLOCK_SIZE];
    unsigned char iv[AES_BLOCK_SIZE];
    unsigned char in_buf[AES_BLOCK_SIZE];
    unsigned char out_buf[AES_BLOCK_SIZE + EVP_MAX_BLOCK_LENGTH];

    /* Generate random key and IV */
    if (!RAND_bytes(key, AES_BLOCK_SIZE))
        return 0;
    if (!RAND_bytes(iv, AES_BLOCK_SIZE))
        return 0;

    /* Initialize the encryption context */
    if (!(ctx = EVP_CIPHER_CTX_new()))
        return 0;
    if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv))
        return 0;

    /* Open the input and output files */
    if (!(in_file = fopen(in_filename, "rb")))
        return 0;
    if (!(out_file = fopen(out_filename, "wb")))
        return 0;

    /* Write the key and IV to the output file */
    if (fwrite(key, 1, AES_BLOCK_SIZE, out_file) != AES_BLOCK_SIZE)
        return 0;
    if (fwrite(iv, 1, AES_BLOCK_SIZE, out_file) != AES_BLOCK_SIZE)
        return 0;

    /* Encrypt and write the ciphertext to the output file */
    while ((len = fread(in_buf, 1, AES_BLOCK_SIZE, in_file))) {
        if (1 != EVP_EncryptUpdate(ctx, out_buf, &ciphertext_len, in_buf, len))
            return 0;
        if (fwrite(out_buf, 1, ciphertext_len, out_file) != ciphertext_len)
            return 0;
    }

    /* Finalize the encryption */
    if (1 != EVP_EncryptFinal_ex(ctx, out_buf, &ciphertext_len))
        return 0;
    if (fwrite(out_buf, 1, ciphertext_len, out_file) != ciphertext_len)
        return 0;

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);
    fclose(in_file);
    fclose(out_file);

    return 1;
}

void encrypt_directory(const char* dir_name)
{
    DIR* dir;
    struct dirent* entry;
    char path[1024];

    /* Open the directory specified by dir_name */
    if (!(dir = opendir(dir_name)))
        return;

    /* Read each entry from the directory */
    while ((entry = readdir(dir))) {
        /* Ignore the current and parent directories */
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
            continue;

        /* Construct the full path of the entry */
        snprintf(path, sizeof(path), "%s/%s", dir_name, entry->d_name);

        /* If the entry is a directory, call encrypt_directory recursively */
        if (entry->d_type == DT_DIR) {
            encrypt_directory(path);
        }
        /* If the entry is a file, encrypt it */
        else if (entry->d_type == DT_REG) {
            /* Construct the output filename by appending ".enc" to the original filename */
            char out_filename[1024];
            strcpy(out_filename, path);
            strcat(out_filename, ".enc");

            /* Call encrypt_file to encrypt the file */
            if (encrypt_file(path, out_filename)) {
                /* If encryption was successful, delete the original file */
                remove(path);
            }
        }
    }

    /* Close the directory */
    closedir(dir);
}
</code>```

I tried threading and it was a huge mess.

Body:
The code works fine it's just I want it faster but am unsure how to. here is what the code does: This code encrypts the contents of a specified directory and all its subdirectories recursively. The encrypt_file function is used to encrypt each file in the directory and its subdirectories. The encrypt_directory function reads each entry in the directory using readdir and checks if it is a regular file or a directory. If it is a regular file, it encrypts the file using the encrypt_file function and appends ".enc" to the filename. If it is a directory, it calls itself recursively to process the subdirectory.

The encryption itself is done using the AES algorithm in CBC mode, with a randomly generated key and IV (initialization vector). The key and IV are written to the beginning of the encrypted file, followed by the encrypted contents of the file. The EVP_EncryptUpdate function is used to encrypt the file in blocks, and EVP_EncryptFinal_ex is used to finalize the encryption and write the final block of ciphertext to the output file.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "dirent.h"
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/aes.h>

#define AES_BLOCK_SIZE 16

int encrypt_file(const char* in_filename, const char* out_filename)
{
    EVP_CIPHER_CTX* ctx;
    int len;
    int ciphertext_len;
    FILE* in_file, * out_file;
    unsigned char key[AES_BLOCK_SIZE];
    unsigned char iv[AES_BLOCK_SIZE];
    unsigned char in_buf[AES_BLOCK_SIZE];
    unsigned char out_buf[AES_BLOCK_SIZE + EVP_MAX_BLOCK_LENGTH];

    /* Generate random key and IV */
    if (!RAND_bytes(key, AES_BLOCK_SIZE))
        return 0;
    if (!RAND_bytes(iv, AES_BLOCK_SIZE))
        return 0;

    /* Initialize the encryption context */
    if (!(ctx = EVP_CIPHER_CTX_new()))
        return 0;
    if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv))
        return 0;

    /* Open the input and output files */
    if (!(in_file = fopen(in_filename, "rb")))
        return 0;
    if (!(out_file = fopen(out_filename, "wb")))
        return 0;

    /* Write the key and IV to the output file */
    if (fwrite(key, 1, AES_BLOCK_SIZE, out_file) != AES_BLOCK_SIZE)
        return 0;
    if (fwrite(iv, 1, AES_BLOCK_SIZE, out_file) != AES_BLOCK_SIZE)
        return 0;

    /* Encrypt and write the ciphertext to the output file */
    while ((len = fread(in_buf, 1, AES_BLOCK_SIZE, in_file))) {
        if (1 != EVP_EncryptUpdate(ctx, out_buf, &ciphertext_len, in_buf, len))
            return 0;
        if (fwrite(out_buf, 1, ciphertext_len, out_file) != ciphertext_len)
            return 0;
    }

    /* Finalize the encryption */
    if (1 != EVP_EncryptFinal_ex(ctx, out_buf, &ciphertext_len))
        return 0;
    if (fwrite(out_buf, 1, ciphertext_len, out_file) != ciphertext_len)
        return 0;

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);
    fclose(in_file);
    fclose(out_file);

    return 1;
}

void encrypt_directory(const char* dir_name)
{
    DIR* dir;
    struct dirent* entry;
    char path[1024];

    /* Open the directory specified by dir_name */
    if (!(dir = opendir(dir_name)))
        return;

    /* Read each entry from the directory */
    while ((entry = readdir(dir))) {
        /* Ignore the current and parent directories */
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
            continue;

        /* Construct the full path of the entry */
        snprintf(path, sizeof(path), "%s/%s", dir_name, entry->d_name);

        /* If the entry is a directory, call encrypt_directory recursively */
        if (entry->d_type == DT_DIR) {
            encrypt_directory(path);
        }
        /* If the entry is a file, encrypt it */
        else if (entry->d_type == DT_REG) {
            /* Construct the output filename by appending ".enc" to the original filename */
            char out_filename[1024];
            strcpy(out_filename, path);
            strcat(out_filename, ".enc");

            /* Call encrypt_file to encrypt the file */
            if (encrypt_file(path, out_filename)) {
                /* If encryption was successful, delete the original file */
                remove(path);
            }
        }
    }

    /* Close the directory */
    closedir(dir);
}

I tried threading and it was a huge mess.


问:
Problems using vector google map in React
I'm using Google maps in my react project, specifically I use @googlemaps/react-wrapper package. For my needs I need to be able to rotate the map, and for that, google maps has a vector rendering mode that supports rotation and tilt. So I've created a MapId, assigned it to my map and nothing happened. map.getRenderingType still returns 'raster' when it should be 'vector'.

Other than this, map works as expected, there are no issues with api keys or anything else. Maybe worth noting that I've restricted my key to 'Maps JavaScript API'.

Map Component:

```<code>export const Map: React.FC<MapProps> = ({ onClick, onIdle, tilt = 45, children, ...options }) => {
  const ref = useRef<HTMLDivElement>(null)
  const [map, setMap] = useState<google.maps.Map>()

  useEffect(() => {
    if (ref.current && !map) {
      setMap(new window.google.maps.Map(ref.current, {}))
    }
  }, [ref, map])

  // because React does not do deep comparisons, a custom hook is used
  // see discussion in https://github.com/googlemaps/js-samples/issues/946
  useDeepCompareEffect(() => {
    if (map) {
      map.setOptions({
        ...options,
        mapId: '74c0d82b6c7405ee',
        disableDefaultUI: true,
        center: { lat: 50, lng: 25 },
        zoom: 16,
        heading: 320,
        tilt: 47.5,
      })
    }
  }, [map, options])

  useEffect(() => {
    if (!map) return
    ;['click', 'idle'].forEach((eventName) => google.maps.event.clearListeners(map, eventName))

    if (onClick) {
      map.addListener('click', (e: google.maps.MapMouseEvent) => {
        onClick(e, map)
      })
    }

    if (onIdle) {
      map.addListener('idle', () => onIdle(map))
    }
  }, [map, onClick, onIdle])

  return <div style={{ flexGrow: '1', height: '100%' }} ref={ref} />
}
</code>```

Body:
I'm using Google maps in my react project, specifically I use @googlemaps/react-wrapper package. For my needs I need to be able to rotate the map, and for that, google maps has a vector rendering mode that supports rotation and tilt. So I've created a MapId, assigned it to my map and nothing happened. map.getRenderingType still returns 'raster' when it should be 'vector'.

Other than this, map works as expected, there are no issues with api keys or anything else. Maybe worth noting that I've restricted my key to 'Maps JavaScript API'.

Map Component:

export const Map: React.FC<MapProps> = ({ onClick, onIdle, tilt = 45, children, ...options }) => {
  const ref = useRef<HTMLDivElement>(null)
  const [map, setMap] = useState<google.maps.Map>()

  useEffect(() => {
    if (ref.current && !map) {
      setMap(new window.google.maps.Map(ref.current, {}))
    }
  }, [ref, map])

  // because React does not do deep comparisons, a custom hook is used
  // see discussion in https://github.com/googlemaps/js-samples/issues/946
  useDeepCompareEffect(() => {
    if (map) {
      map.setOptions({
        ...options,
        mapId: '74c0d82b6c7405ee',
        disableDefaultUI: true,
        center: { lat: 50, lng: 25 },
        zoom: 16,
        heading: 320,
        tilt: 47.5,
      })
    }
  }, [map, options])

  useEffect(() => {
    if (!map) return
    ;['click', 'idle'].forEach((eventName) => google.maps.event.clearListeners(map, eventName))

    if (onClick) {
      map.addListener('click', (e: google.maps.MapMouseEvent) => {
        onClick(e, map)
      })
    }

    if (onIdle) {
      map.addListener('idle', () => onIdle(map))
    }
  }, [map, onClick, onIdle])

  return

}


问:
Python file downloaded via tqdm consistently slows to a crawl
I'm trying to run a Python script using OpenAI's whisper module.  This is more or less right out of the box code that is right on their readme

```<code>import whisper

model = whisper.load_model("tiny")
</code>```

Running the script results in the following:

```<code>Warning (from warnings module):
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\whisper\__init__.py", line 47
    warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
UserWarning: C:\Users\joeSmoe\.cache\whisper\tiny.pt exists, but the SHA256 checksum does not match; re-downloading the file
</code>```

At first the download goes at a reasonable speed of about 4 MiB/s, but then after a second or two slows down to a crawl of about 10 kiB/s.  This happens every time I run the script.  I don't have any other connection issues.  I tried swapping out the model to the others listed on the readme but they all seem to take a very long amount of time (after starting out strong for the first second or two).

After hitting a keyboard interrupt I'm given these messages:

```<code>Traceback (most recent call last):
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\whisperTests.py", line 3, in <module>
    model = whisper.load_model("tiny")
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\whisper\__init__.py", line 102, in load_model
    checkpoint_file = _download(_MODELS[name], download_root, in_memory)
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\whisper\__init__.py", line 57, in _download
    loop.update(len(buffer))
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\tqdm\std.py", line 1256, in update
    self.refresh(lock_args=self.lock_args)
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\tqdm\std.py", line 1361, in refresh
    self.display()
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\tqdm\std.py", line 1509, in display
    self.sp(self.__str__() if msg is None else msg)
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\tqdm\std.py", line 350, in print_status
    fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\tqdm\std.py", line 343, in fp_write
    fp.write(_unicode(s))
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\tqdm\utils.py", line 145, in inner
    return func(*args, **kwargs)
KeyboardInterrupt
</code>```

I tested my network speed: 30 Mb/s, looked for similar issues with this tqdm module but haven't had any success.  I don't think this would be a server issue that's hosting the module because it starts off strong for the first few seconds every time.

Body:
I'm trying to run a Python script using OpenAI's whisper module.  This is more or less right out of the box code that is right on their readme

import whisper

model = whisper.load_model("tiny")

Running the script results in the following:

Warning (from warnings module):
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\whisper\__init__.py", line 47
    warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
UserWarning: C:\Users\joeSmoe\.cache\whisper\tiny.pt exists, but the SHA256 checksum does not match; re-downloading the file

At first the download goes at a reasonable speed of about 4 MiB/s, but then after a second or two slows down to a crawl of about 10 kiB/s.  This happens every time I run the script.  I don't have any other connection issues.  I tried swapping out the model to the others listed on the readme but they all seem to take a very long amount of time (after starting out strong for the first second or two).

After hitting a keyboard interrupt I'm given these messages:

Traceback (most recent call last):
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\whisperTests.py", line 3, in <module>
    model = whisper.load_model("tiny")
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\whisper\__init__.py", line 102, in load_model
    checkpoint_file = _download(_MODELS[name], download_root, in_memory)
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\whisper\__init__.py", line 57, in _download
    loop.update(len(buffer))
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\tqdm\std.py", line 1256, in update
    self.refresh(lock_args=self.lock_args)
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\tqdm\std.py", line 1361, in refresh
    self.display()
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\tqdm\std.py", line 1509, in display
    self.sp(self.__str__() if msg is None else msg)
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\tqdm\std.py", line 350, in print_status
    fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\tqdm\std.py", line 343, in fp_write
    fp.write(_unicode(s))
  File "C:\Users\joeSmoe\AppData\Local\Programs\Python\Python37\Lib\site-packages\tqdm\utils.py", line 145, in inner
    return func(*args, **kwargs)
KeyboardInterrupt

I tested my network speed: 30 Mb/s, looked for similar issues with this tqdm module but haven't had any success.  I don't think this would be a server issue that's hosting the module because it starts off strong for the first few seconds every time.


问:
Antd table How to wrap the columns to the next row on resize
I am working with react Antd table. How can I achieve the following using the table API. The below image shows the original table

After the resize, I want the table to look like this. Is there any way to achieve this  rseult?


问:
Get element's innerText from multiple pages
I need to get the innerText of multiple pages that look like this: website.com/abc/xyz/page-{}.

So far I'm using Selenium and undetected_chromedriver to bypass CloudFlare, get the website and get content using javascript, then click on next button to move to the next page.

The problem is, this method is quite slow. It took quite some time to load the page, and a little bit more time to get and write the content. So ~2000 pages took me an hour.

Also, for some reason, sometimes the written content of multiple next files are duplicates of one page. Though this would not happen if I don't use my laptop while it's running.

Is there a faster way to do this, i.e. another library. Or can I handle multiple tabs simultaneously? Because I don't want to open ~10 different windows at once or use 10 different driver, especially when I also need to load an adblocker to block ads embedded in the "next" button

Currently, I use

WebDriverWait(driver, 3).until(
       EC.presence_of_element_located((By.CLASS_NAME, "class_name")
))
```

to wait for the element to load, then execute return document.getElementsByClassName('className')[0].innerText to get the content, and write it to a file.

Then find element by CLASS_NAME of the next button and click it.

I used to execute location.href = {link.format(i+1)} (where link is the variable storing the link, and i is of the loop) to move to the next page. Not sure if it's faster or not.

Edit:

By "duplicate" I mean for example, page 1 content is abc, page 2 content is def, ... But for some reason, the code stays at page 1, continuously writting it content to page_2.txt, ... page_n.txt. It just don't move to the next page.

Managed to fix the "duplicate" issue by reverting back to location.href method.

Body:
I need to get the innerText of multiple pages that look like this: website.com/abc/xyz/page-{}.

So far I'm using Selenium and undetected_chromedriver to bypass CloudFlare, get the website and get content using javascript, then click on next button to move to the next page.

The problem is, this method is quite slow. It took quite some time to load the page, and a little bit more time to get and write the content. So ~2000 pages took me an hour.

Also, for some reason, sometimes the written content of multiple next files are duplicates of one page. Though this would not happen if I don't use my laptop while it's running.

Is there a faster way to do this, i.e. another library. Or can I handle multiple tabs simultaneously? Because I don't want to open ~10 different windows at once or use 10 different driver, especially when I also need to load an adblocker to block ads embedded in the "next" button

Currently, I use

WebDriverWait(driver, 3).until(
       EC.presence_of_element_located((By.CLASS_NAME, "class_name")
))

to wait for the element to load, then execute return document.getElementsByClassName('className')[0].innerText to get the content, and write it to a file.

Then find element by CLASS_NAME of the next button and click it.

I used to execute location.href = {link.format(i+1)} (where link is the variable storing the link, and i is of the loop) to move to the next page. Not sure if it's faster or not.

Edit:

By "duplicate" I mean for example, page 1 content is abc, page 2 content is def, ... But for some reason, the code stays at page 1, continuously writting it content to page_2.txt, ... page_n.txt. It just don't move to the next page.

Managed to fix the "duplicate" issue by reverting back to location.href method.


问:
Error when Installing Microsoft.Owin.Host.SystemWeb .NET WebForms
I am attempting to use Owin/Identity to authorize users at login/registration on an already existing .NET WebForms site. However, when following the instructions [provided my Microsoft]1 I run into an error when completing the "Configure the application for OWIN authentication" step. This step requires the installation of Microsoft.Owin.Host.SystemWeb. It installs fine through Nuget but then errors at debug. I am using Azure for the db call- Identity has to issue saving the usernames and hashed passwords in the Azure db.

Error at Debug:
Could not load file or assembly 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

From what I can tell the root cause of the error is a file is inconsistent or not in the correct folder.

I have tried... cleaning solutions, rebuilding solution, closing out the entire VS application, and reinstalling all Nuget Identity/Owin packages. I only need this Microsoft.Owin.Host.SystemWeb to run these two lines:


问:
How to dynamically create an image for instagram stories
So I can already post a picture on my app to Instagram stories. However, every time a user clicks the button to share the image, the text and profile photo should be different on the image—like the image below. Needs to be dyanmic.

Right now, I'm thinking of just having a view that's off the screen, then using react-native-view-shot to get the picture & have it be dynamic that way. I was just wondering if there was a better way to do this.


问:
Define 'operator<', constructors for a tuple-style struct in C++
For a 'tuple-style' C++ struct, such as

```<code>struct state {
  int a, b, c;
};
</code>```

how can we most quickly operator< and constructors with natural semantics (e.g. similar to those of std::pair)?

Specifically, is there a way to obtain the following methods without explicitly writing the implementation?

```<code>struct state {
    int a, b, c;
    state() { }  // a = b = c = 0
    state(int _a, int _b, int _c) {  } // a = _a, b = _b, c = _c

    bool operator<(const state& other) const {
        // first compare by a, then by b, then by c
        return (a == other.a ? (b == other.b ? (c < other.c) : b < other.b) : a < other.a)
    }
};
</code>```

More generally, does any approach for when the fields are not all of the same type? For example,

```<code>struct state {
    int a, b;
    string c;
};
</code>```

Body:
For a 'tuple-style' C++ struct, such as

struct state {
  int a, b, c;
};

how can we most quickly operator< and constructors with natural semantics (e.g. similar to those of std::pair)?

Specifically, is there a way to obtain the following methods without explicitly writing the implementation?

struct state {
    int a, b, c;
    state() { }  // a = b = c = 0
    state(int _a, int _b, int _c) {  } // a = _a, b = _b, c = _c

    bool operator<(const state& other) const {
        // first compare by a, then by b, then by c
        return (a == other.a ? (b == other.b ? (c < other.c) : b < other.b) : a < other.a)
    }
};

More generally, does any approach for when the fields are not all of the same type? For example,

struct state {
    int a, b;
    string c;
};


问:
AVD shows error Error while run the device : Illegal char *> at index 0: *.lock
Pixel 4 XL API 30 AVD of my flutter project is not working. It is showing me this error.
enter image description here

Is there anything you can do for me? Please help.


问:
GCP Org policy to restrict deletion of object and bucket in cloud storage
How to create GCP Org policy to restrict deletion of object and bucket in cloud storage.

I have a bucket and few objects in it. I would like t control the deletion part via an org policy even if the project has cloud storage admin rights for that bucket.

not able to see any.


问:
Rails & Groupdate gem to find users with more than X videos per month
Users in my Rails app make videos. I'm using the Groupdate gem to get the monthly active users (meaning the number of user who made more than 1 video in the month):

Video.group_by_month(:created_at).count("DISTINCT user_id")

which returns something like this:

```<code>{
 Mon, 01 Aug 2022=>116,
 Thu, 01 Sep 2022=>101,
 Sat, 01 Oct 2022=>109,
 Tue, 01 Nov 2022=>153,
 Thu, 01 Dec 2022=>104
}
</code>```

Now I want to get the number of user who made more than X videos, grouped by month as before.

How do I do that?

Body:
Users in my Rails app make videos. I'm using the Groupdate gem to get the monthly active users (meaning the number of user who made more than 1 video in the month):

Video.group_by_month(:created_at).count("DISTINCT user_id")

which returns something like this:

{
 Mon, 01 Aug 2022=>116,
 Thu, 01 Sep 2022=>101,
 Sat, 01 Oct 2022=>109,
 Tue, 01 Nov 2022=>153,
 Thu, 01 Dec 2022=>104
}

Now I want to get the number of user who made more than X videos, grouped by month as before.

How do I do that?


问:
Variable tank in fluid library anylogic
[Model]  [1]: https://i.stack.imgur.com/LVslR.png

[variable Tank]  [2]: https://i.stack.imgur.com/3EpIM.png

[Storage tank]  [3]: https://i.stack.imgur.com/Nx8LT.png

[Related tank]  [4]: https://i.stack.imgur.com/i1Tru.png

I'm new to anylogic and trying to learn fluid library. I tried to model a bulk conveyors network with select output and no problem with that. The problem i faced when i tried to assign tanks by changing a tank variable and give it a value of related desired tank( destination ). the flow chart works fine with no error but i cant see the corresponding tank in animation (2D or 3D) getting filled, as the model cant get the variable with the space markup of the tank. Appretiate the help.

Title: Variable tank in fluid library anylogic


问:
Specifying FilePath in Start-Process
I'm trying to boot up a localhost for some GitHub code I've cloned. I am getting the message:

```<code>cmdlet Start-Process at command pipeline position 1
Supply values for the following parameters:
FilePath:
</code>```

Followed by this error when I type anything

```<code>start : This command cannot be run due to the error: The system cannot find the file specified.
At line:1 char:1
+ start
+ ~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
</code>```

I feel this is so simple but need help, how can I specify the FilePath?

I've tried every solution I can currently find.

Title: Specifying FilePath in Start-Process

Body:
I'm trying to boot up a localhost for some GitHub code I've cloned. I am getting the message:

cmdlet Start-Process at command pipeline position 1
Supply values for the following parameters:
FilePath:

Followed by this error when I type anything

start : This command cannot be run due to the error: The system cannot find the file specified.
At line:1 char:1
+ start
+ ~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Start-Process], InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

I feel this is so simple but need help, how can I specify the FilePath?

I've tried every solution I can currently find.


问:
How to write a preprocessing_fn function that relies on an Artifact?
Let's consider a very straightforward pipeline like this:

example_gen = tfx.components.ImportExampleGen(input_base=_dataset_folder)

statistics_gen = tfx.components.StatisticsGen(examples=example_gen.outputs['examples'])

schema_gen = tfx.components.SchemaGen(
    statistics=statistics_gen.outputs['statistics'],
    infer_feature_shape=True)

transform = tfx.components.Transform(
    examples=example_gen.outputs['examples'],
    schema=schema_gen.outputs['schema'],
    module_file=os.path.abspath('preprocessing_fn.py'),
    custom_config={'schema': schema_gen.outputs['schema']})

components = [
    example_gen,
    statistics_gen,
    schema_gen,
    transform,
]

_pipeline_data_folder = './simple_pipeline_data'
pipeline = tfx.dsl.Pipeline(
    pipeline_name='simple_pipeline',
    pipeline_root=_pipeline_data_folder,
    metadata_connection_config=tfx.orchestration.metadata.sqlite_metadata_connection_config(
        f'{_pipeline_data_folder}/metadata.db'),
    components=components)

tfx.orchestration.LocalDagRunner().run(pipeline)

```
<p>The only part of this snippet worth pointing out is the <code>Transform</code> definition. Namely, I want to pass and use the <code>schema</code> artifact in my transformation logic. I was hoping I could write the <code>preprocessing_fn</code> like this:</p>
<pre class="lang-py prettyprint-override"><code>import os
from google.protobuf import text_format

def preprocessing_fn(inputs, custom_config):
    schema = text_format.Parse(os.path.join(custom_config['schema'].uri, 'schema.pbtxt'))
    # do something to the inputs based on the read schema
</code>```

But the problem is that the custom_config['schema'] is not an object of Artifact but a Channel. And the preprocessing_fn is called even before the artifact even exists. I mean I debugged and traced the code and realized that preprocessing_fn is called before the code that creates the artifact executes. So technically, it's impossible to use an artifact inside my preprocessing_fn function.

My question is, is there a way around this? Can I use the results of an artifact inside my preprocessing_fn function? How can I write a transformation that its logic is based on the results of the previous artifacts?

Body:
Let's consider a very straightforward pipeline like this:

example_gen = tfx.components.ImportExampleGen(input_base=_dataset_folder)

statistics_gen = tfx.components.StatisticsGen(examples=example_gen.outputs['examples'])

schema_gen = tfx.components.SchemaGen(
    statistics=statistics_gen.outputs['statistics'],
    infer_feature_shape=True)

transform = tfx.components.Transform(
    examples=example_gen.outputs['examples'],
    schema=schema_gen.outputs['schema'],
    module_file=os.path.abspath('preprocessing_fn.py'),
    custom_config={'schema': schema_gen.outputs['schema']})

components = [
    example_gen,
    statistics_gen,
    schema_gen,
    transform,
]

_pipeline_data_folder = './simple_pipeline_data'
pipeline = tfx.dsl.Pipeline(
    pipeline_name='simple_pipeline',
    pipeline_root=_pipeline_data_folder,
    metadata_connection_config=tfx.orchestration.metadata.sqlite_metadata_connection_config(
        f'{_pipeline_data_folder}/metadata.db'),
    components=components)

tfx.orchestration.LocalDagRunner().run(pipeline)

The only part of this snippet worth pointing out is the Transform definition. Namely, I want to pass and use the schema artifact in my transformation logic. I was hoping I could write the preprocessing_fn like this:

import os
from google.protobuf import text_format

def preprocessing_fn(inputs, custom_config):
    schema = text_format.Parse(os.path.join(custom_config['schema'].uri, 'schema.pbtxt'))
    # do something to the inputs based on the read schema

But the problem is that the custom_config['schema'] is not an object of Artifact but a Channel. And the preprocessing_fn is called even before the artifact even exists. I mean I debugged and traced the code and realized that preprocessing_fn is called before the code that creates the artifact executes. So technically, it's impossible to use an artifact inside my preprocessing_fn function.

My question is, is there a way around this? Can I use the results of an artifact inside my preprocessing_fn function? How can I write a transformation that its logic is based on the results of the previous artifacts?


问:
Pivot table not showing row total Python
I tested the following codes and set margins to be true. However, the result only shows sum of each column but not sum of each row. How to do that, please?

```<code>import pandas as pd

test = pd.DataFrame(
    [['a1', 1, 1, 11],
     ['a1', 2, 3, 12],
     ['a1', 3, 5, 13],
     ['a2', 4, 7, 14],
     ['a2', 5, 9, 15],
     ['b',  6, 2, 16],
     ['c',  7, 4, 17]],
    columns=['ID1', 'Value1', 'Value2', 'Value3']
)

test.pivot_table(values=['Value1'] + ['Value2'], index=['ID1'], aggfunc='sum', margins=True)
      Value1    Value2
ID1
a1         6         9
a2         9        16
b          6         2
c          7         4
All       28        31
</code>```

Body:
I tested the following codes and set margins to be true. However, the result only shows sum of each column but not sum of each row. How to do that, please?

import pandas as pd

test = pd.DataFrame(
    [['a1', 1, 1, 11],
     ['a1', 2, 3, 12],
     ['a1', 3, 5, 13],
     ['a2', 4, 7, 14],
     ['a2', 5, 9, 15],
     ['b',  6, 2, 16],
     ['c',  7, 4, 17]],
    columns=['ID1', 'Value1', 'Value2', 'Value3']
)

test.pivot_table(values=['Value1'] + ['Value2'], index=['ID1'], aggfunc='sum', margins=True)
      Value1    Value2
ID1
a1         6         9
a2         9        16
b          6         2
c          7         4
All       28        31


问:
What is the default path-dir when store-dir for persistent sessions is set to null?
```<code>server.servlet.session.persistent=true
</code>```

If you set server.servlet.session.store-dir to "mypath", the SESSIONS.ser file will appear inside "mypath". This file allows you to maintain a session when the server restarts.

However, persistent sessions work well without setting server.servlet.session.store-dir.

I thought Tomcat was storing the file internally in the default path.

Can I know the default route?
I want to check where the session is stored.

Body:
server.servlet.session.persistent=true

If you set server.servlet.session.store-dir to "mypath", the SESSIONS.ser file will appear inside "mypath". This file allows you to maintain a session when the server restarts.

However, persistent sessions work well without setting server.servlet.session.store-dir.

I thought Tomcat was storing the file internally in the default path.

Can I know the default route?
I want to check where the session is stored.


问:
if the option is already added, then the next time i add the option that already exist will not display in the add modal option
enter image description hereenter image description here

i add the position 'captain' then when i add again the option captain will be disabled or did not show in he option because its already existing

```<code>
<!-- ========================= MODAL ======================= -->
            <div id="addCourseModal" class="modal fade">
            <form class="form-horizontal" method="post" enctype="multipart/form-data">
              <div class="modal-dialog modal-lg" >
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <h4 class="modal-title">Manage officials</h4>
                    </div>
                    <div class="modal-body">

                        <div class="row">
                            <div class="container-fluid">
                                <div class="col-md-6 col-sm-12">

                                     <div class="form-group">
                                    <label>Positions:</label> <span style="color:red;">*</span>
                                    <select name="ddl_pos" required="" class="form-control input-sm">
                                        <option selected="" disabled="">-- Select Position -- </option>
                                        <option value="Captain">Barangay Captain</option>
                                        <option value="Kagawad(Ordinance)">Barangay Kagawad(Ordinance)</option>
                                        <option value="Kagawad(Public Safety)">Barangay Kagawad(Public Safety)</option>
                                        <option value="Kagawad(Tourism)">Barangay Kagawad(Tourism)</option>
                                        <option value="Kagawad(Budget & Finance)">Barangay Kagawad(Budget & Finance)</option>
                                        <option value="Kagawad(Agriculture)">Barangay Kagawad(Agriculture)</option>
                                        <option value="Kagawad(Education)">Barangay Kagawad(Education)</option>
                                        <option value="Kagawad(Infrastracture)">Barangay Kagawad(Infrastracture)</option>
                                        <option value="SK Chairman">SK Chairman</option>
                                        <option value="Secretary">Barangay Secretary</option>
                                        <option value="Treasurer">Barangay Treasurer</option>
                                    </select>
                                </div>

</code>```

Body:
enter image description hereenter image description here

i add the position 'captain' then when i add again the option captain will be disabled or did not show in he option because its already existing

            <form class="form-horizontal" method="post" enctype="multipart/form-data">

                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Manage officials

                                    Positions: *
                                    <select name="ddl_pos" required="" class="form-control input-sm">
                                        <option selected="" disabled="">-- Select Position -- </option>
                                        <option value="Captain">Barangay Captain</option>
                                        <option value="Kagawad(Ordinance)">Barangay Kagawad(Ordinance)</option>
                                        <option value="Kagawad(Public Safety)">Barangay Kagawad(Public Safety)</option>
                                        <option value="Kagawad(Tourism)">Barangay Kagawad(Tourism)</option>
                                        <option value="Kagawad(Budget & Finance)">Barangay Kagawad(Budget & Finance)</option>
                                        <option value="Kagawad(Agriculture)">Barangay Kagawad(Agriculture)</option>
                                        <option value="Kagawad(Education)">Barangay Kagawad(Education)</option>
                                        <option value="Kagawad(Infrastracture)">Barangay Kagawad(Infrastracture)</option>
                                        <option value="SK Chairman">SK Chairman</option>
                                        <option value="Secretary">Barangay Secretary</option>
                                        <option value="Treasurer">Barangay Treasurer</option>
                                    </select>


问:
I want to hide the TabBar in subview - SwiftUI
I got 3 views, the main view is MyTabView, and I would like to hide the TabBar when I navigate to a subview, and I define a class to store config which called TabBarConfig, and I pass it to subviews using EnvironmentObject. But when I change the data inside the class in subview, the TabBar doesn't hide, and it shows a purple warning read that "Accessing StateObject's object without being installed on a View. This will create a new instance each time", Here's the codes:

```<code>

class TabBarConfig: ObservableObject {
    @Published var hideTabBar: Bool = false
}

struct MyTabView: View {
    @ObservedObject var tabBarConfig = TabBarConfig()
    @State private var selectedItem = 0

    init() {
        UITabBar.appearance().isHidden = self.tabBarConfig.hideTabBar
    }

    var body: some View {
        TabView(selection: $selectedItem) {
            HomeView()
                .tabItem {
                    Image(systemName: "house.fill")
                    Text("Home")
                }
                .tag(0)
            UserView()
                .tabItem {
                    Image(systemName: "person.fill")
                    Text("User")
                }
                .tag(1)
        }
        .environmentObject(self.tabBarConfig)
    }
}

struct HomeView: View {
    @EnvironmentObject var tabBarConfig: TabBarConfig
    @State var showSubView: Bool = false

    var body: some View {
        NavigationView {
            NavigationLink(destination: SubView(), isActive: $showSubView) {
                Button(action: {
                    showSubView = true
                }, label: {
                    Text("Go To SubView")
                })
            }
            .environmentObject(self.tabBarConfig)
        }
    }
}

struct SubView: View {
    @EnvironmentObject var tabBarConfig: TabBarConfig

    var body: some View {
        VStack {
            Text("Some Text")
        }
        .onAppear {
            self.tabBarConfig.hideTabBar = true
        }
    }
}
</code>```

Hope you can help me out.

Body:
I got 3 views, the main view is MyTabView, and I would like to hide the TabBar when I navigate to a subview, and I define a class to store config which called TabBarConfig, and I pass it to subviews using EnvironmentObject. But when I change the data inside the class in subview, the TabBar doesn't hide, and it shows a purple warning read that "Accessing StateObject's object without being installed on a View. This will create a new instance each time", Here's the codes:

class TabBarConfig: ObservableObject {
    @Published var hideTabBar: Bool = false
}

struct MyTabView: View {
    @ObservedObject var tabBarConfig = TabBarConfig()
    @State private var selectedItem = 0

    init() {
        UITabBar.appearance().isHidden = self.tabBarConfig.hideTabBar
    }

    var body: some View {
        TabView(selection: $selectedItem) {
            HomeView()
                .tabItem {
                    Image(systemName: "house.fill")
                    Text("Home")
                }
                .tag(0)
            UserView()
                .tabItem {
                    Image(systemName: "person.fill")
                    Text("User")
                }
                .tag(1)
        }
        .environmentObject(self.tabBarConfig)
    }
}

struct HomeView: View {
    @EnvironmentObject var tabBarConfig: TabBarConfig
    @State var showSubView: Bool = false

    var body: some View {
        NavigationView {
            NavigationLink(destination: SubView(), isActive: $showSubView) {
                Button(action: {
                    showSubView = true
                }, label: {
                    Text("Go To SubView")
                })
            }
            .environmentObject(self.tabBarConfig)
        }
    }
}

struct SubView: View {
    @EnvironmentObject var tabBarConfig: TabBarConfig

    var body: some View {
        VStack {
            Text("Some Text")
        }
        .onAppear {
            self.tabBarConfig.hideTabBar = true
        }
    }
}

Hope you can help me out.


问:
How to highlight a Marker when hovering over it in plotly?
I'm trying to do something I thought would be easy, but I cannot figure it out. I have a very simple scatter plot below. I want the markers to get larger as I hover over them. For example, when my cursor is hovering over the point 3,3 in the chart (see image), I want the marker size to increase. Then, once I'm done hovering, I want the marker size to go back to its original size. I've created a simple scatter plot to get the code working but I can't even get it to work with this. Please see code and image below.

```<code>import plotly.graph_objects as go

# Create a line chart with random data
x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
fig = go.Figure()
scatter = go.Scatter(x=x, y=y, mode='lines+markers')
fig.add_trace(scatter)

fig.write_html('test.html', auto_open=True)
</code>```

Scatter Plot

Body:
I'm trying to do something I thought would be easy, but I cannot figure it out. I have a very simple scatter plot below. I want the markers to get larger as I hover over them. For example, when my cursor is hovering over the point 3,3 in the chart (see image), I want the marker size to increase. Then, once I'm done hovering, I want the marker size to go back to its original size. I've created a simple scatter plot to get the code working but I can't even get it to work with this. Please see code and image below.

import plotly.graph_objects as go

# Create a line chart with random data
x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
fig = go.Figure()
scatter = go.Scatter(x=x, y=y, mode='lines+markers')
fig.add_trace(scatter)

fig.write_html('test.html', auto_open=True)

Scatter Plot


问:
Handling http requests in search engines and browsers in nginx
Is there a way that with the help of nginx I can separate requests from search engines and browsers and direct each to a separate project with a proxy or directory, for example.
Thanks for your guidance.</p>


问:
Predict next 30 days in Random Forest Regression
I done training my Random Forest Regression Models and got a pretty good result on my test dataset. But I wonder how can I predict the result in the future?
Here's my code:</p>
```<code>model_rf = RandomForestRegressor(n_estimators=500, oob_score=True, random_state=100)
model_rf.fit(x_train, y_train)
pred_train_rf= model_rf.predict(x_train)
pred_test_rf = model_rf.predict(x_test)
</code>```

Body:
I done training my Random Forest Regression Models and got a pretty good result on my test dataset. But I wonder how can I predict the result in the future?
Here's my code:

model_rf = RandomForestRegressor(n_estimators=500, oob_score=True, random_state=100)
model_rf.fit(x_train, y_train)
pred_train_rf= model_rf.predict(x_train)
pred_test_rf = model_rf.predict(x_test)


问:
How do i add each individual output into the tkinter list(Custom only)?
I'm making a stupid game because I was bored and wanted to make it a little more challenging for myself so i started using Tkinter as i have never really used it before. i want each individual output from my custom_main while loop to output to the list i have created but i can only get it to output the last thing it gets.</p>
```<code>import tkinter
from tkinter import *

def custom_start():
    def custom_main():
        first = int(First_value.get())
        second = int(Second_value.get())
        x = 0
        while x <= max_value:  # while x is being incrementally incereased it checks if x exceeds the user entered max value
            flag = False
            if x == 0:
                x = x + 1
            for i in range(2, x):  # Checks if x is a prime number
                if (x % i) == 0:
                    flag = True
                    break
            if flag:
                if x % first == 0 and x % second == 0:  # uses a remainder checker for finding multiples of the user inputs
                    return ("Fizz Buzz")
                elif x % first == 0:
                    return ("Fizz")
                elif x % second == 0:
                    return ("Buzz")
                else:
                    return (x)
            else:
                return ("Oops")
            x = x + 1

    max_value = int(Max_value.get())

    cust = Tk()
    Label( cust, text='First Value').grid(row=0, column=0)
    Label( cust, text='Second Value').grid(row=1, column=0)

    First_value = Entry( cust )
    Second_value = Entry( cust )

    First_value.grid(row=0, column=1)
    Second_value.grid(row=1, column=1)

    result = tkinter.Listbox(cust)
    result.grid(row=3, column=0, columnspan=2)

    Button( cust, text='Exit', command=cust.quit ).grid(row=2, column=0, sticky=W, pady=4)
    Button( cust, text='Start', command=lambda: result.insert(0, custom_main())).grid(row=2, column=1, sticky=W, pady=4)

def original():
    max_value = int(Max_value.get())
    x = 0
    flag = False
    while x <= max_value:
        if x == 0:
            x = x+1
        if x%3 == 0 and x%5 == 0: #Checks if x is a multiple of 3 or 5 as the given variables
            print("Fizz Buzz")
        elif x%3 == 0:
            print("Fizz")
        elif x%5 == 0:
            print("Buzz")
        else:
            print(x)
        x = x + 1
    def restart():
        restart = input("Would you like to restart?(y/n): ").lower()
        if restart == 'y':
            start()
        elif restart == 'n':
            quit()
        else:
            print("Please enter a valid input.")
            restart()
    restart()

win = Tk()
Label( win, text='Max Value' ).grid( row=0 )

Max_value = Entry( win )

Max_value.grid( row=0, column=1 )

Button( win, text='Exit', command=win.quit ).grid( row=3, column=0, sticky=W, pady=4 )
Button( win, text='Origional', command=original ).grid( row=3, column=1, sticky=W, pady=4 )
Button( win, text='Custom', command=custom_start ).grid( row=3, column=2, sticky=W, pady=4 )

mainloop()

</code>```

Body:
I'm making a stupid game because I was bored and wanted to make it a little more challenging for myself so i started using Tkinter as i have never really used it before. i want each individual output from my custom_main while loop to output to the list i have created but i can only get it to output the last thing it gets.

import tkinter
from tkinter import *

def custom_start():
    def custom_main():
        first = int(First_value.get())
        second = int(Second_value.get())
        x = 0
        while x <= max_value:  # while x is being incrementally incereased it checks if x exceeds the user entered max value
            flag = False
            if x == 0:
                x = x + 1
            for i in range(2, x):  # Checks if x is a prime number
                if (x % i) == 0:
                    flag = True
                    break
            if flag:
                if x % first == 0 and x % second == 0:  # uses a remainder checker for finding multiples of the user inputs
                    return ("Fizz Buzz")
                elif x % first == 0:
                    return ("Fizz")
                elif x % second == 0:
                    return ("Buzz")
                else:
                    return (x)
            else:
                return ("Oops")
            x = x + 1

    max_value = int(Max_value.get())

    cust = Tk()
    Label( cust, text='First Value').grid(row=0, column=0)
    Label( cust, text='Second Value').grid(row=1, column=0)

    First_value = Entry( cust )
    Second_value = Entry( cust )

    First_value.grid(row=0, column=1)
    Second_value.grid(row=1, column=1)

    result = tkinter.Listbox(cust)
    result.grid(row=3, column=0, columnspan=2)

    Button( cust, text='Exit', command=cust.quit ).grid(row=2, column=0, sticky=W, pady=4)
    Button( cust, text='Start', command=lambda: result.insert(0, custom_main())).grid(row=2, column=1, sticky=W, pady=4)

def original():
    max_value = int(Max_value.get())
    x = 0
    flag = False
    while x <= max_value:
        if x == 0:
            x = x+1
        if x%3 == 0 and x%5 == 0: #Checks if x is a multiple of 3 or 5 as the given variables
            print("Fizz Buzz")
        elif x%3 == 0:
            print("Fizz")
        elif x%5 == 0:
            print("Buzz")
        else:
            print(x)
        x = x + 1
    def restart():
        restart = input("Would you like to restart?(y/n): ").lower()
        if restart == 'y':
            start()
        elif restart == 'n':
            quit()
        else:
            print("Please enter a valid input.")
            restart()
    restart()

win = Tk()
Label( win, text='Max Value' ).grid( row=0 )

Max_value = Entry( win )

Max_value.grid( row=0, column=1 )

Button( win, text='Exit', command=win.quit ).grid( row=3, column=0, sticky=W, pady=4 )
Button( win, text='Origional', command=original ).grid( row=3, column=1, sticky=W, pady=4 )
Button( win, text='Custom', command=custom_start ).grid( row=3, column=2, sticky=W, pady=4 )

mainloop()


问:
localhost refused to connect while using with react router
This does not showing the result while connecting with vscode. This would start happening when i import the react router.
I have no idea what should i do.</p>


问:
Angular SSR With Subdomains
I am building a project with 3 web applications (public, user, and store) and an API. Each web application has its own subdomain: www.domain.com for the public app, user.domain.com for the user app, and (store-id)*.domain.com for the store app. I want to use server-side rendering (SSR) for all of the web apps, so when a link is shared, a card with data from the page can be displayed.

I want to separate the API and user apps from each other. I want all of the web apps to access the api.domain.com subdomain to get the data they need. (should I do that?)

I quess that I will have to use express-engine to make requests to the api.domain.com subdomain, where there is an Express app that handles the requests.

Is this the correct approach to set up my project with multiple web apps and an API that are accessed through subdomains, and how can I implement SSR for each app?

This is how I want the project structure to be:

```<code>
my-app/
├─ web/ - contains web-apps with ssr, thay all make requests to one api
│  ├─ user/
│  ├─ public/
│  ├─ store/
├─ api/
│  ├─ index.js - this is where all the requests handled from all the web apps
</code>```

Title: Angular SSR With Subdomains

Body:
I am building a project with 3 web applications (public, user, and store) and an API. Each web application has its own subdomain: www.domain.com for the public app, user.domain.com for the user app, and (store-id)*.domain.com for the store app. I want to use server-side rendering (SSR) for all of the web apps, so when a link is shared, a card with data from the page can be displayed.

I want to separate the API and user apps from each other. I want all of the web apps to access the api.domain.com subdomain to get the data they need. (should I do that?)

I quess that I will have to use express-engine to make requests to the api.domain.com subdomain, where there is an Express app that handles the requests.

Is this the correct approach to set up my project with multiple web apps and an API that are accessed through subdomains, and how can I implement SSR for each app?

This is how I want the project structure to be:

my-app/
├─ web/ - contains web-apps with ssr, thay all make requests to one api
│  ├─ user/
│  ├─ public/
│  ├─ store/
├─ api/
│  ├─ index.js - this is where all the requests handled from all the web apps


问:
Why two if statements that are logically similar showing different outputs,below are two if statements which got me confused
Here the pattern is a string and arr is an array of strings, and map here is a hashmap i.e HashMap<Character,String> map = new HashMap<>();

```<code>if (!map.get(pattern.charAt(i)).equals(arr[i]) {
    return false;
}
</code>```

The above one is working.
But what is wrong with the next one?

```<code>if (map.get(pattern.charAt(i))!=(arr[i])){
    return false;
}
</code>```

This is a part of my solution for question no. 290 leetcode. When I use first if statement the whole code is working, but for the second version of if statement not all test cases are getting passed. Why so?

```<code>class Solution {
    public boolean wordPattern(String pattern, String s) {
        String[] arr=s.split(" ");
        if (arr.length!=pattern.length()) {
            return false;
        }
        HashMap<Character,String> map = new HashMap<>();
        for (int i=0;i<arr.length;i++) {
            if (map.containsKey(pattern.charAt(i))){
                //**this line is my doubt**//
                if (!map.get(pattern.charAt(i)).equals(arr[i])){
                    return false;
                } else {
                    if (map.containsValue(arr[i])) {
                        return false;
                }
                 map.put(pattern.charAt(i),arr[i]);
            }
        }
        return true;
    }
}
</code>```

Body:
Here the pattern is a string and arr is an array of strings, and map here is a hashmap i.e HashMap<Character,String> map = new HashMap<>();

if (!map.get(pattern.charAt(i)).equals(arr[i]) {
    return false;
}

The above one is working.
But what is wrong with the next one?

if (map.get(pattern.charAt(i))!=(arr[i])){
    return false;
}

This is a part of my solution for question no. 290 leetcode. When I use first if statement the whole code is working, but for the second version of if statement not all test cases are getting passed. Why so?

class Solution {
    public boolean wordPattern(String pattern, String s) {
        String[] arr=s.split(" ");
        if (arr.length!=pattern.length()) {
            return false;
        }
        HashMap<Character,String> map = new HashMap<>();
        for (int i=0;i<arr.length;i++) {
            if (map.containsKey(pattern.charAt(i))){
                //**this line is my doubt**//
                if (!map.get(pattern.charAt(i)).equals(arr[i])){
                    return false;
                } else {
                    if (map.containsValue(arr[i])) {
                        return false;
                }
                 map.put(pattern.charAt(i),arr[i]);
            }
        }
        return true;
    }
}