问:
(index):36 Uncaught TypeError: firebase.auth is not a function
index.html code

```<code><html>
    <head>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <script src="http://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="css/style.css" />
        <script src="https://www.gstatic.com/firebasejs/7.14.6/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/7.14.6/firebase-analytics.js"></script>
        <script defer src="https://www.gstatic.com/firebasejs/7.14.6/firebase-auth.js"></script>

    </head>
    <body class="bg-dark">
        <div id="login-card" class="card">
            <div class="card-body">
                <h1>Wallpaper App Admin</h1>

                <form id="login-form">
                    <div class="form-group">
                        <label for="email">Email</label>
                        <input type="email" id="email" class="form-control"/>
                    </div>
                    <div class="form-group">
                        <label for="password">Password</label>
                        <input type="password" id="password" class="form-control"/>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-primary" id="btn-login">Login</button>
                    </div>
                </form>
            </div>
        </div>

        <script src="js/app.js"></script>

        <script>
            firebase.auth().onAuthStateChanged(function(user) {
                if (user) {
                    window.location.href = "admin.html";
                } else {
                    // No user is signed in.
                }
            });
        </script>
    </body>

</html>
</code>```

app.js code

```<code>var firebaseConfig = {
    apiKey: "*******",
    authDomain: "******",
    databaseURL: "*****",
    projectId: "*****",
    storageBucket: "*****",
    messagingSenderId: "*****",
    appId: "*****",
    measurementId: "*****"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

    $("#btn-login").click(function(){

        var email = $("#email").val();
        var password  = $("#password").val();

        var result = firebase.auth().signInWithEmailAndPassword(email, password);
        result.catch(function(error){
            var errorCode = error.code;
            var errorMessage = errror.message;

            console.log(errorCode);
            console.log(errorMessage);
        });
    });
</code>```

Here I am using Firebase authentication sing-in-method as an Email/password. and in Firebase console I enable it. And already I saved one user in the firebase console. But I have an error like this, so my website doesn't work well.
This is the error

```<code>(index):36 Uncaught TypeError: firebase.auth is not a function
    at (index):36
</code>```

It shows this line as an error line, but I cannot understand why.

```<code>firebase.auth().onAuthStateChanged(function(user) {
</code>```

Here I have some problems with this line. The code line is the same in firebase documentation but it doesn't work. I am using Visual Code as a tool for coding this.

答:
Remove the defer from the script tag for the firebase-auth script.  That's causing it to be loaded only after it's required by your code.

```<code><script src="https://www.gstatic.com/firebasejs/7.14.6/firebase-auth.js"></script>
</code>```

Read about defer.

Body:
index.html code

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

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

Wallpaper App Admin

                <form id="login-form">

                        Email
                        <input type="email" id="email" class="form-control"/>

                        Password
                        <input type="password" id="password" class="form-control"/>

                        <button type="button" class="btn btn-primary" id="btn-login">Login</button>

                </form>

app.js code

var firebaseConfig = {
    apiKey: "*******",
    authDomain: "******",
    databaseURL: "*****",
    projectId: "*****",
    storageBucket: "*****",
    messagingSenderId: "*****",
    appId: "*****",
    measurementId: "*****"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

    $("#btn-login").click(function(){

        var email = $("#email").val();
        var password  = $("#password").val();

        var result = firebase.auth().signInWithEmailAndPassword(email, password);
        result.catch(function(error){
            var errorCode = error.code;
            var errorMessage = errror.message;

            console.log(errorCode);
            console.log(errorMessage);
        });
    });

Here I am using Firebase authentication sing-in-method as an Email/password. and in Firebase console I enable it. And already I saved one user in the firebase console. But I have an error like this, so my website doesn't work well.
This is the error

(index):36 Uncaught TypeError: firebase.auth is not a function
    at (index):36

It shows this line as an error line, but I cannot understand why.

firebase.auth().onAuthStateChanged(function(user) {

Here I have some problems with this line. The code line is the same in firebase documentation but it doesn't work. I am using Visual Code as a tool for coding this.

Body:
Remove the defer from the script tag for the firebase-auth script.  That's causing it to be loaded only after it's required by your code.

<script src="https://www.gstatic.com/firebasejs/7.14.6/firebase-auth.js"></script>

Read about defer.


来源: stackexchange

问:
Docker build can't find docker to run tests
I have a NodeJS application that is using ioredis to connect to redis and publish data and other redisy things.

I am trying to write a component test against redis and was able to create a setup/teardown script via jest that runs redis via docker on a random port and tears it down when the tests are done via docker run -d -p 6379 --rm redis and docker stop {containerId}.

This works great locally, but we have the tests running in a multi-stage build in our Dockerfile:
RUN yarn test

which I try to build via docker build . it goes great until it gets to the tests and then complains with the following error - /bin/sh: docker: not found

Hence, Docker is unavailable to the docker-build process to run the tests?

Is there a way to run docker-build to give it the ability to spin up sibling processes during the process?

答:
This smells to me like a "docker-in-docker" situation.

You can't spin up siblings, but you can spawn a container within a container, by doing some tricks: (you might need to do some googling to get it right)

install the docker binaries in the "host container"

mount the docker socket from the actual host inside the "host" container, like so docker run  -v /var/run/docker.sock:/var/run/docker.sock ...

But you won't be able to do it in the build step, so it won't be easy for your case.

I suggest you prepare a dedicated build container capable of running nested containers, which would basically emulate your local env and use that in your CI. Still, you might need to refactor your process a bit make it work.

Good luck :)

ContentLicense: CC BY-SA 4.0


问:
How to Get json data in one another page?
I want to view per user into other page.
How to get user json data using ajax?</p>

```<code>"users": [
{
    {
        "id": "01",
        "name": "Joseph",
        "age": "20",
    },
    {
        "id": "02",
        "name": "Christ",
        "age": "20"
    }
}]

<a href="view.html?id=01"> View Josepth </a>
<a href="view.html?id=02"> View Christ </a>
</code>```

答:
So first you would get the id of the user from the URL (you can use the URL Class) and then depending on how your server is exposing the endpoint you call it using window.prototype.fetch (Fetch API) like so:

(async function() {
  const url = new URL("http://view.html?id=02");

  const { searchParams } = url;

  const userId = searchParams.get("id");

  const userData = await fetch(`https://yourapi.com/user/${userId}`);

  console.log(userData);
})()

```

<p>Hope it helps, notice that since you didnt provide me with information on how to request this data (how does the server that provides data exposes its data - its API) I just wildly guessed you send a <code>GET</code> with the user id as query params.</p>

<p>Since you already told me above that you have a <code>data.json</code> all you need is to get the user id from the URL and then filter the parsed json like so:</p>

```const data = JSON.parse(require('./data.json'));

const url = new URL("http://view.html?id=02");

const { searchParams } = url;

const userId = searchParams.get("id");

const userData = data.filter((user) => user.id === userId);

// here you should see the object with the data for that specific user Id
console.log(userData);

```

Body:
I want to view per user into other page.
How to get user json data using ajax?

"users": [
{
    {
        "id": "01",
        "name": "Joseph",
        "age": "20",
    },
    {
        "id": "02",
        "name": "Christ",
        "age": "20"
    }
}]

 View Josepth
 View Christ

Body:
So first you would get the id of the user from the URL (you can use the URL Class) and then depending on how your server is exposing the endpoint you call it using window.prototype.fetch (Fetch API) like so:

(async function() {
  const url = new URL("http://view.html?id=02");

  const { searchParams } = url;

  const userId = searchParams.get("id");

  const userData = await fetch(`https://yourapi.com/user/${userId}`);

  console.log(userData);
})()

Hope it helps, notice that since you didnt provide me with information on how to request this data (how does the server that provides data exposes its data - its API) I just wildly guessed you send a GET with the user id as query params.

Since you already told me above that you have a data.json all you need is to get the user id from the URL and then filter the parsed json like so:

const data = JSON.parse(require('./data.json'));

const url = new URL("http://view.html?id=02");

const { searchParams } = url;

const userId = searchParams.get("id");

const userData = data.filter((user) => user.id === userId);

// here you should see the object with the data for that specific user Id
console.log(userData);


问:
Why are JavaScript classes not considered "real" classes? (compared to Python, Java, etc.)
Why are JavaScript classes considered not "real" compared to those in a "standard" class-based languages such as Java? I know that JavaScript classes use prototypes under the hood, but doesn't Java code compile down to getfield,invokevirtual etc. that perform dynamic lookups as well? Other than the fact that prototypes are regular objects that can be modified arbitrarily at run time and that you can't implement access control or multiple inheritance with prototypes, how are Java' classes fundamentally different from JavaScript's?

答:
Because JavaScript doesn't have classes; it's a prototypE-based OOPL.

The syntactic sugar of ES6 classes adds no additional functionality to ES5. Classes are implemented on top of its native OOP paradigm: prototypal inheritance can mimic classical inheritance, the reverse is not true (with caveats).

You may actually be asking a duplicate of this question, with the (yet another) caveat that points are applicable to varying degrees depending on which specific languages are being discussed (e.g., Ruby's classes and instances are a lot different than Java's.)

Access control and multiple inheritance are orthogonal discussions, e.g., Self has (prioritized) multiple inheritance, you could implement access control in Lua via metatables/metafunctions, etc.


问:
How to do Region Blocks for Code Folding in android studio with Flutter
I can do region blocks in android studio like this.

```<code>//region Description

Your code here

//endregion
</code>```

But how to the same with flutter ?

答:
In the IntelliJ or Android Studio IDE, you can use REGION folding as written in your question, works fine.
REGION folding also works with //#region (both tested in the IntelliJ IDE CE 2019.3.3 and Android Studio IDE 3.4.1):

// with and without spaces after double slashes
//#region Description
Your code here
//#endregion

// #region Description
Your code here
// #endregion

```

<p>This was also described in the Dart-Code/Dart-Code repository in this issue at GitHub</p>

<p>Off topic:
If someone else prefers to use VSCode then I can recommend the extension #region folding for VS Code. There you can configure the folding comment for each language as you wish.</p>

```"maptz.regionfolder": {
     "[dart]": {
         "foldStart": "// #region [NAME]", // or whatever you like, e.g.`// #some_tag#`
         ...
     }
}
```

Body:
I can do region blocks in android studio like this.

//region Description

Your code here

//endregion

But how to the same with flutter ?

Body:
In the IntelliJ or Android Studio IDE, you can use REGION folding as written in your question, works fine.
REGION folding also works with //#region (both tested in the IntelliJ IDE CE 2019.3.3 and Android Studio IDE 3.4.1):

// with and without spaces after double slashes
//#region Description
Your code here
//#endregion

// #region Description
Your code here
// #endregion

This was also described in the Dart-Code/Dart-Code repository in this issue at GitHub

Off topic:
If someone else prefers to use VSCode then I can recommend the extension #region folding for VS Code. There you can configure the folding comment for each language as you wish.

"maptz.regionfolder": {
     "[dart]": {
         "foldStart": "// #region [NAME]", // or whatever you like, e.g.`// #some_tag#`
         ...
     }
}


