问:
useContext is not showing updated state when user navigates to the next page although cookie has updated data
I have an AddToCart component that calls AddToCart action on context.

context.ts:

```<code>import React, { useContext, useReducer, useEffect } from "react";
import reducer from "./reducer";
import Cookies from "js-cookie";

const initialCart = {
  cart: Cookies.get("cart") ? JSON.parse(Cookies.get("cart")!) : [],
  isShowing: false,
  loading: false,
  lastAdded: null,
  total: 0,
  amount: 0,
};

const CartContext = React.createContext<any>(initialCart);

const CartProvider = ({ children }: { children: any }) => {
  const [state, dispatch] = useReducer(reducer, initialCart);

  const showModal = () => {
    dispatch({ type: "SHOW_MODAL" });
  };

  const hideModal = () => {
    dispatch({ type: "HIDE_MODAL" });
  };

  const addToCart = (product: any) => {
    dispatch({ type: "ADD_TO_CART", payload: product });
  };

  return (
    <CartContext.Provider
      value={{
        ...state,
        showModal,
        hideModal,
        addToCart,
      }}
    >
      {children}
    </CartContext.Provider>
  );
};

// make cart context available to child components
export const useCartContext = () => {
  return useContext(CartContext);
};

export { CartContext, CartProvider };
</code>```

reducer.ts: (excuse my terrible use of types, will fix)

```<code>import Cookies from "js-cookie";

const reducer = (state: any, action: any) => {

if (action.type === "SHOW_MODAL") {
    return { ...state, isShowing: true };
  }

  if (action.type === "HIDE_MODAL") {
    return { ...state, isShowing: false };
  }

  if (action.type === "ADD_TO_CART") {

    const {
      Color,
      MPN,
      SKU,
      SO,
      Size,
      UPC,
      manufacturerID,
      price,
      productID,
      productName,
      qtyInStock,
      pic,
      productURI,
    } = action.payload;

    const tempItem = state.cart.find((item: any) => {
      return item.productID === productID;
    });

    // if item being added to cart already exists in cart:
    if (tempItem) {
      let newCart = state.cart.map((cartItem: any) => {
        if (cartItem.productID === productID) {
          let newQty = cartItem.qty + 1;
          if (newQty > cartItem.qtyInStock) {
            newQty = cartItem.qtyInStock;

            // replace this with toast for a more professional looking alert
            window.alert("No additional items available");
            return { ...cartItem };
          }
          state.isShowing = true;
          state.lastAdded = cartItem;

          // bring user to top of page
          window.scrollTo({
            top: 0,
            behavior: "smooth",
          });
          return { ...cartItem, qty: newQty };
        } else {
          return { ...cartItem };
        }
      });

      return {
        ...state,
        cart: [...newCart],
        isShowing: state.isShowing,
        lastAdded: state.lastAdded,
      };
    } else {
      let newItem = {
        Color,
        MPN,
        SKU,
        SO,
        Size,
        UPC,
        manufacturerID,
        price,
        productID,
        productName,
        qtyInStock,
        pic,
        qty: 1,
        productURI,
      };

      // bring user to top of page
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });

      Cookies.set("cart", JSON.stringify([...state.cart, newItem]));
      const prevState = { ...state };
      // return updated state
      return {
        ...prevState,
        cart: [...state.cart, newItem],
        isShowing: true,
        lastAdded: { ...newItem },
      };
    }
  }

  throw new Error("no matching action type");
};

export default reducer;

</code>```

cart.tsx:

```<code>import React from "react";
import Layout from "../components/layout/Layout";
import { useContext } from "react";
import { CartContext } from "../modules/cart/context";
import CouponCode from "../components/cart/CouponCode";
import dynamic from "next/dynamic";
import CartItem from "../components/cart/CartItem";

const Cart = () => {
  const context = useContext(CartContext);

  return (
    <Layout>
      <div
        className={`sm:container flex mx-auto`}
        style={{ maxWidth: "1100px" }}
      >
        <div className={`flex w-full mx-auto`}>
          <div className={`basis-2/3 mr-8`}>
            <h3 className={`text-2xl font-leagueSpartan mb-4`}>Bag</h3>
            <div className={``}>
              {context.cart.map((product: any, index: number) => {
                return <CartItem key={index} product={product} />;
              })}
            </div>
          </div>
          <div>
            <h3 className={`text-2xl font-leagueSpartan mb-4`}>Summary</h3>
            <div>Do you have a coupon code?</div>
            <CouponCode />
            <div>
              <div>Subtotal:</div>
              <div>Estimated Shipping & Handling:</div>
              <div>Estimated Tax:</div>
            </div>
            <hr className={`my-8 h-px bg-gray-400 border-0`}></hr>
            <div>Total: </div>
            <hr className={`my-8 h-px bg-gray-400 border-0`}></hr>
          </div>
        </div>
      </div>
    </Layout>
  );
};

export default dynamic(() => Promise.resolve(Cart), { ssr: false });
</code>```

After adding to cart and navigating to the cart page, no cart item is shown (the item is stored in the cart cookie correctly). When the page is refreshed, the item is shown.

I initially thought this has to do with deep cloning and that react is not acknowledging that a change is made to the cart array. Upon further research, I think I am using the spread operator correctly, but my next step will be to use lodash deep clone just in case. Other than that, I'm just reviewing the code for a design patter flaw that would prevent state from syncing with the cookie. Thanks!

Body:
I have an AddToCart component that calls AddToCart action on context.

context.ts:

import React, { useContext, useReducer, useEffect } from "react";
import reducer from "./reducer";
import Cookies from "js-cookie";

const initialCart = {
  cart: Cookies.get("cart") ? JSON.parse(Cookies.get("cart")!) : [],
  isShowing: false,
  loading: false,
  lastAdded: null,
  total: 0,
  amount: 0,
};

const CartContext = React.createContext<any>(initialCart);

const CartProvider = ({ children }: { children: any }) => {
  const [state, dispatch] = useReducer(reducer, initialCart);

  const showModal = () => {
    dispatch({ type: "SHOW_MODAL" });
  };

  const hideModal = () => {
    dispatch({ type: "HIDE_MODAL" });
  };

  const addToCart = (product: any) => {
    dispatch({ type: "ADD_TO_CART", payload: product });
  };

  return (
    <CartContext.Provider
      value={{
        ...state,
        showModal,
        hideModal,
        addToCart,
      }}
    >
      {children}
    </CartContext.Provider>
  );
};

// make cart context available to child components
export const useCartContext = () => {
  return useContext(CartContext);
};

export { CartContext, CartProvider };

reducer.ts: (excuse my terrible use of types, will fix)

import Cookies from "js-cookie";

const reducer = (state: any, action: any) => {

if (action.type === "SHOW_MODAL") {
    return { ...state, isShowing: true };
  }

  if (action.type === "HIDE_MODAL") {
    return { ...state, isShowing: false };
  }

  if (action.type === "ADD_TO_CART") {

    const {
      Color,
      MPN,
      SKU,
      SO,
      Size,
      UPC,
      manufacturerID,
      price,
      productID,
      productName,
      qtyInStock,
      pic,
      productURI,
    } = action.payload;

    const tempItem = state.cart.find((item: any) => {
      return item.productID === productID;
    });

    // if item being added to cart already exists in cart:
    if (tempItem) {
      let newCart = state.cart.map((cartItem: any) => {
        if (cartItem.productID === productID) {
          let newQty = cartItem.qty + 1;
          if (newQty > cartItem.qtyInStock) {
            newQty = cartItem.qtyInStock;

            // replace this with toast for a more professional looking alert
            window.alert("No additional items available");
            return { ...cartItem };
          }
          state.isShowing = true;
          state.lastAdded = cartItem;

          // bring user to top of page
          window.scrollTo({
            top: 0,
            behavior: "smooth",
          });
          return { ...cartItem, qty: newQty };
        } else {
          return { ...cartItem };
        }
      });

      return {
        ...state,
        cart: [...newCart],
        isShowing: state.isShowing,
        lastAdded: state.lastAdded,
      };
    } else {
      let newItem = {
        Color,
        MPN,
        SKU,
        SO,
        Size,
        UPC,
        manufacturerID,
        price,
        productID,
        productName,
        qtyInStock,
        pic,
        qty: 1,
        productURI,
      };

      // bring user to top of page
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });

      Cookies.set("cart", JSON.stringify([...state.cart, newItem]));
      const prevState = { ...state };
      // return updated state
      return {
        ...prevState,
        cart: [...state.cart, newItem],
        isShowing: true,
        lastAdded: { ...newItem },
      };
    }
  }

  throw new Error("no matching action type");
};

export default reducer;

cart.tsx:

import React from "react";
import Layout from "../components/layout/Layout";
import { useContext } from "react";
import { CartContext } from "../modules/cart/context";
import CouponCode from "../components/cart/CouponCode";
import dynamic from "next/dynamic";
import CartItem from "../components/cart/CartItem";

const Cart = () => {
  const context = useContext(CartContext);

  return (
    <Layout>
      <div
        className={`sm:container flex mx-auto`}
        style={{ maxWidth: "1100px" }}
      >
        <div className={`flex w-full mx-auto`}>
          <div className={`basis-2/3 mr-8`}>
            <h3 className={`text-2xl font-leagueSpartan mb-4`}>Bag

              {context.cart.map((product: any, index: number) => {
                return <CartItem key={index} product={product} />;
              })}

            <h3 className={`text-2xl font-leagueSpartan mb-4`}>Summary

Do you have a coupon code?

            <CouponCode />

Subtotal:

Estimated Shipping & Handling:

Estimated Tax:

            <hr className={`my-8 h-px bg-gray-400 border-0`}>

Total:

            <hr className={`my-8 h-px bg-gray-400 border-0`}>

    </Layout>
  );
};

export default dynamic(() => Promise.resolve(Cart), { ssr: false });

After adding to cart and navigating to the cart page, no cart item is shown (the item is stored in the cart cookie correctly). When the page is refreshed, the item is shown.

I initially thought this has to do with deep cloning and that react is not acknowledging that a change is made to the cart array. Upon further research, I think I am using the spread operator correctly, but my next step will be to use lodash deep clone just in case. Other than that, I'm just reviewing the code for a design patter flaw that would prevent state from syncing with the cookie. Thanks!


来源: stackexchange

问:
Model "File" is missing from the (plugin - upload) models - strapi with cloudinary
my strapi app can't start properly. I'm getting the following error:

```<code>Error: The model `File`, used in the attribute `Image` in the model Portfolio-card, is missing from the (plugin - upload) models
</code>```

I think I have all my config files configurated as in the docs. I'm using MongoDB for database. It is connected with the strapi-connector-mongoose. The app isn't starting.

Here's my package.json:

