问:
C - Is there a way to read a single character of user input, and not have the rest "pushed down" to the next request for input?
So, I'm working on a simple hangman game in C, and I have the function read_guess, shown below.

```<code>void read_guess(char *guesses, char *p_current_guess)
{
    int valid_guess = 0;

    // Repeatedly takes input until guess is valid
    while (valid_guess == 0)
    {
        printf(">>> ");
        fgets(p_current_guess, 2, stdin);

        if (!isalpha(*p_current_guess)) printf("Guesses must be alphabetic. Please try again.\n\n");
        else
        {
            valid_guess = 1;

            // Iterates over array of guesses and checks if letter has already been guessed
            for (int i = 0; guesses[i] != '\0'; i++)
            {
                if (guesses[i] == *p_current_guess)
                {
                    printf("You have already guessed this letter. Please try again.\n\n");
                    valid_guess = 0;
                    break;
                }
            }
        }
    }
}
</code>```

I've tried all the standard input functions (including getchar), but with all of them, when an input larger than one character is supplied, instead of taking just the first character and moving on (or asking again), the rest of the input is "pushed back", and the next time input is requested, whether it be because the input contained a non-alphabetic character or the next round begins, the rest of the input is automatically processed. This repeats for each character of the input.

How can I avoid this?

答:
You can discard all input until end-of-line, each time you want to ask for input.</p>

```<code>void skip_to_eol(FILE* f, int c)
{
    while (c != EOF && c != '\n')
        c = fgetc(f);
}
...
    char c = getchar(); // instead of fgets
    skip_to_eol(stdin, c);
</code>```

Body:
So, I'm working on a simple hangman game in C, and I have the function read_guess, shown below.

void read_guess(char *guesses, char *p_current_guess)
{
    int valid_guess = 0;

    // Repeatedly takes input until guess is valid
    while (valid_guess == 0)
    {
        printf(">>> ");
        fgets(p_current_guess, 2, stdin);

        if (!isalpha(*p_current_guess)) printf("Guesses must be alphabetic. Please try again.\n\n");
        else
        {
            valid_guess = 1;

            // Iterates over array of guesses and checks if letter has already been guessed
            for (int i = 0; guesses[i] != '\0'; i++)
            {
                if (guesses[i] == *p_current_guess)
                {
                    printf("You have already guessed this letter. Please try again.\n\n");
                    valid_guess = 0;
                    break;
                }
            }
        }
    }
}

I've tried all the standard input functions (including getchar), but with all of them, when an input larger than one character is supplied, instead of taking just the first character and moving on (or asking again), the rest of the input is "pushed back", and the next time input is requested, whether it be because the input contained a non-alphabetic character or the next round begins, the rest of the input is automatically processed. This repeats for each character of the input.

How can I avoid this?

Body:
You can discard all input until end-of-line, each time you want to ask for input.

void skip_to_eol(FILE* f, int c)
{
    while (c != EOF && c != '\n')
        c = fgetc(f);
}
...
    char c = getchar(); // instead of fgets
    skip_to_eol(stdin, c);


来源: stackexchange

问:
Disapearing Object Instance
I've developed an webservice that uses an object instance in order to do part of the required funcionality.

That object is initialized once when I create the webservice class instance throught the use of the constructor.

Sample:

```public class A {
    private B bInstance;
    public A(){
        bInstance = new B();
    }
}```

Unfortunatelly after a few minutes (20 to 30min maybe), my code starts to return a NullPointerException from that object. It is like somehow that object got garbage collected or destroyed.

What can be the cause of this (apart from the possible human mistake)? Maybe I'm missing something specific to web applications

right now I've started to use the object getter that validates for null pointer and rebuilds the object if needed, but that doesn't feel right

Thanks for any tips you might provide

答:
Possible Serialization issue

It might be possible that your code is being serialized by your application container due to memory issues and that the deserialization process is not correctly creating an instance of B.

OwnerDisplayName: Katanagashi

ContentLicense: CC BY-SA 3.0

Title: Disapearing Object Instance

Body:
I've developed an webservice that uses an object instance in order to do part of the required funcionality.

That object is initialized once when I create the webservice class instance throught the use of the constructor.

Sample:

public class A {
    private B bInstance;
    public A(){
        bInstance = new B();
    }
}

Unfortunatelly after a few minutes (20 to 30min maybe), my code starts to return a NullPointerException from that object. It is like somehow that object got garbage collected or destroyed.

What can be the cause of this (apart from the possible human mistake)? Maybe I'm missing something specific to web applications

right now I've started to use the object getter that validates for null pointer and rebuilds the object if needed, but that doesn't feel right

Thanks for any tips you might provide


问:
Need to show Preview Video Thumbnails while seeking (Like youtube) for iOS
I need to show Video Preview Thumbanils while seeking in AVPlayer.
Just like how youtube shows them. (iOS)
(Also for live streaming) (Solution preferred more for Wowza/Amazon S3)

答:
You can try this:

```<code>extension AVAsset {

    func getPreviewImage(for timeInSeconds: Int = 0) -> UIImage? {
        let imageGenerator = AVAssetImageGenerator(asset: self)
        imageGenerator.requestedTimeToleranceBefore = .zero
        imageGenerator.requestedTimeToleranceAfter = .zero
        imageGenerator.appliesPreferredTrackTransform = true
        guard let cgImage = try? imageGenerator.copyCGImage(at: CMTime(value: CMTimeValue(timeInSeconds), timescale: 1), actualTime: nil) else { return nil }
        return UIImage(cgImage: cgImage)
    }

}
</code>```

You shouldn't get the preview in the main thread.

If you require a series of preview images, you can try this:

If you require a series
  of images, you can achieve far greater efficiency using the
  asynchronous method,
  generateCGImagesAsynchronously(forTimes:completionHandler:), which
  employs decoding efficiencies similar to those used during playback.

ContentLicense: CC BY-SA 4.0

Body:
You can try this:

extension AVAsset {

    func getPreviewImage(for timeInSeconds: Int = 0) -> UIImage? {
        let imageGenerator = AVAssetImageGenerator(asset: self)
        imageGenerator.requestedTimeToleranceBefore = .zero
        imageGenerator.requestedTimeToleranceAfter = .zero
        imageGenerator.appliesPreferredTrackTransform = true
        guard let cgImage = try? imageGenerator.copyCGImage(at: CMTime(value: CMTimeValue(timeInSeconds), timescale: 1), actualTime: nil) else { return nil }
        return UIImage(cgImage: cgImage)
    }

}

You shouldn't get the preview in the main thread.

If you require a series of preview images, you can try this:

If you require a series
  of images, you can achieve far greater efficiency using the
  asynchronous method,
  generateCGImagesAsynchronously(forTimes:completionHandler:), which
  employs decoding efficiencies similar to those used during playback.


问:
Create table using iterative statements in "react" rendering
I try to create a table with two arrays in a state(week_today, week_count) and a repeating sentence when rendering.
I don't know how to use map() function . Please advise.

my code

```<code>    render() {
        const {week_today, week_count} = this.state; // this.state in my array put

        return (
            <div>

                <table class="table">
                    <thead class="thead-dark">
                        <tr>
                            <th scope="col">today</th>
                            <th scope="col">count</th>
                        </tr>
                    </thead>
                    <tbody>
                     //<== here my array table

                    </tbody>

                </table>
            </div>

        )
    }
</code>```

use my arrays

```<code>week_today = [ 01,02,03,04,05]
week_count = [ 1,2,3,4,5]
</code>```

答:
Try below. Just a sample code</p>

```<code>  constructor(props) {
    super(props);
    const week_today = ['01', '02', '03', '04', '05'];
    const week_count = [1, 2, 3, 4, 5];

    this.state = {
      week_today: week_today,
      week_count: week_count
    };
  }
  render() {
   const {week_today, week_count} = this.state; // suggest you to use destructuring your variables:
    return (
      <div>
        <table class="table">
          <thead class="thead-dark">
            <tr>
              <th scope="col">today</th>
              <th scope="col">count</th>
            </tr>
          </thead>
          <tbody>
            {week_today.map((today, index) =>
                <tr key={index}>
                  <td>{today}</td>
                  <td>{week_count[index]}</td>
                </tr>
            )}
          </tbody>

        </table>
      </div>
    )
  }
</code>```

Body:
I try to create a table with two arrays in a state(week_today, week_count) and a repeating sentence when rendering.
I don't know how to use map() function . Please advise.

my code

    render() {
        const {week_today, week_count} = this.state; // this.state in my array put

        return (

                            today
                            count

                     //<== here my array table

        )
    }

use my arrays

week_today = [ 01,02,03,04,05]
week_count = [ 1,2,3,4,5]

Body:
Try below. Just a sample code

  constructor(props) {
    super(props);
    const week_today = ['01', '02', '03', '04', '05'];
    const week_count = [1, 2, 3, 4, 5];

    this.state = {
      week_today: week_today,
      week_count: week_count
    };
  }
  render() {
   const {week_today, week_count} = this.state; // suggest you to use destructuring your variables:
    return (
      <div>
        <table class="table">
          <thead class="thead-dark">
            <tr>
              <th scope="col">today</th>
              <th scope="col">count</th>
            </tr>
          </thead>
          <tbody>
            {week_today.map((today, index) =>
                <tr key={index}>
                  <td>{today}</td>
                  <td>{week_count[index]}</td>
                </tr>
            )}
          </tbody>

        </table>
      </div>
    )
  }


问:
For a service bot, should I go with ChatScript or Rasa?
ChatScript runs fast and from my research it looks like it handles dialogue very well. On the other hand, it appears to have only a single active developer.

Rasa on the other hand, looks much more actively developed.

I guess I'd like to know the trade-off in terms of performance and complexity between the two.

答: Rasa and ChatScript are different approaches. Most of the world does the ML thing. There are limitations to that: http://brilligunderstanding.com/ML.html .  ChatScript does have active developers other than me, but you often wont hear from them. Kore.AI is a bot platform based on ChatScript and running bots for large scale enterprise customers. </p>


问:
Select min date value and calculate date value?
I have a table called "SUMMARYDATA" which has columns "STATUSIN,STATUSOUT,LATECOME" and I want to select min value on column "STATUSIN". And make a condition: IF MIN(STATUSIN) > "08.00 AM" Then LATECOME = MIN(STATUSIN) - "08.00 AM". How to select min date value? And how to calculate MIN(STATUSIN) - "08.00 AM"?

This is my code to display data from database:

```<code>    <asp:Repeater ID="rptrSUMMARYDATA" runat="server">
        <HeaderTemplate>
            <table class="table">
                <thead>
                    <tr>
                        <th>IN</th>
                        <th>OUT</th>
                        <th>LATECOME</th>
                    </tr>
                </thead>
                <tbody>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td><%# Eval("STATUSIN") %></td>
                <td><%# Eval("STATUSOUT") %></td>
                <td><%# Eval("LATECOME") %></td>
            </tr>
        </ItemTemplate>
        <FooterTemplate>
                </tbody>
            </table>
        </FooterTemplate>
    </asp:Repeater>
</code>```

