问:
npm "realm-web" - React.js - You may need an appropriate loader to handle this file type
I noticed question with same error. I tried but not working me .
When using  “relam-web” in react.js i have this issue. I am using same code in react native it working fine.

```<code>Module parse failed: Unexpected token (30:28)
You may need an appropriate loader to handle this file type.
|               ProdDb = _context.sent;
|               _context.next = 5;
>               return ProdDb?.mongoClient('mongodb-atlas').db('Demo').collection('Product').aggregate([{
|                 '$limit': 10
|               }]);
</code>```

Home.js

```<code> const [ProductList, setProductList] = useState(ProductListtype);
    const GetData = async () => {
        let ProdDb = await RealmUser()
        let result = await ProdDb?.mongoClient('mongodb-atlas').db('Demo').collection('Product')
            .aggregate([{ '$limit': 10 }]);
        setProductList(result)
    }
    useEffect(() => { GetData() }, [])
    useEffect(() => { }, [ProductList]);
</code>```

RelamApp.tsx

```<code>import * as RealmWeb from "realm-web";
const RealmApp = new Realm.App({ id: process.env.REACT_APP_RELAM_APP ? process.env.REACT_APP_RELAM_APP : "" })
const currentUser = RealmApp.currentUser
console.log("currentUser", currentUser)
const RealmUser = async () => {
    try {
        if (currentUser) return currentUser
        else {
            let credentials = await Realm.Credentials.anonymous();
            return await RealmApp.logIn(credentials);
        }
    } catch (error) {
        console.log(error)
    }

}
export default RealmUser
</code>```

befor useing mongo db i have not webpack.config.js and .babelrc in project.

After facing this issue i create webpack.config.js and .babelrc myself under the path AppName/src/ as below

webpack.config.js

```<code>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: path.resolve(__dirname, 'src/index.js'),
    output: {
        path: path.resolve(__dirname, 'output'),
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {

        loaders: [{
            test: /\.ts$/,
            loaders: ['ts-loader']
        },
        {
            test: /\.css$/,
            loaders: [
                'style-loader',
                'css-loader'
            ]
        }
        ]

        // rules: [{
        //     test: /\.(js|jsx)$/,
        //     exclude: /node_modules/,
        //     use: {
        //         loader: 'babel-loader'
        //     }
        // },
        // {
        //     test: /\.css$/i,
        //     use: ['style-loader', 'css-loader'],
        // }
        // ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./public/index.html",
            filename: "./index.html"
        })
    ]
}
</code>```

.babelrc

```<code>{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
    ]
}
</code>```

package.json

```<code>{
  "name": "shop2",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@babel/preset-env": "^7.20.2",
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@mui/icons-material": "^5.10.14",
    "@mui/material": "^5.10.14",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.5.2",
    "@types/react": "^18.0.25",
    "@types/react-dom": "^18.0.9",
    "babel-preset-es2015": "^6.24.1",
    "firebase": "^9.14.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-phone-input-2": "^2.15.1",
    "react-router-dom": "^6.4.3",
    "react-scripts": "^2.1.3",
    "realm-web": "^2.0.0",
    "typescript": "^4.9.3",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build webpack-dev-server --mode development --open",
    "test": "react-scripts test webpack-dev-server --mode development --open",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ]
  },
  "devDependencies": {
    "@types/node": "^18.11.15"
  }
}
</code>```

Body:
I noticed question with same error. I tried but not working me .
When using  “relam-web” in react.js i have this issue. I am using same code in react native it working fine.

Module parse failed: Unexpected token (30:28)
You may need an appropriate loader to handle this file type.
|               ProdDb = _context.sent;
|               _context.next = 5;
>               return ProdDb?.mongoClient('mongodb-atlas').db('Demo').collection('Product').aggregate([{
|                 '$limit': 10
|               }]);

Home.js

 const [ProductList, setProductList] = useState(ProductListtype);
    const GetData = async () => {
        let ProdDb = await RealmUser()
        let result = await ProdDb?.mongoClient('mongodb-atlas').db('Demo').collection('Product')
            .aggregate([{ '$limit': 10 }]);
        setProductList(result)
    }
    useEffect(() => { GetData() }, [])
    useEffect(() => { }, [ProductList]);

RelamApp.tsx

import * as RealmWeb from "realm-web";
const RealmApp = new Realm.App({ id: process.env.REACT_APP_RELAM_APP ? process.env.REACT_APP_RELAM_APP : "" })
const currentUser = RealmApp.currentUser
console.log("currentUser", currentUser)
const RealmUser = async () => {
    try {
        if (currentUser) return currentUser
        else {
            let credentials = await Realm.Credentials.anonymous();
            return await RealmApp.logIn(credentials);
        }
    } catch (error) {
        console.log(error)
    }

}
export default RealmUser

befor useing mongo db i have not webpack.config.js and .babelrc in project.

After facing this issue i create webpack.config.js and .babelrc myself under the path AppName/src/ as below

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: path.resolve(__dirname, 'src/index.js'),
    output: {
        path: path.resolve(__dirname, 'output'),
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {

        loaders: [{
            test: /\.ts$/,
            loaders: ['ts-loader']
        },
        {
            test: /\.css$/,
            loaders: [
                'style-loader',
                'css-loader'
            ]
        }
        ]

        // rules: [{
        //     test: /\.(js|jsx)$/,
        //     exclude: /node_modules/,
        //     use: {
        //         loader: 'babel-loader'
        //     }
        // },
        // {
        //     test: /\.css$/i,
        //     use: ['style-loader', 'css-loader'],
        // }
        // ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./public/index.html",
            filename: "./index.html"
        })
    ]
}

.babelrc

{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
    ]
}

package.json

{
  "name": "shop2",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@babel/preset-env": "^7.20.2",
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@mui/icons-material": "^5.10.14",
    "@mui/material": "^5.10.14",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.5.2",
    "@types/react": "^18.0.25",
    "@types/react-dom": "^18.0.9",
    "babel-preset-es2015": "^6.24.1",
    "firebase": "^9.14.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-phone-input-2": "^2.15.1",
    "react-router-dom": "^6.4.3",
    "react-scripts": "^2.1.3",
    "realm-web": "^2.0.0",
    "typescript": "^4.9.3",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build webpack-dev-server --mode development --open",
    "test": "react-scripts test webpack-dev-server --mode development --open",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ]
  },
  "devDependencies": {
    "@types/node": "^18.11.15"
  }
}


来源: stackexchange

问:
How do I stub default void method of Mapstruct interface for Unit testing a class that is calling that default method?
I am unit testing a class in Java 8 that is calling a default method of a mapstruct interface and that method returns void. I am not able to stub the method call using Mockito.doNothing()...When(object).method(). The execution enters the actual method (in mapstruct interface) Pls provide your inputs to solve this problem.</p>

ContentLicense: CC BY-SA 4.0


问:
Grafana button in custom plugin not working
I am new into Grafana. I created a custom plugin on which I have a Button. The project compiles without issues, and the button appears on the panel, but no click event is handled

Please find below the source code

```<code>import React from ‘react’;
import { PanelProps } from ‘@grafana/data’;
import { SimpleOptions } from ‘types’;
import { css, cx } from ‘@emotion/css’;
import { Button, useStyles2, useTheme2 } from ‘@grafana/ui’;

interface Props extends PanelProps {}

const getStyles = () => {
return {
wrapper: css font-family: Open Sans; position: relative; ,
svg: css position: absolute; top: 0; left: 0; ,
textBox: css position: absolute; bottom: 0; left: 0; padding: 10px; ,
hover:css background-color: rgba(255, 0, 0, 1); ,
active:css background-color: rgba(255, 255, 0, 1); ,
};
};

export const SimplePanel: React.FC = ({ options, data, width, height }) => {
const theme = useTheme2();

const styles = useStyles2(getStyles);
return (
<div
className={cx(
styles.wrapper,
css width: ${width}px; height: ${height}px;
)}
>
<svg
className={styles.svg}
width={width}
height={height}
xmlns=“SVG namespace”
xmlnsXlink=“XLink namespace”
viewBox={-${width / 2} -${height / 2} ${width} ${height}}
>

<circle style={{ fill: theme.colors.primary.main }} r={100} />

  <div className={styles.textBox}>
    {options.showSeriesCount && <div>Number of series: {data.series.length}</div>}
    <div>Text option value: {options.text}</div>
  </div>
  <Button  onClick={()=>console.log("test")}>TestButton</Button>
</div>
);
};
</code>```

I also changed in the defaults.ini the disable_sanitize_html = true but the problem didn’t get solved.

Please can you advice what to do next.

I set the disable_sanitize_html=true but didn't work.

Body:
I am new into Grafana. I created a custom plugin on which I have a Button. The project compiles without issues, and the button appears on the panel, but no click event is handled

Please find below the source code

import React from ‘react’;
import { PanelProps } from ‘@grafana/data’;
import { SimpleOptions } from ‘types’;
import { css, cx } from ‘@emotion/css’;
import { Button, useStyles2, useTheme2 } from ‘@grafana/ui’;

interface Props extends PanelProps {}

const getStyles = () => {
return {
wrapper: css font-family: Open Sans; position: relative; ,
svg: css position: absolute; top: 0; left: 0; ,
textBox: css position: absolute; bottom: 0; left: 0; padding: 10px; ,
hover:css background-color: rgba(255, 0, 0, 1); ,
active:css background-color: rgba(255, 255, 0, 1); ,
};
};

export const SimplePanel: React.FC = ({ options, data, width, height }) => {
const theme = useTheme2();

const styles = useStyles2(getStyles);
return (

<svg
className={styles.svg}
width={width}
height={height}
xmlns=“SVG namespace”
xmlnsXlink=“XLink namespace”
viewBox={-${width / 2} -${height / 2} ${width} ${height}}
>

<circle style={{ fill: theme.colors.primary.main }} r={100} />

    {options.showSeriesCount &&
Number of series: {data.series.length}
}

Text option value: {options.text}

  <Button  onClick={()=>console.log("test")}>TestButton</Button>

);
};

I also changed in the defaults.ini the disable_sanitize_html = true but the problem didn’t get solved.

Please can you advice what to do next.

I set the disable_sanitize_html=true but didn't work.