{
  "name": "czarogrod-backend-strapi",
  "private": true,
  "version": "0.1.0",
  "description": "A Strapi application",
  "scripts": {
    "develop": "strapi develop",
    "start": "strapi start",
    "build": "strapi build",
    "strapi": "strapi"
  },
  "dependencies": {
    "strapi": "3.6.11",
    "strapi-admin": "3.3.4",
    "strapi-connector-mongoose": "3.3.4",
    "strapi-plugin-content-manager": "3.1.3",
    "strapi-plugin-content-type-builder": "3.1.3",
    "strapi-plugin-email": "3.1.3",
    "strapi-provider-upload-cloudinary": "^3.1.3",
    "strapi-utils": "3.1.3",
    "video-react": "0.16.0",
    "webpack": "^4.44.1"
  },
  "author": {
    "name": "A Strapi developer"
  },
  "strapi": {
    "uuid": "2474ae8d-dfcf-46d2-9167-e53366ff5737"
  },
  "engines": {
    "node": "^16.x",
    "npm": "^6.x"
  },
  "license": "MIT"
}
```
<p>Here's <code>config/plugins.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>module.exports = ({ env }) => ({
  upload: {
    config: {
      provider: "cloudinary",
      providerOptions: {
        cloud_name: env("CLOUDINARY_NAME"),
        api_key: env("CLOUDINARY_KEY"),
        api_secret: env("CLOUDINARY_SECRET"),
      },
      actionOptions: {
        upload: {},
        uploadStream: {},
        delete: {},
      },
    },
  },
});
</code>```

Here's config/middlewares.js:

module.exports = [
  {
    name: "strapi::security",
    config: {
      contentSecurityPolicy: {
        useDefaults: true,
        directives: {
          "connect-src": ["'self'", "https:"],
          "img-src": [
            "'self'",
            "data:",
            "blob:",
            "dl.airtable.com",
            "res.cloudinary.com",
          ],
          "media-src": [
            "'self'",
            "data:",
            "blob:",
            "dl.airtable.com",
            "res.cloudinary.com",
          ],
          upgradeInsecureRequests: null,
        },
      },
    },
  },
];
```
<p>Here's <code>extensions/upload/config.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>{
  "provider": "cloudinary",
  "providerOptions": {
    "cloud_name": "###",
    "api_key": "###",
    "api_secret": "###"
  }
}
</code>```

Thank you in advance for your help.

ContentLicense: CC BY-SA 4.0

Body:
my strapi app can't start properly. I'm getting the following error:

Error: The model `File`, used in the attribute `Image` in the model Portfolio-card, is missing from the (plugin - upload) models

I think I have all my config files configurated as in the docs. I'm using MongoDB for database. It is connected with the strapi-connector-mongoose. The app isn't starting.

Here's my package.json:

{
  "name": "czarogrod-backend-strapi",
  "private": true,
  "version": "0.1.0",
  "description": "A Strapi application",
  "scripts": {
    "develop": "strapi develop",
    "start": "strapi start",
    "build": "strapi build",
    "strapi": "strapi"
  },
  "dependencies": {
    "strapi": "3.6.11",
    "strapi-admin": "3.3.4",
    "strapi-connector-mongoose": "3.3.4",
    "strapi-plugin-content-manager": "3.1.3",
    "strapi-plugin-content-type-builder": "3.1.3",
    "strapi-plugin-email": "3.1.3",
    "strapi-provider-upload-cloudinary": "^3.1.3",
    "strapi-utils": "3.1.3",
    "video-react": "0.16.0",
    "webpack": "^4.44.1"
  },
  "author": {
    "name": "A Strapi developer"
  },
  "strapi": {
    "uuid": "2474ae8d-dfcf-46d2-9167-e53366ff5737"
  },
  "engines": {
    "node": "^16.x",
    "npm": "^6.x"
  },
  "license": "MIT"
}

Here's config/plugins.js:

module.exports = ({ env }) => ({
  upload: {
    config: {
      provider: "cloudinary",
      providerOptions: {
        cloud_name: env("CLOUDINARY_NAME"),
        api_key: env("CLOUDINARY_KEY"),
        api_secret: env("CLOUDINARY_SECRET"),
      },
      actionOptions: {
        upload: {},
        uploadStream: {},
        delete: {},
      },
    },
  },
});

Here's config/middlewares.js:

module.exports = [
  {
    name: "strapi::security",
    config: {
      contentSecurityPolicy: {
        useDefaults: true,
        directives: {
          "connect-src": ["'self'", "https:"],
          "img-src": [
            "'self'",
            "data:",
            "blob:",
            "dl.airtable.com",
            "res.cloudinary.com",
          ],
          "media-src": [
            "'self'",
            "data:",
            "blob:",
            "dl.airtable.com",
            "res.cloudinary.com",
          ],
          upgradeInsecureRequests: null,
        },
      },
    },
  },
];

Here's extensions/upload/config.js:

{
  "provider": "cloudinary",
  "providerOptions": {
    "cloud_name": "###",
    "api_key": "###",
    "api_secret": "###"
  }
}

Thank you in advance for your help.


问:
Convert function with for/while loop into Pandas dataframe.apply(lambda ...: ...) method if there is a change in each iteration
I am looking for a way to convert structure:

```<code>for ... in dataframe:
   while ...:
      if ...:
         do smth
   if ...:
      do smth
</code>```

to

```<code>dataframe.apply(lambda ...: ...)
</code>```

Here is example of function with for/while loop:

```<code>d_test = {
    'name' : ['South Beach', 'Dog', 'Bird', 'Ant', 'Big Dog', 'Beach', 'Dear', 'Cat', 'Fish', 'Dry Fish'],
    'cluster_number' : [1, 2, 3, 3, 2, 1, 4, 2, 2, 2]
}

df_test = pd.DataFrame(d_test)

from rapidfuzz import fuzz

df_test = df_test.sort_values(['cluster_number', 'name'])
df_test.reset_index(drop=True, inplace=True)
df_test['id'] = 0

def loop_in_cluster(index, row, df_test, index_, row_, is_i_used, i):
    while index_ < len(df_test) and df_test.loc[index, 'cluster_number'] == df_test.loc[index_, 'cluster_number'] and df_test.loc[index_, 'id'] == 0:
        if row['name'] == df_test.loc[index_, 'name'] or fuzz.ratio(row['name'], df_test.loc[index_, 'name']) > 50:
            df_test.loc[index_,'id'] = i
            is_i_used = True
        index_ += 1
    return df_test, is_i_used

i = 1
is_i_used = False
for index, row in df_test.iterrows():
    row_ = row
    index_ = index
    df_test, is_i_used = loop_in_cluster(index, row, df_test, index_, row_, is_i_used, i)
    if is_i_used == True:
        i += 1
        is_i_used = False
</code>```

And here is my attempt to use dataframe.apply() method:

```<code>i = 1
df_test.apply(lambda row: loop_in_cluster(i=i+1, index=row.name, row=row, df_test=df_test, index_=index, row_ = row, is_i_used=False) if is_i_used==True else loop_in_cluster(i=i, index=row.name, row=row, df_test=df_test, index_= index, row_=row, is_i_used=True), axis=1)
</code>```

but I am getting: StopIteration: error in output. I tired other methods such as pandas groupby.GroupBy method but it seems that apply method is more closer to what I am looking for.

Body:
I am looking for a way to convert structure:

for ... in dataframe:
   while ...:
      if ...:
         do smth
   if ...:
      do smth

to

dataframe.apply(lambda ...: ...)

Here is example of function with for/while loop:

d_test = {
    'name' : ['South Beach', 'Dog', 'Bird', 'Ant', 'Big Dog', 'Beach', 'Dear', 'Cat', 'Fish', 'Dry Fish'],
    'cluster_number' : [1, 2, 3, 3, 2, 1, 4, 2, 2, 2]
}

df_test = pd.DataFrame(d_test)

from rapidfuzz import fuzz

df_test = df_test.sort_values(['cluster_number', 'name'])
df_test.reset_index(drop=True, inplace=True)
df_test['id'] = 0

def loop_in_cluster(index, row, df_test, index_, row_, is_i_used, i):
    while index_ < len(df_test) and df_test.loc[index, 'cluster_number'] == df_test.loc[index_, 'cluster_number'] and df_test.loc[index_, 'id'] == 0:
        if row['name'] == df_test.loc[index_, 'name'] or fuzz.ratio(row['name'], df_test.loc[index_, 'name']) > 50:
            df_test.loc[index_,'id'] = i
            is_i_used = True
        index_ += 1
    return df_test, is_i_used

i = 1
is_i_used = False
for index, row in df_test.iterrows():
    row_ = row
    index_ = index
    df_test, is_i_used = loop_in_cluster(index, row, df_test, index_, row_, is_i_used, i)
    if is_i_used == True:
        i += 1
        is_i_used = False

And here is my attempt to use dataframe.apply() method:

i = 1
df_test.apply(lambda row: loop_in_cluster(i=i+1, index=row.name, row=row, df_test=df_test, index_=index, row_ = row, is_i_used=False) if is_i_used==True else loop_in_cluster(i=i, index=row.name, row=row, df_test=df_test, index_= index, row_=row, is_i_used=True), axis=1)

but I am getting: StopIteration: error in output. I tired other methods such as pandas groupby.GroupBy method but it seems that apply method is more closer to what I am looking for.


问:
cgroup and process memory usage mismactch
I have a memory cgroup with 1 process in it.
And look for rss memory usage in that cgroup (in memory.stat) and it is much bigger than rss memory of the process (from /proc/[pid]/status).

The only process pid in cgroup:

```<code>$ cat /sys/fs/cgroup/memory/karim/master/cgroup.procs
3744924
</code>```

The memory limit in cgroup:

```<code>$ cat /sys/fs/cgroup/memory/karim/master/memory.limit_in_bytes
7340032000
</code>```

rss of the cgroup is 990 MB:

```<code>$ cat /sys/fs/cgroup/memory/karim/master/memory.stat
cache 5990449152
rss 990224384
rss_huge 0
shmem 0
mapped_file 13516800
dirty 1081344
writeback 270336
pgpgin 4195191
pgpgout 2490628
pgfault 5264589
pgmajfault 0
inactive_anon 0
active_anon 990240768
inactive_file 5862830080
active_file 127021056
unevictable 0
hierarchical_memory_limit 7340032000
total_cache 5990449152
total_rss 990224384
total_rss_huge 0
total_shmem 0
total_mapped_file 13516800
total_dirty 1081344
total_writeback 270336
total_pgpgin 4195191
total_pgpgout 2490628
total_pgfault 5264589
total_pgmajfault 0
total_inactive_anon 0
total_active_anon 990240768
total_inactive_file 5862830080
total_active_file 127021056
total_unevictable 0
</code>```

rss of the process is 165 MB:

```<code>$ cat /proc/3744924/status
Name:   [main]       /h
Umask:  0002
State:  S (sleeping)
Tgid:   3744924
Ngid:   0
Pid:    3744924
PPid:   3744912
TracerPid:  0
Uid:    1000    1000    1000    1000
Gid:    1001    1001    1001    1001
FDSize: 256
Groups: 1000 1001
NStgid: 3744924
NSpid:  3744924
NSpgid: 3744912
NSsid:  45028
VmPeak:  2149068 kB
VmSize:  2088876 kB
VmLck:         0 kB
VmPin:         0 kB
VmHWM:    245352 kB
VmRSS:    198964 kB
RssAnon:      165248 kB
RssFile:       33660 kB
RssShmem:         56 kB
VmData:   575400 kB
VmStk:       132 kB
VmExe:      3048 kB
VmLib:     19180 kB
VmPTE:      1152 kB
VmSwap:        0 kB
HugetlbPages:          0 kB
CoreDumping:    0
THP_enabled:    1
Threads:    17
SigQ:   0/241014
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000001001000
SigCgt: 0000000180000002
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 0000003fffffffff
CapAmb: 0000000000000000
NoNewPrivs: 0
Seccomp:    0
Speculation_Store_Bypass:   thread vulnerable
Cpus_allowed:   fff
Cpus_allowed_list:  0-11
Mems_allowed:   00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001
Mems_allowed_list:  0
voluntary_ctxt_switches:    94902
nonvoluntary_ctxt_switches: 1903
</code>```

Why is there such a big difference?

Body:
I have a memory cgroup with 1 process in it.
And look for rss memory usage in that cgroup (in memory.stat) and it is much bigger than rss memory of the process (from /proc/[pid]/status).

The only process pid in cgroup:

$ cat /sys/fs/cgroup/memory/karim/master/cgroup.procs
3744924

The memory limit in cgroup:

$ cat /sys/fs/cgroup/memory/karim/master/memory.limit_in_bytes
7340032000

rss of the cgroup is 990 MB:

$ cat /sys/fs/cgroup/memory/karim/master/memory.stat
cache 5990449152
rss 990224384
rss_huge 0
shmem 0
mapped_file 13516800
dirty 1081344
writeback 270336
pgpgin 4195191
pgpgout 2490628
pgfault 5264589
pgmajfault 0
inactive_anon 0
active_anon 990240768
inactive_file 5862830080
active_file 127021056
unevictable 0
hierarchical_memory_limit 7340032000
total_cache 5990449152
total_rss 990224384
total_rss_huge 0
total_shmem 0
total_mapped_file 13516800
total_dirty 1081344
total_writeback 270336
total_pgpgin 4195191
total_pgpgout 2490628
total_pgfault 5264589
total_pgmajfault 0
total_inactive_anon 0
total_active_anon 990240768
total_inactive_file 5862830080
total_active_file 127021056
total_unevictable 0

rss of the process is 165 MB:

$ cat /proc/3744924/status
Name:   [main]       /h
Umask:  0002
State:  S (sleeping)
Tgid:   3744924
Ngid:   0
Pid:    3744924
PPid:   3744912
TracerPid:  0
Uid:    1000    1000    1000    1000
Gid:    1001    1001    1001    1001
FDSize: 256
Groups: 1000 1001
NStgid: 3744924
NSpid:  3744924
NSpgid: 3744912
NSsid:  45028
VmPeak:  2149068 kB
VmSize:  2088876 kB
VmLck:         0 kB
VmPin:         0 kB
VmHWM:    245352 kB
VmRSS:    198964 kB
RssAnon:      165248 kB
RssFile:       33660 kB
RssShmem:         56 kB
VmData:   575400 kB
VmStk:       132 kB
VmExe:      3048 kB
VmLib:     19180 kB
VmPTE:      1152 kB
VmSwap:        0 kB
HugetlbPages:          0 kB
CoreDumping:    0
THP_enabled:    1
Threads:    17
SigQ:   0/241014
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000001001000
SigCgt: 0000000180000002
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 0000003fffffffff
CapAmb: 0000000000000000
NoNewPrivs: 0
Seccomp:    0
Speculation_Store_Bypass:   thread vulnerable
Cpus_allowed:   fff
Cpus_allowed_list:  0-11
Mems_allowed:   00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001
Mems_allowed_list:  0
voluntary_ctxt_switches:    94902
nonvoluntary_ctxt_switches: 1903

Why is there such a big difference?


问:
How can I use visNetwork to generate something like the following (image):
I have been trying to replicate something like the following image:

I would like to replicate it using visNetwork (or similar) and I have the following interactive code.

Code:

```<code>library(visNetwork)
nodes <- data.frame(id = 1:30, title = paste("node", 1:30),
                    shape = c("dot", "square"),
                    size = 10:15, color = c("blue", "red"))
edges <- data.frame(from = 1:25, to = c(sample(1:30, 25)))
visNetwork(nodes, edges) %>%
  visOptions(highlightNearest = TRUE, nodesIdSelection = FALSE)
</code>```

Body:
I have been trying to replicate something like the following image:

I would like to replicate it using visNetwork (or similar) and I have the following interactive code.

Code:

library(visNetwork)
nodes <- data.frame(id = 1:30, title = paste("node", 1:30),
                    shape = c("dot", "square"),
                    size = 10:15, color = c("blue", "red"))
edges <- data.frame(from = 1:25, to = c(sample(1:30, 25)))
visNetwork(nodes, edges) %>%
  visOptions(highlightNearest = TRUE, nodesIdSelection = FALSE)


问:
Replacement using the re.sub() if there a date indicated before or after the substring to be replaced, and if there is NO a "/n" or a ";" in between

import re, datetime

#operation function
def add_or_subtract_days(days, operation):
    today = datetime.date.today()
    if   operation == "add" : input_text = (datetime.datetime.strptime(today, "%Y-%m-%d") + datetime.timedelta(days=int(days))).strftime('%Y-%m-%d')
    elif operation == "subtract" : input_text = (datetime.datetime.strptime(today, "%Y-%m-%d") - datetime.timedelta(days=int(days))).strftime('%Y-%m-%d')

    return input_text

#recognition patterns function
def relative_indicated_dates(input_text):

    #both initial after the last line break that they have within their capture range
    # ((?:\w+)?)   ---> with a capturing group this pattern can capture a substring of alphanumeric characters (uppercase and lowercase) until it is taken with a space, a comma or a dot
    # ((?:\w\s*)+)   ---> this pattern is similar to the previous one but it does not stop when finding spaces
    some_text_withot_separations = "" # <--- HERE THE PROBLEM, WHERE I NEED THE RESTRICTION

    date_format = r"\d*-\d{2}-\d{2}"
    #date_format = r"\d*-\d{2}-\[\d{2}_--_\d{2}]"

    input_text = re.sub(date_format + r"[\s|]*" + some_text_withot_separations + " (?:(?:pasados|despues[\s|]*de|después|despues|tras)[\s|]*(?:[\s|]*unos|)?[\s|]*(\d+)[\s|]*(?:días|dias|día|dia)|(\d+)[\s|]*(?:días|dias|día|dia)[\s|]*(?:despues|luego)) " + some_text_withot_separations + r"[\s|]*" + date_format,
                        #lambda m: print(m[1], m[2], m[3]) ,
                        lambda m: m[1] + add_or_subtract_days(m[2] or m[3], "add"),
                        input_text)

    return input_text

#Input string examples:
input_text = "Empezo en 1999-12-30. Seguro eso ocurrio despues de 720 dias, o quizas fue aproximadamente despues de 6 dias o menos, o incluso puede ser el 2000-01-13 mismo"
input_text = "Seguro eso ocurrira despues de 2 dias, o quizas sea aproximadamente despues de 26 dias; actualmente luego de 2 dias ya tendre todo listo"
input_text = "Seguro eso ocurrira despues de 2 dias, o quizas sea aproximadamente despues del 2022-12-03; actualmente luego de 2 dias ya tendre todo listo"
input_text = """Decian muchas cosas; Seguro eso ocurrira despues de 120 dias, o quizas sea aproximadamente pasados 182 dias o quizas incluso menos.
Alla por 1996-11-02 o almenos 1800 dias despues inicio el modesto emprendimiento"""

print(repr(relative_indicated_dates(input_text)))  # --> output
```
<p>I need it to replace the original string with the output of the function <code>add_or_subtract_days()</code>, as long as what is indicated in regex patterns is fulfilled. That is, it must replace with the output of that function, if and only if, there is no date <code>r"\d*-\d{2}-\d{2}"</code> indicated <strong>before</strong> or <strong>after</strong> the phrase(alphanumeric character substring) that it must replace.</p>
<p>Regardless of this algorithm indicated here, the objective of the program is to indicate that if n number of days are indicated after a reference date NOT indicated, then those days begin to be counted taking the present day (today) as a reference date for the operation.</p>
<p>In the only case where it should enter the function even if there is a date before or after it is when there is a semicolon <code>";"</code> or a full stop point <code>".[\s|]*\n*"</code></p>
<p>I have already tried to place the pattern <code>((?:\w+)?)</code> or the pattern <code>((?:\w\s*)+)</code> in the <code>some_text_withot_separations</code> variable, although <strong>these patterns have 2 problems</strong>, so they are not suitable patterns. The first problem they present is that neither of the two patterns allows listing which elements stop the capture (that is, I need it not to find <code>;</code> or <code>\n.</code>). And the second problem they present is that both for some reason start their capture after the last newline of the substring that spans their capture range (which is incorrect).</p>
<p>After doing the replacement of the character strings (if any of the conditions are met), you should get these <strong>correct outputs for these input examples</strong> (assuming <code>today</code> in my country is  <code>= '2022-12-12'</code>)</p>
```'Empezo en 1999-12-30. Seguro eso ocurrio despues de 720 dias, o quizas fue aproximadamente despues de 6 dias o menos, o incluso puede ser el 2000-01-13 mismo'

'Seguro eso ocurrira 2022-12-14, o quizas sea aproximadamente 2023-01-07; actualmente 2022-12-14 ya tendre todo listo'

'Seguro eso ocurrira despues de 2 dias, o quizas sea aproximadamente despues del 2022-12-03; actualmente 2022-12-14 ya tendre todo listo'