问:
How does escaping a literal dot work for sed
The following sed command

```<code>echo '.' | sed "s/\\./foo/"
</code>```

substitutes . with foo, as expected. However, if we escape the non-alphanumeric . in the above command

```<code>echo '.' | sed "s/\\\./foo/"
</code>```

prints barely ., whereas foo is expected. sed should match the character . literally, but it doesn't. I cannot understand what is happening with the dot. I believe that I should simply put a backslash in front of every non-alphanumeric character in bash, if a string is double-quoted. A dot is a non-alphanumeric character so what is wrong about escaping it and why does it produce a different result?

答:
In your second one, the . is still a literal dot, but the regular expression only replaces the two-character sequence \. (not . by itself) with foo:

```<code>$ echo '=\.=' | sed "s/\\\./foo/"
=foo=
</code>```

Body:
The following sed command

echo '.' | sed "s/\\./foo/"

substitutes . with foo, as expected. However, if we escape the non-alphanumeric . in the above command

echo '.' | sed "s/\\\./foo/"

prints barely ., whereas foo is expected. sed should match the character . literally, but it doesn't. I cannot understand what is happening with the dot. I believe that I should simply put a backslash in front of every non-alphanumeric character in bash, if a string is double-quoted. A dot is a non-alphanumeric character so what is wrong about escaping it and why does it produce a different result?

Body:
In your second one, the . is still a literal dot, but the regular expression only replaces the two-character sequence \. (not . by itself) with foo:

$ echo '=\.=' | sed "s/\\\./foo/"
=foo=


问:
Counting the balance factor for AVL trees
Hello everyone!

I can't get the idea of how we count a balance factor for nodes in AVL tree. Can somebody explain it?

Here's the code of counting the balance, that I found:

```<code>size_t height() const
        {
            size_t left_h = (left == nullptr) ? 0 : left->height();
            size_t right_h = (right == nullptr) ? 0 : right->height();
            return left_h < right_h ? right_h + 1 : left_h + 1;
        }

        signed char balance()
        {
            size_t left_h = (left == nullptr) ? 0 : left->height();
            size_t right_h = (right == nullptr) ? 0 : right->height();
            return right_h - left_h;
        }
</code>```

Also, here is the example of AVL tree with counted balances:

Thanks in advance!

答:
As Wikipedia states

In a binary tree, the balance factor of a node is defined to be the height difference of its two-child sub-trees.

So, in order to calculate the balance of a node, you have to calculate the heights of its children.

Let's analyze the code which calculates balance:

```<code>signed char balance()
{
    // calculate height of the children
    // check whether left is absent, if yes: 0, else calculate height on left
    size_t left_h = (left == nullptr) ? 0 : left->height();
    // the same with right
    size_t right_h = (right == nullptr) ? 0 : right->height();

    // return the difference of heights of the right child and the left child
    return right_h - left_h;
}
</code>```

Body:
Hello everyone!

I can't get the idea of how we count a balance factor for nodes in AVL tree. Can somebody explain it?

Here's the code of counting the balance, that I found:

size_t height() const
        {
            size_t left_h = (left == nullptr) ? 0 : left->height();
            size_t right_h = (right == nullptr) ? 0 : right->height();
            return left_h < right_h ? right_h + 1 : left_h + 1;
        }

        signed char balance()
        {
            size_t left_h = (left == nullptr) ? 0 : left->height();
            size_t right_h = (right == nullptr) ? 0 : right->height();
            return right_h - left_h;
        }

Also, here is the example of AVL tree with counted balances:

Thanks in advance!

Body:
As Wikipedia states

In a binary tree, the balance factor of a node is defined to be the height difference of its two-child sub-trees.

So, in order to calculate the balance of a node, you have to calculate the heights of its children.

Let's analyze the code which calculates balance:

signed char balance()
{
    // calculate height of the children
    // check whether left is absent, if yes: 0, else calculate height on left
    size_t left_h = (left == nullptr) ? 0 : left->height();
    // the same with right
    size_t right_h = (right == nullptr) ? 0 : right->height();

    // return the difference of heights of the right child and the left child
    return right_h - left_h;
}


问:
Discrete seekbar in Android app?
I would like to create a seekbar for an Android app that allows the user to select a value between -5 and 5 (which maps to "strongly disagree" and "strongly agree"). How do I make a seekbar with discrete values? or is there a better UI widget I could use for this?

Thanks.

答:
Just use the material components library with something like:

```<code><com.google.android.material.slider.Slider
    android:stepSize="1"
    android:valueFrom="-5"
    android:valueTo="5"
    />
</code>```

ContentLicense: CC BY-SA 3.0

Title: Discrete seekbar in Android app?

Body:
Just use the material components library with something like:

<com.google.android.material.slider.Slider
    android:stepSize="1"
    android:valueFrom="-5"
    android:valueTo="5"
    />


问:
Speech Service Token Duration Extension Issue
I need to keep a Speech Service alive for a long period of time.

Speech Service tokens last 10 minutes by default.

Hence a service duration extension is required.

Thought about the following approaches:

1 - User token generation parameter that would allow its duration extension.

2 - Catch the token expiration exception in my code and request a new token whiteout forcing my bot to restart.

Couldn't find a solution for it yet though.

My bot app always break with a failed: HTTP Authentication failed; no valid credentials available message after the token expires.

Here is my bot code:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>FTD Bit_Bot</title>
</head>
<body style="background-color: #fff; background-image: url('img/FTDBackground.jpg');">
    <div id="chatbot" role="main"
         data-cb-width="320px"
         data-cb-height="400px"
         data-cb-border="1px solid #ededed"
         data-cb-border-radius="0px"
         data-cb-background-color="white"
         data-cb-position="fixed"
         data-cb-right="40px"
         data-cb-bottom="100px"
         data-cb-zIndex="1"
         data-cb-bubble-background="rgba(217, 217, 217, 0.15)"
         data-cb-bubble-from-user-background="#e22e2c"
         data-cb-bubble-from-user-text-color="white"
         data-cb-bubble-max-width="600"
         data-cb-bot-avatar-image="http://demo.radical-thinking.net/bella/microsoft/chat-assets/img/Chat-in-day-Workshop-Icon.png"
         data-cb-hide-send-box="false"
         data-cb-hide-upload-button="true"
         data-cb-send-box-button-color="#e22e2c"
         data-cb-send-box-button-color-on-disabled="#CCC"
         data-cb-send-box-button-color-on-focus="#333"
         data-cb-send-box-button-color-on-hover="#333"
         data-cb-send-box-height="30"
         data-cb-suggested-action-text-color="black"
         data-cb-suggested-action-border="solid 2px #e22e2c"
         data-cb-suggested-action-height="30">
    </div>
    <!-- Include ajax library for speech service token request call -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <!-- Include webchat client functionality (https://github.com/Microsoft/BotFramework-WebChat) -->
    <!-- Change to the latest directory to stop the 'No renderer for this activity' error. However the avatar won't show -->
    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js" charset="utf-8"></script>
    <script>
        var chatbot = document.getElementById('chatbot');

        // Style modifications
        const styleOptions = {

            // Colors
            bubbleBackground: chatbot.dataset.cbBubbleBackground,
            bubbleFromUserBackground: chatbot.dataset.cbBubbleFromUserBackground,
            bubbleFromUserTextColor: chatbot.dataset.cbBubbleFromUserTextColor,
            bubbleMaxWidth: parseInt(chatbot.dataset.cbBubbleMaxWidth), // maximum width of text message

            // Avatar
            botAvatarImage: chatbot.dataset.cbBotAvatarImage,
            userAvatarInitials: '',

            // Send box
            hideSendBox: JSON.parse(chatbot.dataset.cbHideSendBox),
            hideUploadButton: JSON.parse(chatbot.dataset.cbHideUploadButton),
            sendBoxButtonColor: chatbot.dataset.cbSendBoxButtonColor,
            sendBoxButtonColorOnDisabled: chatbot.dataset.cbSendBoxButtonColorOnDisabled,
            sendBoxButtonColorOnFocus: chatbot.dataset.cbSendBoxButtonColorOnFocus,
            sendBoxButtonColorOnHover: chatbot.dataset.cbSendBoxButtonColorOnHover,
            sendBoxHeight: parseInt(chatbot.dataset.cbSendBoxHeight),

            // Suggested actions
            suggestedActionTextColor: chatbot.dataset.cbSuggestedActionTextColor,
            suggestedActionBorder: chatbot.dataset.cbSuggestedActionBorder,
            suggestedActionHeight: parseInt(chatbot.dataset.cbSuggestedActionHeight),

        }
    </script>
    <script>
        var chatbot = document.getElementById("chatbot");

        //style tag start
        var script = {
            id: 'chatbotStyle',
            type: 'text/css',
            style: document.createElement('style'),
            content: '@import url("https://fonts.googleapis.com/css?family=Roboto:300,400,600"); ::-webkit-scrollbar{width:10px}::-webkit-scrollbar-track{background:#f1f1f1}::-webkit-scrollbar-thumb{background:#888}::-webkit-scrollbar-thumb:hover{background:#555} #chatbot{ font-family: Roboto, sans-serif; font-weight: 400; position: fixed; right: 10px; bottom: 20px; text-align: center; } #chatbot img{ margin: auto; } #chatbot small{ display: block; font-size: 9px; } .initLaunchPad{ cursor: pointer; text-align: center; transition: .4s all; } .botHeader{min-height:40px;background:#ededed;border-radius:6px 6px 0 0;display:flex;justify-content:space-between;align-items:center;padding:4px} .botHeader img{float:left;width:32px;height:32px; border-radius:50%;background-color:#f9f9f9}.botHeader h5{float:left;padding:0!important;margin:4px 0 3px 6px} .botHeader h5 small{font-size: 12px;} .botHeader > div{width:40%;display:flex;align-items:center;text-align:left;height:32px} #botClose{cursor:pointer;font-size:12px;font-weight:600;padding:6px 8px;border-radius:4px;background-color:#e22e2c;color:#fff; } #botContainer{ display: none; border-radius: 8px; border:1px solid #cbcbcb; transition:.4s all; width: 310px; height: 420px; max-width:420px; max-height: 420px; margin-bottom: 4px; } #botBody{ height: 366px; } ',
            append: function () {
                this.style.type = this.type;
                this.style.appendChild(document.createTextNode(this.content));
                document.head.appendChild(this.style);
            }
        }; script.append();
        //style tag end

        //initLaunchPad started
        var initLaunchPad = document.createElement('div');
        initLaunchPad.classList.add('initLaunchPad');
        var initBotIcon = document.createElement('img');
        initBotIcon.src = "https://farm5.staticflickr.com/4876/39891228293_13c532f352_o.gif";
        initBotIcon.width = 86;
        initLaunchPad.appendChild(initBotIcon);
        chatbot.appendChild(initLaunchPad);

        $(function getSpeechAuthToken() {
            var params = {
                // Request parameters
            };

            $.ajax({
                url: "https://brazilsouth.api.cognitive.microsoft.com/sts/v1.0/issuetoken" + $.param(params),
                beforeSend: function (xhrObj) {
                    // Request headers
                    xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "XXXXXX");
                },
                type: "POST",
                // Request body
                data: "{body}",
            })
                .done(function (data) {
                    speechAuthToken = data;
                })
                .fail(function () {
                    alert("error");
                });
        });
        initBotIcon.addEventListener('click', function (e) {
            e.preventDefault();
            initLaunchPad.style.display = "none";
            botContainer.style.display = "block";

            /*Call bot API*/
            (async function () {

                const searchParams = new URLSearchParams(window.location.search);

                //Speech Service Token Generation
                const subscriptionKey = 'XXXXXX';
                const region = 'brazilsouth';
                let webSpeechPonyfillFactory;

                //Speech Service Setting
                webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
                    credentials: {
                        authorizationToken: speechAuthToken,
                        region: region
                    }
                });

                //Direct-Line BotToken Generation
                const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate', { method: 'POST', headers: { Authorization: 'Bearer ' + 'XXXXXX' } });
                const { token } = await res.json();

                window.WebChat.renderWebChat({
                    directLine: window.WebChat.createDirectLine({ token }),
                    store,
                    userID: "User",
                    styleOptions,
                    locale: 'pt-BR',
                    selectVoice: (voices, activity) =>
                        activity.locale === 'pt-BR'
                            ? voices.find(({ name }) => /Daniel/iu.test(name))
                            : voices.find(({ name }) => /Daniel/iu.test(name)) ||
                            voices.find(({ name }) => /Daniel/iu.test(name)),
                    webSpeechPonyfillFactory
                }, document.getElementById('botBody'));
                document.querySelector('#botBody > *').focus();

                var mainTag = chatbot.getElementsByClassName('main')[0];
                mainTag.style.borderTop = chatbot.dataset.cbBorder;
            })().catch(err => console.error(err));

            //Bot Message Exchange Setting
            const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
                if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
                    dispatch({
                        type: 'WEB_CHAT/SEND_EVENT',
                        payload: {
                            name: 'userName',
                            value: Paul
                        }
                    });
                }
                return next(action);
            });

        //initLaunchPad ended

        var botContainer = document.createElement('div');
        botContainer.id = "botContainer";

        var botHeader = document.createElement('div');
        botHeader.classList.add('botHeader');

        var botClose = document.createElement('a');
        botClose.id = "botClose";
        botClose.innerText = "X";
        botClose.title = "Close";
        botHeader.innerHTML = "<div><img src='" + chatbot.dataset.cbBotAvatarImage + "'/> <h5>Bit_Bot <small>FTD Educação</small> </div></h5>";
        botHeader.appendChild(botClose);

        botClose.addEventListener('click', function (e) {
            e.preventDefault();
            initLaunchPad.style.display = "";
            botContainer.style.display = "none";
            return false;
        });

        botContainer.appendChild(botHeader);

        var botBody = document.createElement('div');
        botBody.id = "botBody";
        botContainer.appendChild(botBody);

        var poweredBy = document.createElement('div');
        poweredBy.innerHTML = "<small>Powered by <img src='http://ainetw.com/img/icon.png' width=12 /> AI Networks</small>";

        chatbot.appendChild(botContainer);
        chatbot.appendChild(poweredBy);
    </script>
