问:
Combine expressions and parameter expansion in bash
Is it possible to combine parameter expansion with arithmetic expressions in bash? For example, could I do a one-liner to evaluate lineNum or numChar here?

```<code>echo "Some lines here
Here is another
Oh look! Yet another" > $1

lineNum=$( grep -n -m1 'Oh look!' $1 | cut -d : -f 1 )  #Get line number of "Oh look!"
(( lineNum-- ))                                         # Correct for array indexing

readarray -t lines < $1

substr=${lines[lineNum]%%Y*}                            # Get the substring "Oh look! "
numChar=${#substr}                                      # Get the number of characters in the substring
(( numChar -= 2 ))                                      # Get the position of "!" based on the position of "Y"

echo $lineNum
echo $numChar

> 2
  8
</code>```

In other words, can I get the position of one character in a string based on the position of another in a one-line expression?

答:
As far as for getting position of ! in a line that matches Oh look! regex, just:

```<code>awk -F'!' '/Oh look!/{ print length($1) + 1; quit }' "$file"
</code>```

You can also do calculation to your liking, so with your original code I think that would be:

```<code>awk -F':' '/^[[:space:]][A-Z]/{ print length($1) - 2; quit }' "$file"
</code>```

Is it possible to combine parameter expansion with arithmetic expressions in bash?