This is my code on backend:

```<code>     private void BindSUMMARYDATARptr()
    {
        String CS = ConfigurationManager.ConnectionStrings["MANHOURConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM SUMMARYDATA", con))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dtDaily = new DataTable();
                    sda.Fill(dtDaily);

                    rptrSUMMARYDATA.DataSource = dtDaily;
                    rptrSUMMARYDATA.DataBind();
                }

            }

        }
    }
</code>```

答:
Can you try this..</p>

```<code>  SELECT  STATUSIN,STATUSOUT, CASE WHEN CAST(STATUSIN AS TIME) > CAST('08:00:00' AS TIME)
           THEN CONVERT(varchar, dateadd(s, -28800 ,STATUSIN), 108)  END AS LATECOME
  FROM SUMMARYDATA
</code>```

Body:
I have a table called "SUMMARYDATA" which has columns "STATUSIN,STATUSOUT,LATECOME" and I want to select min value on column "STATUSIN". And make a condition: IF MIN(STATUSIN) > "08.00 AM" Then LATECOME = MIN(STATUSIN) - "08.00 AM". How to select min date value? And how to calculate MIN(STATUSIN) - "08.00 AM"?

This is my code to display data from database:

    <asp:Repeater ID="rptrSUMMARYDATA" runat="server">
        <HeaderTemplate>

                        IN
                        OUT
                        LATECOME

        </HeaderTemplate>
        <ItemTemplate>

                <%# Eval("STATUSIN") %>
                <%# Eval("STATUSOUT") %>
                <%# Eval("LATECOME") %>

        </ItemTemplate>
        <FooterTemplate>

        </FooterTemplate>
    </asp:Repeater>

This is my code on backend:

     private void BindSUMMARYDATARptr()
    {
        String CS = ConfigurationManager.ConnectionStrings["MANHOURConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM SUMMARYDATA", con))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dtDaily = new DataTable();
                    sda.Fill(dtDaily);

                    rptrSUMMARYDATA.DataSource = dtDaily;
                    rptrSUMMARYDATA.DataBind();
                }

            }

        }
    }

Body:
Can you try this..

  SELECT  STATUSIN,STATUSOUT, CASE WHEN CAST(STATUSIN AS TIME) > CAST('08:00:00' AS TIME)
           THEN CONVERT(varchar, dateadd(s, -28800 ,STATUSIN), 108)  END AS LATECOME
  FROM SUMMARYDATA


问:
React 16 - unable to make a modal render using createPortal
I'm trying to render a loading notification modal while a POST is processing.
It seems like it should be very simple using createPortal but the modal never displays.

I added a div in index with an id of modal:

```<code><body>
    <noscript>
        You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <div id="modal"></div>
</body>
</code>```

Here is the react component.  When the test button is clicked the state of showModal is set to true:

```<code>import React, { Component, Header } from 'react';
import { render } from "react-dom";
import { Row, Col, Button } from 'reactstrap'
import 'bootstrap/dist/css/bootstrap.css';
import ProcessingModal from '../Modals/ProcessingModal';

export class TestModal extends React.Component {

    constructor(props) {
        this.state = {
            showModal: false,
        }
        this.handleShowModal = this.handleShowModal.bind(this);
    }

    handleShowModal() {
        this.setState({ showModal: true });
    }

render() {
        return (
            <div>
                <div className='container-fluid'>
                    <h2 style={{ textAlign: 'center', border: 'none' }}>
                        Header Text
                    </h2>
                    <br />
                    {this.state.showModal ? <ProcessingModal /> : null }
                    <Row>
                        <Col md={6}>
                            <Button onClick={this.handleShowModal} type="button">test</Button>
                        </Col>
                    </Row>
                </div>
            </div>
         );
     }
</code>```

This is the ProcessingModal js:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.css';

const ModalContent = (
    <div className='modal text-center'>
        <div className="spinner-border text-success"><br />
            Loading...
        </div>
    </div>
);

function ProcessingModal(props) {
    return ReactDOM.createPortal(ModalContent, document.querySelector("#modal"));
}

export default ProcessingModal;
</code>```

Where am i going wrong?

答:
Styling was my issue.  The modal style had display: none;
Once that was removed it worked.</p>

Body:
I'm trying to render a loading notification modal while a POST is processing.
It seems like it should be very simple using createPortal but the modal never displays.

I added a div in index with an id of modal:

        You need to enable JavaScript to run this app.

Here is the react component.  When the test button is clicked the state of showModal is set to true:

import React, { Component, Header } from 'react';
import { render } from "react-dom";
import { Row, Col, Button } from 'reactstrap'
import 'bootstrap/dist/css/bootstrap.css';
import ProcessingModal from '../Modals/ProcessingModal';

export class TestModal extends React.Component {

    constructor(props) {
        this.state = {
            showModal: false,
        }
        this.handleShowModal = this.handleShowModal.bind(this);
    }

    handleShowModal() {
        this.setState({ showModal: true });
    }

render() {
        return (

                        Header Text

                    {this.state.showModal ? <ProcessingModal /> : null }
                    <Row>
                        <Col md={6}>
                            <Button onClick={this.handleShowModal} type="button">test</Button>
                        </Col>
                    </Row>

         );
     }

This is the ProcessingModal js:

import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.css';

const ModalContent = (

            Loading...

);

function ProcessingModal(props) {
    return ReactDOM.createPortal(ModalContent, document.querySelector("#modal"));
}

export default ProcessingModal;

Where am i going wrong?


问:
Filesystemwatcher C# high CPU usage
I have created a very simple from example (console) of the filsystemwatcher to listen for changes on a single directory. I have then taken the exact code and used it in a very simple windows form that has just one list box for the console output, but I have spawned it as a thread - the console version uses 0% cpu whereas the same single thread uses 25% ANY Insights as to why ???

THREADED VERSION

```<code> Thread pdfWatcher = new Thread(t => startFileWatcher(pdfStoragePath))
        { IsBackground = false };
        pdfWatcher.Start();
    }

private void startFileWatcher(string pdfOutputPath)
    {
        statusOutput.Items.Add("Starting Thread : File Watcher...");
        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            watcher.Path = pdfOutputPath;
            messageStatusWindow("Watching Path : [" + pdfOutputPath + "] For new PDF's");

            // Watch for changes in LastAccess and LastWrite times, and
            // the renaming of files or directories.
            watcher.NotifyFilter = NotifyFilters.LastWrite;

            // Only watch text files.
            watcher.Filter = "*.pdf";

            // Add event handlers.
            //watcher.Changed += OnChanged;
            watcher.Created += OnCreated;
            //watcher.Deleted += OnChanged;
            //watcher.Renamed += OnRenamed;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press 'q' to quit the sample.");
            messageStatusWindow("Thread Started : File Watcher");
            while (Console.Read() != 'q') ;
        }
    }
</code>```

CONSOLE VERSION

```<code> class Program
{
    static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            // Display the proper way to call the program.
            Console.WriteLine("Usage: FileWatcher.exe (directory)");
            return;
        }

        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            watcher.Path = args[1];
            Console.WriteLine(args[0]);

            // Watch for changes in LastAccess and LastWrite times, and
            // the renaming of files or directories.
            watcher.NotifyFilter = NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.FileName
                                 | NotifyFilters.DirectoryName
                                 | NotifyFilters.Size;

            // Only watch text files.
            watcher.Filter = "*.pdf";

            // Add event handlers.
            watcher.Changed += OnChanged;
            watcher.Created += OnCreated;
            watcher.Deleted += OnChanged;
            watcher.Renamed += OnRenamed;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press 'q' to quit the sample.");
            while (Console.Read() != 'q') ;
        }