</body>
</html>
</code>```

I unsuccessfully managed to catch the error in following parts of the code.

1) In the speech service setting.

```<code> //Speech Service Setting
        try {
           webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
           credentials: {
               authorizationToken: speechAuthToken,
               region: region
           }
        });
        } catch (error) {
            console.log('Error Speech Service');
            console.log(error);
            //Refreshes token
            getSpeechAuthToken();
            webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
                credentials: {
                    authorizationToken: speechAuthToken,
                    region: region
                }
            });
        }
</code>```

2) In the Webchat setting.

```<code>window.WebChat.renderWebChat({
            directLine: window.WebChat.createDirectLine({ token }),
            store,
            //userID: "Randomly Generated by the Webchat",
            styleOptions,
            locale: 'pt-BR',
            selectVoice: (voices, activity) =>
                activity.locale === 'pt-BR'
                    ? voices.find(({ name }) => /Daniel/iu.test(name))
                    : voices.find(({ name }) => /Daniel/iu.test(name)) ||
                    voices.find(({ name }) => /Daniel/iu.test(name)),
            webSpeechPonyfillFactory
        }, document.getElementById('botBody'));
        document.querySelector('#botBody > *').focus();

        var mainTag = chatbot.getElementsByClassName('main')[0];
        mainTag.style.borderTop = chatbot.dataset.cbBorder;
    })().catch(err =>
        {
            console.log('Error Webchat');
        console.log(error);
        //Refreshes token
        getSpeechAuthToken();
            if (err && err.status === 401) {
                speechAuthToken = speechAuthToken();
                webSpeechPonyfillFactory = window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
                    credentials: {
                        authorizationToken: speechAuthToken,
                        region: region
                    }
                 });
            }
        }
    );
</code>```

How could we avoid the token expiration issue?

Thx

答:
From the Cognitive Services Speech Service docs,

Each access token is valid for 10 minutes. You can get a new token at any time, however, to minimize network traffic and latency, we recommend using the same token for nine minutes.

In my setup, I run a "token" server locally (can be deployed, too), running Restify, that I make my various token generating API service calls from. In the Restify token server, I have setup my own APIs I can call from Web Chat. When I call my token server API, the service API is called, fetching the token, and returns it to Web Chat.

In this way, I solve two problems at once. One, my service's secret is safe on the server side and, two, I can setup a setInterval() that calls the API in question in Web Chat before the token would expire.

tokenServer.js

const path = require('path');
const restify = require('restify');
const request = require('request');

const bodyParser = require('body-parser');
const corsMiddleware = require('restify-cors-middleware');

const cors = corsMiddleware({
    origins: ['*']
});

const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });

// Create HTTP server.
const server = restify.createServer();
server.pre(cors.preflight);
server.use(cors.actual);
server.use(bodyParser.json({
    extended: false
}));

server.post('/speechservices/token', async (req, res) => {
    const options = {
        // method: 'POST',
        uri: `https://${ process.env.SPEECH_SERVICES_REGION }.api.cognitive.microsoft.com/sts/v1.0/issueToken`,
        headers: {
            'Ocp-Apim-Subscription-Key': process.env.SPEECH_SERVICES_SUBSCRIPTION_KEY
        }
    };
    request.post(options, (error, response, body) => {
        if (!error && response.statusCode < 300) {
            body = { region: process.env.SPEECH_SERVICES_REGION, authorizationToken: body };
            res.send({
                authorizationToken: body.authorizationToken,
                region: body.region
            });
            console.log(`Someone requested a speech token...(${ response.statusCode })`);
        } else if (response.statusCode >= 400 && response.statusCode < 500) {
            res.send({ statusCode: response.statusCode, error: "CS's speech token API returned error" });
        } else if (response.statusCode >= 500) {
            res.status(response.statusCode);
            res.send({ statusCode: response.statusCode, error: "CS's speech token API couldn't be reached" });
        }
    });
});
```

<p><strong>Web Chat</strong> - I set the region value on the service side and simply return it with the token.</p>

<pre class="lang-js prettyprint-override"><code>setInterval(() => {
  const fetchPromise =  fetch(
  `http://localhost:3500/speechservices/token`, { method: 'POST' } );

  return fetchPromise.then(async res => {
    if ( res.status === 200 ) {
      const { authorizationToken, region, error: error } = await res.json();
      credentials['authorizationToken'] = authorizationToken;
      credentials['region'] = region;

      return credentials;
    } else {
      console.log( `Speech Services: ${ error }` )
    }
  });
}, 540000); // Is set to 9 minutes
</code>```

Hope of help!

Body:
I need to keep a Speech Service alive for a long period of time.

Speech Service tokens last 10 minutes by default.

Hence a service duration extension is required.

Thought about the following approaches:

1 - User token generation parameter that would allow its duration extension.

2 - Catch the token expiration exception in my code and request a new token whiteout forcing my bot to restart.

Couldn't find a solution for it yet though.

My bot app always break with a failed: HTTP Authentication failed; no valid credentials available message after the token expires.

Here is my bot code:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>FTD Bit_Bot</title>

    <div id="chatbot" role="main"
         data-cb-width="320px"
         data-cb-height="400px"
         data-cb-border="1px solid #ededed"
         data-cb-border-radius="0px"
         data-cb-background-color="white"
         data-cb-position="fixed"
         data-cb-right="40px"
         data-cb-bottom="100px"
         data-cb-zIndex="1"
         data-cb-bubble-background="rgba(217, 217, 217, 0.15)"
         data-cb-bubble-from-user-background="#e22e2c"
         data-cb-bubble-from-user-text-color="white"
         data-cb-bubble-max-width="600"
         data-cb-bot-avatar-image="http://demo.radical-thinking.net/bella/microsoft/chat-assets/img/Chat-in-day-Workshop-Icon.png"
         data-cb-hide-send-box="false"
         data-cb-hide-upload-button="true"
         data-cb-send-box-button-color="#e22e2c"
         data-cb-send-box-button-color-on-disabled="#CCC"
         data-cb-send-box-button-color-on-focus="#333"
         data-cb-send-box-button-color-on-hover="#333"
         data-cb-send-box-height="30"
         data-cb-suggested-action-text-color="black"
         data-cb-suggested-action-border="solid 2px #e22e2c"
         data-cb-suggested-action-height="30">

I unsuccessfully managed to catch the error in following parts of the code.

1) In the speech service setting.

 //Speech Service Setting
        try {
           webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
           credentials: {
               authorizationToken: speechAuthToken,
               region: region
           }
        });
        } catch (error) {
            console.log('Error Speech Service');
            console.log(error);
            //Refreshes token
            getSpeechAuthToken();
            webSpeechPonyfillFactory = await window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
                credentials: {
                    authorizationToken: speechAuthToken,
                    region: region
                }
            });
        }

2) In the Webchat setting.

window.WebChat.renderWebChat({
            directLine: window.WebChat.createDirectLine({ token }),
            store,
            //userID: "Randomly Generated by the Webchat",
            styleOptions,
            locale: 'pt-BR',
            selectVoice: (voices, activity) =>
                activity.locale === 'pt-BR'
                    ? voices.find(({ name }) => /Daniel/iu.test(name))
                    : voices.find(({ name }) => /Daniel/iu.test(name)) ||
                    voices.find(({ name }) => /Daniel/iu.test(name)),
            webSpeechPonyfillFactory
        }, document.getElementById('botBody'));
        document.querySelector('#botBody > *').focus();

        var mainTag = chatbot.getElementsByClassName('main')[0];
        mainTag.style.borderTop = chatbot.dataset.cbBorder;
    })().catch(err =>
        {
            console.log('Error Webchat');
        console.log(error);
        //Refreshes token
        getSpeechAuthToken();
            if (err && err.status === 401) {
                speechAuthToken = speechAuthToken();
                webSpeechPonyfillFactory = window.WebChat.createCognitiveServicesSpeechServicesPonyfillFactory({
                    credentials: {
                        authorizationToken: speechAuthToken,
                        region: region
                    }
                 });
            }
        }
    );

How could we avoid the token expiration issue?

Thx

Body:
From the Cognitive Services Speech Service docs,

Each access token is valid for 10 minutes. You can get a new token at any time, however, to minimize network traffic and latency, we recommend using the same token for nine minutes.

In my setup, I run a "token" server locally (can be deployed, too), running Restify, that I make my various token generating API service calls from. In the Restify token server, I have setup my own APIs I can call from Web Chat. When I call my token server API, the service API is called, fetching the token, and returns it to Web Chat.

In this way, I solve two problems at once. One, my service's secret is safe on the server side and, two, I can setup a setInterval() that calls the API in question in Web Chat before the token would expire.

tokenServer.js

const path = require('path');
const restify = require('restify');
const request = require('request');

const bodyParser = require('body-parser');
const corsMiddleware = require('restify-cors-middleware');

const cors = corsMiddleware({
    origins: ['*']
});

const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });

// Create HTTP server.
const server = restify.createServer();
server.pre(cors.preflight);
server.use(cors.actual);
server.use(bodyParser.json({
    extended: false
}));

server.post('/speechservices/token', async (req, res) => {
    const options = {
        // method: 'POST',
        uri: `https://${ process.env.SPEECH_SERVICES_REGION }.api.cognitive.microsoft.com/sts/v1.0/issueToken`,
        headers: {
            'Ocp-Apim-Subscription-Key': process.env.SPEECH_SERVICES_SUBSCRIPTION_KEY
        }
    };
    request.post(options, (error, response, body) => {
        if (!error && response.statusCode < 300) {
            body = { region: process.env.SPEECH_SERVICES_REGION, authorizationToken: body };
            res.send({
                authorizationToken: body.authorizationToken,
                region: body.region
            });
            console.log(`Someone requested a speech token...(${ response.statusCode })`);
        } else if (response.statusCode >= 400 && response.statusCode < 500) {
            res.send({ statusCode: response.statusCode, error: "CS's speech token API returned error" });
        } else if (response.statusCode >= 500) {
            res.status(response.statusCode);
            res.send({ statusCode: response.statusCode, error: "CS's speech token API couldn't be reached" });
        }
    });
});