"""Decian muchas cosas; Seguro eso ocurrira 2023-04-11, o quizas sea aproximadamente 2023-06-12 o quizas incluso menos.
Alla por 1996-11-02 o almenos 1800 dias despues inicio el modesto emprendimiento"""
```

What regex pattern should I establish to achieve these replacements considering that it does not find the ; or these line breaks?

Body:
import re, datetime

#operation function
def add_or_subtract_days(days, operation):
    today = datetime.date.today()
    if   operation == "add" : input_text = (datetime.datetime.strptime(today, "%Y-%m-%d") + datetime.timedelta(days=int(days))).strftime('%Y-%m-%d')
    elif operation == "subtract" : input_text = (datetime.datetime.strptime(today, "%Y-%m-%d") - datetime.timedelta(days=int(days))).strftime('%Y-%m-%d')

    return input_text

#recognition patterns function
def relative_indicated_dates(input_text):

    #both initial after the last line break that they have within their capture range
    # ((?:\w+)?)   ---> with a capturing group this pattern can capture a substring of alphanumeric characters (uppercase and lowercase) until it is taken with a space, a comma or a dot
    # ((?:\w\s*)+)   ---> this pattern is similar to the previous one but it does not stop when finding spaces
    some_text_withot_separations = "" # <--- HERE THE PROBLEM, WHERE I NEED THE RESTRICTION

    date_format = r"\d*-\d{2}-\d{2}"
    #date_format = r"\d*-\d{2}-\[\d{2}_--_\d{2}]"

    input_text = re.sub(date_format + r"[\s|]*" + some_text_withot_separations + " (?:(?:pasados|despues[\s|]*de|después|despues|tras)[\s|]*(?:[\s|]*unos|)?[\s|]*(\d+)[\s|]*(?:días|dias|día|dia)|(\d+)[\s|]*(?:días|dias|día|dia)[\s|]*(?:despues|luego)) " + some_text_withot_separations + r"[\s|]*" + date_format,
                        #lambda m: print(m[1], m[2], m[3]) ,
                        lambda m: m[1] + add_or_subtract_days(m[2] or m[3], "add"),
                        input_text)

    return input_text

#Input string examples:
input_text = "Empezo en 1999-12-30. Seguro eso ocurrio despues de 720 dias, o quizas fue aproximadamente despues de 6 dias o menos, o incluso puede ser el 2000-01-13 mismo"
input_text = "Seguro eso ocurrira despues de 2 dias, o quizas sea aproximadamente despues de 26 dias; actualmente luego de 2 dias ya tendre todo listo"
input_text = "Seguro eso ocurrira despues de 2 dias, o quizas sea aproximadamente despues del 2022-12-03; actualmente luego de 2 dias ya tendre todo listo"
input_text = """Decian muchas cosas; Seguro eso ocurrira despues de 120 dias, o quizas sea aproximadamente pasados 182 dias o quizas incluso menos.
Alla por 1996-11-02 o almenos 1800 dias despues inicio el modesto emprendimiento"""

print(repr(relative_indicated_dates(input_text)))  # --> output

I need it to replace the original string with the output of the function add_or_subtract_days(), as long as what is indicated in regex patterns is fulfilled. That is, it must replace with the output of that function, if and only if, there is no date r"\d*-\d{2}-\d{2}" indicated before or after the phrase(alphanumeric character substring) that it must replace.

Regardless of this algorithm indicated here, the objective of the program is to indicate that if n number of days are indicated after a reference date NOT indicated, then those days begin to be counted taking the present day (today) as a reference date for the operation.

In the only case where it should enter the function even if there is a date before or after it is when there is a semicolon ";" or a full stop point ".[\s|]*\n*"

I have already tried to place the pattern ((?:\w+)?) or the pattern ((?:\w\s*)+) in the some_text_withot_separations variable, although these patterns have 2 problems, so they are not suitable patterns. The first problem they present is that neither of the two patterns allows listing which elements stop the capture (that is, I need it not to find ; or \n.). And the second problem they present is that both for some reason start their capture after the last newline of the substring that spans their capture range (which is incorrect).

After doing the replacement of the character strings (if any of the conditions are met), you should get these correct outputs for these input examples (assuming today in my country is  = '2022-12-12')

'Empezo en 1999-12-30. Seguro eso ocurrio despues de 720 dias, o quizas fue aproximadamente despues de 6 dias o menos, o incluso puede ser el 2000-01-13 mismo'

'Seguro eso ocurrira 2022-12-14, o quizas sea aproximadamente 2023-01-07; actualmente 2022-12-14 ya tendre todo listo'

'Seguro eso ocurrira despues de 2 dias, o quizas sea aproximadamente despues del 2022-12-03; actualmente 2022-12-14 ya tendre todo listo'

"""Decian muchas cosas; Seguro eso ocurrira 2023-04-11, o quizas sea aproximadamente 2023-06-12 o quizas incluso menos.
Alla por 1996-11-02 o almenos 1800 dias despues inicio el modesto emprendimiento"""

What regex pattern should I establish to achieve these replacements considering that it does not find the ; or these line breaks?


问:
Multi Tenant Rails app: Certbot SSL, Puma and nginx
I'm trying to set up a multi tenant rails app. Nginx & Puma with Certbot. However, certbot will rewrite the nginx conf to hard link to the last domain the server_name list.

Then the other sites "example1.com, exmaple2.com, etc" will not have certs served. They will have certs generated but not hard linked in the conf file.

I've tried seperating each domain into their own conf file in the sites-enabled directory but I get an error about multiple upstreams.

So, what is the solution?


问:
Looping through and editing text files from R
I have a list of text files:

```<code>> filenames
[1] "meanimpactscript.inp"      "measinvarscript_IBR1.inp"  "measinvarscript_IBR10.inp" "measinvarscript_IBR13.inp"
[5] "measinvarscript_IBR2.inp"  "measinvarscript_IBR4.inp"  "measinvarscript_IBR5.inp"  "measinvarscript_IBR7.inp"
[9] "varimpactscript.inp"
</code>```

I would like to apply the following code to each of the files. Would appreciate any help.

```<code>meanimpactscript <- readLines("meanimpactscript.inp")
ix <- grep("ETA BY IBR13" , meanimpactscript)
p <- paste(append(meanimpactscript, "thresholds", ix), collapse = "\n")
writeLines(p, con="meanimpactscript.inp")
</code>```

Body:
I have a list of text files:

> filenames
[1] "meanimpactscript.inp"      "measinvarscript_IBR1.inp"  "measinvarscript_IBR10.inp" "measinvarscript_IBR13.inp"
[5] "measinvarscript_IBR2.inp"  "measinvarscript_IBR4.inp"  "measinvarscript_IBR5.inp"  "measinvarscript_IBR7.inp"
[9] "varimpactscript.inp"

I would like to apply the following code to each of the files. Would appreciate any help.

meanimpactscript <- readLines("meanimpactscript.inp")
ix <- grep("ETA BY IBR13" , meanimpactscript)
p <- paste(append(meanimpactscript, "thresholds", ix), collapse = "\n")
writeLines(p, con="meanimpactscript.inp")


问:
How to manage custom .NET nuget package for single concern/purpose with different teams?
In our organization another organization merged few years before.
Different teams have their own custom .net nuget packages to
do common concerns eg: Logging, Caching, Database Read/Write, Pub/Sub, oAuth2 etc.

We are thinking to come up with single custom nuget package for single concern/purpose (say logging) across teams.
The pros I see, no need to maintain multiple nuget packages for same concern/purpose.
Cons, We need to abstract custom nuget packages in a way that support multiple team's application. Also there might be code change to the existing applications which reference these new custom nuget packages.

Any thoughts/recommendations How to manage custom .NET nuget package for single concern/purpose with different teams?

I googled "How to manage custom .NET nuget package for single concern/purpose with different teams?" and dont see appropriate answer. So thought of posting this question here.


问:
Pyodbc Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'SQL Server' : file not found (0) (SQLDriverConnect)")
I installed the driver and verified it using pyodbc.drivers().

```<code>import pyodbc
print(pyodbc.drivers())

['PostgreSQL', 'MySQL', 'ODBC Driver 13 for SQL Server']

# Connect

connection = pyodbc.connect(
                              'Driver={SQL Server};'
                              'Server=xxx;'
                              'Database=Kxxxx;'
                              'Trusted_Connection=True;'
                           )
</code>```

I get an error:

```<code>Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'SQL Server' : file not found (0) (SQLDriverConnect)")
</code>```

Body:
I installed the driver and verified it using pyodbc.drivers().

import pyodbc
print(pyodbc.drivers())

['PostgreSQL', 'MySQL', 'ODBC Driver 13 for SQL Server']

# Connect

connection = pyodbc.connect(
                              'Driver={SQL Server};'
                              'Server=xxx;'
                              'Database=Kxxxx;'
                              'Trusted_Connection=True;'
                           )

I get an error:

Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'SQL Server' : file not found (0) (SQLDriverConnect)")


问:
playwright and httpx coroutine conflicts，How to solve it？
I created a BaseSpider class that needs to use playwright and httpx, but in the case of coroutines, they conflict.
code:

class BaseSpider():
    def __init__(self) :

        self.play_wright = sync_playwright().start()

    async def req(self, client: AsyncClient, i):
        res = await client.get('https://www.baidu.com')
        print(f'{i + 1}，status_code = {res.status_code}')
        return res

    async def main(self):
        async with httpx.AsyncClient() as client:
            response = await client.get('https://www.baidu.com')
            print(response)

if __name__ == '__main__':
   base = BaseSpider()
   asyncio.run(base.main())
```

run error:asyncio.run() cannot be called from a running event loop

I comment # self.play_wright = sync_playwright().start().They're ready to work.

How to get Playwright and HTTPX to run together in coroutines？

Thank you for your help！

Body:
I created a BaseSpider class that needs to use playwright and httpx, but in the case of coroutines, they conflict.
code:

class BaseSpider():
    def __init__(self) :

        self.play_wright = sync_playwright().start()

    async def req(self, client: AsyncClient, i):
        res = await client.get('https://www.baidu.com')
        print(f'{i + 1}，status_code = {res.status_code}')
        return res

    async def main(self):
        async with httpx.AsyncClient() as client:
            response = await client.get('https://www.baidu.com')
            print(response)

if __name__ == '__main__':
   base = BaseSpider()
   asyncio.run(base.main())

run error:asyncio.run() cannot be called from a running event loop

I comment # self.play_wright = sync_playwright().start().They're ready to work.

How to get Playwright and HTTPX to run together in coroutines？

Thank you for your help！


问:
CI-CD binary dependency not in image GitLab
My teams uses taskfiles to manage tasks in their code (like building/publishing containers to ECS.) Essentially, to make it easy to setup a local environment, all steps needed are in a taskfile. Most of the steps being used in the CI/CD are just re-written taskfiles. This can be difficult to mantain as it is essentially code duplicated in the same place. I prefer not using a shell runner and to use a docker image for builds.

Is there anyway I can use taskfiles in any container?


问:
Can anyone help tranlating this sql queries to functional sql queries for sql server?
I am using TPC-H Benchmark to do some studies, and i have been having some difficulties to understand and find the correct functions to use on sql server.

What is the meaning of :n -1 at the end of the file? What is the meaning of this c_mktsegment = ':1'. How to do this operation,

```<code>and o_orderdate < date ':2'
</code>```

I am going to save a file just as example.

-- $ID$
-- TPC-H/TPC-R Shipping Priority Query (Q3)
-- Functional Query Definition
-- Approved February 1998

```<code>    l_orderkey,
    sum(l_extendedprice * (1 - l_discount)) as revenue,
    o_orderdate,
    o_shippriority
from
    customer,
    orders,
    lineitem
where
    c_mktsegment = ':1'
    and c_custkey = o_custkey
    and l_orderkey = o_orderkey
    and o_orderdate < date ':2'
    and l_shipdate > date ':2'
group by
    l_orderkey,
    o_orderdate,
    o_shippriority
order by
    revenue desc,
    o_orderdate;
:n 10```

I did try to find some examples saying the conversion of the queries to sql server queries, but it seems its already sql server queries, but still, couldnt find the right conversion as if i try toi research some lines of code, i cant find anything.