</code>```

in a

答: The line while (Console.Read() != 'q') ; is consuming all of your cpu. You must eigther use a message pump (no console application) or some kind of wait mechanism like while(Console.Read()!='g') System.Threading.Thread.Sleep(100);

Title: Filesystemwatcher C# high CPU usage

Body:
I have created a very simple from example (console) of the filsystemwatcher to listen for changes on a single directory. I have then taken the exact code and used it in a very simple windows form that has just one list box for the console output, but I have spawned it as a thread - the console version uses 0% cpu whereas the same single thread uses 25% ANY Insights as to why ???

THREADED VERSION

 Thread pdfWatcher = new Thread(t => startFileWatcher(pdfStoragePath))
        { IsBackground = false };
        pdfWatcher.Start();
    }

private void startFileWatcher(string pdfOutputPath)
    {
        statusOutput.Items.Add("Starting Thread : File Watcher...");
        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            watcher.Path = pdfOutputPath;
            messageStatusWindow("Watching Path : [" + pdfOutputPath + "] For new PDF's");

            // Watch for changes in LastAccess and LastWrite times, and
            // the renaming of files or directories.
            watcher.NotifyFilter = NotifyFilters.LastWrite;

            // Only watch text files.
            watcher.Filter = "*.pdf";

            // Add event handlers.
            //watcher.Changed += OnChanged;
            watcher.Created += OnCreated;
            //watcher.Deleted += OnChanged;
            //watcher.Renamed += OnRenamed;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press 'q' to quit the sample.");
            messageStatusWindow("Thread Started : File Watcher");
            while (Console.Read() != 'q') ;
        }
    }

CONSOLE VERSION

 class Program
{
    static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            // Display the proper way to call the program.
            Console.WriteLine("Usage: FileWatcher.exe (directory)");
            return;
        }

        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            watcher.Path = args[1];
            Console.WriteLine(args[0]);

            // Watch for changes in LastAccess and LastWrite times, and
            // the renaming of files or directories.
            watcher.NotifyFilter = NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.FileName
                                 | NotifyFilters.DirectoryName
                                 | NotifyFilters.Size;

            // Only watch text files.
            watcher.Filter = "*.pdf";

            // Add event handlers.
            watcher.Changed += OnChanged;
            watcher.Created += OnCreated;
            watcher.Deleted += OnChanged;
            watcher.Renamed += OnRenamed;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press 'q' to quit the sample.");
            while (Console.Read() != 'q') ;
        }

in a


问:
.Net Core 3.1 IActionFilter get required param in URL
As the title says i am trying to fetch the required param in my route:

https://localhost:44386/api/Users/c6b44b17-1b05-4ab6-a8c0-6968b4ea1ced

This is my Filter which i put a breakpoint to see what is the value of each.

Unfortunately the first two doesn't have anything even if i specify the key (e.g. Query["_id"]).

The third one fetches the array of route which is correct but i don't want to use the last index value as it feels to be just a hack.

I've seen the docs and i can't find a simpler way below without touching the endpoint routing config and explicitly defining this specific route (since i might end up with tons of routes which might require this same scenario).

Any help will be truly appreciated.

```<code>public class ProfileIsCreatorFilter : Attribute, IActionFilter
{
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var query = context.HttpContext.Request.Query;
            var queryString = context.HttpContext.Request.QueryString;
            var route = context.HttpContext.Request.RouteValues;
        }
}
</code>```

```<code>[HttpGet("{_id}"), Authorize, ProfileIsCreatorFilter]
public ActionResult<User> GetUser(Guid _id)
{
    return Ok();
}
</code>```

I have simplified everything to avoid confusion.

答:
You can access all route specific values in the filter-context. The context contains a RouteData dictionary:

```<code>public override void OnActionExecuting(ActionExecutingContext context) {
    string myvalue = context.RouteData.Values["mykey"];
}
</code>```

You can find more infos to ActionFilters in the docs.

Body:
As the title says i am trying to fetch the required param in my route:

https://localhost:44386/api/Users/c6b44b17-1b05-4ab6-a8c0-6968b4ea1ced

This is my Filter which i put a breakpoint to see what is the value of each.

Unfortunately the first two doesn't have anything even if i specify the key (e.g. Query["_id"]).

The third one fetches the array of route which is correct but i don't want to use the last index value as it feels to be just a hack.

I've seen the docs and i can't find a simpler way below without touching the endpoint routing config and explicitly defining this specific route (since i might end up with tons of routes which might require this same scenario).

Any help will be truly appreciated.

public class ProfileIsCreatorFilter : Attribute, IActionFilter
{
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var query = context.HttpContext.Request.Query;
            var queryString = context.HttpContext.Request.QueryString;
            var route = context.HttpContext.Request.RouteValues;
        }
}

[HttpGet("{_id}"), Authorize, ProfileIsCreatorFilter]
public ActionResult<User> GetUser(Guid _id)
{
    return Ok();
}

I have simplified everything to avoid confusion.

Body:
You can access all route specific values in the filter-context. The context contains a RouteData dictionary:

public override void OnActionExecuting(ActionExecutingContext context) {
    string myvalue = context.RouteData.Values["mykey"];
}

You can find more infos to ActionFilters in the docs.


问:
Pandas ignores set encoding in read_csv?
Using Linux, Pandas 1.0.1 and Python 3.6 I get a strange error in production:

```<code>
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/app-root/lib/python3.6/site-packages/luigi/worker.py", line 199, in run
    new_deps = self._run_get_new_deps()
  File "/opt/app-root/lib/python3.6/site-packages/luigi/worker.py", line 141, in _run_get_new_deps
    task_gen = self.task.run()
  File "/opt/app-root/src/import_validation/validate_csv.py", line 275, in run
    validate(temp_csv, self.query_id)
  File "/opt/app-root/src/import_validation/validate_csv.py", line 263, in validate
    pandas.read_csv(path, encoding='latin1', sep=sep)
  File "/opt/app-root/lib/python3.6/site-packages/pandas/io/parsers.py", line 676, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/opt/app-root/lib/python3.6/site-packages/pandas/io/parsers.py", line 454, in _read
    data = parser.read(nrows)
  File "/opt/app-root/lib/python3.6/site-packages/pandas/io/parsers.py", line 1133, in read
    ret = self._engine.read(nrows)
  File "/opt/app-root/lib/python3.6/site-packages/pandas/io/parsers.py", line 2037, in read
    data = self._reader.read(nrows)
  File "pandas/_libs/parsers.pyx", line 859, in pandas._libs.parsers.TextReader.read
  File "pandas/_libs/parsers.pyx", line 874, in pandas._libs.parsers.TextReader._read_low_memory
  File "pandas/_libs/parsers.pyx", line 951, in pandas._libs.parsers.TextReader._read_rows
  File "pandas/_libs/parsers.pyx", line 1083, in pandas._libs.parsers.TextReader._convert_column_data
  File "pandas/_libs/parsers.pyx", line 1136, in pandas._libs.parsers.TextReader._convert_tokens
  File "pandas/_libs/parsers.pyx", line 1253, in pandas._libs.parsers.TextReader._convert_with_dtype
  File "pandas/_libs/parsers.pyx", line 1268, in pandas._libs.parsers.TextReader._string_convert
  File "pandas/_libs/parsers.pyx", line 1458, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe5 in position 12: invalid continuation byte
</code>```

As you can see in the traceback, I am already setting the encoding to latin1:

```<code>pandas.read_csv(path, encoding='latin1', sep=sep)
</code>```

Why does pandas try to decode UTF-8 when i have specified latin1 as encoding? I have tried to use other aliases for latin1, it gives the same result.

Any idea why pandas seems to be ignoring my encoding setting?

Edit: Removed comment on not working in Windows. The same error happened, I just cheated when I passed the file, not passing it the same way.

答: The problem was a few too many layers of abstraction. I had a wrapper around this that tried to decompress the file if it ended with 'gz'. I then gave pandas not a path, but a temporary file. This file does of course already have its encoding set, and then the encoding setting is ignored in pandas. The solution is/was to pass the encoding to the temporary file, or as I did, just pass the original path to pandas, as it handles decompressed of files automatically.</p>

Body:
Using Linux, Pandas 1.0.1 and Python 3.6 I get a strange error in production:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/app-root/lib/python3.6/site-packages/luigi/worker.py", line 199, in run
    new_deps = self._run_get_new_deps()
  File "/opt/app-root/lib/python3.6/site-packages/luigi/worker.py", line 141, in _run_get_new_deps
    task_gen = self.task.run()
  File "/opt/app-root/src/import_validation/validate_csv.py", line 275, in run
    validate(temp_csv, self.query_id)
  File "/opt/app-root/src/import_validation/validate_csv.py", line 263, in validate
    pandas.read_csv(path, encoding='latin1', sep=sep)
  File "/opt/app-root/lib/python3.6/site-packages/pandas/io/parsers.py", line 676, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/opt/app-root/lib/python3.6/site-packages/pandas/io/parsers.py", line 454, in _read
    data = parser.read(nrows)
  File "/opt/app-root/lib/python3.6/site-packages/pandas/io/parsers.py", line 1133, in read
    ret = self._engine.read(nrows)
  File "/opt/app-root/lib/python3.6/site-packages/pandas/io/parsers.py", line 2037, in read
    data = self._reader.read(nrows)
  File "pandas/_libs/parsers.pyx", line 859, in pandas._libs.parsers.TextReader.read
  File "pandas/_libs/parsers.pyx", line 874, in pandas._libs.parsers.TextReader._read_low_memory
  File "pandas/_libs/parsers.pyx", line 951, in pandas._libs.parsers.TextReader._read_rows
  File "pandas/_libs/parsers.pyx", line 1083, in pandas._libs.parsers.TextReader._convert_column_data
  File "pandas/_libs/parsers.pyx", line 1136, in pandas._libs.parsers.TextReader._convert_tokens
  File "pandas/_libs/parsers.pyx", line 1253, in pandas._libs.parsers.TextReader._convert_with_dtype
  File "pandas/_libs/parsers.pyx", line 1268, in pandas._libs.parsers.TextReader._string_convert
  File "pandas/_libs/parsers.pyx", line 1458, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe5 in position 12: invalid continuation byte

As you can see in the traceback, I am already setting the encoding to latin1:

pandas.read_csv(path, encoding='latin1', sep=sep)

Why does pandas try to decode UTF-8 when i have specified latin1 as encoding? I have tried to use other aliases for latin1, it gives the same result.

Any idea why pandas seems to be ignoring my encoding setting?

Edit: Removed comment on not working in Windows. The same error happened, I just cheated when I passed the file, not passing it the same way.


问:
Java application with Apache Livy
I decided to build a web service(app) for Apache Spark with Apache Livy.

Livy server is up and running on localhost port 8998 according to Livy configuration defaults.

My test program is a sample application in Apache Livy documentation:  https://livy.incubator.apache.org/docs/latest/programmatic-api.html

While creating LivyClient by LivyClientBuilder class,

```<code> client = new LivyClientBuilder().setURI(new
 URI("http","user:info","localhost",8998,"","",""))
    .build();
</code>```

I got "URI is not supported by any registered client factories" exception:

```<code>Exception in thread "main" java.lang.IllegalArgumentException: URI 'http://%5Bredacted%5D@localhost:8998?#' is not supported by any registered client factories.
at org.apache.livy.LivyClientBuilder.build(LivyClientBuilder.java:155)
at Client.<init>(Client.java:17)
at Client.main(Client.java:25)
</code>```

I found out client instance stays null in LivyClientBuilder class.

```<code>client = factory.createClient(uri, this.config);
</code>```

factory is an instance of LivyClientFactory interface.

The only class which implements the interface is RSCClientFactory.

  In RSCClientFactory we have this piece of code:

```<code>if (!"rsc".equals(uri.getScheme())) {
     return null;
 }
</code>```

I've tried "rsc" instead of "http", this is the error:

```<code>    2018-09-15 11:32:55 ERROR RSCClient:340 - RPC error.
  java.util.concurrent.ExecutionException: javax.security.sasl.SaslException: Client closed before SASL negotiation finished.
  javax.security.sasl.SaslException: Client closed before SASL negotiation finished.
    at io.netty.util.concurrent.AbstractFuture.get(AbstractFuture.java:41)
    at org.apache.livy.rsc.rpc.Rpc$SaslClientHandler.dispose(Rpc.java:419)
    at org.apache.livy.rsc.JobHandleImpl.get(JobHandleImpl.java:60)
    at org.apache.livy.rsc.rpc.SaslHandler.channelInactive(SaslHandler.java:92)
    at Client.main(Client.java:39)