Web Chat - I set the region value on the service side and simply return it with the token.

setInterval(() => {
  const fetchPromise =  fetch(
  `http://localhost:3500/speechservices/token`, { method: 'POST' } );

  return fetchPromise.then(async res => {
    if ( res.status === 200 ) {
      const { authorizationToken, region, error: error } = await res.json();
      credentials['authorizationToken'] = authorizationToken;
      credentials['region'] = region;

      return credentials;
    } else {
      console.log( `Speech Services: ${ error }` )
    }
  });
}, 540000); // Is set to 9 minutes

Hope of help!


问:
Opening Realm files of format version 0 is not supported by this version of Realm
We have been using Realm from the past year, We recently upgraded the application from V6.1.0 to V7.0.0, post this upgrade we are witnessing the crash mentioned, we are using Kotlin for application development with Realm java and lastly, we have enabled DB encryption

```<code>java.lang.RuntimeException: Unable to create application com.myapp.Application: io.realm.exceptions.RealmFileException: Opening Realm files of format version 0 is not supported by this version of Realm (Database has an unsupported version and cannot be upgraded
Exception backtrace:
(/data/data/com.myapp.Application:/files/myapp.realm) in /Users/cm/Realm/realm-java-release/realm/realm-library/src/main/cpp/io_realm_internal_OsSharedRealm.cpp line 107 Kind: FORMAT_UPGRADE_REQUIRED.
at io.realm.internal.OsSharedRealm.nativeGetSharedRealm(Native Method)
at io.realm.internal.OsSharedRealm.(OsSharedRealm.java:175)
at io.realm.internal.OsSharedRealm.getInstance(OsSharedRealm.java:251)
at io.realm.BaseRealm.(BaseRealm.java:137)
at io.realm.BaseRealm.(BaseRealm.java:104)
at io.realm.Realm.(Realm.java:163)
at io.realm.Realm.createInstance(Realm.java:499)
at io.realm.RealmCache.createInstance(RealmCache.java:507)
at io.realm.RealmCache.doCreateRealmOrGetFromCache(RealmCache.java:473)
at io.realm.RealmCache.createRealmOrGetFromCache(RealmCache.java:414)
at io.realm.Realm.getDefaultInstance(Realm.java:407)```

```

答:
7.0.o is still in BETA, I believe they will add support for migration when it hits stable.
Also I would not recommend use it for production in beta phase.</p>

Body:
We have been using Realm from the past year, We recently upgraded the application from V6.1.0 to V7.0.0, post this upgrade we are witnessing the crash mentioned, we are using Kotlin for application development with Realm java and lastly, we have enabled DB encryption

java.lang.RuntimeException: Unable to create application com.myapp.Application: io.realm.exceptions.RealmFileException: Opening Realm files of format version 0 is not supported by this version of Realm (Database has an unsupported version and cannot be upgraded
Exception backtrace:
(/data/data/com.myapp.Application:/files/myapp.realm) in /Users/cm/Realm/realm-java-release/realm/realm-library/src/main/cpp/io_realm_internal_OsSharedRealm.cpp line 107 Kind: FORMAT_UPGRADE_REQUIRED.
at io.realm.internal.OsSharedRealm.nativeGetSharedRealm(Native Method)
at io.realm.internal.OsSharedRealm.(OsSharedRealm.java:175)
at io.realm.internal.OsSharedRealm.getInstance(OsSharedRealm.java:251)
at io.realm.BaseRealm.(BaseRealm.java:137)
at io.realm.BaseRealm.(BaseRealm.java:104)
at io.realm.Realm.(Realm.java:163)
at io.realm.Realm.createInstance(Realm.java:499)
at io.realm.RealmCache.createInstance(RealmCache.java:507)
at io.realm.RealmCache.doCreateRealmOrGetFromCache(RealmCache.java:473)
at io.realm.RealmCache.createRealmOrGetFromCache(RealmCache.java:414)
at io.realm.Realm.getDefaultInstance(Realm.java:407)```


问:
Transactional annotation avoids services being mocked
I have a drools rule file which uses service classes in the rules. So one rule does something like this:

eval(countryService.getCountryById(1) != null)

In a validationservice that is annotated with @service and @Transactional(propagation=Propagation.SUPPORTS) the drools file is used in a statelessKnowledgebase and facts are added that should be used in the drool. Once that is done the session.execute(facts) is invoked and the rule engine starts.

In order to test the rules I would like to stub the countryService.getCountryById(). No big problem using mockito. Done this for other service that use a drools setup as well and it worked fine. However in this particular case the countryService was not stubbed and I couldn't figure out why. After spending a lot of time and checking my code I found that having @Transactional above the service or lacking this annotation made the difference. Lacking the @Transaction made mockito mock the countryservice without any problem, having the @transactional in place caused mockito to fail (without any error or hint) injecting the mock so the original countryservice object was used.

My question is why this annotation causes this problem. Why can't mockito inject the mocks when @Transactional is set? I've noticed that mockito is failing as when I debug and inspect the countryService when it is being added as global to the drools session I see the following difference when I inspect the countryservice in my debugwindow:

with @transactional: countryService has the value CountryService$$EnhancerByCGLIB$$b80dbb7b

without @transactional:countryService has the value CountryService$$EnhancerByMockitoWithCGLIB$$27f34dc1

In addition with @transactional my breakpoint in the countryservice methode getCountryById is found and the debugger stops at that breakpoint, but without the @transactional my breakpoint is skipped as mockito bypasses it.

ValidationService:

```<code>@Service
@Transactional(propagation=Propagation.SUPPORTS)
public class ValidationService
{
  @Autowired
  private CountryService countryService;

  public void validateFields(Collection<Object> facts)
  {
    KnowledgeBase knowledgeBase = (KnowledgeBase)AppContext.getApplicationContext().getBean(knowledgeBaseName);
    StatelessKnowledgeSession session = knowledgeBase.newStatelessKnowledgeSession();
    session.setGlobal("countryService", countryService);
    session.execute(facts);

  }
</code>```

And the test class:

```<code>public class TestForeignAddressPostalCode extends BaseTestDomainIntegration
{

  private final Collection<Object> postalCodeMinLength0 = new ArrayList<Object>();

  @Mock
  protected CountryService countryService;

  @InjectMocks
  private ValidationService level2ValidationService;

  @BeforeMethod(alwaysRun=true)
  protected void setup()
  {
    // Get the object under test (here the determination engine)
    level2ValidationService = (ValidationService) getAppContext().getBean("validationService");
    // and replace the services as documented above.
    MockitoAnnotations.initMocks(this);

    ForeignAddress foreignAddress = new ForeignAddress();
    foreignAddress.setCountryCode("7029");
    foreignAddress.setForeignPostalCode("foreign");

    // mock country to be able to return a fixed id
    Country country = mock(Country.class);
    foreignAddress.setLand(country);
    doReturn(Integer.valueOf(1)).when(country).getId();

    doReturn(country).when(countryService).getCountryById(anyInt());

    ContextualAddressBean context = new ContextualAddressBean(foreignAddress, "", AddressContext.CORRESPONDENCE_ADDRESS);
    postalCodeMinLength0.add(context);
  }

  @Test
  public void PostalCodeMinLength0_ExpectError()
  {
    // Execute
    level2ValidationService.validateFields(postalCodeMinLength0, null);

  }
</code>```