For computing ${#substr} you have to have the substring.  So you could:

```<code>substr=${lines[lineNum-1]%%.*}; numChar=$((${#substr} - 2))
</code>```

You could also edit your grep and have the filtering from Y done by bash, but awk is going to be magnitudes faster:

```<code>IFS=Y read -r line _ < <(grep -m1 'Oh look!' "$file")
numChar=$((${#line} - 2))
</code>```

Still you could merge the 3 lines into just:

```<code>numChar=$(( $(<<<${lines[lineNum - 1]%%Y*} wc -c) - 1))
</code>```

Body:
Is it possible to combine parameter expansion with arithmetic expressions in bash? For example, could I do a one-liner to evaluate lineNum or numChar here?

echo "Some lines here
Here is another
Oh look! Yet another" > $1

lineNum=$( grep -n -m1 'Oh look!' $1 | cut -d : -f 1 )  #Get line number of "Oh look!"
(( lineNum-- ))                                         # Correct for array indexing

readarray -t lines < $1

substr=${lines[lineNum]%%Y*}                            # Get the substring "Oh look! "
numChar=${#substr}                                      # Get the number of characters in the substring
(( numChar -= 2 ))                                      # Get the position of "!" based on the position of "Y"

echo $lineNum
echo $numChar

> 2
  8

In other words, can I get the position of one character in a string based on the position of another in a one-line expression?

Body:
As far as for getting position of ! in a line that matches Oh look! regex, just:

awk -F'!' '/Oh look!/{ print length($1) + 1; quit }' "$file"

You can also do calculation to your liking, so with your original code I think that would be:

awk -F':' '/^[[:space:]][A-Z]/{ print length($1) - 2; quit }' "$file"

Is it possible to combine parameter expansion with arithmetic expressions in bash?

For computing ${#substr} you have to have the substring.  So you could:

substr=${lines[lineNum-1]%%.*}; numChar=$((${#substr} - 2))

You could also edit your grep and have the filtering from Y done by bash, but awk is going to be magnitudes faster:

IFS=Y read -r line _ < <(grep -m1 'Oh look!' "$file")
numChar=$((${#line} - 2))

Still you could merge the 3 lines into just:

numChar=$(( $(<<<${lines[lineNum - 1]%%Y*} wc -c) - 1))


来源: stackexchange

问:
Using files for for shared memory IPC
In my application, there is one process which writes data to a file, and then, in response to receiving a request, will send (some) of that data via the network to the requesting process.  The basis of this question is to see if we can speed up communication when both processes happen to be on the same host.  (In my case, the processes are Java, but I think this discussion can apply more broadly.)

There are a few projects out there which use the MappedByteBuffers returned by Java's FileChannel.map() as a way to have shared memory IPC between JVMs on the same host (see Chronicle Queue, Aeron IPC, etc.).

One approach to speeding up same-host communication would be to have my application use one of those technologies to provide the request-response pathway for same-host communication, either in conjunction with the existing mechanism for writing to the data file, or by providing a unified means of both communication and writing to the file.

Another approach would be to allow the requesting process to have direct access to the data file.

I tend to favor the second approach - assuming it would be correct - as it would be easier to implement, and seems more efficient than copying/transmitting a copy of the data for each request (assuming we didn't replace the existing mechanism for writing to the file).

Essentially, I'd like to understanding what exactly occurs when two processes have access to the same file, and use it to communicate, specifically Java (1.8) and Linux (3.10).

From my understanding, it seems like if two processes have the same file open at the same time, the "communication" between them will essentially be via "shared memory".

Note that this question is not concerned with the performance implication of using a MappedByteBuffer or not - it seem highly likely that a using mapped buffers, and the reduction in copying and system calls, will reduce overhead compared to reading and writing the file, but that might require significant changes to the application.

Here is my understanding:

When Linux loads a file from disk, it copies the contents of that file to pages in memory.  That region of memory is called the page cache.  As far as I can tell, it does this regardless of which Java method (FileInputStream.read(), RandomAccessFile.read(), FileChannel.read(), FileChannel.map()) or native method is used to read the file (obseved with "free" and monitoring the "cache" value).

If another process attempts to load the same file (while it is still resident in the cache) the kernel detects this and doesn't need to reload the file.  If the page cache gets full, pages will get evicted  - dirty ones being written back out to the disk.  (Pages also get written back out if there is an explicit flush to disk, and periodically, with a kernel thread).

Having a (large) file already in the cache is a significant performance boost, much more so than the differences based on which Java methods we use to open/read that file.

If a file is loaded using the mmap system call (C) or via FileChannel.map() (Java), essentially the file's pages (in the cache) are loaded directly into the process' address space.  Using other methods to open a file, the file is loaded into pages not in the process' address space, and then the various methods to read/write that file copy some bytes from/to those pages into a buffer in the process' address space.  There is an obvious performance benefit avoiding that copy, but my question isn't concerned with performance.

So in summary, if I understand correctly - while mapping offer a performance advantage, it doesn't seem like it offers any "shared memory" functionality that we don't already get just from the nature of the Linux and the page cache.

So, please let me know where my understanding is off.

Thanks.

答:
Worth mentioning three points: performance, and concurrent changes, and memory utilization.

You are correct in the assessment that MMAP-based will usually offer performance advantage over file based IO. In particular, the performance advantage is significant if the code perform lot of small IO at artbitrary point of the file.

consider changing the N-th byte: with mmap buffer[N] = buffer[N] + 1, and with file based access you need (at least) 4 system calls + error checking:

```<code>   seek() + error check
   read() + error check
   update value
   seek() + error check
   write + error check
</code>```

It is true the the number of actual IO (to the disk) most likely be the same.

The second point worth noting the concurrent access. With file based IO, you have to worry about potential concurrent access. You will need to issue explicit locking (before the read), and unlock (after the write), to prevent two processes for incorrectly accessing the value at the same time. With shared memory, atomic operations can eliminate the need for additional lock.

The third point is actual memory usage. For cases where the size of the shared objects is significant, using shared memory can allow large number of processes to access the data without allocating additional memory. If systems constrained by memory, or system that need to provide real-time performance, this could be the only way to access the data.

ContentLicense: CC BY-SA 4.0

Title: Using files for for shared memory IPC

Body:
Worth mentioning three points: performance, and concurrent changes, and memory utilization.

You are correct in the assessment that MMAP-based will usually offer performance advantage over file based IO. In particular, the performance advantage is significant if the code perform lot of small IO at artbitrary point of the file.

consider changing the N-th byte: with mmap buffer[N] = buffer[N] + 1, and with file based access you need (at least) 4 system calls + error checking:

   seek() + error check
   read() + error check
   update value
   seek() + error check
   write + error check

It is true the the number of actual IO (to the disk) most likely be the same.

The second point worth noting the concurrent access. With file based IO, you have to worry about potential concurrent access. You will need to issue explicit locking (before the read), and unlock (after the write), to prevent two processes for incorrectly accessing the value at the same time. With shared memory, atomic operations can eliminate the need for additional lock.

The third point is actual memory usage. For cases where the size of the shared objects is significant, using shared memory can allow large number of processes to access the data without allocating additional memory. If systems constrained by memory, or system that need to provide real-time performance, this could be the only way to access the data.


问:
How to return ActionResult along with async foreach and IAsyncEnumerable
I have a controller method of this signature:

```<code>public async IAsyncEnumerable<MyDto> Get()
</code>```

It works fine but I need to do some request validation and return 401, 400, and other codes accordingly, which it does not support.
Alternatively, the following signature does not compile:

```<code>public async Task<ActionResult<IAsyncEnumerable<MyDto>>> Get()
</code>```

Error:

Cannot implicitly convert type
  'Microsoft.AspNetCore.Mvc.UnauthorizedResult' to
  'MyApi.Responses.MyDto'

The full method:

```<code>public async IAsyncEnumerable<MyDto> Get()
{
    if (IsRequestInvalid())
    {
        // Can't do the following. Does not compile.
        yield return Unauthorized();
    }
    var retrievedDtos = _someService.GetAllDtosAsync(_userId);

    await foreach (var currentDto in retrievedDtos)
    {
        yield return currentDto;
    }
}
</code>```

Any ideas? Can't seem to believe that Microsoft has designed IAsyncEnumerable to be used without the possibility/flexibility of returning anything else.

答:
this should work

```<code>    public ActionResult<IAsyncEnumerable<MyDto>> Get()
    {
        if(IsRequestInvalid())
        {
            // now can do.
            return Unauthorized();
        }

        return new ActionResult<IAsyncEnumerable<MyDto>>(DoSomeProcessing());

        IAsyncEnumerable<MyDto> DoSomeProcessing()
        {
            IAsyncEnumerable<MyDto> retrievedDtos = _someService.GetAllDtosAsync(_userId);

            await foreach(var currentDto in retrievedDtos)
            {
                //work with currentDto here

                yield return currentDto;
            }
        }
    }
</code>```

if there is no processing of items before returning them better:

```<code>public ActionResult<IAsyncEnumerable<MyDto>> Get()
    {
        if(IsRequestInvalid())
        {
            // now can do
            return Unauthorized();
        }

        return new ActionResult<IAsyncEnumerable<MyDto>>(_someService.GetAllDtosAsync(_userId));
    }
</code>```

Body:
I have a controller method of this signature:

public async IAsyncEnumerable<MyDto> Get()

It works fine but I need to do some request validation and return 401, 400, and other codes accordingly, which it does not support.
Alternatively, the following signature does not compile:

public async Task<ActionResult<IAsyncEnumerable<MyDto>>> Get()

Error:

Cannot implicitly convert type
  'Microsoft.AspNetCore.Mvc.UnauthorizedResult' to
  'MyApi.Responses.MyDto'

The full method:

public async IAsyncEnumerable<MyDto> Get()
{
    if (IsRequestInvalid())
    {
        // Can't do the following. Does not compile.
        yield return Unauthorized();
    }
    var retrievedDtos = _someService.GetAllDtosAsync(_userId);

    await foreach (var currentDto in retrievedDtos)
    {
        yield return currentDto;
    }
}

Any ideas? Can't seem to believe that Microsoft has designed IAsyncEnumerable to be used without the possibility/flexibility of returning anything else.

Body:
this should work

    public ActionResult<IAsyncEnumerable<MyDto>> Get()
    {
        if(IsRequestInvalid())
        {
            // now can do.
            return Unauthorized();
        }

        return new ActionResult<IAsyncEnumerable<MyDto>>(DoSomeProcessing());

        IAsyncEnumerable<MyDto> DoSomeProcessing()
        {
            IAsyncEnumerable<MyDto> retrievedDtos = _someService.GetAllDtosAsync(_userId);

            await foreach(var currentDto in retrievedDtos)
            {
                //work with currentDto here

                yield return currentDto;
            }
        }
    }

if there is no processing of items before returning them better:

public ActionResult<IAsyncEnumerable<MyDto>> Get()
    {
        if(IsRequestInvalid())
        {
            // now can do
            return Unauthorized();
        }

        return new ActionResult<IAsyncEnumerable<MyDto>>(_someService.GetAllDtosAsync(_userId));
    }


问:
TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type function. Received undefined
At Object. (C:\Users\Hades\Downloads\Jaxxy\src\bot.js:51:8)

My code for the specified command is

client.on('guildMemberAdd'), member => {
  const channel = member.guild.channels.cache.find(channel=> channel.name === "welcome");
  if(!channel) return;
  channel.send(`Welcome to Hades's Tavern,$(member), make sure to read the rules in #rules!`)

};
```

I'm on discord.js v12!
Anyone has any clue?

答:
The closing parenthesis has to be after the arrow function's body:

client.on('guildMemberAdd', member => {
    const channel = member.guild.channels.cache.find(channel => channel.name === "welcome");
    if (!channel) return;
    channel.send(`Welcome to Hades's Tavern,$(member), make sure to read the rules in #rules!`)

});
```

Body:
At Object. (C:\Users\Hades\Downloads\Jaxxy\src\bot.js:51:8)

My code for the specified command is

client.on('guildMemberAdd'), member => {
  const channel = member.guild.channels.cache.find(channel=> channel.name === "welcome");
  if(!channel) return;
  channel.send(`Welcome to Hades's Tavern,$(member), make sure to read the rules in #rules!`)

};

I'm on discord.js v12!
Anyone has any clue?


问:
Maxpulse code doesn't want to work, really simple
I can't figure out why this simple code isn't working?</p>

```<code>maxpuls = 220

ålder = input("Hej! Vi vill mäta din maxpuls skriv in din ålder här:")

print("Detta är din maxpuls:" + (ålder - maxpuls))
</code>```

答:
Hej, this is because ålder/maxpuls are int type and you're concatenating them with a string. To fix that, cast (ålder - maxpuls) as a string.

```<code>maxpuls = 220

ålder = input("Hej! Vi vill mäta din maxpuls skriv in din ålder här:")

print("Detta är din maxpuls:" + str(int(ålder) - maxpuls))here
</code>```

Trevlig dag, kompis!

Body:
I can't figure out why this simple code isn't working?

maxpuls = 220

ålder = input("Hej! Vi vill mäta din maxpuls skriv in din ålder här:")

print("Detta är din maxpuls:" + (ålder - maxpuls))

Body:
Hej, this is because ålder/maxpuls are int type and you're concatenating them with a string. To fix that, cast (ålder - maxpuls) as a string.

maxpuls = 220

ålder = input("Hej! Vi vill mäta din maxpuls skriv in din ålder här:")

print("Detta är din maxpuls:" + str(int(ålder) - maxpuls))here

Trevlig dag, kompis!


问:
How do I call a modal from a custom quill editor button
I have a custom button (embed) in my quill editor that uses the prompt to call the windows popup

Now, I want to change the windows popup to a modal on the click of the embed button.

I honestly don't know how to go about this as this is my first time using a quill.

I'm using a quill extension file to create the custom button(embed)

I'm perplexed on were to create the modal and also how to call the modal when the quill custom button is clicked.

This is how I call the quill from my view

```<code><div class="form-group col-xs-12">
                                <label class="control-label">
                                    Description
                                </label>

                                <div id="createSchool_Description_div" style="height:300px;"></div>

</div>
 <script>
        $(document).ready(function () {

<text>
      prepareQuill('#createSchool_Description_div');
 </text>
</code>```

}

My quill extension file

```<code>       var quills = {};
function addQuillExtension(__quill) {
    if (__quill === undefined || __quill === null) {
        throw new this.DOMException("__quill editor not defined");
    }
    else {
        __quill.root.addEventListener("paste", function (e) {
            retrieveImageFromClipboardAsBase64(e, function (imageDataBase64) {
                // If there's an image, open it in the browser as a new window :)
                if (imageDataBase64) {
                    // data:image/png;base64,iVBORw0KGgoAAAAN......
                    let content = __quill.getContents();
                    __quill.clipboard.dangerouslyPasteHTML(content.length, "<img src=" + imageDataBase64 + ">");
                    //window.open(imageDataBase64);
                }
            });
        }, false);
        let embedbutton = __quill.container.previousSibling.querySelector('.ql-embed');
        embedbutton.setAttribute('title', 'Embed video/audio');
        embedbutton.onclick = function () {
            let url = prompt("Enter youtube URL");
            let spliturl = url.split('=');
            let suffix = spliturl[1];
            let embedurl = `https://www.youtube.com/embed/${suffix}?rel=0`;
            //debugger;
            let embedhtml = `<iframe class="youtubeembed" src="${embedurl}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
            let content = __quill.getContents();
            __quill.clipboard.dangerouslyPasteHTML(content.length, embedhtml);
        };
    }
    function retrieveImageFromClipboardAsBase64(pasteEvent, callback, imageFormat) {
        if (pasteEvent.clipboardData === false) {
            if (typeof callback === "function") {
                callback(undefined);
            }
        }

        var items = pasteEvent.clipboardData.items;

        if (items === undefined) {
            if (typeof callback === "function") {
                callback(undefined);
            }
        }

        for (var i = 0; i < items.length; i++) {
            // Skip content if not image
            if (items[i].type.indexOf("image") === -1) continue;
            // Retrieve image on clipboard as blob
            var blob = items[i].getAsFile();

            // Create an abstract canvas and get context
            var mycanvas = document.createElement("canvas");
            var ctx = mycanvas.getContext('2d');

            // Create an image
            var img = new Image();

            // Once the image loads, render the img on the canvas
            img.onload = function () {
                // Update dimensions of the canvas with the dimensions of the image
                mycanvas.width = this.width;
                mycanvas.height = this.height;

                // Draw the image
                ctx.drawImage(img, 0, 0);

                // Execute callback with the base64 URI of the image
                if (typeof callback === "function") {
                    callback(mycanvas.toDataURL(imageFormat || "image/png"));
                }
            };

            // Crossbrowser support for URL
            var URLObj = window.URL || window.webkitURL;

            // Creates a DOMString containing a URL representing the object given in the parameter
            // namely the original Blob
            img.src = URLObj.createObjectURL(blob);
        }
    }
}

function prepareQuill(selector, html) {
    let quill;
    var toolbarOptions = [
        ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
        ['blockquote', 'code-block'],

        //[{ 'header': 1 }, { 'header': 2 }],               // custom button values
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
        [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
        [{ 'direction': 'rtl' }],                         // text direction

        //[{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

        [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
        [{ 'font': [] }],
        [{ 'align': [] }],

        ['link', 'image', 'embed'],

        ['clean'],                                         // remove formatting button

        ['save']
    ];

    quill = new Quill(selector, {
        modules: {
            toolbar: toolbarOptions
        },
        theme: 'snow'
    });

    addQuillExtension();

    if (html) {
        quill.clipboard.dangerouslyPasteHTML(html);
    }

    quills[selector] = quill;

    return quill;
    //quill.enable();
}

function getEditorHtml(id) {
    let holder = document.getElementById(id).querySelector('.ql-editor');
    let clone = holder.cloneNode(true);
    return clone.innerHTML;
}

function getQuillEditorHtml(id) {
    let html = getEditorHtml(id);
    return html;
}

function setQuillEditorHtml(selector, html) {
    let quill = quills[selector];
    if (quill) {
        quill.clipboard.dangerouslyPasteHTML(html);
    }
    else {
        throw `quill editor for '${selector}' not found`;
    }
}
</code>```

答:
I do not think you need to write a custom button for this as quill already has a video embed button.

Just add 'video' in your toolbar options when creating the quill example below :

```<code>    ['bold', 'italic', 'underline', 'strike', '**video**']]
</code>```

Body:
I have a custom button (embed) in my quill editor that uses the prompt to call the windows popup

Now, I want to change the windows popup to a modal on the click of the embed button.

I honestly don't know how to go about this as this is my first time using a quill.

I'm using a quill extension file to create the custom button(embed)

I'm perplexed on were to create the modal and also how to call the modal when the quill custom button is clicked.

This is how I call the quill from my view

                                    Description

Body:
I do not think you need to write a custom button for this as quill already has a video embed button.

Just add 'video' in your toolbar options when creating the quill example below :

    ['bold', 'italic', 'underline', 'strike', '**video**']]


问:
Listing all subpages in Wordpress
trying to get my head around this one. I'm sure it's a simple solution. I am using the following script to get generate my navigation. Works fine and lists all the children of the parent, but as soon as I navigate to one of the children it obviously doesn't work.

```<code><?php
  $children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0');
  if ($children) {
?>
  <?php echo $children; ?>
<?php } ?>
</code>```

I have a separate template for the children, so I just need to modify the scope so instead of child_of... it's something like all_children_of...

Thanks in advance!

答:
That looks like a version of the List Sub-Pages example from the wp_list_pages Function Reference. The next example, "List subpages even if on a subpage", is what you need if I'm understanding you correctly.

```<code><?php
if($post->post_parent)
  $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
else
  $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
if ($children) { ?>
  <ul>
  <?php echo $children; ?>
  </ul>
<?php } ?>
</code>```

Phil

ContentLicense: CC BY-SA 3.0

Title: Listing all subpages in Wordpress

Body:
trying to get my head around this one. I'm sure it's a simple solution. I am using the following script to get generate my navigation. Works fine and lists all the children of the parent, but as soon as I navigate to one of the children it obviously doesn't work.

<?php
  $children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0');
  if ($children) {
?>
  <?php echo $children; ?>
<?php } ?>

I have a separate template for the children, so I just need to modify the scope so instead of child_of... it's something like all_children_of...

Thanks in advance!

Body:
That looks like a version of the List Sub-Pages example from the wp_list_pages Function Reference. The next example, "List subpages even if on a subpage", is what you need if I'm understanding you correctly.

<?php
if($post->post_parent)
  $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
else
  $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
if ($children) { ?>
  <ul>
  <?php echo $children; ?>
  </ul>
<?php } ?>

Phil


问:
How to control the space between the start of a bar and the axis in a bar-chart constructed using d3?
I am using d3.js library to construct a barchart with horizontal bars. When there are more than 50 bars in my chart then the spacing between the beginning of the axis and the first bar is strangely higher compared to when there are less than 50 total bars.
Spacing with less than 50 bars  (desired behavior) -

Spacing with more than 50 bars (undesirable) -

I am wondering what could be the issue since in both the cases similar code flow is used. Is it even possible or is there any known attribute/property which is responsible for controlling this particular spacing ?

答:
The trick was to replace

```<code>d3.scale.ordinal()
            .rangeRoundBands([0, size], 0.5);
</code>```

with

```<code>d3.scale.ordinal()
            .rangeBands([0, size], 0.5);
</code>```

because using rangeRoundBand rounding apparently introduces additional outer padding which is, on average, proportional to the length of the domain. This is the reason why in case of more than 50 bars I was able to see more space at the beginning and the end.

Body:
The trick was to replace

d3.scale.ordinal()
            .rangeRoundBands([0, size], 0.5);

with

d3.scale.ordinal()
            .rangeBands([0, size], 0.5);

because using rangeRoundBand rounding apparently introduces additional outer padding which is, on average, proportional to the length of the domain. This is the reason why in case of more than 50 bars I was able to see more space at the beginning and the end.


问:
Javascript - Counting array elements by reduce method until specific value occurs doesn't give a correct output
```<code>const arr = [5,6,0,7,8];
const sum = (arr,num) => arr.reduce((total)=>(num==0 ? total : total+num), 0)
console.log(sum(arr, 0))
</code>```

<p>Please check how can I make it work. Did some mistake but don't know what exactly. Output is a function instead of a result. </p>

答:
This is awkward to do in .reduce because it goes through the entire array. If we do a naive implementation you can see the problem:

const arr = [5,6,0,7,8];
const sum = (arr,num) => arr.reduce((total, x)=>(num==x ? total : total+x), 0)
console.log(sum(arr, 0))```
</div>
</div>
</p>

<p>We now make the check correctly - <code>num==x</code> will return <code>true</code> when <code>x</code> is zero (the value of <code>num</code>). However, the result is wrong because this only returns <code>true</code> <em>once</em> but any other iteration it's still <code>true</code>. And here is the same thing with more logging that describes each step of the process:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [5,6,0,7,8];
const sum = (arr,num) => arr.reduce((total, x)=> {
  const boolCheck = num==x;
  const result = boolCheck ? total : total+x;
  console.log(
`total: ${total}
num: ${num}
x: ${x}
boolCheck: ${boolCheck}
result: ${result}`);

    return result;
  }, 0)
console.log(sum(arr, 0))</code>```

So, you need to add some flag that persists between iterations, so it doesn't get lost.

One option is to have an external flag that you change within the reduce callback:

const arr = [5,6,0,7,8];
const sum = (arr,num) => {
  let finished = false;
  return arr.reduce((total, x) => {
    if(x === num)
      finished = true;

    return finished ? total : total+x;
  }, 0)
}
console.log(sum(arr, 0))```
</div>
</div>
</p>

<p>Alternatively, you can have that flag internal to the <code>reduce</code> callback and pass it around between calls. It works the same way in the end but makes the callback function pure. At the cost of some unorthodox construct:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [5,6,0,7,8];
const sum = (arr,num) => {
  return arr.reduce(({total, finished}, x) => {
    if(x === num)
      finished = true;

    total = finished ? total : total+x;

    return {total, finished};
  }, {total: 0, finished: false})
  .total
}
console.log(sum(arr, 0))</code>```

If you want to use reduce but you're OK with using other methods, then you can use Array#indexOf to find the first instance of a value and Array#slice the array that contains any value up to the target value:

const arr = [5,6,0,7,8];
const sum = (arr,num) => {
  const endIndex = arr.indexOf(num);

  return arr.slice(0, endIndex)
    .reduce((total, x)=> total+x, 0)
}
console.log(sum(arr, 0))```
</div>
</div>
</p>

<p>Or in as one chained expression:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [5,6,0,7,8];
const sum = (arr,num) => arr
  .slice(0, arr.indexOf(num))
  .reduce((total, x)=> total+x, 0);

console.log(sum(arr, 0))</code>```

Other libraries may have a takeUntil or takeWhile operation which is even closer to what you want - it gets you an array from the beginning up to a given value or condition. You can then reduce the result of that.

Here is an example of this using Lodash#takeWhile

By using chaining here, Lodash will do lazy evaluation, so it will only go through the array once, instead of scanning once to find the end index and going through the array again to sum it.

const arr = [5,6,0,7,8];
const sum = (arr,num) => _(arr)
  .takeWhile(x => x !== num)
  .reduce((total, x)=>total+x, 0)

console.log(sum(arr, 0))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script></code>```

As a note, if you are using Lodash, then you may as well use _.sum(). I didn't above just to illustrate how a generic takeUntil/takeWhile looks.

const arr = [5, 6, 0, 7, 8];
const sum = (arr, num) => _(arr)
  .takeWhile(x => x !== num)
  .sum()

console.log(sum(arr, 0))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script></code>```

Body:
const arr = [5,6,0,7,8];
const sum = (arr,num) => arr.reduce((total)=>(num==0 ? total : total+num), 0)
console.log(sum(arr, 0))

Please check how can I make it work. Did some mistake but don't know what exactly. Output is a function instead of a result.

Body:
This is awkward to do in .reduce because it goes through the entire array. If we do a naive implementation you can see the problem:

const arr = [5,6,0,7,8];
const sum = (arr,num) => arr.reduce((total, x)=>(num==x ? total : total+x), 0)
console.log(sum(arr, 0))

We now make the check correctly - num==x will return true when x is zero (the value of num). However, the result is wrong because this only returns true once but any other iteration it's still true. And here is the same thing with more logging that describes each step of the process:

const arr = [5,6,0,7,8];
const sum = (arr,num) => arr.reduce((total, x)=> {
  const boolCheck = num==x;
  const result = boolCheck ? total : total+x;
  console.log(
`total: ${total}
num: ${num}
x: ${x}
boolCheck: ${boolCheck}
result: ${result}`);

    return result;
  }, 0)
console.log(sum(arr, 0))

So, you need to add some flag that persists between iterations, so it doesn't get lost.

One option is to have an external flag that you change within the reduce callback:

const arr = [5,6,0,7,8];
const sum = (arr,num) => {
  let finished = false;
  return arr.reduce((total, x) => {
    if(x === num)
      finished = true;

    return finished ? total : total+x;
  }, 0)
}
console.log(sum(arr, 0))

Alternatively, you can have that flag internal to the reduce callback and pass it around between calls. It works the same way in the end but makes the callback function pure. At the cost of some unorthodox construct:

const arr = [5,6,0,7,8];
const sum = (arr,num) => {
  return arr.reduce(({total, finished}, x) => {
    if(x === num)
      finished = true;

    total = finished ? total : total+x;

    return {total, finished};
  }, {total: 0, finished: false})
  .total
}
console.log(sum(arr, 0))

If you want to use reduce but you're OK with using other methods, then you can use Array#indexOf to find the first instance of a value and Array#slice the array that contains any value up to the target value:

const arr = [5,6,0,7,8];
const sum = (arr,num) => {
  const endIndex = arr.indexOf(num);

  return arr.slice(0, endIndex)
    .reduce((total, x)=> total+x, 0)
}
console.log(sum(arr, 0))

Or in as one chained expression:

const arr = [5,6,0,7,8];
const sum = (arr,num) => arr
  .slice(0, arr.indexOf(num))
  .reduce((total, x)=> total+x, 0);

console.log(sum(arr, 0))

Other libraries may have a takeUntil or takeWhile operation which is even closer to what you want - it gets you an array from the beginning up to a given value or condition. You can then reduce the result of that.

Here is an example of this using Lodash#takeWhile

By using chaining here, Lodash will do lazy evaluation, so it will only go through the array once, instead of scanning once to find the end index and going through the array again to sum it.

const arr = [5,6,0,7,8];
const sum = (arr,num) => _(arr)
  .takeWhile(x => x !== num)
  .reduce((total, x)=>total+x, 0)

console.log(sum(arr, 0))

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>

As a note, if you are using Lodash, then you may as well use _.sum(). I didn't above just to illustrate how a generic takeUntil/takeWhile looks.

const arr = [5, 6, 0, 7, 8];
const sum = (arr, num) => _(arr)
  .takeWhile(x => x !== num)
  .sum()

console.log(sum(arr, 0))

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>


问:
Ruby/Rails - Is there an easy way to make hard-coded HTML symbols html_safe?
In my view I want to display some right double angle quotes in my link.

Before Rails 3, this worked:

<%= link_to "» #{@category.name}", some_path %>

Now what should I do if I want to specify the » as html_safe but not the rest of the link's text?

In other words I do not want to do this:

<%= link_to "» #{@category.name}".html_safe, some_path %>
I do not want the @category.name treated as html_safe.

This produces the desired result:

<%= link_to "»".html_safe + " #{@category.name}", some_path %>

However, if I do this:

<%= link_to "#{@category.name}" + "»".html_safe, some_path %>

The output of the angle quotes is not treated as safe.  I see » on my page and not ».

Why?

I tried extracting "»".html_safe to a helper method with the same results.

Is there a way to easily designate hard coded text/symbols as HMTL safe in Rails 3?

Thanks.

答:
you need to make sure that the whole string is html_safe...

I'd recommend to try this:

```<code>   "» #{h @cagegory.name}".html_safe
</code>```

Body:
you need to make sure that the whole string is html_safe...

I'd recommend to try this:

   "&raquo; #{h @cagegory.name}".html_safe


问:
Ajax not working for second time for duplicate value
While I am submitting this form via ajax it gets only the fist item. I am new so from the last three day I am looking on the web for a solution bit field. please someone help me.</p>

```<code><?php
        include  'db.php';

        $result = $mysqli -> query("SELECT * FROM AlmeenaShop LIMIT 8 ");
        if($result -> num_rows <1){
        /*echo"<h2 >No Record Found</h2>";*/
        }else{

        ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Insert data in MySQL database using Ajax</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    <body>
    <div style="margin: auto;width: 60%;">
        <div class="alert alert-success alert-dismissible" id="success" style="display:none;">
          <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
        </div>
        <?php foreach ($result as $row ) { ?>
        <form id="fupForm" name="form1" method="post">

            <div class="single-products">
                            <div class="productinfo text-center"><img width="200" height="250" alt="" src="<?php  echo  $row['ImageLocation'] ; ?> " />
                                <?php if ($row['OfferPrice']>0): ?>
                                <h2><?php  echo "৳ ".  $row['OfferPrice']  ." /-"; ?><del class="text-primary"><?php  echo "৳ ".  $row['SalesPrice']  ." /-"; ?></del></h2>
                                <?php else : ?>
                                <h2><?php  echo "৳ ".  $row['SalesPrice']  ." /-"; ?></h2>
                                <?php endif ?>

                                <p><?php  echo  $row['ProductName'] ; ?></p>
                                <p><input type="number" name="ProductQuantity" value="1" id="ProductQuantity<?php  echo  $row['StoreID'] ; ?>"  step="1"></p>
                                <p><input type="hidden" id="StoreID<?php  echo  $row['StoreID'] ; ?>" name="StoreID" value="<?php  echo  $row['StoreID'] ; ?>"></p>

                            </div>
                        </div>
            <input type="button" name="target" class="btn btn-primary" value="Save to database" id="<?php  echo  $row['StoreID'] ; ?>">
        </form>
    </div>

            <?php
            } /* FOr Whole Loop*/
            }/* for if then else loop*/

            ?>

    <script>
    $(document).ready(function() {

        $('.btn').on('click', function() {
            var target = $(".btn").attr("id");
            $("#"+target).attr("disabled", "disabled");

            var StoreID = $('#StoreID'+target).val();
            var ProductQuantity = $('#ProductQuantity'+target).val();

            if(StoreID!="" && ProductQuantity!=""){
                $.ajax({
                    url: "MyCart.php",
                    type: "POST",
                    data: {
                        StoreID: StoreID,
                        ProductQuantity: ProductQuantity

                    },
                    cache: false,
                    success: function(){
            alert("ok");

                    }
                });
            }
            else{
                alert('Please fill all the field !StoreID: StoreID , ProductQuantity: ProductQuantity');

            }
        });
    });
    </script>

    </body>
    </html>
</code>```

答:
```<code> <script>
$(document).ready(function() {
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
//alert(this.id);
    var targetid= this.id;

    var PImg = $('#PImg_'+targetid).val();
    var PName = $('#PName_'+targetid).val();
    var PRPrice = $('#PRPrice_'+targetid).val();
    var POPrice = $('#POPrice_'+targetid).val();
    var PQ = $('#PQ_'+targetid).val();
    var PSID = $('#PSID_'+targetid).val();

  //alert(this.id+"StoreID"+StoreID+"ProductQuantity"+ProductQuantity);

          if(PSID!="" && PQ!=""){
            $.ajax({
              url: "MyCart.php",
              type: "POST",
              data: {
                PImg: PImg,
                PName: PName,
                PRPrice: PRPrice,
                POPrice: POPrice,
                PQ: PQ,
                PSID: PSID

              },
              cache: false,
              success: function(){
          //alert("ok");
            window.location.reload();
              }
            });
          }
          else{
          //  alert('Please fill all the field !');
          }

    }

};
});
</script>
</code>```

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
session_start();

include 'db.php';
//Get the current page number
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
//The formula for php pagination
$no_of_records_per_page = 21;
$offset = ($pageno-1) * $no_of_records_per_page;
//Get the number of total number of pages
$result = $mysqli -> query("SELECT * FROM AlmeenaShop ");
$total_rows=$result -> num_rows;
$total_pages = ceil($total_rows / $no_of_records_per_page);
//Constructing the SQL Query for pagination
$ConstructingPagination= $mysqli -> query("SELECT * FROM AlmeenaShop ORDER BY StoreID DESC LIMIT $offset, $no_of_records_per_page");
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Almeena Shop</title>
    <!-- Bootstrap core CSS -->
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom styles for this template -->
    <link href="css/shop-homepage.css" rel="stylesheet">
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  </head>
  <body>
    <!-----------Nav Bat---------------->
    <div class="container">
      <!-- Navigation Start -->
      <nav class="navbar navbar-expand-lg navbar-dark bg-dark  text-white">

        <H1><span style="color:yellow">Almeena</span> <span style="color:white">Shop</span></H1>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarResponsive">
          <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
              Home
                <span class="sr-only">(current)</span>

            </li>
            <li class="nav-item">
              About
            </li>
            <li class="nav-item">
              Services
            </li>
            <li class="nav-item">
              Contact
            </li>
            <li class="nav-item">
              <i style="color:gold" class="fa fa-shopping-cart"></i> <?php echo $ItemCount=count($_SESSION['cart']); ?>
            </li>
          </ul>
        </div>

      </nav>
    </div>
    <!-- Navigation Start -->
    <div class="container bg-light p-5">
      <!-------####### Carosel Start    ###########-------------------->
      <div id="carouselExampleControls" class="carousel slide " data-ride="carousel">
        <div class="carousel-inner ">
          <div class="carousel-item active">
            <img src="StoreImg/grocery_3.jpg" height="300"class="d-block w-100" alt="...">
          </div>
          <div class="carousel-item">
            <img src="StoreImg/Shopping-basket.jpg" height="300" class="d-block w-100" alt="...">
          </div>
          <div class="carousel-item">
            <img src="StoreImg/3c.jpg" height="300" class="d-block w-100" alt="...">
          </div>
        </div>

          <span class="carousel-control-prev-icon" aria-hidden="true"></span>
          <span class="sr-only">Previous</span>

          <span class="carousel-control-next-icon" aria-hidden="true"></span>
          <span class="sr-only">Next</span>

      </div>
      <!-------#######   Carosel END ###########-------------------->
    </div>

    <!-- Page Content -->
    <div class="container">
      <div class="row">
        <!--------------------------LEft Cploum For Category Start ---------------------------------------->
        <div class="col-lg-3 mt-5">
          <?php
          $ProductCategoryResult = $mysqli -> query ("SELECT ProductCategory, count(ProductCategory)AS PCC FROM AlmeenaShop GROUP BY ProductCategory ORDER BY ProductCategory");

          ?>
          <div class="card border-primary mb-3" style="max-width: 18rem;">
            <div class="card-header"><h5>Our Products</h5></div>
            <div class="card-body text-primary">
              <?php foreach ($ProductCategoryResult as $PCrow){
              ?>
              <div class=" card-title" data-toggle="collapse" data-target="#<?php echo $PCrow['ProductCategory']; ?>" ><?php echo $PCrow['ProductCategory']; ?>
                <div class="list-group collapse" id="<?php echo $PCrow['ProductCategory']; ?>" >
                  <ul>
                    <?php
                    $ProductSubCategoryResult = $mysqli -> query("SELECT ProductSubCategory FROM AlmeenaShop WHERE  ProductCategory='".$PCrow['ProductCategory']."' GROUP BY ProductSubCategory ORDER BY ProductSubCategory ");
                    foreach ($ProductSubCategoryResult as $PSCrow){
                    ?>
                    <li>"><?php echo $PSCrow['ProductSubCategory'];?> </li>
                    <?php } ?>
                  </ul>
                </div>
              </div>
              <?php } ?>
              <div class=" card-title" data-toggle="collapse" data-target="#demo241">Offer
                <div class="list-group collapse" id="demo241" >
                  <ul>
                    <li>--------- </li>
                    <li>--------- </li>
                    <li>--------- </li>
                    <li>--------- </li>
                    <li>--------- </li>
                    <li>--------- </li>
                  </ul>
                </div></div>
              </div>
            </div>
          </div>
          <!-- /.col-lg-3 -->
          <!--------------------------LEft Cploum For Category End ---------------------------------------->

          <!-----#########################Rignt Cploum For Product Start ############################------>
          <div class="col-lg-9 mt-5">
            <ul class="pagination">

              <li class="page-item" >First</li>
              <li class="page-item <?php if($pageno <= 1){ echo 'disabled'; } ?>">
                ">Prev
              </li>
              <li class=" page-item <?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
                = $total_pages){ echo '#'; } else { echo "?pageno=".($pageno + 1); } ?>">Next
              </li>
              <li class="page-item">">Last</li>
            </ul>
            <p>Page <?php echo $total_pages; ?> of <?php echo $pageno; ?></p>

            <div class="row">
              <?php foreach ($ConstructingPagination as $row) { ?>
              <div class="col-lg-4 col-md-6 mb-4">
                <div class="card h-100" >
                  <img class="card-img-top p-2" src="http://almeenashop.com/<?php  echo  $row['ImageLocation'] ; ?>" alt="">
                  <div class="card-body">
                    <h4 class="card-title">
                      <p  style="color:black" ><?php  echo  $row['ProductName'] ; ?></p>

                      <p style="color:orange">Price :</p>
                      <?php if ($row['OfferPrice']>0): ?>
                      <?php  echo "৳ ".  $row['OfferPrice']  ." /-"; ?><br /><del class="text-primary"><?php  echo "৳ ".  $row['SalesPrice']  ." /-"; ?></del>
                      <?php else : ?>
                      <?php  echo "৳ ".  $row['SalesPrice']  ." /-"; ?>
                      <?php endif ?>

                    </h4>
                  </div>
                  <div class="card-footer">
                    <form id="CartForm" name="form1" method="post" enctype="multipart/form-data">
                      <input type="hidden"  name="PImg" id="PImg_<?php  echo  $row['StoreID'] ; ?>" value="<?php  echo  $row['ImageLocation'] ; ?>">
                      <input type="hidden"  name="PName" id="PName_<?php  echo  $row['StoreID'] ; ?>" value="<?php  echo  $row['ProductName'] ; ?>">
                      <input type="hidden"  name="PRPrice" id="PRPrice_<?php  echo  $row['StoreID'] ; ?>" value="<?php  echo  $row['SalesPrice'] ; ?>">
                      <input type="hidden"  name="POPrice" id="POPrice_<?php  echo  $row['StoreID'] ; ?>" value="<?php  echo  $row['OfferPrice'] ; ?>">
                      <input type="hidden"  name="PQ" id="PQ_<?php  echo  $row['StoreID'] ; ?>" value="1">
                      <input type="hidden"  name="PSID" id="PSID_<?php  echo  $row['StoreID'] ; ?>" value="<?php  echo  $row['StoreID'] ; ?>">
                    <button type="button" class="btn btn-primary" id="<?php  echo  $row['StoreID'] ; ?>">Add to Cart</button>
                    </form>
                    | Details
                  </div>
                </div>
              </div>
              <?php } ?>
            </div>
            <!-- /.row -->
          </div>
          <!-- /.col-lg-9 -->
          <!-----######################----Rignt Cploum For Product End -----##########################---------------->
        </div>
        <!-- /.row -->
      </div>
      <!-- /.container -->
      <!------- &&&&&&&& Footer Start &&&&&&&&&&&&&&------------>
      <footer id="footer">
        <div class="footer-widget  bg-dark text-white">
          <div class="container pt-4 pb-5">
            <div class="row">
              <div class="col-sm-2">
                <div class="single-widget">
                  <h5>Service</h5>
                  <ul>
                    <li>Online Help</li>
                    <li>Contact Us</li>
                    <li>Order Status</li>
                    <li>Change Location</li>
                    <li>FAQ’s</li>
                  </ul>
                </div>
              </div>
              <div class="col-sm-2">
                <div class="single-widget">
                  <h5>Quock Shop</h5>
                  <ul>
                    <li>T-Shirt</li>
                    <li>Mens</li>
                    <li>Womens</li>
                    <li>Gift Cards</li>
                    <li>Shoes</li>
                  </ul>
                </div>
              </div>
              <div class="col-sm-2">
                <div class="single-widget">
                  <h5>Policies</h5>
                  <ul>
                    <li>Terms of Use</li>
                    <li>Privecy Policy</li>
                    <li>Refund Policy</li>
                    <li>Billing System</li>
                    <li>Ticket System</li>
                  </ul>
                </div>
              </div>
              <div class="col-sm-2">
                <div class="single-widget">
                  <h5>About Shopper</h5>
                  <ul>
                    <li>Company Information</li>
                    <li>Careers</li>
                    <li>Store Location</li>
                    <li>Affillate Program</li>
                    <li>Copyright</li>
                  </ul>
                </div>
              </div>
              <div class="col-sm-3 col-sm-offset-1">
                <div class="single-widget">
                  <h5>News</h5>
                  <form action="#" class="searchform"><input placeholder="Your email address" type="text" /><button class="btn btn-default" type="submit"></button>
                  <p>Get the most recent updates from<br />
                  our site and be updated your self...</p>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="footer-bottom">
        <div class="container">
          <div class="row">
            <p class="pull-left">Copyright © 2020 Inc. All rights reserved.</p>
          </div>
        </div>
      </div>
    </footer>
    <!------- &&&&&&&& Footer End &&&&&&&&&&&&&&------------>
    <!-- Bootstrap core JavaScript -->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <script>
    $(document).ready(function() {
    var buttons = document.getElementsByTagName("button");
    var buttonsCount = buttons.length;
    for (var i = 0; i <= buttonsCount; i += 1) {
    buttons[i].onclick = function(e) {
    //alert(this.id);
        var targetid= this.id;

        var PImg = $('#PImg_'+targetid).val();
        var PName = $('#PName_'+targetid).val();
        var PRPrice = $('#PRPrice_'+targetid).val();
        var POPrice = $('#POPrice_'+targetid).val();
        var PQ = $('#PQ_'+targetid).val();
        var PSID = $('#PSID_'+targetid).val();

      //alert(this.id+"StoreID"+StoreID+"ProductQuantity"+ProductQuantity);

              if(PSID!="" && PQ!=""){
                $.ajax({
                  url: "MyCart.php",
                  type: "POST",
                  data: {
                    PImg: PImg,
                    PName: PName,
                    PRPrice: PRPrice,
                    POPrice: POPrice,
                    PQ: PQ,
                    PSID: PSID

                  },
                  cache: false,
                  success: function(){
              //alert("ok");
                window.location.reload();
                  }
                });
              }
              else{
              //  alert('Please fill all the field !');
              }

        }

    };
    });
    </script>

  </body>
</html></code>```

Body:
While I am submitting this form via ajax it gets only the fist item. I am new so from the last three day I am looking on the web for a solution bit field. please someone help me.

<?php
        include  'db.php';

        $result = $mysqli -> query("SELECT * FROM AlmeenaShop LIMIT 8 ");
        if($result -> num_rows <1){
        /*echo"
No Record Found
";*/
        }else{

        ?>
    <!DOCTYPE html>

        <title>Insert data in MySQL database using Ajax</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

          ×

        <?php foreach ($result as $row ) { ?>
        <form id="fupForm" name="form1" method="post">

<img width="200" height="250" alt="" src="<?php  echo  $row['ImageLocation'] ; ?> " />
                                <?php if ($row['OfferPrice']>0): ?>

<?php  echo "৳ ".  $row['OfferPrice']  ." /-"; ?><?php  echo "৳ ".  $row['SalesPrice']  ." /-"; ?>

                                <?php else : ?>

<?php  echo "৳ ".  $row['SalesPrice']  ." /-"; ?>

                                <?php endif ?>

<?php  echo  $row['ProductName'] ; ?>

<input type="number" name="ProductQuantity" value="1" id="ProductQuantity<?php  echo  $row['StoreID'] ; ?>"  step="1">

<input type="hidden" id="StoreID<?php  echo  $row['StoreID'] ; ?>" name="StoreID" value="<?php  echo  $row['StoreID'] ; ?>">

            <input type="button" name="target" class="btn btn-primary" value="Save to database" id="<?php  echo  $row['StoreID'] ; ?>">
        </form>

            <?php
            } /* FOr Whole Loop*/
            }/* for if then else loop*/

            ?>

Body:
 <script>
$(document).ready(function() {
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
//alert(this.id);
    var targetid= this.id;

    var PImg = $('#PImg_'+targetid).val();
    var PName = $('#PName_'+targetid).val();
    var PRPrice = $('#PRPrice_'+targetid).val();
    var POPrice = $('#POPrice_'+targetid).val();
    var PQ = $('#PQ_'+targetid).val();
    var PSID = $('#PSID_'+targetid).val();

  //alert(this.id+"StoreID"+StoreID+"ProductQuantity"+ProductQuantity);

          if(PSID!="" && PQ!=""){
            $.ajax({
              url: "MyCart.php",
              type: "POST",
              data: {
                PImg: PImg,
                PName: PName,
                PRPrice: PRPrice,
                POPrice: POPrice,
                PQ: PQ,
                PSID: PSID

              },
              cache: false,
              success: function(){
          //alert("ok");
            window.location.reload();
              }
            });
          }
          else{
          //  alert('Please fill all the field !');
          }

    }

};
});
</script>

    <script>
    $(document).ready(function() {
    var buttons = document.getElementsByTagName("button");
    var buttonsCount = buttons.length;
    for (var i = 0; i <= buttonsCount; i += 1) {
    buttons[i].onclick = function(e) {
    //alert(this.id);
        var targetid= this.id;

        var PImg = $('#PImg_'+targetid).val();
        var PName = $('#PName_'+targetid).val();
        var PRPrice = $('#PRPrice_'+targetid).val();
        var POPrice = $('#POPrice_'+targetid).val();
        var PQ = $('#PQ_'+targetid).val();
        var PSID = $('#PSID_'+targetid).val();

      //alert(this.id+"StoreID"+StoreID+"ProductQuantity"+ProductQuantity);

              if(PSID!="" && PQ!=""){
                $.ajax({
                  url: "MyCart.php",
                  type: "POST",
                  data: {
                    PImg: PImg,
                    PName: PName,
                    PRPrice: PRPrice,
                    POPrice: POPrice,
                    PQ: PQ,
                    PSID: PSID

                  },
                  cache: false,
                  success: function(){
              //alert("ok");
                window.location.reload();
                  }
                });
              }
              else{
              //  alert('Please fill all the field !');
              }

        }

    };
    });
    </script>

<?php
session_start();

include 'db.php';
//Get the current page number
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
//The formula for php pagination
$no_of_records_per_page = 21;
$offset = ($pageno-1) * $no_of_records_per_page;
//Get the number of total number of pages
$result = $mysqli -> query("SELECT * FROM AlmeenaShop ");
$total_rows=$result -> num_rows;
$total_pages = ceil($total_rows / $no_of_records_per_page);
//Constructing the SQL Query for pagination
$ConstructingPagination= $mysqli -> query("SELECT * FROM AlmeenaShop ORDER BY StoreID DESC LIMIT $offset, $no_of_records_per_page");
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Almeena Shop</title>
    <!-- Bootstrap core CSS -->
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom styles for this template -->
    <link href="css/shop-homepage.css" rel="stylesheet">
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  </head>
  <body>
    <!-----------Nav Bat---------------->
    <div class="container">
      <!-- Navigation Start -->
      <nav class="navbar navbar-expand-lg navbar-dark bg-dark  text-white">

        <H1><span style="color:yellow">Almeena</span> <span style="color:white">Shop</span></H1>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarResponsive">
          <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
              <a class="nav-link" href="index.php">Home
                <span class="sr-only">(current)</span>
              </a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">About</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Services</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Contact</a>
            </li>
            <li class="nav-item">
              <a style="color:gold" class="nav-link" href="MyCart.php"><i style="color:gold" class="fa fa-shopping-cart"></i> <?php echo $ItemCount=count($_SESSION['cart']); ?></a>
            </li>
          </ul>
        </div>

      </nav>
    </div>
    <!-- Navigation Start -->
    <div class="container bg-light p-5">
      <!-------####### Carosel Start    ###########-------------------->
      <div id="carouselExampleControls" class="carousel slide " data-ride="carousel">
        <div class="carousel-inner ">
          <div class="carousel-item active">
            <img src="StoreImg/grocery_3.jpg" height="300"class="d-block w-100" alt="...">
          </div>
          <div class="carousel-item">
            <img src="StoreImg/Shopping-basket.jpg" height="300" class="d-block w-100" alt="...">
          </div>
          <div class="carousel-item">
            <img src="StoreImg/3c.jpg" height="300" class="d-block w-100" alt="...">
          </div>
        </div>
        <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
          <span class="carousel-control-prev-icon" aria-hidden="true"></span>
          <span class="sr-only">Previous</span>
        </a>
        <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
          <span class="carousel-control-next-icon" aria-hidden="true"></span>
          <span class="sr-only">Next</span>
        </a>
      </div>
      <!-------#######   Carosel END ###########-------------------->
    </div>

    <!-- Page Content -->
    <div class="container">
      <div class="row">
        <!--------------------------LEft Cploum For Category Start ---------------------------------------->
        <div class="col-lg-3 mt-5">
          <?php
          $ProductCategoryResult = $mysqli -> query ("SELECT ProductCategory, count(ProductCategory)AS PCC FROM AlmeenaShop GROUP BY ProductCategory ORDER BY ProductCategory");

          ?>
          <div class="card border-primary mb-3" style="max-width: 18rem;">
            <div class="card-header"><h5>Our Products</h5></div>
            <div class="card-body text-primary">
              <?php foreach ($ProductCategoryResult as $PCrow){
              ?>
              <div class=" card-title" data-toggle="collapse" data-target="#<?php echo $PCrow['ProductCategory']; ?>" ><?php echo $PCrow['ProductCategory']; ?>
                <div class="list-group collapse" id="<?php echo $PCrow['ProductCategory']; ?>" >
                  <ul>
                    <?php
                    $ProductSubCategoryResult = $mysqli -> query("SELECT ProductSubCategory FROM AlmeenaShop WHERE  ProductCategory='".$PCrow['ProductCategory']."' GROUP BY ProductSubCategory ORDER BY ProductSubCategory ");
                    foreach ($ProductSubCategoryResult as $PSCrow){
                    ?>
                    <li><a href="View.php?ProductSubCategory=<?php echo $PSCrow['ProductSubCategory'];?>"><?php echo $PSCrow['ProductSubCategory'];?> </a></li>
                    <?php } ?>
                  </ul>
                </div>
              </div>
              <?php } ?>
              <div class=" card-title" data-toggle="collapse" data-target="#demo241">Offer
                <div class="list-group collapse" id="demo241" >
                  <ul>
                    <li><a href="#">--------- </a></li>
                    <li><a href="#">--------- </a></li>
                    <li><a href="#">--------- </a></li>
                    <li><a href="#">--------- </a></li>
                    <li><a href="#">--------- </a></li>
                    <li><a href="#">--------- </a></li>
                  </ul>
                </div></div>
              </div>
            </div>
          </div>
          <!-- /.col-lg-3 -->
          <!--------------------------LEft Cploum For Category End ---------------------------------------->

          <!-----#########################Rignt Cploum For Product Start ############################------>
          <div class="col-lg-9 mt-5">
            <ul class="pagination">

              <li class="page-item" ><a class="page-link" href="?pageno=1">First</a></li>
              <li class="page-item <?php if($pageno <= 1){ echo 'disabled'; } ?>">
                <a class="page-link"  href="<?php if($pageno <= 1){ echo '#'; } else { echo "?pageno=".($pageno - 1); } ?>">Prev</a>
              </li>
              <li class=" page-item <?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
                <a class="page-link" href="<?php if($pageno >= $total_pages){ echo '#'; } else { echo "?pageno=".($pageno + 1); } ?>">Next</a>
              </li>
              <li class="page-item"><a class="page-link" href="?pageno=<?php echo $total_pages; ?>">Last</a></li>
            </ul>
            <p>Page <?php echo $total_pages; ?> of <?php echo $pageno; ?></p>

            <div class="row">
              <?php foreach ($ConstructingPagination as $row) { ?>
              <div class="col-lg-4 col-md-6 mb-4">
                <div class="card h-100" >
                  <a href="#"><img class="card-img-top p-2" src="http://almeenashop.com/<?php  echo  $row['ImageLocation'] ; ?>" alt=""></a>
                  <div class="card-body">
                    <h4 class="card-title">
                      <p  style="color:black" ><?php  echo  $row['ProductName'] ; ?></p>
                    <a class="text-success" href="#">
                      <p style="color:orange">Price :</p>
                      <?php if ($row['OfferPrice']>0): ?>
                      <?php  echo "&#2547; ".  $row['OfferPrice']  ." /-"; ?><br /><del class="text-primary"><?php  echo "&#2547; ".  $row['SalesPrice']  ." /-"; ?></del>
                      <?php else : ?>
                      <?php  echo "&#2547; ".  $row['SalesPrice']  ." /-"; ?>
                      <?php endif ?>
                    </a>
                    </h4>
                  </div>
                  <div class="card-footer">
                    <form id="CartForm" name="form1" method="post" enctype="multipart/form-data">
                      <input type="hidden"  name="PImg" id="PImg_<?php  echo  $row['StoreID'] ; ?>" value="<?php  echo  $row['ImageLocation'] ; ?>">
                      <input type="hidden"  name="PName" id="PName_<?php  echo  $row['StoreID'] ; ?>" value="<?php  echo  $row['ProductName'] ; ?>">
                      <input type="hidden"  name="PRPrice" id="PRPrice_<?php  echo  $row['StoreID'] ; ?>" value="<?php  echo  $row['SalesPrice'] ; ?>">
                      <input type="hidden"  name="POPrice" id="POPrice_<?php  echo  $row['StoreID'] ; ?>" value="<?php  echo  $row['OfferPrice'] ; ?>">
                      <input type="hidden"  name="PQ" id="PQ_<?php  echo  $row['StoreID'] ; ?>" value="1">
                      <input type="hidden"  name="PSID" id="PSID_<?php  echo  $row['StoreID'] ; ?>" value="<?php  echo  $row['StoreID'] ; ?>">
                    <button type="button" class="btn btn-primary" id="<?php  echo  $row['StoreID'] ; ?>">Add to Cart</button>
                    </form>
                    | <a href="Add-to-cart.php?id=3">Details</a>
                  </div>
                </div>
              </div>
              <?php } ?>
            </div>
            <!-- /.row -->
          </div>
          <!-- /.col-lg-9 -->
          <!-----######################----Rignt Cploum For Product End -----##########################---------------->
        </div>
        <!-- /.row -->
      </div>
      <!-- /.container -->
      <!------- &&&&&&&& Footer Start &&&&&&&&&&&&&&------------>
      <footer id="footer">
        <div class="footer-widget  bg-dark text-white">
          <div class="container pt-4 pb-5">
            <div class="row">
              <div class="col-sm-2">
                <div class="single-widget">
                  <h5>Service</h5>
                  <ul>
                    <li><a href="#">Online Help</a></li>
                    <li><a href="#">Contact Us</a></li>
                    <li><a href="#">Order Status</a></li>
                    <li><a href="#">Change Location</a></li>
                    <li><a href="#">FAQ&rsquo;s</a></li>
                  </ul>
                </div>
              </div>
              <div class="col-sm-2">
                <div class="single-widget">
                  <h5>Quock Shop</h5>
                  <ul>
                    <li><a href="#">T-Shirt</a></li>
                    <li><a href="#">Mens</a></li>
                    <li><a href="#">Womens</a></li>
                    <li><a href="#">Gift Cards</a></li>
                    <li><a href="#">Shoes</a></li>
                  </ul>
                </div>
              </div>
              <div class="col-sm-2">
                <div class="single-widget">
                  <h5>Policies</h5>
                  <ul>
                    <li><a href="#">Terms of Use</a></li>
                    <li><a href="#">Privecy Policy</a></li>
                    <li><a href="#">Refund Policy</a></li>
                    <li><a href="#">Billing System</a></li>
                    <li><a href="#">Ticket System</a></li>
                  </ul>
                </div>
              </div>
              <div class="col-sm-2">
                <div class="single-widget">
                  <h5>About Shopper</h5>
                  <ul>
                    <li><a href="#">Company Information</a></li>
                    <li><a href="#">Careers</a></li>
                    <li><a href="#">Store Location</a></li>
                    <li><a href="#">Affillate Program</a></li>
                    <li><a href="#">Copyright</a></li>
                  </ul>
                </div>
              </div>
              <div class="col-sm-3 col-sm-offset-1">
                <div class="single-widget">
                  <h5>News</h5>
                  <form action="#" class="searchform"><input placeholder="Your email address" type="text" /><button class="btn btn-default" type="submit"></button>
                  <p>Get the most recent updates from<br />
                  our site and be updated your self...</p>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="footer-bottom">
        <div class="container">
          <div class="row">
            <p class="pull-left">Copyright &copy; 2020 Inc. All rights reserved.</p>
          </div>
        </div>
      </div>
    </footer>
    <!------- &&&&&&&& Footer End &&&&&&&&&&&&&&------------>
    <!-- Bootstrap core JavaScript -->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <script>
    $(document).ready(function() {
    var buttons = document.getElementsByTagName("button");
    var buttonsCount = buttons.length;
    for (var i = 0; i <= buttonsCount; i += 1) {
    buttons[i].onclick = function(e) {
    //alert(this.id);
        var targetid= this.id;

        var PImg = $('#PImg_'+targetid).val();
        var PName = $('#PName_'+targetid).val();
        var PRPrice = $('#PRPrice_'+targetid).val();
        var POPrice = $('#POPrice_'+targetid).val();
        var PQ = $('#PQ_'+targetid).val();
        var PSID = $('#PSID_'+targetid).val();

      //alert(this.id+"StoreID"+StoreID+"ProductQuantity"+ProductQuantity);

              if(PSID!="" && PQ!=""){
                $.ajax({
                  url: "MyCart.php",
                  type: "POST",
                  data: {
                    PImg: PImg,
                    PName: PName,
                    PRPrice: PRPrice,
                    POPrice: POPrice,
                    PQ: PQ,
                    PSID: PSID

                  },
                  cache: false,
                  success: function(){
              //alert("ok");
                window.location.reload();
                  }
                });
              }
              else{
              //  alert('Please fill all the field !');
              }

        }

    };
    });
    </script>

  </body>
</html>


问:
How to listen for more than one event expression within a Shiny eventReactive handler
I want two different events to trigger an update of the data being used by various plots / outputs in my app. One is a button being clicked (input$spec_button) and the other is a point on a dot being clicked (mainplot.click$click).

Basically, I want to listed for both at the same time, but I'm not sure how to write the code. Here's what I have now:

in server.R:

```<code>data <- eventReactive({mainplot.click$click | input$spec_button}, {
    if(input$spec_button){
      # get data relevant to the button
    } else {
      # get data relevant to the point clicked
    }
  })
</code>```

But the if-else clause doesn't work

Error in mainplot.click$click | input$spec_button :
  operations are possible only for numeric, logical or complex types

--> Is there some sort of action-combiner function I can use for the mainplot.click$click | input$spec_button clause?

答:
The idea here is to create a reactive function which will execute the condition you want to pass in observeEvent and then you can pass this reactive function to check the validity of the statement. For instance:

```<code>validate_event <- reactive({
    # I have used OR condition here, you can use AND also
    req(input$spec_button) || req(mainplot.click$click)
})

observeEvent(validate_event(),
    { ... }
)
</code>```

Keep Coding!

Body:
I want two different events to trigger an update of the data being used by various plots / outputs in my app. One is a button being clicked (input$spec_button) and the other is a point on a dot being clicked (mainplot.click$click).

Basically, I want to listed for both at the same time, but I'm not sure how to write the code. Here's what I have now:

in server.R:

data <- eventReactive({mainplot.click$click | input$spec_button}, {
    if(input$spec_button){
      # get data relevant to the button
    } else {
      # get data relevant to the point clicked
    }
  })

But the if-else clause doesn't work

Error in mainplot.click$click | input$spec_button :
  operations are possible only for numeric, logical or complex types

--> Is there some sort of action-combiner function I can use for the mainplot.click$click | input$spec_button clause?

Body:
The idea here is to create a reactive function which will execute the condition you want to pass in observeEvent and then you can pass this reactive function to check the validity of the statement. For instance:

validate_event <- reactive({
    # I have used OR condition here, you can use AND also
    req(input$spec_button) || req(mainplot.click$click)
})

observeEvent(validate_event(),
    { ... }
)

Keep Coding!


问:
Using Try/Catch with Promise.all
I have recently been reading about async/await and using try and catch to handle promise rejections, and have been applying it to some of my old code.

I have the following:

```<code>async function() {
    try {
        await Promise.all([some functions]);
        doIfNoError();
    } catch (error) {
        console.log(error);
    }
</code>```

The functions I am passing to Promise.all follow the form:

```<code>async function() {
    some code
    if (some condition) {
        return true
    } else {
        throw false
    }
 }
</code>```

I intend that if any of the functions passed into Promise.all reject, the rejection is displayed. If none of the functions reject, then doIfNoError should fire. However, doIfNoError sometimes fires when it shouldn't, and I am given the error "Unhandled Promise Rejection".

答:
Actually, try/catch does work well with Promise.all().

Here is a snippet to prove it:

async function p1() {
  return 1;
}

async function boom() {
  return new Promise((resolve, reject) => {
setTimeout(() => reject('boom'), 100)
  })
}

// expected output: 'boom', ["value before Promise.all"]
async function asyncCall() {
  let all = ['value before Promise.all'];

  try {
all = await Promise.all([p1(), boom()]);
  } catch(e) {
console.log("caught error:", e);
  }

  console.log(all);
}

asyncCall();```

Title: Using Try/Catch with Promise.all

Body:
I have recently been reading about async/await and using try and catch to handle promise rejections, and have been applying it to some of my old code.

I have the following:

async function() {
    try {
        await Promise.all([some functions]);
        doIfNoError();
    } catch (error) {
        console.log(error);
    }

The functions I am passing to Promise.all follow the form:

async function() {
    some code
    if (some condition) {
        return true
    } else {
        throw false
    }
 }

I intend that if any of the functions passed into Promise.all reject, the rejection is displayed. If none of the functions reject, then doIfNoError should fire. However, doIfNoError sometimes fires when it shouldn't, and I am given the error "Unhandled Promise Rejection".


问:
How to remove black border from option when hover in chrome 83
I update my chrome browser to 83 and saw the option tag and it looks ugly, It shows the black border when hovering in option.

I tried

```<code>option {
    box-shadow: none;
    border: none;
    -webkit-appearance: none;
}

option:hover {
    box-shadow: none;
    border: none;
    -webkit-appearance: none;
}
</code>```

option {
  box-shadow: none;
  border: none;
  -webkit-appearance: none;
}

option:hover {
  box-shadow: none;
  border: none;
  -webkit-appearance: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
</select></code>```

but still no luck!! why? I don't know.

I want to remove that black border because In my project it looks ugly.

MY NEED

I need same result as previous select and option tag have.

答: Changing the colour of the border seems to remove the black hover state</p>

Body:
I update my chrome browser to 83 and saw the option tag and it looks ugly, It shows the black border when hovering in option.

I tried

option {
    box-shadow: none;
    border: none;
    -webkit-appearance: none;
}

option:hover {
    box-shadow: none;
    border: none;
    -webkit-appearance: none;
}

option {
  box-shadow: none;
  border: none;
  -webkit-appearance: none;
}

option:hover {
  box-shadow: none;
  border: none;
  -webkit-appearance: none;
}

<select>
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
  <option value="4">Option 4</option>
</select>

but still no luck!! why? I don't know.

I want to remove that black border because In my project it looks ugly.

MY NEED

I need same result as previous select and option tag have.


问:
Async / Await Task returns no value
What the code does is loops a datagrid of URLs checks in the html for a certain string and returns data accordingly, very basic so far.

I'm trying to understand the await / async methods better, i have a fairly ok grasp so far but i have hit a snag, the code i have so far:

FormMain.cs

```<code>        public async Task RunAsyncAnalyzer()
        {
            try
            {
                BtnPerformLinkAnalysis.Enabled = false;
                if (DataGridViewLinks.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in DataGridViewLinks.Rows)
                    {
                        row.Cells[2].Value = await Task.Run(() => { Helpers.GetLinkPlatformType(row.Cells[0].Value.ToString()); });
                    }
                }
                BtnPerformLinkAnalysis.Enabled = true;
            }
            catch (Exception ex)
            {
                Helpers.DebugLogging("[" + DateTime.Now + "]-[" + ex.ToString() + "]");
            }

        }

        private async void BtnPerformLinkAnalysis_Click(object sender, EventArgs e)
        {
            await RunAsyncAnalyzer();
        }
</code>```

Helpers.cs

```<code>        public static string GetLinkPlatformType(string url) {
            string platform_type = "......";
            try {
                var html = GetWebPageHTML(url);

                if (html.Contains("Start the discussion…")) {
                    platform_type = "DISCUZ|CAN_COMMENT";
                }
            }
            catch (Exception ex)
            {
                Helpers.DebugLogging("[" + DateTime.Now + "]-[" + ex.ToString() + "]");
            }
            return platform_type;
        }
</code>```

The error i am getting is: cannot convert type 'void' to 'object' and it is on this line: row.Cells[2].Value = await Task.Run(() => { Helpers.GetLinkPlatformType(row.Cells[0].Value.ToString()); });

It also says above it: Awaited Task returns no value but the method GetLinkPlatformType does return a value it is not a void i cannot see what the issue is i know i am over looking something but i'm not entirely sure what, any help in the right direction would be appreciated.

答:
The issue is that your task is not returning anything, you missed the return.

```<code>row.Cells[2].Value = await Task.Run(() => { return Helpers.GetLinkPlatformType(row.Cells[0].Value.ToString()); });
</code>```

Otherwise it's just a task that does something but does not return anything.

Also, as @leszek mentioned in the comments, here's another approach:

```<code>row.Cells[2].Value = await Task.Run(() => Helpers.GetLinkPlatformType(row.Cells[0].Value.ToString()) );
</code>```

Hope it helps!

Title: Async / Await Task returns no value

Body:
What the code does is loops a datagrid of URLs checks in the html for a certain string and returns data accordingly, very basic so far.

I'm trying to understand the await / async methods better, i have a fairly ok grasp so far but i have hit a snag, the code i have so far:

FormMain.cs

        public async Task RunAsyncAnalyzer()
        {
            try
            {
                BtnPerformLinkAnalysis.Enabled = false;
                if (DataGridViewLinks.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in DataGridViewLinks.Rows)
                    {
                        row.Cells[2].Value = await Task.Run(() => { Helpers.GetLinkPlatformType(row.Cells[0].Value.ToString()); });
                    }
                }
                BtnPerformLinkAnalysis.Enabled = true;
            }
            catch (Exception ex)
            {
                Helpers.DebugLogging("[" + DateTime.Now + "]-[" + ex.ToString() + "]");
            }

        }

        private async void BtnPerformLinkAnalysis_Click(object sender, EventArgs e)
        {
            await RunAsyncAnalyzer();
        }

Helpers.cs

        public static string GetLinkPlatformType(string url) {
            string platform_type = "......";
            try {
                var html = GetWebPageHTML(url);

                if (html.Contains("Start the discussion…")) {
                    platform_type = "DISCUZ|CAN_COMMENT";
                }
            }
            catch (Exception ex)
            {
                Helpers.DebugLogging("[" + DateTime.Now + "]-[" + ex.ToString() + "]");
            }
            return platform_type;
        }

The error i am getting is: cannot convert type 'void' to 'object' and it is on this line: row.Cells[2].Value = await Task.Run(() => { Helpers.GetLinkPlatformType(row.Cells[0].Value.ToString()); });

It also says above it: Awaited Task returns no value but the method GetLinkPlatformType does return a value it is not a void i cannot see what the issue is i know i am over looking something but i'm not entirely sure what, any help in the right direction would be appreciated.

Body:
The issue is that your task is not returning anything, you missed the return.

row.Cells[2].Value = await Task.Run(() => { return Helpers.GetLinkPlatformType(row.Cells[0].Value.ToString()); });

Otherwise it's just a task that does something but does not return anything.

Also, as @leszek mentioned in the comments, here's another approach:

row.Cells[2].Value = await Task.Run(() => Helpers.GetLinkPlatformType(row.Cells[0].Value.ToString()) );

Hope it helps!


问:
Why is the CakePHP authentication component not hashing my password?
I'm using CakePHP 1.2 with Auth and ACL components.

In my user register action, the password is coming in unhashed.  Specifically, this expression:

```<code>if ($this->data['User']['password'] !=
    $this->Auth->password($this->data['User']['confirm_password']))
</code>```

This is evaluating to true, even when I submit identical values for password and confirm_password.  I know that password is unhashed because when I remove the call to Auth->password, the expression evaluates to false.

I expected the Auth module to automagically hash the password.  What am I doing wrong?

Here is my view:

```<code><?php
    echo $form->create('User', array('action' => 'register'));

    echo $form->input('email',
                      array('after' => $form->error(
                        'email_unique', 'This email is already registered.')));
    echo $form->input('password');
    echo $form->input('confirm_password', array('type' => 'password'));
    echo $form->end('Register');
?>
</code>```

Here is my register action from the user controller:

```<code>function register(){
    if ($this->data) {
        if ($this->data['User']['password'] !=
            $this->Auth->password($this->data['User']['confirm_password'])) {

            $this->Session->setFlash(__('Password and Confirm Password must match.', true));
            $this->data['User']['password'] = '';
            $this->data['User']['confirm_password'] = '';
        }
        else{
            $this->User->create();
            if ($this->User->save($this->data)){
                $this->redirect(array('action' => 'index'), null, true);
            }
            else {
                $this->data['User']['password'] = '';
                $this->data['User']['confirm_password'] = '';
                $this->Session->setFlash(__('Some problem saving your information.', true));
            }
        }
    }
}
</code>```

And here is my appController where I include the Auth and Acl modules:

```<code>class AppController extends Controller {
    var $components = array('Acl', 'Auth');

    function beforeFilter(){
        if (isset($this->Auth)) {
            $this->Auth->allow('display');
            $this->Auth->fields =
              array(
                'username' => 'email',
                'password' => 'password');
            $this->Auth->authorize = 'actions';
        }
    }
}
</code>```

What am I doing wrong?

答:
CakePHP won't hash passwords unless username contains a submitted value.  I'm replacing the username field with email.  However, I remapped those fields by setting the Auth->fields array.  However, I was doing that in the appController instead of userController.  So moving this line:

```<code>$this->Auth->fields = array('username' => 'email', 'password' => 'password');
</code>```

out of appController into userController solved it.

Now the question becomes "Why can't I reset the Auth->fields in appController?"

OwnerDisplayName: Eric

ContentLicense: CC BY-SA 2.5

Body:
I'm using CakePHP 1.2 with Auth and ACL components.

In my user register action, the password is coming in unhashed.  Specifically, this expression:

if ($this->data['User']['password'] !=
    $this->Auth->password($this->data['User']['confirm_password']))

This is evaluating to true, even when I submit identical values for password and confirm_password.  I know that password is unhashed because when I remove the call to Auth->password, the expression evaluates to false.

I expected the Auth module to automagically hash the password.  What am I doing wrong?

Here is my view:

<?php
    echo $form->create('User', array('action' => 'register'));

    echo $form->input('email',
                      array('after' => $form->error(
                        'email_unique', 'This email is already registered.')));
    echo $form->input('password');
    echo $form->input('confirm_password', array('type' => 'password'));
    echo $form->end('Register');
?>

Here is my register action from the user controller:

function register(){
    if ($this->data) {
        if ($this->data['User']['password'] !=
            $this->Auth->password($this->data['User']['confirm_password'])) {

            $this->Session->setFlash(__('Password and Confirm Password must match.', true));
            $this->data['User']['password'] = '';
            $this->data['User']['confirm_password'] = '';
        }
        else{
            $this->User->create();
            if ($this->User->save($this->data)){
                $this->redirect(array('action' => 'index'), null, true);
            }
            else {
                $this->data['User']['password'] = '';
                $this->data['User']['confirm_password'] = '';
                $this->Session->setFlash(__('Some problem saving your information.', true));
            }
        }
    }
}

And here is my appController where I include the Auth and Acl modules:

class AppController extends Controller {
    var $components = array('Acl', 'Auth');

    function beforeFilter(){
        if (isset($this->Auth)) {
            $this->Auth->allow('display');
            $this->Auth->fields =
              array(
                'username' => 'email',
                'password' => 'password');
            $this->Auth->authorize = 'actions';
        }
    }
}

What am I doing wrong?

LastEditorDisplayName: Rich B

Body:
CakePHP won't hash passwords unless username contains a submitted value.  I'm replacing the username field with email.  However, I remapped those fields by setting the Auth->fields array.  However, I was doing that in the appController instead of userController.  So moving this line:

$this->Auth->fields = array('username' => 'email', 'password' => 'password');

out of appController into userController solved it.

Now the question becomes "Why can't I reset the Auth->fields in appController?"