</code>```

Apache Livy is running on  http://localhost:8998 then I think we need submit our jar file to this address, but I don't understand "rsc" there.

I would appreciate if anyone guides me about these problems.

答:
The only class which implements the interface is RSCClientFactory.

Just add livy-client-http to your classpath.

https://github.com/apache/incubator-livy/blob/412ccc8fcf96854fedbe76af8e5a6fec2c542d25/client-http/src/main/java/org/apache/livy/client/http/HttpClientFactory.java#L29

https://github.com/apache/incubator-livy/blob/56c76bc2d4563593edce062a563603fe63e5a431/examples/src/main/java/org/apache/livy/examples/PiApp.java#L79

Docs: https://livy.incubator.apache.org/docs/latest/programmatic-api.html

Title: Java application with Apache Livy

Body:
I decided to build a web service(app) for Apache Spark with Apache Livy.

Livy server is up and running on localhost port 8998 according to Livy configuration defaults.

My test program is a sample application in Apache Livy documentation:  https://livy.incubator.apache.org/docs/latest/programmatic-api.html

While creating LivyClient by LivyClientBuilder class,

 client = new LivyClientBuilder().setURI(new
 URI("http","user:info","localhost",8998,"","",""))
    .build();

I got "URI is not supported by any registered client factories" exception:

Exception in thread "main" java.lang.IllegalArgumentException: URI 'http://%5Bredacted%5D@localhost:8998?#' is not supported by any registered client factories.
at org.apache.livy.LivyClientBuilder.build(LivyClientBuilder.java:155)
at Client.<init>(Client.java:17)
at Client.main(Client.java:25)

I found out client instance stays null in LivyClientBuilder class.

client = factory.createClient(uri, this.config);

factory is an instance of LivyClientFactory interface.

The only class which implements the interface is RSCClientFactory.

  In RSCClientFactory we have this piece of code:

if (!"rsc".equals(uri.getScheme())) {
     return null;
 }

I've tried "rsc" instead of "http", this is the error:

    2018-09-15 11:32:55 ERROR RSCClient:340 - RPC error.
  java.util.concurrent.ExecutionException: javax.security.sasl.SaslException: Client closed before SASL negotiation finished.
  javax.security.sasl.SaslException: Client closed before SASL negotiation finished.
    at io.netty.util.concurrent.AbstractFuture.get(AbstractFuture.java:41)
    at org.apache.livy.rsc.rpc.Rpc$SaslClientHandler.dispose(Rpc.java:419)
    at org.apache.livy.rsc.JobHandleImpl.get(JobHandleImpl.java:60)
    at org.apache.livy.rsc.rpc.SaslHandler.channelInactive(SaslHandler.java:92)
    at Client.main(Client.java:39)

Apache Livy is running on  http://localhost:8998 then I think we need submit our jar file to this address, but I don't understand "rsc" there.

I would appreciate if anyone guides me about these problems.


问:
How to concatenate two webelement, iterate it and get the text out of concatenated Xpath
I am working with Page object model

My Page objects are as below:

```<code>    @FindBy(xpath = "//kendo-grid-list//table/tbody/tr/td[9]//div/p")
    List<WebElement> milestoneListSize;

    private static final String milestoneEditButton1 = "//uif-checklist-complex-group[";

    private static final String milestoneEditButton2 = "]//uif-checklist-table/table/tbody/tr/td[6]//a";

    public void clickMilestoneUser(milestoneListSize, String milestoneEditButton1 , String milestoneEditButton2 ) {

        String Actual;
        int totalsize = milestoneListSize.size();

        for (int i = 1; i <= totalsize; i++) {
        Actual = driver.findElement(By.xpath(milestoneEditButton1 + i + milestoneEditButton2)).getText();
        System.out.println(Actual );
        }

    }