Any idea what to do if I want to keep this @transactional annotation but also be able to stub the countryservice methodes?

regards,

Michael

答:
The exist an Spring utility called AopTestUtils in the Spring Test module.

```<code>public static <T> T getUltimateTargetObject(Object candidate)
</code>```

Get the ultimate target object of the supplied candidate object,
  unwrapping not only a top-level proxy but also any number of nested
  proxies. If the supplied candidate is a Spring proxy, the ultimate
  target of all nested proxies will be returned; otherwise, the
  candidate will be returned as is.

You can inject a mock or spy and unproxy the class during the test to arrange mocks or verify

Body:
I have a drools rule file which uses service classes in the rules. So one rule does something like this:

eval(countryService.getCountryById(1) != null)

In a validationservice that is annotated with @service and @Transactional(propagation=Propagation.SUPPORTS) the drools file is used in a statelessKnowledgebase and facts are added that should be used in the drool. Once that is done the session.execute(facts) is invoked and the rule engine starts.

In order to test the rules I would like to stub the countryService.getCountryById(). No big problem using mockito. Done this for other service that use a drools setup as well and it worked fine. However in this particular case the countryService was not stubbed and I couldn't figure out why. After spending a lot of time and checking my code I found that having @Transactional above the service or lacking this annotation made the difference. Lacking the @Transaction made mockito mock the countryservice without any problem, having the @transactional in place caused mockito to fail (without any error or hint) injecting the mock so the original countryservice object was used.

My question is why this annotation causes this problem. Why can't mockito inject the mocks when @Transactional is set? I've noticed that mockito is failing as when I debug and inspect the countryService when it is being added as global to the drools session I see the following difference when I inspect the countryservice in my debugwindow:

with @transactional: countryService has the value CountryService$$EnhancerByCGLIB$$b80dbb7b

without @transactional:countryService has the value CountryService$$EnhancerByMockitoWithCGLIB$$27f34dc1

In addition with @transactional my breakpoint in the countryservice methode getCountryById is found and the debugger stops at that breakpoint, but without the @transactional my breakpoint is skipped as mockito bypasses it.

ValidationService:

@Service
@Transactional(propagation=Propagation.SUPPORTS)
public class ValidationService
{
  @Autowired
  private CountryService countryService;

  public void validateFields(Collection<Object> facts)
  {
    KnowledgeBase knowledgeBase = (KnowledgeBase)AppContext.getApplicationContext().getBean(knowledgeBaseName);
    StatelessKnowledgeSession session = knowledgeBase.newStatelessKnowledgeSession();
    session.setGlobal("countryService", countryService);
    session.execute(facts);

  }

And the test class:

public class TestForeignAddressPostalCode extends BaseTestDomainIntegration
{

  private final Collection<Object> postalCodeMinLength0 = new ArrayList<Object>();

  @Mock
  protected CountryService countryService;

  @InjectMocks
  private ValidationService level2ValidationService;

  @BeforeMethod(alwaysRun=true)
  protected void setup()
  {
    // Get the object under test (here the determination engine)
    level2ValidationService = (ValidationService) getAppContext().getBean("validationService");
    // and replace the services as documented above.
    MockitoAnnotations.initMocks(this);

    ForeignAddress foreignAddress = new ForeignAddress();
    foreignAddress.setCountryCode("7029");
    foreignAddress.setForeignPostalCode("foreign");

    // mock country to be able to return a fixed id
    Country country = mock(Country.class);
    foreignAddress.setLand(country);
    doReturn(Integer.valueOf(1)).when(country).getId();

    doReturn(country).when(countryService).getCountryById(anyInt());

    ContextualAddressBean context = new ContextualAddressBean(foreignAddress, "", AddressContext.CORRESPONDENCE_ADDRESS);
    postalCodeMinLength0.add(context);
  }

  @Test
  public void PostalCodeMinLength0_ExpectError()
  {
    // Execute
    level2ValidationService.validateFields(postalCodeMinLength0, null);

  }

Any idea what to do if I want to keep this @transactional annotation but also be able to stub the countryservice methodes?

regards,

Michael

Body:
The exist an Spring utility called AopTestUtils in the Spring Test module.

public static <T> T getUltimateTargetObject(Object candidate)

Get the ultimate target object of the supplied candidate object,
  unwrapping not only a top-level proxy but also any number of nested
  proxies. If the supplied candidate is a Spring proxy, the ultimate
  target of all nested proxies will be returned; otherwise, the
  candidate will be returned as is.

You can inject a mock or spy and unproxy the class during the test to arrange mocks or verify


问:
Verifying duplicate objects in array of objects using JavaScript
I am having array of objects in a following form,

```<code>let test = [
{
 RowCreationMethod: "excel",
 deviceID: "123ECd9",
 deviceName: "ZENW42NLPC0378",
 devicePrimary: "Yes",
 deviceType: "Laptop",
 employeeID: 101,
 isExists: "No",
 isRescheduled: "No",
 vipUser: "Yes"
 },{
 RowCreationMethod: "excel",
 deviceName: "ZENW42NLPC0378",
 devicePrimary: "Yes",
 deviceType: "Laptop",
 deviceID: "123ECd9",
 employeeID: 101,
 isExists: "No",
 isRescheduled: "No",
 vipUser: "Yes"
 }];
</code>```

I have written following code to check if their exits any duplicate object in my array its working but if I changes the sequence of any object properties then its not working, because in my code I am converting objects to string and verifying it.

Here is my code

```<code>let final = []
test.forEach(x => {
  if(!final.some(y => JSON.stringify(y) === JSON.stringify(x))){
    final.push(x)
  }
})
</code>```

答:
For checking shallow equality, you can use Object.keys to get the keys of both objects, compare their lengths, and then check if each value is equal.

let test = [
{
 RowCreationMethod: "excel",
 deviceID: "123ECd9",
 deviceName: "ZENW42NLPC0378",
 devicePrimary: "Yes",
 deviceType: "Laptop",
 employeeID: 101,
 isExists: "No",
 isRescheduled: "No",
 vipUser: "Yes"
 },{
 RowCreationMethod: "excel",
 deviceName: "ZENW42NLPC0378",
 devicePrimary: "Yes",
 deviceType: "Laptop",
 deviceID: "123ECd9",
 employeeID: 101,
 isExists: "No",
 isRescheduled: "No",
 vipUser: "Yes"
 }];
 let final = [];
test.forEach(x => {
  if(!final.some(y => objectShallowEquals(x,y))){
    final.push(x);
  }
});
console.log(final);
function objectShallowEquals(obj1, obj2){
  const keys = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  if(keys.length != keys2.length) return false;
  for(const key of keys){
   if(!(key in obj2) || obj1[key] !== obj2[key])return false;
  }
  return true;
}```
</div>
</div>
</p>

<p>If you aren't too worried about performance, you can use JSON.stringify on the entries of each object after sorting to compare them.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let test = [
{
 RowCreationMethod: "excel",
 deviceID: "123ECd9",
 deviceName: "ZENW42NLPC0378",
 devicePrimary: "Yes",
 deviceType: "Laptop",
 employeeID: 101,
 isExists: "No",
 isRescheduled: "No",
 vipUser: "Yes"
 },{
 RowCreationMethod: "excel",
 deviceName: "ZENW42NLPC0378",
 devicePrimary: "Yes",
 deviceType: "Laptop",
 deviceID: "123ECd9",
 employeeID: 101,
 isExists: "No",
 isRescheduled: "No",
 vipUser: "Yes"
 }];
 let final = [];
test.forEach(x => {
  if(!final.some(y =>
JSON.stringify(Object.entries(y).sort())===JSON.stringify(Object.entries(x).sort())
)) {
    final.push(x);
  }
});
console.log(final);</code>```

Body:
I am having array of objects in a following form,

let test = [
{
 RowCreationMethod: "excel",
 deviceID: "123ECd9",
 deviceName: "ZENW42NLPC0378",
 devicePrimary: "Yes",
 deviceType: "Laptop",
 employeeID: 101,
 isExists: "No",
 isRescheduled: "No",
 vipUser: "Yes"
 },{
 RowCreationMethod: "excel",
 deviceName: "ZENW42NLPC0378",
 devicePrimary: "Yes",
 deviceType: "Laptop",
 deviceID: "123ECd9",
 employeeID: 101,
 isExists: "No",
 isRescheduled: "No",
 vipUser: "Yes"
 }];

I have written following code to check if their exits any duplicate object in my array its working but if I changes the sequence of any object properties then its not working, because in my code I am converting objects to string and verifying it.

Here is my code

let final = []
test.forEach(x => {
  if(!final.some(y => JSON.stringify(y) === JSON.stringify(x))){
    final.push(x)
  }
})

Body:
For checking shallow equality, you can use Object.keys to get the keys of both objects, compare their lengths, and then check if each value is equal.

let test = [
{
 RowCreationMethod: "excel",
 deviceID: "123ECd9",
 deviceName: "ZENW42NLPC0378",
 devicePrimary: "Yes",
 deviceType: "Laptop",
 employeeID: 101,
 isExists: "No",
 isRescheduled: "No",
 vipUser: "Yes"
 },{
 RowCreationMethod: "excel",
 deviceName: "ZENW42NLPC0378",
 devicePrimary: "Yes",
 deviceType: "Laptop",
 deviceID: "123ECd9",
 employeeID: 101,
 isExists: "No",
 isRescheduled: "No",
 vipUser: "Yes"
 }];
 let final = [];
test.forEach(x => {
  if(!final.some(y => objectShallowEquals(x,y))){
    final.push(x);
  }
});
console.log(final);
function objectShallowEquals(obj1, obj2){
  const keys = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  if(keys.length != keys2.length) return false;
  for(const key of keys){
   if(!(key in obj2) || obj1[key] !== obj2[key])return false;
  }
  return true;
}

If you aren't too worried about performance, you can use JSON.stringify on the entries of each object after sorting to compare them.

let test = [
{
 RowCreationMethod: "excel",
 deviceID: "123ECd9",
 deviceName: "ZENW42NLPC0378",
 devicePrimary: "Yes",
 deviceType: "Laptop",
 employeeID: 101,
 isExists: "No",
 isRescheduled: "No",
 vipUser: "Yes"
 },{
 RowCreationMethod: "excel",
 deviceName: "ZENW42NLPC0378",
 devicePrimary: "Yes",
 deviceType: "Laptop",
 deviceID: "123ECd9",
 employeeID: 101,
 isExists: "No",
 isRescheduled: "No",
 vipUser: "Yes"
 }];
 let final = [];
test.forEach(x => {
  if(!final.some(y =>
JSON.stringify(Object.entries(y).sort())===JSON.stringify(Object.entries(x).sort())
)) {
    final.push(x);
  }
});
console.log(final);


问:
qt gui to display video using Qfiledialogbox and qlabel .here is my code
FIRST CODE
In this code VideoCapture cap is not taking filename (which contains video path) which is obtained after executing QFileDialog i.e. with  cap.open("fileName") ,code is not executing while with cap.open("G:/mixer.avi") ,code is executing . means If video path is directly given in cap.open() then code is executing but it is not taking QFileDialog output i.e. filename as input

```<code>void MainWindow::on_pushButton_clicked()
{
 if(ui->radioButton->isChecked()) {

      QString fileName = QFileDialog::getOpenFileName(this,
          tr("Open Video"), "G://", "All files (*.*);Video files(*.*)");
      ui->lineEdit->setText(fileName);
     VideoCapture cap
    // cap.open("G:/mixer.avi");
     cap.open("fileName");

    connect(timer, SIGNAL(timeout()), this, SLOT(update_window()));
    timer->start(20);}}
    void MainWindow::update_window()
     {
     cap >> frame;

    cvtColor(frame, frame, cv::COLOR_BGR2RGB);

    qt_image = QImage((const unsigned char*) (frame.data), frame.cols, frame.rows,
     QImage::Format_RGB888);

    ui->label->setPixmap(QPixmap::fromImage(qt_image));

    ui->label->resize(ui->label->pixmap()->size());
}
</code>```

SECOND CODE :

In this code with QFileDialogbox, video is displaying but it is not displaying in QLabel.How to add QLabel in QMultimedia.

```<code> void MainWindow::on_pushButton_2_clicked()
    {
    if(ui->radioButton_2->isChecked()) {

    QString fileName = QFileDialog::getOpenFileName(this,
              tr("Open Video"), "G://", "All files (*.*);Video files(*.*)");
     ui->lineEdit->setText(fileName);
       player = new QMediaPlayer;
            vw=new QVideoWidget;
          player->setVideoOutput(vw) ;
          this->setCentralWidget(vw);
           player->setMedia(QUrl::fromLocalFile(fileName));
           vw->show();
          player->play();

}
}
</code>```

答:
VideoCapture(const String &    filename) can take string as input not QString. 2 things needed to do:

First convert QString filename to string

There can be some extra characters in the first places of that string because the filedialog chosen file output little different than which opencv VideoCapture need.

Body:
FIRST CODE
In this code VideoCapture cap is not taking filename (which contains video path) which is obtained after executing QFileDialog i.e. with  cap.open("fileName") ,code is not executing while with cap.open("G:/mixer.avi") ,code is executing . means If video path is directly given in cap.open() then code is executing but it is not taking QFileDialog output i.e. filename as input

void MainWindow::on_pushButton_clicked()
{
 if(ui->radioButton->isChecked()) {

      QString fileName = QFileDialog::getOpenFileName(this,
          tr("Open Video"), "G://", "All files (*.*);Video files(*.*)");
      ui->lineEdit->setText(fileName);
     VideoCapture cap
    // cap.open("G:/mixer.avi");
     cap.open("fileName");

    connect(timer, SIGNAL(timeout()), this, SLOT(update_window()));
    timer->start(20);}}
    void MainWindow::update_window()
     {
     cap >> frame;

    cvtColor(frame, frame, cv::COLOR_BGR2RGB);

    qt_image = QImage((const unsigned char*) (frame.data), frame.cols, frame.rows,
     QImage::Format_RGB888);

    ui->label->setPixmap(QPixmap::fromImage(qt_image));

    ui->label->resize(ui->label->pixmap()->size());
}

SECOND CODE :

In this code with QFileDialogbox, video is displaying but it is not displaying in QLabel.How to add QLabel in QMultimedia.