when i run the code it shows me for example
Msg 102, Level 15, State 1, Line 19
Incorrect syntax near ':2'.
```

Body:
I am using TPC-H Benchmark to do some studies, and i have been having some difficulties to understand and find the correct functions to use on sql server.

What is the meaning of :n -1 at the end of the file? What is the meaning of this c_mktsegment = ':1'. How to do this operation,

and o_orderdate < date ':2'

I am going to save a file just as example.

-- $ID$
-- TPC-H/TPC-R Shipping Priority Query (Q3)
-- Functional Query Definition
-- Approved February 1998

    l_orderkey,
    sum(l_extendedprice * (1 - l_discount)) as revenue,
    o_orderdate,
    o_shippriority
from
    customer,
    orders,
    lineitem
where
    c_mktsegment = ':1'
    and c_custkey = o_custkey
    and l_orderkey = o_orderkey
    and o_orderdate < date ':2'
    and l_shipdate > date ':2'
group by
    l_orderkey,
    o_orderdate,
    o_shippriority
order by
    revenue desc,
    o_orderdate;
:n 10```

I did try to find some examples saying the conversion of the queries to sql server queries, but it seems its already sql server queries, but still, couldnt find the right conversion as if i try toi research some lines of code, i cant find anything.

when i run the code it shows me for example
Msg 102, Level 15, State 1, Line 19
Incorrect syntax near ':2'.


问:
Nginx redirect http traffic to https
I have a domain which work only in our VPN network.
Recently we enabled the SSL on that and its working fine with https, but now i want to redirect all my http traffic also to https.

For this i added below block along with ssl block but still http request is not re-directing to https.

```<code>server {
    listen 80;
    server_name domain_name.com www.domain_name.com;
    return 301 https://$domain_name$request_uri;
}

server {
   server_name example.com;
   access_log /var/log/nginx/example-access.log;
   error_log /var/log/nginx/example-error.log;
   root /var/www/html/web;

   index index.html index.htm index.php;

   location / {
       try_files $uri $uri/ /index.php$uri?$args;
   }
}
</code>```

I tried with my domain_name,localhost with port number also, nothing works for me.

Title: Nginx redirect http traffic to https

Body:
I have a domain which work only in our VPN network.
Recently we enabled the SSL on that and its working fine with https, but now i want to redirect all my http traffic also to https.

For this i added below block along with ssl block but still http request is not re-directing to https.

server {
    listen 80;
    server_name domain_name.com www.domain_name.com;
    return 301 https://$domain_name$request_uri;
}

server {
   server_name example.com;
   access_log /var/log/nginx/example-access.log;
   error_log /var/log/nginx/example-error.log;
   root /var/www/html/web;

   index index.html index.htm index.php;

   location / {
       try_files $uri $uri/ /index.php$uri?$args;
   }
}

I tried with my domain_name,localhost with port number also, nothing works for me.


问:
How can I have code coverage gutters in Visual Studio Code, but also have working breakpoints?
I have code coverage working for my Python code in VSCode. However, I can't set or remove breakpoints if the gutters are displayed. This is apparently a known issue:

to both use the extension and code debugging breakpoints you need to disable the gutter coverage

https://github.com/ryanluker/vscode-coverage-gutters/issues/288

Is there really no workaround or alternative that doesn't involve turning off the coverage gutter shading?


问:
"Undefined Reference to IMG_Load" SDL_Image/SDL2
I have set up a development environment in VSCode with SDL2, SDL2_Image and MinGW. I am using this command to compile the program.

g++ -Isrc/include -Lsrc/lib -o main main.cpp -lmingw32 -lSDL2main -lSDL2 -lSDL2_image
```
<p>I have SDL2_image.h in src/include/SDL2. I have libSDL2_image.(a/dll.a/la) all in src/lib. I have the SDL2_image.dll in the project folder.</p>
<p>I am including SDL_image like so</p>
```#include "SDL2/SDL_image.h"
```

The program will compile fine as along as I am not using the IMG_Load function, if I do it throws the error: undefined reference to `IMG_Load'.

To my knowledge, I have dragged all necessary files and included them in the appropriate folders. VSCode seems to recognize the file SDL_image.h, so I am unsure why the reference to IMG_Load remains undefined.

Body:
I have set up a development environment in VSCode with SDL2, SDL2_Image and MinGW. I am using this command to compile the program.

g++ -Isrc/include -Lsrc/lib -o main main.cpp -lmingw32 -lSDL2main -lSDL2 -lSDL2_image

I have SDL2_image.h in src/include/SDL2. I have libSDL2_image.(a/dll.a/la) all in src/lib. I have the SDL2_image.dll in the project folder.

I am including SDL_image like so

#include "SDL2/SDL_image.h"

The program will compile fine as along as I am not using the IMG_Load function, if I do it throws the error: undefined reference to `IMG_Load'.

To my knowledge, I have dragged all necessary files and included them in the appropriate folders. VSCode seems to recognize the file SDL_image.h, so I am unsure why the reference to IMG_Load remains undefined.


问:
unable to find valid certification path to requested target
I am installing  running Jenkins in  EKS ( Amazon Kubernetes) , I am trying to integrate Jenkins with AD credentials . For this I am preparing a jks file and passing it to JAVA_OPTS as below , but its giving me error unable to find  valid certification path to requested target, even though the certificate is available at that path. can any one able to help me .
Thanks in Advance .

I am giving JAVA_OPTS as below

```<code>JAVA_OPTS: -Dcasc.reload.token=$(POD_NAME) -Djavax.net.ssl.trustStore=/var/jenkins_keystore/keystore.jks -Djavax.net.ssl.trustStorePassword=changeit
</code>```

The file keystore.jks file exists .

```<code> hudson.util.Retrier#start: The attempt #1 to do the action check updates server failed with an allowed exception:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
    at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
    at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)
    at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:434)
Caused: sun.security.validator.ValidatorException: PKIX path building failed
    at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:439)
    at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:306)
    at java.base/sun.security.validator.Validator.validate(Validator.java:264)
    at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:313)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:222)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.checkServerCerts(CertificateMessage.java:1341)
Caused: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:353)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:296)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:291)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.checkServerCerts(CertificateMessage.java:1357)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.onConsumeCertificate(CertificateMessage.java:1232)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.consume(CertificateMessage.java:1175)
    at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:392)
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:443)
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:421)
    at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:183)
    at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:172)
    at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1506)
    at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1416)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:456)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:427)
    at java.base/sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:572)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:201)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1592)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1520)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
    at hudson.model.DownloadService.loadJSON(DownloadService.java:122)
    at hudson.model.UpdateSite.updateDirectlyNow(UpdateSite.java:219)
    at hudson.model.UpdateSite.updateDirectlyNow(UpdateSite.java:214)
    at hudson.PluginManager.checkUpdatesServer(PluginManager.java:1951)
    at hudson.util.Retrier.start(Retrier.java:62)
    at hudson.PluginManager.doCheckUpdatesServer(PluginManager.java:1922)
    at jenkins.DailyCheck.execute(DailyCheck.java:93)
    at hudson.model.AsyncPeriodicWork.lambda$doRun$1(AsyncPeriodicWork.java:102)
    at java.base/java.lang.Thread.run(Thread.java:829)
</code>```

Body:
I am installing  running Jenkins in  EKS ( Amazon Kubernetes) , I am trying to integrate Jenkins with AD credentials . For this I am preparing a jks file and passing it to JAVA_OPTS as below , but its giving me error unable to find  valid certification path to requested target, even though the certificate is available at that path. can any one able to help me .
Thanks in Advance .

I am giving JAVA_OPTS as below

JAVA_OPTS: -Dcasc.reload.token=$(POD_NAME) -Djavax.net.ssl.trustStore=/var/jenkins_keystore/keystore.jks -Djavax.net.ssl.trustStorePassword=changeit

The file keystore.jks file exists .

 hudson.util.Retrier#start: The attempt #1 to do the action check updates server failed with an allowed exception:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
    at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
    at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)
    at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:434)
Caused: sun.security.validator.ValidatorException: PKIX path building failed
    at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:439)
    at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:306)
    at java.base/sun.security.validator.Validator.validate(Validator.java:264)
    at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:313)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:222)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.checkServerCerts(CertificateMessage.java:1341)
Caused: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:353)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:296)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:291)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.checkServerCerts(CertificateMessage.java:1357)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.onConsumeCertificate(CertificateMessage.java:1232)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.consume(CertificateMessage.java:1175)
    at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:392)
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:443)
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:421)
    at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:183)
    at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:172)
    at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1506)
    at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1416)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:456)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:427)
    at java.base/sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:572)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:201)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1592)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1520)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
    at hudson.model.DownloadService.loadJSON(DownloadService.java:122)
    at hudson.model.UpdateSite.updateDirectlyNow(UpdateSite.java:219)
    at hudson.model.UpdateSite.updateDirectlyNow(UpdateSite.java:214)
    at hudson.PluginManager.checkUpdatesServer(PluginManager.java:1951)
    at hudson.util.Retrier.start(Retrier.java:62)
    at hudson.PluginManager.doCheckUpdatesServer(PluginManager.java:1922)
    at jenkins.DailyCheck.execute(DailyCheck.java:93)
    at hudson.model.AsyncPeriodicWork.lambda$doRun$1(AsyncPeriodicWork.java:102)
    at java.base/java.lang.Thread.run(Thread.java:829)


问:
Error: function uses multiple asynchronous interfaces: callback and promise

Error: function uses multiple asynchronous interfaces: callback and
promise
to use the callback interface: do not return a promise
to use the promise interface: remove the last argument to the function

I'm trying to write a cucumber test to one of my GET node API, and keep getting the above, looked at few GitHub and stack-overflow posts, and could not understand the issue, below are my test method details.

App.ts

```<code>  async getSsoId(refId: any): Promise<string> {
    let ssoId = '';
    const secrets = await this.vaultService.getClientSecrets();
    this.decrypt(refId, secrets.encryption_secret, secrets.encryption_Id).then((value: any) => {
      ssoId = value;
    });
    return ssoId;
  }

api.get('/status', async (req, res) => {
  let id;
  const statusCode = 200;
  try {
    id = await this.getId(String('123456'));
  } catch (err: any) {
    throw new ApiError('Error fetching id');
  }
  try {
    const item = await dbService.getItem(id);
    if (item) {
      statusCode = 201;
    } else {
      statusCode = 202;
    }
  } catch (err: any) {
    throw new ApiError(
      'The API encountered an error while attempting to communicate with the DB service.'
    );
  }
  res.status(statusCode).send(statusCode);
});
</code>```

Step Definition:

```<code>Given('a valid customer', function () {});

When("I call the get-id api", { timeout: 2 * 5000 }, async function (val) {
  util.callGetIdAPI().then((response) => {
    this.setApiResponseStatus(response.status);
    this.setResponseBody(JSON.stringify(response.body));
  });
});

Then("the apiResponseStatus should be <apiResponseStatus>", function (status) {
  assert.strictEqual(status, this.apiResponseStatus);
});