</code>```

Don't know why this piece of code is not working?
Thanks for help in advance

答:
There are several issues with your code, but I won't be able to cover them all.

You have defined milestoneEditButton(1&2) as 'private static' fields meaning that they are accessible from inside every method in this class and you don't need to pass them as method params.

Instead of using 2 separate parts to construct the locator, you can have a single string template:

```<code>private static final String XPATH_EDIT_BTN = "//uif-checklist-complex-group[%d]//uif-checklist-table/table/tbody/tr/td[6]//a";
</code>```

That can be used to construct the locator:

```<code>By.xpath(String.format(XPATH_EDIT_BTN, i))
</code>```

The value of the 'Actual' variable gets reassigned every time 'Actual = ...' is called. You should be using 'Actual += ...' instead, but it's best to use StringBuilder:

```<code>StringBuilder buffer = new StringBuilder();
for (int i = 1; i <= totalsize; i++) {
    By loc = By.xpath(String.format(XPATH_EDIT_BTN, i));
    buffer.append(driver.findElement(loc).getText());
}
System.out.println(buffer.toString());
</code>```

Body:
I am working with Page object model

My Page objects are as below:

    @FindBy(xpath = "//kendo-grid-list//table/tbody/tr/td[9]//div/p")
    List<WebElement> milestoneListSize;

    private static final String milestoneEditButton1 = "//uif-checklist-complex-group[";

    private static final String milestoneEditButton2 = "]//uif-checklist-table/table/tbody/tr/td[6]//a";

    public void clickMilestoneUser(milestoneListSize, String milestoneEditButton1 , String milestoneEditButton2 ) {

        String Actual;
        int totalsize = milestoneListSize.size();

        for (int i = 1; i <= totalsize; i++) {
        Actual = driver.findElement(By.xpath(milestoneEditButton1 + i + milestoneEditButton2)).getText();
        System.out.println(Actual );
        }

    }

Don't know why this piece of code is not working?
Thanks for help in advance

Body:
There are several issues with your code, but I won't be able to cover them all.

You have defined milestoneEditButton(1&2) as 'private static' fields meaning that they are accessible from inside every method in this class and you don't need to pass them as method params.

Instead of using 2 separate parts to construct the locator, you can have a single string template:

private static final String XPATH_EDIT_BTN = "//uif-checklist-complex-group[%d]//uif-checklist-table/table/tbody/tr/td[6]//a";

That can be used to construct the locator:

By.xpath(String.format(XPATH_EDIT_BTN, i))

The value of the 'Actual' variable gets reassigned every time 'Actual = ...' is called. You should be using 'Actual += ...' instead, but it's best to use StringBuilder:

StringBuilder buffer = new StringBuilder();
for (int i = 1; i <= totalsize; i++) {
    By loc = By.xpath(String.format(XPATH_EDIT_BTN, i));
    buffer.append(driver.findElement(loc).getText());
}
System.out.println(buffer.toString());


问:
NetBeans : JUnit no tests executed
So I'm getting this persistent error using netbeans. I've got a LinkedList class which I am testing via a JUnit test, which I created by clicking on LinkedList.java: Tools -> Create/Update Tests and this LinkedListTest.java class is now located in test packages.
My LinkedList.java file works correctly when tested in a file with a main method.

```<code>public class LinkedListTest {

@Test
public void testAddFirst() {

    LinkedList linkedList = new LinkedList();
    Country c1 = new Country("Australia");

    linkedList.addFirst(c1);
    assertEquals("Australias", linkedList.getValue(0)); // Should fail a test

} // default test methods beneath
</code>```

All my imports check out. JUnit 5.3.1 and I had to download apiguardian1.1.0.jar from MVN repository to clear an error for:

```<code>reason: class file for org.apiguardian.api.API$Status not found
</code>```

I right-click in this file and select Test File, or use Ctrl+F6, I've selected Test File from the original LinkedList file, I've even used Alt+F6 which tests the whole project. Yet I'm met with 'No tests executed.', an empty Test Results window, and no Notifications. What am I doing wrong?
Thanks for any help

Edit: I just switched from netbeans to eclipse.

答:
You forget to extend Runner with class --

use like below with class -

```<code>public class LinkedListTest extends Runner {

}
</code>```

Hope this help you.

Title: NetBeans : JUnit no tests executed

Body:
So I'm getting this persistent error using netbeans. I've got a LinkedList class which I am testing via a JUnit test, which I created by clicking on LinkedList.java: Tools -> Create/Update Tests and this LinkedListTest.java class is now located in test packages.
My LinkedList.java file works correctly when tested in a file with a main method.

public class LinkedListTest {

@Test
public void testAddFirst() {

    LinkedList linkedList = new LinkedList();
    Country c1 = new Country("Australia");

    linkedList.addFirst(c1);
    assertEquals("Australias", linkedList.getValue(0)); // Should fail a test

} // default test methods beneath

All my imports check out. JUnit 5.3.1 and I had to download apiguardian1.1.0.jar from MVN repository to clear an error for:

reason: class file for org.apiguardian.api.API$Status not found

I right-click in this file and select Test File, or use Ctrl+F6, I've selected Test File from the original LinkedList file, I've even used Alt+F6 which tests the whole project. Yet I'm met with 'No tests executed.', an empty Test Results window, and no Notifications. What am I doing wrong?
Thanks for any help

Edit: I just switched from netbeans to eclipse.

Body:
You forget to extend Runner with class --

use like below with class -

public class LinkedListTest extends Runner {

}

Hope this help you.


问:
System design pattern for recurring payments
I'd like to ask what are some common, widely adopted patterns to design a system which auto-renew user's subscription when it expires.

I'm specifically asking how to trigger that operation?

Assume there's a system, with some RenewSubscription method that do the all logic. The method should be triggered just after user's subscription expired.

The only way I see to implement it is to have some kind of background task (console app or lambda) that query DB every N seconds (or minutes) and checks if there is any expired subscription to renew.

Can this be implemented without querying DB every few seconds?

答: It would be necessary to query the database at some point to fetch the users with expired subscription, so in any case some kind of cron job is needed. As for how often the background task should be triggered IMO it depends on what's your acceptable threshold between expiration and renewal (seconds, minutes, hours). Also take in account the performance of the RenewSubscription method, the amount of users to update and the time it takes to run the database query. Ideally the cron job should finish before the next one starts and if that's not possible you need to take in account how many processes could be running in parallel without hitting memory/CPU bounds if any. I believe you'll have to run some benchmarks to find an acceptable balance for your use case.</p>


答:
You are using fgets which is good, but unfortunately not the right way...

fgets reads up to an end of line or at most 1 less the the number of character asked. And of course remaining characters are left for the next read operation...

The idiomatic way would be to ensure reading up to the end of line, whatever the length, or at least up to a much larger length.

Simple but could fail in more than SIZE characters on input:

```<code>#define SIZE 64
...

void read_guess(char *guesses, char *p_current_guess)
{
    char line[SIZE];
    int valid_guess = 0;

    // Repeatedly takes input until guess is valid
    while (valid_guess == 0)
    {
        printf(">>> ");
        fgets(line, SiZE, stdin);                // read a line of size at most SIZE-1
        p_current_guess[0] = line[0];            // keep first character
        p_current_guess[1] = '\0';
        ...
</code>```

Robust but slightly more complex

```<code>/**
 * Read a line and only keep the first character
 *
 * Syntax: char * fgetfirst(dest, fd);
 *
 * Parameters:
 *  dest: points to a buffer of size at least 2 that will recieve the
 *         first character followed with a null
 *  fd  : FILE* from which to read
 *
 * Return value: dest if one character was successfully read, else NULL
 */
char *readfirst(dest, fd) {
#define SIZE 256              // may be adapted
    char buf[SIZE];
    char *cr = NULL;          // return value initialized to NULL if nothing can be read
    for (;;) {
        if(NULL == fgets(buff, sizeof(buff), fd)) return cr; // read error or end of file
        if (0 == strcspn(buff, "\n")) return cr;             // end of file
        if (cr == NULL) {                                    // first read:
            cr = dest;                        //  prepare to return first char
            dest[0] = buff[0];
            dest[1] = 0;
        }
    }
}
</code>```

You can then use it simply in your code:

```<code>void read_guess(char *guesses, char *p_current_guess)
{
    int valid_guess = 0;

    // Repeatedly takes input until guess is valid
    while (valid_guess == 0)
    {
        printf(">>> ");
        fgetfirst(p_current_guess, stdin);
</code>```

Title: C - Is there a way to read a single character of user input, and not have the rest "pushed down" to the next request for input?

Body:
So, I'm working on a simple hangman game in C, and I have the function read_guess, shown below.

void read_guess(char *guesses, char *p_current_guess)
{
    int valid_guess = 0;

    // Repeatedly takes input until guess is valid
    while (valid_guess == 0)
    {
        printf(">>> ");
        fgets(p_current_guess, 2, stdin);

        if (!isalpha(*p_current_guess)) printf("Guesses must be alphabetic. Please try again.\n\n");
        else
        {
            valid_guess = 1;

            // Iterates over array of guesses and checks if letter has already been guessed
            for (int i = 0; guesses[i] != '\0'; i++)
            {
                if (guesses[i] == *p_current_guess)
                {
                    printf("You have already guessed this letter. Please try again.\n\n");
                    valid_guess = 0;
                    break;
                }
            }
        }
    }
}

I've tried all the standard input functions (including getchar), but with all of them, when an input larger than one character is supplied, instead of taking just the first character and moving on (or asking again), the rest of the input is "pushed back", and the next time input is requested, whether it be because the input contained a non-alphabetic character or the next round begins, the rest of the input is automatically processed. This repeats for each character of the input.

How can I avoid this?

Body:
You are using fgets which is good, but unfortunately not the right way...

fgets reads up to an end of line or at most 1 less the the number of character asked. And of course remaining characters are left for the next read operation...

The idiomatic way would be to ensure reading up to the end of line, whatever the length, or at least up to a much larger length.

Simple but could fail in more than SIZE characters on input:

#define SIZE 64
...

void read_guess(char *guesses, char *p_current_guess)
{
    char line[SIZE];
    int valid_guess = 0;

    // Repeatedly takes input until guess is valid
    while (valid_guess == 0)
    {
        printf(">>> ");
        fgets(line, SiZE, stdin);                // read a line of size at most SIZE-1
        p_current_guess[0] = line[0];            // keep first character
        p_current_guess[1] = '\0';
        ...

Robust but slightly more complex

/**
 * Read a line and only keep the first character
 *
 * Syntax: char * fgetfirst(dest, fd);
 *
 * Parameters:
 *  dest: points to a buffer of size at least 2 that will recieve the
 *         first character followed with a null
 *  fd  : FILE* from which to read
 *
 * Return value: dest if one character was successfully read, else NULL
 */
char *readfirst(dest, fd) {
#define SIZE 256              // may be adapted
    char buf[SIZE];
    char *cr = NULL;          // return value initialized to NULL if nothing can be read
    for (;;) {
        if(NULL == fgets(buff, sizeof(buff), fd)) return cr; // read error or end of file
        if (0 == strcspn(buff, "\n")) return cr;             // end of file
        if (cr == NULL) {                                    // first read:
            cr = dest;                        //  prepare to return first char
            dest[0] = buff[0];
            dest[1] = 0;
        }
    }
}

You can then use it simply in your code:

void read_guess(char *guesses, char *p_current_guess)
{
    int valid_guess = 0;

    // Repeatedly takes input until guess is valid
    while (valid_guess == 0)
    {
        printf(">>> ");
        fgetfirst(p_current_guess, stdin);


问:
Using Azure Build pipeline log within build
I have an Azure build pipeline that runs a Checkmarx scan on a regular basis. Once this runs, the build log is populated with the amount of 'high', 'medium', 'low' severity results are found during the scan. I'd like to access this log to be able to act upon the 'high' severity results found (specifically, I'll be creating an Azure DevOps task).

Is there a way to read the Build log during the actual build? I've found that there is a 'Get Build Log' Azure endpoint but that seems odd to call an endpoint from a build to read its own logs.

Additionally, my first idea was to simply export the Checkmarx results within the Checkmarx step but that doesn't seem to be an option.

答:
Is there a way to read the Build log during the actual build?

You could use the REST API Builds - Get Build Logs:

```<code>GET https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}/logs?api-version=5.1
</code>```

Then we could grab the url from the response body to download the last log and parse the log find out the 'high' severity results.

There is a similar thread about this issue, you could check it for some more info.

Hope this helps.

Body:
Is there a way to read the Build log during the actual build?

You could use the REST API Builds - Get Build Logs:

GET https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}/logs?api-version=5.1

Then we could grab the url from the response body to download the last log and parse the log find out the 'high' severity results.

There is a similar thread about this issue, you could check it for some more info.

Hope this helps.


问:
v-show and other stuff like this does not work on <template>
I try to make a div appear with a v-show directive when you click it but nothing works and don't know why...

here's the code :

```<code><template>
  <section class="hero is-fullheight homepage-section">
    <columns style="height: 100vh; margin: 0">
      <column v-show="isShow" class="domain-column is-9" position="relative">
        <div class="video-background">
          <div class="video-foreground">
            <iframe
              src="https://XXXX?controls=0&showinfo=0&rel=0&autoplay=1&loop=1&mute=1"
              frameborder="0"
              allowfullscreen
            ></iframe>
          </div>
        </div>
      </column>
      <column
        class="domain-column is-3"
        position="relative"
        style="background: rgba(25, 28, 33, 0.90);"
      >
        <div
          class="columns is-vcentered text-center"
          style="display: flex; color: white;"
          fillheight
        >
          <div>
            <p class="list-item menu-item">
              ABOUT
            </p>
            <p class="list-item menu-item">
              WORK
            </p>
            <p @click="test" class="list-item menu-item">
              POLES
            </p>
            <p class="list-item menu-item">
              CONTACT
            </p>
          </div>
        </div>
      </column>
    </columns>
  </section>
</template>

<script>
export default {
  layout: 'homepage',
  data: {
    isShow: true
  },
  methods: {
    test() {
      console.log('hello!', this, this.isShow);
      alert('test function => ' + this.isShow);
      this.isShow =  !this.isShow;
    },
    goToPage(domain) {
      this.$router.push(`/${domain}`)
    }
  },

  head() {
    return {
      title:
        'Walter',
      meta: [
        {
          hid: 'description',
          name: 'description',
          content:
            'Walter'
        }
      ]
    }
  }
}
</script>
</code>```

Can you help me understand why this thing does not happen when I click on it? Event isShow change between true and false when POLES is clicked.

One more thing for exemple if I do this : hello there : {{ msg }}

msg will not be display.

答:
Ok everyone!

I found my mistake! It's a very novice error :

```<code>data: {
    isShow: true
  }
</code>```

Don't gonna work , I think i understand why. If I use my react notions I could just suppose it's because of the 'state' of the component (WOAW so obvious sorry but it's my first time on vue, I learn about my mistakes) but after few documentations I learn more about vue and data like it written above is work as a function and not as an object like I though.

Like this:

```<code>data() {
    return { isShow: true }
  }
</code>```

In fact that’s because each time you use a component, a new instance of it is created. So the component have him own state so if you got 50 render of the same component they ll have they own properties.
What a big misunderstood but know i figured out what was my problem it's look very logic and natural! I'm happy for that!

Hopefully this response will help some novice like me.

Thx everyone who's tried to help me.

Body:
I try to make a div appear with a v-show directive when you click it but nothing works and don't know why...

here's the code :

<template>

    <columns style="height: 100vh; margin: 0">
      <column v-show="isShow" class="domain-column is-9" position="relative">

      </column>
      <column
        class="domain-column is-3"
        position="relative"
        style="background: rgba(25, 28, 33, 0.90);"
      >

              ABOUT

              WORK

              POLES

              CONTACT

      </column>
    </columns>

</template>

Can you help me understand why this thing does not happen when I click on it? Event isShow change between true and false when POLES is clicked.

One more thing for exemple if I do this : hello there : {{ msg }}

msg will not be display.

Body:
Ok everyone!

I found my mistake! It's a very novice error :

data: {
    isShow: true
  }

Don't gonna work , I think i understand why. If I use my react notions I could just suppose it's because of the 'state' of the component (WOAW so obvious sorry but it's my first time on vue, I learn about my mistakes) but after few documentations I learn more about vue and data like it written above is work as a function and not as an object like I though.

Like this:

data() {
    return { isShow: true }
  }

In fact that’s because each time you use a component, a new instance of it is created. So the component have him own state so if you got 50 render of the same component they ll have they own properties.
What a big misunderstood but know i figured out what was my problem it's look very logic and natural! I'm happy for that!

Hopefully this response will help some novice like me.

Thx everyone who's tried to help me.


问:
How to display filenames of word documents in a folder using python?
I want to display the filenames of word document present in a specified path using python.</p>

答:
It could be just as simple as creating a custom iterator using scandir passing the file extension (for word documents you can use docx). Like this:

import os
from typing import Type, Iterable

def scan_dir(path, file_ext) -> Iterable[Type[os.DirEntry]]:
    for dir_entry in os.scandir(path):
        if dir_entry.name.endswith(f'.{file_ext}'): yield dir_entry

if __name__ == '__main__':
    for word_doc in scan_dir('.', 'docx'):
        print(word_doc.name)

```


问:
How can I get the size of a zoomed or pinched image in iphone sdk?
I had a image which is added to a scrollView, I want to get the size of the image when ever I pinch/zoom that image. Can anyone please help me

Thanks

Praveena

答:
This seems to be an easier way to get the size –</p>

```<code>CGSize currentImageSize = myImageView.frame.size;
</code>```

Body:
This seems to be an easier way to get the size –

CGSize currentImageSize = myImageView.frame.size;


问:
Virtualbox enable nested vtx/amd-v greyed out
On my Ubuntu 18.04, I've installed VirtualBox 6.0 in order to have nested virtualization. Virtualization is enabled in my bios.

However, when I open the settings of my (powered off) virtual machine and go to System -> Processor, the option "Enable Nested VT-x/AMD-V" is greyed out and I cannot enable it.

答:
It's alive on VirtualBox 6.1.2 r135662 (Qt5.6.2) and Intel Core i3-8100!

CMD's output from image as text:

```<code>C:\WINDOWS\system32>ssh myuser@192.168.56.111
myuser@192.168.56.111's password:
Last login: Mon Feb 17 10:11:06 2020 from 192.168.56.1

myuser@nestedvt ~ $ su
Пароль:

root@nestedvt /home/myuser # egrep "svm|vmx" /proc/cpuinfo
root@nestedvt /home/myuser #

root@nestedvt /home/myuser # poweroff
Connection to 192.168.56.111 closed by remote host.
Connection to 192.168.56.111 closed.

C:\WINDOWS\system32>cd "C:\Program Files\Oracle\VirtualBox"
C:\Program Files\Oracle\VirtualBox>VBoxManage modifyvm CentOS7_nestedVT --nested-hw-virt on

C:\Program Files\Oracle\VirtualBox>VBoxManage startvm CentOS7_nestedVT
Waiting for VM "CentOS7_nestedVT" to power on...
VM "CentOS7_nestedVT" has been successfully started.

C:\Program Files\Oracle\VirtualBox>ssh myuser@192.168.56.111
myuser@192.168.56.111's password:
Last login: Mon Feb 17 10:12:08 2020 from 192.168.56.1

myuser@nestedvt ~ $ su
Пароль:

root@nestedvt /home/myuser # egrep "svm|vmx" /proc/cpuinfo
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc eagerfpu pni pclmulqdq vmx ssse3 cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single tpr_shadow flexpriority fsgsbase avx2 invpcid rdseed clflushopt md_clear flush_l1d
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc eagerfpu pni pclmulqdq vmx ssse3 cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single tpr_shadow flexpriority fsgsbase avx2 invpcid rdseed clflushopt md_clear flush_l1d

root@nestedvt /home/myuser # exit
exit
myuser@nestedvt ~ $ exit
logout
Connection to 192.168.56.111 closed.

C:\Program Files\Oracle\VirtualBox>wmic cpu get name
Name
Intel(R) Core(TM) i3-8100 CPU @ 3.60GHz

C:\Program Files\Oracle\VirtualBox>wmic os get caption
Caption
Microsoft Windows 10 Pro
</code>```

Body:
It's alive on VirtualBox 6.1.2 r135662 (Qt5.6.2) and Intel Core i3-8100!

CMD's output from image as text:

C:\WINDOWS\system32>ssh myuser@192.168.56.111
myuser@192.168.56.111's password:
Last login: Mon Feb 17 10:11:06 2020 from 192.168.56.1

myuser@nestedvt ~ $ su
Пароль:

root@nestedvt /home/myuser # egrep "svm|vmx" /proc/cpuinfo
root@nestedvt /home/myuser #

root@nestedvt /home/myuser # poweroff
Connection to 192.168.56.111 closed by remote host.
Connection to 192.168.56.111 closed.

C:\WINDOWS\system32>cd "C:\Program Files\Oracle\VirtualBox"
C:\Program Files\Oracle\VirtualBox>VBoxManage modifyvm CentOS7_nestedVT --nested-hw-virt on

C:\Program Files\Oracle\VirtualBox>VBoxManage startvm CentOS7_nestedVT
Waiting for VM "CentOS7_nestedVT" to power on...
VM "CentOS7_nestedVT" has been successfully started.

C:\Program Files\Oracle\VirtualBox>ssh myuser@192.168.56.111
myuser@192.168.56.111's password:
Last login: Mon Feb 17 10:12:08 2020 from 192.168.56.1

myuser@nestedvt ~ $ su
Пароль:

root@nestedvt /home/myuser # egrep "svm|vmx" /proc/cpuinfo
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc eagerfpu pni pclmulqdq vmx ssse3 cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single tpr_shadow flexpriority fsgsbase avx2 invpcid rdseed clflushopt md_clear flush_l1d
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc eagerfpu pni pclmulqdq vmx ssse3 cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single tpr_shadow flexpriority fsgsbase avx2 invpcid rdseed clflushopt md_clear flush_l1d

root@nestedvt /home/myuser # exit
exit
myuser@nestedvt ~ $ exit
logout
Connection to 192.168.56.111 closed.

C:\Program Files\Oracle\VirtualBox>wmic cpu get name
Name
Intel(R) Core(TM) i3-8100 CPU @ 3.60GHz

C:\Program Files\Oracle\VirtualBox>wmic os get caption
Caption
Microsoft Windows 10 Pro


问:
1. Forward slash in routing parameter
I have a GET end point which will take user name as parameter. Below is the action

```<code>[Route("user/{userName}")]
public User GetUserByName([FromUri] string userName)
{
  // logic here
}
</code>```

This is how i make the request.

```<code>var restClient = new RestClient("uri");
var request = new RestRequest("user/" + userName);
var response = restClient.Execute(request);
</code>```

It worked fine for all cases till a user with name containing forward slash came.
Eg: Akbar/Badhusha
Then the request will looks like user/Akbar/Badhusha

This causing the request to return Not Fount error

I tried to add the parameter with AddQueryParameter method. All returning Not found error.

I also tried HttpUtility.UrlEncode

Also tried replacing / with  %2f

Also tried user?userName=Akbar/Badhusha

All of them failed.

Is there any way to make it work?

答:
Try removing [FromUri] from the parameter as shown below,

```<code>[Route("user")]
public User GetUserByName(string userName)
{
  // logic here
}
</code>```

And the request may look like,

user?userName=Akbar/Badhush

Title: 1. Forward slash in routing parameter

Body:
I have a GET end point which will take user name as parameter. Below is the action

[Route("user/{userName}")]
public User GetUserByName([FromUri] string userName)
{
  // logic here
}

This is how i make the request.

var restClient = new RestClient("uri");
var request = new RestRequest("user/" + userName);
var response = restClient.Execute(request);

It worked fine for all cases till a user with name containing forward slash came.
Eg: Akbar/Badhusha
Then the request will looks like user/Akbar/Badhusha

This causing the request to return Not Fount error

I tried to add the parameter with AddQueryParameter method. All returning Not found error.

I also tried HttpUtility.UrlEncode

Also tried replacing / with  %2f

Also tried user?userName=Akbar/Badhusha

All of them failed.

Is there any way to make it work?

Body:
Try removing [FromUri] from the parameter as shown below,

[Route("user")]
public User GetUserByName(string userName)
{
  // logic here
}

And the request may look like,

user?userName=Akbar/Badhush


问:
image-charts url is not respecting chds

chds = 0,1800

https://image-charts.com/chart?chd=a%3A2060%2C971%2C849&chds=0,1800&chs=700x100&cht=bvg

chds = 0,2000

https://image-charts.com/chart?chd=a%3A2060%2C971%2C849&chds=0,2000&chs=700x100&cht=bvg

So chds = 0,1800 has a lower bar than chds = 0,2000 when I expect the opposite. With chds = 0,1800 I expect the bar to take up the whole image since 2060 is more than 1800.

Docs: https://documentation.image-charts.com/reference/chart-axis/

答:
Image-Charts founder here :)

As per our documentation, chds as you want to use it works with chd=t: (like in Google Image Charts). chds is not necessary with chd=a:.

With chd=t: chds work as expected:

chds=0,1800&chd=t:

```<code>https://image-charts.com/chart?chd=t:2060,971,849&chds=0,1800&chs=700x100&cht=bvg
</code>```

chds=0,2000&chd=t:

```<code>https://image-charts.com/chart?chd=t:2060,971,849&chds=0,2000&chs=700x100&cht=bvg
</code>```

Title: image-charts url is not respecting chds

Body:
Image-Charts founder here :)

As per our documentation, chds as you want to use it works with chd=t: (like in Google Image Charts). chds is not necessary with chd=a:.

With chd=t: chds work as expected:

chds=0,1800&chd=t:

https://image-charts.com/chart?chd=t:2060,971,849&chds=0,1800&chs=700x100&cht=bvg

chds=0,2000&chd=t:

https://image-charts.com/chart?chd=t:2060,971,849&chds=0,2000&chs=700x100&cht=bvg


问:
Issue with rails s (with sass apparently)
I tried to run rails s but sudently I'm getting an error message:

```<code>/home/leiver/.rbenv/versions/2.4.5/lib/ruby/gems/2.4.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require': cannot load such file -- sass (LoadError)
        from /home/leiver/.rbenv/versions/2.4.5/lib/ruby/gems/2.4.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:287:in `block in require'
        from /home/leiver/.rbenv/versions/2.4.5/lib/ruby/gems/2.4.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:253:in `load_dependency'
        from
.....
</code>```

I know that there's something about sass about how it's going to disapear or something and I don't know if it's linked

Thanks if you can help :)

EDIT

here's my full Gemfile:

```<code>source 'https://rubygems.org'
ruby '2.4.5'

gem 'bootsnap', require: false
gem 'jbuilder', '~> 2.0'
gem 'pg', '~> 0.21'
gem 'puma'
gem 'rails', '5.2.1'
gem 'redis'

gem 'autoprefixer-rails'
gem 'bootstrap-sass', '~> 3.3'
gem 'font-awesome-sass', '~> 5.0.9'
gem 'sassc-rails'
gem 'simple_form'
gem 'uglifier'
gem 'webpacker'
gem 'devise'
gem 'money-rails'
gem "pundit"

group :development do
  gem 'web-console', '>= 3.3.0'
end

group :development, :test do
  gem 'pry-byebug'
  gem 'pry-rails'
  gem 'listen', '~> 3.0.5'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem 'dotenv-rails'
end
</code>```

答:
The problem may be exists in gems. The problem founded by OP (and described in his answer) appears in the application files. However same problem problem may be caused in gems. The same problem in gems with same reason has identical solution.

In details. The problem during installation or some else may corrupt some gem so it is visible as installed but actually has missed or corrupted files. Check before that hard drive has enough free space.

So solution is fully reinstall bundle gems:

bundle install --force
```

Body:
I tried to run rails s but sudently I'm getting an error message:

/home/leiver/.rbenv/versions/2.4.5/lib/ruby/gems/2.4.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require': cannot load such file -- sass (LoadError)
        from /home/leiver/.rbenv/versions/2.4.5/lib/ruby/gems/2.4.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:287:in `block in require'
        from /home/leiver/.rbenv/versions/2.4.5/lib/ruby/gems/2.4.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:253:in `load_dependency'
        from
.....

I know that there's something about sass about how it's going to disapear or something and I don't know if it's linked

Thanks if you can help :)

EDIT

here's my full Gemfile:

source 'https://rubygems.org'
ruby '2.4.5'

gem 'bootsnap', require: false
gem 'jbuilder', '~> 2.0'
gem 'pg', '~> 0.21'
gem 'puma'
gem 'rails', '5.2.1'
gem 'redis'

gem 'autoprefixer-rails'
gem 'bootstrap-sass', '~> 3.3'
gem 'font-awesome-sass', '~> 5.0.9'
gem 'sassc-rails'
gem 'simple_form'
gem 'uglifier'
gem 'webpacker'
gem 'devise'
gem 'money-rails'
gem "pundit"

group :development do
  gem 'web-console', '>= 3.3.0'
end

group :development, :test do
  gem 'pry-byebug'
  gem 'pry-rails'
  gem 'listen', '~> 3.0.5'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem 'dotenv-rails'
end


问:
Constructor on Injected class not getting called Laravel IOC
I am injecting the InvoiceService in the testclass. Test class calling the create method of the invoice service..
Constructor  of the injected class not getting called because of this $repo is null create is failing.
Any help is appreciated. </p>

```<code>$this->app->singleton(
    'App\Models\Subscription\Interfaces\IInvoiceService',
    'App\Models\Subscription\Impl\InvoiceService'
);

class InvoiceService implements  IInvoiceService
{

    protected $repo;

    public function _construct(){

        $this->app = App::getFacadeRoot();

        $this->repo = $this->app['repo'];

    }
    public function Create($array)
    {
    $this->repo->insert($array); // //$this->repo is null as Constructor not getting called
    }
 }

 class TestClass

 {
    protected $InvoiceService;
    public function _construct(IInvoiceService $InvoiceService){

            $this->InvoiceService =$InvoiceService

    }

    public create($input) {

        this->InvoiceService->create($input);  // This is failing
    }
 }
</code>```

答:
To override default functionality you use __ "two underscores", in your example you are only using one.

```<code>_construct()
</code>```

Should be.

```<code>__construct()
</code>```

Body:
I am injecting the InvoiceService in the testclass. Test class calling the create method of the invoice service..
Constructor  of the injected class not getting called because of this $repo is null create is failing.
Any help is appreciated.

$this->app->singleton(
    'App\Models\Subscription\Interfaces\IInvoiceService',
    'App\Models\Subscription\Impl\InvoiceService'
);

class InvoiceService implements  IInvoiceService
{

    protected $repo;

    public function _construct(){

        $this->app = App::getFacadeRoot();

        $this->repo = $this->app['repo'];

    }
    public function Create($array)
    {
    $this->repo->insert($array); // //$this->repo is null as Constructor not getting called
    }
 }

 class TestClass

 {
    protected $InvoiceService;
    public function _construct(IInvoiceService $InvoiceService){

            $this->InvoiceService =$InvoiceService

    }

    public create($input) {

        this->InvoiceService->create($input);  // This is failing
    }
 }

Body:
To override default functionality you use __ "two underscores", in your example you are only using one.

_construct()

Should be.

__construct()


问:
RBAC issues using MassTransit with Azure service bus and MSI authentication
We are using MassTransit (v.5.5.5) with Azure Service Bus in a .net core v.2.2 application running in a container within Kubernetes. During the Bus setup we create a token using the managed service identity (MSI), like this...

```<code>var tokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider();
var busControl = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
{
    IServiceBusHost busHost = cfg.Host(new Uri(Settings.Host), h =>
    {
        h.OperationTimeout = TimeSpan.FromSeconds(5);
        h.TokenProvider = tokenProvider;
        h.TransportType = Settings.TransportType;
    });
    ...
}
</code>```

Within Azure, the MSI is configured with all 3 Service Bus permissions (Owner, Sender and Receiver) - as decribed here.

When the application starts authentication seems to happen successfully but when MassTransit begins to listen on the specific queues we create it fails with the following error:

```<code>MassTransit.Azure.ServiceBus.Core.Transport.ReceiveTransport Error: 0 :
ReceiveTransport Faulted: sb://hostname.servicebus.windows.net/some-custom-queue,
Microsoft.Azure.ServiceBus.UnauthorizedException: Generic: Failed during RBAC check,
please make sure service resource provider is registered on your tenant.
</code>```

Points to note:

The application does create the temporary bus queue, and there are no errors to do with accessing it.

The application does not create our custom queues.

If the MSI permissions are removed then no queues are created and the error is different: Authorization failed for specified action: Manage,EntityWrite.

For what it's worth we are using the AmqpWebSockets transport type.

It seems weird that the temporary queue is created but not our application-specific ones.

So I guess my question is this... have I done anything wrong or is this something that is not yet available for MassTransit using Service Bus with MSI?

Thanks in advance.

答:
We came across the same issue. We are using Mass Transit 6.* and Azure Service Bus. When switched to MSI we start see the same error:

```<code>Microsoft.Azure.ServiceBus.UnauthorizedException: Generic: Failed during RBAC check, please make sure service resource provider is registered on your tenant. TrackingId:2644d62a-83a9-444f-8aeb-b4bdee2fa84d_G30, SystemTracker:NoSystemTracker, Timestamp:2020-02-13T15:54:49
    at Microsoft.Azure.ServiceBus.Management.ManagementClient.SendHttpRequest(HttpRequestMessage request, CancellationToken cancellationToken)
    at Microsoft.Azure.ServiceBus.Management.ManagementClient.PutEntity(String path, String requestBody, Boolean isUpdate, String forwardTo, String fwdDeadLetterTo, CancellationToken cancellationToken)
    at Microsoft.Azure.ServiceBus.Management.ManagementClient.CreateTopicAsync(TopicDescription topicDescription, CancellationToken cancellationToken)
    at MassTransit.Azure.ServiceBus.Core.Contexts.NamespaceManager.<>c__DisplayClass25_0`1.<<RunOperation>b__0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
    at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
    at MassTransit.Azure.ServiceBus.Core.Contexts.NamespaceManager.RunOperation[T](Func`1 operation)
    at MassTransit.Azure.ServiceBus.Core.Contexts.ServiceBusNamespaceContext.CreateTopic(TopicDescription topicDescription)
    at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.ConfigureTopology(NamespaceContext context)
    at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.<>c__DisplayClass5_0.<<Send>b__0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at GreenPipes.PipeExtensions.OneTimeSetup[T](PipeContext context, Func`2 setupMethod, PayloadFactory`1 payloadFactory)
    at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.Send(NamespaceContext context, IPipe`1 next)
    at GreenPipes.Agents.AsyncPipeContextPipe`1.Send(TContext context)
    at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
    at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
    at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
    at MassTransit.Azure.ServiceBus.Core.Pipeline.JoinContextFactory`3.<>c__DisplayClass7_0.<<CreateJoinContext>g__Join|0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at MassTransit.Azure.ServiceBus.Core.Pipeline.ClientContextFactory.CreateSharedContext(Task`1 context, CancellationToken cancellationToken)
    at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
    at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
    at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
    at MassTransit.Azure.ServiceBus.Core.Transport.ReceiveTransport.<Receiver>b__12_0()
    at MassTransit.Azure.ServiceBus.Core.Pipeline.JoinContextFactory`3.<>c__DisplayClass7_0.<<CreateJoinContext>g__Join|0>d.MoveNext()
</code>```