 void MainWindow::on_pushButton_2_clicked()
    {
    if(ui->radioButton_2->isChecked()) {

    QString fileName = QFileDialog::getOpenFileName(this,
              tr("Open Video"), "G://", "All files (*.*);Video files(*.*)");
     ui->lineEdit->setText(fileName);
       player = new QMediaPlayer;
            vw=new QVideoWidget;
          player->setVideoOutput(vw) ;
          this->setCentralWidget(vw);
           player->setMedia(QUrl::fromLocalFile(fileName));
           vw->show();
          player->play();

}
}


问:
Can we run flutter app wirelessly on iOS device?
In Xcode I'm able to connect iOS device wirelessly but not in android studio. Can anyone know how to do in android studio if it is possible?</p>

答:
Not yet, but it will be implemented soon.
Take a look at this issue.</p>


问:
Creating percentiles of data set
I've tried using the quantile function but it doesn't do as intended.

I also used new function

```<code> percentile <- function(Df, percentile = 50)
   {
   Df_Names <- names(Df)
  percentile <- percentile/100
  f <- function(x, p) c(NA, x[-length(x)]) + p * c(NA, diff(x))
  while(length(which(!is.na(Df[[length(Df)]]))) > 1)
  {
Df <- cbind(Df, f(Df[[length(Df)]], percentile))
}
setNames(Df, c(Df_Names, paste0("v", 1:(length(df) - length(df_Names)))))
}

Output=data.frame(pecentile(df, percentile = 50))
</code>```

Assume we are finding the P50 where I mention percentiles. Note: I used excel to calculate the percentiles with the percentile function, but the results should be the same using R. In most instances there are thousands of data points per column and R would be more time efficient to calculate them.

an example data set would be

```<code>  Date           data
  2020-01-01      49.5
  2020-02-01      49.7
  2020-03-14      48.5
  2020-05-02      50.2
</code>```

I'm trying to have the script result in a percentile output using the column before it as a starting point. However columns after V1 their percentiles are calculated differently than V1. As shown here

V1 Calculation

Where 49.35 is the percentile calculation in excel using 48.5 and 50.2 in the red box and 49.1 is the result of using 49.7 and 48.5 in the blue box that overlaps the red box.

and V2 calculation

where 49.225 is the result of using 49.1 and 49.35 in the red box while 49.35 is the result of using 49.6, 49.1 and 49.35 in the blue box that overlaps the red box.

V2 calculation starts off the same, but the calculations above it include the adjacent cell plus the cells below the adjacent cells, which the script doesn't do.

The result from this script should be:

```<code>  Date           data    V1     V2      V3
  2020-01-01      49.5   49.6   49.35    49.2875
  2020-02-01      49.7   49.1   49.225
  2020-03-14      48.5   49.35
  2020-05-02      50.2
</code>```

Note2: The script purposes is to be in a loop until the script creates the final column in this instance the final column is V3. but in reality it may go up to V800 or more

Then when this is done bring down the results without altering the output, resulting in:

```<code>  Date           data    V1     V2      V3
  2020-01-01      49.5   NA     NA      NA
  2020-02-01      49.7   49.6   NA      NA
  2020-03-14      48.5   49.1   49.35   NA
  2020-05-02      50.2   49.35  49.225  49.2875
</code>```

NOTE: The function works well to calculate the P50 in V1 which is fine, but it drops the ball with V2, V3 etc.

答:
I would use a for loop here, because the starting set renews with each iteration.

```<code>res <- NULL
res[[1]] <- dat$data

for (i in 2:4) {
  res[[i]] <- mapply(function(y)
    quantile(res[[i - 1]][y], .5),
    Map(function(x) x:length(res[[i - 1]]), 1:(length(res[[i - 1]]) - 1)))
}
sapply(res, `length<-`, 4)
#      [,1]  [,2]   [,3]    [,4]
# [1,] 49.5 49.60 49.600 49.5625
# [2,] 49.7 49.70 49.525      NA
# [3,] 48.5 49.35     NA      NA
# [4,] 50.2    NA     NA      NA
</code>```

However, I get different results with the logic you provided.

Data:

```<code>dat <- read.table(header=T, text='Date           data
2020-01-01      49.5
2020-02-01      49.7
2020-03-14      48.5
2020-05-02      50.2')
</code>```

Title: Creating percentiles of data set

Body:
I've tried using the quantile function but it doesn't do as intended.

I also used new function

 percentile <- function(Df, percentile = 50)
   {
   Df_Names <- names(Df)
  percentile <- percentile/100
  f <- function(x, p) c(NA, x[-length(x)]) + p * c(NA, diff(x))
  while(length(which(!is.na(Df[[length(Df)]]))) > 1)
  {
Df <- cbind(Df, f(Df[[length(Df)]], percentile))
}
setNames(Df, c(Df_Names, paste0("v", 1:(length(df) - length(df_Names)))))
}

Output=data.frame(pecentile(df, percentile = 50))

Assume we are finding the P50 where I mention percentiles. Note: I used excel to calculate the percentiles with the percentile function, but the results should be the same using R. In most instances there are thousands of data points per column and R would be more time efficient to calculate them.

an example data set would be

  Date           data
  2020-01-01      49.5
  2020-02-01      49.7
  2020-03-14      48.5
  2020-05-02      50.2

I'm trying to have the script result in a percentile output using the column before it as a starting point. However columns after V1 their percentiles are calculated differently than V1. As shown here

V1 Calculation

Where 49.35 is the percentile calculation in excel using 48.5 and 50.2 in the red box and 49.1 is the result of using 49.7 and 48.5 in the blue box that overlaps the red box.

and V2 calculation

where 49.225 is the result of using 49.1 and 49.35 in the red box while 49.35 is the result of using 49.6, 49.1 and 49.35 in the blue box that overlaps the red box.

V2 calculation starts off the same, but the calculations above it include the adjacent cell plus the cells below the adjacent cells, which the script doesn't do.

The result from this script should be:

  Date           data    V1     V2      V3
  2020-01-01      49.5   49.6   49.35    49.2875
  2020-02-01      49.7   49.1   49.225
  2020-03-14      48.5   49.35
  2020-05-02      50.2

Note2: The script purposes is to be in a loop until the script creates the final column in this instance the final column is V3. but in reality it may go up to V800 or more

Then when this is done bring down the results without altering the output, resulting in:

  Date           data    V1     V2      V3
  2020-01-01      49.5   NA     NA      NA
  2020-02-01      49.7   49.6   NA      NA
  2020-03-14      48.5   49.1   49.35   NA
  2020-05-02      50.2   49.35  49.225  49.2875

NOTE: The function works well to calculate the P50 in V1 which is fine, but it drops the ball with V2, V3 etc.

Body:
I would use a for loop here, because the starting set renews with each iteration.

res <- NULL
res[[1]] <- dat$data

for (i in 2:4) {
  res[[i]] <- mapply(function(y)
    quantile(res[[i - 1]][y], .5),
    Map(function(x) x:length(res[[i - 1]]), 1:(length(res[[i - 1]]) - 1)))
}
sapply(res, `length<-`, 4)
#      [,1]  [,2]   [,3]    [,4]
# [1,] 49.5 49.60 49.600 49.5625
# [2,] 49.7 49.70 49.525      NA
# [3,] 48.5 49.35     NA      NA
# [4,] 50.2    NA     NA      NA

However, I get different results with the logic you provided.

Data:

dat <- read.table(header=T, text='Date           data
2020-01-01      49.5
2020-02-01      49.7
2020-03-14      48.5
2020-05-02      50.2')


问:
componentDidMount life cycle method is called twice in react
In my react application, the initial API call is made twice when the application gets loaded. I looked at the Network tab in Chrome->inpsect, the 'initiator' call stack is showing that the first call is made from VM123000_bundle.js whereas the second call is just made from the actual bundle.js. The same code working in the prod environment except that the Webpack (1.x -> 4.x) and React (15.x->16.x) modules are upgraded. Could someone please point what is the VM123000_bundle.js and why it gets called the first time when the home page gets loaded?

AppHome.js

```<code>componentDidMount () {
const appdata = this.props.ebayHome.toJS();
this.props.getAccounts("/EName/Account/, ActionTypes.ACCOUNT_DATA, JSON.stringify(accountMutualParams));
}
</code>```

答:
It is an issue with HtmlWebpackPlugin which actually injects all the generated bundle references into the existing HTML page. There are two ways to fix it.

skip injection in webpack config

remove the bundle references in the HTML page

Body:
In my react application, the initial API call is made twice when the application gets loaded. I looked at the Network tab in Chrome->inpsect, the 'initiator' call stack is showing that the first call is made from VM123000_bundle.js whereas the second call is just made from the actual bundle.js. The same code working in the prod environment except that the Webpack (1.x -> 4.x) and React (15.x->16.x) modules are upgraded. Could someone please point what is the VM123000_bundle.js and why it gets called the first time when the home page gets loaded?

AppHome.js

componentDidMount () {
const appdata = this.props.ebayHome.toJS();
this.props.getAccounts("/EName/Account/, ActionTypes.ACCOUNT_DATA, JSON.stringify(accountMutualParams));
}


问:
How to make a list of numbers from a txt file in python?
I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

```<code>L=[52,2,103,592,2090,34452,0,1]
</code>```

The best I have managed to do so far is:

```<code>txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)
</code>```

which returns:

```<code>L=['52','2','103','592','2090','34452','0','1']

</code>```

but the ' around the numbers bother me.

Any help is appreciated.

答:
You can convert them to integers using int:

```<code>txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(int(line.rstrip()))
txtfile.close()
print(L)

[52, 2, 103, 592, 2090, 34452, 0, 1]
</code>```

Body:
I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

L=[52,2,103,592,2090,34452,0,1]

The best I have managed to do so far is:

txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)

which returns:

L=['52','2','103','592','2090','34452','0','1']

but the ' around the numbers bother me.

Any help is appreciated.

Body:
You can convert them to integers using int:

txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(int(line.rstrip()))
txtfile.close()
print(L)

[52, 2, 103, 592, 2090, 34452, 0, 1]


问:
Azure SQL Server BACPAC import failed
whenever i try to import BACPAC on local sql server I am getting below error message:

```<code>TITLE: Microsoft SQL Server Management Studio
------------------------------

Could not import package.
Warning SQL0: The source contains users that rely on an external authentication provider that is not supported by the target. These users will be treated as users without logins.
Warning SQL72012: The object [DB_NAME_Data] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.
Warning SQL72012: The object [DB_NAME_Log] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.
Error SQL72014: .Net SqlClient Data Provider: Msg 33161, Level 15, State 1, Line 1 Database master keys without password are not supported in this version of SQL Server.
Error SQL72045: Script execution error.  The executed script:
CREATE MASTER KEY;

 (Microsoft.SqlServer.Dac)

------------------------------
BUTTONS:

OK
------------------------------
</code>```

All the previously reported issues on SO are not same as this one. Does anyone faced the same issue before?

答:
Try running this against your master database (right click on the server name in SSMS -> New Query)

```<code>sp_configure 'contained database authentication', 1;
GO
RECONFIGURE;
GO
</code>```

After this, you can go through the import bacpac wizard again and the issue should be resolved.

Title: Azure SQL Server BACPAC import failed

Body:
whenever i try to import BACPAC on local sql server I am getting below error message:

TITLE: Microsoft SQL Server Management Studio
------------------------------

Could not import package.
Warning SQL0: The source contains users that rely on an external authentication provider that is not supported by the target. These users will be treated as users without logins.
Warning SQL72012: The object [DB_NAME_Data] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.
Warning SQL72012: The object [DB_NAME_Log] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.
Error SQL72014: .Net SqlClient Data Provider: Msg 33161, Level 15, State 1, Line 1 Database master keys without password are not supported in this version of SQL Server.
Error SQL72045: Script execution error.  The executed script:
CREATE MASTER KEY;

 (Microsoft.SqlServer.Dac)

------------------------------
BUTTONS:

OK
------------------------------

All the previously reported issues on SO are not same as this one. Does anyone faced the same issue before?

Body:
Try running this against your master database (right click on the server name in SSMS -> New Query)

sp_configure 'contained database authentication', 1;
GO
RECONFIGURE;
GO

After this, you can go through the import bacpac wizard again and the issue should be resolved.


问:
tox does not run sphinx
I want to run the following command from tox.

```<code>python setup.py build_sphinx -b html
</code>```

I have configured my setup.py to build the docs when I run the above command from the console (I checked that from the console, that command makes doc).

Then I have edited my tox.ini as follows:

```<code>.....
[testenv:sphinx]
command = python setup.py build_sphinx -b html
</code>```

setup.cfg as follows:

```<code>[build_sphinx]
project = project_name
source-dir = module_name/doc
build-dir = module_name/doc/build
</code>```

But when I run tox -e sphinx, tox exits with a successful message, but no docs generated.

Can somebody help me with this?

答: I'd not recommend using setuptools to build documentation. Consider instead using sphinx directly as tox itself does at https://github.com/tox-dev/tox/blob/master/tox.ini#L48-L53 Alternatively please post the exact output of the run with -vvv, or make the project publicly available for us to try it too.</p>

Title: tox does not run sphinx

Body:
I want to run the following command from tox.

python setup.py build_sphinx -b html

I have configured my setup.py to build the docs when I run the above command from the console (I checked that from the console, that command makes doc).

Then I have edited my tox.ini as follows:

.....
[testenv:sphinx]
command = python setup.py build_sphinx -b html

setup.cfg as follows:

[build_sphinx]
project = project_name
source-dir = module_name/doc
build-dir = module_name/doc/build

But when I run tox -e sphinx, tox exits with a successful message, but no docs generated.

Can somebody help me with this?


问:
include(helveticab.php): failed to open stream in FPDF
I tried to create pdf using FPDF
and I run the code in localserver.
It did not produced any errors.

I created a VM instance and Installed Xampp in it using Google Cloud Platform.

Then I moved all my local files to the server path /opt/lampp/htdocs.

After this when I try to run my php file it produced error like this.

```<code>    Warning: include(helveticab.php): failed to open stream: No such file or directory in
    /opt/lampp/lib/php/fpdf.php on line 1145

    Warning: include(): Failed opening 'helveticab.php' for inclusion
    (include_path='.:/opt/lampp/lib/php') in /opt/lampp/lib/php/fpdf.php on line 1145

    FPDF error: Could not include font definition file
</code>```

What is the way to get rid of this error?

答:
My FPDF font folder located in server at /opt/lampp/htdocs/Server/fpdf/font.

So I added define('FPDF_FONTPATH','/opt/lampp/htdocs/Server/fpdf/font'); in my php file.
This fixed my issue.

Body:
I tried to create pdf using FPDF
and I run the code in localserver.
It did not produced any errors.

I created a VM instance and Installed Xampp in it using Google Cloud Platform.

Then I moved all my local files to the server path /opt/lampp/htdocs.

After this when I try to run my php file it produced error like this.

    Warning: include(helveticab.php): failed to open stream: No such file or directory in
    /opt/lampp/lib/php/fpdf.php on line 1145

    Warning: include(): Failed opening 'helveticab.php' for inclusion
    (include_path='.:/opt/lampp/lib/php') in /opt/lampp/lib/php/fpdf.php on line 1145

    FPDF error: Could not include font definition file

What is the way to get rid of this error?


问:
How can I use "docker run --user" but with root priviliges
I have a Docker image which contains an analysis pipeline. To run this pipeline, I need to provide input data and I want to keep the outputs. This pipeline must be able to be run by other users than myself, on their own laptops.

Briefly, my root (/) folder structure is as follows:

```<code>total 72
drwxr-xr-x   1 root   root 4096 May 29 15:38 bin
drwxr-xr-x   2 root   root 4096 Feb  1 17:09 boot
drwxr-xr-x   5 root   root  360 Jun  1 15:31 dev
drwxr-xr-x   1 root   root 4096 Jun  1 15:31 etc
drwxr-xr-x   2 root   root 4096 Feb  1 17:09 home
drwxr-xr-x   1 root   root 4096 May 29 15:49 lib
drwxr-xr-x   2 root   root 4096 Feb 24 00:00 lib64
drwxr-xr-x   2 root   root 4096 Feb 24 00:00 media
drwxr-xr-x   2 root   root 4096 Feb 24 00:00 mnt
drwxr-xr-x   1 root   root 4096 Mar 12 19:38 opt
drwxr-xr-x   1 root   root 4096 Jun  1 15:24 pipeline
dr-xr-xr-x 615 root   root    0 Jun  1 15:31 proc
drwx------   1 root   root 4096 Mar 12 19:38 root
drwxr-xr-x   3 root   root 4096 Feb 24 00:00 run
drwxr-xr-x   1 root   root 4096 May 29 15:38 sbin
drwxr-xr-x   2 root   root 4096 Feb 24 00:00 srv
dr-xr-xr-x  13 root   root    0 Apr 29 10:14 sys
drwxrwxrwt   1 root   root 4096 Jun  1 15:25 tmp
drwxr-xr-x   1 root   root 4096 Feb 24 00:00 usr
drwxr-xr-x   1 root   root 4096 Feb 24 00:00 var
</code>```

The pipeline scripts are in /pipeline and are packaged into the image with a "COPY. /pipeline" instruction in my Dockerfile.

For various reasons, this pipeline (which is a legacy pipeline) is set up so that the input data must be in a folder such /pipeline/project. To run my pipeline, I use:

```<code>docker run --rm --mount type=bind,source=$(pwd),target=/pipeline/project --user "$(id -u):$(id -g)" pipelineimage:v1
</code>```

In other words, I mount a folder with the data to /pipeline/project. I found I needed to use the --user to insure the output files would have the correct permissions - i.e. I would have read/write/exec access on my host computer after the container exits.

The pipeline runs but I have one issue: one particular software used by the pipeline automatically tries to produce (and I can't change that) 1 folder in $HOME (so / - which I showed above) and 1 folder in my WORKDIR (which I have set up in my Dockerfile to be /pipeline). These attempts fails, and I'm guessing it's because I am not running the pipeline as root. But I need to use --user to make sure my outputs have the correct permissions - i.e. that I don't require sudo rights to read these outputs etc.

My question is: how am I meant to handle this? It seems that by using --user, I have the correct permissions set for the mounted folder (/pipeline/projects) where many output files are successfully made, no problems there. But how can I ensure the other 2 folders are correctly made outside of that mount?

I have tried the following but not success:

Doing "COPY -chown myhostuid:mygroupid" . pipeline/". This works but I have to hardcode my uid and gid so that won't work if another colleague tries to run the image.

Adding a new user with sudo rights and making it run the image: "RUN useradd -r newuser -g sudo" (I also tried using the "root" group but no success). This just gives me outputs which require sudo rights to read/write/exec. Which is not what I want.

Am I missing something? I don't understand why it's "easy" to handle permissions for a mounted folder but so much harder for the other folders in a container. Thanks.

答:
If your software doesn't rely on relative paths (~/, ./), you can just set $HOME and WORKDIR to a directory that any user can write:

```<code>ENV HOME=/tmp
WORKDIR /tmp
</code>```

If you can't do that, you can pass the uid/gid via the environment to an entrypoint script running as root, chown/chmod as necessary, then drop privileges to run the pipeline (runuser, su, sudo, setuidgid).

For example (untested):

entrypoint.sh

```<code>#!/bin/bash

[[ -v "RUN_UID" ]] || { echo "unset RUN_UID" >&2; exit 1; }
[[ -v "RUN_GID" ]] || { echo "unset RUN_GID" >&2; exit 1; }

# chown, chmod, set env, etc.
chown $RUN_UID:$RUN_GID "/path/that/requires/write/permissions"
export HOME=/tmp

# Run the pipeline as a non-root user.
sudo -E -u "#$RUN_UID" -g "#$RUN_GID" /path/to/pipeline
</code>```

Dockerfile

```<code>...
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
</code>```

Finally, pass the user and group IDs via the environment when running:

docker run --rm --mount type=bind,source=$(pwd),target=/pipeline/project -e RUN_UID=$(id -u) -e RUN_GID=$(id -g) pipelineimage:v1

Body:
I have a Docker image which contains an analysis pipeline. To run this pipeline, I need to provide input data and I want to keep the outputs. This pipeline must be able to be run by other users than myself, on their own laptops.

Briefly, my root (/) folder structure is as follows:

total 72
drwxr-xr-x   1 root   root 4096 May 29 15:38 bin
drwxr-xr-x   2 root   root 4096 Feb  1 17:09 boot
drwxr-xr-x   5 root   root  360 Jun  1 15:31 dev
drwxr-xr-x   1 root   root 4096 Jun  1 15:31 etc
drwxr-xr-x   2 root   root 4096 Feb  1 17:09 home
drwxr-xr-x   1 root   root 4096 May 29 15:49 lib
drwxr-xr-x   2 root   root 4096 Feb 24 00:00 lib64
drwxr-xr-x   2 root   root 4096 Feb 24 00:00 media
drwxr-xr-x   2 root   root 4096 Feb 24 00:00 mnt
drwxr-xr-x   1 root   root 4096 Mar 12 19:38 opt
drwxr-xr-x   1 root   root 4096 Jun  1 15:24 pipeline
dr-xr-xr-x 615 root   root    0 Jun  1 15:31 proc
drwx------   1 root   root 4096 Mar 12 19:38 root
drwxr-xr-x   3 root   root 4096 Feb 24 00:00 run
drwxr-xr-x   1 root   root 4096 May 29 15:38 sbin
drwxr-xr-x   2 root   root 4096 Feb 24 00:00 srv
dr-xr-xr-x  13 root   root    0 Apr 29 10:14 sys
drwxrwxrwt   1 root   root 4096 Jun  1 15:25 tmp
drwxr-xr-x   1 root   root 4096 Feb 24 00:00 usr
drwxr-xr-x   1 root   root 4096 Feb 24 00:00 var

The pipeline scripts are in /pipeline and are packaged into the image with a "COPY. /pipeline" instruction in my Dockerfile.

For various reasons, this pipeline (which is a legacy pipeline) is set up so that the input data must be in a folder such /pipeline/project. To run my pipeline, I use:

docker run --rm --mount type=bind,source=$(pwd),target=/pipeline/project --user "$(id -u):$(id -g)" pipelineimage:v1

In other words, I mount a folder with the data to /pipeline/project. I found I needed to use the --user to insure the output files would have the correct permissions - i.e. I would have read/write/exec access on my host computer after the container exits.

The pipeline runs but I have one issue: one particular software used by the pipeline automatically tries to produce (and I can't change that) 1 folder in $HOME (so / - which I showed above) and 1 folder in my WORKDIR (which I have set up in my Dockerfile to be /pipeline). These attempts fails, and I'm guessing it's because I am not running the pipeline as root. But I need to use --user to make sure my outputs have the correct permissions - i.e. that I don't require sudo rights to read these outputs etc.

My question is: how am I meant to handle this? It seems that by using --user, I have the correct permissions set for the mounted folder (/pipeline/projects) where many output files are successfully made, no problems there. But how can I ensure the other 2 folders are correctly made outside of that mount?

I have tried the following but not success:

Doing "COPY -chown myhostuid:mygroupid" . pipeline/". This works but I have to hardcode my uid and gid so that won't work if another colleague tries to run the image.

Adding a new user with sudo rights and making it run the image: "RUN useradd -r newuser -g sudo" (I also tried using the "root" group but no success). This just gives me outputs which require sudo rights to read/write/exec. Which is not what I want.

Am I missing something? I don't understand why it's "easy" to handle permissions for a mounted folder but so much harder for the other folders in a container. Thanks.

Body:
If your software doesn't rely on relative paths (~/, ./), you can just set $HOME and WORKDIR to a directory that any user can write:

ENV HOME=/tmp
WORKDIR /tmp

If you can't do that, you can pass the uid/gid via the environment to an entrypoint script running as root, chown/chmod as necessary, then drop privileges to run the pipeline (runuser, su, sudo, setuidgid).

For example (untested):

entrypoint.sh

#!/bin/bash

[[ -v "RUN_UID" ]] || { echo "unset RUN_UID" >&2; exit 1; }
[[ -v "RUN_GID" ]] || { echo "unset RUN_GID" >&2; exit 1; }

# chown, chmod, set env, etc.
chown $RUN_UID:$RUN_GID "/path/that/requires/write/permissions"
export HOME=/tmp

# Run the pipeline as a non-root user.
sudo -E -u "#$RUN_UID" -g "#$RUN_GID" /path/to/pipeline

Dockerfile

...
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]

Finally, pass the user and group IDs via the environment when running:

docker run --rm --mount type=bind,source=$(pwd),target=/pipeline/project -e RUN_UID=$(id -u) -e RUN_GID=$(id -g) pipelineimage:v1


问:
how to create a DF from a DF based on a condition
My current DF looks like this

```<code>Combinations               Count
1   ('IDLY', 'VADA')       3734
6   ('DOSA', 'IDLY')        2020
9   ('CHAPPATHI', 'DOSA')   1297
10  ('IDLY', 'POORI')       1297
11  ('COFFEE', 'TEA')       1179
13  ('DOSA', 'VADA')        1141
15  ('CHAPPATHI', 'IDLY')   1070
16  ('COFFEE', 'SAMOSA')    1061
17  ('COFFEE', 'IDLY')      1016
18  ('POORI', 'VADA')       1008
</code>```

Lets say I filter by the keyword 'DOSA' from above data frame I get the below OP

```<code>    Combinations           Count
6   ('DOSA', 'IDLY')        2020
9   ('CHAPPATHI', 'DOSA')   1297
13  ('DOSA', 'VADA')        1141
</code>```

But I would like the output to be like the df below(which has ignored the filter key word as its common,

```<code>    Combinations    Count
6   IDLY            2020
9   CHAPPATHI       1297
13  VADA            1141
</code>```

What concept of pandas needs to be used here? How can this be achieved?

答:
you can also try creating a dataframe as a reference , then mask where keyword matches with stack for dropping NaN:

```<code>keyword = 'DOSA'

m = pd.DataFrame(df['Combinations'].tolist(),index=df.index)
c = m.eq(keyword).any(1)
df[m.eq(keyword).any(1)].assign(Combinations=
                         m[c].where(m[c].ne(keyword)).stack().droplevel(1))
</code>```

```<code>   Combinations  Count
6          IDLY   2020
9     CHAPPATHI   1297
13         VADA   1141
</code>```

For string type, you can convert into tuple by:

```<code>import ast
df['Combinations'] = df['Combinations'].apply(ast.literal_eval)
</code>```

Body:
My current DF looks like this

Combinations               Count
1   ('IDLY', 'VADA')       3734
6   ('DOSA', 'IDLY')        2020
9   ('CHAPPATHI', 'DOSA')   1297
10  ('IDLY', 'POORI')       1297
11  ('COFFEE', 'TEA')       1179
13  ('DOSA', 'VADA')        1141
15  ('CHAPPATHI', 'IDLY')   1070
16  ('COFFEE', 'SAMOSA')    1061
17  ('COFFEE', 'IDLY')      1016
18  ('POORI', 'VADA')       1008

Lets say I filter by the keyword 'DOSA' from above data frame I get the below OP

    Combinations           Count
6   ('DOSA', 'IDLY')        2020
9   ('CHAPPATHI', 'DOSA')   1297
13  ('DOSA', 'VADA')        1141

But I would like the output to be like the df below(which has ignored the filter key word as its common,

    Combinations    Count
6   IDLY            2020
9   CHAPPATHI       1297
13  VADA            1141

What concept of pandas needs to be used here? How can this be achieved?

Body:
you can also try creating a dataframe as a reference , then mask where keyword matches with stack for dropping NaN:

keyword = 'DOSA'

m = pd.DataFrame(df['Combinations'].tolist(),index=df.index)
c = m.eq(keyword).any(1)
df[m.eq(keyword).any(1)].assign(Combinations=
                         m[c].where(m[c].ne(keyword)).stack().droplevel(1))

   Combinations  Count
6          IDLY   2020
9     CHAPPATHI   1297
13         VADA   1141

For string type, you can convert into tuple by:

import ast
df['Combinations'] = df['Combinations'].apply(ast.literal_eval)