Then("the responseBody should be {string}", function (responseBody) {
  assert.equal(responseBody, this.responseBody);
});
</code>```

Util Function

```<code>callGetIdAPI = async () => {
  const headers = {
    'Content-Type': 'application/json;v=1',
    Accept: 'application/json;v=1'
  }
  const client = await getClient('url');
  const options = {
    method: 'GET',
    headers: headers,
    version: 3
  };
  let response;
  try {
    response = await client.get('/status', options);
    return {
      status: response.statusCode,
      body: response.body
    };
  } catch(error) {
    return {
      status: error.statusCode,
      body: {
        error: {
          id: error.id,
          message: error.message
        }
      }
    }
  }
};
</code>```

I'm new to this and trying to understand how multiple Premisses and Callbacks works in parallel, any thoughts or inputs on what possibly cause the error, or am I missing anything ??

Body:
Error: function uses multiple asynchronous interfaces: callback and
promise
to use the callback interface: do not return a promise
to use the promise interface: remove the last argument to the function

I'm trying to write a cucumber test to one of my GET node API, and keep getting the above, looked at few GitHub and stack-overflow posts, and could not understand the issue, below are my test method details.

App.ts

  async getSsoId(refId: any): Promise<string> {
    let ssoId = '';
    const secrets = await this.vaultService.getClientSecrets();
    this.decrypt(refId, secrets.encryption_secret, secrets.encryption_Id).then((value: any) => {
      ssoId = value;
    });
    return ssoId;
  }

api.get('/status', async (req, res) => {
  let id;
  const statusCode = 200;
  try {
    id = await this.getId(String('123456'));
  } catch (err: any) {
    throw new ApiError('Error fetching id');
  }
  try {
    const item = await dbService.getItem(id);
    if (item) {
      statusCode = 201;
    } else {
      statusCode = 202;
    }
  } catch (err: any) {
    throw new ApiError(
      'The API encountered an error while attempting to communicate with the DB service.'
    );
  }
  res.status(statusCode).send(statusCode);
});

Step Definition:

Given('a valid customer', function () {});

When("I call the get-id api", { timeout: 2 * 5000 }, async function (val) {
  util.callGetIdAPI().then((response) => {
    this.setApiResponseStatus(response.status);
    this.setResponseBody(JSON.stringify(response.body));
  });
});

Then("the apiResponseStatus should be <apiResponseStatus>", function (status) {
  assert.strictEqual(status, this.apiResponseStatus);
});

Then("the responseBody should be {string}", function (responseBody) {
  assert.equal(responseBody, this.responseBody);
});

Util Function

callGetIdAPI = async () => {
  const headers = {
    'Content-Type': 'application/json;v=1',
    Accept: 'application/json;v=1'
  }
  const client = await getClient('url');
  const options = {
    method: 'GET',
    headers: headers,
    version: 3
  };
  let response;
  try {
    response = await client.get('/status', options);
    return {
      status: response.statusCode,
      body: response.body
    };
  } catch(error) {
    return {
      status: error.statusCode,
      body: {
        error: {
          id: error.id,
          message: error.message
        }
      }
    }
  }
};

I'm new to this and trying to understand how multiple Premisses and Callbacks works in parallel, any thoughts or inputs on what possibly cause the error, or am I missing anything ??


问:
Flink: Kafka CDC topic playback
I am working on a solution where I am reading from a Kafka CDC compacted topic (debezium format). But this, technically would be used as source of external information stored in a Flink Table. The problem is that how would I wait for this table to catch up to the latest offset on the compacted topic for it to start processing the other stuff? I want to do this for when the flink app needs to restart, so it can first finish playing back data from the CDC topic and then start consuming messages from the other kafka source

Flink: 1.15.2

Kafka CDC table:

```<code>CREATE TABLE metadata (
id                  VARCHAR,
eventMetadata       VARCHAR,
origin_ts as PROCTIME(),
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'connector'                           = 'kafka',
'properties.bootstrap.servers'        = 'SERVER_ADDR',
'properties.group.id'                 = 'SOME_GROUP',
'topic'                               = 'SOME_TOPIC',
'scan.startup.mode'                   = 'latest-offset',
'value.format'                        = 'debezium-json'
)
</code>```

Ideally, I need to wait until the CDC table has caught up with the latest offset on the topic and only then start processing the messages from the actual source of messages

```<code>KafkaSource.<CustomObject>builder()
        .setBootstrapServers(params.get("kafka.bootstrap.servers"))
        .setBounded(OffsetsInitializer.latest())
        .setDeserializer(KafkaRecordDeserializationSchema.of(new CustomObjectDeserializer()))
        .setTopics(params.get("kafka.source.topic"))
        .setGroupId(params.get("kafka.source.consumer.id"))
        .build();
</code>```

Would I have to write some blocking code that would only execute the rest of the topology once the CDC table is "quiet" (ie. hasn't read any new rows in, let's say, last 10 seconds)? Are there any better ways of playing back kafka topics in flink at startup which would wait until the CDC source is all caught up?

Title: Flink: Kafka CDC topic playback

Body:
I am working on a solution where I am reading from a Kafka CDC compacted topic (debezium format). But this, technically would be used as source of external information stored in a Flink Table. The problem is that how would I wait for this table to catch up to the latest offset on the compacted topic for it to start processing the other stuff? I want to do this for when the flink app needs to restart, so it can first finish playing back data from the CDC topic and then start consuming messages from the other kafka source

Flink: 1.15.2

Kafka CDC table:

CREATE TABLE metadata (
id                  VARCHAR,
eventMetadata       VARCHAR,
origin_ts as PROCTIME(),
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'connector'                           = 'kafka',
'properties.bootstrap.servers'        = 'SERVER_ADDR',
'properties.group.id'                 = 'SOME_GROUP',
'topic'                               = 'SOME_TOPIC',
'scan.startup.mode'                   = 'latest-offset',
'value.format'                        = 'debezium-json'
)

Ideally, I need to wait until the CDC table has caught up with the latest offset on the topic and only then start processing the messages from the actual source of messages

KafkaSource.<CustomObject>builder()
        .setBootstrapServers(params.get("kafka.bootstrap.servers"))
        .setBounded(OffsetsInitializer.latest())
        .setDeserializer(KafkaRecordDeserializationSchema.of(new CustomObjectDeserializer()))
        .setTopics(params.get("kafka.source.topic"))
        .setGroupId(params.get("kafka.source.consumer.id"))
        .build();

Would I have to write some blocking code that would only execute the rest of the topology once the CDC table is "quiet" (ie. hasn't read any new rows in, let's say, last 10 seconds)? Are there any better ways of playing back kafka topics in flink at startup which would wait until the CDC source is all caught up?


问:
how to Share a Google Sheet via API
I am trying to share a Sheet, not the hole Spreadsheet, using Sheets API, via Make (former Integromat).

I tried via Google Drive, but it shares the hole Spreadsheet. Can´t especify a single Sheet.

Title: how to Share a Google Sheet via API


问:
intern_profile_view() missing 1 required positional argument: 'request'
Can anyone tell me what I've done wrong? I'm trying to create a simple multi users app in django and I can't quite tell what I'm missing in my view.

Here's what I have so far.

views.py

```<code>@method_decorator([login_required, intern_required], name='dispatch')
def intern_profile_view(request):

  if request.method == 'POST':

    user_form = InternSignUpForm(request.POST, prefix='UF')
    profile_form = InternProfileForm(request.POST, prefix='PF')

    if user_form.is_valid() and profile_form.is_valid():
        user = user_form.save(commit=False)

        user.save()

        user.intern_profile.bio = profile_form.cleaned_data.get('bio')
        user.intern_profile.location = profile_form.cleaned_data.get('location')
        user.intern_profile.save()

    else:
        user_form = InternSignUpForm(prefix='UF')
        profile_form = InternProfileForm(prefix='PF')

    return render(request, 'interns/intern_profile.html',{
            'user_form': user_form,
            'profile_form': profile_form,
        })
</code>```

models.py

```<code>class User(AbstractUser):
    is_student = models.BooleanField(default=False)
    is_teacher = models.BooleanField(default=False)
    is_intern = models.BooleanField(default=False)

class InternProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True,
           related_name='intern_profile')
    bio = models.CharField(max_length=30, blank=True)
    location = models.CharField(max_length=30, blank=True)
</code>```

traceback

```<code>Traceback (most recent call last):
  File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\mikha\issue_env\lib\site-packages\django\utils\decorators.py", line 46, in _wrapper
    return bound_method(*args, **kwargs)
TypeError: intern_profile_view() missing 1 required positional argument: 'request'
</code>```

urls.py

```<code>path('interns/', include(([
        path('', interns.intern_profile_view, name='intern_profile'),
    ], 'classroom'), namespace='interns')),
</code>```

Body:
Can anyone tell me what I've done wrong? I'm trying to create a simple multi users app in django and I can't quite tell what I'm missing in my view.

Here's what I have so far.

views.py

@method_decorator([login_required, intern_required], name='dispatch')
def intern_profile_view(request):

  if request.method == 'POST':

    user_form = InternSignUpForm(request.POST, prefix='UF')
    profile_form = InternProfileForm(request.POST, prefix='PF')

    if user_form.is_valid() and profile_form.is_valid():
        user = user_form.save(commit=False)

        user.save()

        user.intern_profile.bio = profile_form.cleaned_data.get('bio')
        user.intern_profile.location = profile_form.cleaned_data.get('location')
        user.intern_profile.save()

    else:
        user_form = InternSignUpForm(prefix='UF')
        profile_form = InternProfileForm(prefix='PF')

    return render(request, 'interns/intern_profile.html',{
            'user_form': user_form,
            'profile_form': profile_form,
        })

models.py

class User(AbstractUser):
    is_student = models.BooleanField(default=False)
    is_teacher = models.BooleanField(default=False)
    is_intern = models.BooleanField(default=False)

class InternProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True,
           related_name='intern_profile')
    bio = models.CharField(max_length=30, blank=True)
    location = models.CharField(max_length=30, blank=True)

traceback

Traceback (most recent call last):
  File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\mikha\issue_env\lib\site-packages\django\utils\decorators.py", line 46, in _wrapper
    return bound_method(*args, **kwargs)
TypeError: intern_profile_view() missing 1 required positional argument: 'request'

urls.py

path('interns/', include(([
        path('', interns.intern_profile_view, name='intern_profile'),
    ], 'classroom'), namespace='interns')),


问:
Replacement error calculating replacement in clang
I'm trying to refactor if-else branches and am unable to generate accurate Replacements for it. I try to fetch nodes using:

```<code>clang::IfStmt *ifstmt = const_cast<clang::IfStmt *>(
                result.Nodes.getNodeAs<clang::IfStmt>("if_simple_else_bind_name"))
</code>```

and then calculate its source range using

```<code>ifstmt->getSourceRange()
</code>```

However, I find that after using this SourceRange for calculating the start and end for the branch sometimes misses a semicolon for cases like these:

```<code>if(cond) {
     return a;
}
else
     return b; <-- here