问:
In React Native and React Navigation, is there a way to determine what the left and right margins are to align screen content with those buttons?
In my current React Native project, I have my horizontal base padding set to 15. But depending on the device screen size being used this is usually not aligned with the margin the back button has.

Is there a way to tap into what that margin is so I can dynamically set my horizontal padding to always align with the button?


问:
Redirecting with user data
I am trying to figure out how I send user data back after authentication. Typically when you want information back you just make and api call on the front end and send it back, however for authentication I am using oath and instead of an api call its a link.

Front end

```<code>function App() {
  return (
    <>
      <div className="App">welcome to paragon over prime builds.</div>
      <br></br>
      <a href="http://localhost:3001/auth/google">Sign in</a>
    </>
  );
}
</code>```

Back End

```<code>app.get(
  "/auth/google",
  passport.authenticate("google", { scope: ["email", "profile"] })
);

app.get(
  "/auth/google/oauth2callback",
  passport.authenticate("google", {
    successRedirect: "/auth/google/success",
    failureRedirect: "/auth/google/failure",
    failureMessage: true,
  })
);

// respond here
// redirect???
app.get("/auth/google/failure", (req, res) => {
  // res.status(400).send({ error: "something went wrong" });
});

// respond here
// redirect???
app.get("/auth/google/success", isLoggedIn, (req, res) => {
  // res.status(200).send(req.user.username);
});
</code>```

What am I supposed to do for the redirects?
Something like use res.redirect("front end url").send(req,user) ???

Title: Redirecting with user data

Body:
I am trying to figure out how I send user data back after authentication. Typically when you want information back you just make and api call on the front end and send it back, however for authentication I am using oath and instead of an api call its a link.

Front end

function App() {
  return (
    <>

welcome to paragon over prime builds.

      Sign in
    </>
  );
}

Back End

app.get(
  "/auth/google",
  passport.authenticate("google", { scope: ["email", "profile"] })
);

app.get(
  "/auth/google/oauth2callback",
  passport.authenticate("google", {
    successRedirect: "/auth/google/success",
    failureRedirect: "/auth/google/failure",
    failureMessage: true,
  })
);

// respond here
// redirect???
app.get("/auth/google/failure", (req, res) => {
  // res.status(400).send({ error: "something went wrong" });
});

// respond here
// redirect???
app.get("/auth/google/success", isLoggedIn, (req, res) => {
  // res.status(200).send(req.user.username);
});

What am I supposed to do for the redirects?
Something like use res.redirect("front end url").send(req,user) ???


问:
Bluetooth remote music control (VLC from Phone to Car Android System) [A2DP/AVRCP?]
TLDR: Stream music from one Android to another Android device via bluetooth, remote controlling VLC or foobar2k or another app on source Android, displaying play/pause/nex/prev button and track name, which app (besides that one that came with my car Android radio)?

I got an old NoName China Android Car Radio (Android7 from 2017). This device comes with an app just called A2DP (and just called "Bluetooth' v2.4.0) in the App list), that magically is able to control VLC music from my Android smartphone. It's just got a Play/Pause, Next and Prev button, and is also showing the current track name from VLC.

I recently wrote myself a car dashboard app that displays the current track (via NotificationListenerService) which works with LOCAL VLC on my car Android, however not with this A2DP called China app open.

From what I think i found out is, that this app is probably not announcing/broadcasting the track name to the local car Android

(see e.g. send track informations via A2DP/AVRCP)

So to test out my theory I just wanted to try out ANOTHER app that does the same thing... and guess what... i searched the App Store, F-Droid and more, with search terms containing "bluettoh" "media controller" "avrcp/a2dp" "bluetooth music player" etc.etc... I COULDN'T FIND A SINGLE APP THAT DOES WHAT THIS CHINA APP DOES :)

So I'm questioning now if i'm missing something here... hope someone can point me in the right direction ;)

Thanks

Installed almost every app on Play Store that hast to do with bluetooth, nothing works. Even random .apk files....


问:
State machine freezes when switching
I have an unpleasant situation: I start the state machine and answer a sequence of questions, but suppose I didn’t want to answer to the end and called another command from the bot’s arsenal. The bot reacts like this: it continues to send questions from FSM, and a little later it freezes. Only reboot helps.

Here is the code:

```<code></code>```
```<code>class Protest(StatesGroup):
    full_name = State()
    team_name = State()
    enemy = State()
    date = State()
    time = State()
    cause = State()

@dp.message_handler(commands=["protest"], state=None)
async def start_protest(message: types.Message):
    await Protest.full_name.set()
    await message.answer("Введите Ваше ФИО:")

@dp.message_handler(state=Protest.full_name)
async def name_protest(message: types.Message, state=FSMContext):
    async with state.proxy() as data:
        data["full_name"] = message.text
    await Protest.next()
    await message.answer("Введите название Вашей команды:")

@dp.message_handler(state=Protest.team_name)
async def teem_name_protest(message: types.Message, state=FSMContext):
    await Protest.next()
    async with state.proxy() as data:
        data["teem_name"] = message.text
    await message.answer("Введите название команды соперника")

@dp.message_handler(state=Protest.enemy)
async def enemy_teem(message: types.Message, state=FSMContext):
    await Protest.next()
    async with state.proxy() as data:
        data["enemy"] = message.text
    calendar, step = DetailedTelegramCalendar(min_date=date.today(), locale="ru").build()
    await bot.send_message(message.chat.id,
                           f"Выберите дату проведения матча:",
                           reply_markup=calendar)

@dp.callback_query_handler(DetailedTelegramCalendar.func(), state=Protest.date)
async def inline_kb_answer_callback_handler(query, state=FSMContext):
    result, key, step = DetailedTelegramCalendar(locale="ru").process(query.data)

    if not result and key:
        await bot.edit_message_text(f"Выберите дату проведения матча",
                                    query.message.chat.id,
                                    query.message.message_id,
                                    reply_markup=key)
    elif result:
        await bot.edit_message_text(f"Вы выбрали: {result}. Напишите время проведения матча",
                                    query.message.chat.id,
                                    query.message.message_id)

        await Protest.next()
        async with state.proxy() as data:
            data["date"] = result

@dp.message_handler(state=Protest.time)
async def time_match(message: types.Message, state=FSMContext):
    async with state.proxy() as data:
        data["time"] = message.text
    await Protest.next()
    await message.answer("Назовите причину Вашего протеста")

@dp.message_handler(state=Protest.cause)
async def cause_protest(message: types.Message, state=FSMContext):
    async with state.proxy() as data:
        data["cause"] = message.text
    await protest_db.sql_add_command(state)
    await state.finish()
    await message.answer("Ваш протест будет рассмотрен")
</code>```
```<code></code>```

I have two versions:

Need to use try except

You need to install the bot on the server

I could send you my bot, but it is made in Russian, I'm afraid that it will be inconvenient for you to use it

Title: State machine freezes when switching

Body:
I have an unpleasant situation: I start the state machine and answer a sequence of questions, but suppose I didn’t want to answer to the end and called another command from the bot’s arsenal. The bot reacts like this: it continues to send questions from FSM, and a little later it freezes. Only reboot helps.

Here is the code:

class Protest(StatesGroup):
    full_name = State()
    team_name = State()
    enemy = State()
    date = State()
    time = State()
    cause = State()

@dp.message_handler(commands=["protest"], state=None)
async def start_protest(message: types.Message):
    await Protest.full_name.set()
    await message.answer("Введите Ваше ФИО:")

@dp.message_handler(state=Protest.full_name)
async def name_protest(message: types.Message, state=FSMContext):
    async with state.proxy() as data:
        data["full_name"] = message.text
    await Protest.next()
    await message.answer("Введите название Вашей команды:")

@dp.message_handler(state=Protest.team_name)
async def teem_name_protest(message: types.Message, state=FSMContext):
    await Protest.next()
    async with state.proxy() as data:
        data["teem_name"] = message.text
    await message.answer("Введите название команды соперника")

@dp.message_handler(state=Protest.enemy)
async def enemy_teem(message: types.Message, state=FSMContext):
    await Protest.next()
    async with state.proxy() as data:
        data["enemy"] = message.text
    calendar, step = DetailedTelegramCalendar(min_date=date.today(), locale="ru").build()
    await bot.send_message(message.chat.id,
                           f"Выберите дату проведения матча:",
                           reply_markup=calendar)

@dp.callback_query_handler(DetailedTelegramCalendar.func(), state=Protest.date)
async def inline_kb_answer_callback_handler(query, state=FSMContext):
    result, key, step = DetailedTelegramCalendar(locale="ru").process(query.data)

    if not result and key:
        await bot.edit_message_text(f"Выберите дату проведения матча",
                                    query.message.chat.id,
                                    query.message.message_id,
                                    reply_markup=key)
    elif result:
        await bot.edit_message_text(f"Вы выбрали: {result}. Напишите время проведения матча",
                                    query.message.chat.id,
                                    query.message.message_id)

        await Protest.next()
        async with state.proxy() as data:
            data["date"] = result

@dp.message_handler(state=Protest.time)
async def time_match(message: types.Message, state=FSMContext):
    async with state.proxy() as data:
        data["time"] = message.text
    await Protest.next()
    await message.answer("Назовите причину Вашего протеста")

@dp.message_handler(state=Protest.cause)
async def cause_protest(message: types.Message, state=FSMContext):
    async with state.proxy() as data:
        data["cause"] = message.text
    await protest_db.sql_add_command(state)
    await state.finish()
    await message.answer("Ваш протест будет рассмотрен")

I have two versions:

Need to use try except

You need to install the bot on the server

I could send you my bot, but it is made in Russian, I'm afraid that it will be inconvenient for you to use it


问:
Sort CPT by taxonomy AND THEN by custom field
I am trying to sort a CPT first by Taxonomy (tag) ASC and then by custom field (last_updated_hc) DESC which is a date-picker field. Using posts_orderby I can sort by taxonomy but I am running into issues with sorting by the custon field. Here is the code that does work thus far.

```<code>add_filter( 'posts_orderby', 'hc_sort', 99, 2 );
function hc_sort( $orderby, $query ) {
  if ( ! hc_is_topic_tax_query( $query ) ) return;
  global $wpdb;
  return "{$wpdb->term_relationships}.term_order ASC";
}
function hc_is_topic_tax_query( $query ) {
  if ( empty( $query->tax_query ) ) return;
  if ( empty( $query->tax_query->queries ) ) return;
  return in_array(
    $query->tax_query->queries[0]['taxonomy'],
    [ 'high_court_tag' ],
    true
  );
}
</code>```