Finally we found that ASB Sdk Microsoft.Azure.ServiceBus.Management.ManagementClient doesn't allow to create topics with slashes in path when tokens from MSI used. This code below return the same error:

```<code>         try
            {
                var address = "sb://[name].servicebus.windows.net";
                var tokenProvider = new TokenProvider.CreateManagedIdentityTokenProvider();();
                var _managementClient = new ManagementClient(address.ToString(), tokenProvider);
                var topicDefinition = new TopicDescription("myNewTopic/22222");
                await _managementClient.CreateTopicAsync(topicDefinition);

            }
            catch (Exception e)
            {
                Debug.WriteLine(e);

                throw;
            }
</code>```

Since MT uses special naming convention to setup messaging topology, we get topic path with namespace of particular message type. If we have message MassTransitTest.Message1 it will be converted to topic MassTransitTest/Message1 (with slash). To fix this we setup our own IEntityNameFormatter

```<code>public class MyEntityNameFormatter : IEntityNameFormatter
{
    readonly IMessageNameFormatter _formatter;

    public MyEntityNameFormatter()
    {
        _formatter = new ServiceBusMessageNameFormatter();
    }
    public string FormatEntityName<T>()
    {
        var entityName = _formatter.GetMessageName(typeof(T)).ToString().Replace("/",".");
        return entityName;
    }
}
</code>```