</code>```

How do I find the correct source range and further on generate the correct replacement rewriting the whole branch regardless of whether there are any braces or simple statements?

Any help would be highly appreciated!

Body:
I'm trying to refactor if-else branches and am unable to generate accurate Replacements for it. I try to fetch nodes using:

clang::IfStmt *ifstmt = const_cast<clang::IfStmt *>(
                result.Nodes.getNodeAs<clang::IfStmt>("if_simple_else_bind_name"))

and then calculate its source range using

ifstmt->getSourceRange()

However, I find that after using this SourceRange for calculating the start and end for the branch sometimes misses a semicolon for cases like these:

if(cond) {
     return a;
}
else
     return b; <-- here

How do I find the correct source range and further on generate the correct replacement rewriting the whole branch regardless of whether there are any braces or simple statements?

Any help would be highly appreciated!


Title: Bucket prediction given an integer?

Body:
If I have a dictionary of integers where the value is an array of two integers sorted, with the two values being the largest value, and the smallest value out of k values present in bucket n, how can I predict/estimate which bucket a given number would appear.

An example of said dictionary is:

{
    1: [
        541247,
        14771
    ],
    15: [
        9789,
        9621
    ],
    22: [
        8984,
        8923
    ],
    64: [
        7278,
        7263
    ],
    93: [
        6846,
        6804
    ],
    126: [
        5789,
        5765
    ],
    139: [
        5484,
        5462
    ],
    208: [
        4326,
        4314
    ],
    285: [
        3788,
        3783
    ],
    322: [
        3634,
        3631
    ],
    337: [
        3586,
        3582
    ],
    356: [
        3517,
        3513
    ],
    448: [
        3232,
        3229
    ],
    459: [
        3199,
        3196
    ],
    539: [
        2990,
        2989
    ],
    581: [
        2891,
        2890
    ],
    596: [
        2858,
        2856
    ],
    640: [
        2770,
        2768
    ],
    675: [
        2704,
        2702
    ],
    679: [
        2697,
        2695
    ],
    686: [
        2684,
        2682
    ],
    733: [
        2602,
        2600
    ],
    879: [
        2387,
        2386
    ],
    961: [
        2283,
        2282
    ],
    980: [
        2261,
        2260
    ],
    995: [
        2244,
        2243
    ],
    1000: [
        2238,
        2237
    ],
    1169: [
        2064,
        2063
    ],
    1175: [
        2058,
        2057
    ],
    1236: [
        2005,
        2004
    ],
    1259: [
        1985,
        1984
    ],
    1281: [
        1967,
        1966
    ],
    1348: [
        1913,
        1912
    ],
    1424: [
        1855,
        1855
    ],
    1429: [
        1852,
        1851
    ],
    1514: [
        1796,
        1795
    ],
    1564: [
        1764,
        1764
    ],
    1596: [
        1744,
        1744
    ],
    1625: [
        1726,
        1726
    ],
    1661: [
        1704,
        1703
    ],
    1695: [
        1683,
        1682
    ],
    1710: [
        1675,
        1674
    ],
    1713: [
        1673,
        1673
    ],
    1720: [
        1669,
        1669
    ],
    1835: [
        1609,
        1608
    ],
    1846: [
        1603,
        1602
    ],
    1861: [
        1594,
        1594
    ],
    1864: [
        1593,
        1592
    ],
    1916: [
        1562,
        1561
    ],
    2093: [
        1462,
        1462
    ],
    2159: [
        1424,
        1423
    ],
    2175: [
        1414,
        1413
    ],
    2189: [
        1405,
        1405
    ],
    2209: [
        1394,
        1393
    ],
    2266: [
        1359,
        1358
    ],
    2319: [
        1327,
        1326
    ],
    2352: [
        1306,
        1306
    ],
    2429: [
        1260,
        1260
    ],
    2512: [
        1214,
        1214
    ],
    2629: [
        1141,
        1141
    ],
    2704: [
        1088,
        1088
    ],
    2736: [
        1064,
        1063
    ],
    2745: [
        1057,
        1057
    ],
    2766: [
        1042,
        1042
    ],
    2779: [
        1033,
        1032
    ],
    2790: [
        1025,
        1024
    ],
    2798: [
        1019,
        1018
    ],
    2880: [
        964,
        964
    ],
    2945: [
        928,
        927
    ],
    3032: [
        885,
        884
    ],
    3115: [
        838,
        837
    ],
    3120: [
        835,
        834
    ],
    3140: [
        823,
        822
    ],
    3169: [
        806,
        805
    ],
    3235: [
        770,
        770
    ],
    3252: [
        762,
        762
    ],
    3258: [
        759,
        758
    ],
    3366: [
        715,
        714
    ],
    3414: [
        690,
        690
    ],
    3444: [
        675,
        674
    ],
    3507: [
        645,
        644
    ],
    3543: [
        630,
        629
    ],
    3758: [
        516,
        515
    ],
    3764: [
        512,
        511
    ],
    3770: [
        509,
        508
    ],
    3931: [
        446,
        446
    ],
    4013: [
        416,
        415
    ],
    4055: [
        390,
        390
    ],
    4116: [
        378,
        377
    ],
    4255: [
        370,
        370
    ],
    4286: [
        362,
        361
    ],
    4325: [
        360,
        360
    ],
    4337: [
        355,
        355
    ],
    4349: [
        347,
        347
    ],
    4355: [
        344,
        343
    ],
    4366: [
        339,
        339
    ],
    4379: [
        333,
        333
    ],
    4460: [
        312,
        311
    ],
    4474: [
        309,
        309
    ],
    4487: [
        308,
        308
    ],
    4545: [
        259,
        257
    ],
    4555: [
        242,
        241
    ]
}

If I am searching for the bucket containing 2672 how would I go about doing this? The bucket data is gathered from web scraping so I know that bucket 692 contains 2672, but I am looking for a more general solution that would allow me to only have to scrape x number of buckets before I have enough data to predict which bucket would hold any value. I will add that the first and last entries in the dict are guaranteed to hold both the largest and smallest searchable values.

Is this a known problem already? If so what is it called?

My current solution is below:

def bucket_search(buckets, n):
    start_idx = None
    end_idx = None
    bucket_keys = list(buckets.keys())
    bucket_values = list(buckets.values())
    for idx, bv in enumerate(bucket_values):
        high,low = bv
        if n > low and n < high:
            start_idx = idx
            end_idx = idx
            break
        elif high < n:
            end_idx = idx
            break

    if (end_idx != start_idx):
        continue_search = True
        tmp_start_idx = end_idx - 1
        while continue_search:
            high, low = bucket_values[tmp_start_idx]
            if (low > n):
                continue_search = False
            elif (low < n and high < n):
                tmp_start_idx -= 1
        start_idx = tmp_start_idx

        start_bucket_value = bucket_keys[start_idx]
        end_bucket_value = bucket_keys[end_idx]

        start_value = bucket_values[start_idx][1]
        end_value = bucket_values[end_idx][0]

        bucket_value_difference = end_bucket_value - start_bucket_value
        value_difference = start_value - end_value

        increment_amount = bucket_value_difference / value_difference

        tmp_value = start_value
        tmp_bucket_value = start_bucket_value

        for i in range(bucket_value_difference):
            tmp_value -= increment_amount
            tmp_bucket_value += 1
            if (n > tmp_value):
                break
        return tmp_bucket_value

    else:
        return bucket_keys[start_idx]

Currently bucket_search(data, 2672) (where data is the example data provided above) returns 704. That is close to 692 but I would think that there is a better, more accurate/precise solution.

While I used python, answers of any language are fine as long as the answer can be rewritten in another language, i.e. please don't use any niche libraries.

If there is already an answered SO question that solves this problem, I apologize as I am unsure what to call this kind of problem.


问:
Importing a nestjs interceptor from another package
I am trying to extract some implementation that are common to several projects into a separate package that I would deploy on the NPM registry. Specifically, rather that create a Nestjs interceptor with the same requirement and repeat this in different project, I have decided to extract this into a separated package to be deployed separately. So that I can import the package like a normal import and apply the interceptor as usual. But I've noticed that the interceptor does not take effect.my interceptor in a separate package

I've tried several ways so far, including exporting the class and extending it within my service, but it seems the Nestjs within my service does not recognize the package dependency. The application runs fine, but the interceptor does not take effect. I also annotated my controller with the @UseInterceptors(). I've not been able to successfully test locally, so I haven't deployed.a work around to access the package and it's functionality

The lastest error message when trying to run locally: (I built locally and linked the package to another project using npm link)

```<code>Argument of type 'FinalInterceptor' is not assignable to parameter of type 'Function | NestInterceptor<any, any>'.
  Type 'FinalInterceptor' is not assignable to type 'NestInterceptor<any, any>'.
    Types of property 'intercept' are incompatible.
      Type '(context: import("/Users/m/Documents/m/awe-interceptor/awe-interceptor/node_modules/@nestjs/common/interfaces/features/execution-context.interface").ExecutionContext, next: import("/Users/m/Documents/m/awe-interceptor/awe-interceptor/node_modules/@nestjs/common/interfaces/...' is not assignable to type '(context: import("/Users/m/Documents/m/testing-interceptor/testing-interceptor/node_modules/@nestjs/common/interfaces/features/execution-context.interface").ExecutionContext, next: import("/Users/m/Documents/m/testing-interceptor/testing-interceptor/node_modules/@nestjs/comm...'.
        Types of parameters 'next' and 'next' are incompatible.
          Type 'import("/Users/m/Documents/m/testing-interceptor/testing-interceptor/node_modules/@nestjs/common/interfaces/features/nest-interceptor.interface").CallHandler<any>' is not assignable to type 'import("/Users/m/Documents/m/awe-interceptor/awe-interceptor/node_modules/@nestjs/common/interfaces/features/nest-interceptor.interface").CallHandler<any>'.
            The types of 'handle().operator.call' are incompatible between these types.
              Type '(subscriber: import("/Users/m/Documents/m/testing-interceptor/testing-interceptor/node_modules/rxjs/dist/types/internal/Subscriber").Subscriber<any>, source: any) => import("/Users/m/Documents/m/testing-interceptor/testing-interceptor/node_modules/rxjs/dist/types/internal/ty...' is not assignable to type '(subscriber: import("/Users/m/Documents/m/awe-interceptor/awe-interceptor/node_modules/rxjs/dist/types/internal/Subscriber").Subscriber<any>, source: any) => import("/Users/m/Documents/m/awe-interceptor/awe-interceptor/node_modules/rxjs/dist/types/internal/types").Teardown...'.
                Types of parameters 'subscriber' and 'subscriber' are incompatible.
                  Type 'import("/Users/m/Documents/m/awe-interceptor/awe-interceptor/node_modules/rxjs/dist/types/internal/Subscriber").Subscriber<any>' is not assignable to type 'import("/Users/m/Documents/m/testing-interceptor/testing-interceptor/node_modules/rxjs/dist/types/internal/Subscriber").Subscriber<any>'.
                    Property 'isStopped' is protected but type 'Subscriber<T>' is not a class derived from 'Subscriber<T>'.ts(2345)