I have tried some variations from this post on SE but to no avail.

Body:
I am trying to sort a CPT first by Taxonomy (tag) ASC and then by custom field (last_updated_hc) DESC which is a date-picker field. Using posts_orderby I can sort by taxonomy but I am running into issues with sorting by the custon field. Here is the code that does work thus far.

add_filter( 'posts_orderby', 'hc_sort', 99, 2 );
function hc_sort( $orderby, $query ) {
  if ( ! hc_is_topic_tax_query( $query ) ) return;
  global $wpdb;
  return "{$wpdb->term_relationships}.term_order ASC";
}
function hc_is_topic_tax_query( $query ) {
  if ( empty( $query->tax_query ) ) return;
  if ( empty( $query->tax_query->queries ) ) return;
  return in_array(
    $query->tax_query->queries[0]['taxonomy'],
    [ 'high_court_tag' ],
    true
  );
}

I have tried some variations from this post on SE but to no avail.


问:
detect socket timeout when using "with" instead of "try"
Using python 3.6.8, I have the following code

```<code>with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.settimeout(20)
    s.connect(host, port)
</code>```

As I understand it, using with as shown instead of a try except block better handles the error condition that occurs if opening the socket (s.connect()) fails. How so? In the code as shown, if s.connect() times out, will it print a message? My main question is, can I detect that it timed out, e.g. to run some code if a timeout occurs? I want to be able to do that from within the with block without using try. I read this example

```<code>with opened_w_error("/etc/passwd", "a") as (f, err):
    if err:
        print "IOError:", err
    else:
        f.write("guido::0:0::/:/bin/sh\n")
</code>```

But that doesn't detect the type of error. I read this as well

```<code>try:
    with ContextManager():
        BLOCK
except InitError:  # raised from __init__
    ...
except AcquireResourceError:  # raised from __enter__
    ...
except ValueError:  # raised from BLOCK
    ...
except ReleaseResourceError:  # raised from __exit__
</code>```

But I'm hoping there is a way to detect if it's a timeout error from within the with block.

Body:
Using python 3.6.8, I have the following code

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.settimeout(20)
    s.connect(host, port)

As I understand it, using with as shown instead of a try except block better handles the error condition that occurs if opening the socket (s.connect()) fails. How so? In the code as shown, if s.connect() times out, will it print a message? My main question is, can I detect that it timed out, e.g. to run some code if a timeout occurs? I want to be able to do that from within the with block without using try. I read this example

with opened_w_error("/etc/passwd", "a") as (f, err):
    if err:
        print "IOError:", err
    else:
        f.write("guido::0:0::/:/bin/sh\n")

But that doesn't detect the type of error. I read this as well

try:
    with ContextManager():
        BLOCK
except InitError:  # raised from __init__
    ...
except AcquireResourceError:  # raised from __enter__
    ...
except ValueError:  # raised from BLOCK
    ...
except ReleaseResourceError:  # raised from __exit__

But I'm hoping there is a way to detect if it's a timeout error from within the with block.


问:
Extract info from zepp in python
I need to take information from the "Zepp" app for use in another project.
If possible in python but it's ok if there is another language in use.
The Zepp app is a fitness app for android connected with a smart watch.

Thank you in advance.

Title: Extract info from zepp in python


问:
How to customize image toolbar in ckeditor and enable Upload outside admin panel?
The first problem:
If click on the image toolbar, the wizard appears with additional settings. Can I modify it to upload the image in one click without entering additional information and sending the image to the server?

Correct example https://ckeditor.com/docs/ckeditor5/latest/features/images/images-overview.html#inserting-images-via-source-url

The second problem:
Outside the admin panel, there is no upload tab on the image toolbar. How to fix it?
Thanks for your time.


问:
cannot use -fallow-argument-mismatch as #cgo FFLAGS:
I am in the process of updating to a new version of gfortran (9.4 to 11.3) for a go application that uses cgo to execute fortran code.  I am getting a rank mismatch error:

somdec.f90:507:36:

  111 |           call respir(co2los,2,SRFC,som1c,som1ci,s11c2,resp, &
      |                                    2
......
  507 |           call respir(co2los,1,SRFC,som3c,som3ci,s3c2,resp, &
      |                                    1
Error: Rank mismatch between actual argument at (1) and actual argument at (2) (rank-1 and scalar)
```
<p>This is a common occurrence as fortran developers used to have optional args and now don't, fixing this error/feature deletion will be a pain as this spans across a vast number of functions.  Places online tell me to use <code>-fallow-argument-mismatch</code> flag as an -fflag in gfortran, however go does not support the use of this flag</p>
<p>my cgo config:</p>
<pre class="lang-golang prettyprint-override"><code>package main

// #cgo LDFLAGS: -lm
// #cgo CFLAGS: -Wstringop-overflow=0
// #cgo FFLAGS: -fallow-argument-mismatch
import "C"

etc...
</code>```

and I get the error:

go build myapp: invalid flag in #cgo FFLAGS: -fallow-argument-mismatch
```
<p>Unless there is a good way to fix/mitigate the black box that fortran is, my only option is to use this seemingly deprecated fortran flag, does cgo explicitly disable this flag?</p>
<p>I've also tried setting these as environment variables, but to no avail</p>
<pre class="lang-bash prettyprint-override"><code>export FFLAGS=-fallow-argument-mismatch
export FCFLAGS=-fallow-argument-mismatch
</code>```

It's frustrating that this is a common thing that happens to fortran developers with a deprecated flag being the only option and with little/unclear documentation on fixing this error.

Body:
I am in the process of updating to a new version of gfortran (9.4 to 11.3) for a go application that uses cgo to execute fortran code.  I am getting a rank mismatch error:

somdec.f90:507:36:

  111 |           call respir(co2los,2,SRFC,som1c,som1ci,s11c2,resp, &
      |                                    2
......
  507 |           call respir(co2los,1,SRFC,som3c,som3ci,s3c2,resp, &
      |                                    1
Error: Rank mismatch between actual argument at (1) and actual argument at (2) (rank-1 and scalar)

This is a common occurrence as fortran developers used to have optional args and now don't, fixing this error/feature deletion will be a pain as this spans across a vast number of functions.  Places online tell me to use -fallow-argument-mismatch flag as an -fflag in gfortran, however go does not support the use of this flag

my cgo config:

package main

// #cgo LDFLAGS: -lm
// #cgo CFLAGS: -Wstringop-overflow=0
// #cgo FFLAGS: -fallow-argument-mismatch
import "C"

etc...

and I get the error:

go build myapp: invalid flag in #cgo FFLAGS: -fallow-argument-mismatch

Unless there is a good way to fix/mitigate the black box that fortran is, my only option is to use this seemingly deprecated fortran flag, does cgo explicitly disable this flag?

I've also tried setting these as environment variables, but to no avail

export FFLAGS=-fallow-argument-mismatch
export FCFLAGS=-fallow-argument-mismatch

It's frustrating that this is a common thing that happens to fortran developers with a deprecated flag being the only option and with little/unclear documentation on fixing this error.


问:
I have an error when I try to use a session from my login file in another file
Notice: A session had already been started - ignoring session_start() in /home/user/public_html/finalweb/header.php on line 3

the session was started in my login file as seen below

```<code><?php
ini_set("session.save_path", "/home/unn_w22016721/sessionData");
session_start();

</code>```

the session variable was created in the same login file after login checks were complete as seen below

```<code>if (!array_filter($errors)) {

        $Username = mysqli_real_escape_string($conn, $_POST['username']);
        $pwd = mysqli_real_escape_string($conn, $_POST['Password']);
        $_SESSION['logged-in'] = true;
        if ($_SESSION['logged-in']) {
            # code...
            $_SESSION['username'] = $Username;
            // echo "session has been set";
            // echo $_SESSION['username'];
            header("location: index.php");

        }

    }
</code>```

the session variable is called in the header/navbar file as seen below

```<code><?php
ini_set("session.save_path", "/home/unn_w22016721/sessionData");
    session_start();

?>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
<!-- css -->
    <link rel="stylesheet" type="text/css" href="style.css">
    <!-- Google fonts -->

    <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,500;0,600;1,500&display=swap" rel="stylesheet">
      <!-- font awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer">

    </head>
<body>

    <header>

        <nav class="nav-bar">
            <div class="logo">
                <h1 ><a class="Company" href="index.html">East Experience</a></h1>
                <!-- closing tag for Company -->
            </div>

                <ul class="nav-items">
                    <li><a href="index.php">Home</a></li>
                    <li><a href="about.php">About</a></li>
                    <li><a href="Design-Notes.pdf" target="_blank">Wireframes</a></li>
                    <li><a href="CREDITS.pdf">Credits</a></li>
                    <li><a href="destinations.php">Destination</a></li>
                    <?php

                        if (isset($_SESSION['logged-in])) {
                            # code...
                            echo "<li><a href='book.php'>Book</a></li>";
                            echo " <li><a href='logout.php'>Log out</a></li>";
                        } else{
                            echo "<li><a href='signup.php'>Sign up</a></li>";
                            echo " <li><a href='login.php'>Log in</a></li>";
                        }

                    ?>
                    <!-- <li><a href='signup.php'>Signup</a></li>
                    <li><a href="login.php">login</a></li> -->
                    <!-- <li><a href="details.html"><Details></Details></a></li> -->

                </ul>

        <!-- closing tag for nav section -->
        </nav>
            </header>

</code>```

I tried to remove the session_start() in the header file but then my dynamic changes were'nt taking effect. i'm not sure how to fix this error because i know the session has to be called in any page i'm going to use it. Please i'll appreciate any suggestions as i'm very new to php, thanks!

Body:
Notice: A session had already been started - ignoring session_start() in /home/user/public_html/finalweb/header.php on line 3

the session was started in my login file as seen below

<?php
ini_set("session.save_path", "/home/unn_w22016721/sessionData");
session_start();

the session variable was created in the same login file after login checks were complete as seen below

if (!array_filter($errors)) {

        $Username = mysqli_real_escape_string($conn, $_POST['username']);
        $pwd = mysqli_real_escape_string($conn, $_POST['Password']);
        $_SESSION['logged-in'] = true;
        if ($_SESSION['logged-in']) {
            # code...
            $_SESSION['username'] = $Username;
            // echo "session has been set";
            // echo $_SESSION['username'];
            header("location: index.php");

        }

    }

the session variable is called in the header/navbar file as seen below

<?php
ini_set("session.save_path", "/home/unn_w22016721/sessionData");
    session_start();

?>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>

    <link rel="stylesheet" type="text/css" href="style.css">

    <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,500;0,600;1,500&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer">

East Experience

Home

About

Wireframes

Credits

Destination

                    <?php

                        if (isset($_SESSION['logged-in])) {
                            # code...
                            echo "
Book
";
                            echo "
Log out
";
                        } else{
                            echo "
Sign up
";
                            echo "
Log in
";
                        }

                    ?>

I tried to remove the session_start() in the header file but then my dynamic changes were'nt taking effect. i'm not sure how to fix this error because i know the session has to be called in any page i'm going to use it. Please i'll appreciate any suggestions as i'm very new to php, thanks!


问:
How to fix Vulnerable WebRTC version error by third party libraries?
My Application in play developer console is showing error "Vulnerable WebRTC Versions, Your app uses a bad version of WebRTC, which contains security vulnerabilities."

I am using twilio video SDK, however it seems to be the latest version. Still cant figure out which library is using webrtc.

```<code>implementation platform('com.google.firebase:firebase-bom:31.1.1')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-messaging'
implementation 'com.google.firebase:firebase-crashlytics'

implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.dagger:dagger-android-support:2.38'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.jakewharton:butterknife:10.2.3'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.google.code.gson:gson:2.8.9'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

debugImplementation "com.github.chuckerteam.chucker:library:3.5.2"
releaseImplementation "com.github.chuckerteam.chucker:library-no-op:3.5.2"
implementation 'com.squareup.picasso:picasso:2.71828'
implementation "androidx.lifecycle:lifecycle-runtime:2.5.1"
implementation "androidx.lifecycle:lifecycle-common-java8:2.5.1"
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test:core:1.5.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.4'
androidTestImplementation 'androidx.test:runner:1.5.1'
androidTestImplementation "androidx.test:rules:1.5.0"
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.38'
annotationProcessor 'com.google.dagger:dagger-compiler:2.38'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation "com.google.android.material:material:1.8.0-beta01"

//nav components
implementation 'androidx.navigation:navigation-fragment:2.5.3'

implementation 'androidx.navigation:navigation-ui:2.5.3'

implementation 'com.github.aabhasr1:OtpView:v1.1.2'
implementation 'com.pusher:pusher-java-client:2.2.6'

implementation 'androidx.room:room-runtime:2.4.3'
annotationProcessor 'androidx.room:room-compiler:2.4.3'
implementation 'com.squareup:otto:1.3.8'

implementation 'com.twilio:video-android:7.5.1'
implementation "com.twilio:audioswitch:1.1.2"

implementation 'androidx.core:core-splashscreen:1.0.0'
implementation "androidx.coordinatorlayout:coordinatorlayout:1.2.0"

//progress bar
implementation 'com.github.uzairiqbal91:CircularTimerView:1.0'
implementation "androidx.work:work-runtime:2.7.1"

//country code picker
implementation 'com.hbb20:ccp:2.6.0'

implementation 'com.android.support:multidex:1.0.3'
implementation 'io.github.informramiz:nameinitialscircleimageview:1.6'
implementation 'com.github.Drjacky:ImagePicker:2.1.16'

//App update
implementation 'com.google.android.play:app-update:2.0.1'

//Live
implementation 'com.github.florent37:singledateandtimepicker:2.2.7'

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
</code>```

Is there a way to find which of these libraries use webrtc and what versions?

Body:
My Application in play developer console is showing error "Vulnerable WebRTC Versions, Your app uses a bad version of WebRTC, which contains security vulnerabilities."

I am using twilio video SDK, however it seems to be the latest version. Still cant figure out which library is using webrtc.

implementation platform('com.google.firebase:firebase-bom:31.1.1')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-messaging'
implementation 'com.google.firebase:firebase-crashlytics'

implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.dagger:dagger-android-support:2.38'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.jakewharton:butterknife:10.2.3'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.google.code.gson:gson:2.8.9'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

debugImplementation "com.github.chuckerteam.chucker:library:3.5.2"
releaseImplementation "com.github.chuckerteam.chucker:library-no-op:3.5.2"
implementation 'com.squareup.picasso:picasso:2.71828'
implementation "androidx.lifecycle:lifecycle-runtime:2.5.1"
implementation "androidx.lifecycle:lifecycle-common-java8:2.5.1"
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test:core:1.5.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.4'
androidTestImplementation 'androidx.test:runner:1.5.1'
androidTestImplementation "androidx.test:rules:1.5.0"
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.38'
annotationProcessor 'com.google.dagger:dagger-compiler:2.38'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation "com.google.android.material:material:1.8.0-beta01"

//nav components
implementation 'androidx.navigation:navigation-fragment:2.5.3'

implementation 'androidx.navigation:navigation-ui:2.5.3'

implementation 'com.github.aabhasr1:OtpView:v1.1.2'
implementation 'com.pusher:pusher-java-client:2.2.6'

implementation 'androidx.room:room-runtime:2.4.3'
annotationProcessor 'androidx.room:room-compiler:2.4.3'
implementation 'com.squareup:otto:1.3.8'

implementation 'com.twilio:video-android:7.5.1'
implementation "com.twilio:audioswitch:1.1.2"

implementation 'androidx.core:core-splashscreen:1.0.0'
implementation "androidx.coordinatorlayout:coordinatorlayout:1.2.0"

//progress bar
implementation 'com.github.uzairiqbal91:CircularTimerView:1.0'
implementation "androidx.work:work-runtime:2.7.1"

//country code picker
implementation 'com.hbb20:ccp:2.6.0'

implementation 'com.android.support:multidex:1.0.3'
implementation 'io.github.informramiz:nameinitialscircleimageview:1.6'
implementation 'com.github.Drjacky:ImagePicker:2.1.16'

//App update
implementation 'com.google.android.play:app-update:2.0.1'

//Live
implementation 'com.github.florent37:singledateandtimepicker:2.2.7'

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'

Is there a way to find which of these libraries use webrtc and what versions?


问:
How can I parse/read, not play, an audio file in Swift based on its formatting?
My app already finds silence in audio as it is being recorded on an iOS device. I compare background and speaking volumes from samples then compare it and so far it has been pretty accurate. This way I save the audio into smaller multiple files, yet without cutting words.

Now I would like to do the same with prerecorded audio files (m4a).

Open an m4a audio file on my iOS device

Read 0.5 seconds of an audio file based on it's format, channels, etc,

Use my detect silence function to determine whether to read more or less data

While I have no problem opening the files and getting their format (below), I am unsure as to how to calculate how much of the data to read in to get a sample. If I determine just silence, read more data in. If I determine there's a spoken word, read less data so as not to clip the word.

I have tried googling to get info as to how to interpret the format of the file (sampling rate, channels, etc. )to figure out how much to read, but have not been able to find any.

```<code>   //left out error checking in this sample
   let input = try? AVAudioFile(forReading: url) else {
       return nil
    }

   let buffer = AVAudioPCMBuffer(pcmFormat: input.processingFormat, frameCapacity: AVAudioFrameCount(input.length)) else {
       return nil
    }

    do {
       // reads entire audio file
       try input.read(into: buffer)
    } catch {
       return nil
    }
</code>```

Body:
My app already finds silence in audio as it is being recorded on an iOS device. I compare background and speaking volumes from samples then compare it and so far it has been pretty accurate. This way I save the audio into smaller multiple files, yet without cutting words.

Now I would like to do the same with prerecorded audio files (m4a).

Open an m4a audio file on my iOS device

Read 0.5 seconds of an audio file based on it's format, channels, etc,

Use my detect silence function to determine whether to read more or less data

While I have no problem opening the files and getting their format (below), I am unsure as to how to calculate how much of the data to read in to get a sample. If I determine just silence, read more data in. If I determine there's a spoken word, read less data so as not to clip the word.

I have tried googling to get info as to how to interpret the format of the file (sampling rate, channels, etc. )to figure out how much to read, but have not been able to find any.

   //left out error checking in this sample
   let input = try? AVAudioFile(forReading: url) else {
       return nil
    }

   let buffer = AVAudioPCMBuffer(pcmFormat: input.processingFormat, frameCapacity: AVAudioFrameCount(input.length)) else {
       return nil
    }

    do {
       // reads entire audio file
       try input.read(into: buffer)
    } catch {
       return nil
    }


问:
AWS Api Gateway VTL Merge Json Object
Trying to merge the principalId from Lambda Authorizer into the payload that will be sent to Event Bridge.

So far I've gotten close by transforming to map and re-creating the Json object. The problem is that this Json object is printed out as a key:value pair with no quotes, So there's an error thrown.

According to the docs, there's non $util.toJson($map) available, this seems to be only available for AppSync.

```<code>    const eventsAPI = new RestApi(this, 'eventsAPI', apigwOps);

    const LambdaAuth0Authorizer = new LambdaAuth0Authorizer(this, 'LambdaAuth0Authorizer', {
      env: {
        auth0Audience: '',
        auth0Domain: '',
      },
    });

    const eventTypeResource = eventsAPI.root.addResource('event');
    const options: IntegrationOptions = {
      credentialsRole: apigwRole,
      passthroughBehavior: PassthroughBehavior.NEVER,
      requestParameters: {
        'integration.request.header.X-Amz-Target': "'AWSEvents.PutEvents'",
        'integration.request.header.Content-Type': "'application/x-amz-json-1.1'",
      },

      requestTemplates: {
        'application/json': `
        #set ( $map = $util.parseJson($input.body) )
        #set ( $j = {
          "eventType": "$map['eventType']",
          "action": "$map['action']",
          "subject": "$map['subject']",
          "eventTime": $map['eventTime'],
          "actor": "$context.authorizer.principalId"
         }
        )
                    {"Entries":
                          [
                            {
                              "Source": "com.xyz",
                              "Detail": "$util.escapeJavascript($j)",
                              "Resources": [],
                              "DetailType": "event",
                              "EventBusName": "${eventBus.eventBusName}"
                            }
                          ]
                        }
          `,
      },
      integrationResponses: [
        {
          statusCode: '200',
          responseTemplates: {
            'application/json': '',
          },
        },
      ],
    };
    eventTypeResource.addMethod('POST', new Integration({
      type: IntegrationType.AWS,
      uri: `arn:aws:apigateway:${env.region}:events:path//`,
      integrationHttpMethod: 'POST',
      options: options,
    }), {
      authorizer: LambdaAuth0Authorizer.authorizer,
      methodResponses: [{ statusCode: '200' }],
      requestModels: { 'application/json': getEventModel(this, eventsAPI) },
      requestValidator: new RequestValidator(this, 'eventValidator', {
        restApi: eventsAPI,
        validateRequestBody: true,
      }),
    });
</code>```

This generates:

```<code>{"Entries":
  [
    {
      "Source": "com.uproarapi",
      "Detail": "{eventType=FOLLOW, action=CREATE, subject=USER_777POIUY, eventTime=51644444444, actor=}",
      "Resources": [],
      "DetailType": "UpRoarEvent",
      "EventBusName": "UpRoarEventBus"
    }
  ]
}
</code>```

With an error:

```<code>{"Entries":[{"ErrorCode":"MalformedDetail","ErrorMessage":"Detail is malformed."}],"FailedEntryCount":1}
</code>```

Title: AWS Api Gateway VTL Merge Json Object

Body:
Trying to merge the principalId from Lambda Authorizer into the payload that will be sent to Event Bridge.

So far I've gotten close by transforming to map and re-creating the Json object. The problem is that this Json object is printed out as a key:value pair with no quotes, So there's an error thrown.

According to the docs, there's non $util.toJson($map) available, this seems to be only available for AppSync.

    const eventsAPI = new RestApi(this, 'eventsAPI', apigwOps);

    const LambdaAuth0Authorizer = new LambdaAuth0Authorizer(this, 'LambdaAuth0Authorizer', {
      env: {
        auth0Audience: '',
        auth0Domain: '',
      },
    });

    const eventTypeResource = eventsAPI.root.addResource('event');
    const options: IntegrationOptions = {
      credentialsRole: apigwRole,
      passthroughBehavior: PassthroughBehavior.NEVER,
      requestParameters: {
        'integration.request.header.X-Amz-Target': "'AWSEvents.PutEvents'",
        'integration.request.header.Content-Type': "'application/x-amz-json-1.1'",
      },

      requestTemplates: {
        'application/json': `
        #set ( $map = $util.parseJson($input.body) )
        #set ( $j = {
          "eventType": "$map['eventType']",
          "action": "$map['action']",
          "subject": "$map['subject']",
          "eventTime": $map['eventTime'],
          "actor": "$context.authorizer.principalId"
         }
        )
                    {"Entries":
                          [
                            {
                              "Source": "com.xyz",
                              "Detail": "$util.escapeJavascript($j)",
                              "Resources": [],
                              "DetailType": "event",
                              "EventBusName": "${eventBus.eventBusName}"
                            }
                          ]
                        }
          `,
      },
      integrationResponses: [
        {
          statusCode: '200',
          responseTemplates: {
            'application/json': '',
          },
        },
      ],
    };
    eventTypeResource.addMethod('POST', new Integration({
      type: IntegrationType.AWS,
      uri: `arn:aws:apigateway:${env.region}:events:path//`,
      integrationHttpMethod: 'POST',
      options: options,
    }), {
      authorizer: LambdaAuth0Authorizer.authorizer,
      methodResponses: [{ statusCode: '200' }],
      requestModels: { 'application/json': getEventModel(this, eventsAPI) },
      requestValidator: new RequestValidator(this, 'eventValidator', {
        restApi: eventsAPI,
        validateRequestBody: true,
      }),
    });