and then

```<code> var bus = Bus.Factory.CreateUsingAzureServiceBus(configurator =>
            {
                ...
                configurator.MessageTopology.SetEntityNameFormatter(new MyEntityNameFormatter());
                ...
</code>```

This fixed our issue. (We tried use ~ instead of . but got some validation errors, so decided use dots)

Body:
We are using MassTransit (v.5.5.5) with Azure Service Bus in a .net core v.2.2 application running in a container within Kubernetes. During the Bus setup we create a token using the managed service identity (MSI), like this...

var tokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider();
var busControl = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
{
    IServiceBusHost busHost = cfg.Host(new Uri(Settings.Host), h =>
    {
        h.OperationTimeout = TimeSpan.FromSeconds(5);
        h.TokenProvider = tokenProvider;
        h.TransportType = Settings.TransportType;
    });
    ...
}

Within Azure, the MSI is configured with all 3 Service Bus permissions (Owner, Sender and Receiver) - as decribed here.

When the application starts authentication seems to happen successfully but when MassTransit begins to listen on the specific queues we create it fails with the following error:

MassTransit.Azure.ServiceBus.Core.Transport.ReceiveTransport Error: 0 :
ReceiveTransport Faulted: sb://hostname.servicebus.windows.net/some-custom-queue,
Microsoft.Azure.ServiceBus.UnauthorizedException: Generic: Failed during RBAC check,
please make sure service resource provider is registered on your tenant.

Points to note:

The application does create the temporary bus queue, and there are no errors to do with accessing it.

The application does not create our custom queues.

If the MSI permissions are removed then no queues are created and the error is different: Authorization failed for specified action: Manage,EntityWrite.

For what it's worth we are using the AmqpWebSockets transport type.

It seems weird that the temporary queue is created but not our application-specific ones.

So I guess my question is this... have I done anything wrong or is this something that is not yet available for MassTransit using Service Bus with MSI?

Thanks in advance.

Body:
We came across the same issue. We are using Mass Transit 6.* and Azure Service Bus. When switched to MSI we start see the same error:

Microsoft.Azure.ServiceBus.UnauthorizedException: Generic: Failed during RBAC check, please make sure service resource provider is registered on your tenant. TrackingId:2644d62a-83a9-444f-8aeb-b4bdee2fa84d_G30, SystemTracker:NoSystemTracker, Timestamp:2020-02-13T15:54:49
    at Microsoft.Azure.ServiceBus.Management.ManagementClient.SendHttpRequest(HttpRequestMessage request, CancellationToken cancellationToken)
    at Microsoft.Azure.ServiceBus.Management.ManagementClient.PutEntity(String path, String requestBody, Boolean isUpdate, String forwardTo, String fwdDeadLetterTo, CancellationToken cancellationToken)
    at Microsoft.Azure.ServiceBus.Management.ManagementClient.CreateTopicAsync(TopicDescription topicDescription, CancellationToken cancellationToken)
    at MassTransit.Azure.ServiceBus.Core.Contexts.NamespaceManager.<>c__DisplayClass25_0`1.<<RunOperation>b__0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
    at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
    at MassTransit.Azure.ServiceBus.Core.Contexts.NamespaceManager.RunOperation[T](Func`1 operation)
    at MassTransit.Azure.ServiceBus.Core.Contexts.ServiceBusNamespaceContext.CreateTopic(TopicDescription topicDescription)
    at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.ConfigureTopology(NamespaceContext context)
    at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.<>c__DisplayClass5_0.<<Send>b__0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at GreenPipes.PipeExtensions.OneTimeSetup[T](PipeContext context, Func`2 setupMethod, PayloadFactory`1 payloadFactory)
    at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.Send(NamespaceContext context, IPipe`1 next)
    at GreenPipes.Agents.AsyncPipeContextPipe`1.Send(TContext context)
    at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
    at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
    at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
    at MassTransit.Azure.ServiceBus.Core.Pipeline.JoinContextFactory`3.<>c__DisplayClass7_0.<<CreateJoinContext>g__Join|0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at MassTransit.Azure.ServiceBus.Core.Pipeline.ClientContextFactory.CreateSharedContext(Task`1 context, CancellationToken cancellationToken)
    at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
    at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
    at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
    at MassTransit.Azure.ServiceBus.Core.Transport.ReceiveTransport.<Receiver>b__12_0()
    at MassTransit.Azure.ServiceBus.Core.Pipeline.JoinContextFactory`3.<>c__DisplayClass7_0.<<CreateJoinContext>g__Join|0>d.MoveNext()

Finally we found that ASB Sdk Microsoft.Azure.ServiceBus.Management.ManagementClient doesn't allow to create topics with slashes in path when tokens from MSI used. This code below return the same error:

         try
            {
                var address = "sb://[name].servicebus.windows.net";
                var tokenProvider = new TokenProvider.CreateManagedIdentityTokenProvider();();
                var _managementClient = new ManagementClient(address.ToString(), tokenProvider);
                var topicDefinition = new TopicDescription("myNewTopic/22222");
                await _managementClient.CreateTopicAsync(topicDefinition);

            }
            catch (Exception e)
            {
                Debug.WriteLine(e);

                throw;
            }

Since MT uses special naming convention to setup messaging topology, we get topic path with namespace of particular message type. If we have message MassTransitTest.Message1 it will be converted to topic MassTransitTest/Message1 (with slash). To fix this we setup our own IEntityNameFormatter

public class MyEntityNameFormatter : IEntityNameFormatter
{
    readonly IMessageNameFormatter _formatter;

    public MyEntityNameFormatter()
    {
        _formatter = new ServiceBusMessageNameFormatter();
    }
    public string FormatEntityName<T>()
    {
        var entityName = _formatter.GetMessageName(typeof(T)).ToString().Replace("/",".");
        return entityName;
    }
}

and then

 var bus = Bus.Factory.CreateUsingAzureServiceBus(configurator =>
            {
                ...
                configurator.MessageTopology.SetEntityNameFormatter(new MyEntityNameFormatter());
                ...

This fixed our issue. (We tried use ~ instead of . but got some validation errors, so decided use dots)


问:
Android notification's names on settings like facebook
I would like to make users able to disable/enable notifications separately by their functionalities from settings app like Facebook or other applications do.

As image, Facebook shows a title for each notification use case (as you can understand from my terrible English I'm Italian, so screenshot is in Italian too), so users can disable or enable notifications depending on his need.

How can I do it? Can you post me a code example?
Thank you very much and tell me if I wasn't clear

答:
You need to create Notification Channels. Here’s a Util method I’ve created for that purpose:

```<code>public void createChannel(String channelId, CharSequence channelName, int importance) {
    notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    channel = new NotificationChannel(channelId, channelName, importance);
    channel.enableLights(true);
    channel.setLightColor(Color.RED);
    channel.enableVibration(true);
    channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
    notificationManager.createNotificationChannel(channel);
}
</code>```

where channel and notificationManager:

```<code>private NotificationChannel channel;
private NotificationManager notificationManager;
</code>```

Just name the channels using the channelId and give them a description using channelName

Here's the Javadoc for the NotificationChannel:

```<code>/**
     * Creates a notification channel.
     *
     * @param id The id of the channel. Must be unique per package. The value may be truncated if
     *           it is too long.
     * @param name The user visible name of the channel. You can rename this channel when the system
     *             locale changes by listening for the {@link Intent#ACTION_LOCALE_CHANGED}
     *             broadcast. The recommended maximum length is 40 characters; the value may be
     *             truncated if it is too long.
     * @param importance The importance of the channel. This controls how interruptive notifications
     *                   posted to this channel are.
     */
    public NotificationChannel(String id, CharSequence name, @Importance int importance) {
        this.mId = getTrimmedString(id);
        this.mName = name != null ? getTrimmedString(name.toString()) : null;
        this.mImportance = importance;
    }
</code>```

Body:
You need to create Notification Channels. Here’s a Util method I’ve created for that purpose:

public void createChannel(String channelId, CharSequence channelName, int importance) {
    notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    channel = new NotificationChannel(channelId, channelName, importance);
    channel.enableLights(true);
    channel.setLightColor(Color.RED);
    channel.enableVibration(true);
    channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
    notificationManager.createNotificationChannel(channel);
}

where channel and notificationManager:

private NotificationChannel channel;
private NotificationManager notificationManager;

Just name the channels using the channelId and give them a description using channelName

Here's the Javadoc for the NotificationChannel:

/**
     * Creates a notification channel.
     *
     * @param id The id of the channel. Must be unique per package. The value may be truncated if
     *           it is too long.
     * @param name The user visible name of the channel. You can rename this channel when the system
     *             locale changes by listening for the {@link Intent#ACTION_LOCALE_CHANGED}
     *             broadcast. The recommended maximum length is 40 characters; the value may be
     *             truncated if it is too long.
     * @param importance The importance of the channel. This controls how interruptive notifications
     *                   posted to this channel are.
     */
    public NotificationChannel(String id, CharSequence name, @Importance int importance) {
        this.mId = getTrimmedString(id);
        this.mName = name != null ? getTrimmedString(name.toString()) : null;
        this.mImportance = importance;
    }


问:
embed youtube video with autoplay and no-controls
I want to embed a youtube video with autoplay ( the video start when you open the page ) and controls suppressed.

i tried :

I also changed the 'iframe' to 'embed', but it doesn't work.

答:
```<code><video autoplay="">
            <source src="yourvideo.mp4" type="video/mp4">
            Your browser does not support the element<code>video</code>
          </video>
</code>```

dont worry about this message "Your browser does not support the element"

i have that code in my web and its working

Body:
<video autoplay="">
            <source src="yourvideo.mp4" type="video/mp4">
            Your browser does not support the element<code>video</code>
          </video>

dont worry about this message "Your browser does not support the element"

i have that code in my web and its working


问:
How to add color gradients according to y-value to a bar plot?
Suppose I have a vertical bar plot like this:

MWE per this suggestion:

```<code>import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

bar = ax.bar([1,2,3,4,5,6],[4,5,6,3,7,5], bottom=[1,7,4,6,3,2])

def gradientbars(bars):
    grad = np.atleast_2d(np.linspace(0,1,256)).T
    ax = bars[0].axes
    lim = ax.get_xlim()+ax.get_ylim()
    for bar in bars:
        bar.set_zorder(1)
        bar.set_facecolor("none")
        x,y = bar.get_xy()
        w, h = bar.get_width(), bar.get_height()
        ax.imshow(grad, extent=[x,x+w,y,y+h], aspect="auto", zorder=0)
    ax.axis(lim)

gradientbars(bar)
plt.show()
</code>```

Is there an easy way to color the bars with a colormap according to the y-values they actually span (suppose my color bar goes from 1-12 where 1 is represented by yellow and 12 is represented by dark-blue)?

I have tried to adapt this example but wasn't successful.

答:
Here is the code in this post adapted such that each bar shows a corresponding slice of the gradient.

```<code>import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = np.arange(35)
bar = ax.bar(x, 6 - np.sin(x / 10) * 3, bottom=5 - np.cos(x / 10) * 5)
plt.xlim(x[0] - 0.5, x[-1] + 0.5)

def gradientbars_sliced(bars):
    ax = bars[0].axes
    xmin, xmax = ax.get_xlim()
    ymin, ymax = ax.get_ylim()
    for bar in bars:
        bar.set_zorder(1)
        bar.set_facecolor("none")
        x, y = bar.get_xy()
        w, h = bar.get_width(), bar.get_height()
        grad = np.linspace(y, y + h, 256).reshape(256, 1)
        ax.imshow(grad, extent=[x, x + w, y, y + h], aspect="auto", zorder=0, origin='lower',
                  vmin=ymin, vmax=ymax, cmap='magma')
    ax.axis([xmin, xmax, ymin, ymax])

gradientbars_sliced(bar)
plt.show()
</code>```

Body:
Suppose I have a vertical bar plot like this:

MWE per this suggestion:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

bar = ax.bar([1,2,3,4,5,6],[4,5,6,3,7,5], bottom=[1,7,4,6,3,2])

def gradientbars(bars):
    grad = np.atleast_2d(np.linspace(0,1,256)).T
    ax = bars[0].axes
    lim = ax.get_xlim()+ax.get_ylim()
    for bar in bars:
        bar.set_zorder(1)
        bar.set_facecolor("none")
        x,y = bar.get_xy()
        w, h = bar.get_width(), bar.get_height()
        ax.imshow(grad, extent=[x,x+w,y,y+h], aspect="auto", zorder=0)
    ax.axis(lim)

gradientbars(bar)
plt.show()

Is there an easy way to color the bars with a colormap according to the y-values they actually span (suppose my color bar goes from 1-12 where 1 is represented by yellow and 12 is represented by dark-blue)?

I have tried to adapt this example but wasn't successful.

Body:
Here is the code in this post adapted such that each bar shows a corresponding slice of the gradient.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = np.arange(35)
bar = ax.bar(x, 6 - np.sin(x / 10) * 3, bottom=5 - np.cos(x / 10) * 5)
plt.xlim(x[0] - 0.5, x[-1] + 0.5)

def gradientbars_sliced(bars):
    ax = bars[0].axes
    xmin, xmax = ax.get_xlim()
    ymin, ymax = ax.get_ylim()
    for bar in bars:
        bar.set_zorder(1)
        bar.set_facecolor("none")
        x, y = bar.get_xy()
        w, h = bar.get_width(), bar.get_height()
        grad = np.linspace(y, y + h, 256).reshape(256, 1)
        ax.imshow(grad, extent=[x, x + w, y, y + h], aspect="auto", zorder=0, origin='lower',
                  vmin=ymin, vmax=ymax, cmap='magma')
    ax.axis([xmin, xmax, ymin, ymax])

gradientbars_sliced(bar)
plt.show()