</code>```

Body:
I am trying to extract some implementation that are common to several projects into a separate package that I would deploy on the NPM registry. Specifically, rather that create a Nestjs interceptor with the same requirement and repeat this in different project, I have decided to extract this into a separated package to be deployed separately. So that I can import the package like a normal import and apply the interceptor as usual. But I've noticed that the interceptor does not take effect.my interceptor in a separate package

I've tried several ways so far, including exporting the class and extending it within my service, but it seems the Nestjs within my service does not recognize the package dependency. The application runs fine, but the interceptor does not take effect. I also annotated my controller with the @UseInterceptors(). I've not been able to successfully test locally, so I haven't deployed.a work around to access the package and it's functionality

The lastest error message when trying to run locally: (I built locally and linked the package to another project using npm link)

Argument of type 'FinalInterceptor' is not assignable to parameter of type 'Function | NestInterceptor<any, any>'.
  Type 'FinalInterceptor' is not assignable to type 'NestInterceptor<any, any>'.
    Types of property 'intercept' are incompatible.
      Type '(context: import("/Users/m/Documents/m/awe-interceptor/awe-interceptor/node_modules/@nestjs/common/interfaces/features/execution-context.interface").ExecutionContext, next: import("/Users/m/Documents/m/awe-interceptor/awe-interceptor/node_modules/@nestjs/common/interfaces/...' is not assignable to type '(context: import("/Users/m/Documents/m/testing-interceptor/testing-interceptor/node_modules/@nestjs/common/interfaces/features/execution-context.interface").ExecutionContext, next: import("/Users/m/Documents/m/testing-interceptor/testing-interceptor/node_modules/@nestjs/comm...'.
        Types of parameters 'next' and 'next' are incompatible.
          Type 'import("/Users/m/Documents/m/testing-interceptor/testing-interceptor/node_modules/@nestjs/common/interfaces/features/nest-interceptor.interface").CallHandler<any>' is not assignable to type 'import("/Users/m/Documents/m/awe-interceptor/awe-interceptor/node_modules/@nestjs/common/interfaces/features/nest-interceptor.interface").CallHandler<any>'.
            The types of 'handle().operator.call' are incompatible between these types.
              Type '(subscriber: import("/Users/m/Documents/m/testing-interceptor/testing-interceptor/node_modules/rxjs/dist/types/internal/Subscriber").Subscriber<any>, source: any) => import("/Users/m/Documents/m/testing-interceptor/testing-interceptor/node_modules/rxjs/dist/types/internal/ty...' is not assignable to type '(subscriber: import("/Users/m/Documents/m/awe-interceptor/awe-interceptor/node_modules/rxjs/dist/types/internal/Subscriber").Subscriber<any>, source: any) => import("/Users/m/Documents/m/awe-interceptor/awe-interceptor/node_modules/rxjs/dist/types/internal/types").Teardown...'.
                Types of parameters 'subscriber' and 'subscriber' are incompatible.
                  Type 'import("/Users/m/Documents/m/awe-interceptor/awe-interceptor/node_modules/rxjs/dist/types/internal/Subscriber").Subscriber<any>' is not assignable to type 'import("/Users/m/Documents/m/testing-interceptor/testing-interceptor/node_modules/rxjs/dist/types/internal/Subscriber").Subscriber<any>'.
                    Property 'isStopped' is protected but type 'Subscriber<T>' is not a class derived from 'Subscriber<T>'.ts(2345)


问:
WebView on Flutter
When trying to run the below code, we got the error

```<code>import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() {
  runApp(
    const MaterialApp(
    home: WebViewApp(),
   ),
 );
}

class WebViewApp extends StatefulWidget {
  const WebViewApp({super.key});

  @override
  State<WebViewApp> createState() => _WebViewAppState();
 }

class _WebViewAppState extends State<WebViewApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       appBar: AppBar(
       title: const Text('Flutter WebView'),
     ),
      body: const WebView(
      initialUrl: 'https://flutter.dev',
     ),
   );
 }
}
</code>```

In import 'package:webview_flutter/webview_flutter.dart';
we got the error:
Target of URI doesn't exist: 'package:webview_flutter/webview_flutter.dart'.
Try creating the file referenced by the URI, or try using a URI for a file that does exist.

Title: WebView on Flutter

Body:
When trying to run the below code, we got the error

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() {
  runApp(
    const MaterialApp(
    home: WebViewApp(),
   ),
 );
}

class WebViewApp extends StatefulWidget {
  const WebViewApp({super.key});

  @override
  State<WebViewApp> createState() => _WebViewAppState();
 }

class _WebViewAppState extends State<WebViewApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       appBar: AppBar(
       title: const Text('Flutter WebView'),
     ),
      body: const WebView(
      initialUrl: 'https://flutter.dev',
     ),
   );
 }
}

In import 'package:webview_flutter/webview_flutter.dart';
we got the error:
Target of URI doesn't exist: 'package:webview_flutter/webview_flutter.dart'.
Try creating the file referenced by the URI, or try using a URI for a file that does exist.


问:
Are pandas DataFrame methods picklable?
I am developing an algorithm to process a pool of datasets in parallel. I would like to examine wherther the DataFrame methods are pickable.

I wrote the code as the following:

```<code>import pickle
import pandas as pd

# Define a custom function that we will use with the apply method
def my_custom_function(col):
  # Do something with the col of data
  return col+1

# Create a DataFrame
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Check if the apply method is picklable
try:
  pickle.dumps(df[0].apply(my_custom_function))
  print("The apply method is picklable.")
except:
  print("The apply method is not picklable.")

out:
The apply method is picklable.
</code>```

Is this true?

Title: Are pandas DataFrame methods picklable?

Body:
I am developing an algorithm to process a pool of datasets in parallel. I would like to examine wherther the DataFrame methods are pickable.

I wrote the code as the following:

import pickle
import pandas as pd

# Define a custom function that we will use with the apply method
def my_custom_function(col):
  # Do something with the col of data
  return col+1

# Create a DataFrame
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Check if the apply method is picklable
try:
  pickle.dumps(df[0].apply(my_custom_function))
  print("The apply method is picklable.")
except:
  print("The apply method is not picklable.")

out:
The apply method is picklable.

Is this true?


问:
How to save response from Volley post request and use it in Unit Test
1. How can i Unit test the following?I have a post request using volley in code.-What i do?I call in unit test instrumental the function that posts an object with volley in a server and that function need to return the response from server and since i call that function in unit test then in unit test i can save in a variable the respnse and check if it is correct and then all is good.

2. Problem? How can i save the response from server since the request is asynchronous code and it don't let me save response in a variable and then use return (my variable with saved response..)

3. Solutions? What would be a correct easy way to solve my problem? fragment is included in an activity and inside fragment there is the post function, and of couse i have an instrumental test that i call function from the fragment that posts and in that post i return the response which i need fetch in unit test? can i do that or i need fake it in unit test or something.

```<code>>  @Test
> public void test() throws Exception{
>   JSONObject rawSample = new JSONObject(readJsonFile("sample.json"));
>   Gson gson = new Gson();
>   String sample = gson.toJson(rawSample);
>   Context appContext=InstrumentationRegistry.getInstrumentation().getTargetContext();
>   Fragment myfragment = new Fragment();
>   //JSONObject savedResponse = myfragment.myfunction(sample);
>   final Runnable r = new Runnable(){public void run(){
>   JSONObject savedResponse = myfragment.myfunction( sample);
> }
>          };
>     }

> public static String post(Context context,String myJsonString)
>
>
> RequestQueue mQueue = VolleySingleton.getInstance(context).getRequestQueue();
> JSONObject returnJsonObject;
> String returnString="";
>
> try {
> JSONObject json1 = new JSONObject(myJsonString);
>
>             //String postUrl = getString(R.string.base_url) + getString(R.string.post_sessions_url);
> String postUrl = "";
>
>
> JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, postUrl, json1,
> new com.android.volley.Response.Listener<JSONObject>() {
>                         @Override
> public void onResponse(JSONObject response) {
>
>                             //returnJsonObject=response;
> //return str;
>
>                         }
>                     },
> new com.android.volley.Response.ErrorListener() {
>                         @Override
> public void onErrorResponse(VolleyError error) {
> Log.d("POST", "Failure: "+error.networkResponse.statusCode + error.getMessage());
> progressBar.setVisibility(View.GONE);
>                         }
>                     }
>             ) {
>                 @Override
> public Priority getPriority() {
> return Priority.HIGH;
>                 }
>
>                 @Override
> protected Map<String, String> getParams() throws AuthFailureError {
> Map<String, String> params = new HashMap<>();
>
> return params;
>                 }
>
>                 @Override
> public Map<String, String> getHeaders() throws AuthFailureError {
> Map<String, String> headers = new HashMap<>();
> return headers;
>                 }
>             };
> mQueue.add(jsonObjectRequest);
>
>
> catch (JSONException e) {};
>
>     }`
</code>```

Body:
1. How can i Unit test the following?I have a post request using volley in code.-What i do?I call in unit test instrumental the function that posts an object with volley in a server and that function need to return the response from server and since i call that function in unit test then in unit test i can save in a variable the respnse and check if it is correct and then all is good.

2. Problem? How can i save the response from server since the request is asynchronous code and it don't let me save response in a variable and then use return (my variable with saved response..)

3. Solutions? What would be a correct easy way to solve my problem? fragment is included in an activity and inside fragment there is the post function, and of couse i have an instrumental test that i call function from the fragment that posts and in that post i return the response which i need fetch in unit test? can i do that or i need fake it in unit test or something.

>  @Test
> public void test() throws Exception{
>   JSONObject rawSample = new JSONObject(readJsonFile("sample.json"));
>   Gson gson = new Gson();
>   String sample = gson.toJson(rawSample);
>   Context appContext=InstrumentationRegistry.getInstrumentation().getTargetContext();
>   Fragment myfragment = new Fragment();
>   //JSONObject savedResponse = myfragment.myfunction(sample);
>   final Runnable r = new Runnable(){public void run(){
>   JSONObject savedResponse = myfragment.myfunction( sample);
> }
>          };
>     }

> public static String post(Context context,String myJsonString)
>
>
> RequestQueue mQueue = VolleySingleton.getInstance(context).getRequestQueue();
> JSONObject returnJsonObject;
> String returnString="";
>
> try {
> JSONObject json1 = new JSONObject(myJsonString);
>
>             //String postUrl = getString(R.string.base_url) + getString(R.string.post_sessions_url);
> String postUrl = "";
>
>
> JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, postUrl, json1,
> new com.android.volley.Response.Listener<JSONObject>() {
>                         @Override
> public void onResponse(JSONObject response) {
>
>                             //returnJsonObject=response;
> //return str;
>
>                         }
>                     },
> new com.android.volley.Response.ErrorListener() {
>                         @Override
> public void onErrorResponse(VolleyError error) {
> Log.d("POST", "Failure: "+error.networkResponse.statusCode + error.getMessage());
> progressBar.setVisibility(View.GONE);
>                         }
>                     }
>             ) {
>                 @Override
> public Priority getPriority() {
> return Priority.HIGH;
>                 }
>
>                 @Override
> protected Map<String, String> getParams() throws AuthFailureError {
> Map<String, String> params = new HashMap<>();
>
> return params;
>                 }
>
>                 @Override
> public Map<String, String> getHeaders() throws AuthFailureError {
> Map<String, String> headers = new HashMap<>();
> return headers;
>                 }
>             };
> mQueue.add(jsonObjectRequest);
>
>
> catch (JSONException e) {};
>
>     }`