This generates:

{"Entries":
  [
    {
      "Source": "com.uproarapi",
      "Detail": "{eventType=FOLLOW, action=CREATE, subject=USER_777POIUY, eventTime=51644444444, actor=}",
      "Resources": [],
      "DetailType": "UpRoarEvent",
      "EventBusName": "UpRoarEventBus"
    }
  ]
}

With an error:

{"Entries":[{"ErrorCode":"MalformedDetail","ErrorMessage":"Detail is malformed."}],"FailedEntryCount":1}


问:
Should I put this code in the shouldUpdate call?
I have the following shouldUpdate call

shouldUpdate(changedProperties: PropertyValues): boolean {
    if (changedProperties.has("mobile") &&
        !this._isOpeningDialog &&
        this._testStore.isShareSheetOpen) {
        this._testStore.closeShareSheet();
    }

    return this._isOpeningDialog;
}
```

I need to check if the mobile property has changed and if so update the element. However, this seems like an anti-pattern. Does anyone have a better way to do this?

this._testStore.closeShareSheet() causes the element to re-render and shouldUpdate to be called.

Body:
I have the following shouldUpdate call

shouldUpdate(changedProperties: PropertyValues): boolean {
    if (changedProperties.has("mobile") &&
        !this._isOpeningDialog &&
        this._testStore.isShareSheetOpen) {
        this._testStore.closeShareSheet();
    }

    return this._isOpeningDialog;
}

I need to check if the mobile property has changed and if so update the element. However, this seems like an anti-pattern. Does anyone have a better way to do this?

this._testStore.closeShareSheet() causes the element to re-render and shouldUpdate to be called.


问:
What is the valid flow for prompt=none if user checked "don't remember my consent"
Assume that client uses prompt=none for silent authentication, but user checked "Do not remember my consent" earlier. So we always will return consent_required error if user didn't want to remember his consent?

If not, what is valid flow for scenario like it?


问:
How to keep my Minecraft server running in Google Cloud Platform?
I used a VM in Google Cloud Platform to host a Minecraft server, which I use ./run.sh to start the server. However, once I close the VM bash it shuts down my server. It's a way to keep my server running?

I tried using screen -S run.sh it didn't work though.


问:
why does Ginkgo Bioworks have ~2.0 B Operating expense in 2021
why does Ginkgo Bioworks have ~2.0 B Operating expense in 2021.
The company raised money in IPO and it seems its expensing equity grants, or something.
Can someone explain what Ginkgo is spending its money on?


问:
how to get all available event slots in google calendar?
I have an appointment schedule that I want to retrieve. But the list event method only returns the slots that have been booked and not all slots so that I can filter out available slots.

    $events = $service->events->listEvents('calendarID'); // Only returns booked appointments (my case 2)
```

How can I achieve this?

Body:
I have an appointment schedule that I want to retrieve. But the list event method only returns the slots that have been booked and not all slots so that I can filter out available slots.

    $events = $service->events->listEvents('calendarID'); // Only returns booked appointments (my case 2)

How can I achieve this?


问:
Can I read from InputStream, while program is busy?
I get an InputStream from a TCP connection and read from it (via BufferedReader). When receiving a message, my program will process that request. This includes some database operations. It will do so continuously in a while loop (TCP long connection).

Schematically it looks like this:

```<code>while(!clientSocket.isClosed()) {
    in.read(request);
    // process request
}
</code>```

What happens, if a new message arrives, while my program is still busy processing the previous request?
Will it be "stored" and fetched with the next in.read() call? Or do I have to create a thread for the database operations to not miss requests?

Body:
I get an InputStream from a TCP connection and read from it (via BufferedReader). When receiving a message, my program will process that request. This includes some database operations. It will do so continuously in a while loop (TCP long connection).

Schematically it looks like this:

while(!clientSocket.isClosed()) {
    in.read(request);
    // process request
}

What happens, if a new message arrives, while my program is still busy processing the previous request?
Will it be "stored" and fetched with the next in.read() call? Or do I have to create a thread for the database operations to not miss requests?


问:
C# Trying to save a picture from a user in a web browser
I am trying to allow a user to insert a file and then send it in an email, but I don't know how to receive that file. There is an error on the "System.IO.File" part of my code that says "static types cannot be used as return types" I am not sure what to do from here, I have tried looking that up but I'm not sure.

C# Class

```<code>        [Required]
        [DataType(DataType.Upload)]
        [Display(Name = "Picture of Product sticker")]
  error ->      public System.IO.File strFileName { get; set; }
</code>```

HTML

```<code>        <div class="form-group">
            <label asp-for="strFileName"></label>
            <input asp-for="strFileName" type="file" class="form-control" />
            <span asp-validation-for="strFileName" class="text-danger"></span>
        </div>
</code>```

Body:
I am trying to allow a user to insert a file and then send it in an email, but I don't know how to receive that file. There is an error on the "System.IO.File" part of my code that says "static types cannot be used as return types" I am not sure what to do from here, I have tried looking that up but I'm not sure.

C# Class

        [Required]
        [DataType(DataType.Upload)]
        [Display(Name = "Picture of Product sticker")]
  error ->      public System.IO.File strFileName { get; set; }

HTML

            <input asp-for="strFileName" type="file" class="form-control" />


问:
Connect MongoDB from DNS URL without port
I have a MongoDB deployed from a Kubernetes instance and with a Ingress/F5 forwarder creating a custom url to access it, something like:

IP: 10.0.0.1:27017

DNS: https://my-mongo-url.company.net

If I put both the Ip/Port or the DNS in my browser I receive the message;

```<code>It looks like you are trying to access MongoDB over HTTP on the native driver port.
</code>```

And when I try to use them to connect on Compass, the IP/Port connects normally.. but with the URL it autofill the port field with the 27017 default port and then won't reach the server!

I tried some "default http/https ports" but none of them worked.

Body:
I have a MongoDB deployed from a Kubernetes instance and with a Ingress/F5 forwarder creating a custom url to access it, something like:

IP: 10.0.0.1:27017

DNS: https://my-mongo-url.company.net

If I put both the Ip/Port or the DNS in my browser I receive the message;

It looks like you are trying to access MongoDB over HTTP on the native driver port.

And when I try to use them to connect on Compass, the IP/Port connects normally.. but with the URL it autofill the port field with the 27017 default port and then won't reach the server!

I tried some "default http/https ports" but none of them worked.


问:
Make custom fixed intervals chartjs
Need to make fixed interval with number values[0,100000,300000,500000,5000000] for left side of graph as this:

```<code>        scales: {
          y: {
            max: 5000000 ,
            beginAtZero: true,

            grid: {
              color: '#FFFFFF05',
            },
            ticks:{
              color: '#FFFFFF20',
              font: {
                size: 10,
              },
              count: 5,
            }
          },
</code>```

Actual intervals, that depends on count.

One way I found depends on values: https://www.chartjs.org/docs/latest/samples/scales/log.html

I don't need any dependencies, just fixed numbers.

Title: Make custom fixed intervals chartjs

Body:
Need to make fixed interval with number values[0,100000,300000,500000,5000000] for left side of graph as this:

        scales: {
          y: {
            max: 5000000 ,
            beginAtZero: true,

            grid: {
              color: '#FFFFFF05',
            },
            ticks:{
              color: '#FFFFFF20',
              font: {
                size: 10,
              },
              count: 5,
            }
          },

Actual intervals, that depends on count.

One way I found depends on values: https://www.chartjs.org/docs/latest/samples/scales/log.html

I don't need any dependencies, just fixed numbers.


问:
Can I programmatically deduce the native text encoding of my target(preferably statically)?
I have a bunch of strings in my program.  I don't know how these strings are encoded, or what determines the encoding.  Everything I read about this in c++ seems to simply state that char and string are encoding agnostic and don't care about what you shove into them.  However, it would be very useful to me to know this.

When I write std::string = "some text" if this is a utf8/16/32, ascii, extended ascii, or other encoding scheme that gets utilized.  Is this determined by the compiler?  Or the target OS?  The target hardware?

What factors are at play in the implementation that determines how the string gets encoded, and how can I detect them?

Does the encoding of the source file matter?  If all my source files are utf8, can I guarantee that gcc/g++ will always encode strings as utf8?


问:
How to approach setting up domain2 (server2) pointing to domain1 (server1) and creating 2 subdomains on domain2 for 2 apps both using SSL?
How to approach setting up domain2 (server2) pointing to domain1 (server1) and creating 2 subdomains on domain2 for 2 apps?

server2 has Apache loaded on it.
server1 is a 3rd-party web host.

I have a wildcard SSL on my server2 for the 2 apps.
app1 is on port 443
app2 is on port 444

I've gotten both of these subdomain apps to run locally.

It has blown up though for me once I tried to get them to have SSL by setting up my 3rd-party web host dns records.

If someone can help solve this puzzle for me, I'd appreciate.

I've tried setting it up the dns on the 3rd-party hosting with a subdomain forwarding to my server2, but the IP was changing and the SSL was complaining.


问:
waiting for debugger to settle in android studio
enter image description here When I try to a debug it gives error and all read files error, I couldn't solve the problem please help me step by step

I tried to do Rebuild Project , Clean Project but it doesn't work


问:
Flutter devtools search widget tree details?
I am trying to search for something in the Widget Details Tree of the devtools inspector but it doesn't seem like I can. There is a search function in the Widget Tree in the devtools but not the Widget Details Tree. Is it possible to search the Widget Details Tree?


问:
Getting error connection failure, transport failure reason: TLS error: 268435581:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED
We have two istio installed in k8s cluster one is 1.8.6 and 1.14.1.
we have injected 1.8.6 istio in namespace-1 and 1.14.1 istio in namespace-2
Running some workloads on both namespace

when i try to make curl request from one pod(namespace-1) to another pod(namespace-2) getting error
"upstream connect error or disconnect/reset before headers. reset reason: connection failure, transport failure reason: TLS error: 268435581:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED"

Expectation:- It should hit the API properly.

P.S- It might be issues with the istio version hitting from 1.8 version to 1.14 version


问:
listen to changes in response object from the custom hook with React
Am quite new to react and I have the following custom hook that I have to use.

```<code>import { useState } from "react";

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const useSubmit = () => {
    const [isLoading, setLoading] = useState(false);
    const [response, setResponse] = useState(null);

    const submit = async (url, data) => {
        const random = Math.random();
        setLoading(true);
        try {
            await wait(2000);
            if (random < 0.5) {
                throw new Error("Something went wrong");
            }
            setResponse({
                type: 'success',
                message: `Thanks for your submission ${data.firstName}, we will get back to you shortly!`,
            })
        } catch (error) {
            setResponse({
                type: 'error',
                message: 'Something went wrong, please try again later!',
            })
        } finally {
            setLoading(false);
        }
    };

    return { isLoading, response, submit };
}

export default useSubmit;

</code>```

Then on a form component using formik I'm trying to call the submit() on onSubmit:

```<code>    const { isLoading, response, submit } = useSubmit();

    const formik = useFormik({

        onSubmit: (values, actions) => {
            submit("", values);
        }
    });

</code>```

After calling submit I need to get the response set in the submit function, what is the best practise to call the submit and listen to the response object. Should I use a useEffect checking the response or is there a better way to handle this?

Thanks.

Body:
Am quite new to react and I have the following custom hook that I have to use.

import { useState } from "react";

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const useSubmit = () => {
    const [isLoading, setLoading] = useState(false);
    const [response, setResponse] = useState(null);

    const submit = async (url, data) => {
        const random = Math.random();
        setLoading(true);
        try {
            await wait(2000);
            if (random < 0.5) {
                throw new Error("Something went wrong");
            }
            setResponse({
                type: 'success',
                message: `Thanks for your submission ${data.firstName}, we will get back to you shortly!`,
            })
        } catch (error) {
            setResponse({
                type: 'error',
                message: 'Something went wrong, please try again later!',
            })
        } finally {
            setLoading(false);
        }
    };

    return { isLoading, response, submit };
}

export default useSubmit;

Then on a form component using formik I'm trying to call the submit() on onSubmit:

    const { isLoading, response, submit } = useSubmit();

    const formik = useFormik({

        onSubmit: (values, actions) => {
            submit("", values);
        }
    });

After calling submit I need to get the response set in the submit function, what is the best practise to call the submit and listen to the response object. Should I use a useEffect checking the response or is there a better way to handle this?

Thanks.


问:
Deleting a record in a file in Java
```<code>
public class Client {
    private Scanner scanner;
    private String fileClient="client.txt";
    public File client =new File(fileClient);

public void deletClient() {
            int lineRemove =GetLineRemove();
            String tempFile="temp.txt";
            File newfile=new File(tempFile);
            int line=0;
            String currentLine;

            try {
                FileWriter fw=new FileWriter(tempFile,true);
                BufferedWriter bw=new BufferedWriter(fw);
                PrintWriter pw=new PrintWriter(bw);

                FileReader fr=new FileReader(fileClient);
                BufferedReader br=new BufferedReader(fr);

                while((currentLine=br.readLine())!=null ) {
                    line++;

                    if(line !=lineRemove) {
                        pw.println(currentLine);
                    }
                }
                pw.flush();
                fr.close();
                bw.close();
                pw.close();
                br.close();
                fw.close();
             // i try to delet a file
                client.delete();
                        // create a file have the same name
                File dumy=new File(fileClient);
                      // rename it to first file
                newfile.renameTo(dumy);

            }catch(Exception e){
                System.out.print(e);
            }

        }

</code>```

I want to remove a line from a file but when i do that i found the first file still exist and the second file what should get rename to the first file still have has it name temp  i don't know should do so i hope u can help me to know where is the problem.

Title: Deleting a record in a file in Java

Body:
public class Client {
    private Scanner scanner;
    private String fileClient="client.txt";
    public File client =new File(fileClient);

public void deletClient() {
            int lineRemove =GetLineRemove();
            String tempFile="temp.txt";
            File newfile=new File(tempFile);
            int line=0;
            String currentLine;

            try {
                FileWriter fw=new FileWriter(tempFile,true);
                BufferedWriter bw=new BufferedWriter(fw);
                PrintWriter pw=new PrintWriter(bw);

                FileReader fr=new FileReader(fileClient);
                BufferedReader br=new BufferedReader(fr);

                while((currentLine=br.readLine())!=null ) {
                    line++;

                    if(line !=lineRemove) {
                        pw.println(currentLine);
                    }
                }
                pw.flush();
                fr.close();
                bw.close();
                pw.close();
                br.close();
                fw.close();
             // i try to delet a file
                client.delete();
                        // create a file have the same name
                File dumy=new File(fileClient);
                      // rename it to first file
                newfile.renameTo(dumy);

            }catch(Exception e){
                System.out.print(e);
            }

        }

I want to remove a line from a file but when i do that i found the first file still exist and the second file what should get rename to the first file still have has it name temp  i don't know should do so i hope u can help me to know where is the problem.


问:
populating elements of dict using pandas.read_pickle() results in killed python process
On an Ubuntu 18.04.5 image running on AWS, I've noticed that attempting to populate a dict with multiple (7, in my case) dataframes loaded via pandas.read_pickle(), e.g., using something like

```<code>import pathlib
import pandas as pd
df_dict = {}
base_dir = pathlib.Path('some_path')
for i, f in base_dir.glob('*.pkl'):
    print(f)
    df = pd.read_pickle(f)
</code>```

results in the python process being killed before all of the dataframes are loaded. What's odd is that if I read the files but don't assign them to elements of the dict, the loop completes successfully. Also, if I try loading the exact same dataframes stored in some other file format such as Feather (using pandas.read_feather()), the loop completes successfully. Any thoughts as to what could be going on? I'm using Python 3.8.8 and Pandas 1.2.4 installed via conda; I've also tried Python 3.8.15 with Pandas 1.5.2 and the same pickle files, but the result is the same. When I try to replicate the problem using the same Python and Pandas versions on MacOS 12.6.2 (also installed via conda), the problem does not occur.

Body:
On an Ubuntu 18.04.5 image running on AWS, I've noticed that attempting to populate a dict with multiple (7, in my case) dataframes loaded via pandas.read_pickle(), e.g., using something like

import pathlib
import pandas as pd
df_dict = {}
base_dir = pathlib.Path('some_path')
for i, f in base_dir.glob('*.pkl'):
    print(f)
    df = pd.read_pickle(f)

results in the python process being killed before all of the dataframes are loaded. What's odd is that if I read the files but don't assign them to elements of the dict, the loop completes successfully. Also, if I try loading the exact same dataframes stored in some other file format such as Feather (using pandas.read_feather()), the loop completes successfully. Any thoughts as to what could be going on? I'm using Python 3.8.8 and Pandas 1.2.4 installed via conda; I've also tried Python 3.8.15 with Pandas 1.5.2 and the same pickle files, but the result is the same. When I try to replicate the problem using the same Python and Pandas versions on MacOS 12.6.2 (also installed via conda), the problem does not occur.


问:
Where do Linux shells look for interpreters for ELF binaries?
I've been trying to add an entry point to a C shared library, so that executing

$ ./lib/mylib.so

prints some helpful information to the terminal.

Following the work here, I was able to get my library to run like so:

$ /lib64/ld-linux-x86-64.so.2 ./lib/mylib.so
Some useful configuration information about this library:
- blah blah
- Gcc version: gcc-9
- Hostname where compiled: foo

$
```

However, when I run without the interpreter, I get a no such file or directory error. Why is this? What can I do to help my shell find the correct interpreter?

Body:
I've been trying to add an entry point to a C shared library, so that executing

$ ./lib/mylib.so

prints some helpful information to the terminal.

Following the work here, I was able to get my library to run like so:

$ /lib64/ld-linux-x86-64.so.2 ./lib/mylib.so
Some useful configuration information about this library:
- blah blah
- Gcc version: gcc-9
- Hostname where compiled: foo

$

However, when I run without the interpreter, I get a no such file or directory error. Why is this? What can I do to help my shell find the correct interpreter?


问:
PyCharm, open new window for each "View as DataFrame"
In Debug mode, I would like PyCharm to open a new window (not a new tab!) for every "View as DataFrame" click I do.

Right now, they are opened as tabs, which makes it very difficult to compare.

Other posts suggest to klick the "Open in editor" button to then move it. This works but it is annoyingly cumbersome. And I remember in the past multiple windows opened (maybe in the community edition?)


问:
Java 11 Linux VM cpu memory not coming down until we restart application
Recently we upgraded the java version from 8 to 11. Whenever the application processing a high load of data, CPU and memory reach maximum >90%. Still, after the load got reduced, the CPU/Memory is not getting down until we restart the application.

I have these parameters

```<code>APP_JVM_XMS=256M
APP_JVM_XMX=4096M
</code>```

Body:
Recently we upgraded the java version from 8 to 11. Whenever the application processing a high load of data, CPU and memory reach maximum >90%. Still, after the load got reduced, the CPU/Memory is not getting down until we restart the application.

I have these parameters

APP_JVM_XMS=256M
APP_JVM_XMX=4096M


问:
Is the package nixos-rebuild for a distribution different from nixos?
I've read the documentation for nix-rebuild. It look like it is only intended to use in nixos. The constant $NIX_PATH (/etc/nixos/configuration.nix) can be found only on a nixos distribution..
But in the package manager , there is a possibility to install the package a distribution different from nixos.

```<code>nix-env -iA nixpkgs.nixos-rebuild
</code>```

Can this be useful for a non nix-os distribution?

Body:
I've read the documentation for nix-rebuild. It look like it is only intended to use in nixos. The constant $NIX_PATH (/etc/nixos/configuration.nix) can be found only on a nixos distribution..
But in the package manager , there is a possibility to install the package a distribution different from nixos.

nix-env -iA nixpkgs.nixos-rebuild

Can this be useful for a non nix-os distribution?


问:
How can I load bootfont.bin from Windows XP in my own programs?
I would like to load bootfont.bin from Windows XP from my own code to draw more graphical text, but I don't know the file format specification of bootfont.bin.

Where can I find it?


问:
Initial connect of Google Sheets API to SP-API
I've just discovered I can automate my Amazon business through google scripts. I've created an SP-API account and followed all the processes up to the point of authorizing the applications. I want to connect SP-API to Google sheets API. How can I authorize them, please?
Thanks

It feels like everything at this point, I've been stuck on this for about 4 hours. I know it'll be a really simple process for someone with any programming experience.


问:
How can i set the action of a button in a PowerPoint slide through VSTO PowerPoint AddIn?
I am working on a PowerPoint add-in using VSTO.

I want to insert a button into the current slide of a PowerPoint, that when clicked calls a function in my code behind. Something like the following:
`

```<code>PowerPoint.Slide Sld = Globals.ThisAddIn.Application.ActiveWindow.View.Slide;
            PowerPoint.Shape shape = Sld.Shapes.AddShape(MsoAutoShapeType.msoShapeActionButtonCustom, 0, 100, 500, 50);
            shape.TextFrame.TextRange.InsertAfter("This text was also added by using code.");
            shape.Name = "shape3";
            //when clicked, run method abc()
</code>```

`
i'm struggling to find anyone who has actually made a button inside the PowerPoint slide, that runs some code. What most people do is have a button in the ribbon, and program that one, but that isn't what i'm interested in.
I simply can't figure out how to add an eventlistener or something alike to the button inside the slide.

Can anyone help me on this issue?

I've found the Shape.Script.ScriptText, but i can't figure how it actually works, of if it even is a way to fix my problem

```<code>            shape.Script.ScriptText = ??somescript??

</code>```

Neither am i certain that the code above even is the right approach at all. All i know is that it works for inserting textboxes and the like, but they aren't interactive.

Update
I've stumpled upon something like

```<code>PowePoint.Shape shape = Sld.Shapes.AddOLEObject(0, 100, 500, 50, "Forms.CommandButton.1", "",
                Office.MsoTriState.msoFalse, "", 0, "", Office.MsoTriState.msoFalse);
</code>```

Which inserts a nice button into the slide, and i've also found this
https://www.youtube.com/watch?v=tnXPgy0BCp4&ab_channel=DigitalCatalog
which is a video of how to use this sort of commandbutton in excel, and apply code to it. All i am missing is how to choose which code the CommandButton is running, when clicked, in my addin.

Edit
I've given up on the idea, I simply couldn't see how. Instead i have an eventlistener on slidechanges, and prevent the slidechange from happening, which then works as my button. That does mean i can only have one "button" on a slide, but luckily i don't need more for this project.

It does seem possible to do, in a somewhat more complicated way, looking at the coordinates of the mouse, and doing it from scratch. check out following:
How to invoke an action during powerpoint slideshow programmatically?

Body:
I am working on a PowerPoint add-in using VSTO.

I want to insert a button into the current slide of a PowerPoint, that when clicked calls a function in my code behind. Something like the following:
`

PowerPoint.Slide Sld = Globals.ThisAddIn.Application.ActiveWindow.View.Slide;
            PowerPoint.Shape shape = Sld.Shapes.AddShape(MsoAutoShapeType.msoShapeActionButtonCustom, 0, 100, 500, 50);
            shape.TextFrame.TextRange.InsertAfter("This text was also added by using code.");
            shape.Name = "shape3";
            //when clicked, run method abc()

`
i'm struggling to find anyone who has actually made a button inside the PowerPoint slide, that runs some code. What most people do is have a button in the ribbon, and program that one, but that isn't what i'm interested in.
I simply can't figure out how to add an eventlistener or something alike to the button inside the slide.

Can anyone help me on this issue?

I've found the Shape.Script.ScriptText, but i can't figure how it actually works, of if it even is a way to fix my problem

            shape.Script.ScriptText = ??somescript??

Neither am i certain that the code above even is the right approach at all. All i know is that it works for inserting textboxes and the like, but they aren't interactive.

Update
I've stumpled upon something like

PowePoint.Shape shape = Sld.Shapes.AddOLEObject(0, 100, 500, 50, "Forms.CommandButton.1", "",
                Office.MsoTriState.msoFalse, "", 0, "", Office.MsoTriState.msoFalse);

Which inserts a nice button into the slide, and i've also found this
https://www.youtube.com/watch?v=tnXPgy0BCp4&ab_channel=DigitalCatalog
which is a video of how to use this sort of commandbutton in excel, and apply code to it. All i am missing is how to choose which code the CommandButton is running, when clicked, in my addin.

Edit
I've given up on the idea, I simply couldn't see how. Instead i have an eventlistener on slidechanges, and prevent the slidechange from happening, which then works as my button. That does mean i can only have one "button" on a slide, but luckily i don't need more for this project.

It does seem possible to do, in a somewhat more complicated way, looking at the coordinates of the mouse, and doing it from scratch. check out following:
How to invoke an action during powerpoint slideshow programmatically?


问:
Showing 1 or more overloads when writing a class with a custom constructor in C++
I tried searching about this problem but most questions seem to be the opposite, which is "where did my default constructor go?" Whereas I have the opposite problem and am getting additional overloads that I'm not sure where from. I've tried writing and instantiating the simplest class I can:

```<code>class MyClass
{
public:
    MyClass(int)
    {
    }
};

MyClass a(1);
</code>```

But when I mouse over the class in Visual Studio, or auto-complete pops up, it says I have not 1, but 3 constructor possibilities:

```<code>MyClass(const MyClass &&)
MyClass(MyClass &)
MyClass(int)
</code>```

Obviously this doesn't stop my program from running but is annoying since I'd like any instantiation of MyClass to be forced to provide an int parameter! I'm at a loss where these extra overloads are coming from? If I don't define the constructor then I get no popup at all regarding possible parameters for the class. I've tried moving my class declaration/definition out of MyClass.h and .cpp directly into my main.cpp even to eliminate any possible issue with linking multiple definitions or anything like that, and get the same behavior.

Body:
I tried searching about this problem but most questions seem to be the opposite, which is "where did my default constructor go?" Whereas I have the opposite problem and am getting additional overloads that I'm not sure where from. I've tried writing and instantiating the simplest class I can:

class MyClass
{
public:
    MyClass(int)
    {
    }
};

MyClass a(1);

But when I mouse over the class in Visual Studio, or auto-complete pops up, it says I have not 1, but 3 constructor possibilities:

MyClass(const MyClass &&)
MyClass(MyClass &)
MyClass(int)

Obviously this doesn't stop my program from running but is annoying since I'd like any instantiation of MyClass to be forced to provide an int parameter! I'm at a loss where these extra overloads are coming from? If I don't define the constructor then I get no popup at all regarding possible parameters for the class. I've tried moving my class declaration/definition out of MyClass.h and .cpp directly into my main.cpp even to eliminate any possible issue with linking multiple definitions or anything like that, and get the same behavior.


问:
How to match Rest of Collections in firestore rules?
I have like 50+ collections on firestore and now I am working on security rules.
let's say all collections should have the same rules like (read and write if user is autheticated).
and only one collection has some different criteria.

I used the following:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /LovesCollection/{loveid} {
      allow read: if request.auth != null;
      allow write: if request.auth != null && get(/databases/$(database)/documents/UsersCollection/$(request.auth.uid)).data.User_admin_type == Owner;
    }
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}
```

the result here is that the second match overrides the first one and the user have write access if only authenticated.

so I am wondering if there is a way to say "rest of collections" or I have to go for all collections one by one?

Body:
I have like 50+ collections on firestore and now I am working on security rules.
let's say all collections should have the same rules like (read and write if user is autheticated).
and only one collection has some different criteria.

I used the following:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /LovesCollection/{loveid} {
      allow read: if request.auth != null;
      allow write: if request.auth != null && get(/databases/$(database)/documents/UsersCollection/$(request.auth.uid)).data.User_admin_type == Owner;
    }
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

the result here is that the second match overrides the first one and the user have write access if only authenticated.

so I am wondering if there is a way to say "rest of collections" or I have to go for all collections one by one?


问:
Uncaught (in promise) ReferenceError: can't access lexical declaration 'initializeBoard' before initialization
```<code>const initialBoard = [];

const nestedMenuitems = ref([

    {
        label: 'Shipments',

        items: initializeBoard()
    },

]);
const initializeBoard = () => {
  stores.map((store) => initialBoard.push({lable: store.shop}));
//   stores.map(function(value, _key) {
//     initialBoard.push({lable: value.shop});
// });
  return initialBoard;
}
onMounted(() => {
    ApiService.getStores().then((data) => {
        stores.value = data;
//         stores.value.map(function(value, _key) {

//             list.push({lable: value.shop});

//      console.log(value.shop);
//    });
    //    stores.value.forEach((store) => { return {

    //  }});

    });

});
</code>```
```<code>const nestedMenuitems = ref([

 {
        label: 'Shipments',

        items: [
            {
                label: 'Tracker',

            },
            {
                label: 'Map',

            },
            {
                label: 'Manage',

            }
        ]
    },

]);
</code>```

this is i want to

but this line

```<code>        items: initializeBoard()

</code>```

here  i fetch data in onMounted and then i call initializeBoard map function .the initializeBoard
call to  items: initializeBoard().but i get a error i get a error Uncaught (in promise)
ReferenceError: can't access lexical declaration 'initializeBoard' before initialization how to solve thi problem?

Body:
const initialBoard = [];

const nestedMenuitems = ref([

    {
        label: 'Shipments',

        items: initializeBoard()
    },

]);
const initializeBoard = () => {
  stores.map((store) => initialBoard.push({lable: store.shop}));
//   stores.map(function(value, _key) {
//     initialBoard.push({lable: value.shop});
// });
  return initialBoard;
}
onMounted(() => {
    ApiService.getStores().then((data) => {
        stores.value = data;
//         stores.value.map(function(value, _key) {

//             list.push({lable: value.shop});

//      console.log(value.shop);
//    });
    //    stores.value.forEach((store) => { return {

    //  }});

    });

});

const nestedMenuitems = ref([

 {
        label: 'Shipments',

        items: [
            {
                label: 'Tracker',

            },
            {
                label: 'Map',

            },
            {
                label: 'Manage',

            }
        ]
    },

]);

this is i want to

but this line

        items: initializeBoard()

here  i fetch data in onMounted and then i call initializeBoard map function .the initializeBoard
call to  items: initializeBoard().but i get a error i get a error Uncaught (in promise)
ReferenceError: can't access lexical declaration 'initializeBoard' before initialization how to solve thi problem?


问:
Graph disconnected: cannot obtain value for tensor in Keras
I am trying to build a Convolutional network where the labels will be concatenated at the encoder and at the decoder. But i am getting a 'Graph: Disconnected error'

```<code>X_train = X_train.astype('float32') / 255.
X_train = X_train.reshape(-1,28,28,1)
Y_train = to_categorical(Y_train).shape[1]
X_valid = X_valid.astype('float32') / 255.
X_valid = X_valid.reshape(-1,28,28,1)

img_shape = (28, 28, 1)    # for MNIST
batch_size = 150
latent_dim = 128

input_img = Input(shape=img_shape)
label_inputs = Input(shape=(10,), name='label')

x = Conv2D(32, 3, padding='same', activation='relu')(input_img)
x = Conv2D(64, 3, padding='same', activation='relu', strides=(2, 2))(x)
x = Conv2D(64, 3, padding='same', activation='relu')(x)
x = Conv2D(64, 3, padding='same', activation='relu')(x)
</code>```

need to know the shape of the network here for the decoder

```<code>shape_before_flattening = K.int_shape(x)

x = Flatten()(x)
x = Concatenate()([x, label_inputs])
x = Dense(32, activation='relu')(x)

z_mu = Dense(latent_dim)(x)
z_log_sigma = Dense(latent_dim)(x)
</code>```

sampling function

```<code>def sampling(args):
    z_mu, z_log_sigma = args
    epsilon = K.random_normal(shape=(K.shape(z_mu)[0], latent_dim),
                              mean=0., stddev=1.)
    return z_mu + K.exp(z_log_sigma) * epsilon
</code>```

sample vector from the latent distribution

```<code>z = Lambda(sampling)([z_mu, z_log_sigma])
decoder_input = Input(K.int_shape(z)[1:])

x = Concatenate()([decoder_input, label_inputs])

x = Dense(np.prod(shape_before_flattening[1:]), activation='relu')(x)

x = Reshape(shape_before_flattening[1:])(x)

x = Conv2DTranspose(32, 3, padding='same', activation='relu', strides=(2, 2))(x)
x = Conv2D(1, 3, padding='same', activation='sigmoid')(x)

decoder = Model(decoder_input, x)

z_ecoded = decoder(z)

class CustomVariationalLayer(keras.layers.Layer):

    def vae_loss(self, x, z_decoded):
        x = K.flatten(x)
        z_decoded = K.flatten(z_decoded)
        # Reconstruction loss
        xent_loss = metrics.binary_crossentropy(x, z_decoded)
        # KL divergence
        kl_loss = -5e-4 * K.mean(1 + z_log_sigma - K.square(z_mu) - K.exp(z_log_sigma), axis=-1)
        return K.mean(xent_loss + kl_loss)

    # adds the custom loss to the class
    def call(self, inputs):
        x = inputs[0]
        z_decoded = inputs[1]
        loss = self.vae_loss(x, z_decoded)
        self.add_loss(loss, inputs=inputs)
        return x

y = CustomVariationalLayer()([input_img, z_decoded])

vae = Model(input_img, y)
vae.compile(optimizer='rmsprop', loss=None)
vae.summary()

</code>```

The input have a shape of (None, 28,28,1) same as MNIST and the the labels has a shape of (None, 10). I knwo i cannot directly concatenate the two values at the input as they are of of different shapes. So to tried to concatenate after flattening the input Convolutional layer. But it is still not working on both the side at the encoder and decoder.

I don't really know how to fix that.

Can anyone help me?

Thanks in advance.

Body:
I am trying to build a Convolutional network where the labels will be concatenated at the encoder and at the decoder. But i am getting a 'Graph: Disconnected error'

X_train = X_train.astype('float32') / 255.
X_train = X_train.reshape(-1,28,28,1)
Y_train = to_categorical(Y_train).shape[1]
X_valid = X_valid.astype('float32') / 255.
X_valid = X_valid.reshape(-1,28,28,1)

img_shape = (28, 28, 1)    # for MNIST
batch_size = 150
latent_dim = 128

input_img = Input(shape=img_shape)
label_inputs = Input(shape=(10,), name='label')

x = Conv2D(32, 3, padding='same', activation='relu')(input_img)
x = Conv2D(64, 3, padding='same', activation='relu', strides=(2, 2))(x)
x = Conv2D(64, 3, padding='same', activation='relu')(x)
x = Conv2D(64, 3, padding='same', activation='relu')(x)

need to know the shape of the network here for the decoder

shape_before_flattening = K.int_shape(x)

x = Flatten()(x)
x = Concatenate()([x, label_inputs])
x = Dense(32, activation='relu')(x)

z_mu = Dense(latent_dim)(x)
z_log_sigma = Dense(latent_dim)(x)

sampling function

def sampling(args):
    z_mu, z_log_sigma = args
    epsilon = K.random_normal(shape=(K.shape(z_mu)[0], latent_dim),
                              mean=0., stddev=1.)
    return z_mu + K.exp(z_log_sigma) * epsilon

sample vector from the latent distribution

z = Lambda(sampling)([z_mu, z_log_sigma])
decoder_input = Input(K.int_shape(z)[1:])

x = Concatenate()([decoder_input, label_inputs])

x = Dense(np.prod(shape_before_flattening[1:]), activation='relu')(x)

x = Reshape(shape_before_flattening[1:])(x)

x = Conv2DTranspose(32, 3, padding='same', activation='relu', strides=(2, 2))(x)
x = Conv2D(1, 3, padding='same', activation='sigmoid')(x)

decoder = Model(decoder_input, x)

z_ecoded = decoder(z)

class CustomVariationalLayer(keras.layers.Layer):

    def vae_loss(self, x, z_decoded):
        x = K.flatten(x)
        z_decoded = K.flatten(z_decoded)
        # Reconstruction loss
        xent_loss = metrics.binary_crossentropy(x, z_decoded)
        # KL divergence
        kl_loss = -5e-4 * K.mean(1 + z_log_sigma - K.square(z_mu) - K.exp(z_log_sigma), axis=-1)
        return K.mean(xent_loss + kl_loss)

    # adds the custom loss to the class
    def call(self, inputs):
        x = inputs[0]
        z_decoded = inputs[1]
        loss = self.vae_loss(x, z_decoded)
        self.add_loss(loss, inputs=inputs)
        return x

y = CustomVariationalLayer()([input_img, z_decoded])

vae = Model(input_img, y)
vae.compile(optimizer='rmsprop', loss=None)
vae.summary()

The input have a shape of (None, 28,28,1) same as MNIST and the the labels has a shape of (None, 10). I knwo i cannot directly concatenate the two values at the input as they are of of different shapes. So to tried to concatenate after flattening the input Convolutional layer. But it is still not working on both the side at the encoder and decoder.

I don't really know how to fix that.

Can anyone help me?

Thanks in advance.